file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/105598.c
#include <stdio.h> int main(int argc, char const *argv[]) { char ch; printf("Enter a character:"); scanf("%c",&ch); printf("ASCII code:%d",ch ); return 0; }
the_stack_data/150139807.c
static const char messg[] = "def"; static inline int add(int a, int b) { return a + b; } int foo(int a, int b, int p) { if (p) { add(a + b, 1); return p; } return 0; } /* * check-name: call-inlined * check-command: test-linearize -Wno-decl $file * * check-output-ignore * check-output-returns: %arg3 */
the_stack_data/231392788.c
#define __CRT__NO_INLINE /* Don't let mingw insert code */ #include <math.h> #define fabs_def(type, name, isinf_func, isnan_func, abs_func) \ type name(type f) \ { \ __ESBMC_HIDE:; \ return abs_func(f); \ } \ \ type __##name(type f) \ { \ __ESBMC_HIDE:; \ return name(f); \ } fabs_def(float, fabsf, isinff, isnanf, __ESBMC_fabsf); fabs_def(double, fabs, isinf, isnan, __ESBMC_fabsd); fabs_def(long double, fabsl, isinfl, isnanl, __ESBMC_fabsld); #undef fabs_def
the_stack_data/104610.c
/* { dg-do run } */ /* { dg-options "-fno-common" { target hppa*-*-hpux* } } */ struct a { int a[100]; }; typedef struct a misaligned_t __attribute__ ((aligned (8))); typedef struct a aligned_t __attribute__ ((aligned (32))); __attribute__ ((used)) __attribute__ ((noinline)) void t(void *a, int misaligned, aligned_t *d) { int i,v; for (i=0;i<100;i++) { if (misaligned) v=((misaligned_t *)a)->a[i]; else v=((aligned_t *)a)->a[i]; d->a[i]+=v; } } struct b {int v; misaligned_t m;aligned_t aa;} b; aligned_t d; int main() { t(&b.m, 1, &d); return 0; }
the_stack_data/90764448.c
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : [email protected] institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include<stdio.h> int main() { int n,a[100000],e=0,o=0; scanf("%d",&n); while(n--){ scanf("%d",&a[n]); if(a[n]%2) o++; else e++; } if(e>o) printf("READY FOR BATTLE"); else printf("NOT READY"); printf("\n"); return 0; }
the_stack_data/123156.c
#include <stdio.h> /* & | 0 1 --------- 0 | 0 0 1 | 0 1 */ void l31() { int nr; scanf("%d", &nr); if(nr & 1) printf("impar"); else printf("par"); } void l32() { // n*8, n/4, n*10 // n*10 = n*2*5 = n*2*(1+4) = n*2 + n*8 /* 12 = 8+4 1100 00011000 nr*2 01100000 nr*8 12 * 10 = 120 10000000 128 01111111 127 01111000 120 14 = 8+4+2 1110 00011100 nr*2 01110000 nr*8 -------- 10001100 cu | am obtine 01111100 14 * 10 = 140 10000000 128 10000010 130 10001010 138 10001100 140 */ int nr; printf("nr="); scanf("%d", &nr); printf("nr*8: %d, nr/4: %d, nr*10: %d\n", nr << 3, nr >> 2, (nr << 1) + (nr << 3)); //printf("nr*8: %d, nr/4: %d, nr*10: %d\n", nr << 3, nr >> 2, (nr << 1) ?? (nr << 3)); // ca să facem și adunarea pe biți, ar trebui să facem // a ^ b // apoi trebuie adunat carry dacă (a & b) este diferit de 0 // carry va fi (a & b) << 1; vom face xor cu rezultatul a ^ b // trebuie să facem asta recursiv până când nu mai avem carry // ... numai că aceste apeluri recursive sunt mai costisitoare dacă le facem din software } int main() { //l31(); l32(); return 0; }
the_stack_data/231393400.c
#include <stdio.h> #include <string.h> #define MAX 100 void delchar(); int main() { char string[MAX]; printf("Enter the string: "); fgets(string, MAX, stdin); int len = strlen(string); while(len != 2) { for (int i = 0; i <= len; i++) { if (string[i] == string[i + 1]) delchar(string, 2, i+1); } } } void delchar(char *x,int a, int b) { if ((a+b-1) <= strlen(x)) { strcpy(&x[b-1],&x[a+b-1]); puts(x); } }
the_stack_data/493005.c
#include <stdio.h> #include <stdlib.h> #include <string.h> //#define DEBUG 0 #define size 100000 int array[size]; int partition_strategy = 0; void swap(int x, int y) { int temp; temp = array[x]; array[x] = array[y]; array[y] = temp; } void set_pivot(int start, int end) { int el1, el2, el3; switch (partition_strategy) { case 0: break; case 1: swap(start, end); break; case 2: el1 = array[start]; el2 = array[(end - start)/2]; el3 = array[end]; if ((el1 <= el2 && el2 <= el3) || (el3 <= el2 && el2 <= el1)) swap(start, (end - start)/2); else if ((el1 <= el3 && el3 <= el2) || (el2 <= el3 && el3 <= el1)) swap(start, end); else if ((el2 <= el1 && el1 <= el3) || (el3 <= el1 && el1 <= el2)) { /* pivot already at the beginning of the array */ } break; default: break; } } int partition(int start, int end) { int p, i, j; p = array[start]; i = start + 1; for (j = start + 1; j <= end; j++) if (array[j] < p) swap(j, i++); swap(i - 1, start); #ifdef DEBUG #if (DEBUG == 1) printf("Pivot element %d moved to position %d\n", p, (i - 1)); printf("\n"); #endif #endif return (i - 1); } int sort_and_count(int start, int end) { int pivot_pos; unsigned long long n1, n2; if (start >= end) return 0; set_pivot(start, end); pivot_pos = partition(start, end); n1 = (pivot_pos - 1 - start) + sort_and_count(start, pivot_pos - 1); n2 = (end - pivot_pos - 1) + sort_and_count(pivot_pos + 1, end); return n1 + n2; } int main(int argc, char **argv) { int i, j; unsigned long long total; FILE *fp = NULL; char *line = NULL; size_t len = 0; ssize_t read; char *filename; if (argc == 2) { partition_strategy = atoi(argv[1]); } if (argc == 3) { partition_strategy = atoi(argv[1]); filename = (char *)malloc(sizeof(char) * strlen(argv[2])); filename = argv[2]; } else { filename = (char *)malloc(sizeof(char) * 8); filename = "numbers"; } fp = fopen(filename, "r"); if (fp == NULL) { array[0] = 1; array[1] = 3; array[2] = 5; array[3] = 2; array[4] = 4; array[5] = 6; i = 6; } else { i = 0; while ((read = getline(&line, &len, fp)) != -1) { #ifdef DEBUG #if (DEBUG == 1) printf("%s", line); #endif #endif array[i++] = atoi(line); } fclose(fp); #ifdef DEBUG #if (DEBUG == 1) printf("\n"); #endif #endif } total = i - 1; total += sort_and_count(0, i - 1); printf("Total number of comparisons: %Lu\n", total); #ifdef DEBUG #if (DEBUG == 0) printf("\nAfter the sort\n"); for (j = 0; j < i; j++) printf("%d \n", array[j]); printf("\n"); #endif #endif return 0; }
the_stack_data/12165.c
extern void abort (void); __attribute__((noinline, noclone)) void foo (int *p, int *q, int *r, int n, int m) { int i, err, *s = r; int sep = 1; #pragma omp target map(to:sep) sep = 0; #pragma omp target data map(to:p[0:8]) { /* For zero length array sections, p points to the start of already mapped range, q to the end of it (with nothing mapped after it), and r does not point to an mapped range. */ #pragma omp target map(alloc:p[:0]) map(to:q[:0]) map(from:r[:0]) private(i) map(from:err) firstprivate (s) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (sep) { if (q != (int *) 0 || r != (int *) 0) err = 1; } else if (p + 8 != q || r != s) err = 1; } if (err) abort (); /* Implicit mapping of pointers behaves the same way. */ #pragma omp target private(i) map(from:err) firstprivate (s) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (sep) { if (q != (int *) 0 || r != (int *) 0) err = 1; } else if (p + 8 != q || r != s) err = 1; } if (err) abort (); /* And zero-length array sections, though not known at compile time, behave the same. */ #pragma omp target map(p[:n]) map(tofrom:q[:n]) map(alloc:r[:n]) private(i) map(from:err) firstprivate (s) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (sep) { if (q != (int *) 0 || r != (int *) 0) err = 1; } else if (p + 8 != q || r != s) err = 1; } if (err) abort (); /* Non-zero length array sections, though not known at compile, behave differently. */ #pragma omp target map(p[:m]) map(tofrom:q[:m]) map(to:r[:m]) private(i) map(from:err) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (q[0] != 9 || r[0] != 10) err = 1; } if (err) abort (); #pragma omp target data map(to:q[0:1]) { /* For zero length array sections, p points to the start of already mapped range, q points to the start of another one, and r to the end of the second one. */ #pragma omp target map(to:p[:0]) map(from:q[:0]) map(tofrom:r[:0]) private(i) map(from:err) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (q[0] != 9) err = 1; else if (sep) { if (r != (int *) 0) err = 1; } else if (r != q + 1) err = 1; } if (err) abort (); /* Implicit mapping of pointers behaves the same way. */ #pragma omp target private(i) map(from:err) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (q[0] != 9) err = 1; else if (sep) { if (r != (int *) 0) err = 1; } else if (r != q + 1) err = 1; } if (err) abort (); /* And zero-length array sections, though not known at compile time, behave the same. */ #pragma omp target map(p[:n]) map(alloc:q[:n]) map(from:r[:n]) private(i) map(from:err) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (q[0] != 9) err = 1; else if (sep) { if (r != (int *) 0) err = 1; } else if (r != q + 1) err = 1; } if (err) abort (); /* Non-zero length array sections, though not known at compile, behave differently. */ #pragma omp target map(p[:m]) map(alloc:q[:m]) map(tofrom:r[:m]) private(i) map(from:err) { err = 0; for (i = 0; i < 8; i++) if (p[i] != i + 1) err = 1; if (q[0] != 9 || r[0] != 10) err = 1; } if (err) abort (); } } } int main () { int a[32], i; for (i = 0; i < 32; i++) a[i] = i; foo (a + 1, a + 9, a + 10, 0, 1); return 0; }
the_stack_data/35623.c
int callee_function(int my_arg); void caller_function() { callee_function(0xdede); } int callee_function(int my_arg) { return my_arg; }
the_stack_data/140766421.c
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_strlcpy.c :+: :+: */ /* +:+ */ /* By: tosinga <[email protected]> +#+ */ /* +#+ */ /* Created: 2022/04/05 14:08:27 by tosinga #+# #+# */ /* Updated: 2022/04/05 14:08:28 by tosinga ######## odam.nl */ /* */ /* ************************************************************************** */ #include <stddef.h> size_t ft_strlcpy(char *dst, const char *src, size_t dstsize) { size_t a; size_t b; a = 0; b = 0; while (src[b] != '\0') b++; if (dstsize == 0) return (b); while (src[a] && dstsize > a + 1) { dst[a] = src[a]; a++; } dst[a] = '\0'; return (b); }
the_stack_data/159514688.c
// SPDX-License-Identifier: GPL-2.0-only /* * Minimal BPF assembler * * Instead of libpcap high-level filter expressions, it can be quite * useful to define filters in low-level BPF assembler (that is kept * close to Steven McCanne and Van Jacobson's original BPF paper). * In particular for BPF JIT implementors, JIT security auditors, or * just for defining BPF expressions that contain extensions which are * not supported by compilers. * * How to get into it: * * 1) read Documentation/networking/filter.txt * 2) Run `bpf_asm [-c] <filter-prog file>` to translate into binary * blob that is loadable with xt_bpf, cls_bpf et al. Note: -c will * pretty print a C-like construct. * * Copyright 2013 Daniel Borkmann <[email protected]> */ #include <stdbool.h> #include <stdio.h> #include <string.h> extern void bpf_asm_compile(FILE *fp, bool cstyle); int main(int argc, char **argv) { FILE *fp = stdin; bool cstyle = false; int i; for (i = 1; i < argc; i++) { if (!strncmp("-c", argv[i], 2)) { cstyle = true; continue; } fp = fopen(argv[i], "r"); if (!fp) { fp = stdin; continue; } break; } bpf_asm_compile(fp, cstyle); return 0; }
the_stack_data/51699857.c
#ifdef COMMENT Proprietary Rand Corporation, 1981. Further distribution of this software subject to the terms of the Rand license agreement. #endif errtype(file, errmsg) char *file, *errmsg; { register char *r1, *r2; char errlin[80]; register char *r3; r3 = errlin; r1 = r3; r2 = file; while (*r1++ = *r2++); r1[-1] = ':'; r2 = errmsg; while (*r1++ = *r2++); r1[-1] = '\n'; write(2, r3, r1-r3); }
the_stack_data/3261876.c
/* Leia um vetor contendo letras de uma frase inclusive os espac¸os em branco. Retirar os espacos em branco do vetor e depois escrever o vetor resultante. */ #include <stdio.h> #include <string.h> #include <locale.h> #include <ctype.h> int main(){ char str[255], str2[255]; fgets(str, 100, stdin); int by = strlen(str); int count = 0; while (str[count] != '\0'){ if (str[count] != ' '){ str2[count] = str[count]; } ++count; } printf("%s\n", str2); return 0; }
the_stack_data/87638246.c
static inline unsigned long rdfpcr(void) { unsigned long tmp, ret; __asm__ ("" : "=r"(tmp), "=r"(ret)); return ret; } static inline unsigned long swcr_update_status(unsigned long swcr, unsigned long fpcr) { swcr &= ~0x7e0000ul; swcr |= (fpcr >> 3) & 0x7e0000ul; return swcr; } unsigned long osf_getsysinfo(unsigned long flags) { unsigned long w; w = swcr_update_status(flags, rdfpcr()); return w; }
the_stack_data/6387036.c
#include <stdio.h> int ft_find_next_prime(int nb); int main(void) { printf("Test 0: %d\n", ft_find_next_prime(0)); printf("Test 1: %d\n", ft_find_next_prime(1)); printf("Test -2: %d\n", ft_find_next_prime(-2)); printf("Test 5409832: %d\n", ft_find_next_prime(5409832)); printf("Test 1098758934: %d\n", ft_find_next_prime(1098758934)); printf("Test 2,147,483,645: %d\n", ft_find_next_prime(2147483645)); printf("Test 2,147,483,646: %d\n", ft_find_next_prime(2147483646)); printf("Test 2,147,483,587: %d\n", ft_find_next_prime(2147483587)); printf("Test 2,147,483,643: %d\n", ft_find_next_prime(2147483643)); printf("Test 2,147,483,645: %d\n", ft_find_next_prime(2147483645)); printf("Test 2,147,483,647: %d\n", ft_find_next_prime(2147483647)); return (0); }
the_stack_data/243891955.c
// Matheus Corrêa - 202010270 // Leonardo Rossi Vinagre - 202010277 #include <stdio.h> #include <stdlib.h> typedef int dataType; typedef struct bloc { dataType data; struct bloc *left, *right; struct bloc *dad; } node; FILE *output; int initBinTree(node **AB) { *AB = NULL; return 0; } void printNode(int d, int p, int b) { int i; for (i = 1; i < b; i++) printf("|------"); printf("%d(%d)\n", d, p); for (i = 1; i < b; i++) fprintf(output, "|------"); fprintf(output, "%d(%d)\n", d, p); } void printTree(node *dad, node *AB, int b) { if (AB == NULL) { return; } printTree(AB, AB->right, b + 1); if ((AB->dad) != NULL) printNode(AB->data, (AB->dad)->data, b); else printNode(AB->data, 0, b); printTree(AB, AB->left, b + 1); } int insertBinTree(node **AB, dataType data) { node *newNode, *aux, *temp; newNode = (node *)malloc(sizeof(node)); if (newNode == NULL) return 1; newNode->data = data; newNode->left = NULL; newNode->right = NULL; aux = *AB; while (aux != NULL) { temp = aux; if (data == (aux->data)) return 1; if (data > (aux->data)) aux = aux->right; else aux = aux->left; } if (aux == *AB) { newNode->dad = NULL; *AB = newNode; } else { newNode->dad = temp; if (data > temp->data) temp->right = newNode; else temp->left = newNode; } return 0; } void leftAux(node *Tree, int layer, int *MaxLayer) { if (Tree == NULL) return; if (*MaxLayer < layer) { printf("%d-", Tree->data); *MaxLayer = layer; } leftAux(Tree->left, layer + 1, MaxLayer); leftAux(Tree->right, layer + 1, MaxLayer); } void printLeft(node *Tree) { int MaxLayer = 0; leftAux(Tree, 1, &MaxLayer); } int main() { int i, option, data, erro; node *Tree; initBinTree(&Tree); do { system("cls"); printf("\nBinari Tree"); printf("\n\n1 -> Add data"); printf("\n2 -> Print Tree"); printf("\n3 -> Print left Tree"); printf("\n0 -> Close"); printf("\n\nOptions:"); scanf("%d", &option); switch (option) { case 1: system("cls"); printf("\nData: "); scanf("%d", &data); erro = insertBinTree(&Tree, data); if (erro == 1) printf("\nNumber already exist!\n"); break; case 2: system("cls"); printTree(NULL, Tree, 1); system("pause"); break; case 3: system("cls"); printLeft(Tree); system("pause"); break; case 0: break; default: printf("\n\n Invalid Option"); } getchar(); } while ((option != 0)); system("pause"); }
the_stack_data/159515500.c
//-----------------------BEGIN NOTICE -- DO NOT EDIT----------------------- // NASA Goddard Space Flight Center // Land Information System Framework (LISF) // Version 7.3 // // Copyright (c) 2020 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. //-------------------------END NOTICE -- DO NOT EDIT----------------------- #ifndef XMRG_RESERVE_BYTE #define XMRG_RESERVE_BYTE 1 //BOP // !ROUTINE: reverse_byte_order // \label{reverse_byte_order} // !INTERFACE: void reverse_byte_order(int *in_array,int arraysize) // !DESCRIPTION: // This routine reverses byte order for 4-byte integer. Real number has to be // casted into (int *) type when calling reverse\_byte\_order. // This code is adapted from \url{http://www.nws.noaa.gov/oh/hrl/dmip/2/src/read_xmrg2.c} //EOP { unsigned int i,k; signed char *p_data; /*data pointer*/ signed char *p_temp; /*temporaty data pointer */ int temp; p_data = (signed char *) in_array - 1; for ( k = 0 ; k < arraysize ; k++ ) { temp = *( in_array + k ); p_temp = ( signed char * ) ( &temp ) + 4; for( i = 0 ; i < 4 ; i++ ) { *(++p_data) = *(--p_temp); } } } //BOP // !ROUTINE: reverse_byte_order_short // \label{reverse_byte_order_short} // !INTERFACE: void reverse_byte_order_short(short *in_array,int arraysize) // !DESCRIPTION: // This routine reverses byte order for 2-byte integer. // This code is adpated from \url{http://www.nws.noaa.gov/oh/hrl/dmip/2/src/read_xmrg2.c} //EOP { unsigned int i,k; signed char *p_data; /*data pointer*/ signed char *p_temp; /*temporaty data pointer */ short temp; p_data = (signed char *) in_array - 1; for ( k = 0 ; k < arraysize ; k++ ) { temp = *( in_array + k ); p_temp = ( signed char * ) ( &temp ) + 2; for ( i = 0 ; i < 2 ; i++ ) { *(++p_data) = *(--p_temp); } } } #endif
the_stack_data/750075.c
/* { dg-do assemble } */ /* { dg-skip-if "" { pdp11-*-* } { "-O0" } { "" } } */ /* PR optimization/5892 */ typedef struct { unsigned long a; unsigned int b, c; } A; typedef struct { unsigned long a; A *b; int c; } B; static inline unsigned int bar (unsigned int x) { unsigned long r; asm ("" : "=r" (r) : "0" (x)); return r >> 31; } int foo (B *x) { A *y; y = x->b; y->b = bar (x->c); y->c = ({ unsigned int z = 1; (z << 24) | (z >> 24); }); }
the_stack_data/140764972.c
int foo (void); int foo (void) { return 0; }
the_stack_data/118987.c
/* $OpenBSD: recv.c,v 1.5 2005/08/06 20:30:03 espie Exp $ */ /* * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/types.h> #include <sys/socket.h> #include <stddef.h> ssize_t recv(int s, void *buf, size_t len, int flags) { return (recvfrom(s, buf, len, flags, NULL, 0)); }
the_stack_data/98332.c
/* ** This file contains all sources (including headers) to the LEMON ** LALR(1) parser generator. The sources have been combined into a ** single file to make it easy to include LEMON in the source tree ** and Makefile of another program. ** ** The author of this program disclaims copyright. */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <assert.h> #ifndef __WIN32__ # if defined(_WIN32) || defined(WIN32) # define __WIN32__ # endif #endif #ifdef __WIN32__ #ifdef __cplusplus extern "C" { #endif extern int access(const char *path, int mode); #ifdef __cplusplus } #endif #else #include <unistd.h> #endif /* #define PRIVATE static */ #define PRIVATE #ifdef TEST #define MAXRHS 5 /* Set low to exercise exception code */ #else #define MAXRHS 1000 #endif static int showPrecedenceConflict = 0; static char *msort(char*,char**,int(*)(const char*,const char*)); /* ** Compilers are getting increasingly pedantic about type conversions ** as C evolves ever closer to Ada.... To work around the latest problems ** we have to define the following variant of strlen(). */ #define lemonStrlen(X) ((int)strlen(X)) /* a few forward declarations... */ struct rule; struct lemon; struct action; static struct action *Action_new(void); static struct action *Action_sort(struct action *); /********** From the file "build.h" ************************************/ void FindRulePrecedences(); void FindFirstSets(); void FindStates(); void FindLinks(); void FindFollowSets(); void FindActions(); /********* From the file "configlist.h" *********************************/ void Configlist_init(void); struct config *Configlist_add(struct rule *, int); struct config *Configlist_addbasis(struct rule *, int); void Configlist_closure(struct lemon *); void Configlist_sort(void); void Configlist_sortbasis(void); struct config *Configlist_return(void); struct config *Configlist_basis(void); void Configlist_eat(struct config *); void Configlist_reset(void); /********* From the file "error.h" ***************************************/ void ErrorMsg(const char *, int,const char *, ...); /****** From the file "option.h" ******************************************/ enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; struct s_options { enum option_type type; const char *label; char *arg; const char *message; }; int OptInit(char**,struct s_options*,FILE*); int OptNArgs(void); char *OptArg(int); void OptErr(int); void OptPrint(void); /******** From the file "parse.h" *****************************************/ void Parse(struct lemon *lemp); /********* From the file "plink.h" ***************************************/ struct plink *Plink_new(void); void Plink_add(struct plink **, struct config *); void Plink_copy(struct plink **, struct plink *); void Plink_delete(struct plink *); /********** From the file "report.h" *************************************/ void Reprint(struct lemon *); void ReportOutput(struct lemon *); void ReportTable(struct lemon *, int); void ReportHeader(struct lemon *); void CompressTables(struct lemon *); void ResortStates(struct lemon *); /********** From the file "set.h" ****************************************/ void SetSize(int); /* All sets will be of size N */ char *SetNew(void); /* A new set for element 0..N */ void SetFree(char*); /* Deallocate a set */ int SetAdd(char*,int); /* Add element to a set */ int SetUnion(char *,char *); /* A <- A U B, thru element N */ #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ /********** From the file "struct.h" *************************************/ /* ** Principal data structures for the LEMON parser generator. */ typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean; /* Symbols (terminals and nonterminals) of the grammar are stored ** in the following: */ enum symbol_type { TERMINAL, NONTERMINAL, MULTITERMINAL }; enum e_assoc { LEFT, RIGHT, NONE, UNK }; struct symbol { const char *name; /* Name of the symbol */ int index; /* Index number for this symbol */ enum symbol_type type; /* Symbols are all either TERMINALS or NTs */ struct rule *rule; /* Linked list of rules of this (if an NT) */ struct symbol *fallback; /* fallback token in case this token doesn't parse */ int prec; /* Precedence if defined (-1 otherwise) */ enum e_assoc assoc; /* Associativity if precedence is defined */ char *firstset; /* First-set for all rules of this symbol */ Boolean lambda; /* True if NT and can generate an empty string */ int useCnt; /* Number of times used */ char *destructor; /* Code which executes whenever this symbol is ** popped from the stack during error processing */ int destLineno; /* Line number for start of destructor */ char *datatype; /* The data type of information held by this ** object. Only used if type==NONTERMINAL */ int dtnum; /* The data type number. In the parser, the value ** stack is a union. The .yy%d element of this ** union is the correct data type for this object */ /* The following fields are used by MULTITERMINALs only */ int nsubsym; /* Number of constituent symbols in the MULTI */ struct symbol **subsym; /* Array of constituent symbols */ }; /* Each production rule in the grammar is stored in the following ** structure. */ struct rule { struct symbol *lhs; /* Left-hand side of the rule */ const char *lhsalias; /* Alias for the LHS (NULL if none) */ int lhsStart; /* True if left-hand side is the start symbol */ int ruleline; /* Line number for the rule */ int nrhs; /* Number of RHS symbols */ struct symbol **rhs; /* The RHS symbols */ const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ int line; /* Line number at which code begins */ const char *code; /* The code executed when this rule is reduced */ struct symbol *precsym; /* Precedence symbol for this rule */ int index; /* An index number for this rule */ Boolean canReduce; /* True if this rule is ever reduced */ struct rule *nextlhs; /* Next rule with the same LHS */ struct rule *next; /* Next rule in the global list */ }; /* A configuration is a production rule of the grammar together with ** a mark (dot) showing how much of that rule has been processed so far. ** Configurations also contain a follow-set which is a list of terminal ** symbols which are allowed to immediately follow the end of the rule. ** Every configuration is recorded as an instance of the following: */ enum cfgstatus { COMPLETE, INCOMPLETE }; struct config { struct rule *rp; /* The rule upon which the configuration is based */ int dot; /* The parse point */ char *fws; /* Follow-set for this configuration only */ struct plink *fplp; /* Follow-set forward propagation links */ struct plink *bplp; /* Follow-set backwards propagation links */ struct state *stp; /* Pointer to state which contains this */ enum cfgstatus status; /* used during followset and shift computations */ struct config *next; /* Next configuration in the state */ struct config *bp; /* The next basis configuration */ }; enum e_action { SHIFT, ACCEPT, REDUCE, ERROR, SSCONFLICT, /* A shift/shift conflict */ SRCONFLICT, /* Was a reduce, but part of a conflict */ RRCONFLICT, /* Was a reduce, but part of a conflict */ SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ NOT_USED /* Deleted by compression */ }; /* Every shift or reduce operation is stored as one of the following */ struct action { struct symbol *sp; /* The look-ahead symbol */ enum e_action type; union { struct state *stp; /* The new state, if a shift */ struct rule *rp; /* The rule, if a reduce */ } x; struct action *next; /* Next action for this state */ struct action *collide; /* Next action with the same hash */ }; /* Each state of the generated parser's finite state machine ** is encoded as an instance of the following structure. */ struct state { struct config *bp; /* The basis configurations for this state */ struct config *cfp; /* All configurations in this set */ int statenum; /* Sequential number for this state */ struct action *ap; /* Array of actions for this state */ int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ int iDflt; /* Default action */ }; #define NO_OFFSET (-2147483647) /* A followset propagation link indicates that the contents of one ** configuration followset should be propagated to another whenever ** the first changes. */ struct plink { struct config *cfp; /* The configuration to which linked */ struct plink *next; /* The next propagate link */ }; /* The state vector for the entire parser generator is recorded as ** follows. (LEMON uses no global variables and makes little use of ** static variables. Fields in the following structure can be thought ** of as begin global variables in the program.) */ struct lemon { struct state **sorted; /* Table of states sorted by state number */ struct rule *rule; /* List of all rules */ int nstate; /* Number of states */ int nrule; /* Number of rules */ int nsymbol; /* Number of terminal and nonterminal symbols */ int nterminal; /* Number of terminal symbols */ struct symbol **symbols; /* Sorted array of pointers to symbols */ int errorcnt; /* Number of errors */ struct symbol *errsym; /* The error symbol */ struct symbol *wildcard; /* Token that matches anything */ char *name; /* Name of the generated parser */ char *arg; /* Declaration of the 3th argument to parser */ char *tokentype; /* Type of terminal symbols in the parser stack */ char *vartype; /* The default type of non-terminal symbols */ char *start; /* Name of the start symbol for the grammar */ char *stacksize; /* Size of the parser stack */ char *include; /* Code to put at the start of the C file */ char *error; /* Code to execute when an error is seen */ char *overflow; /* Code to execute on a stack overflow */ char *failure; /* Code to execute on parser failure */ char *accept; /* Code to execute when the parser excepts */ char *extracode; /* Code appended to the generated file */ char *tokendest; /* Code to execute to destroy token data */ char *vardest; /* Code for the default non-terminal destructor */ char *filename; /* Name of the input file */ char *outname; /* Name of the current output file */ char *tokenprefix; /* A prefix added to token names in the .h file */ int nconflict; /* Number of parsing conflicts */ int tablesize; /* Size of the parse tables */ int basisflag; /* Print only basis configurations */ int has_fallback; /* True if any %fallback is seen in the grammar */ int nolinenosflag; /* True if #line statements should not be printed */ char *argv0; /* Name of the program */ }; #define MemoryCheck(X) if((X)==0){ \ extern void memory_error(); \ memory_error(); \ } /**************** From the file "table.h" *********************************/ /* ** All code in this file has been automatically generated ** from a specification in the file ** "table.q" ** by the associative array code building program "aagen". ** Do not edit this file! Instead, edit the specification ** file, then rerun aagen. */ /* ** Code for processing tables in the LEMON parser generator. */ /* Routines for handling a strings */ const char *Strsafe(const char *); void Strsafe_init(void); int Strsafe_insert(const char *); const char *Strsafe_find(const char *); /* Routines for handling symbols of the grammar */ struct symbol *Symbol_new(const char *); int Symbolcmpp(const void *, const void *); void Symbol_init(void); int Symbol_insert(struct symbol *, const char *); struct symbol *Symbol_find(const char *); struct symbol *Symbol_Nth(int); int Symbol_count(void); struct symbol **Symbol_arrayof(void); /* Routines to manage the state table */ int Configcmp(const char *, const char *); struct state *State_new(void); void State_init(void); int State_insert(struct state *, struct config *); struct state *State_find(struct config *); struct state **State_arrayof(/* */); /* Routines used for efficiency in Configlist_add */ void Configtable_init(void); int Configtable_insert(struct config *); struct config *Configtable_find(struct config *); void Configtable_clear(int(*)(struct config *)); /****************** From the file "action.c" *******************************/ /* ** Routines processing parser actions in the LEMON parser generator. */ /* Allocate a new parser action */ static struct action *Action_new(void){ static struct action *freelist = 0; struct action *newaction; if( freelist==0 ){ int i; int amt = 100; freelist = (struct action *)calloc(amt, sizeof(struct action)); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new parser action."); exit(1); } for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1]; freelist[amt-1].next = 0; } newaction = freelist; freelist = freelist->next; return newaction; } /* Compare two actions for sorting purposes. Return negative, zero, or ** positive if the first action is less than, equal to, or greater than ** the first */ static int actioncmp( struct action *ap1, struct action *ap2 ){ int rc; rc = ap1->sp->index - ap2->sp->index; if( rc==0 ){ rc = (int)ap1->type - (int)ap2->type; } if( rc==0 && ap1->type==REDUCE ){ rc = ap1->x.rp->index - ap2->x.rp->index; } if( rc==0 ){ rc = (int) (ap2 - ap1); } return rc; } /* Sort parser actions */ static struct action *Action_sort( struct action *ap ){ ap = (struct action *)msort((char *)ap,(char **)&ap->next, (int(*)(const char*,const char*))actioncmp); return ap; } void Action_add( struct action **app, enum e_action type, struct symbol *sp, char *arg ){ struct action *newaction; newaction = Action_new(); newaction->next = *app; *app = newaction; newaction->type = type; newaction->sp = sp; if( type==SHIFT ){ newaction->x.stp = (struct state *)arg; }else{ newaction->x.rp = (struct rule *)arg; } } /********************** New code to implement the "acttab" module ***********/ /* ** This module implements routines use to construct the yy_action[] table. */ /* ** The state of the yy_action table under construction is an instance of ** the following structure. ** ** The yy_action table maps the pair (state_number, lookahead) into an ** action_number. The table is an array of integers pairs. The state_number ** determines an initial offset into the yy_action array. The lookahead ** value is then added to this initial offset to get an index X into the ** yy_action array. If the aAction[X].lookahead equals the value of the ** of the lookahead input, then the value of the action_number output is ** aAction[X].action. If the lookaheads do not match then the ** default action for the state_number is returned. ** ** All actions associated with a single state_number are first entered ** into aLookahead[] using multiple calls to acttab_action(). Then the ** actions for that single state_number are placed into the aAction[] ** array with a single call to acttab_insert(). The acttab_insert() call ** also resets the aLookahead[] array in preparation for the next ** state number. */ struct lookahead_action { int lookahead; /* Value of the lookahead token */ int action; /* Action to take on the given lookahead */ }; typedef struct acttab acttab; struct acttab { int nAction; /* Number of used slots in aAction[] */ int nActionAlloc; /* Slots allocated for aAction[] */ struct lookahead_action *aAction, /* The yy_action[] table under construction */ *aLookahead; /* A single new transaction set */ int mnLookahead; /* Minimum aLookahead[].lookahead */ int mnAction; /* Action associated with mnLookahead */ int mxLookahead; /* Maximum aLookahead[].lookahead */ int nLookahead; /* Used slots in aLookahead[] */ int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ }; /* Return the number of entries in the yy_action table */ #define acttab_size(X) ((X)->nAction) /* The value for the N-th entry in yy_action */ #define acttab_yyaction(X,N) ((X)->aAction[N].action) /* The value for the N-th entry in yy_lookahead */ #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) /* Free all memory associated with the given acttab */ void acttab_free(acttab *p){ free( p->aAction ); free( p->aLookahead ); free( p ); } /* Allocate a new acttab structure */ acttab *acttab_alloc(void){ acttab *p = (acttab *) calloc( 1, sizeof(*p) ); if( p==0 ){ fprintf(stderr,"Unable to allocate memory for a new acttab."); exit(1); } memset(p, 0, sizeof(*p)); return p; } /* Add a new action to the current transaction set. ** ** This routine is called once for each lookahead for a particular ** state. */ void acttab_action(acttab *p, int lookahead, int action){ if( p->nLookahead>=p->nLookaheadAlloc ){ p->nLookaheadAlloc += 25; p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead, sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); if( p->aLookahead==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } } if( p->nLookahead==0 ){ p->mxLookahead = lookahead; p->mnLookahead = lookahead; p->mnAction = action; }else{ if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead; if( p->mnLookahead>lookahead ){ p->mnLookahead = lookahead; p->mnAction = action; } } p->aLookahead[p->nLookahead].lookahead = lookahead; p->aLookahead[p->nLookahead].action = action; p->nLookahead++; } /* ** Add the transaction set built up with prior calls to acttab_action() ** into the current action table. Then reset the transaction set back ** to an empty set in preparation for a new round of acttab_action() calls. ** ** Return the offset into the action table of the new transaction. */ int acttab_insert(acttab *p){ int i, j, k, n; assert( p->nLookahead>0 ); /* Make sure we have enough space to hold the expanded action table ** in the worst case. The worst case occurs if the transaction set ** must be appended to the current action table */ n = p->mxLookahead + 1; if( p->nAction + n >= p->nActionAlloc ){ int oldAlloc = p->nActionAlloc; p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; p->aAction = (struct lookahead_action *) realloc( p->aAction, sizeof(p->aAction[0])*p->nActionAlloc); if( p->aAction==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } for(i=oldAlloc; i<p->nActionAlloc; i++){ p->aAction[i].lookahead = -1; p->aAction[i].action = -1; } } /* Scan the existing action table looking for an offset that is a ** duplicate of the current transaction set. Fall out of the loop ** if and when the duplicate is found. ** ** i is the index in p->aAction[] where p->mnLookahead is inserted. */ for(i=p->nAction-1; i>=0; i--){ if( p->aAction[i].lookahead==p->mnLookahead ){ /* All lookaheads and actions in the aLookahead[] transaction ** must match against the candidate aAction[i] entry. */ if( p->aAction[i].action!=p->mnAction ) continue; for(j=0; j<p->nLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; if( k<0 || k>=p->nAction ) break; if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; if( p->aLookahead[j].action!=p->aAction[k].action ) break; } if( j<p->nLookahead ) continue; /* No possible lookahead value that is not in the aLookahead[] ** transaction is allowed to match aAction[i] */ n = 0; for(j=0; j<p->nAction; j++){ if( p->aAction[j].lookahead<0 ) continue; if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; } if( n==p->nLookahead ){ break; /* An exact match is found at offset i */ } } } /* If no existing offsets exactly match the current transaction, find an ** an empty offset in the aAction[] table in which we can add the ** aLookahead[] transaction. */ if( i<0 ){ /* Look for holes in the aAction[] table that fit the current ** aLookahead[] transaction. Leave i set to the offset of the hole. ** If no holes are found, i is left at p->nAction, which means the ** transaction will be appended. */ for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){ if( p->aAction[i].lookahead<0 ){ for(j=0; j<p->nLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; if( k<0 ) break; if( p->aAction[k].lookahead>=0 ) break; } if( j<p->nLookahead ) continue; for(j=0; j<p->nAction; j++){ if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; } if( j==p->nAction ){ break; /* Fits in empty slots */ } } } } /* Insert transaction set at index i. */ for(j=0; j<p->nLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; p->aAction[k] = p->aLookahead[j]; if( k>=p->nAction ) p->nAction = k+1; } p->nLookahead = 0; /* Return the offset that is added to the lookahead in order to get the ** index into yy_action of the action */ return i - p->mnLookahead; } /********************** From the file "build.c" *****************************/ /* ** Routines to construction the finite state machine for the LEMON ** parser generator. */ /* Find a precedence symbol of every rule in the grammar. ** ** Those rules which have a precedence symbol coded in the input ** grammar using the "[symbol]" construct will already have the ** rp->precsym field filled. Other rules take as their precedence ** symbol the first RHS symbol with a defined precedence. If there ** are not RHS symbols with a defined precedence, the precedence ** symbol field is left blank. */ void FindRulePrecedences(struct lemon *xp) { struct rule *rp; for(rp=xp->rule; rp; rp=rp->next){ if( rp->precsym==0 ){ int i, j; for(i=0; i<rp->nrhs && rp->precsym==0; i++){ struct symbol *sp = rp->rhs[i]; if( sp->type==MULTITERMINAL ){ for(j=0; j<sp->nsubsym; j++){ if( sp->subsym[j]->prec>=0 ){ rp->precsym = sp->subsym[j]; break; } } }else if( sp->prec>=0 ){ rp->precsym = rp->rhs[i]; } } } } return; } /* Find all nonterminals which will generate the empty string. ** Then go back and compute the first sets of every nonterminal. ** The first set is the set of all terminal symbols which can begin ** a string generated by that nonterminal. */ void FindFirstSets(struct lemon *lemp) { int i, j; struct rule *rp; int progress; for(i=0; i<lemp->nsymbol; i++){ lemp->symbols[i]->lambda = LEMON_FALSE; } for(i=lemp->nterminal; i<lemp->nsymbol; i++){ lemp->symbols[i]->firstset = SetNew(); } /* First compute all lambdas */ do{ progress = 0; for(rp=lemp->rule; rp; rp=rp->next){ if( rp->lhs->lambda ) continue; for(i=0; i<rp->nrhs; i++){ struct symbol *sp = rp->rhs[i]; assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE ); if( sp->lambda==LEMON_FALSE ) break; } if( i==rp->nrhs ){ rp->lhs->lambda = LEMON_TRUE; progress = 1; } } }while( progress ); /* Now compute all first sets */ do{ struct symbol *s1, *s2; progress = 0; for(rp=lemp->rule; rp; rp=rp->next){ s1 = rp->lhs; for(i=0; i<rp->nrhs; i++){ s2 = rp->rhs[i]; if( s2->type==TERMINAL ){ progress += SetAdd(s1->firstset,s2->index); break; }else if( s2->type==MULTITERMINAL ){ for(j=0; j<s2->nsubsym; j++){ progress += SetAdd(s1->firstset,s2->subsym[j]->index); } break; }else if( s1==s2 ){ if( s1->lambda==LEMON_FALSE ) break; }else{ progress += SetUnion(s1->firstset,s2->firstset); if( s2->lambda==LEMON_FALSE ) break; } } } }while( progress ); return; } /* Compute all LR(0) states for the grammar. Links ** are added to between some states so that the LR(1) follow sets ** can be computed later. */ PRIVATE struct state *getstate(struct lemon *); /* forward reference */ void FindStates(struct lemon *lemp) { struct symbol *sp; struct rule *rp; Configlist_init(); /* Find the start symbol */ if( lemp->start ){ sp = Symbol_find(lemp->start); if( sp==0 ){ ErrorMsg(lemp->filename,0, "The specified start symbol \"%s\" is not \ in a nonterminal of the grammar. \"%s\" will be used as the start \ symbol instead.",lemp->start,lemp->rule->lhs->name); lemp->errorcnt++; sp = lemp->rule->lhs; } }else{ sp = lemp->rule->lhs; } /* Make sure the start symbol doesn't occur on the right-hand side of ** any rule. Report an error if it does. (YACC would generate a new ** start symbol in this case.) */ for(rp=lemp->rule; rp; rp=rp->next){ int i; for(i=0; i<rp->nrhs; i++){ if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */ ErrorMsg(lemp->filename,0, "The start symbol \"%s\" occurs on the \ right-hand side of a rule. This will result in a parser which \ does not work properly.",sp->name); lemp->errorcnt++; } } } /* The basis configuration set for the first state ** is all rules which have the start symbol as their ** left-hand side */ for(rp=sp->rule; rp; rp=rp->nextlhs){ struct config *newcfp; rp->lhsStart = 1; newcfp = Configlist_addbasis(rp,0); SetAdd(newcfp->fws,0); } /* Compute the first state. All other states will be ** computed automatically during the computation of the first one. ** The returned pointer to the first state is not used. */ (void)getstate(lemp); return; } /* Return a pointer to a state which is described by the configuration ** list which has been built from calls to Configlist_add. */ PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */ PRIVATE struct state *getstate(struct lemon *lemp) { struct config *cfp, *bp; struct state *stp; /* Extract the sorted basis of the new state. The basis was constructed ** by prior calls to "Configlist_addbasis()". */ Configlist_sortbasis(); bp = Configlist_basis(); /* Get a state with the same basis */ stp = State_find(bp); if( stp ){ /* A state with the same basis already exists! Copy all the follow-set ** propagation links from the state under construction into the ** preexisting state, then return a pointer to the preexisting state */ struct config *x, *y; for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ Plink_copy(&y->bplp,x->bplp); Plink_delete(x->fplp); x->fplp = x->bplp = 0; } cfp = Configlist_return(); Configlist_eat(cfp); }else{ /* This really is a new state. Construct all the details */ Configlist_closure(lemp); /* Compute the configuration closure */ Configlist_sort(); /* Sort the configuration closure */ cfp = Configlist_return(); /* Get a pointer to the config list */ stp = State_new(); /* A new state structure */ MemoryCheck(stp); stp->bp = bp; /* Remember the configuration basis */ stp->cfp = cfp; /* Remember the configuration closure */ stp->statenum = lemp->nstate++; /* Every state gets a sequence number */ stp->ap = 0; /* No actions, yet. */ State_insert(stp,stp->bp); /* Add to the state table */ buildshifts(lemp,stp); /* Recursively compute successor states */ } return stp; } /* ** Return true if two symbols are the same. */ int same_symbol(struct symbol *a, struct symbol *b) { int i; if( a==b ) return 1; if( a->type!=MULTITERMINAL ) return 0; if( b->type!=MULTITERMINAL ) return 0; if( a->nsubsym!=b->nsubsym ) return 0; for(i=0; i<a->nsubsym; i++){ if( a->subsym[i]!=b->subsym[i] ) return 0; } return 1; } /* Construct all successor states to the given state. A "successor" ** state is any state which can be reached by a shift action. */ PRIVATE void buildshifts(struct lemon *lemp, struct state *stp) { struct config *cfp; /* For looping thru the config closure of "stp" */ struct config *bcfp; /* For the inner loop on config closure of "stp" */ struct config *newcfg; /* */ struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ struct state *newstp; /* A pointer to a successor state */ /* Each configuration becomes complete after it contibutes to a successor ** state. Initially, all configurations are incomplete */ for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; /* Loop through all configurations of the state "stp" */ for(cfp=stp->cfp; cfp; cfp=cfp->next){ if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ Configlist_reset(); /* Reset the new config set */ sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ /* For every configuration in the state "stp" which has the symbol "sp" ** following its dot, add the same configuration to the basis set under ** construction but with the dot shifted one symbol to the right. */ for(bcfp=cfp; bcfp; bcfp=bcfp->next){ if( bcfp->status==COMPLETE ) continue; /* Already used */ if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ bcfp->status = COMPLETE; /* Mark this config as used */ newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); Plink_add(&newcfg->bplp,bcfp); } /* Get a pointer to the state described by the basis configuration set ** constructed in the preceding loop */ newstp = getstate(lemp); /* The state "newstp" is reached from the state "stp" by a shift action ** on the symbol "sp" */ if( sp->type==MULTITERMINAL ){ int i; for(i=0; i<sp->nsubsym; i++){ Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); } }else{ Action_add(&stp->ap,SHIFT,sp,(char *)newstp); } } } /* ** Construct the propagation links */ void FindLinks(struct lemon *lemp) { int i; struct config *cfp, *other; struct state *stp; struct plink *plp; /* Housekeeping detail: ** Add to every propagate link a pointer back to the state to ** which the link is attached. */ for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ cfp->stp = stp; } } /* Convert all backlinks into forward links. Only the forward ** links are used in the follow-set computation. */ for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ for(plp=cfp->bplp; plp; plp=plp->next){ other = plp->cfp; Plink_add(&other->fplp,cfp); } } } } /* Compute all followsets. ** ** A followset is the set of all symbols which can come immediately ** after a configuration. */ void FindFollowSets(struct lemon *lemp) { int i; struct config *cfp; struct plink *plp; int progress; int change; for(i=0; i<lemp->nstate; i++){ for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ cfp->status = INCOMPLETE; } } do{ progress = 0; for(i=0; i<lemp->nstate; i++){ for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ if( cfp->status==COMPLETE ) continue; for(plp=cfp->fplp; plp; plp=plp->next){ change = SetUnion(plp->cfp->fws,cfp->fws); if( change ){ plp->cfp->status = INCOMPLETE; progress = 1; } } cfp->status = COMPLETE; } } }while( progress ); } static int resolve_conflict(struct action *,struct action *); /* Compute the reduce actions, and resolve conflicts. */ void FindActions(struct lemon *lemp) { int i,j; struct config *cfp; struct state *stp; struct symbol *sp; struct rule *rp; /* Add all of the reduce actions ** A reduce action is added for each element of the followset of ** a configuration which has its dot at the extreme right. */ for(i=0; i<lemp->nstate; i++){ /* Loop over all states */ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ for(j=0; j<lemp->nterminal; j++){ if( SetFind(cfp->fws,j) ){ /* Add a reduce action to the state "stp" which will reduce by the ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); } } } } } /* Add the accepting token */ if( lemp->start ){ sp = Symbol_find(lemp->start); if( sp==0 ) sp = lemp->rule->lhs; }else{ sp = lemp->rule->lhs; } /* Add to the first state (which is always the starting state of the ** finite state machine) an action to ACCEPT if the lookahead is the ** start nonterminal. */ Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); /* Resolve conflicts */ for(i=0; i<lemp->nstate; i++){ struct action *ap, *nap; struct state *stp; stp = lemp->sorted[i]; /* assert( stp->ap ); */ stp->ap = Action_sort(stp->ap); for(ap=stp->ap; ap && ap->next; ap=ap->next){ for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ /* The two actions "ap" and "nap" have the same lookahead. ** Figure out which one should be used */ lemp->nconflict += resolve_conflict(ap,nap); } } } /* Report an error for each rule that can never be reduced. */ for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE; for(i=0; i<lemp->nstate; i++){ struct action *ap; for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE; } } for(rp=lemp->rule; rp; rp=rp->next){ if( rp->canReduce ) continue; ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); lemp->errorcnt++; } } /* Resolve a conflict between the two given actions. If the ** conflict can't be resolved, return non-zero. ** ** NO LONGER TRUE: ** To resolve a conflict, first look to see if either action ** is on an error rule. In that case, take the action which ** is not associated with the error rule. If neither or both ** actions are associated with an error rule, then try to ** use precedence to resolve the conflict. ** ** If either action is a SHIFT, then it must be apx. This ** function won't work if apx->type==REDUCE and apy->type==SHIFT. */ static int resolve_conflict( struct action *apx, struct action *apy ){ struct symbol *spx, *spy; int errcnt = 0; assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ if( apx->type==SHIFT && apy->type==SHIFT ){ apy->type = SSCONFLICT; errcnt++; } if( apx->type==SHIFT && apy->type==REDUCE ){ spx = apx->sp; spy = apy->x.rp->precsym; if( spy==0 || spx->prec<0 || spy->prec<0 ){ /* Not enough precedence information. */ apy->type = SRCONFLICT; errcnt++; }else if( spx->prec>spy->prec ){ /* higher precedence wins */ apy->type = RD_RESOLVED; }else if( spx->prec<spy->prec ){ apx->type = SH_RESOLVED; }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ apy->type = RD_RESOLVED; /* associativity */ }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ apx->type = SH_RESOLVED; }else{ assert( spx->prec==spy->prec && spx->assoc==NONE ); apy->type = SRCONFLICT; errcnt++; } }else if( apx->type==REDUCE && apy->type==REDUCE ){ spx = apx->x.rp->precsym; spy = apy->x.rp->precsym; if( spx==0 || spy==0 || spx->prec<0 || spy->prec<0 || spx->prec==spy->prec ){ apy->type = RRCONFLICT; errcnt++; }else if( spx->prec>spy->prec ){ apy->type = RD_RESOLVED; }else if( spx->prec<spy->prec ){ apx->type = RD_RESOLVED; } }else{ assert( apx->type==SH_RESOLVED || apx->type==RD_RESOLVED || apx->type==SSCONFLICT || apx->type==SRCONFLICT || apx->type==RRCONFLICT || apy->type==SH_RESOLVED || apy->type==RD_RESOLVED || apy->type==SSCONFLICT || apy->type==SRCONFLICT || apy->type==RRCONFLICT ); /* The REDUCE/SHIFT case cannot happen because SHIFTs come before ** REDUCEs on the list. If we reach this point it must be because ** the parser conflict had already been resolved. */ } return errcnt; } /********************* From the file "configlist.c" *************************/ /* ** Routines to processing a configuration list and building a state ** in the LEMON parser generator. */ static struct config *freelist = 0; /* List of free configurations */ static struct config *current = 0; /* Top of list of configurations */ static struct config **currentend = 0; /* Last on list of configs */ static struct config *basis = 0; /* Top of list of basis configs */ static struct config **basisend = 0; /* End of list of basis configs */ /* Return a pointer to a new configuration */ PRIVATE struct config *newconfig(){ struct config *newcfg; if( freelist==0 ){ int i; int amt = 3; freelist = (struct config *)calloc( amt, sizeof(struct config) ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new configuration."); exit(1); } for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1]; freelist[amt-1].next = 0; } newcfg = freelist; freelist = freelist->next; return newcfg; } /* The configuration "old" is no longer used */ PRIVATE void deleteconfig(struct config *old) { old->next = freelist; freelist = old; } /* Initialized the configuration list builder */ void Configlist_init(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_init(); return; } /* Initialized the configuration list builder */ void Configlist_reset(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_clear(0); return; } /* Add another configuration to the configuration list */ struct config *Configlist_add( struct rule *rp, /* The rule */ int dot /* Index into the RHS of the rule where the dot goes */ ){ struct config *cfp, model; assert( currentend!=0 ); model.rp = rp; model.dot = dot; cfp = Configtable_find(&model); if( cfp==0 ){ cfp = newconfig(); cfp->rp = rp; cfp->dot = dot; cfp->fws = SetNew(); cfp->stp = 0; cfp->fplp = cfp->bplp = 0; cfp->next = 0; cfp->bp = 0; *currentend = cfp; currentend = &cfp->next; Configtable_insert(cfp); } return cfp; } /* Add a basis configuration to the configuration list */ struct config *Configlist_addbasis(struct rule *rp, int dot) { struct config *cfp, model; assert( basisend!=0 ); assert( currentend!=0 ); model.rp = rp; model.dot = dot; cfp = Configtable_find(&model); if( cfp==0 ){ cfp = newconfig(); cfp->rp = rp; cfp->dot = dot; cfp->fws = SetNew(); cfp->stp = 0; cfp->fplp = cfp->bplp = 0; cfp->next = 0; cfp->bp = 0; *currentend = cfp; currentend = &cfp->next; *basisend = cfp; basisend = &cfp->bp; Configtable_insert(cfp); } return cfp; } /* Compute the closure of the configuration list */ void Configlist_closure(struct lemon *lemp) { struct config *cfp, *newcfp; struct rule *rp, *newrp; struct symbol *sp, *xsp; int i, dot; assert( currentend!=0 ); for(cfp=current; cfp; cfp=cfp->next){ rp = cfp->rp; dot = cfp->dot; if( dot>=rp->nrhs ) continue; sp = rp->rhs[dot]; if( sp->type==NONTERMINAL ){ if( sp->rule==0 && sp!=lemp->errsym ){ ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", sp->name); lemp->errorcnt++; } for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ newcfp = Configlist_add(newrp,0); for(i=dot+1; i<rp->nrhs; i++){ xsp = rp->rhs[i]; if( xsp->type==TERMINAL ){ SetAdd(newcfp->fws,xsp->index); break; }else if( xsp->type==MULTITERMINAL ){ int k; for(k=0; k<xsp->nsubsym; k++){ SetAdd(newcfp->fws, xsp->subsym[k]->index); } break; }else{ SetUnion(newcfp->fws,xsp->firstset); if( xsp->lambda==LEMON_FALSE ) break; } } if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); } } } return; } /* Sort the configuration list */ void Configlist_sort(){ current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); currentend = 0; return; } /* Sort the basis configuration list */ void Configlist_sortbasis(){ basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); basisend = 0; return; } /* Return a pointer to the head of the configuration list and ** reset the list */ struct config *Configlist_return(){ struct config *old; old = current; current = 0; currentend = 0; return old; } /* Return a pointer to the head of the configuration list and ** reset the list */ struct config *Configlist_basis(){ struct config *old; old = basis; basis = 0; basisend = 0; return old; } /* Free all elements of the given configuration list */ void Configlist_eat(struct config *cfp) { struct config *nextcfp; for(; cfp; cfp=nextcfp){ nextcfp = cfp->next; assert( cfp->fplp==0 ); assert( cfp->bplp==0 ); if( cfp->fws ) SetFree(cfp->fws); deleteconfig(cfp); } return; } /***************** From the file "error.c" *********************************/ /* ** Code for printing error message. */ void ErrorMsg(const char *filename, int lineno, const char *format, ...){ va_list ap; fprintf(stderr, "%s:%d: ", filename, lineno); va_start(ap, format); vfprintf(stderr,format,ap); va_end(ap); fprintf(stderr, "\n"); } /**************** From the file "main.c" ************************************/ /* ** Main program file for the LEMON parser generator. */ /* Report an out-of-memory condition and abort. This function ** is used mostly by the "MemoryCheck" macro in struct.h */ void memory_error(){ fprintf(stderr,"Out of memory. Aborting...\n"); exit(1); } static int nDefine = 0; /* Number of -D options on the command line */ static char **azDefine = 0; /* Name of the -D macros */ /* This routine is called with the argument to each -D command-line option. ** Add the macro defined to the azDefine array. */ static void handle_D_option(char *z){ char **paz; nDefine++; azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine); if( azDefine==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } paz = &azDefine[nDefine-1]; *paz = (char *) malloc( lemonStrlen(z)+1 ); if( *paz==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } strcpy(*paz, z); for(z=*paz; *z && *z!='='; z++){} *z = 0; } static char *user_outputname = NULL; static void handle_O_option(char *z){ user_outputname = (char *) malloc( lemonStrlen(z)+1 ); if( user_outputname ==0 ){ memory_error(); } strcpy(user_outputname, z); } static char *user_templatename = NULL; static void handle_T_option(char *z){ user_templatename = (char *) malloc( lemonStrlen(z)+1 ); if( user_templatename==0 ){ memory_error(); } strcpy(user_templatename, z); } /* The main program. Parse the command line and do it... */ int main(int argc, char **argv) { static int version = 0; static int rpflag = 0; static int basisflag = 0; static int compress = 0; static int quiet = 0; static int statistics = 0; static int mhflag = 0; static int nolinenosflag = 0; static int noResort = 0; static struct s_options options[] = { {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."}, {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."}, {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."}, {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."}, {OPT_FSTR, "O", (char*)handle_O_option, "Specify an output file."}, {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."}, {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."}, {OPT_FLAG, "p", (char*)&showPrecedenceConflict, "Show conflicts resolved by precedence rules"}, {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"}, {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."}, {OPT_FLAG, "x", (char*)&version, "Print the version number."}, {OPT_FLAG,0,0,0} }; int i; int exitcode; struct lemon lem; OptInit(argv,options,stderr); if( version ){ printf("Lemon version 1.0\n"); exit(0); } if( OptNArgs()!=1 ){ fprintf(stderr,"Exactly one filename argument is required.\n"); exit(1); } memset(&lem, 0, sizeof(lem)); lem.errorcnt = 0; /* Initialize the machine */ Strsafe_init(); Symbol_init(); State_init(); lem.argv0 = argv[0]; lem.filename = OptArg(0); lem.basisflag = basisflag; lem.nolinenosflag = nolinenosflag; Symbol_new("$"); lem.errsym = Symbol_new("error"); lem.errsym->useCnt = 0; /* Parse the input file */ Parse(&lem); if( lem.errorcnt ) exit(lem.errorcnt); if( lem.nrule==0 ){ fprintf(stderr,"Empty grammar.\n"); exit(1); } /* Count and index the symbols of the grammar */ lem.nsymbol = Symbol_count(); Symbol_new("{default}"); lem.symbols = Symbol_arrayof(); for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp); for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; for(i=1; isupper(lem.symbols[i]->name[0]); i++); lem.nterminal = i; /* Generate a reprint of the grammar, if requested on the command line */ if( rpflag ){ Reprint(&lem); }else{ /* Initialize the size for all follow and first sets */ SetSize(lem.nterminal+1); /* Find the precedence for every production rule (that has one) */ FindRulePrecedences(&lem); /* Compute the lambda-nonterminals and the first-sets for every ** nonterminal */ FindFirstSets(&lem); /* Compute all LR(0) states. Also record follow-set propagation ** links so that the follow-set can be computed later */ lem.nstate = 0; FindStates(&lem); lem.sorted = State_arrayof(); /* Tie up loose ends on the propagation links */ FindLinks(&lem); /* Compute the follow set of every reducible configuration */ FindFollowSets(&lem); /* Compute the action tables */ FindActions(&lem); /* Compress the action tables */ if( compress==0 ) CompressTables(&lem); /* Reorder and renumber the states so that states with fewer choices ** occur at the end. This is an optimization that helps make the ** generated parser tables smaller. */ if( noResort==0 ) ResortStates(&lem); /* Generate a report of the parser generated. (the "y.output" file) */ if( !quiet ) ReportOutput(&lem); /* Generate the source code for the parser */ ReportTable(&lem, mhflag); /* Produce a header file for use by the scanner. (This step is ** omitted if the "-m" option is used because makeheaders will ** generate the file for us.) */ if( !mhflag ) ReportHeader(&lem); } if( statistics ){ printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n", lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); printf(" %d states, %d parser table entries, %d conflicts\n", lem.nstate, lem.tablesize, lem.nconflict); } if( lem.nconflict > 0 ){ fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); } /* return 0 on success, 1 on failure. */ exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; exit(exitcode); return (exitcode); } /******************** From the file "msort.c" *******************************/ /* ** A generic merge-sort program. ** ** USAGE: ** Let "ptr" be a pointer to some structure which is at the head of ** a null-terminated list. Then to sort the list call: ** ** ptr = msort(ptr,&(ptr->next),cmpfnc); ** ** In the above, "cmpfnc" is a pointer to a function which compares ** two instances of the structure and returns an integer, as in ** strcmp. The second argument is a pointer to the pointer to the ** second element of the linked list. This address is used to compute ** the offset to the "next" field within the structure. The offset to ** the "next" field must be constant for all structures in the list. ** ** The function returns a new pointer which is the head of the list ** after sorting. ** ** ALGORITHM: ** Merge-sort. */ /* ** Return a pointer to the next structure in the linked list. */ #define NEXT(A) (*(char**)(((unsigned long)A)+offset)) /* ** Inputs: ** a: A sorted, null-terminated linked list. (May be null). ** b: A sorted, null-terminated linked list. (May be null). ** cmp: A pointer to the comparison function. ** offset: Offset in the structure to the "next" field. ** ** Return Value: ** A pointer to the head of a sorted list containing the elements ** of both a and b. ** ** Side effects: ** The "next" pointers for elements in the lists a and b are ** changed. */ static char *merge( char *a, char *b, int (*cmp)(const char*,const char*), int offset ){ char *ptr, *head; if( a==0 ){ head = b; }else if( b==0 ){ head = a; }else{ if( (*cmp)(a,b)<=0 ){ ptr = a; a = NEXT(a); }else{ ptr = b; b = NEXT(b); } head = ptr; while( a && b ){ if( (*cmp)(a,b)<=0 ){ NEXT(ptr) = a; ptr = a; a = NEXT(a); }else{ NEXT(ptr) = b; ptr = b; b = NEXT(b); } } if( a ) NEXT(ptr) = a; else NEXT(ptr) = b; } return head; } /* ** Inputs: ** list: Pointer to a singly-linked list of structures. ** next: Pointer to pointer to the second element of the list. ** cmp: A comparison function. ** ** Return Value: ** A pointer to the head of a sorted list containing the elements ** orginally in list. ** ** Side effects: ** The "next" pointers for elements in list are changed. */ #define LISTSIZE 30 static char *msort( char *list, char **next, int (*cmp)(const char*,const char*) ){ unsigned long offset; char *ep; char *set[LISTSIZE]; int i; offset = (unsigned long)next - (unsigned long)list; for(i=0; i<LISTSIZE; i++) set[i] = 0; while( list ){ ep = list; list = NEXT(list); NEXT(ep) = 0; for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){ ep = merge(ep,set[i],cmp,offset); set[i] = 0; } set[i] = ep; } ep = 0; for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset); return ep; } /************************ From the file "option.c" **************************/ static char **argv; static struct s_options *op; static FILE *errstream; #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0) /* ** Print the command line with a carrot pointing to the k-th character ** of the n-th field. */ static void errline(int n, int k, FILE *err) { int spcnt, i; if( argv[0] ) fprintf(err,"%s",argv[0]); spcnt = lemonStrlen(argv[0]) + 1; for(i=1; i<n && argv[i]; i++){ fprintf(err," %s",argv[i]); spcnt += lemonStrlen(argv[i])+1; } spcnt += k; for(; argv[i]; i++) fprintf(err," %s",argv[i]); if( spcnt<20 ){ fprintf(err,"\n%*s^-- here\n",spcnt,""); }else{ fprintf(err,"\n%*shere --^\n",spcnt-7,""); } } /* ** Return the index of the N-th non-switch argument. Return -1 ** if N is out of range. */ static int argindex(int n) { int i; int dashdash = 0; if( argv!=0 && *argv!=0 ){ for(i=1; argv[i]; i++){ if( dashdash || !ISOPT(argv[i]) ){ if( n==0 ) return i; n--; } if( strcmp(argv[i],"--")==0 ) dashdash = 1; } } return -1; } static char emsg[] = "Command line syntax error: "; /* ** Process a flag command line argument. */ static int handleflags(int i, FILE *err) { int v; int errcnt = 0; int j; for(j=0; op[j].label; j++){ if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break; } v = argv[i][0]=='-' ? 1 : 0; if( op[j].label==0 ){ if( err ){ fprintf(err,"%sundefined option.\n",emsg); errline(i,1,err); } errcnt++; }else if( op[j].type==OPT_FLAG ){ *((int*)op[j].arg) = v; }else if( op[j].type==OPT_FFLAG ){ (*(void(*)(int))(op[j].arg))(v); }else if( op[j].type==OPT_FSTR ){ (*(void(*)(char *))(op[j].arg))(&argv[i][2]); }else{ if( err ){ fprintf(err,"%smissing argument on switch.\n",emsg); errline(i,1,err); } errcnt++; } return errcnt; } /* ** Process a command line switch which has an argument. */ static int handleswitch(int i, FILE *err) { int lv = 0; double dv = 0.0; char *sv = 0, *end; char *cp; int j; int errcnt = 0; cp = strchr(argv[i],'='); assert( cp!=0 ); *cp = 0; for(j=0; op[j].label; j++){ if( strcmp(argv[i],op[j].label)==0 ) break; } *cp = '='; if( op[j].label==0 ){ if( err ){ fprintf(err,"%sundefined option.\n",emsg); errline(i,0,err); } errcnt++; }else{ cp++; switch( op[j].type ){ case OPT_FLAG: case OPT_FFLAG: if( err ){ fprintf(err,"%soption requires an argument.\n",emsg); errline(i,0,err); } errcnt++; break; case OPT_DBL: case OPT_FDBL: dv = strtod(cp,&end); if( *end ){ if( err ){ fprintf(err,"%sillegal character in floating-point argument.\n",emsg); errline(i,((unsigned long)end)-(unsigned long)argv[i],err); } errcnt++; } break; case OPT_INT: case OPT_FINT: lv = strtol(cp,&end,0); if( *end ){ if( err ){ fprintf(err,"%sillegal character in integer argument.\n",emsg); errline(i,((unsigned long)end)-(unsigned long)argv[i],err); } errcnt++; } break; case OPT_STR: case OPT_FSTR: sv = cp; break; } switch( op[j].type ){ case OPT_FLAG: case OPT_FFLAG: break; case OPT_DBL: *(double*)(op[j].arg) = dv; break; case OPT_FDBL: (*(void(*)(double))(op[j].arg))(dv); break; case OPT_INT: *(int*)(op[j].arg) = lv; break; case OPT_FINT: (*(void(*)(int))(op[j].arg))((int)lv); break; case OPT_STR: *(char**)(op[j].arg) = sv; break; case OPT_FSTR: (*(void(*)(char *))(op[j].arg))(sv); break; } } return errcnt; } int OptInit(char **a, struct s_options *o, FILE *err) { int errcnt = 0; argv = a; op = o; errstream = err; if( argv && *argv && op ){ int i; for(i=1; argv[i]; i++){ if( argv[i][0]=='+' || argv[i][0]=='-' ){ errcnt += handleflags(i,err); }else if( strchr(argv[i],'=') ){ errcnt += handleswitch(i,err); } } } if( errcnt>0 ){ fprintf(err,"Valid command line options for \"%s\" are:\n",*a); OptPrint(); exit(1); } return 0; } int OptNArgs(){ int cnt = 0; int dashdash = 0; int i; if( argv!=0 && argv[0]!=0 ){ for(i=1; argv[i]; i++){ if( dashdash || !ISOPT(argv[i]) ) cnt++; if( strcmp(argv[i],"--")==0 ) dashdash = 1; } } return cnt; } char *OptArg(int n) { int i; i = argindex(n); return i>=0 ? argv[i] : 0; } void OptErr(int n) { int i; i = argindex(n); if( i>=0 ) errline(i,0,errstream); } void OptPrint(){ int i; int max, len; max = 0; for(i=0; op[i].label; i++){ len = lemonStrlen(op[i].label) + 1; switch( op[i].type ){ case OPT_FLAG: case OPT_FFLAG: break; case OPT_INT: case OPT_FINT: len += 9; /* length of "<integer>" */ break; case OPT_DBL: case OPT_FDBL: len += 6; /* length of "<real>" */ break; case OPT_STR: case OPT_FSTR: len += 8; /* length of "<string>" */ break; } if( len>max ) max = len; } for(i=0; op[i].label; i++){ switch( op[i].type ){ case OPT_FLAG: case OPT_FFLAG: fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message); break; case OPT_INT: case OPT_FINT: fprintf(errstream," %s=<integer>%*s %s\n",op[i].label, (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message); break; case OPT_DBL: case OPT_FDBL: fprintf(errstream," %s=<real>%*s %s\n",op[i].label, (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message); break; case OPT_STR: case OPT_FSTR: fprintf(errstream," %s=<string>%*s %s\n",op[i].label, (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message); break; } } } /*********************** From the file "parse.c" ****************************/ /* ** Input file parser for the LEMON parser generator. */ /* The state of the parser */ enum e_state { INITIALIZE, WAITING_FOR_DECL_OR_RULE, WAITING_FOR_DECL_KEYWORD, WAITING_FOR_DECL_ARG, WAITING_FOR_PRECEDENCE_SYMBOL, WAITING_FOR_ARROW, IN_RHS, LHS_ALIAS_1, LHS_ALIAS_2, LHS_ALIAS_3, RHS_ALIAS_1, RHS_ALIAS_2, PRECEDENCE_MARK_1, PRECEDENCE_MARK_2, RESYNC_AFTER_RULE_ERROR, RESYNC_AFTER_DECL_ERROR, WAITING_FOR_DESTRUCTOR_SYMBOL, WAITING_FOR_DATATYPE_SYMBOL, WAITING_FOR_FALLBACK_ID, WAITING_FOR_WILDCARD_ID }; struct pstate { char *filename; /* Name of the input file */ int tokenlineno; /* Linenumber at which current token starts */ int errorcnt; /* Number of errors so far */ char *tokenstart; /* Text of current token */ struct lemon *gp; /* Global state vector */ enum e_state state; /* The state of the parser */ struct symbol *fallback; /* The fallback token */ struct symbol *lhs; /* Left-hand side of current rule */ const char *lhsalias; /* Alias for the LHS */ int nrhs; /* Number of right-hand side symbols seen */ struct symbol *rhs[MAXRHS]; /* RHS symbols */ const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */ struct rule *prevrule; /* Previous rule parsed */ const char *declkeyword; /* Keyword of a declaration */ char **declargslot; /* Where the declaration argument should be put */ int insertLineMacro; /* Add #line before declaration insert */ int *decllinenoslot; /* Where to write declaration line number */ enum e_assoc declassoc; /* Assign this association to decl arguments */ int preccounter; /* Assign this precedence to decl arguments */ struct rule *firstrule; /* Pointer to first rule in the grammar */ struct rule *lastrule; /* Pointer to the most recently parsed rule */ }; /* Parse a single token */ static void parseonetoken(struct pstate *psp) { const char *x; x = Strsafe(psp->tokenstart); /* Save the token permanently */ #if 0 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno, x,psp->state); #endif switch( psp->state ){ case INITIALIZE: psp->prevrule = 0; psp->preccounter = 0; psp->firstrule = psp->lastrule = 0; psp->gp->nrule = 0; /* Fall thru to next case */ case WAITING_FOR_DECL_OR_RULE: if( x[0]=='%' ){ psp->state = WAITING_FOR_DECL_KEYWORD; }else if( islower(x[0]) ){ psp->lhs = Symbol_new(x); psp->nrhs = 0; psp->lhsalias = 0; psp->state = WAITING_FOR_ARROW; }else if( x[0]=='{' ){ if( psp->prevrule==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "There is no prior rule upon which to attach the code \ fragment which begins on this line."); psp->errorcnt++; }else if( psp->prevrule->code!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Code fragment beginning on this line is not the first \ to follow the previous rule."); psp->errorcnt++; }else{ psp->prevrule->line = psp->tokenlineno; psp->prevrule->code = &x[1]; } }else if( x[0]=='[' ){ psp->state = PRECEDENCE_MARK_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Token \"%s\" should be either \"%%\" or a nonterminal name.", x); psp->errorcnt++; } break; case PRECEDENCE_MARK_1: if( !isupper(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "The precedence symbol must be a terminal."); psp->errorcnt++; }else if( psp->prevrule==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "There is no prior rule to assign precedence \"[%s]\".",x); psp->errorcnt++; }else if( psp->prevrule->precsym!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Precedence mark on this line is not the first \ to follow the previous rule."); psp->errorcnt++; }else{ psp->prevrule->precsym = Symbol_new(x); } psp->state = PRECEDENCE_MARK_2; break; case PRECEDENCE_MARK_2: if( x[0]!=']' ){ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \"]\" on precedence mark."); psp->errorcnt++; } psp->state = WAITING_FOR_DECL_OR_RULE; break; case WAITING_FOR_ARROW: if( x[0]==':' && x[1]==':' && x[2]=='=' ){ psp->state = IN_RHS; }else if( x[0]=='(' ){ psp->state = LHS_ALIAS_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Expected to see a \":\" following the LHS symbol \"%s\".", psp->lhs->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_1: if( isalpha(x[0]) ){ psp->lhsalias = x; psp->state = LHS_ALIAS_2; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "\"%s\" is not a valid alias for the LHS \"%s\"\n", x,psp->lhs->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_2: if( x[0]==')' ){ psp->state = LHS_ALIAS_3; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_3: if( x[0]==':' && x[1]==':' && x[2]=='=' ){ psp->state = IN_RHS; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \"->\" following: \"%s(%s)\".", psp->lhs->name,psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case IN_RHS: if( x[0]=='.' ){ struct rule *rp; rp = (struct rule *)calloc( sizeof(struct rule) + sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); if( rp==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Can't allocate enough memory for this rule."); psp->errorcnt++; psp->prevrule = 0; }else{ int i; rp->ruleline = psp->tokenlineno; rp->rhs = (struct symbol**)&rp[1]; rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]); for(i=0; i<psp->nrhs; i++){ rp->rhs[i] = psp->rhs[i]; rp->rhsalias[i] = psp->alias[i]; } rp->lhs = psp->lhs; rp->lhsalias = psp->lhsalias; rp->nrhs = psp->nrhs; rp->code = 0; rp->precsym = 0; rp->index = psp->gp->nrule++; rp->nextlhs = rp->lhs->rule; rp->lhs->rule = rp; rp->next = 0; if( psp->firstrule==0 ){ psp->firstrule = psp->lastrule = rp; }else{ psp->lastrule->next = rp; psp->lastrule = rp; } psp->prevrule = rp; } psp->state = WAITING_FOR_DECL_OR_RULE; }else if( isalpha(x[0]) ){ if( psp->nrhs>=MAXRHS ){ ErrorMsg(psp->filename,psp->tokenlineno, "Too many symbols on RHS of rule beginning at \"%s\".", x); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; }else{ psp->rhs[psp->nrhs] = Symbol_new(x); psp->alias[psp->nrhs] = 0; psp->nrhs++; } }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){ struct symbol *msp = psp->rhs[psp->nrhs-1]; if( msp->type!=MULTITERMINAL ){ struct symbol *origsp = msp; msp = (struct symbol *) calloc(1,sizeof(*msp)); memset(msp, 0, sizeof(*msp)); msp->type = MULTITERMINAL; msp->nsubsym = 1; msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*)); msp->subsym[0] = origsp; msp->name = origsp->name; psp->rhs[psp->nrhs-1] = msp; } msp->nsubsym++; msp->subsym = (struct symbol **) realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym); msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "Cannot form a compound containing a non-terminal"); psp->errorcnt++; } }else if( x[0]=='(' && psp->nrhs>0 ){ psp->state = RHS_ALIAS_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal character on RHS of rule: \"%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case RHS_ALIAS_1: if( isalpha(x[0]) ){ psp->alias[psp->nrhs-1] = x; psp->state = RHS_ALIAS_2; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", x,psp->rhs[psp->nrhs-1]->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case RHS_ALIAS_2: if( x[0]==')' ){ psp->state = IN_RHS; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case WAITING_FOR_DECL_KEYWORD: if( isalpha(x[0]) ){ psp->declkeyword = x; psp->declargslot = 0; psp->decllinenoslot = 0; psp->insertLineMacro = 1; psp->state = WAITING_FOR_DECL_ARG; if( strcmp(x,"name")==0 ){ psp->declargslot = &(psp->gp->name); psp->insertLineMacro = 0; }else if( strcmp(x,"include")==0 ){ psp->declargslot = &(psp->gp->include); }else if( strcmp(x,"code")==0 ){ psp->declargslot = &(psp->gp->extracode); }else if( strcmp(x,"token_destructor")==0 ){ psp->declargslot = &psp->gp->tokendest; }else if( strcmp(x,"default_destructor")==0 ){ psp->declargslot = &psp->gp->vardest; }else if( strcmp(x,"token_prefix")==0 ){ psp->declargslot = &psp->gp->tokenprefix; psp->insertLineMacro = 0; }else if( strcmp(x,"syntax_error")==0 ){ psp->declargslot = &(psp->gp->error); }else if( strcmp(x,"parse_accept")==0 ){ psp->declargslot = &(psp->gp->accept); }else if( strcmp(x,"parse_failure")==0 ){ psp->declargslot = &(psp->gp->failure); }else if( strcmp(x,"stack_overflow")==0 ){ psp->declargslot = &(psp->gp->overflow); }else if( strcmp(x,"extra_argument")==0 ){ psp->declargslot = &(psp->gp->arg); psp->insertLineMacro = 0; }else if( strcmp(x,"token_type")==0 ){ psp->declargslot = &(psp->gp->tokentype); psp->insertLineMacro = 0; }else if( strcmp(x,"default_type")==0 ){ psp->declargslot = &(psp->gp->vartype); psp->insertLineMacro = 0; }else if( strcmp(x,"stack_size")==0 ){ psp->declargslot = &(psp->gp->stacksize); psp->insertLineMacro = 0; }else if( strcmp(x,"start_symbol")==0 ){ psp->declargslot = &(psp->gp->start); psp->insertLineMacro = 0; }else if( strcmp(x,"left")==0 ){ psp->preccounter++; psp->declassoc = LEFT; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"right")==0 ){ psp->preccounter++; psp->declassoc = RIGHT; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"nonassoc")==0 ){ psp->preccounter++; psp->declassoc = NONE; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"destructor")==0 ){ psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; }else if( strcmp(x,"type")==0 ){ psp->state = WAITING_FOR_DATATYPE_SYMBOL; }else if( strcmp(x,"fallback")==0 ){ psp->fallback = 0; psp->state = WAITING_FOR_FALLBACK_ID; }else if( strcmp(x,"wildcard")==0 ){ psp->state = WAITING_FOR_WILDCARD_ID; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Unknown declaration keyword: \"%%%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal declaration keyword: \"%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } break; case WAITING_FOR_DESTRUCTOR_SYMBOL: if( !isalpha(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol name missing after %%destructor keyword"); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ struct symbol *sp = Symbol_new(x); psp->declargslot = &sp->destructor; psp->decllinenoslot = &sp->destLineno; psp->insertLineMacro = 1; psp->state = WAITING_FOR_DECL_ARG; } break; case WAITING_FOR_DATATYPE_SYMBOL: if( !isalpha(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol name missing after %%type keyword"); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ struct symbol *sp = Symbol_find(x); if((sp) && (sp->datatype)){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol %%type \"%s\" already defined", x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ if (!sp){ sp = Symbol_new(x); } psp->declargslot = &sp->datatype; psp->insertLineMacro = 0; psp->state = WAITING_FOR_DECL_ARG; } } break; case WAITING_FOR_PRECEDENCE_SYMBOL: if( x[0]=='.' ){ psp->state = WAITING_FOR_DECL_OR_RULE; }else if( isupper(x[0]) ){ struct symbol *sp; sp = Symbol_new(x); if( sp->prec>=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol \"%s\" has already be given a precedence.",x); psp->errorcnt++; }else{ sp->prec = psp->preccounter; sp->assoc = psp->declassoc; } }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Can't assign a precedence to \"%s\".",x); psp->errorcnt++; } break; case WAITING_FOR_DECL_ARG: if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){ const char *zOld, *zNew; char *zBuf, *z; int nOld, n, nLine, nNew, nBack; int addLineMacro; char zLine[50]; zNew = x; if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; nNew = lemonStrlen(zNew); if( *psp->declargslot ){ zOld = *psp->declargslot; }else{ zOld = ""; } nOld = lemonStrlen(zOld); n = nOld + nNew + 20; addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); if( addLineMacro ){ for(z=psp->filename, nBack=0; *z; z++){ if( *z=='\\' ) nBack++; } sprintf(zLine, "#line %d ", psp->tokenlineno); nLine = lemonStrlen(zLine); n += nLine + lemonStrlen(psp->filename) + nBack; } *psp->declargslot = (char *) realloc(*psp->declargslot, n); zBuf = *psp->declargslot + nOld; if( addLineMacro ){ if( nOld && zBuf[-1]!='\n' ){ *(zBuf++) = '\n'; } memcpy(zBuf, zLine, nLine); zBuf += nLine; *(zBuf++) = '"'; for(z=psp->filename; *z; z++){ if( *z=='\\' ){ *(zBuf++) = '\\'; } *(zBuf++) = *z; } *(zBuf++) = '"'; *(zBuf++) = '\n'; } if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ psp->decllinenoslot[0] = psp->tokenlineno; } memcpy(zBuf, zNew, nNew); zBuf += nNew; *zBuf = 0; psp->state = WAITING_FOR_DECL_OR_RULE; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal argument to %%%s: %s",psp->declkeyword,x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } break; case WAITING_FOR_FALLBACK_ID: if( x[0]=='.' ){ psp->state = WAITING_FOR_DECL_OR_RULE; }else if( !isupper(x[0]) ){ ErrorMsg(psp->filename, psp->tokenlineno, "%%fallback argument \"%s\" should be a token", x); psp->errorcnt++; }else{ struct symbol *sp = Symbol_new(x); if( psp->fallback==0 ){ psp->fallback = sp; }else if( sp->fallback ){ ErrorMsg(psp->filename, psp->tokenlineno, "More than one fallback assigned to token %s", x); psp->errorcnt++; }else{ sp->fallback = psp->fallback; psp->gp->has_fallback = 1; } } break; case WAITING_FOR_WILDCARD_ID: if( x[0]=='.' ){ psp->state = WAITING_FOR_DECL_OR_RULE; }else if( !isupper(x[0]) ){ ErrorMsg(psp->filename, psp->tokenlineno, "%%wildcard argument \"%s\" should be a token", x); psp->errorcnt++; }else{ struct symbol *sp = Symbol_new(x); if( psp->gp->wildcard==0 ){ psp->gp->wildcard = sp; }else{ ErrorMsg(psp->filename, psp->tokenlineno, "Extra wildcard to token: %s", x); psp->errorcnt++; } } break; case RESYNC_AFTER_RULE_ERROR: /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; ** break; */ case RESYNC_AFTER_DECL_ERROR: if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; break; } } /* Run the preprocessor over the input file text. The global variables ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and ** comments them out. Text in between is also commented out as appropriate. */ static void preprocess_input(char *z){ int i, j, k, n; int exclude = 0; int start = 0; int lineno = 1; int start_lineno = 1; for(i=0; z[i]; i++){ if( z[i]=='\n' ) lineno++; if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){ if( exclude ){ exclude--; if( exclude==0 ){ for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' '; } } for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' '; }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6])) || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){ if( exclude ){ exclude++; }else{ for(j=i+7; isspace(z[j]); j++){} for(n=0; z[j+n] && !isspace(z[j+n]); n++){} exclude = 1; for(k=0; k<nDefine; k++){ if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){ exclude = 0; break; } } if( z[i+3]=='n' ) exclude = !exclude; if( exclude ){ start = i; start_lineno = lineno; } } for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' '; } } if( exclude ){ fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno); exit(1); } } /* In spite of its name, this function is really a scanner. It read ** in the entire input file (all at once) then tokenizes it. Each ** token is passed to the function "parseonetoken" which builds all ** the appropriate data structures in the global state vector "gp". */ void Parse(struct lemon *gp) { struct pstate ps; FILE *fp; char *filebuf; int filesize; int lineno; int c; char *cp, *nextcp; int startline = 0; memset(&ps, '\0', sizeof(ps)); ps.gp = gp; ps.filename = gp->filename; ps.errorcnt = 0; ps.state = INITIALIZE; /* Begin by reading the input file */ fp = fopen(ps.filename,"rb"); if( fp==0 ){ ErrorMsg(ps.filename,0,"Can't open this file for reading."); gp->errorcnt++; return; } fseek(fp,0,2); filesize = ftell(fp); rewind(fp); filebuf = (char *)malloc( filesize+1 ); if( filebuf==0 ){ ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.", filesize+1); gp->errorcnt++; fclose(fp); return; } if( fread(filebuf,1,filesize,fp)!=filesize ){ ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", filesize); free(filebuf); gp->errorcnt++; fclose(fp); return; } fclose(fp); filebuf[filesize] = 0; /* Make an initial pass through the file to handle %ifdef and %ifndef */ preprocess_input(filebuf); /* Now scan the text of the input file */ lineno = 1; for(cp=filebuf; (c= *cp)!=0; ){ if( c=='\n' ) lineno++; /* Keep track of the line number */ if( isspace(c) ){ cp++; continue; } /* Skip all white space */ if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ cp+=2; while( (c= *cp)!=0 && c!='\n' ) cp++; continue; } if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ cp+=2; while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ if( c=='\n' ) lineno++; cp++; } if( c ) cp++; continue; } ps.tokenstart = cp; /* Mark the beginning of the token */ ps.tokenlineno = lineno; /* Linenumber on which token begins */ if( c=='\"' ){ /* String literals */ cp++; while( (c= *cp)!=0 && c!='\"' ){ if( c=='\n' ) lineno++; cp++; } if( c==0 ){ ErrorMsg(ps.filename,startline, "String starting on this line is not terminated before the end of the file."); ps.errorcnt++; nextcp = cp; }else{ nextcp = cp+1; } }else if( c=='{' ){ /* A block of C code */ int level; cp++; for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ if( c=='\n' ) lineno++; else if( c=='{' ) level++; else if( c=='}' ) level--; else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ int prevc; cp = &cp[2]; prevc = 0; while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ if( c=='\n' ) lineno++; prevc = c; cp++; } }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ cp = &cp[2]; while( (c= *cp)!=0 && c!='\n' ) cp++; if( c ) lineno++; }else if( c=='\'' || c=='\"' ){ /* String a character literals */ int startchar, prevc; startchar = c; prevc = 0; for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ if( c=='\n' ) lineno++; if( prevc=='\\' ) prevc = 0; else prevc = c; } } } if( c==0 ){ ErrorMsg(ps.filename,ps.tokenlineno, "C code starting on this line is not terminated before the end of the file."); ps.errorcnt++; nextcp = cp; }else{ nextcp = cp+1; } }else if( isalnum(c) ){ /* Identifiers */ while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++; nextcp = cp; }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ cp += 3; nextcp = cp; }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){ cp += 2; while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++; nextcp = cp; }else{ /* All other (one character) operators */ cp++; nextcp = cp; } c = *cp; *cp = 0; /* Null terminate the token */ parseonetoken(&ps); /* Parse the token */ *cp = c; /* Restore the buffer */ cp = nextcp; } free(filebuf); /* Release the buffer after parsing */ gp->rule = ps.firstrule; gp->errorcnt = ps.errorcnt; } /*************************** From the file "plink.c" *********************/ /* ** Routines processing configuration follow-set propagation links ** in the LEMON parser generator. */ static struct plink *plink_freelist = 0; /* Allocate a new plink */ struct plink *Plink_new(){ struct plink *newlink; if( plink_freelist==0 ){ int i; int amt = 100; plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) ); if( plink_freelist==0 ){ fprintf(stderr, "Unable to allocate memory for a new follow-set propagation link.\n"); exit(1); } for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1]; plink_freelist[amt-1].next = 0; } newlink = plink_freelist; plink_freelist = plink_freelist->next; return newlink; } /* Add a plink to a plink list */ void Plink_add(struct plink **plpp, struct config *cfp) { struct plink *newlink; newlink = Plink_new(); newlink->next = *plpp; *plpp = newlink; newlink->cfp = cfp; } /* Transfer every plink on the list "from" to the list "to" */ void Plink_copy(struct plink **to, struct plink *from) { struct plink *nextpl; while( from ){ nextpl = from->next; from->next = *to; *to = from; from = nextpl; } } /* Delete every plink on the list */ void Plink_delete(struct plink *plp) { struct plink *nextpl; while( plp ){ nextpl = plp->next; plp->next = plink_freelist; plink_freelist = plp; plp = nextpl; } } /*********************** From the file "report.c" **************************/ /* ** Procedures for generating reports and tables in the LEMON parser generator. */ /* Generate a filename with the given suffix. Space to hold the ** name comes from malloc() and must be freed by the calling ** function. */ PRIVATE char *file_makename(const char *filename, const char *suffix) { char *name; char *cp; name = (char*)malloc( lemonStrlen(filename) + lemonStrlen(suffix) + 5 ); if( name==0 ){ fprintf(stderr,"Can't allocate space for a filename.\n"); exit(1); } strcpy(name,filename); cp = strrchr(name,'.'); if( cp ) *cp = 0; strcat(name,suffix); return name; } /* Open a file with a name based on the name of the input file, ** but with a different (specified) suffix, and return a pointer ** to the stream */ PRIVATE FILE *file_open( struct lemon *lemp, const char *suffix, const char *mode ){ FILE *fp; if( lemp->outname ) free(lemp->outname); lemp->outname = file_makename(lemp->filename, suffix); fp = fopen(lemp->outname,mode); if( fp==0 && *mode=='w' ){ fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); lemp->errorcnt++; return 0; } return fp; } /* Duplicate the input file without comments and without actions ** on rules */ void Reprint(struct lemon *lemp) { struct rule *rp; struct symbol *sp; int i, j, maxlen, len, ncolumns, skip; printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); maxlen = 10; for(i=0; i<lemp->nsymbol; i++){ sp = lemp->symbols[i]; len = lemonStrlen(sp->name); if( len>maxlen ) maxlen = len; } ncolumns = 76/(maxlen+5); if( ncolumns<1 ) ncolumns = 1; skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; for(i=0; i<skip; i++){ printf("//"); for(j=i; j<lemp->nsymbol; j+=skip){ sp = lemp->symbols[j]; assert( sp->index==j ); printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); } printf("\n"); } for(rp=lemp->rule; rp; rp=rp->next){ printf("%s",rp->lhs->name); /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ printf(" ::="); for(i=0; i<rp->nrhs; i++){ sp = rp->rhs[i]; printf(" %s", sp->name); if( sp->type==MULTITERMINAL ){ for(j=1; j<sp->nsubsym; j++){ printf("|%s", sp->subsym[j]->name); } } /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ } printf("."); if( rp->precsym ) printf(" [%s]",rp->precsym->name); /* if( rp->code ) printf("\n %s",rp->code); */ printf("\n"); } } void ConfigPrint(FILE *fp, struct config *cfp) { struct rule *rp; struct symbol *sp; int i, j; rp = cfp->rp; fprintf(fp,"%s ::=",rp->lhs->name); for(i=0; i<=rp->nrhs; i++){ if( i==cfp->dot ) fprintf(fp," *"); if( i==rp->nrhs ) break; sp = rp->rhs[i]; fprintf(fp," %s", sp->name); if( sp->type==MULTITERMINAL ){ for(j=1; j<sp->nsubsym; j++){ fprintf(fp,"|%s",sp->subsym[j]->name); } } } } /* #define TEST */ #if 0 /* Print a set */ PRIVATE void SetPrint(out,set,lemp) FILE *out; char *set; struct lemon *lemp; { int i; char *spacer; spacer = ""; fprintf(out,"%12s[",""); for(i=0; i<lemp->nterminal; i++){ if( SetFind(set,i) ){ fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); spacer = " "; } } fprintf(out,"]\n"); } /* Print a plink chain */ PRIVATE void PlinkPrint(out,plp,tag) FILE *out; struct plink *plp; char *tag; { while( plp ){ fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum); ConfigPrint(out,plp->cfp); fprintf(out,"\n"); plp = plp->next; } } #endif /* Print an action to the given file descriptor. Return FALSE if ** nothing was actually printed. */ int PrintAction(struct action *ap, FILE *fp, int indent){ int result = 1; switch( ap->type ){ case SHIFT: fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum); break; case REDUCE: fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); break; case ACCEPT: fprintf(fp,"%*s accept",indent,ap->sp->name); break; case ERROR: fprintf(fp,"%*s error",indent,ap->sp->name); break; case SRCONFLICT: case RRCONFLICT: fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", indent,ap->sp->name,ap->x.rp->index); break; case SSCONFLICT: fprintf(fp,"%*s shift %-3d ** Parsing conflict **", indent,ap->sp->name,ap->x.stp->statenum); break; case SH_RESOLVED: if( showPrecedenceConflict ){ fprintf(fp,"%*s shift %-3d -- dropped by precedence", indent,ap->sp->name,ap->x.stp->statenum); }else{ result = 0; } break; case RD_RESOLVED: if( showPrecedenceConflict ){ fprintf(fp,"%*s reduce %-3d -- dropped by precedence", indent,ap->sp->name,ap->x.rp->index); }else{ result = 0; } break; case NOT_USED: result = 0; break; } return result; } /* Generate the "y.output" log file */ void ReportOutput(struct lemon *lemp) { int i; struct state *stp; struct config *cfp; struct action *ap; FILE *fp; fp = file_open(lemp,".out","wb"); if( fp==0 ) return; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; fprintf(fp,"State %d:\n",stp->statenum); if( lemp->basisflag ) cfp=stp->bp; else cfp=stp->cfp; while( cfp ){ char buf[20]; if( cfp->dot==cfp->rp->nrhs ){ sprintf(buf,"(%d)",cfp->rp->index); fprintf(fp," %5s ",buf); }else{ fprintf(fp," "); } ConfigPrint(fp,cfp); fprintf(fp,"\n"); #if 0 SetPrint(fp,cfp->fws,lemp); PlinkPrint(fp,cfp->fplp,"To "); PlinkPrint(fp,cfp->bplp,"From"); #endif if( lemp->basisflag ) cfp=cfp->bp; else cfp=cfp->next; } fprintf(fp,"\n"); for(ap=stp->ap; ap; ap=ap->next){ if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); } fprintf(fp,"\n"); } fprintf(fp, "----------------------------------------------------\n"); fprintf(fp, "Symbols:\n"); for(i=0; i<lemp->nsymbol; i++){ int j; struct symbol *sp; sp = lemp->symbols[i]; fprintf(fp, " %3d: %s", i, sp->name); if( sp->type==NONTERMINAL ){ fprintf(fp, ":"); if( sp->lambda ){ fprintf(fp, " <lambda>"); } for(j=0; j<lemp->nterminal; j++){ if( sp->firstset && SetFind(sp->firstset, j) ){ fprintf(fp, " %s", lemp->symbols[j]->name); } } } fprintf(fp, "\n"); } fclose(fp); return; } /* Search for the file "name" which is in the same directory as ** the exacutable */ PRIVATE char *pathsearch(char *argv0, char *name, int modemask) { const char *pathlist; char *pathbufptr; char *pathbuf; char *path,*cp; char c; #ifdef __WIN32__ cp = strrchr(argv0,'\\'); #else cp = strrchr(argv0,'/'); #endif if( cp ){ c = *cp; *cp = 0; path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); if( path ) sprintf(path,"%s/%s",argv0,name); *cp = c; }else{ pathlist = getenv("PATH"); if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 ); path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); if( (pathbuf != 0) && (path!=0) ){ pathbufptr = pathbuf; strcpy(pathbuf, pathlist); while( *pathbuf ){ cp = strchr(pathbuf,':'); if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; c = *cp; *cp = 0; sprintf(path,"%s/%s",pathbuf,name); *cp = c; if( c==0 ) pathbuf[0] = 0; else pathbuf = &cp[1]; if( access(path,modemask)==0 ) break; } free(pathbufptr); } } return path; } /* Given an action, compute the integer value for that action ** which is to be put in the action table of the generated machine. ** Return negative if no action should be generated. */ PRIVATE int compute_action(struct lemon *lemp, struct action *ap) { int act; switch( ap->type ){ case SHIFT: act = ap->x.stp->statenum; break; case REDUCE: act = ap->x.rp->index + lemp->nstate; break; case ERROR: act = lemp->nstate + lemp->nrule; break; case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break; default: act = -1; break; } return act; } #define LINESIZE 1000 /* The next cluster of routines are for reading the template file ** and writing the results to the generated parser */ /* The first function transfers data from "in" to "out" until ** a line is seen which begins with "%%". The line number is ** tracked. ** ** if name!=0, then any word that begin with "Parse" is changed to ** begin with *name instead. */ PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno) { int i, iStart; char line[LINESIZE]; while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ (*lineno)++; iStart = 0; if( name ){ for(i=0; line[i]; i++){ if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 && (i==0 || !isalpha(line[i-1])) ){ if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); fprintf(out,"%s",name); i += 4; iStart = i+1; } } } fprintf(out,"%s",&line[iStart]); } } /* The next function finds the template file and opens it, returning ** a pointer to the opened file. */ PRIVATE FILE *tplt_open(struct lemon *lemp) { static char templatename[] = "lempar.c"; char buf[1000]; FILE *in; char *tpltname; char *cp; /* first, see if user specified a template filename on the command line. */ if (user_templatename != 0) { if( access(user_templatename,004)==-1 ){ fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", user_templatename); lemp->errorcnt++; return 0; } in = fopen(user_templatename,"rb"); if( in==0 ){ fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename); lemp->errorcnt++; return 0; } return in; } cp = strrchr(lemp->filename,'.'); if( cp ){ sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); }else{ sprintf(buf,"%s.lt",lemp->filename); } if( access(buf,004)==0 ){ tpltname = buf; }else if( access(templatename,004)==0 ){ tpltname = templatename; }else{ tpltname = pathsearch(lemp->argv0,templatename,0); } if( tpltname==0 ){ fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", templatename); lemp->errorcnt++; return 0; } in = fopen(tpltname,"rb"); if( in==0 ){ fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); lemp->errorcnt++; return 0; } return in; } /* Print a #line directive line to the output file. */ PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) { fprintf(out,"#line %d \"",lineno); while( *filename ){ if( *filename == '\\' ) putc('\\',out); putc(*filename,out); filename++; } fprintf(out,"\"\n"); } /* Print a string to the file and keep the linenumber up to date */ PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) { if( str==0 ) return; while( *str ){ putc(*str,out); if( *str=='\n' ) (*lineno)++; str++; } if( str[-1]!='\n' ){ putc('\n',out); (*lineno)++; } if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } return; } /* ** The following routine emits code for the destructor for the ** symbol sp */ void emit_destructor_code( FILE *out, struct symbol *sp, struct lemon *lemp, int *lineno ){ char *cp = 0; if( sp->type==TERMINAL ){ cp = lemp->tokendest; if( cp==0 ) return; fprintf(out,"{\n"); (*lineno)++; }else if( sp->destructor ){ cp = sp->destructor; fprintf(out,"{\n"); (*lineno)++; if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); } }else if( lemp->vardest ){ cp = lemp->vardest; if( cp==0 ) return; fprintf(out,"{\n"); (*lineno)++; }else{ assert( 0 ); /* Cannot happen */ } for(; *cp; cp++){ if( *cp=='$' && cp[1]=='$' ){ fprintf(out,"(yypminor->yy%d)",sp->dtnum); cp++; continue; } if( *cp=='\n' ) (*lineno)++; fputc(*cp,out); } fprintf(out,"\n"); (*lineno)++; if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } fprintf(out,"}\n"); (*lineno)++; return; } /* ** Return TRUE (non-zero) if the given symbol has a destructor. */ int has_destructor(struct symbol *sp, struct lemon *lemp) { int ret; if( sp->type==TERMINAL ){ ret = lemp->tokendest!=0; }else{ ret = lemp->vardest!=0 || sp->destructor!=0; } return ret; } /* ** Append text to a dynamically allocated string. If zText is 0 then ** reset the string to be empty again. Always return the complete text ** of the string (which is overwritten with each call). ** ** n bytes of zText are stored. If n==0 then all of zText up to the first ** \000 terminator is stored. zText can contain up to two instances of ** %d. The values of p1 and p2 are written into the first and second ** %d. ** ** If n==-1, then the previous character is overwritten. */ PRIVATE char *append_str(const char *zText, int n, int p1, int p2){ static char empty[1] = { 0 }; static char *z = 0; static int alloced = 0; static int used = 0; int c; char zInt[40]; if( zText==0 ){ used = 0; return z; } if( n<=0 ){ if( n<0 ){ used += n; assert( used>=0 ); } n = lemonStrlen(zText); } if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ alloced = n + sizeof(zInt)*2 + used + 200; z = (char *) realloc(z, alloced); } if( z==0 ) return empty; while( n-- > 0 ){ c = *(zText++); if( c=='%' && n>0 && zText[0]=='d' ){ sprintf(zInt, "%d", p1); p1 = p2; strcpy(&z[used], zInt); used += lemonStrlen(&z[used]); zText++; n--; }else{ z[used++] = c; } } z[used] = 0; return z; } /* ** zCode is a string that is the action associated with a rule. Expand ** the symbols in this string so that the refer to elements of the parser ** stack. */ PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){ char *cp, *xp; int i; char lhsused = 0; /* True if the LHS element has been used */ char used[MAXRHS]; /* True for each RHS element which is used */ for(i=0; i<rp->nrhs; i++) used[i] = 0; lhsused = 0; if( rp->code==0 ){ static char newlinestr[2] = { '\n', '\0' }; rp->code = newlinestr; rp->line = rp->ruleline; } append_str(0,0,0,0); /* This const cast is wrong but harmless, if we're careful. */ for(cp=(char *)rp->code; *cp; cp++){ if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){ char saved; for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++); saved = *xp; *xp = 0; if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0); cp = xp; lhsused = 1; }else{ for(i=0; i<rp->nrhs; i++){ if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ if( cp!=rp->code && cp[-1]=='@' ){ /* If the argument is of the form @X then substituted ** the token number of X, not the value of X */ append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); }else{ struct symbol *sp = rp->rhs[i]; int dtnum; if( sp->type==MULTITERMINAL ){ dtnum = sp->subsym[0]->dtnum; }else{ dtnum = sp->dtnum; } append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum); } cp = xp; used[i] = 1; break; } } } *xp = saved; } append_str(cp, 1, 0, 0); } /* End loop */ /* Check to make sure the LHS has been used */ if( rp->lhsalias && !lhsused ){ ErrorMsg(lemp->filename,rp->ruleline, "Label \"%s\" for \"%s(%s)\" is never used.", rp->lhsalias,rp->lhs->name,rp->lhsalias); lemp->errorcnt++; } /* Generate destructor code for RHS symbols which are not used in the ** reduce code */ for(i=0; i<rp->nrhs; i++){ if( rp->rhsalias[i] && !used[i] ){ ErrorMsg(lemp->filename,rp->ruleline, "Label %s for \"%s(%s)\" is never used.", rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); lemp->errorcnt++; }else if( rp->rhsalias[i]==0 ){ if( has_destructor(rp->rhs[i],lemp) ){ append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, rp->rhs[i]->index,i-rp->nrhs+1); }else{ /* No destructor defined for this term */ } } } if( rp->code ){ cp = append_str(0,0,0,0); rp->code = Strsafe(cp?cp:""); } } /* ** Generate code which executes when the rule "rp" is reduced. Write ** the code to "out". Make sure lineno stays up-to-date. */ PRIVATE void emit_code( FILE *out, struct rule *rp, struct lemon *lemp, int *lineno ){ const char *cp; /* Generate code to do the reduce action */ if( rp->code ){ if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); } fprintf(out,"{%s",rp->code); for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; } /* End loop */ fprintf(out,"}\n"); (*lineno)++; if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } } /* End if( rp->code ) */ return; } /* ** Print the definition of the union used for the parser's data stack. ** This union contains fields for every possible data type for tokens ** and nonterminals. In the process of computing and printing this ** union, also set the ".dtnum" field of every terminal and nonterminal ** symbol. */ void print_stack_union( FILE *out, /* The output stream */ struct lemon *lemp, /* The main info structure for this parser */ int *plineno, /* Pointer to the line number */ int mhflag /* True if generating makeheaders output */ ){ int lineno = *plineno; /* The line number of the output */ char **types; /* A hash table of datatypes */ int arraysize; /* Size of the "types" array */ int maxdtlength; /* Maximum length of any ".datatype" field. */ char *stddt; /* Standardized name for a datatype */ int i,j; /* Loop counters */ int hash; /* For hashing the name of a type */ const char *name; /* Name of the parser */ /* Allocate and initialize types[] and allocate stddt[] */ arraysize = lemp->nsymbol * 2; types = (char**)calloc( arraysize, sizeof(char*) ); if( types==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } for(i=0; i<arraysize; i++) types[i] = 0; maxdtlength = 0; if( lemp->vartype ){ maxdtlength = lemonStrlen(lemp->vartype); } for(i=0; i<lemp->nsymbol; i++){ int len; struct symbol *sp = lemp->symbols[i]; if( sp->datatype==0 ) continue; len = lemonStrlen(sp->datatype); if( len>maxdtlength ) maxdtlength = len; } stddt = (char*)malloc( maxdtlength*2 + 1 ); if( stddt==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } /* Build a hash table of datatypes. The ".dtnum" field of each symbol ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is ** used for terminal symbols. If there is no %default_type defined then ** 0 is also used as the .dtnum value for nonterminals which do not specify ** a datatype using the %type directive. */ for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; char *cp; if( sp==lemp->errsym ){ sp->dtnum = arraysize+1; continue; } if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ sp->dtnum = 0; continue; } cp = sp->datatype; if( cp==0 ) cp = lemp->vartype; j = 0; while( isspace(*cp) ) cp++; while( *cp ) stddt[j++] = *cp++; while( j>0 && isspace(stddt[j-1]) ) j--; stddt[j] = 0; if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ sp->dtnum = 0; continue; } hash = 0; for(j=0; stddt[j]; j++){ hash = hash*53 + stddt[j]; } hash = (hash & 0x7fffffff)%arraysize; while( types[hash] ){ if( strcmp(types[hash],stddt)==0 ){ sp->dtnum = hash + 1; break; } hash++; if( hash>=arraysize ) hash = 0; } if( types[hash]==0 ){ sp->dtnum = hash + 1; types[hash] = (char*)malloc( lemonStrlen(stddt)+1 ); if( types[hash]==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } strcpy(types[hash],stddt); } } /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ name = lemp->name ? lemp->name : "Parse"; lineno = *plineno; if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } fprintf(out,"#define %sTOKENTYPE %s\n",name, lemp->tokentype?lemp->tokentype:"void*"); lineno++; if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } fprintf(out,"typedef union {\n"); lineno++; fprintf(out," int yyinit;\n"); lineno++; fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; for(i=0; i<arraysize; i++){ if( types[i]==0 ) continue; fprintf(out," %s yy%d;\n",types[i],i+1); lineno++; free(types[i]); } if( lemp->errsym->useCnt ){ fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++; } free(stddt); free(types); fprintf(out,"} YYMINORTYPE;\n"); lineno++; *plineno = lineno; } /* ** Return the name of a C datatype able to represent values between ** lwr and upr, inclusive. */ static const char *minimum_size_type(int lwr, int upr){ if( lwr>=0 ){ if( upr<=255 ){ return "unsigned char"; }else if( upr<65535 ){ return "unsigned short int"; }else{ return "unsigned int"; } }else if( lwr>=-127 && upr<=127 ){ return "signed char"; }else if( lwr>=-32767 && upr<32767 ){ return "short"; }else{ return "int"; } } /* ** Each state contains a set of token transaction and a set of ** nonterminal transactions. Each of these sets makes an instance ** of the following structure. An array of these structures is used ** to order the creation of entries in the yy_action[] table. */ struct axset { struct state *stp; /* A pointer to a state */ int isTkn; /* True to use tokens. False for non-terminals */ int nAction; /* Number of actions */ int iOrder; /* Original order of action sets */ }; /* ** Compare to axset structures for sorting purposes */ static int axset_compare(const void *a, const void *b){ struct axset *p1 = (struct axset*)a; struct axset *p2 = (struct axset*)b; int c; c = p2->nAction - p1->nAction; if( c==0 ){ c = p2->iOrder - p1->iOrder; } assert( c!=0 || p1==p2 ); return c; } /* ** Write text on "out" that describes the rule "rp". */ static void writeRuleText(FILE *out, struct rule *rp){ int j; fprintf(out,"%s ::=", rp->lhs->name); for(j=0; j<rp->nrhs; j++){ struct symbol *sp = rp->rhs[j]; fprintf(out," %s", sp->name); if( sp->type==MULTITERMINAL ){ int k; for(k=1; k<sp->nsubsym; k++){ fprintf(out,"|%s",sp->subsym[k]->name); } } } } /* Generate C source code for the parser */ void ReportTable( struct lemon *lemp, int mhflag /* Output in makeheaders format if true */ ){ FILE *out, *in; char line[LINESIZE]; int lineno; struct state *stp; struct action *ap; struct rule *rp; struct acttab *pActtab; int i, j, n; const char *name; int mnTknOfst, mxTknOfst; int mnNtOfst, mxNtOfst; struct axset *ax; in = tplt_open(lemp); if( in==0 ) return; if ( user_outputname ){ // XXX - This should be moved to file_open out = fopen(user_outputname, "wb"); if ( lemp->outname ) free(lemp->outname); lemp->outname = strdup(user_outputname); } else { out = file_open(lemp,".c","wb"); } if( out==0 ){ fclose(in); return; } lineno = 1; tplt_xfer(lemp->name,in,out,&lineno); /* Generate the include code, if any */ tplt_print(out,lemp,lemp->include,&lineno); if( mhflag ){ char *name = file_makename(lemp->outname, ".h"); fprintf(out,"#include \"%s\"\n", name); lineno++; free(name); } tplt_xfer(lemp->name,in,out,&lineno); /* Generate #includes for the header file */ if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; fprintf(out,"#include <stdio.h>\n"); lineno++; fprintf(out,"#endif\n"); lineno++; } /* Generate #defines for all tokens */ if( mhflag ){ const char *prefix; fprintf(out,"#if INTERFACE\n"); lineno++; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; for(i=1; i<lemp->nterminal; i++){ fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); lineno++; } fprintf(out,"#endif\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate the defines */ fprintf(out,"#define YYCODETYPE %s\n", minimum_size_type(0, lemp->nsymbol+1)); lineno++; fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; fprintf(out,"#define YYACTIONTYPE %s\n", minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; if( lemp->wildcard ){ fprintf(out,"#define YYWILDCARD %d\n", lemp->wildcard->index); lineno++; } print_stack_union(out,lemp,&lineno,mhflag); fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; if( lemp->stacksize ){ fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; }else{ fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; } fprintf(out, "#endif\n"); lineno++; if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } name = lemp->name ? lemp->name : "Parse"; if( lemp->arg && lemp->arg[0] ){ int i; i = lemonStrlen(lemp->arg); while( i>=1 && isspace(lemp->arg[i-1]) ) i--; while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n", name,lemp->arg,&lemp->arg[i]); lineno++; fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n", name,&lemp->arg[i],&lemp->arg[i]); lineno++; }else{ fprintf(out,"#define %sARG_SDECL\n",name); lineno++; fprintf(out,"#define %sARG_PDECL\n",name); lineno++; fprintf(out,"#define %sARG_FETCH\n",name); lineno++; fprintf(out,"#define %sARG_STORE\n",name); lineno++; } if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; if( lemp->errsym->useCnt ){ fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; } if( lemp->has_fallback ){ fprintf(out,"#define YYFALLBACK 1\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate the action table and its associates: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ /* Compute the actions on all states and count them up */ ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0])); if( ax==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; ax[i*2].stp = stp; ax[i*2].isTkn = 1; ax[i*2].nAction = stp->nTknAct; ax[i*2+1].stp = stp; ax[i*2+1].isTkn = 0; ax[i*2+1].nAction = stp->nNtAct; } mxTknOfst = mnTknOfst = 0; mxNtOfst = mnNtOfst = 0; /* Compute the action table. In order to try to keep the size of the ** action table to a minimum, the heuristic of placing the largest action ** sets first is used. */ for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i; qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); pActtab = acttab_alloc(); for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){ stp = ax[i].stp; if( ax[i].isTkn ){ for(ap=stp->ap; ap; ap=ap->next){ int action; if( ap->sp->index>=lemp->nterminal ) continue; action = compute_action(lemp, ap); if( action<0 ) continue; acttab_action(pActtab, ap->sp->index, action); } stp->iTknOfst = acttab_insert(pActtab); if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst; if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; }else{ for(ap=stp->ap; ap; ap=ap->next){ int action; if( ap->sp->index<lemp->nterminal ) continue; if( ap->sp->index==lemp->nsymbol ) continue; action = compute_action(lemp, ap); if( action<0 ) continue; acttab_action(pActtab, ap->sp->index, action); } stp->iNtOfst = acttab_insert(pActtab); if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst; if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; } } free(ax); /* Output the yy_action table */ n = acttab_size(pActtab); fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; for(i=j=0; i<n; i++){ int action = acttab_yyaction(pActtab, i); if( action<0 ) action = lemp->nstate + lemp->nrule + 2; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", action); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_lookahead table */ fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++; for(i=j=0; i<n; i++){ int la = acttab_yylookahead(pActtab, i); if( la<0 ) la = lemp->nsymbol; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", la); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_shift_ofst[] table */ fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; n = lemp->nstate; while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; fprintf(out, "static const %s yy_shift_ofst[] = {\n", minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; for(i=j=0; i<n; i++){ int ofst; stp = lemp->sorted[i]; ofst = stp->iTknOfst; if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", ofst); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_reduce_ofst[] table */ fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; n = lemp->nstate; while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; fprintf(out, "static const %s yy_reduce_ofst[] = {\n", minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; for(i=j=0; i<n; i++){ int ofst; stp = lemp->sorted[i]; ofst = stp->iNtOfst; if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", ofst); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the default action table */ fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++; n = lemp->nstate; for(i=j=0; i<n; i++){ stp = lemp->sorted[i]; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", stp->iDflt); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; tplt_xfer(lemp->name,in,out,&lineno); /* Generate the table of fallback tokens. */ if( lemp->has_fallback ){ int mx = lemp->nterminal - 1; while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } for(i=0; i<=mx; i++){ struct symbol *p = lemp->symbols[i]; if( p->fallback==0 ){ fprintf(out, " 0, /* %10s => nothing */\n", p->name); }else{ fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, p->name, p->fallback->name); } lineno++; } } tplt_xfer(lemp->name, in, out, &lineno); /* Generate a table containing the symbolic name of every symbol */ for(i=0; i<lemp->nsymbol; i++){ sprintf(line,"\"%s\",",lemp->symbols[i]->name); fprintf(out," %-15s",line); if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } } if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate a table containing a text string that describes every ** rule in the rule set of the grammar. This information is used ** when tracing REDUCE actions. */ for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ assert( rp->index==i ); fprintf(out," /* %3d */ \"", i); writeRuleText(out, rp); fprintf(out,"\",\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes every time a symbol is popped from ** the stack while processing errors or while destroying the parser. ** (In other words, generate the %destructor actions) */ if( lemp->tokendest ){ int once = 1; for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type!=TERMINAL ) continue; if( once ){ fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; once = 0; } fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; } for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++); if( i<lemp->nsymbol ){ emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); fprintf(out," break;\n"); lineno++; } } if( lemp->vardest ){ struct symbol *dflt_sp = 0; int once = 1; for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type==TERMINAL || sp->index<=0 || sp->destructor!=0 ) continue; if( once ){ fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++; once = 0; } fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; dflt_sp = sp; } if( dflt_sp!=0 ){ emit_destructor_code(out,dflt_sp,lemp,&lineno); } fprintf(out," break;\n"); lineno++; } for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; /* Combine duplicate destructors into a single case */ for(j=i+1; j<lemp->nsymbol; j++){ struct symbol *sp2 = lemp->symbols[j]; if( sp2 && sp2->type!=TERMINAL && sp2->destructor && sp2->dtnum==sp->dtnum && strcmp(sp->destructor,sp2->destructor)==0 ){ fprintf(out," case %d: /* %s */\n", sp2->index, sp2->name); lineno++; sp2->destructor = 0; } } emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); fprintf(out," break;\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes whenever the parser stack overflows */ tplt_print(out,lemp,lemp->overflow,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate the table of rule information ** ** Note: This code depends on the fact that rules are number ** sequentually beginning with 0. */ for(rp=lemp->rule; rp; rp=rp->next){ fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which execution during each REDUCE action */ for(rp=lemp->rule; rp; rp=rp->next){ translate_code(lemp, rp); } /* First output rules other than the default: rule */ for(rp=lemp->rule; rp; rp=rp->next){ struct rule *rp2; /* Other rules with the same action */ if( rp->code==0 ) continue; if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */ fprintf(out," case %d: /* ", rp->index); writeRuleText(out, rp); fprintf(out, " */\n"); lineno++; for(rp2=rp->next; rp2; rp2=rp2->next){ if( rp2->code==rp->code ){ fprintf(out," case %d: /* ", rp2->index); writeRuleText(out, rp2); fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++; rp2->code = 0; } } emit_code(out,rp,lemp,&lineno); fprintf(out," break;\n"); lineno++; rp->code = 0; } /* Finally, output the default: rule. We choose as the default: all ** empty actions. */ fprintf(out," default:\n"); lineno++; for(rp=lemp->rule; rp; rp=rp->next){ if( rp->code==0 ) continue; assert( rp->code[0]=='\n' && rp->code[1]==0 ); fprintf(out," /* (%d) ", rp->index); writeRuleText(out, rp); fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++; } fprintf(out," break;\n"); lineno++; tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes if a parse fails */ tplt_print(out,lemp,lemp->failure,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when a syntax error occurs */ tplt_print(out,lemp,lemp->error,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when the parser accepts its input */ tplt_print(out,lemp,lemp->accept,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Append any addition code the user desires */ tplt_print(out,lemp,lemp->extracode,&lineno); fclose(in); fclose(out); return; } /* Generate a header file for the parser */ void ReportHeader(struct lemon *lemp) { FILE *out, *in; const char *prefix; char line[LINESIZE]; char pattern[LINESIZE]; int i; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; in = file_open(lemp,".h","rb"); if( in ){ for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){ sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); if( strcmp(line,pattern) ) break; } fclose(in); if( i==lemp->nterminal ){ /* No change in the file. Don't rewrite it. */ return; } } out = file_open(lemp,".h","wb"); if( out ){ for(i=1; i<lemp->nterminal; i++){ fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); } fclose(out); } return; } /* Reduce the size of the action tables, if possible, by making use ** of defaults. ** ** In this version, we take the most frequent REDUCE action and make ** it the default. Except, there is no default if the wildcard token ** is a possible look-ahead. */ void CompressTables(struct lemon *lemp) { struct state *stp; struct action *ap, *ap2; struct rule *rp, *rp2, *rbest; int nbest, n; int i; int usesWildcard; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; nbest = 0; rbest = 0; usesWildcard = 0; for(ap=stp->ap; ap; ap=ap->next){ if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ usesWildcard = 1; } if( ap->type!=REDUCE ) continue; rp = ap->x.rp; if( rp->lhsStart ) continue; if( rp==rbest ) continue; n = 1; for(ap2=ap->next; ap2; ap2=ap2->next){ if( ap2->type!=REDUCE ) continue; rp2 = ap2->x.rp; if( rp2==rbest ) continue; if( rp2==rp ) n++; } if( n>nbest ){ nbest = n; rbest = rp; } } /* Do not make a default if the number of rules to default ** is not at least 1 or if the wildcard token is a possible ** lookahead. */ if( nbest<1 || usesWildcard ) continue; /* Combine matching REDUCE actions into a single default */ for(ap=stp->ap; ap; ap=ap->next){ if( ap->type==REDUCE && ap->x.rp==rbest ) break; } assert( ap ); ap->sp = Symbol_new("{default}"); for(ap=ap->next; ap; ap=ap->next){ if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; } stp->ap = Action_sort(stp->ap); } } /* ** Compare two states for sorting purposes. The smaller state is the ** one with the most non-terminal actions. If they have the same number ** of non-terminal actions, then the smaller is the one with the most ** token actions. */ static int stateResortCompare(const void *a, const void *b){ const struct state *pA = *(const struct state**)a; const struct state *pB = *(const struct state**)b; int n; n = pB->nNtAct - pA->nNtAct; if( n==0 ){ n = pB->nTknAct - pA->nTknAct; if( n==0 ){ n = pB->statenum - pA->statenum; } } assert( n!=0 ); return n; } /* ** Renumber and resort states so that states with fewer choices ** occur at the end. Except, keep state 0 as the first state. */ void ResortStates(struct lemon *lemp) { int i; struct state *stp; struct action *ap; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; stp->nTknAct = stp->nNtAct = 0; stp->iDflt = lemp->nstate + lemp->nrule; stp->iTknOfst = NO_OFFSET; stp->iNtOfst = NO_OFFSET; for(ap=stp->ap; ap; ap=ap->next){ if( compute_action(lemp,ap)>=0 ){ if( ap->sp->index<lemp->nterminal ){ stp->nTknAct++; }else if( ap->sp->index<lemp->nsymbol ){ stp->nNtAct++; }else{ stp->iDflt = compute_action(lemp, ap); } } } } qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), stateResortCompare); for(i=0; i<lemp->nstate; i++){ lemp->sorted[i]->statenum = i; } } /***************** From the file "set.c" ************************************/ /* ** Set manipulation routines for the LEMON parser generator. */ static int size = 0; /* Set the set size */ void SetSize(int n) { size = n+1; } /* Allocate a new set */ char *SetNew(){ char *s; s = (char*)calloc( size, 1); if( s==0 ){ extern void memory_error(); memory_error(); } return s; } /* Deallocate a set */ void SetFree(char *s) { free(s); } /* Add a new element to the set. Return TRUE if the element was added ** and FALSE if it was already there. */ int SetAdd(char *s, int e) { int rv; assert( e>=0 && e<size ); rv = s[e]; s[e] = 1; return !rv; } /* Add every element of s2 to s1. Return TRUE if s1 changes. */ int SetUnion(char *s1, char *s2) { int i, progress; progress = 0; for(i=0; i<size; i++){ if( s2[i]==0 ) continue; if( s1[i]==0 ){ progress = 1; s1[i] = 1; } } return progress; } /********************** From the file "table.c" ****************************/ /* ** All code in this file has been automatically generated ** from a specification in the file ** "table.q" ** by the associative array code building program "aagen". ** Do not edit this file! Instead, edit the specification ** file, then rerun aagen. */ /* ** Code for processing tables in the LEMON parser generator. */ PRIVATE int strhash(const char *x) { int h = 0; while( *x) h = h*13 + *(x++); return h; } /* Works like strdup, sort of. Save a string in malloced memory, but ** keep strings in a table so that the same string is not in more ** than one place. */ const char *Strsafe(const char *y) { const char *z; char *cpy; if( y==0 ) return 0; z = Strsafe_find(y); if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){ strcpy(cpy,y); z = cpy; Strsafe_insert(z); } MemoryCheck(z); return z; } /* There is one instance of the following structure for each ** associative array of type "x1". */ struct s_x1 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x1node *tbl; /* The data stored here */ struct s_x1node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x1". */ typedef struct s_x1node { const char *data; /* The data */ struct s_x1node *next; /* Next entry with the same hash */ struct s_x1node **from; /* Previous link */ } x1node; /* There is only one instance of the array, which is the following */ static struct s_x1 *x1a; /* Allocate a new associative array */ void Strsafe_init(){ if( x1a ) return; x1a = (struct s_x1*)malloc( sizeof(struct s_x1) ); if( x1a ){ x1a->size = 1024; x1a->count = 0; x1a->tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*1024 ); if( x1a->tbl==0 ){ free(x1a); x1a = 0; }else{ int i; x1a->ht = (x1node**)&(x1a->tbl[1024]); for(i=0; i<1024; i++) x1a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Strsafe_insert(const char *data) { x1node *np; int h; int ph; if( x1a==0 ) return 0; ph = strhash(data); h = ph & (x1a->size-1); np = x1a->ht[h]; while( np ){ if( strcmp(np->data,data)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x1a->count>=x1a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x1 array; array.size = size = x1a->size*2; array.count = x1a->count; array.tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x1node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x1a->count; i++){ x1node *oldnp, *newnp; oldnp = &(x1a->tbl[i]); h = strhash(oldnp->data) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x1a->tbl); *x1a = array; } /* Insert the new data */ h = ph & (x1a->size-1); np = &(x1a->tbl[x1a->count++]); np->data = data; if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); np->next = x1a->ht[h]; x1a->ht[h] = np; np->from = &(x1a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ const char *Strsafe_find(const char *key) { int h; x1node *np; if( x1a==0 ) return 0; h = strhash(key) & (x1a->size-1); np = x1a->ht[h]; while( np ){ if( strcmp(np->data,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return a pointer to the (terminal or nonterminal) symbol "x". ** Create a new symbol if this is the first time "x" has been seen. */ struct symbol *Symbol_new(const char *x) { struct symbol *sp; sp = Symbol_find(x); if( sp==0 ){ sp = (struct symbol *)calloc(1, sizeof(struct symbol) ); MemoryCheck(sp); sp->name = Strsafe(x); sp->type = isupper(*x) ? TERMINAL : NONTERMINAL; sp->rule = 0; sp->fallback = 0; sp->prec = -1; sp->assoc = UNK; sp->firstset = 0; sp->lambda = LEMON_FALSE; sp->destructor = 0; sp->destLineno = 0; sp->datatype = 0; sp->useCnt = 0; Symbol_insert(sp,sp->name); } sp->useCnt++; return sp; } /* Compare two symbols for working purposes ** ** Symbols that begin with upper case letters (terminals or tokens) ** must sort before symbols that begin with lower case letters ** (non-terminals). Other than that, the order does not matter. ** ** We find experimentally that leaving the symbols in their original ** order (the order they appeared in the grammar file) gives the ** smallest parser tables in SQLite. */ int Symbolcmpp(const void *_a, const void *_b) { const struct symbol **a = (const struct symbol **) _a; const struct symbol **b = (const struct symbol **) _b; int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 ); return i1-i2; } /* There is one instance of the following structure for each ** associative array of type "x2". */ struct s_x2 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x2node *tbl; /* The data stored here */ struct s_x2node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x2". */ typedef struct s_x2node { struct symbol *data; /* The data */ const char *key; /* The key */ struct s_x2node *next; /* Next entry with the same hash */ struct s_x2node **from; /* Previous link */ } x2node; /* There is only one instance of the array, which is the following */ static struct s_x2 *x2a; /* Allocate a new associative array */ void Symbol_init(){ if( x2a ) return; x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); if( x2a ){ x2a->size = 128; x2a->count = 0; x2a->tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*128 ); if( x2a->tbl==0 ){ free(x2a); x2a = 0; }else{ int i; x2a->ht = (x2node**)&(x2a->tbl[128]); for(i=0; i<128; i++) x2a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Symbol_insert(struct symbol *data, const char *key) { x2node *np; int h; int ph; if( x2a==0 ) return 0; ph = strhash(key); h = ph & (x2a->size-1); np = x2a->ht[h]; while( np ){ if( strcmp(np->key,key)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x2a->count>=x2a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x2 array; array.size = size = x2a->size*2; array.count = x2a->count; array.tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x2node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x2a->count; i++){ x2node *oldnp, *newnp; oldnp = &(x2a->tbl[i]); h = strhash(oldnp->key) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->key = oldnp->key; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x2a->tbl); *x2a = array; } /* Insert the new data */ h = ph & (x2a->size-1); np = &(x2a->tbl[x2a->count++]); np->key = key; np->data = data; if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); np->next = x2a->ht[h]; x2a->ht[h] = np; np->from = &(x2a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct symbol *Symbol_find(const char *key) { int h; x2node *np; if( x2a==0 ) return 0; h = strhash(key) & (x2a->size-1); np = x2a->ht[h]; while( np ){ if( strcmp(np->key,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return the n-th data. Return NULL if n is out of range. */ struct symbol *Symbol_Nth(int n) { struct symbol *data; if( x2a && n>0 && n<=x2a->count ){ data = x2a->tbl[n-1].data; }else{ data = 0; } return data; } /* Return the size of the array */ int Symbol_count() { return x2a ? x2a->count : 0; } /* Return an array of pointers to all data in the table. ** The array is obtained from malloc. Return NULL if memory allocation ** problems, or if the array is empty. */ struct symbol **Symbol_arrayof() { struct symbol **array; int i,size; if( x2a==0 ) return 0; size = x2a->count; array = (struct symbol **)calloc(size, sizeof(struct symbol *)); if( array ){ for(i=0; i<size; i++) array[i] = x2a->tbl[i].data; } return array; } /* Compare two configurations */ int Configcmp(const char *_a,const char *_b) { const struct config *a = (struct config *) _a; const struct config *b = (struct config *) _b; int x; x = a->rp->index - b->rp->index; if( x==0 ) x = a->dot - b->dot; return x; } /* Compare two states */ PRIVATE int statecmp(struct config *a, struct config *b) { int rc; for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ rc = a->rp->index - b->rp->index; if( rc==0 ) rc = a->dot - b->dot; } if( rc==0 ){ if( a ) rc = 1; if( b ) rc = -1; } return rc; } /* Hash a state */ PRIVATE int statehash(struct config *a) { int h=0; while( a ){ h = h*571 + a->rp->index*37 + a->dot; a = a->bp; } return h; } /* Allocate a new state structure */ struct state *State_new() { struct state *newstate; newstate = (struct state *)calloc(1, sizeof(struct state) ); MemoryCheck(newstate); return newstate; } /* There is one instance of the following structure for each ** associative array of type "x3". */ struct s_x3 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x3node *tbl; /* The data stored here */ struct s_x3node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x3". */ typedef struct s_x3node { struct state *data; /* The data */ struct config *key; /* The key */ struct s_x3node *next; /* Next entry with the same hash */ struct s_x3node **from; /* Previous link */ } x3node; /* There is only one instance of the array, which is the following */ static struct s_x3 *x3a; /* Allocate a new associative array */ void State_init(){ if( x3a ) return; x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); if( x3a ){ x3a->size = 128; x3a->count = 0; x3a->tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*128 ); if( x3a->tbl==0 ){ free(x3a); x3a = 0; }else{ int i; x3a->ht = (x3node**)&(x3a->tbl[128]); for(i=0; i<128; i++) x3a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int State_insert(struct state *data, struct config *key) { x3node *np; int h; int ph; if( x3a==0 ) return 0; ph = statehash(key); h = ph & (x3a->size-1); np = x3a->ht[h]; while( np ){ if( statecmp(np->key,key)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x3a->count>=x3a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x3 array; array.size = size = x3a->size*2; array.count = x3a->count; array.tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x3node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x3a->count; i++){ x3node *oldnp, *newnp; oldnp = &(x3a->tbl[i]); h = statehash(oldnp->key) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->key = oldnp->key; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x3a->tbl); *x3a = array; } /* Insert the new data */ h = ph & (x3a->size-1); np = &(x3a->tbl[x3a->count++]); np->key = key; np->data = data; if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); np->next = x3a->ht[h]; x3a->ht[h] = np; np->from = &(x3a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct state *State_find(struct config *key) { int h; x3node *np; if( x3a==0 ) return 0; h = statehash(key) & (x3a->size-1); np = x3a->ht[h]; while( np ){ if( statecmp(np->key,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return an array of pointers to all data in the table. ** The array is obtained from malloc. Return NULL if memory allocation ** problems, or if the array is empty. */ struct state **State_arrayof() { struct state **array; int i,size; if( x3a==0 ) return 0; size = x3a->count; array = (struct state **)malloc( sizeof(struct state *)*size ); if( array ){ for(i=0; i<size; i++) array[i] = x3a->tbl[i].data; } return array; } /* Hash a configuration */ PRIVATE int confighash(struct config *a) { int h=0; h = h*571 + a->rp->index*37 + a->dot; return h; } /* There is one instance of the following structure for each ** associative array of type "x4". */ struct s_x4 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x4node *tbl; /* The data stored here */ struct s_x4node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x4". */ typedef struct s_x4node { struct config *data; /* The data */ struct s_x4node *next; /* Next entry with the same hash */ struct s_x4node **from; /* Previous link */ } x4node; /* There is only one instance of the array, which is the following */ static struct s_x4 *x4a; /* Allocate a new associative array */ void Configtable_init(){ if( x4a ) return; x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); if( x4a ){ x4a->size = 64; x4a->count = 0; x4a->tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*64 ); if( x4a->tbl==0 ){ free(x4a); x4a = 0; }else{ int i; x4a->ht = (x4node**)&(x4a->tbl[64]); for(i=0; i<64; i++) x4a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Configtable_insert(struct config *data) { x4node *np; int h; int ph; if( x4a==0 ) return 0; ph = confighash(data); h = ph & (x4a->size-1); np = x4a->ht[h]; while( np ){ if( Configcmp((const char *) np->data,(const char *) data)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x4a->count>=x4a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x4 array; array.size = size = x4a->size*2; array.count = x4a->count; array.tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x4node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x4a->count; i++){ x4node *oldnp, *newnp; oldnp = &(x4a->tbl[i]); h = confighash(oldnp->data) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x4a->tbl); *x4a = array; } /* Insert the new data */ h = ph & (x4a->size-1); np = &(x4a->tbl[x4a->count++]); np->data = data; if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); np->next = x4a->ht[h]; x4a->ht[h] = np; np->from = &(x4a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct config *Configtable_find(struct config *key) { int h; x4node *np; if( x4a==0 ) return 0; h = confighash(key) & (x4a->size-1); np = x4a->ht[h]; while( np ){ if( Configcmp((const char *) np->data,(const char *) key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Remove all data from the table. Pass each data to the function "f" ** as it is removed. ("f" may be null to avoid this step.) */ void Configtable_clear(int(*f)(struct config *)) { int i; if( x4a==0 || x4a->count==0 ) return; if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data); for(i=0; i<x4a->size; i++) x4a->ht[i] = 0; x4a->count = 0; return; }
the_stack_data/243893406.c
// Example C11 code: simple example to start things off (testing command line option: -rose:c11) // Note that this feature requires EDG 4.8 or greater: // #include<stdalign.h> // DQ (1/18/2017): Fixed position of alignment keyword. // every object of type sse_t will be aligned to 16-byte boundary // struct alignas(16) sse_t // struct _Alignas(16) sse_t struct sse_tag { char c; float sse_data[4]; } _Alignas(16) sse_t;
the_stack_data/154828528.c
// RUN: %clang_cc1 -fsyntax-only %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=BASE // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-option %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-option -Werror %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_ERROR // RUN: %clang_cc1 -fsyntax-only -std=c89 -pedantic -fdiagnostics-show-option %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_PEDANTIC // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-category id %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=CATEGORY_ID // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-category name %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=CATEGORY_NAME // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-option -fdiagnostics-show-category name -Werror %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_ERROR_CATEGORY void test(int x, int y) { if (x = y) ++x; // BASE: {{.*}}: warning: {{[a-z ]+$}} // OPTION: {{.*}}: warning: {{[a-z ]+}} [-Wparentheses] // OPTION_ERROR: {{.*}}: error: {{[a-z ]+}} [-Werror,-Wparentheses] // CATEGORY_ID: {{.*}}: warning: {{[a-z ]+}} [2] // CATEGORY_NAME: {{.*}}: warning: {{[a-z ]+}} [Semantic Issue] // OPTION_ERROR_CATEGORY: {{.*}}: error: {{[a-z ]+}} [-Werror,-Wparentheses,Semantic Issue] // Leverage the fact that all these '//'s get warned about in C89 pedantic. // OPTION_PEDANTIC: {{.*}}: warning: {{[/a-z ]+}} [-pedantic,-Wcomment] }
the_stack_data/250828.c
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> unsigned fib(unsigned n); int main(int argc, char *argv[]) { if (argc != 2) { printf("You must provide a number of childprocesses\n"); return EXIT_FAILURE; } unsigned int n = strtol(argv[1], NULL, 10); for (unsigned int i = 0; i < n; i++) { pid_t pid; pid = fork(); if (pid < 0) { fprintf(stderr, "Fork failed"); return EXIT_FAILURE; } else if (pid == 0) { printf("Child %d PID = %d. Fib(40) = %d\n", i, getpid(), fib(40)); return 0; } else { wait(NULL); } } printf("Done\n"); return EXIT_SUCCESS; } unsigned fib(unsigned n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } /* Analyze the obtained output. Is the order of the messages consistent? Can the order of these messages be predicted? What does it depend on? Yes it is, because the program waits for the childprocess before starting a new one. */
the_stack_data/157483.c
void main() { int i, *r = (int *)0x7f00; while (1) { for (i = 1; i <= 25; i++) { *r = fib(i); } } } int fib(int n) { if (n == 1) return 0; if (n == 2) return 1; return fib(n-2) + fib(n-1); }
the_stack_data/78674.c
# 1 "wronglock_bad.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "wronglock_bad.c" # 1 "/usr/include/stdio.h" 1 3 # 28 "/usr/include/stdio.h" 3 # 1 "/usr/include/features.h" 1 3 # 335 "/usr/include/features.h" 3 # 1 "/usr/include/sys/cdefs.h" 1 3 # 360 "/usr/include/sys/cdefs.h" 3 # 1 "/usr/include/bits/wordsize.h" 1 3 # 361 "/usr/include/sys/cdefs.h" 2 3 # 336 "/usr/include/features.h" 2 3 # 359 "/usr/include/features.h" 3 # 1 "/usr/include/gnu/stubs.h" 1 3 # 1 "/usr/include/bits/wordsize.h" 1 3 # 5 "/usr/include/gnu/stubs.h" 2 3 # 1 "/usr/include/gnu/stubs-32.h" 1 3 # 8 "/usr/include/gnu/stubs.h" 2 3 # 360 "/usr/include/features.h" 2 3 # 29 "/usr/include/stdio.h" 2 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 214 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 3 4 typedef unsigned int size_t; # 35 "/usr/include/stdio.h" 2 3 # 1 "/usr/include/bits/types.h" 1 3 # 28 "/usr/include/bits/types.h" 3 # 1 "/usr/include/bits/wordsize.h" 1 3 # 29 "/usr/include/bits/types.h" 2 3 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; __extension__ typedef signed long long int __int64_t; __extension__ typedef unsigned long long int __uint64_t; __extension__ typedef long long int __quad_t; __extension__ typedef unsigned long long int __u_quad_t; # 131 "/usr/include/bits/types.h" 3 # 1 "/usr/include/bits/typesizes.h" 1 3 # 132 "/usr/include/bits/types.h" 2 3 __extension__ typedef __u_quad_t __dev_t; __extension__ typedef unsigned int __uid_t; __extension__ typedef unsigned int __gid_t; __extension__ typedef unsigned long int __ino_t; __extension__ typedef __u_quad_t __ino64_t; __extension__ typedef unsigned int __mode_t; __extension__ typedef unsigned int __nlink_t; __extension__ typedef long int __off_t; __extension__ typedef __quad_t __off64_t; __extension__ typedef int __pid_t; __extension__ typedef struct { int __val[2]; } __fsid_t; __extension__ typedef long int __clock_t; __extension__ typedef unsigned long int __rlim_t; __extension__ typedef __u_quad_t __rlim64_t; __extension__ typedef unsigned int __id_t; __extension__ typedef long int __time_t; __extension__ typedef unsigned int __useconds_t; __extension__ typedef long int __suseconds_t; __extension__ typedef int __daddr_t; __extension__ typedef long int __swblk_t; __extension__ typedef int __key_t; __extension__ typedef int __clockid_t; __extension__ typedef void * __timer_t; __extension__ typedef long int __blksize_t; __extension__ typedef long int __blkcnt_t; __extension__ typedef __quad_t __blkcnt64_t; __extension__ typedef unsigned long int __fsblkcnt_t; __extension__ typedef __u_quad_t __fsblkcnt64_t; __extension__ typedef unsigned long int __fsfilcnt_t; __extension__ typedef __u_quad_t __fsfilcnt64_t; __extension__ typedef int __ssize_t; typedef __off64_t __loff_t; typedef __quad_t *__qaddr_t; typedef char *__caddr_t; __extension__ typedef int __intptr_t; __extension__ typedef unsigned int __socklen_t; # 37 "/usr/include/stdio.h" 2 3 # 45 "/usr/include/stdio.h" 3 struct _IO_FILE; typedef struct _IO_FILE FILE; # 65 "/usr/include/stdio.h" 3 typedef struct _IO_FILE __FILE; # 75 "/usr/include/stdio.h" 3 # 1 "/usr/include/libio.h" 1 3 # 32 "/usr/include/libio.h" 3 # 1 "/usr/include/_G_config.h" 1 3 # 15 "/usr/include/_G_config.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 16 "/usr/include/_G_config.h" 2 3 # 1 "/usr/include/wchar.h" 1 3 # 78 "/usr/include/wchar.h" 3 typedef struct { int __count; union { unsigned int __wch; char __wchb[4]; } __value; } __mbstate_t; # 21 "/usr/include/_G_config.h" 2 3 typedef struct { __off_t __pos; __mbstate_t __state; } _G_fpos_t; typedef struct { __off64_t __pos; __mbstate_t __state; } _G_fpos64_t; # 53 "/usr/include/_G_config.h" 3 typedef int _G_int16_t __attribute__ ((__mode__ (__HI__))); typedef int _G_int32_t __attribute__ ((__mode__ (__SI__))); typedef unsigned int _G_uint16_t __attribute__ ((__mode__ (__HI__))); typedef unsigned int _G_uint32_t __attribute__ ((__mode__ (__SI__))); # 33 "/usr/include/libio.h" 2 3 # 53 "/usr/include/libio.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stdarg.h" 1 3 4 # 43 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stdarg.h" 3 4 typedef __builtin_va_list __gnuc_va_list; # 54 "/usr/include/libio.h" 2 3 # 170 "/usr/include/libio.h" 3 struct _IO_jump_t; struct _IO_FILE; # 180 "/usr/include/libio.h" 3 typedef void _IO_lock_t; struct _IO_marker { struct _IO_marker *_next; struct _IO_FILE *_sbuf; int _pos; # 203 "/usr/include/libio.h" 3 }; enum __codecvt_result { __codecvt_ok, __codecvt_partial, __codecvt_error, __codecvt_noconv }; # 271 "/usr/include/libio.h" 3 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; # 319 "/usr/include/libio.h" 3 __off64_t _offset; # 328 "/usr/include/libio.h" 3 void *__pad1; void *__pad2; void *__pad3; void *__pad4; size_t __pad5; int _mode; char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)]; }; typedef struct _IO_FILE _IO_FILE; struct _IO_FILE_plus; extern struct _IO_FILE_plus _IO_2_1_stdin_; extern struct _IO_FILE_plus _IO_2_1_stdout_; extern struct _IO_FILE_plus _IO_2_1_stderr_; # 364 "/usr/include/libio.h" 3 typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes); typedef __ssize_t __io_write_fn (void *__cookie, __const char *__buf, size_t __n); typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w); typedef int __io_close_fn (void *__cookie); # 416 "/usr/include/libio.h" 3 extern int __underflow (_IO_FILE *); extern int __uflow (_IO_FILE *); extern int __overflow (_IO_FILE *, int); # 458 "/usr/include/libio.h" 3 extern int _IO_getc (_IO_FILE *__fp); extern int _IO_putc (int __c, _IO_FILE *__fp); extern int _IO_feof (_IO_FILE *__fp) __attribute__ ((__nothrow__)); extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__)); extern int _IO_peekc_locked (_IO_FILE *__fp); extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__)); extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__)); extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__)); # 488 "/usr/include/libio.h" 3 extern int _IO_vfscanf (_IO_FILE * __restrict, const char * __restrict, __gnuc_va_list, int *__restrict); extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict, __gnuc_va_list); extern __ssize_t _IO_padn (_IO_FILE *, int, __ssize_t); extern size_t _IO_sgetn (_IO_FILE *, void *, size_t); extern __off64_t _IO_seekoff (_IO_FILE *, __off64_t, int, int); extern __off64_t _IO_seekpos (_IO_FILE *, __off64_t, int); extern void _IO_free_backup_area (_IO_FILE *) __attribute__ ((__nothrow__)); # 76 "/usr/include/stdio.h" 2 3 # 89 "/usr/include/stdio.h" 3 typedef _G_fpos_t fpos_t; # 141 "/usr/include/stdio.h" 3 # 1 "/usr/include/bits/stdio_lim.h" 1 3 # 142 "/usr/include/stdio.h" 2 3 extern struct _IO_FILE *stdin; extern struct _IO_FILE *stdout; extern struct _IO_FILE *stderr; extern int remove (__const char *__filename) __attribute__ ((__nothrow__)); extern int rename (__const char *__old, __const char *__new) __attribute__ ((__nothrow__)); extern FILE *tmpfile (void) ; # 188 "/usr/include/stdio.h" 3 extern char *tmpnam (char *__s) __attribute__ ((__nothrow__)) ; extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__)) ; # 206 "/usr/include/stdio.h" 3 extern char *tempnam (__const char *__dir, __const char *__pfx) __attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) ; extern int fclose (FILE *__stream); extern int fflush (FILE *__stream); # 231 "/usr/include/stdio.h" 3 extern int fflush_unlocked (FILE *__stream); # 245 "/usr/include/stdio.h" 3 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) ; # 274 "/usr/include/stdio.h" 3 # 285 "/usr/include/stdio.h" 3 extern FILE *fdopen (int __fd, __const char *__modes) __attribute__ ((__nothrow__)) ; # 306 "/usr/include/stdio.h" 3 extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__)); extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf, int __modes, size_t __n) __attribute__ ((__nothrow__)); extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf, size_t __size) __attribute__ ((__nothrow__)); extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__)); 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))); # 400 "/usr/include/stdio.h" 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__)); # 443 "/usr/include/stdio.h" 3 # 506 "/usr/include/stdio.h" 3 extern int fgetc (FILE *__stream); extern int getc (FILE *__stream); extern int getchar (void); # 530 "/usr/include/stdio.h" 3 extern int getc_unlocked (FILE *__stream); extern int getchar_unlocked (void); # 541 "/usr/include/stdio.h" 3 extern int fgetc_unlocked (FILE *__stream); extern int fputc (int __c, FILE *__stream); extern int putc (int __c, FILE *__stream); extern int putchar (int __c); # 574 "/usr/include/stdio.h" 3 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) ; extern char *gets (char *__s) ; # 655 "/usr/include/stdio.h" 3 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) ; # 708 "/usr/include/stdio.h" 3 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); # 744 "/usr/include/stdio.h" 3 extern int fseeko (FILE *__stream, __off_t __off, int __whence); extern __off_t ftello (FILE *__stream) ; # 763 "/usr/include/stdio.h" 3 extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos); extern int fsetpos (FILE *__stream, __const fpos_t *__pos); # 786 "/usr/include/stdio.h" 3 # 795 "/usr/include/stdio.h" 3 extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__)); extern int feof (FILE *__stream) __attribute__ ((__nothrow__)) ; extern int ferror (FILE *__stream) __attribute__ ((__nothrow__)) ; extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__)); extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__)) ; extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__)) ; extern void perror (__const char *__s); # 1 "/usr/include/bits/sys_errlist.h" 1 3 # 27 "/usr/include/bits/sys_errlist.h" 3 extern int sys_nerr; extern __const char *__const sys_errlist[]; # 825 "/usr/include/stdio.h" 2 3 extern int fileno (FILE *__stream) __attribute__ ((__nothrow__)) ; extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__)) ; # 844 "/usr/include/stdio.h" 3 extern FILE *popen (__const char *__command, __const char *__modes) ; extern int pclose (FILE *__stream); extern char *ctermid (char *__s) __attribute__ ((__nothrow__)); # 884 "/usr/include/stdio.h" 3 extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__)); extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__)) ; extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__)); # 914 "/usr/include/stdio.h" 3 # 2 "wronglock_bad.c" 2 # 1 "/usr/include/stdlib.h" 1 3 # 33 "/usr/include/stdlib.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 326 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 3 4 typedef long int wchar_t; # 34 "/usr/include/stdlib.h" 2 3 # 96 "/usr/include/stdlib.h" 3 typedef struct { int quot; int rem; } div_t; typedef struct { long int quot; long int rem; } ldiv_t; # 140 "/usr/include/stdlib.h" 3 extern size_t __ctype_get_mb_cur_max (void) __attribute__ ((__nothrow__)) ; extern double atof (__const char *__nptr) __attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern int atoi (__const char *__nptr) __attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern long int atol (__const char *__nptr) __attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern long long int atoll (__const char *__nptr) __attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern double strtod (__const char *__restrict __nptr, char **__restrict __endptr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; # 182 "/usr/include/stdlib.h" 3 extern long int strtol (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; extern unsigned long int strtoul (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern long long int strtoq (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern unsigned long long int strtouq (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern long long int strtoll (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern unsigned long long int strtoull (__const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; # 311 "/usr/include/stdlib.h" 3 extern char *l64a (long int __n) __attribute__ ((__nothrow__)) ; extern long int a64l (__const char *__s) __attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; # 1 "/usr/include/sys/types.h" 1 3 # 29 "/usr/include/sys/types.h" 3 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; # 62 "/usr/include/sys/types.h" 3 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; # 100 "/usr/include/sys/types.h" 3 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; # 133 "/usr/include/sys/types.h" 3 # 1 "/usr/include/time.h" 1 3 # 75 "/usr/include/time.h" 3 typedef __time_t time_t; # 93 "/usr/include/time.h" 3 typedef __clockid_t clockid_t; # 105 "/usr/include/time.h" 3 typedef __timer_t timer_t; # 134 "/usr/include/sys/types.h" 2 3 # 147 "/usr/include/sys/types.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 148 "/usr/include/sys/types.h" 2 3 typedef unsigned long int ulong; typedef unsigned short int ushort; typedef unsigned int uint; # 195 "/usr/include/sys/types.h" 3 typedef int int8_t __attribute__ ((__mode__ (__QI__))); typedef int int16_t __attribute__ ((__mode__ (__HI__))); typedef int int32_t __attribute__ ((__mode__ (__SI__))); typedef int int64_t __attribute__ ((__mode__ (__DI__))); typedef unsigned int u_int8_t __attribute__ ((__mode__ (__QI__))); typedef unsigned int u_int16_t __attribute__ ((__mode__ (__HI__))); typedef unsigned int u_int32_t __attribute__ ((__mode__ (__SI__))); typedef unsigned int u_int64_t __attribute__ ((__mode__ (__DI__))); typedef int register_t __attribute__ ((__mode__ (__word__))); # 217 "/usr/include/sys/types.h" 3 # 1 "/usr/include/endian.h" 1 3 # 37 "/usr/include/endian.h" 3 # 1 "/usr/include/bits/endian.h" 1 3 # 38 "/usr/include/endian.h" 2 3 # 61 "/usr/include/endian.h" 3 # 1 "/usr/include/bits/byteswap.h" 1 3 # 62 "/usr/include/endian.h" 2 3 # 218 "/usr/include/sys/types.h" 2 3 # 1 "/usr/include/sys/select.h" 1 3 # 31 "/usr/include/sys/select.h" 3 # 1 "/usr/include/bits/select.h" 1 3 # 32 "/usr/include/sys/select.h" 2 3 # 1 "/usr/include/bits/sigset.h" 1 3 # 24 "/usr/include/bits/sigset.h" 3 typedef int __sig_atomic_t; typedef struct { unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))]; } __sigset_t; # 35 "/usr/include/sys/select.h" 2 3 typedef __sigset_t sigset_t; # 1 "/usr/include/time.h" 1 3 # 121 "/usr/include/time.h" 3 struct timespec { __time_t tv_sec; long int tv_nsec; }; # 45 "/usr/include/sys/select.h" 2 3 # 1 "/usr/include/bits/time.h" 1 3 # 69 "/usr/include/bits/time.h" 3 struct timeval { __time_t tv_sec; __suseconds_t tv_usec; }; # 47 "/usr/include/sys/select.h" 2 3 typedef __suseconds_t suseconds_t; typedef long int __fd_mask; # 67 "/usr/include/sys/select.h" 3 typedef struct { __fd_mask __fds_bits[1024 / (8 * sizeof (__fd_mask))]; } fd_set; typedef __fd_mask fd_mask; # 99 "/usr/include/sys/select.h" 3 # 109 "/usr/include/sys/select.h" 3 extern int select (int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, fd_set *__restrict __exceptfds, struct timeval *__restrict __timeout); # 121 "/usr/include/sys/select.h" 3 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); # 221 "/usr/include/sys/types.h" 2 3 # 1 "/usr/include/sys/sysmacros.h" 1 3 # 30 "/usr/include/sys/sysmacros.h" 3 __extension__ extern unsigned int gnu_dev_major (unsigned long long int __dev) __attribute__ ((__nothrow__)); __extension__ extern unsigned int gnu_dev_minor (unsigned long long int __dev) __attribute__ ((__nothrow__)); __extension__ extern unsigned long long int gnu_dev_makedev (unsigned int __major, unsigned int __minor) __attribute__ ((__nothrow__)); # 224 "/usr/include/sys/types.h" 2 3 # 235 "/usr/include/sys/types.h" 3 typedef __blkcnt_t blkcnt_t; typedef __fsblkcnt_t fsblkcnt_t; typedef __fsfilcnt_t fsfilcnt_t; # 270 "/usr/include/sys/types.h" 3 # 1 "/usr/include/bits/pthreadtypes.h" 1 3 # 36 "/usr/include/bits/pthreadtypes.h" 3 typedef unsigned long int pthread_t; typedef union { char __size[36]; long int __align; } pthread_attr_t; typedef struct __pthread_internal_slist { struct __pthread_internal_slist *__next; } __pthread_slist_t; typedef union { struct __pthread_mutex_s { int __lock; unsigned int __count; int __owner; int __kind; unsigned int __nusers; __extension__ union { int __spins; __pthread_slist_t __list; }; } __data; char __size[24]; long int __align; } pthread_mutex_t; typedef union { char __size[4]; long int __align; } pthread_mutexattr_t; typedef union { struct { int __lock; unsigned int __futex; __extension__ unsigned long long int __total_seq; __extension__ unsigned long long int __wakeup_seq; __extension__ unsigned long long int __woken_seq; void *__mutex; unsigned int __nwaiters; unsigned int __broadcast_seq; } __data; char __size[48]; __extension__ long long int __align; } pthread_cond_t; typedef union { char __size[4]; long int __align; } pthread_condattr_t; typedef unsigned int pthread_key_t; typedef int pthread_once_t; typedef union { struct { int __lock; unsigned int __nr_readers; unsigned int __readers_wakeup; unsigned int __writer_wakeup; unsigned int __nr_readers_queued; unsigned int __nr_writers_queued; unsigned char __flags; unsigned char __shared; unsigned char __pad1; unsigned char __pad2; int __writer; } __data; char __size[32]; 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[20]; long int __align; } pthread_barrier_t; typedef union { char __size[4]; int __align; } pthread_barrierattr_t; # 271 "/usr/include/sys/types.h" 2 3 # 321 "/usr/include/stdlib.h" 2 3 extern long int random (void) __attribute__ ((__nothrow__)); extern void srandom (unsigned int __seed) __attribute__ ((__nothrow__)); extern char *initstate (unsigned int __seed, char *__statebuf, size_t __statelen) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2))); extern char *setstate (char *__statebuf) __attribute__ ((__nothrow__)) __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__)) __attribute__ ((__nonnull__ (1, 2))); extern int srandom_r (unsigned int __seed, struct random_data *__buf) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2))); extern int initstate_r (unsigned int __seed, char *__restrict __statebuf, size_t __statelen, struct random_data *__restrict __buf) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2, 4))); extern int setstate_r (char *__restrict __statebuf, struct random_data *__restrict __buf) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int rand (void) __attribute__ ((__nothrow__)); extern void srand (unsigned int __seed) __attribute__ ((__nothrow__)); extern int rand_r (unsigned int *__seed) __attribute__ ((__nothrow__)); extern double drand48 (void) __attribute__ ((__nothrow__)); extern double erand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern long int lrand48 (void) __attribute__ ((__nothrow__)); extern long int nrand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern long int mrand48 (void) __attribute__ ((__nothrow__)); extern long int jrand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern void srand48 (long int __seedval) __attribute__ ((__nothrow__)); extern unsigned short int *seed48 (unsigned short int __seed16v[3]) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern void lcong48 (unsigned short int __param[7]) __attribute__ ((__nothrow__)) __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; unsigned long long int __a; }; extern int drand48_r (struct drand48_data *__restrict __buffer, double *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int erand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, double *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int lrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int nrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int mrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int jrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int srand48_r (long int __seedval, struct drand48_data *__buffer) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2))); extern int seed48_r (unsigned short int __seed16v[3], struct drand48_data *__buffer) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int lcong48_r (unsigned short int __param[7], struct drand48_data *__buffer) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern void *malloc (size_t __size) __attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) ; extern void *calloc (size_t __nmemb, size_t __size) __attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) ; extern void *realloc (void *__ptr, size_t __size) __attribute__ ((__nothrow__)) __attribute__ ((__warn_unused_result__)); extern void free (void *__ptr) __attribute__ ((__nothrow__)); extern void cfree (void *__ptr) __attribute__ ((__nothrow__)); # 1 "/usr/include/alloca.h" 1 3 # 25 "/usr/include/alloca.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 26 "/usr/include/alloca.h" 2 3 extern void *alloca (size_t __size) __attribute__ ((__nothrow__)); # 498 "/usr/include/stdlib.h" 2 3 extern void *valloc (size_t __size) __attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) ; extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; extern void abort (void) __attribute__ ((__nothrow__)) __attribute__ ((__noreturn__)); extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern void exit (int __status) __attribute__ ((__nothrow__)) __attribute__ ((__noreturn__)); # 543 "/usr/include/stdlib.h" 3 extern char *getenv (__const char *__name) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; extern char *__secure_getenv (__const char *__name) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; extern int putenv (char *__string) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int setenv (__const char *__name, __const char *__value, int __replace) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2))); extern int unsetenv (__const char *__name) __attribute__ ((__nothrow__)); extern int clearenv (void) __attribute__ ((__nothrow__)); # 583 "/usr/include/stdlib.h" 3 extern char *mktemp (char *__template) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; # 594 "/usr/include/stdlib.h" 3 extern int mkstemp (char *__template) __attribute__ ((__nonnull__ (1))) ; # 614 "/usr/include/stdlib.h" 3 extern char *mkdtemp (char *__template) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; # 640 "/usr/include/stdlib.h" 3 extern int system (__const char *__command) ; # 662 "/usr/include/stdlib.h" 3 extern char *realpath (__const char *__restrict __name, char *__restrict __resolved) __attribute__ ((__nothrow__)) ; typedef int (*__compar_fn_t) (__const void *, __const void *); # 680 "/usr/include/stdlib.h" 3 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))); # 699 "/usr/include/stdlib.h" 3 extern int abs (int __x) __attribute__ ((__nothrow__)) __attribute__ ((__const__)) ; extern long int labs (long int __x) __attribute__ ((__nothrow__)) __attribute__ ((__const__)) ; extern div_t div (int __numer, int __denom) __attribute__ ((__nothrow__)) __attribute__ ((__const__)) ; extern ldiv_t ldiv (long int __numer, long int __denom) __attribute__ ((__nothrow__)) __attribute__ ((__const__)) ; # 735 "/usr/include/stdlib.h" 3 extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *gcvt (double __value, int __ndigit, char *__buf) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3))) ; extern char *qecvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *qfcvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *qgcvt (long double __value, int __ndigit, char *__buf) __attribute__ ((__nothrow__)) __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__)) __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__)) __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__)) __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__)) __attribute__ ((__nonnull__ (3, 4, 5))); extern int mblen (__const char *__s, size_t __n) __attribute__ ((__nothrow__)) ; extern int mbtowc (wchar_t *__restrict __pwc, __const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__)) ; extern int wctomb (char *__s, wchar_t __wchar) __attribute__ ((__nothrow__)) ; extern size_t mbstowcs (wchar_t *__restrict __pwcs, __const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__)); extern size_t wcstombs (char *__restrict __s, __const wchar_t *__restrict __pwcs, size_t __n) __attribute__ ((__nothrow__)); extern int rpmatch (__const char *__response) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) ; # 840 "/usr/include/stdlib.h" 3 extern int posix_openpt (int __oflag) ; # 875 "/usr/include/stdlib.h" 3 extern int getloadavg (double __loadavg[], int __nelem) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 891 "/usr/include/stdlib.h" 3 # 3 "wronglock_bad.c" 2 # 1 "/usr/include/pthread.h" 1 3 # 25 "/usr/include/pthread.h" 3 # 1 "/usr/include/sched.h" 1 3 # 29 "/usr/include/sched.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 30 "/usr/include/sched.h" 2 3 # 1 "/usr/include/time.h" 1 3 # 33 "/usr/include/sched.h" 2 3 # 1 "/usr/include/bits/sched.h" 1 3 # 71 "/usr/include/bits/sched.h" 3 struct sched_param { int __sched_priority; }; extern int clone (int (*__fn) (void *__arg), void *__child_stack, int __flags, void *__arg, ...) __attribute__ ((__nothrow__)); extern int unshare (int __flags) __attribute__ ((__nothrow__)); extern int sched_getcpu (void) __attribute__ ((__nothrow__)); struct __sched_param { int __sched_priority; }; # 113 "/usr/include/bits/sched.h" 3 typedef unsigned long int __cpu_mask; typedef struct { __cpu_mask __bits[1024 / (8 * sizeof (__cpu_mask))]; } cpu_set_t; # 196 "/usr/include/bits/sched.h" 3 extern int __sched_cpucount (size_t __setsize, const cpu_set_t *__setp) __attribute__ ((__nothrow__)); extern cpu_set_t *__sched_cpualloc (size_t __count) __attribute__ ((__nothrow__)) ; extern void __sched_cpufree (cpu_set_t *__set) __attribute__ ((__nothrow__)); # 36 "/usr/include/sched.h" 2 3 extern int sched_setparam (__pid_t __pid, __const struct sched_param *__param) __attribute__ ((__nothrow__)); extern int sched_getparam (__pid_t __pid, struct sched_param *__param) __attribute__ ((__nothrow__)); extern int sched_setscheduler (__pid_t __pid, int __policy, __const struct sched_param *__param) __attribute__ ((__nothrow__)); extern int sched_getscheduler (__pid_t __pid) __attribute__ ((__nothrow__)); extern int sched_yield (void) __attribute__ ((__nothrow__)); extern int sched_get_priority_max (int __algorithm) __attribute__ ((__nothrow__)); extern int sched_get_priority_min (int __algorithm) __attribute__ ((__nothrow__)); extern int sched_rr_get_interval (__pid_t __pid, struct timespec *__t) __attribute__ ((__nothrow__)); # 118 "/usr/include/sched.h" 3 # 26 "/usr/include/pthread.h" 2 3 # 1 "/usr/include/time.h" 1 3 # 31 "/usr/include/time.h" 3 # 1 "/usr/lib/gcc/i386-redhat-linux/4.3.2/include/stddef.h" 1 3 4 # 40 "/usr/include/time.h" 2 3 # 1 "/usr/include/bits/time.h" 1 3 # 44 "/usr/include/time.h" 2 3 # 59 "/usr/include/time.h" 3 typedef __clock_t clock_t; # 132 "/usr/include/time.h" 3 struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; long int tm_gmtoff; __const char *tm_zone; }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; struct sigevent; # 181 "/usr/include/time.h" 3 extern clock_t clock (void) __attribute__ ((__nothrow__)); extern time_t time (time_t *__timer) __attribute__ ((__nothrow__)); extern double difftime (time_t __time1, time_t __time0) __attribute__ ((__nothrow__)) __attribute__ ((__const__)); extern time_t mktime (struct tm *__tp) __attribute__ ((__nothrow__)); extern size_t strftime (char *__restrict __s, size_t __maxsize, __const char *__restrict __format, __const struct tm *__restrict __tp) __attribute__ ((__nothrow__)); # 229 "/usr/include/time.h" 3 extern struct tm *gmtime (__const time_t *__timer) __attribute__ ((__nothrow__)); extern struct tm *localtime (__const time_t *__timer) __attribute__ ((__nothrow__)); extern struct tm *gmtime_r (__const time_t *__restrict __timer, struct tm *__restrict __tp) __attribute__ ((__nothrow__)); extern struct tm *localtime_r (__const time_t *__restrict __timer, struct tm *__restrict __tp) __attribute__ ((__nothrow__)); extern char *asctime (__const struct tm *__tp) __attribute__ ((__nothrow__)); extern char *ctime (__const time_t *__timer) __attribute__ ((__nothrow__)); extern char *asctime_r (__const struct tm *__restrict __tp, char *__restrict __buf) __attribute__ ((__nothrow__)); extern char *ctime_r (__const time_t *__restrict __timer, char *__restrict __buf) __attribute__ ((__nothrow__)); extern char *__tzname[2]; extern int __daylight; extern long int __timezone; extern char *tzname[2]; extern void tzset (void) __attribute__ ((__nothrow__)); extern int daylight; extern long int timezone; extern int stime (__const time_t *__when) __attribute__ ((__nothrow__)); # 312 "/usr/include/time.h" 3 extern time_t timegm (struct tm *__tp) __attribute__ ((__nothrow__)); extern time_t timelocal (struct tm *__tp) __attribute__ ((__nothrow__)); extern int dysize (int __year) __attribute__ ((__nothrow__)) __attribute__ ((__const__)); # 327 "/usr/include/time.h" 3 extern int nanosleep (__const struct timespec *__requested_time, struct timespec *__remaining); extern int clock_getres (clockid_t __clock_id, struct timespec *__res) __attribute__ ((__nothrow__)); extern int clock_gettime (clockid_t __clock_id, struct timespec *__tp) __attribute__ ((__nothrow__)); extern int clock_settime (clockid_t __clock_id, __const struct timespec *__tp) __attribute__ ((__nothrow__)); extern int clock_nanosleep (clockid_t __clock_id, int __flags, __const struct timespec *__req, struct timespec *__rem); extern int clock_getcpuclockid (pid_t __pid, clockid_t *__clock_id) __attribute__ ((__nothrow__)); extern int timer_create (clockid_t __clock_id, struct sigevent *__restrict __evp, timer_t *__restrict __timerid) __attribute__ ((__nothrow__)); extern int timer_delete (timer_t __timerid) __attribute__ ((__nothrow__)); extern int timer_settime (timer_t __timerid, int __flags, __const struct itimerspec *__restrict __value, struct itimerspec *__restrict __ovalue) __attribute__ ((__nothrow__)); extern int timer_gettime (timer_t __timerid, struct itimerspec *__value) __attribute__ ((__nothrow__)); extern int timer_getoverrun (timer_t __timerid) __attribute__ ((__nothrow__)); # 416 "/usr/include/time.h" 3 # 27 "/usr/include/pthread.h" 2 3 # 1 "/usr/include/signal.h" 1 3 # 31 "/usr/include/signal.h" 3 # 1 "/usr/include/bits/sigset.h" 1 3 # 34 "/usr/include/signal.h" 2 3 # 402 "/usr/include/signal.h" 3 # 30 "/usr/include/pthread.h" 2 3 # 1 "/usr/include/bits/setjmp.h" 1 3 # 29 "/usr/include/bits/setjmp.h" 3 typedef int __jmp_buf[6]; # 32 "/usr/include/pthread.h" 2 3 # 1 "/usr/include/bits/wordsize.h" 1 3 # 33 "/usr/include/pthread.h" 2 3 enum { PTHREAD_CREATE_JOINABLE, PTHREAD_CREATE_DETACHED }; enum { PTHREAD_MUTEX_TIMED_NP, PTHREAD_MUTEX_RECURSIVE_NP, PTHREAD_MUTEX_ERRORCHECK_NP, PTHREAD_MUTEX_ADAPTIVE_NP # 63 "/usr/include/pthread.h" 3 }; # 115 "/usr/include/pthread.h" 3 enum { PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_RWLOCK_PREFER_WRITER_NP, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP, PTHREAD_RWLOCK_DEFAULT_NP = PTHREAD_RWLOCK_PREFER_READER_NP }; # 147 "/usr/include/pthread.h" 3 enum { PTHREAD_INHERIT_SCHED, PTHREAD_EXPLICIT_SCHED }; enum { PTHREAD_SCOPE_SYSTEM, PTHREAD_SCOPE_PROCESS }; enum { PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED }; # 182 "/usr/include/pthread.h" 3 struct _pthread_cleanup_buffer { void (*__routine) (void *); void *__arg; int __canceltype; struct _pthread_cleanup_buffer *__prev; }; enum { PTHREAD_CANCEL_ENABLE, PTHREAD_CANCEL_DISABLE }; enum { PTHREAD_CANCEL_DEFERRED, PTHREAD_CANCEL_ASYNCHRONOUS }; # 220 "/usr/include/pthread.h" 3 extern int pthread_create (pthread_t *__restrict __newthread, __const pthread_attr_t *__restrict __attr, void *(*__start_routine) (void *), void *__restrict __arg) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 3))); extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__)); extern int pthread_join (pthread_t __th, void **__thread_return); # 263 "/usr/include/pthread.h" 3 extern int pthread_detach (pthread_t __th) __attribute__ ((__nothrow__)); extern pthread_t pthread_self (void) __attribute__ ((__nothrow__)) __attribute__ ((__const__)); extern int pthread_equal (pthread_t __thread1, pthread_t __thread2) __attribute__ ((__nothrow__)); extern int pthread_attr_init (pthread_attr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_destroy (pthread_attr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getdetachstate (__const pthread_attr_t *__attr, int *__detachstate) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setdetachstate (pthread_attr_t *__attr, int __detachstate) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getguardsize (__const pthread_attr_t *__attr, size_t *__guardsize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setguardsize (pthread_attr_t *__attr, size_t __guardsize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getschedparam (__const pthread_attr_t *__restrict __attr, struct sched_param *__restrict __param) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setschedparam (pthread_attr_t *__restrict __attr, __const struct sched_param *__restrict __param) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_getschedpolicy (__const pthread_attr_t *__restrict __attr, int *__restrict __policy) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setschedpolicy (pthread_attr_t *__attr, int __policy) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getinheritsched (__const pthread_attr_t *__restrict __attr, int *__restrict __inherit) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setinheritsched (pthread_attr_t *__attr, int __inherit) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getscope (__const pthread_attr_t *__restrict __attr, int *__restrict __scope) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setscope (pthread_attr_t *__attr, int __scope) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getstackaddr (__const pthread_attr_t *__restrict __attr, void **__restrict __stackaddr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__deprecated__)); extern int pthread_attr_setstackaddr (pthread_attr_t *__attr, void *__stackaddr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__deprecated__)); extern int pthread_attr_getstacksize (__const pthread_attr_t *__restrict __attr, size_t *__restrict __stacksize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_attr_setstacksize (pthread_attr_t *__attr, size_t __stacksize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_attr_getstack (__const pthread_attr_t *__restrict __attr, void **__restrict __stackaddr, size_t *__restrict __stacksize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2, 3))); extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr, size_t __stacksize) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 413 "/usr/include/pthread.h" 3 extern int pthread_setschedparam (pthread_t __target_thread, int __policy, __const struct sched_param *__param) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (3))); extern int pthread_getschedparam (pthread_t __target_thread, int *__restrict __policy, struct sched_param *__restrict __param) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2, 3))); extern int pthread_setschedprio (pthread_t __target_thread, int __prio) __attribute__ ((__nothrow__)); # 466 "/usr/include/pthread.h" 3 extern int pthread_once (pthread_once_t *__once_control, void (*__init_routine) (void)) __attribute__ ((__nonnull__ (1, 2))); # 478 "/usr/include/pthread.h" 3 extern int pthread_setcancelstate (int __state, int *__oldstate); extern int pthread_setcanceltype (int __type, int *__oldtype); extern int pthread_cancel (pthread_t __th); extern void pthread_testcancel (void); typedef struct { struct { __jmp_buf __cancel_jmp_buf; int __mask_was_saved; } __cancel_jmp_buf[1]; void *__pad[4]; } __pthread_unwind_buf_t __attribute__ ((__aligned__)); # 512 "/usr/include/pthread.h" 3 struct __pthread_cleanup_frame { void (*__cancel_routine) (void *); void *__cancel_arg; int __do_it; int __cancel_type; }; # 652 "/usr/include/pthread.h" 3 extern void __pthread_register_cancel (__pthread_unwind_buf_t *__buf) __attribute__ ((__regparm__ (1))); # 664 "/usr/include/pthread.h" 3 extern void __pthread_unregister_cancel (__pthread_unwind_buf_t *__buf) __attribute__ ((__regparm__ (1))); # 705 "/usr/include/pthread.h" 3 extern void __pthread_unwind_next (__pthread_unwind_buf_t *__buf) __attribute__ ((__regparm__ (1))) __attribute__ ((__noreturn__)) __attribute__ ((__weak__)) ; struct __jmp_buf_tag; extern int __sigsetjmp (struct __jmp_buf_tag *__env, int __savemask) __attribute__ ((__nothrow__)); extern int pthread_mutex_init (pthread_mutex_t *__mutex, __const pthread_mutexattr_t *__mutexattr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutex_destroy (pthread_mutex_t *__mutex) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutex_trylock (pthread_mutex_t *__mutex) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutex_lock (pthread_mutex_t *__mutex) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutex_timedlock (pthread_mutex_t *__restrict __mutex, __const struct timespec *__restrict __abstime) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_mutex_unlock (pthread_mutex_t *__mutex) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 776 "/usr/include/pthread.h" 3 extern int pthread_mutexattr_init (pthread_mutexattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutexattr_destroy (pthread_mutexattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_mutexattr_getpshared (__const pthread_mutexattr_t * __restrict __attr, int *__restrict __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_mutexattr_setpshared (pthread_mutexattr_t *__attr, int __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 848 "/usr/include/pthread.h" 3 extern int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock, __const pthread_rwlockattr_t *__restrict __attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_tryrdlock (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_timedrdlock (pthread_rwlock_t *__restrict __rwlock, __const struct timespec *__restrict __abstime) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_trywrlock (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlock_timedwrlock (pthread_rwlock_t *__restrict __rwlock, __const struct timespec *__restrict __abstime) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlockattr_init (pthread_rwlockattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlockattr_destroy (pthread_rwlockattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlockattr_getpshared (__const pthread_rwlockattr_t * __restrict __attr, int *__restrict __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_rwlockattr_setpshared (pthread_rwlockattr_t *__attr, int __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_rwlockattr_getkind_np (__const pthread_rwlockattr_t * __restrict __attr, int *__restrict __pref) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_rwlockattr_setkind_np (pthread_rwlockattr_t *__attr, int __pref) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_cond_init (pthread_cond_t *__restrict __cond, __const pthread_condattr_t *__restrict __cond_attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_cond_destroy (pthread_cond_t *__cond) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_cond_signal (pthread_cond_t *__cond) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_cond_broadcast (pthread_cond_t *__cond) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_cond_wait (pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex) __attribute__ ((__nonnull__ (1, 2))); # 960 "/usr/include/pthread.h" 3 extern int pthread_cond_timedwait (pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex, __const struct timespec *__restrict __abstime) __attribute__ ((__nonnull__ (1, 2, 3))); extern int pthread_condattr_init (pthread_condattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_condattr_destroy (pthread_condattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_condattr_getpshared (__const pthread_condattr_t * __restrict __attr, int *__restrict __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_condattr_setpshared (pthread_condattr_t *__attr, int __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_condattr_getclock (__const pthread_condattr_t * __restrict __attr, __clockid_t *__restrict __clock_id) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_condattr_setclock (pthread_condattr_t *__attr, __clockid_t __clock_id) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 1004 "/usr/include/pthread.h" 3 extern int pthread_spin_init (pthread_spinlock_t *__lock, int __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_spin_destroy (pthread_spinlock_t *__lock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_spin_lock (pthread_spinlock_t *__lock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_spin_trylock (pthread_spinlock_t *__lock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_spin_unlock (pthread_spinlock_t *__lock) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrier_init (pthread_barrier_t *__restrict __barrier, __const pthread_barrierattr_t *__restrict __attr, unsigned int __count) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrier_destroy (pthread_barrier_t *__barrier) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrier_wait (pthread_barrier_t *__barrier) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrierattr_init (pthread_barrierattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrierattr_destroy (pthread_barrierattr_t *__attr) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_barrierattr_getpshared (__const pthread_barrierattr_t * __restrict __attr, int *__restrict __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2))); extern int pthread_barrierattr_setpshared (pthread_barrierattr_t *__attr, int __pshared) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); # 1071 "/usr/include/pthread.h" 3 extern int pthread_key_create (pthread_key_t *__key, void (*__destr_function) (void *)) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1))); extern int pthread_key_delete (pthread_key_t __key) __attribute__ ((__nothrow__)); extern void *pthread_getspecific (pthread_key_t __key) __attribute__ ((__nothrow__)); extern int pthread_setspecific (pthread_key_t __key, __const void *__pointer) __attribute__ ((__nothrow__)) ; extern int pthread_getcpuclockid (pthread_t __thread_id, __clockid_t *__clock_id) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2))); # 1105 "/usr/include/pthread.h" 3 extern int pthread_atfork (void (*__prepare) (void), void (*__parent) (void), void (*__child) (void)) __attribute__ ((__nothrow__)); # 1119 "/usr/include/pthread.h" 3 # 4 "wronglock_bad.c" 2 # 1 "/usr/include/assert.h" 1 3 # 66 "/usr/include/assert.h" 3 extern void __assert_fail (__const char *__assertion, __const char *__file, unsigned int __line, __const char *__function) __attribute__ ((__nothrow__)) __attribute__ ((__noreturn__)); extern void __assert_perror_fail (int __errnum, __const char *__file, unsigned int __line, __const char *__function) __attribute__ ((__nothrow__)) __attribute__ ((__noreturn__)); extern void __assert (const char *__assertion, const char *__file, int __line) __attribute__ ((__nothrow__)) __attribute__ ((__noreturn__)); # 5 "wronglock_bad.c" 2 static int iNum1 = 1; static int iNum2 = 3; static volatile int dataValue = 0; pthread_mutex_t *dataLock; pthread_mutex_t *thisLock; void lock(pthread_mutex_t *); void unlock(pthread_mutex_t *); void *funcA(void *param) { lock(dataLock); int x = dataValue; dataValue++; if (dataValue != (x+1)) { fprintf(stderr, "Bug Found!\n"); ((0) ? (void) (0) : __assert_fail ("0", "wronglock_bad.c", 23, __PRETTY_FUNCTION__)); } unlock(dataLock); return ((void *)0); } void *funcB(void *param) { lock(thisLock); dataValue++; unlock(thisLock); return ((void *)0); } int main(int argc, char *argv[]) { int i,err; if (argc != 1) { if (argc != 3) { fprintf(stderr, "./wronglock <param1> <param2>\n"); exit(-1); } else { sscanf(argv[1], "%d", &iNum1); sscanf(argv[2], "%d", &iNum2); } } dataLock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); thisLock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); if (0 != (err = pthread_mutex_init(dataLock, ((void *)0)))) { fprintf(stderr, "pthread_mutex_init error: %d\n", err); exit(-1); } if (0 != (err = pthread_mutex_init(thisLock, ((void *)0)))) { fprintf(stderr, "pthread_mutex_init error: %d\n", err); exit(-1); } pthread_t num1Pool[iNum1]; pthread_t num2Pool[iNum2]; for (i = 0; i < iNum1; i++) { if (0 != (err = pthread_create(&num1Pool[i], ((void *)0), &funcA, ((void *)0)))) { fprintf(stderr, "Error [%d] found creating num1 thread.\n", err); exit(-1); } } for (i = 0; i < iNum2; i++) { if (0 != (err = pthread_create(&num2Pool[i], ((void *)0), &funcB, ((void *)0)))) { fprintf(stderr, "Error [%d] found creating num2 thread.\n", err); exit(-1); } } for (i = 0; i < iNum1; i++) { if (0 != (err = pthread_join(num1Pool[i], ((void *)0)))) { fprintf(stderr, "pthread join error: %d\n", err); exit(-1); } } for (i = 0; i < iNum2; i++) { if (0 != (err = pthread_join(num2Pool[i], ((void *)0)))) { fprintf(stderr, "pthread join error: %d\n", err); exit(-1); } } return 0; } void lock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_lock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_lock.\n", err); exit(-1); } } void unlock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_unlock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_unlock.\n", err); exit(-1); } }
the_stack_data/62638649.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned char input[1] , unsigned char 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 char input[1] , unsigned char output[1] ) { unsigned char state[1] ; { state[0UL] = (input[0UL] | 51238316UL) >> (unsigned char)3; if ((state[0UL] >> (unsigned char)3) & (unsigned char)1) { if ((state[0UL] >> (unsigned char)4) & (unsigned char)1) { if (state[0UL] & (unsigned char)1) { state[0UL] >>= (state[0UL] & (unsigned char)7) | 1UL; state[0UL] <<= ((state[0UL] >> (unsigned char)1) & (unsigned char)7) | 1UL; } else { state[0UL] >>= ((state[0UL] >> (unsigned char)4) & (unsigned char)7) | 1UL; state[0UL] <<= (state[0UL] & (unsigned char)7) | 1UL; } } else if (state[0UL] & (unsigned char)1) { state[0UL] <<= ((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL; state[0UL] >>= ((state[0UL] >> (unsigned char)1) & (unsigned char)7) | 1UL; } else { state[0UL] >>= ((state[0UL] >> (unsigned char)4) & (unsigned char)7) | 1UL; state[0UL] >>= ((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL; } } else { state[0UL] >>= ((state[0UL] >> (unsigned char)1) & (unsigned char)7) | 1UL; state[0UL] >>= ((state[0UL] >> (unsigned char)2) & (unsigned char)7) | 1UL; } output[0UL] = (state[0UL] | 922086874UL) | (unsigned char)175; } } int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == (unsigned char)42) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void megaInit(void) { { } }
the_stack_data/3263525.c
#if 0 mini_strstr mini_buf 128 globals_on_stack mini_start shrinkelf INCLUDESRC LDSCRIPT default OPTFLAG -Os return #endif int main(){ volatile int ret=42; volatile const char * a1=""; volatile const char * a2=""; strstr(a1,a2); return(ret); }
the_stack_data/7035.c
int main() { int x; #pragma omp parallel { x = 0; 0; if (1) { 2; #pragma omp barrier x; 3; } else { 4; while (5) { 6; #pragma omp barrier 7; } 8; } 9; #pragma omp barrier 10; } }
the_stack_data/153266834.c
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> int main() { // message that the server will send to the client char server_message[256] = "You have reached the server!"; // create the server socket int server_socket; server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (server_socket == -1) { perror("Server socket creation failed!"); exit(0); } // define the server address struct sockaddr_in server_address, client_address; // use IPv4 addresses server_address.sin_family = AF_INET; // use port 9302 server_address.sin_port = htons(9302); // bind socket to all available network interfaces // including the localhost 127.0.0.1 server_address.sin_addr.s_addr = INADDR_ANY; // bind the socket to our specified IP and port int b_code = bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)); if (b_code < 0) { perror("Failed to bind socket to IP & port"); exit(0); } // receive data from client char buf[256]; int size = sizeof(client_address); recvfrom(server_socket, buf, 256, 0, (struct sockaddr *) &client_address, &size); printf("Server received: %s\n", buf); // send data to the client sendto(server_socket, server_message, sizeof(server_message), 0, (struct sockaddr*) &client_address, sizeof(client_address)); printf("Server sent: %s\n", server_message); // close the socket close(server_socket); return 0; }
the_stack_data/9512542.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <zlib.h> typedef struct _tar_header { /* byte offset */ char name[100]; /* 0 */ char mode[8]; /* 100 */ char uid[8]; /* 108 */ char gid[8]; /* 116 */ char size[12]; /* 124 */ char mtime[12]; /* 136 */ char chksum[8]; /* 148 */ char typeflag; /* 156 */ char linkname[100]; /* 157 */ char magic[6]; /* 257 */ char version[2]; /* 263 */ char uname[32]; /* 265 */ char gname[32]; /* 297 */ char devmajor[8]; /* 329 */ char devminor[8]; /* 337 */ char prefix[155]; /* 345 */ char padding[12]; /* 500 */ }tar_header; int GetSize(char size[12]) { int res = 0; int i = 0; for(i = 0 ; i < 12 ; i++) { if(size[i] == 0) break; res = res * 8 + size[i] -'0'; } return res; } char *GetTarFile(char *tarfile, char *targetfile, int *size) { char *targetContent = NULL; gzFile test = gzopen(tarfile,"r"); int offset = 0; *size = 0; if(test == NULL) { return NULL; } char c[512]; while(1) { memset(c,0,sizeof(c)); int ret = gzread(test,c,512); offset += 512; if(ret <= 0) { break; } tar_header *head = (tar_header *) c; if(strncmp(head->magic, "ustar ", 6) != 0) { break; } int csize = GetSize(head->size); int bsize = ((csize + 511) / 512) * 512; int len = strlen(targetfile); if(len > 100) len = 100; offset += bsize; if(strncmp(head->name,targetfile,len) == 0) { targetContent = (char *)malloc(bsize); int rc = gzread(test, targetContent, bsize); if(rc < 0) { free(targetContent); *size = 0; return NULL; } *size = csize; } else { gzseek(test, offset, SEEK_SET); } } gzclose(test); return targetContent; }
the_stack_data/421458.c
// UVa 10340 #include <stdio.h> #include <string.h> #define MAXS 1000000 char s[MAXS]; char t[MAXS]; void input() { scanf("%s", t); scanf("%s", s); //printf("%s\n", s); //printf("%s\n", t); } int solve() { int ls = strlen(s); int lt = strlen(t); int p = 0; for (int i = 0; i < ls; i++) { if (t[p] == s[i]) p++; } if (p == lt) return 1; else return 0; } int main() { int c; while ((c = getchar()) != EOF) { ungetc(c, stdin); //printf("%c\n", c); input(); //printf("%s %s\n", s, t); int result = solve(); if (result) printf("Yes\n"); else printf("No\n"); getchar(); } }
the_stack_data/111077331.c
#include <stdio.h> int main() { // store user's input int N; // accept user's input scanf ("%d", &N); // stores the sum unsigned long long int sum = 0; // compute the sum for (int i = 0; i <= N; ++i) sum = sum + i; // print the sum printf ("%llu\n", sum); // successful exit return 0; }
the_stack_data/149647.c
/** * Copyright (c) 2013 Nicolas Hillegeer <nicolas at hillegeer dot com> * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <X11/X.h> #include <X11/Xlib.h> #include <sys/select.h> #include <sys/time.h> #include <signal.h> #include <time.h> #include <getopt.h> #include <stdio.h> #include <string.h> #include <stdlib.h> static int gIdleTimeout = 1; static int gVerbose = 0; static volatile sig_atomic_t working; static void signalHandler(int signo) { working = 0; } static int setupSignals() { struct sigaction act; memset(&act, 0, sizeof(act)); /* Use the sa_sigaction field because the handles has two additional parameters */ act.sa_handler = signalHandler; act.sa_flags = 0; sigemptyset(&act.sa_mask); if (sigaction(SIGTERM, &act, NULL) == -1) { perror("hhpc: could not register SIGTERM"); return 0; } if (sigaction(SIGHUP, &act, NULL) == -1) { perror("hhpc: could not register SIGHUP"); return 0; } if (sigaction(SIGINT, &act, NULL) == -1) { perror("hhpc: could not register SIGINT"); return 0; } if (sigaction(SIGQUIT, &act, NULL) == -1) { perror("hhpc: could not register SIGQUIT"); return 0; } return 1; } /** * milliseconds over 1000 will be ignored */ static void delay(time_t sec, long msec) { struct timespec sleep; sleep.tv_sec = sec; sleep.tv_nsec = (msec % 1000) * 1000 * 1000; if (nanosleep(&sleep, NULL) == -1) { signalHandler(0); } } /** * generates an empty cursor, * don't forget to destroy the cursor with XFreeCursor * * do we need to use XAllocColor or will it always just work * as I've observed? */ static Cursor nullCursor(Display *dpy, Drawable dw) { XColor color = { 0 }; const char data[] = { 0 }; Pixmap pixmap = XCreateBitmapFromData(dpy, dw, data, 1, 1); Cursor cursor = XCreatePixmapCursor(dpy, pixmap, pixmap, &color, &color, 0, 0); XFreePixmap(dpy, pixmap); return cursor; } /** * returns 0 for failure, 1 for success */ static int grabPointer(Display *dpy, Window win, Cursor cursor, unsigned int mask) { int rc; /* retry until we actually get the pointer (with a suitable delay) * or we get an error we can't recover from. */ while (working) { rc = XGrabPointer(dpy, win, True, mask, GrabModeSync, GrabModeAsync, None, cursor, CurrentTime); switch (rc) { case GrabSuccess: if (gVerbose) fprintf(stderr, "hhpc: succesfully grabbed mouse pointer\n"); return 1; case AlreadyGrabbed: if (gVerbose) fprintf(stderr, "hhpc: XGrabPointer: already grabbed mouse pointer, retrying with delay\n"); delay(0, 500); break; case GrabFrozen: if (gVerbose) fprintf(stderr, "hhpc: XGrabPointer: grab was frozen, retrying after delay\n"); delay(0, 500); break; case GrabNotViewable: fprintf(stderr, "hhpc: XGrabPointer: grab was not viewable, exiting\n"); return 0; case GrabInvalidTime: fprintf(stderr, "hhpc: XGrabPointer: invalid time, exiting\n"); return 0; default: fprintf(stderr, "hhpc: XGrabPointer: could not grab mouse pointer (%d), exiting\n", rc); return 0; } } return 0; } static void waitForMotion(Display *dpy, Window win, int timeout) { int ready = 0; int xfd = ConnectionNumber(dpy); const unsigned int mask = PointerMotionMask | ButtonPressMask; fd_set fds; XEvent event; Cursor emptyCursor = nullCursor(dpy, win); working = 1; if (!setupSignals()) { fprintf(stderr, "hhpc: could not register signals, program will not exit cleanly\n"); } while (working && grabPointer(dpy, win, emptyCursor, mask)) { /* we grab in sync mode, which stops pointer events from processing, * so we explicitly have to re-allow it with XAllowEvents. The old * method was to just grab in async mode so we wouldn't need this, * but that disables replaying the pointer events */ XAllowEvents(dpy, SyncPointer, CurrentTime); /* syncing is necessary, otherwise the X11 FD will never receive an * event (and thus will never be ready, strangely enough) */ XSync(dpy, False); /* add the X11 fd to the fdset so we can poll/select on it */ FD_ZERO(&fds); FD_SET(xfd, &fds); /* we poll on the X11 fd to see if an event has come in, select() * is interruptible by signals, which allows ctrl+c to work. If we * were to just use XNextEvent() (which blocks), ctrl+c would not * work. */ ready = select(xfd + 1, &fds, NULL, NULL, NULL); if (ready > 0) { if (gVerbose) fprintf(stderr, "hhpc: event received, ungrabbing and sleeping\n"); /* event received, replay event, release mouse, drain, sleep, regrab */ XAllowEvents(dpy, ReplayPointer, CurrentTime); XUngrabPointer(dpy, CurrentTime); /* drain events */ while (XPending(dpy)) { XMaskEvent(dpy, mask, &event); if (gVerbose) fprintf(stderr, "hhpc: draining event\n"); } delay(timeout, 0); } else if (ready == 0) { if (gVerbose) fprintf(stderr, "hhpc: timeout\n"); } else { if (working) perror("hhpc: error while select()'ing"); } } XUngrabPointer(dpy, CurrentTime); XFreeCursor(dpy, emptyCursor); } static int parseOptions(int argc, char *argv[]) { int option = 0; while ((option = getopt(argc, argv, "i:v")) != -1) { switch (option) { case 'i': gIdleTimeout = atoi(optarg); break; case 'v': gVerbose = 1; break; default: return 0; } } return 1; } static void usage() { printf("hhpc [-i] seconds [-v]\n"); } int main(int argc, char *argv[]) { if (!parseOptions(argc, argv)) { usage(); return 1; } char *displayName = getenv("DISPLAY"); Display *dpy = XOpenDisplay(NULL); if (!dpy) { if (!displayName || strlen(displayName) == 0) { fprintf(stderr, "hhpc: could not open display, DISPLAY environment variable not set, are you sure the X server is started?\n"); return 2; } else { fprintf(stderr, "hhpc: could not open display %s, check if your X server is running and/or the DISPLAY environment value is correct\n", displayName); return 1; } } int scr = DefaultScreen(dpy); Window rootwin = RootWindow(dpy, scr); if (gVerbose) fprintf(stderr, "hhpc: got root window, screen = %d, display = %p, rootwin = %d\n", scr, (void *) dpy, (int) rootwin); waitForMotion(dpy, rootwin, gIdleTimeout); XCloseDisplay(dpy); return 0; }
the_stack_data/168892638.c
#include <stdio.h> int main() { int vet[5], contneg = 9999, contpos = -9999; for (int i = 0; i < 5; i++) { printf ("enter the number"); scanf ("%d", &vet[i]); if (vet[i] < contneg) { contneg = vet[i]; } if (vet[i] > contpos) { contpos = vet[i]; } } printf ("%d", contpos - contneg); }
the_stack_data/165765615.c
#include<stdio.h> int binary_search(int a[],int lb,int ub,int ele) { int mid; if(lb<ub) { mid=(lb+ub)/2; if(a[mid]==ele) { return (mid+1); } else if(a[mid]<ele) { return binary_search(a,mid+1,ub,ele); } else { return binary_search(a,lb,mid-1,ele); } } else { return -1; } } int main() { int n,i,pos,ele; printf("enter the size of array\n"); scanf("%d",&n); int a[n]; printf("enter the elements\n"); for(i=0;i<n;++i) { scanf("%d",&a[i]); } printf("enter the element to be searched\n"); scanf("%d",&ele); int flag=0; for(i=0;i<n;++i) { if(a[i]==ele) { flag=1; } } if(flag==1) { pos=binary_search(a,0,n-1,ele); printf("\nthe element found at position= %d",pos); } else { printf("element not found\n"); } return 0; }
the_stack_data/231391953.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern int __VERIFIER_nondet_int(void); /* Generated by CIL v. 1.3.7 */ /* print_CIL_Input is true */ int ssl3_connect(void) { int s__info_callback = __VERIFIER_nondet_int(); int s__in_handshake = __VERIFIER_nondet_int(); int s__state ; int s__new_session ; int s__server ; int s__version = __VERIFIER_nondet_int(); int s__type ; int s__init_num ; int s__bbio = __VERIFIER_nondet_int(); int s__wbio = __VERIFIER_nondet_int(); int s__hit = __VERIFIER_nondet_int(); int s__rwstate ; int s__init_buf___0 ; int s__debug = __VERIFIER_nondet_int(); int s__shutdown ; int s__ctx__info_callback = __VERIFIER_nondet_int(); int s__ctx__stats__sess_connect_renegotiate ; int s__ctx__stats__sess_connect ; int s__ctx__stats__sess_hit = __VERIFIER_nondet_int(); int s__ctx__stats__sess_connect_good = __VERIFIER_nondet_int(); int s__s3__change_cipher_spec ; int s__s3__flags ; int s__s3__delay_buf_pop_ret ; int s__s3__tmp__cert_req = __VERIFIER_nondet_int(); int s__s3__tmp__new_compression = __VERIFIER_nondet_int(); int s__s3__tmp__reuse_message = __VERIFIER_nondet_int(); int s__s3__tmp__new_cipher = __VERIFIER_nondet_int(); int s__s3__tmp__new_cipher__algorithms = __VERIFIER_nondet_int(); int s__s3__tmp__next_state___0 ; int s__s3__tmp__new_compression__id = __VERIFIER_nondet_int(); int s__session__cipher ; int s__session__compress_meth ; int buf ; unsigned long tmp ; unsigned long l ; int num1 ; int cb ; int ret ; int new_state ; int state ; int skip ; int tmp___0 ; int tmp___1 = __VERIFIER_nondet_int(); int tmp___2 = __VERIFIER_nondet_int(); int tmp___3 = __VERIFIER_nondet_int(); int tmp___4 = __VERIFIER_nondet_int(); int tmp___5 = __VERIFIER_nondet_int(); int tmp___6 = __VERIFIER_nondet_int(); int tmp___7 = __VERIFIER_nondet_int(); int tmp___8 = __VERIFIER_nondet_int(); int tmp___9 = __VERIFIER_nondet_int(); int blastFlag ; int ag_X ; int ag_Y ; int ag_Z ; int __retres60 ; { s__state = 12292; blastFlag = 0; tmp = __VERIFIER_nondet_int(); cb = 0; ret = -1; skip = 0; tmp___0 = 0; if (s__info_callback != 0) { cb = s__info_callback; } else { if (s__ctx__info_callback != 0) { cb = s__ctx__info_callback; } else { } } s__in_handshake = s__in_handshake + 1; if (tmp___1 + 12288) { if (tmp___2 + 16384) { } else { } } else { } if (s__hit) { ag_Y = 208; } else { ag_Z = 48; } { while (1) { while_0_continue: /* CIL Label */ ; state = s__state; if (s__state == 12292) { goto switch_1_12292; } else { if (s__state == 16384) { goto switch_1_16384; } else { if (s__state == 4096) { goto switch_1_4096; } else { if (s__state == 20480) { goto switch_1_20480; } else { if (s__state == 4099) { goto switch_1_4099; } else { if (s__state == 4368) { goto switch_1_4368; } else { if (s__state == 4369) { goto switch_1_4369; } else { if (s__state == 4384) { goto switch_1_4384; } else { if (s__state == 4385) { goto switch_1_4385; } else { if (s__state == 4400) { goto switch_1_4400; } else { if (s__state == 4401) { goto switch_1_4401; } else { if (s__state == 4416) { goto switch_1_4416; } else { if (s__state == 4417) { goto switch_1_4417; } else { if (s__state == 4432) { goto switch_1_4432; } else { if (s__state == 4433) { goto switch_1_4433; } else { if (s__state == 4448) { goto switch_1_4448; } else { if (s__state == 4449) { goto switch_1_4449; } else { if (s__state == 4464) { goto switch_1_4464; } else { if (s__state == 4465) { goto switch_1_4465; } else { if (s__state == 4466) { goto switch_1_4466; } else { if (s__state == 4467) { goto switch_1_4467; } else { if (s__state == 4480) { goto switch_1_4480; } else { if (s__state == 4481) { goto switch_1_4481; } else { if (s__state == 4496) { goto switch_1_4496; } else { if (s__state == 4497) { goto switch_1_4497; } else { if (s__state == 4512) { goto switch_1_4512; } else { if (s__state == 4513) { goto switch_1_4513; } else { if (s__state == 4528) { goto switch_1_4528; } else { if (s__state == 4529) { goto switch_1_4529; } else { if (s__state == 4560) { goto switch_1_4560; } else { if (s__state == 4561) { goto switch_1_4561; } else { if (s__state == 4352) { goto switch_1_4352; } else { if (s__state == 3) { goto switch_1_3; } else { { goto switch_1_default; if (0) { switch_1_12292: /* CIL Label */ s__new_session = 1; s__state = 4096; s__ctx__stats__sess_connect_renegotiate = s__ctx__stats__sess_connect_renegotiate + 1; switch_1_16384: /* CIL Label */ ; switch_1_4096: /* CIL Label */ ; switch_1_20480: /* CIL Label */ ; switch_1_4099: /* CIL Label */ s__server = 0; if (cb != 0) { } else { } if (s__version + 65280 != 768) { ret = -1; goto end; } else { } s__type = 4096; if ((unsigned long )s__init_buf___0 == (unsigned long )((void *)0)) { buf = __VERIFIER_nondet_int(); if ((unsigned long )buf == (unsigned long )((void *)0)) { ret = -1; goto end; } else { } if (! tmp___3) { ret = -1; goto end; } else { } s__init_buf___0 = buf; } else { } if (! tmp___4) { ret = -1; goto end; } else { } if (! tmp___5) { ret = -1; goto end; } else { } s__state = 4368; s__ctx__stats__sess_connect = s__ctx__stats__sess_connect + 1; s__init_num = 0; goto switch_1_break; switch_1_4368: /* CIL Label */ ; switch_1_4369: /* CIL Label */ s__shutdown = 0; ret = __VERIFIER_nondet_int(); if (blastFlag == 0) { blastFlag = 1; } else { } if (ret <= 0) { goto end; } else { } s__state = 4384; ag_X = s__state - 32; s__init_num = 0; if ((unsigned long )s__bbio != (unsigned long )s__wbio) { } else { } goto switch_1_break; switch_1_4384: /* CIL Label */ ; switch_1_4385: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (blastFlag == 1) { blastFlag = 2; } else { if (blastFlag == 4) { blastFlag = 5; } else { } } if (ret <= 0) { goto end; } else { } s__state = ag_X; if (s__hit) { s__state = s__state | ag_Y; } else { s__state = s__state | ag_Z; } s__init_num = 0; goto switch_1_break; switch_1_4400: /* CIL Label */ ; switch_1_4401: /* CIL Label */ ; if ((unsigned long )s__s3__tmp__new_cipher__algorithms + 256UL) { skip = 1; } else { ret = __VERIFIER_nondet_int(); if (blastFlag == 2) { blastFlag = 3; } else { } if (ret <= 0) { goto end; } else { } } s__state = 4416; s__init_num = 0; goto switch_1_break; switch_1_4416: /* CIL Label */ ; switch_1_4417: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (blastFlag == 3) { blastFlag = 4; } else { } if (ret <= 0) { goto end; } else { } s__state = 4432; s__init_num = 0; if (! tmp___6) { ret = -1; goto end; } else { } goto switch_1_break; switch_1_4432: /* CIL Label */ ; switch_1_4433: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (blastFlag <= 5) { goto ERROR; } else { } if (ret <= 0) { goto end; } else { } s__state = 4448; s__init_num = 0; goto switch_1_break; switch_1_4448: /* CIL Label */ ; switch_1_4449: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } if (s__s3__tmp__cert_req) { s__state = 4464; } else { s__state = 4480; } s__init_num = 0; goto switch_1_break; switch_1_4464: /* CIL Label */ ; switch_1_4465: /* CIL Label */ ; switch_1_4466: /* CIL Label */ ; switch_1_4467: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } s__state = 4480; s__init_num = 0; goto switch_1_break; switch_1_4480: /* CIL Label */ ; switch_1_4481: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } l = s__s3__tmp__new_cipher__algorithms; if (s__s3__tmp__cert_req == 1) { s__state = 4496; } else { s__state = 4512; s__s3__change_cipher_spec = 0; } s__init_num = 0; goto switch_1_break; switch_1_4496: /* CIL Label */ ; switch_1_4497: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } s__state = 4512; s__init_num = 0; s__s3__change_cipher_spec = 0; goto switch_1_break; switch_1_4512: /* CIL Label */ ; switch_1_4513: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } s__state = 4528; s__init_num = 0; s__session__cipher = s__s3__tmp__new_cipher; if (s__s3__tmp__new_compression == 0) { s__session__compress_meth = 0; } else { s__session__compress_meth = s__s3__tmp__new_compression__id; } if (! tmp___7) { ret = -1; goto end; } else { } if (! tmp___8) { ret = -1; goto end; } else { } goto switch_1_break; switch_1_4528: /* CIL Label */ ; switch_1_4529: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } s__state = 4352; s__s3__flags = (long )s__s3__flags + -5L; if (s__hit) { s__s3__tmp__next_state___0 = 3; if ((long )s__s3__flags + 2L) { s__state = 3; s__s3__flags = (long )s__s3__flags * 4L; s__s3__delay_buf_pop_ret = 0; } else { } } else { s__s3__tmp__next_state___0 = 4560; } s__init_num = 0; goto switch_1_break; switch_1_4560: /* CIL Label */ ; switch_1_4561: /* CIL Label */ ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } if (s__hit) { s__state = 4512; } else { s__state = 3; } s__init_num = 0; goto switch_1_break; switch_1_4352: /* CIL Label */ if ((long )num1 > 0L) { s__rwstate = 2; num1 = (long )tmp___9; if ((long )num1 <= 0L) { ret = -1; goto end; } else { } s__rwstate = 1; } else { } s__state = s__s3__tmp__next_state___0; goto switch_1_break; switch_1_3: /* CIL Label */ if (s__init_buf___0 != 0) { s__init_buf___0 = 0; } else { } if (! ((long )s__s3__flags + 4L)) { } else { } s__init_num = 0; s__new_session = 0; if (s__hit) { s__ctx__stats__sess_hit = s__ctx__stats__sess_hit + 1; } else { } ret = 1; s__ctx__stats__sess_connect_good = s__ctx__stats__sess_connect_good + 1; if (cb != 0) { } else { } goto end; switch_1_default: /* CIL Label */ ret = -1; goto end; } else { switch_1_break: /* CIL Label */ ; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } if (! s__s3__tmp__reuse_message) { if (! skip) { if (s__debug) { ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } else { } } else { } if (cb != 0) { if (s__state != state) { new_state = s__state; s__state = state; s__state = new_state; } else { } } else { } } else { } } else { } skip = 0; } while_0_break: /* CIL Label */ ; } end: s__in_handshake = s__in_handshake - 1; if (cb != 0) { } else { } __retres60 = ret; goto return_label; ERROR: __VERIFIER_error(); { } __retres60 = -1; return_label: /* CIL Label */ return (__retres60); } } int main(void) { int __retres1 ; { { ssl3_connect(); } __retres1 = 0; return (__retres1); } }
the_stack_data/67738.c
#include <stdio.h> #include <string.h> #define MAX_LEN 10000 int wcount (char *s); int main () { char str_arr[MAX_LEN]; int am; gets (str_arr); am = wcount (str_arr); printf ("%d\n", am); return 0; } int wcount (char *s) { int counter=0; int status=0; char *car_ptr; for (car_ptr=s; *car_ptr!=0; car_ptr++) { if (status==0) { if (*car_ptr!=' ') { status=1; ++counter; } } if (status==1) { if (*car_ptr==' ') status=0; } } return (counter); }
the_stack_data/184518839.c
/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <[email protected]>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks [email protected]) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From [email protected] and [email protected] - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <[email protected]> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED #include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be called. // The current downside is the times written to your archives will be from 1979. //#define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. //#define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) #include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1, } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; #include <string.h> #include <assert.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a,b) (((a)>(b))?(a):(b)) #define MZ_MIN(a,b) (((a)<(b))?(a):(b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for ( ; ; ) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state* pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state*)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for ( ; ; ) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = { { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif //MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN switch(r->m_state) { case 0: #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for ( ; ; ) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else c = *pIn_buf_cur++; } MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ int temp; mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for ( i = 0; i <= 143; ++i) { *p++ = 8; } for ( ; i <= 255; ++i) { *p++ = 9; } for ( ; i <= 279; ++i) { *p++ = 7; } for ( ; i <= 287; ++i) { *p++ = 8; } } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for ( ; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for ( ; ; ) { mz_uint8 *pSrc; for ( ; ; ) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for ( ; ; ) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for ( ; ; ) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; static const mz_uint8 s_tdefl_len_extra[256] = { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 }; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32* pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, [email protected], Jyrki Katajainen, [email protected], November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next=1; next < n-1; next++) { if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; avbl = 1; used = dpth = 0; root = n-2; next = n-1; while (avbl>0) { while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2*used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) do { \ mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ } rle_repeat_count = 0; } } #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ } rle_z_count = 0; } } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64*)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) { break; } q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) { continue; } p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output buffer. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif //MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size-41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0, (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } #ifdef _MSC_VER #pragma warning (pop) #endif // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE* pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE* pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for ( ; ; ) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for ( ; ; ) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for ( ; ; ) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for ( ; ; ) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */
the_stack_data/25136938.c
# 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" # 35 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 1 # 47 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_null.h" 1 # 48 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" 1 # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/cdefs.h" 1 # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/cdefs.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cdefs.h" 1 # 42 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/cdefs.h" 2 # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/endian.h" 1 # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/endian.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_endian.h" 1 # 36 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_endian.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_types.h" 1 # 37 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_types.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/_types.h" 1 # 54 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/_types.h" typedef struct label_t { long val[8]; } label_t; typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef short __int16_t; typedef unsigned short __uint16_t; typedef int __int32_t; typedef unsigned int __uint32_t; typedef long long __int64_t; typedef unsigned long long __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 __int32_t __int_fast8_t; typedef __uint32_t __uint_fast8_t; typedef __int32_t __int_fast16_t; typedef __uint32_t __uint_fast16_t; typedef __int32_t __int_fast32_t; typedef __uint32_t __uint_fast32_t; typedef __int64_t __int_fast64_t; typedef __uint64_t __uint_fast64_t; # 102 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/_types.h" typedef long __intptr_t; typedef unsigned long __uintptr_t; typedef __int64_t __intmax_t; typedef __uint64_t __uintmax_t; typedef long __register_t; typedef unsigned long __vaddr_t; typedef unsigned long __paddr_t; typedef unsigned long __vsize_t; typedef unsigned long __psize_t; typedef double __double_t; typedef float __float_t; typedef long __ptrdiff_t; typedef unsigned long __size_t; typedef long __ssize_t; typedef __builtin_va_list __va_list; typedef int __wchar_t; typedef int __wint_t; typedef int __rune_t; typedef void * __wctrans_t; typedef void * __wctype_t; # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_types.h" 2 typedef __int64_t __blkcnt_t; typedef __int32_t __blksize_t; typedef __int64_t __clock_t; typedef __int32_t __clockid_t; typedef unsigned long __cpuid_t; typedef __int32_t __dev_t; typedef __uint32_t __fixpt_t; typedef __uint64_t __fsblkcnt_t; typedef __uint64_t __fsfilcnt_t; typedef __uint32_t __gid_t; typedef __uint32_t __id_t; typedef __uint32_t __in_addr_t; typedef __uint16_t __in_port_t; typedef __uint64_t __ino_t; typedef long __key_t; typedef __uint32_t __mode_t; typedef __uint32_t __nlink_t; typedef __int64_t __off_t; typedef __int32_t __pid_t; typedef __uint64_t __rlim_t; typedef __uint8_t __sa_family_t; typedef __int32_t __segsz_t; typedef __uint32_t __socklen_t; typedef long __suseconds_t; typedef __int32_t __swblk_t; typedef __int64_t __time_t; typedef __int32_t __timer_t; typedef __uint32_t __uid_t; typedef __uint32_t __useconds_t; typedef union { char __mbstate8[128]; __int64_t __mbstateL; } __mbstate_t; # 37 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_endian.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/endian.h" 1 # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_endian.h" 2 # 42 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/endian.h" 2 # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" 2 typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned char unchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef __cpuid_t cpuid_t; typedef __register_t register_t; # 75 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" typedef __int8_t int8_t; typedef __uint8_t uint8_t; typedef __int16_t int16_t; typedef __uint16_t uint16_t; typedef __int32_t int32_t; typedef __uint32_t uint32_t; typedef __int64_t int64_t; typedef __uint64_t uint64_t; 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 __int64_t quad_t; typedef __uint64_t u_quad_t; typedef __vaddr_t vaddr_t; typedef __paddr_t paddr_t; typedef __vsize_t vsize_t; typedef __psize_t psize_t; typedef __blkcnt_t blkcnt_t; typedef __blksize_t blksize_t; typedef char * caddr_t; typedef __int32_t daddr32_t; typedef __int64_t daddr_t; typedef __dev_t dev_t; typedef __fixpt_t fixpt_t; typedef __gid_t gid_t; typedef __id_t id_t; typedef __ino_t ino_t; typedef __key_t key_t; typedef __mode_t mode_t; typedef __nlink_t nlink_t; typedef __rlim_t rlim_t; typedef __segsz_t segsz_t; typedef __swblk_t swblk_t; typedef __uid_t uid_t; typedef __useconds_t useconds_t; typedef __suseconds_t suseconds_t; typedef __fsblkcnt_t fsblkcnt_t; typedef __fsfilcnt_t fsfilcnt_t; # 162 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" typedef __in_addr_t in_addr_t; typedef __in_port_t in_port_t; typedef __clock_t clock_t; typedef __clockid_t clockid_t; typedef __pid_t pid_t; typedef __size_t size_t; typedef __ssize_t ssize_t; typedef __time_t time_t; typedef __timer_t timer_t; typedef __off_t off_t; # 234 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/types.h" struct proc; struct pgrp; struct ucred; struct rusage; struct file; struct buf; struct tty; struct uio; # 51 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 60 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/syslimits.h" 1 # 61 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 75 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/errno.h" 1 # 76 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" 1 # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/select.h" 1 # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/select.h" struct timeval { time_t tv_sec; suseconds_t tv_usec; }; struct timespec { time_t tv_sec; long tv_nsec; }; # 70 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/select.h" typedef uint32_t __fd_mask; typedef struct fd_set { __fd_mask fds_bits[(((1024) + ((((unsigned)(sizeof(__fd_mask) * 8))) - 1)) / (((unsigned)(sizeof(__fd_mask) * 8))))]; } fd_set; static __inline void __fd_set(int fd, fd_set *p) { p->fds_bits[fd / ((unsigned)(sizeof(__fd_mask) * 8))] |= (1U << (fd % ((unsigned)(sizeof(__fd_mask) * 8)))); } static __inline void __fd_clr(int fd, fd_set *p) { p->fds_bits[fd / ((unsigned)(sizeof(__fd_mask) * 8))] &= ~(1U << (fd % ((unsigned)(sizeof(__fd_mask) * 8)))); } static __inline int __fd_isset(int fd, const fd_set *p) { return (p->fds_bits[fd / ((unsigned)(sizeof(__fd_mask) * 8))] & (1U << (fd % ((unsigned)(sizeof(__fd_mask) * 8))))); } # 39 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" 2 # 72 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" struct timezone { int tz_minuteswest; int tz_dsttime; }; # 144 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" struct itimerval { struct timeval it_interval; struct timeval it_value; }; struct clockinfo { int hz; int tick; int tickadj; int stathz; int profhz; }; # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_time.h" 1 # 55 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/_time.h" struct itimerspec { struct timespec it_interval; struct timespec it_value; }; # 164 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" 2 struct bintime { time_t sec; uint64_t frac; }; static __inline void bintime_addx(struct bintime *bt, uint64_t x) { uint64_t u; u = bt->frac; bt->frac += x; if (u > bt->frac) bt->sec++; } static __inline void bintime_add(struct bintime *bt, struct bintime *bt2) { uint64_t u; u = bt->frac; bt->frac += bt2->frac; if (u > bt->frac) bt->sec++; bt->sec += bt2->sec; } static __inline void bintime_sub(struct bintime *bt, struct bintime *bt2) { uint64_t u; u = bt->frac; bt->frac -= bt2->frac; if (u < bt->frac) bt->sec--; bt->sec -= bt2->sec; } # 220 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" static __inline void bintime2timespec(struct bintime *bt, struct timespec *ts) { ts->tv_sec = bt->sec; ts->tv_nsec = (long)(((uint64_t)1000000000 * (uint32_t)(bt->frac >> 32)) >> 32); } static __inline void timespec2bintime(struct timespec *ts, struct bintime *bt) { bt->sec = ts->tv_sec; bt->frac = (uint64_t)ts->tv_nsec * (uint64_t)18446744073ULL; } static __inline void bintime2timeval(struct bintime *bt, struct timeval *tv) { tv->tv_sec = bt->sec; tv->tv_usec = (long)(((uint64_t)1000000 * (uint32_t)(bt->frac >> 32)) >> 32); } static __inline void timeval2bintime(struct timeval *tv, struct bintime *bt) { bt->sec = (time_t)tv->tv_sec; bt->frac = (uint64_t)tv->tv_usec * (uint64_t)18446744073709ULL; } extern volatile time_t time_second; extern volatile time_t time_uptime; # 278 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/time.h" void bintime(struct bintime *); void nanotime(struct timespec *); void microtime(struct timeval *); void getnanotime(struct timespec *); void getmicrotime(struct timeval *); void binuptime(struct bintime *); void nanouptime(struct timespec *); void microuptime(struct timeval *); void getnanouptime(struct timespec *); void getmicrouptime(struct timeval *); struct proc; int clock_gettime(struct proc *, clockid_t, struct timespec *); int timespecfix(struct timespec *); int itimerfix(struct timeval *); int itimerdecr(struct itimerval *itp, int usec); void itimerround(struct timeval *); int settime(struct timespec *); int ratecheck(struct timeval *, const struct timeval *); int ppsratecheck(struct timeval *, int *, int); struct clock_ymdhms { u_short dt_year; u_char dt_mon; u_char dt_day; u_char dt_wday; u_char dt_hour; u_char dt_min; u_char dt_sec; }; time_t clock_ymdhms_to_secs(struct clock_ymdhms *); void clock_secs_to_ymdhms(time_t, struct clock_ymdhms *); # 77 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/resource.h" 1 # 58 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/resource.h" struct rusage { struct timeval ru_utime; struct timeval ru_stime; long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; # 98 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/resource.h" struct rlimit { rlim_t rlim_cur; rlim_t rlim_max; }; struct loadavg { fixpt_t ldavg[3]; long fscale; }; extern struct loadavg averunnable; struct process; int dosetrlimit(struct proc *, u_int, struct rlimit *); int donice(struct proc *, struct process *, int); int dogetrusage(struct proc *, int, struct rusage *); # 78 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ucred.h" 1 # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ucred.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/syslimits.h" 1 # 39 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ucred.h" 2 struct ucred { u_int cr_ref; uid_t cr_uid; uid_t cr_ruid; uid_t cr_svuid; gid_t cr_gid; gid_t cr_rgid; gid_t cr_svgid; short cr_ngroups; gid_t cr_groups[16]; }; struct xucred { uid_t cr_uid; gid_t cr_gid; short cr_ngroups; gid_t cr_groups[16]; }; int crfromxucred(struct ucred *, const struct xucred *); void crset(struct ucred *, const struct ucred *); struct ucred *crcopy(struct ucred *cr); struct ucred *crdup(struct ucred *cr); void crfree(struct ucred *cr); struct ucred *crget(void); int suser(struct proc *p, u_int flags); int suser_ucred(struct ucred *cred); # 79 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/uio.h" 1 # 51 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/uio.h" struct iovec { void *iov_base; size_t iov_len; }; enum uio_rw { UIO_READ, UIO_WRITE }; enum uio_seg { UIO_USERSPACE, UIO_SYSSPACE }; struct uio { struct iovec *uio_iov; int uio_iovcnt; off_t uio_offset; size_t uio_resid; enum uio_seg uio_segflg; enum uio_rw uio_rw; struct proc *uio_procp; }; # 97 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/uio.h" int ureadc(int c, struct uio *); struct file; int dofilereadv(struct proc *, int, struct file *, const struct iovec *, int, int, off_t *, register_t *); int dofilewritev(struct proc *, int, struct file *, const struct iovec *, int, int, off_t *, register_t *); # 80 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/srp.h" 1 # 22 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/srp.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/refcnt.h" 1 # 22 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/refcnt.h" struct refcnt { unsigned int refs; }; void refcnt_init(struct refcnt *); void refcnt_take(struct refcnt *); int refcnt_rele(struct refcnt *); void refcnt_rele_wake(struct refcnt *); void refcnt_finalize(struct refcnt *, const char *); # 23 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/srp.h" 2 # 32 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/srp.h" struct srp { void *ref; }; struct srp_hazard { struct srp *sh_p; void *sh_v; }; struct srp_ref { struct srp_hazard *hz; } __attribute__((__unused__)); struct srp_gc { void (*srp_gc_dtor)(void *, void *); void *srp_gc_cookie; struct refcnt srp_gc_refcnt; }; struct srpl_rc { void (*srpl_ref)(void *, void *); struct srp_gc srpl_gc; }; struct srpl { struct srp sl_head; }; void srp_startup(void); void srp_gc_init(struct srp_gc *, void (*)(void *, void *), void *); void *srp_swap_locked(struct srp *, void *); void srp_update_locked(struct srp_gc *, struct srp *, void *); void *srp_get_locked(struct srp *); void srp_gc_finalize(struct srp_gc *); void srp_init(struct srp *); # 101 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/srp.h" void srpl_rc_init(struct srpl_rc *, void (*)(void *, void *), void (*)(void *, void *), void *); # 81 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" 1 # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/signal.h" 1 # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/signal.h" typedef int sig_atomic_t; # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/trap.h" 1 # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/signal.h" 2 # 54 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/signal.h" struct sigcontext { long sc_rdi; long sc_rsi; long sc_rdx; long sc_rcx; long sc_r8; long sc_r9; long sc_r10; long sc_r11; long sc_r12; long sc_r13; long sc_r14; long sc_r15; long sc_rbp; long sc_rbx; long sc_rax; long sc_gs; long sc_fs; long sc_es; long sc_ds; long sc_trapno; long sc_err; long sc_rip; long sc_cs; long sc_rflags; long sc_rsp; long sc_ss; struct fxsave64 *sc_fpstate; int __sc_unused; int sc_mask; long sc_cookie; }; # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" 2 # 104 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" typedef unsigned int sigset_t; # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/siginfo.h" 1 # 33 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/siginfo.h" union sigval { int sival_int; void *sival_ptr; }; # 132 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/siginfo.h" typedef struct { int si_signo; int si_code; int si_errno; union { int _pad[((128 / sizeof (int)) - 3)]; struct { pid_t _pid; union { struct { uid_t _uid; union sigval _value; } _kill; struct { clock_t _utime; clock_t _stime; int _status; } _cld; } _pdata; } _proc; struct { caddr_t _addr; int _trapno; } _fault; # 172 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/siginfo.h" } _data; } siginfo_t; # 196 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/siginfo.h" void initsiginfo(siginfo_t *, int, u_long, int, union sigval); # 108 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" 2 struct sigaction { union { void (*__sa_handler)(int); void (*__sa_sigaction)(int, siginfo_t *, void *); } __sigaction_u; sigset_t sa_mask; int sa_flags; }; # 146 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" typedef void (*sig_t)(int); struct sigvec { void (*sv_handler)(int); int sv_mask; int sv_flags; }; # 176 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/signal.h" typedef struct sigaltstack { void *ss_sp; size_t ss_size; int ss_flags; } stack_t; typedef struct sigcontext ucontext_t; # 85 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/limits.h" 1 # 34 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/limits.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/limits.h" 1 # 35 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/limits.h" 2 # 88 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/param.h" 1 # 42 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/param.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 1 # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/frame.h" 1 # 75 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/frame.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/fpu.h" 1 # 16 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/fpu.h" struct fxsave64 { u_int16_t fx_fcw; u_int16_t fx_fsw; u_int8_t fx_ftw; u_int8_t fx_unused1; u_int16_t fx_fop; u_int64_t fx_rip; u_int64_t fx_rdp; u_int32_t fx_mxcsr; u_int32_t fx_mxcsr_mask; u_int64_t fx_st[8][2]; u_int64_t fx_xmm[16][2]; u_int8_t fx_unused3[96]; } __attribute__((__packed__)); struct xstate_hdr { uint64_t xstate_bv; uint64_t xstate_xcomp_bv; uint8_t xstate_rsrv0[0]; uint8_t xstate_rsrv[40]; } __attribute__((__packed__)); struct savefpu { struct fxsave64 fp_fxsave; struct xstate_hdr fp_xstate; u_int64_t fp_ymm[16][2]; u_int16_t fp_ex_sw; u_int16_t fp_ex_tw; }; # 58 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/fpu.h" struct trapframe; struct cpu_info; extern size_t fpu_save_len; extern uint32_t fpu_mxcsr_mask; extern uint64_t xsave_mask; void fpuinit(struct cpu_info *); void fpudrop(void); void fpudiscard(struct proc *); void fputrap(struct trapframe *); void fpusave_proc(struct proc *, int); void fpusave_cpu(struct cpu_info *, int); void fpu_kernel_enter(void); void fpu_kernel_exit(void); # 76 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/frame.h" 2 # 84 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/frame.h" struct trapframe { int64_t tf_rdi; int64_t tf_rsi; int64_t tf_rdx; int64_t tf_rcx; int64_t tf_r8; int64_t tf_r9; int64_t tf_r10; int64_t tf_r11; int64_t tf_r12; int64_t tf_r13; int64_t tf_r14; int64_t tf_r15; int64_t tf_rbp; int64_t tf_rbx; int64_t tf_rax; int64_t tf_gs; int64_t tf_fs; int64_t tf_es; int64_t tf_ds; int64_t tf_trapno; int64_t tf_err; int64_t tf_rip; int64_t tf_cs; int64_t tf_rflags; int64_t tf_rsp; int64_t tf_ss; }; struct intrframe { int64_t if_ppl; int64_t if_rdi; int64_t if_rsi; int64_t if_rdx; int64_t if_rcx; int64_t if_r8; int64_t if_r9; int64_t if_r10; int64_t if_r11; int64_t if_r12; int64_t if_r13; int64_t if_r14; int64_t if_r15; int64_t if_rbp; int64_t if_rbx; int64_t if_rax; int64_t tf_gs; int64_t tf_fs; int64_t tf_es; int64_t tf_ds; u_int64_t __if_trapno; u_int64_t __if_err; int64_t if_rip; int64_t if_cs; int64_t if_rflags; int64_t if_rsp; int64_t if_ss; }; struct switchframe { int64_t sf_r15; int64_t sf_r14; int64_t sf_r13; int64_t sf_r12; int64_t sf_rbp; int64_t sf_rbx; int64_t sf_rip; }; struct callframe { struct callframe *f_frame; long f_retaddr; long f_arg0; }; # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/segments.h" 1 # 95 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/segments.h" struct sys_segment_descriptor { u_int64_t sd_lolimit:16; u_int64_t sd_lobase:24; u_int64_t sd_type:5; u_int64_t sd_dpl:2; u_int64_t sd_p:1; u_int64_t sd_hilimit:4; u_int64_t sd_xx1:3; u_int64_t sd_gran:1; u_int64_t sd_hibase:40; u_int64_t sd_xx2:8; u_int64_t sd_zero:5; u_int64_t sd_xx3:19; } __attribute__((__packed__)); struct mem_segment_descriptor { unsigned int sd_lolimit:16; unsigned int sd_lobase:24; unsigned int sd_type:5; unsigned int sd_dpl:2; unsigned int sd_p:1; unsigned int sd_hilimit:4; unsigned int sd_avl:1; unsigned int sd_long:1; unsigned int sd_def32:1; unsigned int sd_gran:1; unsigned int sd_hibase:8; } __attribute__((__packed__)); struct gate_descriptor { u_int64_t gd_looffset:16; u_int64_t gd_selector:16; u_int64_t gd_ist:3; u_int64_t gd_xx1:5; u_int64_t gd_type:5; u_int64_t gd_dpl:2; u_int64_t gd_p:1; u_int64_t gd_hioffset:48; u_int64_t gd_xx2:8; u_int64_t gd_zero:5; u_int64_t gd_xx3:19; } __attribute__((__packed__)); struct region_descriptor { u_int16_t rd_limit; u_int64_t rd_base; } __attribute__((__packed__)); extern struct gate_descriptor *idt; void setgate(struct gate_descriptor *, void *, int, int, int, int); void unsetgate(struct gate_descriptor *); void setregion(struct region_descriptor *, void *, u_int16_t); void set_sys_segment(struct sys_segment_descriptor *, void *, size_t, int, int, int); void set_mem_segment(struct mem_segment_descriptor *, void *, size_t, int, int, int, int, int); int idt_vec_alloc(int, int); void idt_vec_set(int, void (*)(void)); void idt_vec_free(int); void cpu_init_idt(void); # 47 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cacheinfo.h" 1 struct x86_cache_info { uint8_t cai_index; uint8_t cai_desc; uint8_t cai_associativity; u_int cai_totalsize; u_int cai_linesize; const char *cai_string; }; # 27 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cacheinfo.h" struct cpu_info; const struct x86_cache_info *cache_info_lookup(const struct x86_cache_info *, u_int8_t); void amd_cpu_cacheinfo(struct cpu_info *); void x86_print_cacheinfo(struct cpu_info *); # 48 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intrdefs.h" 1 # 49 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/device.h" 1 # 47 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/device.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/queue.h" 1 # 48 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/device.h" 2 enum devclass { DV_DULL, DV_CPU, DV_DISK, DV_IFNET, DV_TAPE, DV_TTY }; # 72 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/device.h" struct device { enum devclass dv_class; struct { struct device *tqe_next; struct device **tqe_prev; } dv_list; struct cfdata *dv_cfdata; int dv_unit; char dv_xname[16]; struct device *dv_parent; int dv_flags; int dv_ref; }; struct devicelist { struct device *tqh_first; struct device **tqh_last; }; struct cfdata { struct cfattach *cf_attach; struct cfdriver *cf_driver; short cf_unit; short cf_fstate; long *cf_loc; int cf_flags; short *cf_parents; int cf_locnames; short cf_starunit1; }; extern struct cfdata cfdata[]; typedef int (*cfmatch_t)(struct device *, void *, void *); typedef void (*cfscan_t)(struct device *, void *); # 127 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/device.h" struct cfattach { size_t ca_devsize; cfmatch_t ca_match; void (*ca_attach)(struct device *, struct device *, void *); int (*ca_detach)(struct device *, int); int (*ca_activate)(struct device *, int); }; struct cfdriver { void **cd_devs; char *cd_name; enum devclass cd_class; int cd_indirect; int cd_ndevs; }; typedef int (*cfprint_t)(void *, const char *); struct pdevinit { void (*pdev_attach)(int); int pdev_count; }; extern struct devicelist alldevs; extern int autoconf_verbose; extern volatile int config_pending; void config_init(void); void *config_search(cfmatch_t, struct device *, void *); struct device *config_found_sm(struct device *, void *, cfprint_t, cfmatch_t); struct device *config_rootfound(char *, void *); void config_scan(cfscan_t, struct device *); struct device *config_attach(struct device *, void *, void *, cfprint_t); int config_detach(struct device *, int); int config_detach_children(struct device *, int); int config_deactivate(struct device *); int config_suspend(struct device *, int); int config_suspend_all(int); int config_activate_children(struct device *, int); struct device *config_make_softc(struct device *parent, struct cfdata *cf); void config_defer(struct device *, void (*)(struct device *)); void config_pending_incr(void); void config_pending_decr(void); void config_mountroot(struct device *, void (*)(struct device *)); void config_process_deferred_mountroot(void); struct device *device_mainbus(void); struct device *device_mpath(void); struct device *device_lookup(struct cfdriver *, int unit); void device_ref(struct device *); void device_unref(struct device *); struct nam2blk { char *name; int maj; }; int findblkmajor(struct device *dv); char *findblkname(int); void setroot(struct device *, int, int); struct device *getdisk(char *str, int len, int defpart, dev_t *devp); struct device *parsedisk(char *str, int len, int defpart, dev_t *devp); void device_register(struct device *, void *); int loadfirmware(const char *name, u_char **bufp, size_t *buflen); # 52 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sched.h" 1 # 96 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sched.h" struct schedstate_percpu { struct timespec spc_runtime; volatile int spc_schedflags; u_int spc_schedticks; u_int64_t spc_cp_time[5]; u_char spc_curpriority; int spc_rrticks; int spc_pscnt; int spc_psdiv; struct proc *spc_idleproc; u_int spc_nrun; fixpt_t spc_ldavg; struct prochead { struct proc *tqh_first; struct proc **tqh_last; } spc_qs[32]; volatile uint32_t spc_whichqs; struct { struct proc *lh_first; } spc_deadproc; volatile int spc_barrier; }; # 134 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sched.h" extern int schedhz; extern int rrticks_init; struct proc; void schedclock(struct proc *); struct cpu_info; void roundrobin(struct cpu_info *); void scheduler_start(void); void userret(struct proc *p); void sched_init_cpu(struct cpu_info *); void sched_idle(void *); void sched_exit(struct proc *); void mi_switch(void); void cpu_switchto(struct proc *, struct proc *); struct proc *sched_chooseproc(void); struct cpu_info *sched_choosecpu(struct proc *); struct cpu_info *sched_choosecpu_fork(struct proc *parent, int); void cpu_idle_enter(void); void cpu_idle_cycle(void); void cpu_idle_leave(void); void sched_peg_curproc(struct cpu_info *ci); void sched_barrier(struct cpu_info *ci); int sysctl_hwsetperf(void *, size_t *, void *, size_t); int sysctl_hwperfpolicy(void *, size_t *, void *, size_t); # 168 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sched.h" void sched_init_runqueues(void); void setrunqueue(struct proc *); void remrunqueue(struct proc *); # 53 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sensors.h" 1 # 33 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sensors.h" enum sensor_type { SENSOR_TEMP, SENSOR_FANRPM, SENSOR_VOLTS_DC, SENSOR_VOLTS_AC, SENSOR_OHMS, SENSOR_WATTS, SENSOR_AMPS, SENSOR_WATTHOUR, SENSOR_AMPHOUR, SENSOR_INDICATOR, SENSOR_INTEGER, SENSOR_PERCENT, SENSOR_LUX, SENSOR_DRIVE, SENSOR_TIMEDELTA, SENSOR_HUMIDITY, SENSOR_FREQ, SENSOR_ANGLE, SENSOR_DISTANCE, SENSOR_PRESSURE, SENSOR_ACCEL, SENSOR_MAX_TYPES }; # 97 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sensors.h" enum sensor_status { SENSOR_S_UNSPEC, SENSOR_S_OK, SENSOR_S_WARN, SENSOR_S_CRIT, SENSOR_S_UNKNOWN }; struct sensor { char desc[32]; struct timeval tv; int64_t value; enum sensor_type type; enum sensor_status status; int numt; int flags; }; struct sensordev { int num; char xname[16]; int maxnumt[SENSOR_MAX_TYPES]; int sensors_count; }; struct ksensor { struct { struct ksensor *sle_next; } list; char desc[32]; struct timeval tv; int64_t value; enum sensor_type type; enum sensor_status status; int numt; int flags; }; struct ksensors_head { struct ksensor *slh_first; }; struct ksensordev { struct { struct ksensordev *sle_next; } list; int num; char xname[16]; int maxnumt[SENSOR_MAX_TYPES]; int sensors_count; struct ksensors_head sensors_list; }; void sensordev_install(struct ksensordev *); void sensordev_deinstall(struct ksensordev *); int sensordev_get(int, struct ksensordev **); void sensor_attach(struct ksensordev *, struct ksensor *); void sensor_detach(struct ksensordev *, struct ksensor *); int sensor_find(int, enum sensor_type, int, struct ksensor **); struct sensor_task; struct sensor_task *sensor_task_register(void *, void (*)(void *), unsigned int); void sensor_task_unregister(struct sensor_task *); # 54 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 struct vmxon_region { uint32_t vr_revision; }; struct vmx { uint64_t vmx_cr0_fixed0; uint64_t vmx_cr0_fixed1; uint64_t vmx_cr4_fixed0; uint64_t vmx_cr4_fixed1; uint32_t vmx_vmxon_revision; uint32_t vmx_msr_table_size; uint32_t vmx_cr3_tgt_count; uint64_t vmx_vm_func; }; struct svm { }; union vmm_cpu_cap { struct vmx vcc_vmx; struct svm vcc_svm; }; struct x86_64_tss; struct cpu_info { struct device *ci_dev; struct cpu_info *ci_self; struct schedstate_percpu ci_schedstate; struct cpu_info *ci_next; struct proc *ci_curproc; u_int ci_cpuid; u_int ci_apicid; u_int ci_acpi_proc_id; u_int32_t ci_randseed; u_int64_t ci_scratch; struct proc *ci_fpcurproc; struct proc *ci_fpsaveproc; int ci_fpsaving; struct pcb *ci_curpcb; struct pcb *ci_idle_pcb; struct intrsource *ci_isources[64]; u_int64_t ci_ipending; int ci_ilevel; int ci_idepth; int ci_handled_intr_level; u_int64_t ci_imask[16]; u_int64_t ci_iunmask[16]; int ci_mutex_level; volatile u_int ci_flags; u_int32_t ci_ipis; u_int32_t ci_feature_flags; u_int32_t ci_feature_eflags; u_int32_t ci_feature_sefflags_ebx; u_int32_t ci_feature_sefflags_ecx; u_int32_t ci_feature_tpmflags; u_int32_t ci_pnfeatset; u_int32_t ci_efeature_eax; u_int32_t ci_efeature_ecx; u_int32_t ci_brand[12]; u_int32_t ci_amdcacheinfo[4]; u_int32_t ci_extcacheinfo[4]; u_int32_t ci_signature; u_int32_t ci_family; u_int32_t ci_model; u_int32_t ci_cflushsz; u_int64_t ci_tsc_freq; int ci_inatomic; u_int32_t ci_smt_id; u_int32_t ci_core_id; u_int32_t ci_pkg_id; struct cpu_functions *ci_func; void (*cpu_setup)(struct cpu_info *); void (*ci_info)(struct cpu_info *); struct device *ci_acpicpudev; volatile u_int ci_mwait; int ci_want_resched; struct x86_cache_info ci_cinfo[8]; struct x86_64_tss *ci_tss; char *ci_gdt; volatile int ci_ddb_paused; # 176 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" struct ksensordev ci_sensordev; struct ksensor ci_sensor; u_int32_t ci_vmm_flags; union vmm_cpu_cap ci_vmm_cap; paddr_t ci_vmxon_region_pa; struct vmxon_region *ci_vmxon_region; }; # 215 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" extern struct cpu_info cpu_info_primary; extern struct cpu_info *cpu_info_list; # 228 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" extern void need_resched(struct cpu_info *); # 261 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" extern struct cpu_info cpu_info_primary; # 281 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/psl.h" 1 # 77 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/psl.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" 1 # 39 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 1 # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/evcount.h" 1 # 35 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/evcount.h" struct evcount { u_int64_t ec_count; int ec_id; const char *ec_name; void *ec_data; struct { struct evcount *tqe_next; struct evcount **tqe_prev; } next; }; void evcount_attach(struct evcount *, const char *, void *); void evcount_detach(struct evcount *); int evcount_sysctl(int *, u_int, void *, size_t *, void *, size_t); # 42 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" 2 # 61 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" struct intrstub { void *ist_entry; void *ist_recurse; void *ist_resume; }; struct intrsource { int is_maxlevel; int is_pin; struct intrhand *is_handlers; struct pic *is_pic; void *is_recurse; void *is_resume; char is_evname[32]; int is_flags; int is_type; int is_idtvec; int is_minlevel; }; # 91 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" struct intrhand { int (*ih_fun)(void *); void *ih_arg; int ih_level; int ih_flags; struct intrhand *ih_next; int ih_pin; int ih_slot; struct cpu_info *ih_cpu; int ih_irq; struct evcount ih_count; }; extern void Xspllower(int); int splraise(int); int spllower(int); void softintr(int); # 162 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" void splassert_fail(int, int, const char *); extern int splassert_ctl; void splassert_check(int, const char *); # 179 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/pic.h" 1 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mutex.h" 1 # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mutex.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/mutex.h" 1 # 30 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/mutex.h" struct mutex { int mtx_wantipl; int mtx_oldipl; volatile void *mtx_owner; }; # 52 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/mutex.h" void __mtx_init(struct mutex *, int); # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mutex.h" 2 void mtx_enter(struct mutex *); void mtx_leave(struct mutex *); int mtx_enter_try(struct mutex *); # 9 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/pic.h" 2 struct cpu_info; struct pic { struct device pic_dev; int pic_type; void (*pic_hwmask)(struct pic *, int); void (*pic_hwunmask)(struct pic *, int); void (*pic_addroute)(struct pic *, struct cpu_info *, int, int, int); void (*pic_delroute)(struct pic *, struct cpu_info *, int, int, int); struct intrstub *pic_level_stubs; struct intrstub *pic_edge_stubs; }; # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/pic.h" extern struct pic i8259_pic; extern struct pic local_pic; extern struct pic msi_pic; extern struct pic softintr_pic; # 180 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" 2 extern void Xsoftclock(void); extern void Xsoftnet(void); extern void Xsofttty(void); extern struct intrstub i8259_stubs[]; extern struct intrstub ioapic_edge_stubs[]; extern struct intrstub ioapic_level_stubs[]; struct cpu_info; extern int intr_shared_edge; extern char idt_allocmap[]; void intr_default_setup(void); int x86_nmi(void); void intr_calculatemasks(struct cpu_info *); int intr_allocate_slot_cpu(struct cpu_info *, struct pic *, int, int *); int intr_allocate_slot(struct pic *, int, int, int, struct cpu_info **, int *, int *); void *intr_establish(int, struct pic *, int, int, int, int (*)(void *), void *, const char *); void intr_disestablish(struct intrhand *); int intr_handler(struct intrframe *, struct intrhand *); void cpu_intr_init(struct cpu_info *); int intr_find_mpmapping(int bus, int pin, int *handle); void intr_printconfig(void); void intr_barrier(void *); # 238 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/intr.h" struct x86_soft_intrhand { struct { struct x86_soft_intrhand *tqe_next; struct x86_soft_intrhand **tqe_prev; } sih_q; struct x86_soft_intr *sih_intrhead; void (*sih_fn)(void *); void *sih_arg; int sih_pending; }; struct x86_soft_intr { struct { struct x86_soft_intrhand *tqh_first; struct x86_soft_intrhand **tqh_last; } softintr_q; int softintr_ssir; struct mutex softintr_lock; }; void *softintr_establish(int, void (*)(void *), void *); void softintr_disestablish(void *); void softintr_init(void); void softintr_dispatch(int); # 78 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/psl.h" 2 # 282 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" 2 # 311 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/cpu.h" void signotify(struct proc *); extern void (*delay_func)(int); struct timeval; extern int biosbasemem; extern int biosextmem; extern int cpu; extern int cpu_feature; extern int cpu_ebxfeature; extern int cpu_ecxfeature; extern int cpu_perf_eax; extern int cpu_perf_ebx; extern int cpu_perf_edx; extern int cpu_apmi_edx; extern int ecpu_ecxfeature; extern int cpu_id; extern char cpu_vendor[]; extern int cpuid_level; extern int cpuspeed; extern u_int cpu_mwait_size; extern u_int cpu_mwait_states; void identifycpu(struct cpu_info *); int cpu_amd64speed(int *); void dumpconf(void); void cpu_reset(void); void x86_64_proc0_tss_ldt_init(void); void x86_64_bufinit(void); void x86_64_init_pcb_tss_ldt(struct cpu_info *); void cpu_proc_fork(struct proc *, struct proc *); int amd64_pa_used(paddr_t); extern void (*cpu_idle_enter_fcn)(void); extern void (*cpu_idle_cycle_fcn)(void); extern void (*cpu_idle_leave_fcn)(void); struct region_descriptor; void lgdt(struct region_descriptor *); struct pcb; void savectx(struct pcb *); void switch_exit(struct proc *, void (*)(struct proc *)); void proc_trampoline(void); extern void (*initclock_func)(void); void startclocks(void); void rtcstart(void); void rtcstop(void); void i8254_delay(int); void i8254_initclocks(void); void i8254_startclock(void); void i8254_inittimecounter(void); void i8254_inittimecounter_simple(void); void i8259_default_setup(void); void cpu_init_msrs(struct cpu_info *); void dkcsumattach(void); void x86_bus_space_init(void); void x86_bus_space_mallocok(void); void k8_powernow_init(struct cpu_info *); void k8_powernow_setperf(int); void k1x_init(struct cpu_info *); void k1x_setperf(int); void est_init(struct cpu_info *); void est_setperf(int); # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/param.h" 2 # 89 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/param.h" 2 # 36 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" 1 # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stdarg.h" 1 # 29 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stdarg.h" typedef __builtin_va_list __gnuc_va_list; # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stdarg.h" typedef __gnuc_va_list va_list; # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" 2 # 73 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" extern int securelevel; extern const char *panicstr; extern const char version[]; extern const char copyright[]; extern const char ostype[]; extern const char osversion[]; extern const char osrelease[]; extern int cold; extern int ncpus; extern int ncpusfound; extern int nblkdev; extern int nchrdev; extern int selwait; extern int maxmem; extern int physmem; extern dev_t dumpdev; extern long dumplo; extern dev_t rootdev; extern u_char bootduid[8]; extern u_char rootduid[8]; extern struct vnode *rootvp; extern dev_t swapdev; extern struct vnode *swapdev_vp; struct proc; struct process; typedef int sy_call_t(struct proc *, void *, register_t *); extern struct sysent { short sy_narg; short sy_argsize; int sy_flags; sy_call_t *sy_call; } sysent[]; # 131 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" extern int boothowto; extern void (*v_putc)(int); int nullop(void *); int enodev(void); int enosys(void); int enoioctl(void); int enxio(void); int eopnotsupp(void *); struct vnodeopv_desc; void vfs_opv_init_explicit(struct vnodeopv_desc *); void vfs_opv_init_default(struct vnodeopv_desc *); void vfs_op_init(void); int seltrue(dev_t dev, int which, struct proc *); int selfalse(dev_t dev, int which, struct proc *); void *hashinit(int, int, int, u_long *); void hashfree(void *, int, int); int sys_nosys(struct proc *, void *, register_t *); void panic(const char *, ...) __attribute__((__noreturn__,__format__(__kprintf__,1,2))); void __assert(const char *, const char *, int, const char *) __attribute__((__noreturn__)); int printf(const char *, ...) __attribute__((__format__(__kprintf__,1,2))); void uprintf(const char *, ...) __attribute__((__format__(__kprintf__,1,2))); int vprintf(const char *, va_list) __attribute__((__format__(__kprintf__,1,0))); int vsnprintf(char *, size_t, const char *, va_list) __attribute__((__format__(__kprintf__,3,0))); int snprintf(char *buf, size_t, const char *, ...) __attribute__((__format__(__kprintf__,3,4))); struct tty; void ttyprintf(struct tty *, const char *, ...) __attribute__((__format__(__kprintf__,2,3))); void splassert_fail(int, int, const char *); extern int splassert_ctl; void assertwaitok(void); void tablefull(const char *); int kcopy(const void *, void *, size_t) __attribute__ ((__bounded__(__buffer__,1,3))) __attribute__ ((__bounded__(__buffer__,2,3))); void bcopy(const void *, void *, size_t) __attribute__ ((__bounded__(__buffer__,1,3))) __attribute__ ((__bounded__(__buffer__,2,3))); void bzero(void *, size_t) __attribute__ ((__bounded__(__buffer__,1,2))); void explicit_bzero(void *, size_t) __attribute__ ((__bounded__(__buffer__,1,2))); int bcmp(const void *, const void *, size_t); void *memcpy(void *, const void *, size_t) __attribute__ ((__bounded__(__buffer__,1,3))) __attribute__ ((__bounded__(__buffer__,2,3))); void *memmove(void *, const void *, size_t) __attribute__ ((__bounded__(__buffer__,1,3))) __attribute__ ((__bounded__(__buffer__,2,3))); void *memset(void *, int, size_t) __attribute__ ((__bounded__(__buffer__,1,3))); int copystr(const void *, void *, size_t, size_t *) __attribute__ ((__bounded__(__string__,2,3))); int copyinstr(const void *, void *, size_t, size_t *) __attribute__ ((__bounded__(__string__,2,3))); int copyoutstr(const void *, void *, size_t, size_t *); int copyin(const void *, void *, size_t) __attribute__ ((__bounded__(__buffer__,2,3))); int copyout(const void *, void *, size_t); void arc4random_buf(void *, size_t) __attribute__ ((__bounded__(__buffer__,1,2))); u_int32_t arc4random(void); u_int32_t arc4random_uniform(u_int32_t); struct timeval; struct timespec; int tvtohz(const struct timeval *); int tstohz(const struct timespec *); void realitexpire(void *); struct intrframe; void hardclock(struct intrframe *); void softclock(void *); void statclock(struct intrframe *); void initclocks(void); void inittodr(time_t); void resettodr(void); void cpu_initclocks(void); void startprofclock(struct process *); void stopprofclock(struct process *); void setstatclockrate(int); void start_periodic_resettodr(void); void stop_periodic_resettodr(void); struct sleep_state; void sleep_setup(struct sleep_state *, const volatile void *, int, const char *); void sleep_setup_timeout(struct sleep_state *, int); void sleep_setup_signal(struct sleep_state *, int); void sleep_finish(struct sleep_state *, int); int sleep_finish_timeout(struct sleep_state *); int sleep_finish_signal(struct sleep_state *); void sleep_queue_init(void); struct mutex; struct rwlock; void wakeup_n(const volatile void *, int); void wakeup(const volatile void *); int tsleep(const volatile void *, int, const char *, int); int msleep(const volatile void *, struct mutex *, int, const char*, int); int rwsleep(const volatile void *, struct rwlock *, int, const char *, int); void yield(void); void wdog_register(int (*)(void *, int), void *); void wdog_shutdown(void *); struct hook_desc { struct { struct hook_desc *tqe_next; struct hook_desc **tqe_prev; } hd_list; void (*hd_fn)(void *); void *hd_arg; }; struct hook_desc_head { struct hook_desc *tqh_first; struct hook_desc **tqh_last; }; extern struct hook_desc_head startuphook_list; void *hook_establish(struct hook_desc_head *, int, void (*)(void *), void *); void hook_disestablish(struct hook_desc_head *, void *); void dohooks(struct hook_desc_head *, int); # 289 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" struct uio; int uiomove(void *, size_t, struct uio *); # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/rwlock.h" 1 # 57 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/rwlock.h" struct proc; struct rwlock { volatile unsigned long rwl_owner; const char *rwl_name; }; # 93 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/rwlock.h" struct rrwlock { struct rwlock rrwl_lock; uint32_t rrwl_wcnt; }; void rw_init(struct rwlock *, const char *); void rw_enter_read(struct rwlock *); void rw_enter_write(struct rwlock *); void rw_exit_read(struct rwlock *); void rw_exit_write(struct rwlock *); void rw_assert_wrlock(struct rwlock *); void rw_assert_rdlock(struct rwlock *); void rw_assert_unlocked(struct rwlock *); int rw_enter(struct rwlock *, int); void rw_exit(struct rwlock *); int rw_status(struct rwlock *); void rrw_init(struct rrwlock *, char *); int rrw_enter(struct rrwlock *, int); void rrw_exit(struct rrwlock *); int rrw_status(struct rrwlock *); # 295 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" 2 extern struct rwlock netlock; # 317 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" __attribute__((returns_twice)) int setjmp(label_t *); __attribute__((__noreturn__)) void longjmp(label_t *); void consinit(void); void cpu_startup(void); void cpu_configure(void); void diskconf(void); int nfs_mountroot(void); int dk_mountroot(void); extern int (*mountroot)(void); # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/lib/libkern/libkern.h" 1 # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/lib/libkern/libkern.h" static __inline int imax(int, int); static __inline int imin(int, int); static __inline u_int max(u_int, u_int); static __inline u_int min(u_int, u_int); static __inline long lmax(long, long); static __inline long lmin(long, long); static __inline u_long ulmax(u_long, u_long); static __inline u_long ulmin(u_long, u_long); static __inline int abs(int); static __inline int imax(int a, int b) { return (a > b ? a : b); } static __inline int imin(int a, int b) { return (a < b ? a : b); } static __inline long lmax(long a, long b) { return (a > b ? a : b); } static __inline long lmin(long a, long b) { return (a < b ? a : b); } static __inline u_int max(u_int a, u_int b) { return (a > b ? a : b); } static __inline u_int min(u_int a, u_int b) { return (a < b ? a : b); } static __inline u_long ulmax(u_long a, u_long b) { return (a > b ? a : b); } static __inline u_long ulmin(u_long a, u_long b) { return (a < b ? a : b); } static __inline int abs(int j) { return(j < 0 ? -j : j); } # 161 "/crypt/home/bluhm/openbsd/cvs/src/sys/lib/libkern/libkern.h" void __assert(const char *, const char *, int, const char *) __attribute__ ((__noreturn__)); int bcmp(const void *, const void *, size_t); void bzero(void *, size_t); void explicit_bzero(void *, size_t); int ffs(int); int fls(int); int flsl(long); void *memchr(const void *, int, size_t); int memcmp(const void *, const void *, size_t); void *memset(void *, int c, size_t len); u_int32_t random(void); int scanc(u_int, const u_char *, const u_char [], int); int skpc(int, size_t, u_char *); size_t strlen(const char *); char *strncpy(char *, const char *, size_t) __attribute__ ((__bounded__(__string__,1,3))); size_t strnlen(const char *, size_t); size_t strlcpy(char *, const char *, size_t) __attribute__ ((__bounded__(__string__,1,3))); size_t strlcat(char *, const char *, size_t) __attribute__ ((__bounded__(__string__,1,3))); int strcmp(const char *, const char *); int strncmp(const char *, const char *, size_t); int strncasecmp(const char *, const char *, size_t); int getsn(char *, int); char *strchr(const char *, int); char *strrchr(const char *, int); int timingsafe_bcmp(const void *, const void *, size_t); # 332 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/systm.h" 2 void Debugger(void); void user_config(void); # 37 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/file.h" 1 # 35 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/file.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/fcntl.h" 1 # 179 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/fcntl.h" struct flock { off_t l_start; off_t l_len; pid_t l_pid; short l_type; short l_whence; }; # 36 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/file.h" 2 struct proc; struct uio; struct knote; struct stat; struct file; struct ucred; struct fileops { int (*fo_read)(struct file *, off_t *, struct uio *, struct ucred *); int (*fo_write)(struct file *, off_t *, struct uio *, struct ucred *); int (*fo_ioctl)(struct file *, u_long, caddr_t, struct proc *); int (*fo_poll)(struct file *, int, struct proc *); int (*fo_kqfilter)(struct file *, struct knote *); int (*fo_stat)(struct file *, struct stat *, struct proc *); int (*fo_close)(struct file *, struct proc *); }; struct file { struct { struct file *le_next; struct file **le_prev; } f_list; short f_flag; short f_type; long f_count; struct ucred *f_cred; struct fileops *f_ops; off_t f_offset; void *f_data; int f_iflags; u_int64_t f_rxfer; u_int64_t f_wxfer; u_int64_t f_seek; u_int64_t f_rbytes; u_int64_t f_wbytes; }; # 99 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/file.h" int fdrop(struct file *, struct proc *); struct filelist { struct file *lh_first; }; extern struct filelist filehead; extern int maxfiles; extern int numfiles; extern struct fileops vnops; # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 1 # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/proc.h" 1 # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/proc.h" struct trapframe; struct mdproc { struct trapframe *md_regs; int md_flags; volatile int md_astpending; }; # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/selinfo.h" 1 # 37 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/selinfo.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/event.h" 1 # 53 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/event.h" struct kevent { __uintptr_t ident; short filter; u_short flags; u_int fflags; __int64_t data; void *udata; }; # 116 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/event.h" struct knote; struct klist { struct knote *slh_first; }; # 134 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/event.h" struct filterops { int f_isfd; int (*f_attach)(struct knote *kn); void (*f_detach)(struct knote *kn); int (*f_event)(struct knote *kn, long hint); }; struct knote { struct { struct knote *sle_next; } kn_link; struct { struct knote *sle_next; } kn_selnext; struct { struct knote *tqe_next; struct knote **tqe_prev; } kn_tqe; struct kqueue *kn_kq; struct kevent kn_kevent; int kn_status; int kn_sfflags; __int64_t kn_sdata; union { struct file *p_fp; struct process *p_process; } kn_ptr; const struct filterops *kn_fop; void *kn_hook; # 167 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/event.h" }; struct proc; extern void knote(struct klist *list, long hint); extern void knote_activate(struct knote *); extern void knote_remove(struct proc *p, struct klist *list); extern void knote_fdclose(struct proc *p, int fd); extern void knote_processexit(struct proc *); extern int kqueue_register(struct kqueue *kq, struct kevent *kev, struct proc *p); extern int filt_seltrue(struct knote *kn, long hint); extern int seltrue_kqfilter(dev_t, struct knote *); extern void klist_invalidate(struct klist *); # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/selinfo.h" 2 struct selinfo { pid_t si_seltid; struct klist si_note; short si_flags; }; struct proc; void selrecord(struct proc *selector, struct selinfo *); void selwakeup(struct selinfo *); # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/syslimits.h" 1 # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/timeout.h" 1 # 54 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/timeout.h" struct circq { struct circq *next; struct circq *prev; }; struct timeout { struct circq to_list; void (*to_func)(void *); void *to_arg; int to_time; int to_flags; }; # 89 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/timeout.h" struct bintime; void timeout_set(struct timeout *, void (*)(void *), void *); void timeout_set_proc(struct timeout *, void (*)(void *), void *); int timeout_add(struct timeout *, int); int timeout_add_tv(struct timeout *, const struct timeval *); int timeout_add_ts(struct timeout *, const struct timespec *); int timeout_add_bt(struct timeout *, const struct bintime *); int timeout_add_sec(struct timeout *, int); int timeout_add_msec(struct timeout *, int); int timeout_add_usec(struct timeout *, int); int timeout_add_nsec(struct timeout *, int); int timeout_del(struct timeout *); void timeout_startup(void); void timeout_adjust_ticks(int); int timeout_hardclock_update(void); # 48 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/atomic.h" 1 # 58 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/atomic.h" static inline unsigned int _atomic_cas_uint(volatile unsigned int *p, unsigned int e, unsigned int n) { __asm volatile( " cmpxchgl %2, %1" : "=a" (n), "=m" (*p) : "r" (n), "a" (e), "m" (*p)); return (n); } static inline unsigned long _atomic_cas_ulong(volatile unsigned long *p, unsigned long e, unsigned long n) { __asm volatile( " cmpxchgq %2, %1" : "=a" (n), "=m" (*p) : "r" (n), "a" (e), "m" (*p)); return (n); } static inline void * _atomic_cas_ptr(volatile void *p, void *e, void *n) { __asm volatile( " cmpxchgq %2, %1" : "=a" (n), "=m" (*(unsigned long *)p) : "r" (n), "a" (e), "m" (*(unsigned long *)p)); return (n); } static inline unsigned int _atomic_swap_uint(volatile unsigned int *p, unsigned int n) { __asm volatile("xchgl %0, %1" : "=a" (n), "=m" (*p) : "0" (n), "m" (*p)); return (n); } static inline unsigned long _atomic_swap_ulong(volatile unsigned long *p, unsigned long n) { __asm volatile("xchgq %0, %1" : "=a" (n), "=m" (*p) : "0" (n), "m" (*p)); return (n); } static inline uint64_t _atomic_swap_64(volatile uint64_t *p, uint64_t n) { __asm volatile("xchgq %0, %1" : "=a" (n), "=m" (*p) : "0" (n), "m" (*p)); return (n); } static inline void * _atomic_swap_ptr(volatile void *p, void *n) { __asm volatile("xchgq %0, %1" : "=a" (n), "=m" (*(unsigned long *)p) : "0" (n), "m" (*(unsigned long *)p)); return (n); } static inline void _atomic_inc_int(volatile unsigned int *p) { __asm volatile( " incl %0" : "+m" (*p)); } static inline void _atomic_inc_long(volatile unsigned long *p) { __asm volatile( " incq %0" : "+m" (*p)); } static inline void _atomic_dec_int(volatile unsigned int *p) { __asm volatile( " decl %0" : "+m" (*p)); } static inline void _atomic_dec_long(volatile unsigned long *p) { __asm volatile( " decq %0" : "+m" (*p)); } static inline void _atomic_add_int(volatile unsigned int *p, unsigned int v) { __asm volatile( " addl %1,%0" : "+m" (*p) : "a" (v)); } static inline void _atomic_add_long(volatile unsigned long *p, unsigned long v) { __asm volatile( " addq %1,%0" : "+m" (*p) : "a" (v)); } static inline void _atomic_sub_int(volatile unsigned int *p, unsigned int v) { __asm volatile( " subl %1,%0" : "+m" (*p) : "a" (v)); } static inline void _atomic_sub_long(volatile unsigned long *p, unsigned long v) { __asm volatile( " subq %1,%0" : "+m" (*p) : "a" (v)); } static inline unsigned long _atomic_add_int_nv(volatile unsigned int *p, unsigned int v) { unsigned int rv = v; __asm volatile( " xaddl %0,%1" : "+a" (rv), "+m" (*p)); return (rv + v); } static inline unsigned long _atomic_add_long_nv(volatile unsigned long *p, unsigned long v) { unsigned long rv = v; __asm volatile( " xaddq %0,%1" : "+a" (rv), "+m" (*p)); return (rv + v); } static inline unsigned long _atomic_sub_int_nv(volatile unsigned int *p, unsigned int v) { unsigned int rv = 0 - v; __asm volatile( " xaddl %0,%1" : "+a" (rv), "+m" (*p)); return (rv - v); } static inline unsigned long _atomic_sub_long_nv(volatile unsigned long *p, unsigned long v) { unsigned long rv = 0 - v; __asm volatile( " xaddq %0,%1" : "+a" (rv), "+m" (*p)); return (rv - v); } # 284 "/crypt/home/bluhm/openbsd/cvs/src/sys/arch/amd64/compile/GENERIC/obj/machine/atomic.h" static __inline void x86_atomic_setbits_u32(volatile u_int32_t *ptr, u_int32_t bits) { __asm volatile( " orl %1,%0" : "=m" (*ptr) : "ir" (bits)); } static __inline void x86_atomic_clearbits_u32(volatile u_int32_t *ptr, u_int32_t bits) { __asm volatile( " andl %1,%0" : "=m" (*ptr) : "ir" (~bits)); } static __inline void x86_atomic_setbits_u64(volatile u_int64_t *ptr, u_int64_t bits) { __asm volatile( " orq %1,%0" : "=m" (*ptr) : "er" (bits)); } static __inline void x86_atomic_clearbits_u64(volatile u_int64_t *ptr, u_int64_t bits) { __asm volatile( " andq %1,%0" : "=m" (*ptr) : "er" (~bits)); } # 52 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" 2 # 60 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct process; struct session { int s_count; struct process *s_leader; struct vnode *s_ttyvp; struct tty *s_ttyp; char s_login[32]; pid_t s_verauthppid; uid_t s_verauthuid; struct timeout s_verauthto; }; void zapverauth( void *); struct pgrp { struct { struct pgrp *le_next; struct pgrp **le_prev; } pg_hash; struct { struct process *lh_first; } pg_members; struct session *pg_session; pid_t pg_id; int pg_jobc; }; struct exec_package; struct proc; struct ps_strings; struct uvm_object; struct whitepaths; union sigval; struct emul { char e_name[8]; int *e_errno; void (*e_sendsig)(void (*)(int), int, int, u_long, int, union sigval); int e_nosys; int e_nsysent; struct sysent *e_sysent; char **e_syscallnames; int e_arglen; void *(*e_copyargs)(struct exec_package *, struct ps_strings *, void *, void *); void (*e_setregs)(struct proc *, struct exec_package *, u_long, register_t *); int (*e_fixup)(struct proc *, struct exec_package *); int (*e_coredump)(struct proc *, void *cookie); char *e_sigcode; char *e_esigcode; char *e_esigret; int e_flags; struct uvm_object *e_sigobject; void (*e_proc_exec)(struct proc *, struct exec_package *); void (*e_proc_fork)(struct proc *p, struct proc *parent); void (*e_proc_exit)(struct proc *); }; # 132 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct tusage { struct timespec tu_runtime; uint64_t tu_uticks; uint64_t tu_sticks; uint64_t tu_iticks; }; # 152 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct process { # 161 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct proc *ps_mainproc; struct ucred *ps_ucred; struct { struct process *le_next; struct process **le_prev; } ps_list; struct { struct proc *tqh_first; struct proc **tqh_last; } ps_threads; struct { struct process *le_next; struct process **le_prev; } ps_pglist; struct process *ps_pptr; struct { struct process *le_next; struct process **le_prev; } ps_sibling; struct { struct process *lh_first; } ps_children; struct { struct process *le_next; struct process **le_prev; } ps_hash; struct sigacts *ps_sigacts; struct vnode *ps_textvp; struct filedesc *ps_fd; struct vmspace *ps_vmspace; pid_t ps_pid; struct klist ps_klist; int ps_flags; struct proc *ps_single; int ps_singlecount; int ps_traceflag; struct vnode *ps_tracevp; struct ucred *ps_tracecred; pid_t ps_oppid; int ps_ptmask; struct ptrace_state *ps_ptstat; struct rusage *ps_ru; struct tusage ps_tu; struct rusage ps_cru; struct itimerval ps_timer[3]; u_int64_t ps_wxcounter; struct plimit *ps_limit; struct pgrp *ps_pgrp; struct emul *ps_emul; vaddr_t ps_strings; vaddr_t ps_stackgap; vaddr_t ps_sigcode; vaddr_t ps_sigcoderet; u_long ps_sigcookie; u_int ps_rtableid; char ps_nice; struct uprof { caddr_t pr_base; size_t pr_size; u_long pr_off; u_int pr_scale; } ps_prof; u_short ps_acflag; uint64_t ps_pledge; struct whitepaths *ps_pledgepaths; int64_t ps_kbind_cookie; u_long ps_kbind_addr; int ps_refcnt; struct timespec ps_start; struct timeout ps_realit_to; }; # 280 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct proc { struct { struct proc *tqe_next; struct proc **tqe_prev; } p_runq; struct { struct proc *le_next; struct proc **le_prev; } p_list; struct process *p_p; struct { struct proc *tqe_next; struct proc **tqe_prev; } p_thr_link; struct filedesc *p_fd; struct vmspace *p_vmspace; int p_flag; u_char p_spare; char p_stat; char p_pad1[1]; u_char p_descfd; pid_t p_tid; struct { struct proc *le_next; struct proc **le_prev; } p_hash; int p_dupfd; long p_thrslpid; u_int p_estcpu; int p_cpticks; const volatile void *p_wchan; struct timeout p_sleep_to; const char *p_wmesg; fixpt_t p_pctcpu; u_int p_slptime; u_int p_uticks; u_int p_sticks; u_int p_iticks; struct cpu_info * volatile p_cpu; struct rusage p_ru; struct tusage p_tu; struct timespec p_rtime; void *p_emuldata; int p_siglist; sigset_t p_sigmask; u_char p_priority; u_char p_usrpri; char p_comm[16 +1]; int p_pledge_syscall; struct ucred *p_ucred; struct sigaltstack p_sigstk; u_long p_prof_addr; u_long p_prof_ticks; struct user *p_addr; struct mdproc p_md; sigset_t p_oldmask; int p_sisig; union sigval p_sigval; long p_sitrapno; int p_sicode; u_short p_xstat; }; # 411 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct uidinfo { struct { struct uidinfo *le_next; struct uidinfo **le_prev; } ui_hash; uid_t ui_uid; long ui_proccnt; long ui_lockcnt; }; struct uidinfo *uid_find(uid_t); # 465 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" extern struct tidhashhead { struct proc *lh_first; } *tidhashtbl; extern u_long tidhash; extern struct pidhashhead { struct process *lh_first; } *pidhashtbl; extern u_long pidhash; extern struct pgrphashhead { struct pgrp *lh_first; } *pgrphashtbl; extern u_long pgrphash; extern struct proc proc0; extern struct process process0; extern int nprocesses, maxprocess; extern int nthreads, maxthread; extern int randompid; struct proclist { struct proc *lh_first; }; struct processlist { struct process *lh_first; }; extern struct processlist allprocess; extern struct processlist zombprocess; extern struct proclist allproc; extern struct process *initprocess; extern struct proc *reaperproc; extern struct proc *syncerproc; extern struct pool process_pool; extern struct pool proc_pool; extern struct pool rusage_pool; extern struct pool ucred_pool; extern struct pool session_pool; extern struct pool pgrp_pool; void freepid(pid_t); struct process *prfind(pid_t); struct process *zombiefind(pid_t); struct proc *pfind(pid_t); struct pgrp *pgfind(pid_t); void proc_printit(struct proc *p, const char *modif, int (*pr)(const char *, ...)); int chgproccnt(uid_t uid, int diff); int enterpgrp(struct process *, pid_t, struct pgrp *, struct session *); void fixjobc(struct process *, struct pgrp *, int); int inferior(struct process *, struct process *); void leavepgrp(struct process *); void preempt(struct proc *); void pgdelete(struct pgrp *); void procinit(void); void resetpriority(struct proc *); void setrunnable(struct proc *); void endtsleep(void *); void unsleep(struct proc *); void reaper(void); void exit1(struct proc *, int, int); void exit2(struct proc *); int dowait4(struct proc *, pid_t, int *, int, struct rusage *, register_t *); void cpu_exit(struct proc *); void process_initialize(struct process *, struct proc *); int fork1(struct proc *, int, void *, pid_t *, void (*)(void *), void *, register_t *, struct proc **); int groupmember(gid_t, struct ucred *); void dorefreshcreds(struct process *, struct proc *); void dosigsuspend(struct proc *, sigset_t); static inline void refreshcreds(struct proc *p) { struct process *pr = p->p_p; if (pr->ps_ucred != p->p_ucred) dorefreshcreds(pr, p); } enum single_thread_mode { SINGLE_SUSPEND, SINGLE_PTRACE, SINGLE_UNWIND, SINGLE_EXIT }; int single_thread_set(struct proc *, enum single_thread_mode, int); void single_thread_wait(struct process *); void single_thread_clear(struct proc *, int); int single_thread_check(struct proc *, int); void child_return(void *); int proc_cansugid(struct proc *); struct sleep_state { int sls_s; int sls_catch; int sls_do_sleep; int sls_sig; }; # 577 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/proc.h" struct cpuset { int cs_set[(((1) - 1)/32 + 1)]; }; void cpuset_init_cpu(struct cpu_info *); void cpuset_clear(struct cpuset *); void cpuset_add(struct cpuset *, struct cpu_info *); void cpuset_del(struct cpuset *, struct cpu_info *); int cpuset_isset(struct cpuset *, struct cpu_info *); void cpuset_add_all(struct cpuset *); void cpuset_copy(struct cpuset *, struct cpuset *); void cpuset_union(struct cpuset *, struct cpuset *, struct cpuset *); void cpuset_intersection(struct cpuset *t, struct cpuset *, struct cpuset *); void cpuset_complement(struct cpuset *, struct cpuset *, struct cpuset *); struct cpu_info *cpuset_first(struct cpuset *); # 39 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" 1 # 69 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" struct m_tag { struct { struct m_tag *sle_next; } m_tag_link; u_int16_t m_tag_id; u_int16_t m_tag_len; }; # 82 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" struct m_hdr { struct mbuf *mh_next; struct mbuf *mh_nextpkt; caddr_t mh_data; u_int mh_len; short mh_type; u_short mh_flags; }; struct pf_state_key; struct inpcb; struct pkthdr_pf { struct pf_state_key *statekey; struct inpcb *inp; u_int32_t qid; u_int16_t tag; u_int8_t flags; u_int8_t routed; u_int8_t prio; u_int8_t pad[3]; }; # 122 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" struct pkthdr { void *ph_cookie; struct { struct m_tag *slh_first; } ph_tags; int len; u_int16_t ph_tagsset; u_int16_t ph_flowid; u_int16_t csum_flags; u_int16_t ether_vtag; u_int ph_rtableid; u_int ph_ifidx; u_int8_t ph_loopcnt; struct pkthdr_pf pf; }; struct mbuf_ext { caddr_t ext_buf; void *ext_arg; u_int ext_free_fn; u_int ext_size; struct mbuf *ext_nextref; struct mbuf *ext_prevref; }; struct mbuf { struct m_hdr m_hdr; union { struct { struct pkthdr MH_pkthdr; union { struct mbuf_ext MH_ext; char MH_databuf[((256 - sizeof(struct m_hdr)) - sizeof(struct pkthdr))]; } MH_dat; } MH; char M_databuf[(256 - sizeof(struct m_hdr))]; } M_dat; }; # 245 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/malloc.h" 1 # 319 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/malloc.h" struct kmemstats { long ks_inuse; long ks_calls; long ks_memuse; u_short ks_limblocks; u_short ks_mapblocks; long ks_maxused; long ks_limit; long ks_size; long ks_spare; }; struct kmemusage { short ku_indx; union { u_short freecnt; u_short pagecnt; } ku_un; }; struct kmem_freelist; struct kmembuckets { struct { struct kmem_freelist *sqx_first; struct kmem_freelist **sqx_last; unsigned long sqx_cookie; } kb_freelist; u_int64_t kb_calls; u_int64_t kb_total; u_int64_t kb_totalfree; u_int64_t kb_elmpercl; u_int64_t kb_highwat; u_int64_t kb_couldfree; }; # 388 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/malloc.h" extern struct kmemstats kmemstats[]; extern struct kmemusage *kmemusage; extern char *kmembase; extern struct kmembuckets bucket[]; void *malloc(size_t, int, int); void *mallocarray(size_t, size_t, int, int); void free(void *, int, size_t); int sysctl_malloc(int *, u_int, void *, size_t *, void *, size_t, struct proc *); size_t malloc_roundup(size_t); void malloc_printit(int (*)(const char *, ...)); void poison_mem(void *, size_t); int poison_check(void *, size_t, size_t *, uint32_t *); uint32_t poison_value(void *); # 246 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" 2 # 312 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" u_int mextfree_register(void (*)(caddr_t, u_int, void *)); # 389 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" struct mbstat { u_long m_drops; u_long m_wait; u_long m_drain; u_short m_mtypes[256]; }; # 404 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" struct mbuf_list { struct mbuf *ml_head; struct mbuf *ml_tail; u_int ml_len; }; struct mbuf_queue { struct mutex mq_mtx; struct mbuf_list mq_list; u_int mq_maxlen; u_int mq_drops; }; extern int nmbclust; extern int mblowat; extern int mcllowat; extern int max_linkhdr; extern int max_protohdr; extern int max_hdr; void mbinit(void); void mbcpuinit(void); struct mbuf *m_copym(struct mbuf *, int, int, int); struct mbuf *m_free(struct mbuf *); struct mbuf *m_get(int, int); struct mbuf *m_getclr(int, int); struct mbuf *m_gethdr(int, int); struct mbuf *m_inithdr(struct mbuf *); void m_resethdr(struct mbuf *); int m_defrag(struct mbuf *, int); struct mbuf *m_prepend(struct mbuf *, int, int); struct mbuf *m_pulldown(struct mbuf *, int, int, int *); struct mbuf *m_pullup(struct mbuf *, int); struct mbuf *m_split(struct mbuf *, int, int); struct mbuf *m_makespace(struct mbuf *, int, int, int *); struct mbuf *m_getptr(struct mbuf *, int, int *); int m_leadingspace(struct mbuf *); int m_trailingspace(struct mbuf *); struct mbuf *m_clget(struct mbuf *, int, u_int); void m_extref(struct mbuf *, struct mbuf *); void m_extfree_pool(caddr_t, u_int, void *); void m_adj(struct mbuf *, int); int m_copyback(struct mbuf *, int, int, const void *, int); struct mbuf *m_freem(struct mbuf *); void m_purge(struct mbuf *); void m_reclaim(void *, int); void m_copydata(struct mbuf *, int, int, caddr_t); void m_cat(struct mbuf *, struct mbuf *); struct mbuf *m_devget(char *, int, int); int m_apply(struct mbuf *, int, int, int (*)(caddr_t, caddr_t, unsigned int), caddr_t); struct mbuf *m_dup_pkt(struct mbuf *, unsigned int, int); int m_dup_pkthdr(struct mbuf *, struct mbuf *, int); struct m_tag *m_tag_get(int, int, int); void m_tag_prepend(struct mbuf *, struct m_tag *); void m_tag_delete(struct mbuf *, struct m_tag *); void m_tag_delete_chain(struct mbuf *); struct m_tag *m_tag_find(struct mbuf *, int, struct m_tag *); struct m_tag *m_tag_copy(struct m_tag *, int); int m_tag_copy_chain(struct mbuf *, struct mbuf *, int); void m_tag_init(struct mbuf *); struct m_tag *m_tag_first(struct mbuf *); struct m_tag *m_tag_next(struct mbuf *, struct m_tag *); # 505 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" void ml_init(struct mbuf_list *); void ml_enqueue(struct mbuf_list *, struct mbuf *); struct mbuf * ml_dequeue(struct mbuf_list *); void ml_enlist(struct mbuf_list *, struct mbuf_list *); struct mbuf * ml_dechain(struct mbuf_list *); unsigned int ml_purge(struct mbuf_list *); # 530 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/mbuf.h" void mq_init(struct mbuf_queue *, u_int, int); int mq_enqueue(struct mbuf_queue *, struct mbuf *); struct mbuf * mq_dequeue(struct mbuf_queue *); int mq_enlist(struct mbuf_queue *, struct mbuf_list *); void mq_delist(struct mbuf_queue *, struct mbuf_list *); struct mbuf * mq_dechain(struct mbuf_queue *); unsigned int mq_purge(struct mbuf_queue *); # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/protosw.h" 1 # 58 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/protosw.h" struct mbuf; struct sockaddr; struct socket; struct domain; struct proc; struct protosw { short pr_type; struct domain *pr_domain; short pr_protocol; short pr_flags; void (*pr_input)(struct mbuf *, ...); int (*pr_output)(struct mbuf *, ...); void *(*pr_ctlinput)(int, struct sockaddr *, u_int, void *); int (*pr_ctloutput)(int, struct socket *, int, int, struct mbuf **); int (*pr_usrreq)(struct socket *, int, struct mbuf *, struct mbuf *, struct mbuf *, struct proc *); void (*pr_init)(void); void (*pr_fasttimo)(void); void (*pr_slowtimo)(void); void (*pr_drain)(void); int (*pr_sysctl)(int *, u_int, void *, size_t *, void *, size_t); }; # 229 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/protosw.h" struct sockaddr; struct protosw *pffindproto(int, int, int); struct protosw *pffindtype(int, int); void pfctlinput(int, struct sockaddr *); extern u_char ip_protox[]; extern struct protosw inetsw[]; # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" 1 # 47 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" typedef __socklen_t socklen_t; typedef __sa_family_t sa_family_t; # 119 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct linger { int l_onoff; int l_linger; }; # 137 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct splice { int sp_fd; off_t sp_max; struct timeval sp_idle; }; # 206 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct sockaddr { __uint8_t sa_len; sa_family_t sa_family; char sa_data[14]; }; # 224 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct sockaddr_storage { __uint8_t ss_len; sa_family_t ss_family; unsigned char __ss_pad1[6]; __uint64_t __ss_pad2; unsigned char __ss_pad3[240]; }; struct sockproto { unsigned short sp_family; unsigned short sp_protocol; }; # 297 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct sockpeercred { uid_t uid; gid_t gid; pid_t pid; }; # 427 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct msghdr { void *msg_name; socklen_t msg_namelen; struct iovec *msg_iov; unsigned int msg_iovlen; void *msg_control; socklen_t msg_controllen; int msg_flags; }; # 456 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" struct cmsghdr { socklen_t cmsg_len; int cmsg_level; int cmsg_type; }; # 535 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socket.h" void pfctlinput(int, struct sockaddr *); # 42 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" 1 # 37 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/task.h" 1 # 24 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/task.h" struct taskq; struct task { struct { struct task *tqe_next; struct task **tqe_prev; } t_entry; void (*t_func)(void *); void *t_arg; unsigned int t_flags; }; struct task_list { struct task *tqh_first; struct task **tqh_last; }; extern struct taskq *const systq; extern struct taskq *const systqmp; struct taskq *taskq_create(const char *, unsigned int, int, unsigned int); void taskq_destroy(struct taskq *); void task_set(struct task *, void (*)(void *), void *); int task_add(struct taskq *, struct task *); int task_del(struct taskq *, struct task *); # 38 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" 2 struct soqhead { struct socket *tqh_first; struct socket **tqh_last; }; struct socket { short so_type; short so_options; short so_linger; short so_state; void *so_pcb; struct protosw *so_proto; # 71 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" struct socket *so_head; struct soqhead *so_onq; struct soqhead so_q0; struct soqhead so_q; struct { struct socket *tqe_next; struct socket **tqe_prev; } so_qe; short so_q0len; short so_qlen; short so_qlimit; short so_timeo; u_short so_error; pid_t so_pgid; uid_t so_siguid; uid_t so_sigeuid; u_long so_oobmark; struct sosplice { struct socket *ssp_socket; struct socket *ssp_soback; off_t ssp_len; off_t ssp_max; struct timeval ssp_idletv; struct timeout ssp_idleto; struct task ssp_task; } *so_sp; struct sockbuf { u_long sb_cc; u_long sb_datacc; u_long sb_hiwat; u_long sb_wat; u_long sb_mbcnt; u_long sb_mbmax; long sb_lowat; struct mbuf *sb_mb; struct mbuf *sb_mbtail; struct mbuf *sb_lastrecord; struct selinfo sb_sel; int sb_flagsintr; short sb_flags; u_short sb_timeo; } so_rcv, so_snd; # 127 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" void (*so_upcall)(struct socket *so, caddr_t arg, int waitf); caddr_t so_upcallarg; uid_t so_euid, so_ruid; gid_t so_egid, so_rgid; pid_t so_cpid; }; # 218 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" struct rwlock; int sblock(struct sockbuf *, int, struct rwlock *); void sbunlock(struct sockbuf *); # 237 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/socketvar.h" extern u_long sb_max; extern struct pool socket_pool; struct mbuf; struct sockaddr; struct proc; struct msghdr; struct stat; struct knote; int soo_read(struct file *fp, off_t *, struct uio *uio, struct ucred *cred); int soo_write(struct file *fp, off_t *, struct uio *uio, struct ucred *cred); int soo_ioctl(struct file *fp, u_long cmd, caddr_t data, struct proc *p); int soo_poll(struct file *fp, int events, struct proc *p); int soo_kqfilter(struct file *fp, struct knote *kn); int soo_close(struct file *fp, struct proc *p); int soo_stat(struct file *, struct stat *, struct proc *); int uipc_usrreq(struct socket *, int , struct mbuf *, struct mbuf *, struct mbuf *, struct proc *); void sbappend(struct sockbuf *sb, struct mbuf *m); void sbappendstream(struct sockbuf *sb, struct mbuf *m); int sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0, struct mbuf *control); int sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control); void sbappendrecord(struct sockbuf *sb, struct mbuf *m0); void sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n); struct mbuf * sbcreatecontrol(caddr_t p, int size, int type, int level); void sbdrop(struct sockbuf *sb, int len); void sbdroprecord(struct sockbuf *sb); void sbflush(struct sockbuf *sb); void sbinsertoob(struct sockbuf *sb, struct mbuf *m0); void sbrelease(struct sockbuf *sb); int sbcheckreserve(u_long cnt, u_long defcnt); int sbchecklowmem(void); int sbreserve(struct sockbuf *sb, u_long cc); int sbwait(struct sockbuf *sb); int sb_lock(struct sockbuf *sb); void soinit(void); int soabort(struct socket *so); int soaccept(struct socket *so, struct mbuf *nam); int sobind(struct socket *so, struct mbuf *nam, struct proc *p); void socantrcvmore(struct socket *so); void socantsendmore(struct socket *so); int soclose(struct socket *so); int soconnect(struct socket *so, struct mbuf *nam); int soconnect2(struct socket *so1, struct socket *so2); int socreate(int dom, struct socket **aso, int type, int proto); int sodisconnect(struct socket *so); void sofree(struct socket *so); int sogetopt(struct socket *so, int level, int optname, struct mbuf **mp); void sohasoutofband(struct socket *so); void soisconnected(struct socket *so); void soisconnecting(struct socket *so); void soisdisconnected(struct socket *so); void soisdisconnecting(struct socket *so); int solisten(struct socket *so, int backlog); struct socket *sonewconn(struct socket *head, int connstatus); void soqinsque(struct socket *head, struct socket *so, int q); int soqremque(struct socket *so, int q); int soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp, socklen_t controllen); int soreserve(struct socket *so, u_long sndcc, u_long rcvcc); void sorflush(struct socket *so); int sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top, struct mbuf *control, int flags); int sosetopt(struct socket *so, int level, int optname, struct mbuf *m0); int soshutdown(struct socket *so, int how); void sowakeup(struct socket *so, struct sockbuf *sb); void sorwakeup(struct socket *); void sowwakeup(struct socket *); int sockargs(struct mbuf **, const void *, size_t, int); int sendit(struct proc *, int, struct msghdr *, int, register_t *); int recvit(struct proc *, int, struct msghdr *, caddr_t, register_t *); int doaccept(struct proc *, int, struct sockaddr *, socklen_t *, int, register_t *); # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioctl.h" 1 # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioctl.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ttycom.h" 1 # 43 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ttycom.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioccom.h" 1 # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ttycom.h" 2 struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; unsigned short ws_ypixel; }; struct tstamps { int ts_set; int ts_clr; }; # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioctl.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/filio.h" 1 # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioctl.h" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/sockio.h" 1 # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/ioctl.h" 2 # 44 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/poll.h" 1 # 31 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/poll.h" typedef struct pollfd { int fd; short events; short revents; } pollfd_t; typedef unsigned int nfds_t; # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stat.h" 1 # 45 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stat.h" struct stat { mode_t st_mode; dev_t st_dev; ino_t st_ino; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; dev_t st_rdev; struct timespec st_atim; struct timespec st_mtim; struct timespec st_ctim; # 65 "/crypt/home/bluhm/openbsd/cvs/src/sys/sys/stat.h" off_t st_size; blkcnt_t st_blocks; blksize_t st_blksize; u_int32_t st_flags; u_int32_t st_gen; struct timespec __st_birthtim; }; # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" 1 # 46 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" struct if_nameindex { unsigned int if_index; char *if_name; }; # 65 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" struct if_clonereq { int ifcr_total; int ifcr_count; char *ifcr_buffer; }; struct if_rxring { int rxr_adjusted; u_int rxr_alive; u_int rxr_cwm; u_int rxr_lwm; u_int rxr_hwm; }; struct if_rxring_info { char ifr_name[16]; u_int ifr_size; struct if_rxring ifr_info; }; struct if_rxrinfo { u_int ifri_total; struct if_rxring_info *ifri_entries; }; struct if_data { u_char ifi_type; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_int32_t ifi_mtu; u_int32_t ifi_metric; u_int32_t ifi_rdomain; u_int64_t ifi_baudrate; u_int64_t ifi_ipackets; u_int64_t ifi_ierrors; u_int64_t ifi_opackets; u_int64_t ifi_oerrors; u_int64_t ifi_collisions; u_int64_t ifi_ibytes; u_int64_t ifi_obytes; u_int64_t ifi_imcasts; u_int64_t ifi_omcasts; u_int64_t ifi_iqdrops; u_int64_t ifi_oqdrops; u_int64_t ifi_noproto; u_int32_t ifi_capabilities; struct timeval ifi_lastchange; }; # 145 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" struct if_status_description { u_char ifs_type; u_char ifs_state; const char *ifs_string; }; # 258 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" struct if_msghdr { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; u_short ifm_hdrlen; u_short ifm_index; u_short ifm_tableid; u_char ifm_pad1; u_char ifm_pad2; int ifm_addrs; int ifm_flags; int ifm_xflags; struct if_data ifm_data; }; struct ifa_msghdr { u_short ifam_msglen; u_char ifam_version; u_char ifam_type; u_short ifam_hdrlen; u_short ifam_index; u_short ifam_tableid; u_char ifam_pad1; u_char ifam_pad2; int ifam_addrs; int ifam_flags; int ifam_metric; }; struct if_announcemsghdr { u_short ifan_msglen; u_char ifan_version; u_char ifan_type; u_short ifan_hdrlen; u_short ifan_index; u_short ifan_what; char ifan_name[16]; }; struct if_nameindex_msg { unsigned int if_index; char if_name[16]; }; # 320 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" struct ifg_req { union { char ifgrqu_group[16]; char ifgrqu_member[16]; } ifgrq_ifgrqu; }; struct ifg_attrib { int ifg_carp_demoted; }; struct ifgroupreq { char ifgr_name[16]; u_int ifgr_len; union { char ifgru_group[16]; struct ifg_req *ifgru_groups; struct ifg_attrib ifgru_attrib; } ifgr_ifgru; }; struct ifreq { char ifr_name[16]; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; short ifru_flags; int ifru_metric; int64_t ifru_vnetid; uint64_t ifru_media; caddr_t ifru_data; unsigned int ifru_index; } ifr_ifru; # 382 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" }; struct ifaliasreq { char ifra_name[16]; union { struct sockaddr ifrau_addr; int ifrau_align; } ifra_ifrau; struct sockaddr ifra_dstaddr; struct sockaddr ifra_mask; }; struct ifmediareq { char ifm_name[16]; uint64_t ifm_current; uint64_t ifm_mask; uint64_t ifm_status; uint64_t ifm_active; int ifm_count; uint64_t *ifm_ulist; }; struct ifkalivereq { char ikar_name[16]; int ikar_timeo; int ikar_cnt; }; struct ifconf { int ifc_len; union { caddr_t ifcu_buf; struct ifreq *ifcu_req; } ifc_ifcu; }; struct if_laddrreq { char iflr_name[16]; unsigned int flags; unsigned int prefixlen; struct sockaddr_storage addr; struct sockaddr_storage dstaddr; }; struct if_afreq { char ifar_name[16]; sa_family_t ifar_af; }; struct if_parent { char ifp_name[16]; char ifp_parent[16]; }; # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if_arp.h" 1 # 47 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if_arp.h" struct arphdr { u_int16_t ar_hrd; u_int16_t ar_pro; u_int8_t ar_hln; u_int8_t ar_pln; u_int16_t ar_op; # 73 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if_arp.h" }; struct arpreq { struct sockaddr arp_pa; struct sockaddr arp_ha; int arp_flags; }; # 455 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/if.h" 2 struct socket; struct ifnet; void if_alloc_sadl(struct ifnet *); void if_free_sadl(struct ifnet *); void if_attach(struct ifnet *); void if_attachtail(struct ifnet *); void if_attachhead(struct ifnet *); void if_deactivate(struct ifnet *); void if_detach(struct ifnet *); void if_down(struct ifnet *); void if_downall(void); void if_link_state_change(struct ifnet *); void if_up(struct ifnet *); int ifconf(u_long, caddr_t); void ifinit(void); int ifioctl(struct socket *, u_long, caddr_t, struct proc *); int ifpromisc(struct ifnet *, int); struct ifg_group *if_creategroup(const char *); int if_addgroup(struct ifnet *, const char *); int if_delgroup(struct ifnet *, const char *); void if_group_routechange(struct sockaddr *, struct sockaddr *); struct ifnet *ifunit(const char *); struct ifnet *if_get(unsigned int); void if_put(struct ifnet *); void ifnewlladdr(struct ifnet *); void if_congestion(void); int if_congested(void); __attribute__((__noreturn__)) void unhandled_af(int); int if_setlladdr(struct ifnet *, const uint8_t *); # 48 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" 1 # 49 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" struct rt_kmetrics { u_int64_t rmx_pksent; int64_t rmx_expire; u_int rmx_locks; u_int rmx_mtu; }; struct rt_metrics { u_int64_t rmx_pksent; int64_t rmx_expire; u_int rmx_locks; u_int rmx_mtu; u_int rmx_refcnt; u_int rmx_hopcount; u_int rmx_recvpipe; u_int rmx_sendpipe; u_int rmx_ssthresh; u_int rmx_rtt; u_int rmx_rttvar; u_int rmx_pad; }; # 84 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/rtable.h" 1 # 40 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/rtable.h" # 1 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/art.h" 1 # 29 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/art.h" struct art_root { struct srp ar_root; struct rwlock ar_lock; uint8_t ar_bits[32]; uint8_t ar_nlvl; uint8_t ar_alen; uint8_t ar_off; unsigned int ar_rtableid; }; struct rtentry; struct art_node { struct srpl an_rtlist; union { struct sockaddr *an__dst; struct art_node *an__gc; } an_pointer; uint8_t an_plen; }; void art_init(void); struct art_root *art_alloc(unsigned int, unsigned int, unsigned int); struct art_node *art_insert(struct art_root *, struct art_node *, uint8_t *, int); struct art_node *art_delete(struct art_root *, struct art_node *, uint8_t *, int); struct art_node *art_match(struct art_root *, uint8_t *, struct srp_ref *); struct art_node *art_lookup(struct art_root *, uint8_t *, int, struct srp_ref *); int art_walk(struct art_root *, int (*)(struct art_node *, void *), void *); struct art_node *art_get(struct sockaddr *, uint8_t); void art_put(struct art_node *); # 41 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/rtable.h" 2 int rtable_satoplen(sa_family_t, struct sockaddr *); void rtable_init(void); int rtable_exists(unsigned int); int rtable_add(unsigned int); unsigned int rtable_l2(unsigned int); unsigned int rtable_loindex(unsigned int); void rtable_l2set(unsigned int, unsigned int, unsigned int); struct rtentry *rtable_lookup(unsigned int, struct sockaddr *, struct sockaddr *, struct sockaddr *, uint8_t); struct rtentry *rtable_match(unsigned int, struct sockaddr *, uint32_t *); struct rtentry *rtable_iterate(struct rtentry *); int rtable_insert(unsigned int, struct sockaddr *, struct sockaddr *, struct sockaddr *, uint8_t, struct rtentry *); int rtable_delete(unsigned int, struct sockaddr *, struct sockaddr *, struct rtentry *); int rtable_walk(unsigned int, sa_family_t, int (*)(struct rtentry *, void *, unsigned int), void *); int rtable_mpath_capable(unsigned int, sa_family_t); struct rtentry *rtable_mpath_match(unsigned int, struct rtentry *, struct sockaddr *, uint8_t); int rtable_mpath_reprio(unsigned int, struct sockaddr *, struct sockaddr *, uint8_t, struct rtentry *); # 85 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" 2 # 95 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" struct rtentry { struct sockaddr *rt_dest; struct { struct srp se_next; } rt_next; struct sockaddr *rt_gateway; struct ifaddr *rt_ifa; caddr_t rt_llinfo; union { struct rtentry *_nh; unsigned int _ref; } RT_gw; struct rtentry *rt_parent; struct { struct rttimer *lh_first; } rt_timer; struct rt_kmetrics rt_rmx; unsigned int rt_ifidx; unsigned int rt_flags; int rt_refcnt; int rt_plen; uint16_t rt_labelid; uint8_t rt_priority; }; # 178 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" struct rtstat { u_int32_t rts_badredirect; u_int32_t rts_dynamic; u_int32_t rts_newgateway; u_int32_t rts_unreach; u_int32_t rts_wildcard; }; struct rt_tableinfo { u_short rti_tableid; u_short rti_domainid; }; struct rt_msghdr { u_short rtm_msglen; u_char rtm_version; u_char rtm_type; u_short rtm_hdrlen; u_short rtm_index; u_short rtm_tableid; u_char rtm_priority; u_char rtm_mpls; int rtm_addrs; int rtm_flags; int rtm_fmask; pid_t rtm_pid; int rtm_seq; int rtm_errno; u_int rtm_inits; struct rt_metrics rtm_rmx; }; # 292 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" struct sockaddr_rtlabel { u_int8_t sr_len; sa_family_t sr_family; char sr_label[32]; }; struct route { struct rtentry *ro_rt; u_long ro_tableid; struct sockaddr ro_dst; }; struct rt_addrinfo { int rti_addrs; struct sockaddr *rti_info[11]; int rti_flags; struct ifaddr *rti_ifa; struct rt_msghdr *rti_rtm; u_char rti_mpls; }; # 325 "/crypt/home/bluhm/openbsd/cvs/src/sys/net/route.h" struct rttimer { struct { struct rttimer *tqe_next; struct rttimer **tqe_prev; } rtt_next; struct { struct rttimer *le_next; struct rttimer **le_prev; } rtt_link; struct rttimer_queue *rtt_queue; struct rtentry *rtt_rt; void (*rtt_func)(struct rtentry *, struct rttimer *); time_t rtt_time; u_int rtt_tableid; }; struct rttimer_queue { long rtq_timeout; unsigned long rtq_count; struct { struct rttimer *tqh_first; struct rttimer **tqh_last; } rtq_head; struct { struct rttimer_queue *le_next; struct rttimer_queue **le_prev; } rtq_link; }; const char *rtlabel_id2name(u_int16_t); u_int16_t rtlabel_name2id(char *); struct sockaddr *rtlabel_id2sa(u_int16_t, struct sockaddr_rtlabel *); void rtlabel_unref(u_int16_t); extern struct rtstat rtstat; struct mbuf; struct socket; struct ifnet; struct sockaddr_in6; struct bfd_config; void route_init(void); int route_output(struct mbuf *, ...); int route_usrreq(struct socket *, int, struct mbuf *, struct mbuf *, struct mbuf *, struct proc *); void rt_ifmsg(struct ifnet *); void rt_ifannouncemsg(struct ifnet *, int); void rt_bfdmsg(struct bfd_config *); void rt_maskedcopy(struct sockaddr *, struct sockaddr *, struct sockaddr *); struct sockaddr *rt_plen2mask(struct rtentry *, struct sockaddr_in6 *); void rt_sendmsg(struct rtentry *, int, u_int); void rt_sendaddrmsg(struct rtentry *, int, struct ifaddr *); void rt_missmsg(int, struct rt_addrinfo *, int, uint8_t, u_int, int, u_int); int rt_setgate(struct rtentry *, struct sockaddr *, u_int); struct rtentry *rt_getll(struct rtentry *); void rt_setmetrics(u_long, const struct rt_metrics *, struct rt_kmetrics *); void rt_getmetrics(const struct rt_kmetrics *, struct rt_metrics *); int rt_timer_add(struct rtentry *, void(*)(struct rtentry *, struct rttimer *), struct rttimer_queue *, u_int); void rt_timer_remove_all(struct rtentry *); struct rttimer_queue *rt_timer_queue_create(u_int); void rt_timer_queue_change(struct rttimer_queue *, long); void rt_timer_queue_destroy(struct rttimer_queue *); unsigned long rt_timer_queue_count(struct rttimer_queue *); void rt_timer_timer(void *); int rtisvalid(struct rtentry *); int rt_hash(struct rtentry *, struct sockaddr *, uint32_t *); struct rtentry *rtalloc_mpath(struct sockaddr *, uint32_t *, u_int); struct rtentry *rtalloc(struct sockaddr *, int, unsigned int); void rtref(struct rtentry *); void rtfree(struct rtentry *); int rt_getifa(struct rt_addrinfo *, u_int); int rt_ifa_add(struct ifaddr *, int, struct sockaddr *); int rt_ifa_del(struct ifaddr *, int, struct sockaddr *); void rt_ifa_purge(struct ifaddr *); int rt_ifa_addlocal(struct ifaddr *); int rt_ifa_dellocal(struct ifaddr *); void rtredirect(struct sockaddr *, struct sockaddr *, struct sockaddr *, struct rtentry **, unsigned int); int rtrequest(int, struct rt_addrinfo *, u_int8_t, struct rtentry **, u_int); void rt_if_track(struct ifnet *); int rt_if_linkstate_change(struct rtentry *, void *, u_int); int rtdeletemsg(struct rtentry *, struct ifnet *, u_int); # 49 "/crypt/home/bluhm/openbsd/cvs/src/sys/kern/sys_socket.c" 2 struct fileops socketops = { soo_read, soo_write, soo_ioctl, soo_poll, soo_kqfilter, soo_stat, soo_close }; int soo_read(struct file *fp, off_t *poff, struct uio *uio, struct ucred *cred) { return (soreceive((struct socket *)fp->f_data, (struct mbuf **)((void *)0), uio, (struct mbuf **)((void *)0), (struct mbuf **)((void *)0), (int *)((void *)0), (socklen_t)0)); } int soo_write(struct file *fp, off_t *poff, struct uio *uio, struct ucred *cred) { return (sosend((struct socket *)fp->f_data, (struct mbuf *)((void *)0), uio, (struct mbuf *)((void *)0), (struct mbuf *)((void *)0), 0)); } int soo_ioctl(struct file *fp, u_long cmd, caddr_t data, struct proc *p) { struct socket *so = (struct socket *)fp->f_data; int s, error = 0; switch (cmd) { case ((unsigned long)0x80000000 | ((sizeof(int) & 0x1fff) << 16) | ((('f')) << 8) | ((126))): if (*(int *)data) so->so_state |= 0x100; else so->so_state &= ~0x100; return (0); case ((unsigned long)0x80000000 | ((sizeof(int) & 0x1fff) << 16) | ((('f')) << 8) | ((125))): if (*(int *)data) { so->so_state |= 0x200; so->so_rcv.sb_flags |= 0x10; so->so_snd.sb_flags |= 0x10; } else { so->so_state &= ~0x200; so->so_rcv.sb_flags &= ~0x10; so->so_snd.sb_flags &= ~0x10; } return (0); case ((unsigned long)0x40000000 | ((sizeof(int) & 0x1fff) << 16) | ((('f')) << 8) | ((127))): *(int *)data = so->so_rcv.sb_datacc; return (0); case ((unsigned long)0x80000000 | ((sizeof(int) & 0x1fff) << 16) | ((('s')) << 8) | ((8))): so->so_pgid = *(int *)data; so->so_siguid = p->p_ucred->cr_ruid; so->so_sigeuid = p->p_ucred->cr_uid; return (0); case ((unsigned long)0x40000000 | ((sizeof(int) & 0x1fff) << 16) | ((('s')) << 8) | ((9))): *(int *)data = so->so_pgid; return (0); case ((unsigned long)0x40000000 | ((sizeof(int) & 0x1fff) << 16) | ((('s')) << 8) | ((7))): *(int *)data = (so->so_state&0x040) != 0; return (0); } if ((((cmd) >> 8) & 0xff) == 'i') { do { rw_enter_write(&netlock); s = splraise(0x5); } while (0); error = ifioctl(so, cmd, data, p); do { spllower(s); rw_exit_write(&netlock); } while (0); return (error); } if ((((cmd) >> 8) & 0xff) == 'r') return (45); do { rw_enter_write(&netlock); s = splraise(0x5); } while (0); error = ((*so->so_proto->pr_usrreq)(so, 11, (struct mbuf *)cmd, (struct mbuf *)data, (struct mbuf *)((void *)0), p)); do { spllower(s); rw_exit_write(&netlock); } while (0); return (error); } int soo_poll(struct file *fp, int events, struct proc *p) { struct socket *so = fp->f_data; int revents = 0; int s; do { rw_enter_write(&netlock); s = splraise(0x5); } while (0); if (events & (0x0001 | 0x0040)) { if ((!((so)->so_sp && (so)->so_sp->ssp_socket) && ((so)->so_rcv.sb_cc >= (so)->so_rcv.sb_lowat || ((so)->so_state & 0x020) || (so)->so_qlen || (so)->so_error))) revents |= events & (0x0001 | 0x0040); } if (so->so_state & 0x800) { revents |= 0x0010; } else if (events & (0x0004 | 0x0004)) { if (((lmin((&(so)->so_snd)->sb_hiwat - (&(so)->so_snd)->sb_cc, (&(so)->so_snd)->sb_mbmax - (&(so)->so_snd)->sb_mbcnt) >= (so)->so_snd.sb_lowat && (((so)->so_state & 0x002) || ((so)->so_proto->pr_flags & 0x04)==0)) || ((so)->so_state & 0x010) || (so)->so_error)) revents |= events & (0x0004 | 0x0004); } if (events & (0x0002 | 0x0080)) { if (so->so_oobmark || (so->so_state & 0x040)) revents |= events & (0x0002 | 0x0080); } if (revents == 0) { if (events & (0x0001 | 0x0002 | 0x0040 | 0x0080)) { selrecord(p, &so->so_rcv.sb_sel); so->so_rcv.sb_flagsintr |= 0x08; } if (events & (0x0004 | 0x0004)) { selrecord(p, &so->so_snd.sb_sel); so->so_snd.sb_flagsintr |= 0x08; } } do { spllower(s); rw_exit_write(&netlock); } while (0); return (revents); } int soo_stat(struct file *fp, struct stat *ub, struct proc *p) { struct socket *so = fp->f_data; int s; memset(ub, 0, sizeof (*ub)); ub->st_mode = 0140000; if ((so->so_state & 0x020) == 0 || so->so_rcv.sb_cc != 0) ub->st_mode |= 0000400 | 0000040 | 0000004; if ((so->so_state & 0x010) == 0) ub->st_mode |= 0000200 | 0000020 | 0000002; ub->st_uid = so->so_euid; ub->st_gid = so->so_egid; do { rw_enter_write(&netlock); s = splraise(0x5); } while (0); (void) ((*so->so_proto->pr_usrreq)(so, 12, (struct mbuf *)ub, ((void *)0), ((void *)0), p)); do { spllower(s); rw_exit_write(&netlock); } while (0); return (0); } int soo_close(struct file *fp, struct proc *p) { int error = 0; if (fp->f_data) error = soclose(fp->f_data); fp->f_data = 0; return (error); }
the_stack_data/20451654.c
/*********************************************************************** * * TUTORATO 6: Stringhe * ==================== * * * Primo esercizio: codifica di un messaggio * ----------------------------------------- * * 1) Completa il file inserendo il corpo della funzione * "codifica_messaggio". Potrebbe essere opportuno * definire ulteriori funzioni di appoggio. * * 2) Compila il programma con il comando: * * gcc -Wall -o cesare cesare.c * * 3) Esegui il programma digitando al terminale: * * ./cesare * * 4) Verifica la correttezza del programma con il comando: * * ./pvcheck ./cesare * * Se i test hanno rilevato errori cerca di capirne * la causa, correggi il problema e riprova finche' il programma * non passa tutti i test. * ***********************************************************************/ #include <stdio.h> /* scanf, printf */ #include <stdlib.h> /* atoi */ #include <ctype.h> /* isalpha, isupper, toupper */ /* Lunghezza massima del messaggio da elaborare, senza contare il terminatore. */ #define LUNGHEZZA_MAX 4000 /* Trasforma il messaggio in chiaro nella sua versione cifrata utilizzando la chiave data. */ void codifica_messaggio(char *messaggio, int chiave) { /* COMPLETA LA FUNZIONE */ } /* Legge il messaggio inserito da terminale e lo memorizza nella stringa `messaggio'. */ void leggi_messaggio(char *messaggio) { char c; int i = 0; /* Indica il numero di caratteri gia` letti */ int letto; do { /* legge un carattere */ letto = scanf("%c", &c); /* letto < 1 quando la lettura fallisce (ad esempio perche' l'input si e` esaurito. */ if (letto == 1) { messaggio[i] = c; i++; } /* Continua finche' non si raggiunge la lunghezza limite e non si incontra il punto (o la fine dell'input). */ } while (letto == 1 && i < LUNGHEZZA_MAX && c != '.'); /* Imposta il terminatore della stringa */ messaggio[i] = '\0'; } int main(int argc, char *argv[]) { int chiave; /* +1 per il terminatore */ char messaggio[LUNGHEZZA_MAX + 1]; /* Si inizia leggendo il messaggio da elaborare */ leggi_messaggio(messaggio); if (argc != 2) { printf("Errore: specificare la chiave di cifratura\n"); } else { /* La chiave e` una stringa passata come primo parametro dalla riga di comando. La funzione atoi converte il testo in un numero intero. */ chiave = atoi(argv[1]); codifica_messaggio(messaggio, chiave); printf("[CIFRATO]\n"); printf("%s\n", messaggio); } /* Fine: tutto ok */ return 0; }
the_stack_data/767669.c
#include <stdio.h> int main (int argc, const char * argv[]) { int myInt = 6; double myDouble = 4.5; printf("%d\n", myInt); printf("%f\n", myDouble); return 0; }
the_stack_data/146651.c
#include<stdio.h> double metertofeet(double); double gramtopound(double); double ctof(double); void conversion(double,char); int main(void){ int num,i; i = 0; double con; char unit; scanf("%d",&num); for(i=0;i<num;i++){ scanf("%lf %c",&con,&unit); conversion(con,unit); } return 0; } void conversion(double x, char c){ double result; if(c =='m'){ result = metertofeet(x); printf("%lf ft\n",result); }else if(c == 'g'){ result = gramtopound(x); printf("%lf lbs\n",result); }else if(c =='c'){ result = ctof(x); printf("%lf f\n",result); } } double metertofeet(double x){ double result; result = x*3.2808; return result; } double gramtopound(double x){ double result; result = x * 0.002205; return result; } double ctof(double x){ double result; result = 32 + 1.8 * x; return result; }
the_stack_data/88268.c
#include <stdio.h> #define SPACE ' ' int main(void) { char ch;; while ((ch = getchar()) != '\n') { printf("%d \n", ch); if (SPACE == ch) { putchar(ch); } else { putchar(ch + 1); } } putchar(ch); return 0; }
the_stack_data/111078327.c
//file: _insn_test_mula_hu_ls_X0.c //op=170 #include <stdio.h> #include <stdlib.h> void func_exit(void) { printf("%s\n", __func__); exit(0); } void func_call(void) { printf("%s\n", __func__); exit(0); } unsigned long mem[2] = { 0x7c2b00bc8a60c95d, 0x8a6bdf08a51f10d3 }; int main(void) { unsigned long a[4] = { 0, 0 }; asm __volatile__ ( "moveli r22, -8315\n" "shl16insli r22, r22, 5404\n" "shl16insli r22, r22, 15177\n" "shl16insli r22, r22, -6931\n" "moveli r12, -20178\n" "shl16insli r12, r12, 16109\n" "shl16insli r12, r12, -17955\n" "shl16insli r12, r12, 766\n" "moveli r43, -29874\n" "shl16insli r43, r43, -7795\n" "shl16insli r43, r43, -2712\n" "shl16insli r43, r43, 26506\n" "{ mula_hu_ls r22, r12, r43 ; fnop }\n" "move %0, r22\n" "move %1, r12\n" "move %2, r43\n" :"=r"(a[0]),"=r"(a[1]),"=r"(a[2])); printf("%016lx\n", a[0]); printf("%016lx\n", a[1]); printf("%016lx\n", a[2]); return 0; }
the_stack_data/306403.c
/****** 树的存储结构 ******/ //树的双亲表示法 结点结构定义 #define MAX_TREE_SIZE 100 typedef char ElemType; typedef struct PTNode { ElemType data; //结点数据 int parent; //双亲位置 } PTNode; typedef struct { PTNode nodes[MAX_TREE_SIZE]; int root; //根的位置 int count; //结点数目 } PTree; //孩子表示法 //双亲孩子表示法 //孩子结点 typedef struct CTNode { int child; //孩子结点的下标 struct CTNode *next; //指向下一个孩子结点的指针 } *ChildPtr; //表头结构 typedef struct { ElemType data; //存放在树中的结点的数据 int parent; //存放双亲的下标 ChildPtr firstChild; //指向第一个孩子的指针 } CTBox; //树的结构 typedef struct { CTBox nodes[MAX_TREE_SIZE]; //结点数组 int r; //根的位置 int n; //结点数目 } PCTree; //二叉树的链式存储结构:二叉链表 typedef struct BiTNode { ElemType data; //数据域 struct BiTNode *lchild, *rchild; //指针域,左右两个孩子 } BiTNode, *BiTree;
the_stack_data/577873.c
int main() { int a = 150; char b = (char)a; return 0; }
the_stack_data/40763826.c
/* -*- mode: C; mode: fold -*- */ /* * LAME MP3 encoding engine * * Copyright (c) 1999-2000 Mark Taylor * Copyright (c) 2003 Olcios * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* $Id: mpglib_interface.c,v 1.1 2007-04-15 00:43:43 dave Exp $ */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef HAVE_MPGLIB #include <limits.h> #include <stdlib.h> #include <assert.h> #include "interface.h" #include "lame.h" #ifdef WITH_DMALLOC #include <dmalloc.h> #endif MPSTR mp; plotting_data *mpg123_pinfo = NULL; int lame_decode_exit(void) { ExitMP3(&mp); return 0; } int lame_decode_init(void) { InitMP3(&mp); return 0; } /* copy mono samples */ #define COPY_MONO(DST_TYPE, SRC_TYPE) \ DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw; \ SRC_TYPE *p_samples = (SRC_TYPE *)p; \ for (i = 0; i < processed_samples; i++) \ *pcm_l++ = (DST_TYPE)*p_samples++; /* copy stereo samples */ #define COPY_STEREO(DST_TYPE, SRC_TYPE) \ DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw, *pcm_r = (DST_TYPE *)pcm_r_raw; \ SRC_TYPE *p_samples = (SRC_TYPE *)p; \ for (i = 0; i < processed_samples; i++) { \ *pcm_l++ = (DST_TYPE)*p_samples++; \ *pcm_r++ = (DST_TYPE)*p_samples++; \ } /* * For lame_decode: return code * -1 error * 0 ok, but need more data before outputing any samples * n number of samples output. either 576 or 1152 depending on MP3 file. */ int lame_decode1_headersB_clipchoice(unsigned char *buffer, int len, char pcm_l_raw[], char pcm_r_raw[], mp3data_struct * mp3data, int *enc_delay, int *enc_padding, char *p, size_t psize, int decoded_sample_size, int (*decodeMP3_ptr)(PMPSTR,unsigned char *,int,char *,int,int*) ) { static const int smpls[2][4] = { /* Layer I II III */ {0, 384, 1152, 1152}, /* MPEG-1 */ {0, 384, 1152, 576} /* MPEG-2(.5) */ }; int processed_bytes; int processed_samples; /* processed samples per channel */ int ret; int i; mp3data->header_parsed = 0; ret = (*decodeMP3_ptr)(&mp, buffer, len, p, psize, &processed_bytes); /* three cases: * 1. headers parsed, but data not complete * mp.header_parsed==1 * mp.framesize=0 * mp.fsizeold=size of last frame, or 0 if this is first frame * * 2. headers, data parsed, but ancillary data not complete * mp.header_parsed==1 * mp.framesize=size of frame * mp.fsizeold=size of last frame, or 0 if this is first frame * * 3. frame fully decoded: * mp.header_parsed==0 * mp.framesize=0 * mp.fsizeold=size of frame (which is now the last frame) * */ if (mp.header_parsed || mp.fsizeold > 0 || mp.framesize > 0) { mp3data->header_parsed = 1; mp3data->stereo = mp.fr.stereo; mp3data->samplerate = freqs[mp.fr.sampling_frequency]; mp3data->mode = mp.fr.mode; mp3data->mode_ext = mp.fr.mode_ext; mp3data->framesize = smpls[mp.fr.lsf][mp.fr.lay]; /* free format, we need the entire frame before we can determine * the bitrate. If we haven't gotten the entire frame, bitrate=0 */ if (mp.fsizeold > 0) /* works for free format and fixed, no overrun, temporal results are < 400.e6 */ mp3data->bitrate = 8 * (4 + mp.fsizeold) * mp3data->samplerate / (1.e3 * mp3data->framesize) + 0.5; else if (mp.framesize > 0) mp3data->bitrate = 8 * (4 + mp.framesize) * mp3data->samplerate / (1.e3 * mp3data->framesize) + 0.5; else mp3data->bitrate = tabsel_123[mp.fr.lsf][mp.fr.lay - 1][mp.fr.bitrate_index]; if (mp.num_frames > 0) { /* Xing VBR header found and num_frames was set */ mp3data->totalframes = mp.num_frames; mp3data->nsamp = mp3data->framesize * mp.num_frames; *enc_delay = mp.enc_delay; *enc_padding = mp.enc_padding; } } switch (ret) { case MP3_OK: switch (mp.fr.stereo) { case 1: processed_samples = processed_bytes / decoded_sample_size; if (decoded_sample_size == sizeof(short)) { COPY_MONO(short,short) } else { COPY_MONO(sample_t,FLOAT) } break; case 2: processed_samples = (processed_bytes / decoded_sample_size) >> 1; if (decoded_sample_size == sizeof(short)) { COPY_STEREO(short,short) } else { COPY_STEREO(sample_t,FLOAT) } break; default: processed_samples = -1; assert(0); break; } break; case MP3_NEED_MORE: processed_samples = 0; break; default: assert(0); case MP3_ERR: processed_samples = -1; break; } /*fprintf(stderr,"ok, more, err: %i %i %i\n", MP3_OK, MP3_NEED_MORE, MP3_ERR );*/ /*fprintf(stderr,"ret = %i out=%i\n", ret, processed_samples );*/ return processed_samples; } #define OUTSIZE_CLIPPED 4096*sizeof(short) int lame_decode1_headersB(unsigned char *buffer, int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data, int *enc_delay, int *enc_padding) { static char out[OUTSIZE_CLIPPED]; return lame_decode1_headersB_clipchoice(buffer, len, (char *)pcm_l, (char *)pcm_r, mp3data, enc_delay, enc_padding, out, OUTSIZE_CLIPPED, sizeof(short), decodeMP3 ); } /* we forbid input with more than 1152 samples per channel for output in the unclipped mode */ #define OUTSIZE_UNCLIPPED 1152*2*sizeof(FLOAT) int lame_decode1_unclipped(unsigned char *buffer, int len, sample_t pcm_l[], sample_t pcm_r[]) { static char out[OUTSIZE_UNCLIPPED]; mp3data_struct mp3data; int enc_delay,enc_padding; return lame_decode1_headersB_clipchoice(buffer, len, (char *)pcm_l, (char *)pcm_r, &mp3data, &enc_delay, &enc_padding, out, OUTSIZE_UNCLIPPED, sizeof(FLOAT), decodeMP3_unclipped ); } /* * For lame_decode: return code * -1 error * 0 ok, but need more data before outputing any samples * n number of samples output. Will be at most one frame of * MPEG data. */ int lame_decode1_headers(unsigned char *buffer, int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data) { int enc_delay,enc_padding; return lame_decode1_headersB(buffer,len,pcm_l,pcm_r,mp3data,&enc_delay,&enc_padding); } int lame_decode1(unsigned char *buffer, int len, short pcm_l[], short pcm_r[]) { mp3data_struct mp3data; return lame_decode1_headers(buffer, len, pcm_l, pcm_r, &mp3data); } /* * For lame_decode: return code * -1 error * 0 ok, but need more data before outputing any samples * n number of samples output. a multiple of 576 or 1152 depending on MP3 file. */ int lame_decode_headers(unsigned char *buffer, int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data) { int ret; int totsize = 0; /* number of decoded samples per channel */ while (1) { switch (ret = lame_decode1_headers(buffer, len, pcm_l + totsize, pcm_r + totsize, mp3data)) { case -1: return ret; case 0: return totsize; default: totsize += ret; len = 0; /* future calls to decodeMP3 are just to flush buffers */ break; } } } int lame_decode(unsigned char *buffer, int len, short pcm_l[], short pcm_r[]) { mp3data_struct mp3data; return lame_decode_headers(buffer, len, pcm_l, pcm_r, &mp3data); } #endif /* end of mpglib_interface.c */
the_stack_data/8023.c
/* * Copyright (C) 2009 - 2012 Robin Seggelmann, [email protected], * Michael Tuexen, [email protected] * 2019 Felix Weinrank, [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 the project 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 PROJECT 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 PROJECT 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 WIN32 #include <winsock2.h> #include <Ws2tcpip.h> #define in_port_t u_short #define ssize_t int #else #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #endif #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/opensslv.h> #define BUFFER_SIZE (1<<16) #define COOKIE_SECRET_LENGTH 16 int verbose = 0; int veryverbose = 0; unsigned char cookie_secret[COOKIE_SECRET_LENGTH]; int cookie_initialized=0; char Usage[] = "Usage: dtls_udp_echo [options] [address]\n" "Options:\n" " -l message length (Default: 100 Bytes)\n" " -L local address\n" " -p port (Default: 23232)\n" " -n number of messages to send (Default: 5)\n" " -v verbose\n" " -V very verbose\n"; #if WIN32 static HANDLE* mutex_buf = NULL; #else static pthread_mutex_t* mutex_buf = NULL; #endif static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) #ifdef WIN32 WaitForSingleObject(mutex_buf[n], INFINITE); else ReleaseMutex(mutex_buf[n]); #else pthread_mutex_lock(&mutex_buf[n]); else pthread_mutex_unlock(&mutex_buf[n]); #endif } static unsigned long id_function(void) { #ifdef WIN32 return (unsigned long) GetCurrentThreadId(); #else return (unsigned long) pthread_self(); #endif } int THREAD_setup() { int i; #ifdef WIN32 mutex_buf = (HANDLE*) malloc(CRYPTO_num_locks() * sizeof(HANDLE)); #else mutex_buf = (pthread_mutex_t*) malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); #endif if (!mutex_buf) return 0; for (i = 0; i < CRYPTO_num_locks(); i++) #ifdef WIN32 mutex_buf[i] = CreateMutex(NULL, FALSE, NULL); #else pthread_mutex_init(&mutex_buf[i], NULL); #endif CRYPTO_set_id_callback(id_function); CRYPTO_set_locking_callback(locking_function); return 1; } int THREAD_cleanup() { int i; if (!mutex_buf) return 0; CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for (i = 0; i < CRYPTO_num_locks(); i++) #ifdef WIN32 CloseHandle(mutex_buf[i]); #else pthread_mutex_destroy(&mutex_buf[i]); #endif free(mutex_buf); mutex_buf = NULL; return 1; } int handle_socket_error() { switch (errno) { case EINTR: /* Interrupted system call. * Just ignore. */ printf("Interrupted system call!\n"); return 1; case EBADF: /* Invalid socket. * Must close connection. */ printf("Invalid socket!\n"); return 0; break; #ifdef EHOSTDOWN case EHOSTDOWN: /* Host is down. * Just ignore, might be an attacker * sending fake ICMP messages. */ printf("Host is down!\n"); return 1; #endif #ifdef ECONNRESET case ECONNRESET: /* Connection reset by peer. * Just ignore, might be an attacker * sending fake ICMP messages. */ printf("Connection reset by peer!\n"); return 1; #endif case ENOMEM: /* Out of memory. * Must close connection. */ printf("Out of memory!\n"); return 0; break; case EACCES: /* Permission denied. * Just ignore, we might be blocked * by some firewall policy. Try again * and hope for the best. */ printf("Permission denied!\n"); return 1; break; default: /* Something unexpected happened */ printf("Unexpected error! (errno = %d)\n", errno); return 0; break; } return 0; } int generate_cookie(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) { unsigned char *buffer, result[EVP_MAX_MD_SIZE]; unsigned int length = 0, resultlength; union { struct sockaddr_storage ss; struct sockaddr_in6 s6; struct sockaddr_in s4; } peer; /* Initialize a random secret */ if (!cookie_initialized) { if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH)) { printf("error setting random cookie secret\n"); return 0; } cookie_initialized = 1; } /* Read peer information */ (void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer); /* Create buffer with peer's address and port */ length = 0; switch (peer.ss.ss_family) { case AF_INET: length += sizeof(struct in_addr); break; case AF_INET6: length += sizeof(struct in6_addr); break; default: OPENSSL_assert(0); break; } length += sizeof(in_port_t); buffer = (unsigned char*) OPENSSL_malloc(length); if (buffer == NULL) { printf("out of memory\n"); return 0; } switch (peer.ss.ss_family) { case AF_INET: memcpy(buffer, &peer.s4.sin_port, sizeof(in_port_t)); memcpy(buffer + sizeof(peer.s4.sin_port), &peer.s4.sin_addr, sizeof(struct in_addr)); break; case AF_INET6: memcpy(buffer, &peer.s6.sin6_port, sizeof(in_port_t)); memcpy(buffer + sizeof(in_port_t), &peer.s6.sin6_addr, sizeof(struct in6_addr)); break; default: OPENSSL_assert(0); break; } /* Calculate HMAC of buffer using the secret */ HMAC(EVP_sha1(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH, (const unsigned char*) buffer, length, result, &resultlength); OPENSSL_free(buffer); memcpy(cookie, result, resultlength); *cookie_len = resultlength; return 1; } int verify_cookie(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) { unsigned char *buffer, result[EVP_MAX_MD_SIZE]; unsigned int length = 0, resultlength; union { struct sockaddr_storage ss; struct sockaddr_in6 s6; struct sockaddr_in s4; } peer; /* If secret isn't initialized yet, the cookie can't be valid */ if (!cookie_initialized) return 0; /* Read peer information */ (void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer); /* Create buffer with peer's address and port */ length = 0; switch (peer.ss.ss_family) { case AF_INET: length += sizeof(struct in_addr); break; case AF_INET6: length += sizeof(struct in6_addr); break; default: OPENSSL_assert(0); break; } length += sizeof(in_port_t); buffer = (unsigned char*) OPENSSL_malloc(length); if (buffer == NULL) { printf("out of memory\n"); return 0; } switch (peer.ss.ss_family) { case AF_INET: memcpy(buffer, &peer.s4.sin_port, sizeof(in_port_t)); memcpy(buffer + sizeof(in_port_t), &peer.s4.sin_addr, sizeof(struct in_addr)); break; case AF_INET6: memcpy(buffer, &peer.s6.sin6_port, sizeof(in_port_t)); memcpy(buffer + sizeof(in_port_t), &peer.s6.sin6_addr, sizeof(struct in6_addr)); break; default: OPENSSL_assert(0); break; } /* Calculate HMAC of buffer using the secret */ HMAC(EVP_sha1(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH, (const unsigned char*) buffer, length, result, &resultlength); OPENSSL_free(buffer); if (cookie_len == resultlength && memcmp(result, cookie, resultlength) == 0) return 1; return 0; } struct pass_info { union { struct sockaddr_storage ss; struct sockaddr_in6 s6; struct sockaddr_in s4; } server_addr, client_addr; SSL *ssl; }; int dtls_verify_callback (int ok, X509_STORE_CTX *ctx) { /* This function should ask the user * if he trusts the received certificate. * Here we always trust. */ return 1; } #ifdef WIN32 DWORD WINAPI connection_handle(LPVOID *info) { #else void* connection_handle(void *info) { #endif ssize_t len; char buf[BUFFER_SIZE]; char addrbuf[INET6_ADDRSTRLEN]; struct pass_info *pinfo = (struct pass_info*) info; SSL *ssl = pinfo->ssl; int fd, reading = 0, ret; const int on = 1, off = 0; struct timeval timeout; int num_timeouts = 0, max_timeouts = 5; #ifndef WIN32 pthread_detach(pthread_self()); #endif OPENSSL_assert(pinfo->client_addr.ss.ss_family == pinfo->server_addr.ss.ss_family); fd = socket(pinfo->client_addr.ss.ss_family, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); goto cleanup; } #ifdef WIN32 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, (socklen_t) sizeof(on)); #else setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on)); #if defined(SO_REUSEPORT) && !defined(__linux__) setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void*) &on, (socklen_t) sizeof(on)); #endif #endif switch (pinfo->client_addr.ss.ss_family) { case AF_INET: if (bind(fd, (const struct sockaddr *) &pinfo->server_addr, sizeof(struct sockaddr_in))) { perror("bind"); goto cleanup; } if (connect(fd, (struct sockaddr *) &pinfo->client_addr, sizeof(struct sockaddr_in))) { perror("connect"); goto cleanup; } break; case AF_INET6: setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof(off)); if (bind(fd, (const struct sockaddr *) &pinfo->server_addr, sizeof(struct sockaddr_in6))) { perror("bind"); goto cleanup; } if (connect(fd, (struct sockaddr *) &pinfo->client_addr, sizeof(struct sockaddr_in6))) { perror("connect"); goto cleanup; } break; default: OPENSSL_assert(0); break; } /* Set new fd and set BIO to connected */ BIO_set_fd(SSL_get_rbio(ssl), fd, BIO_NOCLOSE); BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SET_CONNECTED, 0, &pinfo->client_addr.ss); /* Finish handshake */ do { ret = SSL_accept(ssl); } while (ret == 0); if (ret < 0) { perror("SSL_accept"); printf("%s\n", ERR_error_string(ERR_get_error(), buf)); goto cleanup; } /* Set and activate timeouts */ timeout.tv_sec = 5; timeout.tv_usec = 0; BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); if (verbose) { if (pinfo->client_addr.ss.ss_family == AF_INET) { printf ("\nThread %lx: accepted connection from %s:%d\n", id_function(), inet_ntop(AF_INET, &pinfo->client_addr.s4.sin_addr, addrbuf, INET6_ADDRSTRLEN), ntohs(pinfo->client_addr.s4.sin_port)); } else { printf ("\nThread %lx: accepted connection from %s:%d\n", id_function(), inet_ntop(AF_INET6, &pinfo->client_addr.s6.sin6_addr, addrbuf, INET6_ADDRSTRLEN), ntohs(pinfo->client_addr.s6.sin6_port)); } } if (veryverbose && SSL_get_peer_certificate(ssl)) { printf ("------------------------------------------------------------\n"); X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)), 1, XN_FLAG_MULTILINE); printf("\n\n Cipher: %s", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl))); printf ("\n------------------------------------------------------------\n\n"); } while (!(SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) && num_timeouts < max_timeouts) { reading = 1; while (reading) { len = SSL_read(ssl, buf, sizeof(buf)); switch (SSL_get_error(ssl, len)) { case SSL_ERROR_NONE: if (verbose) { printf("Thread %lx: read %d bytes\n", id_function(), (int) len); printf("buf[0] is %c\n", buf[0]); } reading = 0; break; case SSL_ERROR_WANT_READ: /* Handle socket timeouts */ if (BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)) { num_timeouts++; reading = 0; } /* Just try again */ break; case SSL_ERROR_ZERO_RETURN: reading = 0; break; case SSL_ERROR_SYSCALL: printf("Socket read error: "); if (!handle_socket_error()) goto cleanup; reading = 0; break; case SSL_ERROR_SSL: printf("SSL read error: "); printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len)); goto cleanup; break; default: printf("Unexpected error while reading!\n"); goto cleanup; break; } } if (len > 0) { buf[0] = 's'; len = SSL_write(ssl, buf, len); switch (SSL_get_error(ssl, len)) { case SSL_ERROR_NONE: if (verbose) { printf("Thread %lx: wrote %d bytes\n", id_function(), (int) len); } break; case SSL_ERROR_WANT_WRITE: /* Can't write because of a renegotiation, so * we actually have to retry sending this message... */ break; case SSL_ERROR_WANT_READ: /* continue with reading */ break; case SSL_ERROR_SYSCALL: printf("Socket write error: "); if (!handle_socket_error()) goto cleanup; //reading = 0; break; case SSL_ERROR_SSL: printf("SSL write error: "); printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len)); goto cleanup; break; default: printf("Unexpected error while writing!\n"); goto cleanup; break; } } } SSL_shutdown(ssl); cleanup: #ifdef WIN32 closesocket(fd); #else close(fd); #endif free(info); SSL_free(ssl); if (verbose) printf("Thread %lx: done, connection closed.\n", id_function()); #if WIN32 ExitThread(0); #else pthread_exit( (void *) NULL ); #endif } void start_server(int port, char *local_address) { int fd; union { struct sockaddr_storage ss; struct sockaddr_in s4; struct sockaddr_in6 s6; } server_addr, client_addr; #if WIN32 WSADATA wsaData; DWORD tid; #else pthread_t tid; #endif SSL_CTX *ctx; SSL *ssl; BIO *bio; struct timeval timeout; struct pass_info *info; const int on = 1, off = 0; memset(&server_addr, 0, sizeof(struct sockaddr_storage)); if (strlen(local_address) == 0) { server_addr.s6.sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN server_addr.s6.sin6_len = sizeof(struct sockaddr_in6); #endif server_addr.s6.sin6_addr = in6addr_any; server_addr.s6.sin6_port = htons(port); } else { if (inet_pton(AF_INET, local_address, &server_addr.s4.sin_addr) == 1) { server_addr.s4.sin_family = AF_INET; #ifdef HAVE_SIN_LEN server_addr.s4.sin_len = sizeof(struct sockaddr_in); #endif server_addr.s4.sin_port = htons(port); } else if (inet_pton(AF_INET6, local_address, &server_addr.s6.sin6_addr) == 1) { server_addr.s6.sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN server_addr.s6.sin6_len = sizeof(struct sockaddr_in6); #endif server_addr.s6.sin6_port = htons(port); } else { return; } } //THREAD_setup(); OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); ctx = SSL_CTX_new(DTLS_server_method()); /* We accept all ciphers, including NULL. * Not recommended beyond testing and debugging */ //SSL_CTX_set_cipher_list(ctx, "ALL:NULL:eNULL:aNULL"); SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); if (!SSL_CTX_use_certificate_file(ctx, "certs/server-cert.pem", SSL_FILETYPE_PEM)) printf("\nERROR: no certificate found!"); if (!SSL_CTX_use_PrivateKey_file(ctx, "certs/server-key.pem", SSL_FILETYPE_PEM)) printf("\nERROR: no private key found!"); if (!SSL_CTX_check_private_key (ctx)) printf("\nERROR: invalid private key!"); /* Client has to authenticate */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, dtls_verify_callback); SSL_CTX_set_read_ahead(ctx, 1); SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie); SSL_CTX_set_cookie_verify_cb(ctx, &verify_cookie); #ifdef WIN32 WSAStartup(MAKEWORD(2, 2), &wsaData); #endif fd = socket(server_addr.ss.ss_family, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); exit(-1); } #ifdef WIN32 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, (socklen_t) sizeof(on)); #else setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on)); #if defined(SO_REUSEPORT) && !defined(__linux__) setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void*) &on, (socklen_t) sizeof(on)); #endif #endif if (server_addr.ss.ss_family == AF_INET) { if (bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in))) { perror("bind"); exit(EXIT_FAILURE); } } else { setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof(off)); if (bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in6))) { perror("bind"); exit(EXIT_FAILURE); } } while (1) { memset(&client_addr, 0, sizeof(struct sockaddr_storage)); /* Create BIO */ bio = BIO_new_dgram(fd, BIO_NOCLOSE); /* Set and activate timeouts */ timeout.tv_sec = 5; timeout.tv_usec = 0; BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); ssl = SSL_new(ctx); SSL_set_bio(ssl, bio, bio); SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE); printf("server listening..., the ssl address is %d\n", (int) ssl); //printf("server listening...\n"); // BIO_ADDR is not defined in openssl 1.0.2 //while (DTLSv1_listen(ssl, (BIO_ADDR *) &client_addr) <= 0); while (DTLSv1_listen(ssl, &client_addr) <= 0); info = (struct pass_info*) malloc (sizeof(struct pass_info)); memcpy(&info->server_addr, &server_addr, sizeof(struct sockaddr_storage)); memcpy(&info->client_addr, &client_addr, sizeof(struct sockaddr_storage)); info->ssl = ssl; #ifdef WIN32 if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) connection_handle, info, 0, &tid) == NULL) { exit(-1); } #else if (pthread_create( &tid, NULL, connection_handle, info) != 0) { perror("pthread_create"); exit(-1); } #endif } //THREAD_cleanup(); #ifdef WIN32 WSACleanup(); #endif } void start_client(char *remote_address, char *local_address, int port, int length, int messagenumber) { int fd, retval; union { struct sockaddr_storage ss; struct sockaddr_in s4; struct sockaddr_in6 s6; } remote_addr, local_addr; char buf[BUFFER_SIZE]; char addrbuf[INET6_ADDRSTRLEN]; socklen_t len; SSL_CTX *ctx; SSL *ssl; BIO *bio; int reading = 0; struct timeval timeout; #if WIN32 WSADATA wsaData; #endif memset((void *) &remote_addr, 0, sizeof(struct sockaddr_storage)); memset((void *) &local_addr, 0, sizeof(struct sockaddr_storage)); if (inet_pton(AF_INET, remote_address, &remote_addr.s4.sin_addr) == 1) { remote_addr.s4.sin_family = AF_INET; #ifdef HAVE_SIN_LEN remote_addr.s4.sin_len = sizeof(struct sockaddr_in); #endif remote_addr.s4.sin_port = htons(port); } else if (inet_pton(AF_INET6, remote_address, &remote_addr.s6.sin6_addr) == 1) { remote_addr.s6.sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN remote_addr.s6.sin6_len = sizeof(struct sockaddr_in6); #endif remote_addr.s6.sin6_port = htons(port); } else { return; } #ifdef WIN32 WSAStartup(MAKEWORD(2, 2), &wsaData); #endif fd = socket(remote_addr.ss.ss_family, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); exit(-1); } if (strlen(local_address) > 0) { if (inet_pton(AF_INET, local_address, &local_addr.s4.sin_addr) == 1) { local_addr.s4.sin_family = AF_INET; #ifdef HAVE_SIN_LEN local_addr.s4.sin_len = sizeof(struct sockaddr_in); #endif local_addr.s4.sin_port = htons(0); } else if (inet_pton(AF_INET6, local_address, &local_addr.s6.sin6_addr) == 1) { local_addr.s6.sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN local_addr.s6.sin6_len = sizeof(struct sockaddr_in6); #endif local_addr.s6.sin6_port = htons(0); } else { return; } OPENSSL_assert(remote_addr.ss.ss_family == local_addr.ss.ss_family); if (local_addr.ss.ss_family == AF_INET) { if (bind(fd, (const struct sockaddr *) &local_addr, sizeof(struct sockaddr_in))) { perror("bind"); exit(EXIT_FAILURE); } } else { if (bind(fd, (const struct sockaddr *) &local_addr, sizeof(struct sockaddr_in6))) { perror("bind"); exit(EXIT_FAILURE); } } } OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); ctx = SSL_CTX_new(DTLS_client_method()); //SSL_CTX_set_cipher_list(ctx, "eNULL:!MD5"); if (!SSL_CTX_use_certificate_file(ctx, "certs/client-cert.pem", SSL_FILETYPE_PEM)) printf("\nERROR: no certificate found!"); if (!SSL_CTX_use_PrivateKey_file(ctx, "certs/client-key.pem", SSL_FILETYPE_PEM)) printf("\nERROR: no private key found!"); if (!SSL_CTX_check_private_key (ctx)) printf("\nERROR: invalid private key!"); SSL_CTX_set_verify_depth (ctx, 2); SSL_CTX_set_read_ahead(ctx, 1); ssl = SSL_new(ctx); /* Create BIO, connect and set to already connected */ bio = BIO_new_dgram(fd, BIO_CLOSE); if (remote_addr.ss.ss_family == AF_INET) { if (connect(fd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in))) { perror("connect"); } } else { if (connect(fd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in6))) { perror("connect"); } } BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &remote_addr.ss); SSL_set_bio(ssl, bio, bio); retval = SSL_connect(ssl); if (retval <= 0) { switch (SSL_get_error(ssl, retval)) { case SSL_ERROR_ZERO_RETURN: fprintf(stderr, "SSL_connect failed with SSL_ERROR_ZERO_RETURN\n"); break; case SSL_ERROR_WANT_READ: fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_READ\n"); break; case SSL_ERROR_WANT_WRITE: fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_WRITE\n"); break; case SSL_ERROR_WANT_CONNECT: fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_CONNECT\n"); break; case SSL_ERROR_WANT_ACCEPT: fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_ACCEPT\n"); break; case SSL_ERROR_WANT_X509_LOOKUP: fprintf(stderr, "SSL_connect failed with SSL_ERROR_WANT_X509_LOOKUP\n"); break; case SSL_ERROR_SYSCALL: fprintf(stderr, "SSL_connect failed with SSL_ERROR_SYSCALL\n"); break; case SSL_ERROR_SSL: fprintf(stderr, "SSL_connect failed with SSL_ERROR_SSL\n"); break; default: fprintf(stderr, "SSL_connect failed with unknown error\n"); break; } exit(EXIT_FAILURE); } /* Set and activate timeouts */ timeout.tv_sec = 3; timeout.tv_usec = 0; BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); if (verbose) { if (remote_addr.ss.ss_family == AF_INET) { printf ("\nConnected to %s\n", inet_ntop(AF_INET, &remote_addr.s4.sin_addr, addrbuf, INET6_ADDRSTRLEN)); } else { printf ("\nConnected to %s\n", inet_ntop(AF_INET6, &remote_addr.s6.sin6_addr, addrbuf, INET6_ADDRSTRLEN)); } } if (veryverbose && SSL_get_peer_certificate(ssl)) { printf ("------------------------------------------------------------\n"); X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)), 1, XN_FLAG_MULTILINE); printf("\n\n Cipher: %s", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl))); printf ("\n------------------------------------------------------------\n\n"); } while (!(SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN)) { if (messagenumber > 0) { buf[0] = 'c'; len = SSL_write(ssl, buf, length); switch (SSL_get_error(ssl, len)) { case SSL_ERROR_NONE: if (verbose) { printf("wrote %d bytes\n", (int) len); } messagenumber--; break; case SSL_ERROR_WANT_WRITE: /* Just try again later */ break; case SSL_ERROR_WANT_READ: /* continue with reading */ break; case SSL_ERROR_SYSCALL: printf("Socket write error: "); if (!handle_socket_error()) exit(1); //reading = 0; break; case SSL_ERROR_SSL: printf("SSL write error: "); printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len)); exit(1); break; default: printf("Unexpected error while writing!\n"); exit(1); break; } #if 0 /* Send heartbeat. Requires Heartbeat extension. */ if (messagenumber == 2) SSL_heartbeat(ssl); #endif /* Shut down if all messages sent */ if (messagenumber == 0) SSL_shutdown(ssl); } reading = 1; while (reading) { len = SSL_read(ssl, buf, sizeof(buf)); switch (SSL_get_error(ssl, len)) { case SSL_ERROR_NONE: if (verbose) { printf("read %d bytes\n", (int) len); printf("buf[0] is %c\n", buf[0]); } reading = 0; break; case SSL_ERROR_WANT_READ: /* Stop reading on socket timeout, otherwise try again */ if (BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)) { printf("Timeout! No response received.\n"); reading = 0; } break; case SSL_ERROR_ZERO_RETURN: reading = 0; break; case SSL_ERROR_SYSCALL: printf("Socket read error: "); if (!handle_socket_error()) exit(1); reading = 0; break; case SSL_ERROR_SSL: printf("SSL read error: "); printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len)); exit(1); break; default: printf("Unexpected error while reading!\n"); exit(1); break; } } } #ifdef WIN32 closesocket(fd); #else close(fd); #endif if (verbose) printf("Connection closed.\n"); #ifdef WIN32 WSACleanup(); #endif } int main(int argc, char **argv) { int port = 23232; int length = 100; int messagenumber = 5; char local_addr[INET6_ADDRSTRLEN+1]; memset(local_addr, 0, INET6_ADDRSTRLEN+1); argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-l") == 0) { if (--argc < 1) goto cmd_err; length = atoi(*++argv); if (length > BUFFER_SIZE) length = BUFFER_SIZE; } else if (strcmp(*argv, "-L") == 0) { if (--argc < 1) goto cmd_err; strncpy(local_addr, *++argv, INET6_ADDRSTRLEN); } else if (strcmp(*argv, "-n") == 0) { if (--argc < 1) goto cmd_err; messagenumber = atoi(*++argv); } else if (strcmp(*argv, "-p") == 0) { if (--argc < 1) goto cmd_err; port = atoi(*++argv); } else if (strcmp(*argv, "-v") == 0) { verbose = 1; } else if (strcmp(*argv, "-V") == 0) { verbose = 1; veryverbose = 1; } else if (((*argv)[0]) == '-') { goto cmd_err; } else break; argc--; argv++; } if (argc > 1) goto cmd_err; // remove the version check /*if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) { printf("Warning: OpenSSL version mismatch!\n"); printf("Compiled against %s\n", OPENSSL_VERSION_TEXT); printf("Linked against %s\n", OpenSSL_version(OPENSSL_VERSION)); if (OpenSSL_version_num() >> 20 != OPENSSL_VERSION_NUMBER >> 20) { printf("Error: Major and minor version numbers must match, exiting.\n"); exit(EXIT_FAILURE); } } else if (verbose) { printf("Using %s\n", OpenSSL_version(OPENSSL_VERSION)); } if (OPENSSL_VERSION_NUMBER < 0x1010102fL) { printf("Error: %s is unsupported, use OpenSSL Version 1.1.1a or higher\n", OpenSSL_version(OPENSSL_VERSION)); exit(EXIT_FAILURE); }*/ if (argc == 1) start_client(*argv, local_addr, port, length, messagenumber); else start_server(port, local_addr); return 0; cmd_err: fprintf(stderr, "%s\n", Usage); return 1; }
the_stack_data/77662.c
/* Modified version of itoa; to handle the situation of MIN_INT of limits.h in the previous number = -2147483648 would fail at n =-n,because the max value of integer is 2147483647 modifying itoa to handle these situations. sign is stored as the number itself, absolute value of each digit is stored in the string and while loop is tested not for 0 itoa: convert an integer to string */ #include<stdio.h> #include<string.h> #define MAXLINE 1000 #define abs(x) ( (x) > 0 ? (x): -(x)) void itoa(int n,char s[]); void reverse(char s[]); int main(void) { int number; char str[MAXLINE]; /* number=-2345645; */ number = -2147483648; printf("Integer %d printed as\n String:",number); itoa(number,str); printf("%s",str); return 0; } void itoa(int n,char s[]) { int i,sign; sign=n; i = 0; do { s[i++]= abs(n%10) + '0'; }while((n/=10)!=0); if( sign < 0) s[i++]='-'; s[i]='\0'; reverse(s); } void reverse(char s[]) { int c,i,j; for(i=0,j=strlen(s)-1;i<j;i++,j--) c=s[i],s[i]=s[j],s[j]=c; }
the_stack_data/50124.c
#include <stdio.h> int add(int a, int b); int main() { return 0; }
the_stack_data/778725.c
#include <stdio.h> #include <stdlib.h> void receive(int number1, int number2) { /* * Creates an integer variable and assigns the sum of both parameters * Does not return anything */ int c = number1 + number2; } int result() { /* * Takes no parameter, declares an integer variable without initialization * Returns that variable (indetermined) */ int x; return x; } /* Main program expects up to two integers as inpunts, from command line * If any parameter is omited, default value is 0 * If more than two parameters are given, only the first two will be taken, the rest ignored * If any parameter is not integer, the behavior is not defined. The program is expected to fail */ int main (int argc, char *argv[]) { int first = 0; // Default for first variable is 0 int second = 0; // Default for second variable is 0 /* * The following block only parses the input and assigns the values to variables * If second variable is empty, default value is kept. If both are empty, both defaults are kept * Some non-numericals may be converted to zero, dependending on the implementation of strtol */ if (argc >= 3) { second = (int)strtol(argv[2],NULL,10); first = (int)strtol(argv[1],NULL,10); } else if (argc==2) { first = (int)strtol(argv[1],NULL,10); } // Now we call the two functions we defined above. Result 'should' be indetermined... or should it? receive(first, second); int surprise = result(); printf ("Sum is: %d \n", surprise); printf ("Do you know what just happened? And why? \n\n"); return 0; }
the_stack_data/1248225.c
//#Safe //@ ltl invariant positive: (<> AP(output == 26)); extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume() __attribute__ ((__noreturn__)); extern int __VERIFIER_nondet_int() __attribute__ ((__noreturn__)); int input; int output; int aux=0; int main() { int tmp; // default output output = -1; // main i/o-loop while(1) { // read input input = __VERIFIER_nondet_int(); __VERIFIER_assume(input == 4 || input == 2 || input == 3 || input == 6 || input == 5 || input == 1 ); // operate eca engine if(input == 4){ tmp = 26; } else { aux++; if( aux > 10){ tmp = aux; } else{ tmp = 0; } } output = tmp; } }
the_stack_data/167330233.c
#include<stdio.h> struct Node { int data; struct Node* next; }; struct Node* head; void insert(int data) { struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->data = data; if (head == NULL) { head = newnode; return; } struct Node* traverse = head; while (traverse != NULL) { if (traverse->next == NULL) { traverse->next = newnode; return; } traverse = traverse->next; } } void print() { struct Node* traverse = head; while (traverse != NULL) { printf("%d-->", traverse->data); traverse = traverse->next; } } int main() { insert(5); insert(15); insert(25); insert(35); insert(45); print(); return 0; }
the_stack_data/170452549.c
#include <stdio.h> int isPrime(int num) { for(int i=2; i<=num/2; i++) if (!(num%i)) return 0; return 1; }
the_stack_data/97324.c
#include <stdio.h> #include <stdlib.h> int table[100][100]; int count[100], Nchild[100]; int Nlevel; void dfs(x, level) { if (Nchild[x] == 0) { count[level]++; if (level > Nlevel) Nlevel = level; return; } for (int i = 0; i < Nchild[x]; ++i) dfs(table[x][i], level + 1); } int main() { int N, M, ID, k, cnt = 0; scanf("%d %d", &N, &M); for (int i = 0; i < M; ++i) { scanf("%d %d", &ID, &k); for (int j = 0; j < k; ++j) { scanf("%d", &table[ID][Nchild[ID]++]); } } dfs(1, 0); printf("%d", count[0]); for (int i = 1; i <= Nlevel; ++i) printf(" %d", count[i]); printf("\n"); return 0; }
the_stack_data/117991.c
/* Copyright (c) 1979 Regents of the University of California */ static char *sccsid = "@(#)ovprintf.c 1.1 8/26/80"; /* * This version of printf calls doprnt, and as such is not portable, * since doprnt is written in pdp-11 assembly language. (There is a * vax doprnt which has the first 2 arguments reversed. We don't use it.) * This version is used because it is about 900 bytes smaller than the * portable version, which is also included in case it is needed. */ #ifdef TRACE #include <stdio.h> #undef putchar #endif printf(fmt, args) char *fmt; { _doprnt(fmt, &args, 0); } _strout(string, count, adjust, file, fillch) register char *string; register count; int adjust; register struct _iobuf *file; { while (adjust < 0) { if (*string=='-' && fillch=='0') { putchar(*string++); count--; } putchar(fillch); adjust++; } while (--count>=0) putchar(*string++); while (adjust) { putchar(fillch); adjust--; } }
the_stack_data/431502.c
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* * proprietary and confidential information of Varian, Inc. and its * contributors. Use, disclosure and reproduction is prohibited * without prior consent. */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <sys/param.h> /* * File headers from data.h: */ /* The file headers are defined as follows: */ /*****************/ struct datafilehead /*****************/ /* Used at the beginning of each data file (fid's, spectra, 2D) */ { int nblocks; /* number of blocks in file */ int ntraces; /* number of traces per block */ int np; /* number of elements per trace */ int ebytes; /* number of bytes per element */ int tbytes; /* number of bytes per trace */ int bbytes; /* number of bytes per block */ short vers_id; /* software version and file_id status bits */ short status; /* status of whole file */ int nbheaders; /* number of block headers */ }; /*******************/ struct datablockhead /*******************/ /* Each file block contains the following header */ { short scale; /* scaling factor */ short status; /* status of data in block */ short index; /* block index */ short mode; /* mode of data in block */ int ctcount; /* ct value for FID */ float lpval; /* F2 left phase in phasefile */ float rpval; /* F2 right phase in phasefile */ float lvl; /* F2 level drift correction */ float tlt; /* F2 tilt drift correction */ }; static void usage(char *progname) { fprintf(stderr,"Usage: %s dir infile wt [infile wt] ... outfile", progname); } int main(int argc, char **argv) { int i, j, k; int nb; int ne; int nfiles; int sumfile; int *infile; int fhdrsize; int ntraces; int np; int ebytes; int bbytes; int nblocks; char fpath[MAXPATHLEN]; char *dir; char *blkbuf; char *sumbuf; float *indata; float *sumdata; float *wt; float sumwt; struct datafilehead *inhdr; if (argc < 5 || (argc % 2) != 1) { usage(argv[0]); return -1; } fhdrsize = sizeof(struct datafilehead); /* * Open files */ nfiles = (argc - 3) / 2; infile = (int *)malloc(sizeof(int) * nfiles); wt = (float *)malloc(sizeof(float) * nfiles); if (!infile || !wt) { fprintf(stderr,"%s: malloc() failed\n", argv[0]); return -1; } dir = argv[1]; for (i=0, j=2; i<nfiles; i++, j+=2) { sprintf(fpath,"%s/%s", dir, argv[j]); infile[i] = open(fpath, O_RDONLY); if (infile[i] == -1) { fprintf(stderr,"Source data file \"%s\" not found.\n", fpath); return -1; } if (sscanf(argv[j+1], "%f", &wt[i]) != 1) { fprintf(stderr,"Bad weight for %d'th input file: %s\n", i+1, argv[j+1]); return -1; } } sprintf(fpath,"%s/%s", dir, argv[j]); sumfile = open(fpath, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (sumfile == -1) { fprintf(stderr,"Sum file \"%s\" cannot be created.\n", *argv[j]); return -1; } /* * Check headers for consistency */ inhdr = (struct datafilehead *)malloc(sizeof(struct datafilehead) * nfiles); if (!inhdr) { fprintf(stderr,"%s: malloc() failed\n", argv[0]); return -1; } for (i=0; i<nfiles; i++) { if (read(infile[i], inhdr+i, fhdrsize) != fhdrsize) { fprintf(stderr,"Error getting file header for data file %s.\n", argv[i+1]); return -1; } } ntraces = inhdr[0].ntraces; for (i=1; i<nfiles; i++) { if (ntraces != inhdr[i].ntraces) { fprintf(stderr,"ntraces mismatch: data 1: %d vs. data %d: %d\n", ntraces, i+1, inhdr[i].ntraces); return -1; } } np = inhdr[0].np; for (i=1; i<nfiles; i++) { if (np != inhdr[i].np) { fprintf(stderr,"np mismatch: data 1: %d vs. data %d: %d\n", np, i+1, inhdr[i].np); return -1; } } ebytes = inhdr[0].ebytes; for (i=1; i<nfiles; i++) { if (ebytes != inhdr[i].ebytes) { fprintf(stderr,"ebytes mismatch: data 1: %d vs. data %d: %d\n", ebytes, i+1, inhdr[i].ebytes); return -1; } } bbytes = inhdr[0].bbytes; for (i=1; i<nfiles; i++) { if (bbytes != inhdr[i].bbytes) { fprintf(stderr,"bbytes mismatch: data 1: %d vs. data %d: %d\n", bbytes, i+1, inhdr[i].bbytes); return -1; } } nblocks = inhdr[0].nblocks; for (i=1; i<nfiles; i++) { if (nblocks != inhdr[i].nblocks) { fprintf(stderr,"nblocks mismatch: data 1: %d vs. data %d: %d\n", nblocks, i+1, inhdr[i].nblocks); return -1; } } blkbuf = (char *)malloc(bbytes); sumbuf = (char *)malloc(bbytes); if (blkbuf == NULL || sumbuf == NULL) { fprintf(stderr,"Malloc failed\n"); return -1; } indata = (float *)(blkbuf + sizeof(struct datablockhead)); sumdata = (float *)(sumbuf + sizeof(struct datablockhead)); write(sumfile, &inhdr[0], sizeof(inhdr[0])); /* Write file header */ /* Prepare weighting parameters */ sumwt = 0; for (j=0; j<nfiles; j++) { wt[j] *= wt[j]; /* Square the weighting factors */ sumwt += wt[j]; } sumwt /= nfiles; if (sumwt == 0) sumwt = 1; /* * Crunch the data */ ne = np * ntraces; for (i=0; i<nblocks; i++) { for (j=0; j<nfiles; j++) { nb = read(infile[j], blkbuf, bbytes); if (nb == -1) { perror("Read error getting data block"); return -1; } else if (nb != bbytes) { fprintf(stderr,"Read of data block failed: got %d bytes\n", nb); return -1; } if (j == 0) { for (k=0; k<ne; k++) { sumdata[k] = indata[k] * indata[k] * wt[j]; } } else { for (k=0; k<ne; k++) { sumdata[k] += indata[k] * indata[k] * wt[j]; } } } memcpy(sumbuf, blkbuf, sizeof(struct datablockhead)); for (k=0; k<ne; k++) { sumdata[k] = sqrt(sumdata[k] / sumwt); } write(sumfile, sumbuf, bbytes); } return 0; }
the_stack_data/6388020.c
int main(void) { return 3?45:86; }
the_stack_data/392490.c
/** * @brief session - UI session manager * * Runs the user's yutanirc or starts up a panel and desktop * if they don't have one. Generally run by glogin. * * @copyright * This file is part of ToaruOS and is released under the terms * of the NCSA / University of Illinois License - see LICENSE.md * Copyright (C) 2018 K. Lange */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <sys/wait.h> int main(int argc, char * argv[]) { char path[1024]; char * home = getenv("HOME"); if (home) { sprintf(path, "%s/.yutanirc", home); char * args[] = {path, NULL}; execvp(args[0], args); } /* Fallback */ int _background_pid = fork(); if (!_background_pid) { sprintf(path, "%s/Desktop", home); chdir(path); char * args[] = {"/bin/file-browser", "--wallpaper", NULL}; execvp(args[0], args); } int _panel_pid = fork(); if (!_panel_pid) { char * args[] = {"/bin/panel", "--really", NULL}; execvp(args[0], args); } wait(NULL); int pid; do { pid = waitpid(-1, NULL, 0); } while ((pid > 0) || (pid == -1 && errno == EINTR)); return 0; }
the_stack_data/87637250.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char ** argv) { char * symbol; if (argc != 1) { symbol = argv[1]; } if (argc == 1) { char * env_symbol = getenv("CCC_SYMBOL"); if (env_symbol == NULL) { symbol = ""; } else { symbol = env_symbol; } } printf("\n"); for (int i = -1; i < 7; i++) { printf(" \033[%dm%s \033[m", 31 + i, symbol); } printf("\n"); for (int i = -1; i < 7; i++) { printf(" \033[%dm%s \033[m", 91 + i, symbol); } printf("\n\n"); }
the_stack_data/200144353.c
#include "stdio.h" int factor(int a, int b){ //注意,a大于等于b if (a%b==0) return b; return factor(b,a%b); } int main(void){ int a,b; printf ("输入需要求最大公约数的两整数:\n"); scanf ("%d %d", &a,&b); if (a>=b) printf("%d\n", factor(a,b)); else printf("%d\n", factor(b,a)); return 0; }
the_stack_data/40761575.c
/* C Library for Skeleton 3D Darwin PIC Code field diagnostics */ /* Wrappers for calling the Fortran routines from a C main program */ #include <complex.h> void potp3_(float complex *q, float complex *pot, float complex *ffc, float *we, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void divf3_(float complex *f, float complex *df, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void gradf3_(float complex *df, float complex *f, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void curlf3_(float complex *f, float complex *g, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv); void apotp33_(float complex *cu, float complex *axyz, float complex *ffc, float *ci, float *wm, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void etfield33_(float complex *dcu, float complex *exyz, float complex *ffe, float *ci, float *wf, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void smooth3_(float complex *q, float complex *qs, float complex *ffc, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void smooth33_(float complex *cu, float complex *cus, float complex *ffc, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd); void rdmodes3_(float complex *pot, float complex *pott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void wrmodes3_(float complex *pot, float complex *pott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void rdvmodes3_(float complex *vpot, float complex *vpott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *ndim, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); void wrvmodes3_(float complex *vpot, float complex *vpott, int *nx, int *ny, int *nz, int *modesx, int *modesy, int *modesz, int *ndim, int *nxvh, int *nyv, int *nzv, int *modesxd, int *modesyd, int *modeszd); /* Interfaces to C */ /*--------------------------------------------------------------------*/ void cpotp3(float complex q[], float complex pot[], float complex ffc[], float *we, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { potp3_(q,pot,ffc,we,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void cdivf3(float complex f[], float complex df[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { divf3_(f,df,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void cgradf3(float complex df[], float complex f[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { gradf3_(df,f,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void ccurlf3(float complex f[], float complex g[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { curlf3_(f,g,&nx,&ny,&nz,&nxvh,&nyv,&nzv); return; } /*--------------------------------------------------------------------*/ void capotp33(float complex cu[], float complex axyz[], float complex ffc[], float ci, float *wm, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { apotp33_(cu,axyz,ffc,&ci,wm,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd, &nzhd); return; } /*--------------------------------------------------------------------*/ void cetfield33(float complex dcu[], float complex exyz[], float complex ffe[], float ci, float *wf, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { etfield33_(dcu,exyz,ffe,&ci,wf,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd, &nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void csmooth3(float complex q[], float complex qs[], float complex ffc[], int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { smooth3_(q,qs,ffc,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void csmooth33(float complex cu[], float complex cus[], float complex ffc[], int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { smooth33_(cu,cus,ffc,&nx,&ny,&nz,&nxvh,&nyv,&nzv,&nxhd,&nyhd,&nzhd); return; } /*--------------------------------------------------------------------*/ void crdmodes3(float complex pot[], float complex pott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { rdmodes3_(pot,pott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&nxvh,&nyv, &nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void cwrmodes3(float complex pot[], float complex pott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { wrmodes3_(pot,pott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&nxvh,&nyv, &nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void crdvmodes3(float complex vpot[], float complex vpott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int ndim, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { rdvmodes3_(vpot,vpott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&ndim, &nxvh,&nyv,&nzv,&modesxd,&modesyd,&modeszd); return; } /*--------------------------------------------------------------------*/ void cwrvmodes3(float complex vpot[], float complex vpott[], int nx, int ny, int nz, int modesx, int modesy, int modesz, int ndim, int nxvh, int nyv, int nzv, int modesxd, int modesyd, int modeszd) { wrvmodes3_(vpot,vpott,&nx,&ny,&nz,&modesx,&modesy,&modesz,&ndim, &nxvh,&nyv,&nzv,&modesxd,&modesyd,&modeszd); return; }
the_stack_data/64200656.c
# 1 "sumRange.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 "<command-line>" 2 # 1 "sumRange.c" # 1 "/usr/include/stdio.h" 1 3 4 # 27 "/usr/include/stdio.h" 3 4 # 1 "/usr/include/features.h" 1 3 4 # 367 "/usr/include/features.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4 # 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4 # 368 "/usr/include/features.h" 2 3 4 # 391 "/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 # 392 "/usr/include/features.h" 2 3 4 # 28 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 1 3 4 # 216 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 3 4 # 216 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 3 4 typedef long unsigned int size_t; # 34 "/usr/include/stdio.h" 2 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 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 long int __quad_t; typedef unsigned long int __u_quad_t; # 121 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/typesizes.h" 1 3 4 # 122 "/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 __quad_t *__qaddr_t; typedef char *__caddr_t; typedef long int __intptr_t; typedef unsigned int __socklen_t; # 36 "/usr/include/stdio.h" 2 3 4 # 44 "/usr/include/stdio.h" 3 4 struct _IO_FILE; typedef struct _IO_FILE FILE; # 64 "/usr/include/stdio.h" 3 4 typedef struct _IO_FILE __FILE; # 74 "/usr/include/stdio.h" 3 4 # 1 "/usr/include/libio.h" 1 3 4 # 31 "/usr/include/libio.h" 3 4 # 1 "/usr/include/_G_config.h" 1 3 4 # 15 "/usr/include/_G_config.h" 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 1 3 4 # 16 "/usr/include/_G_config.h" 2 3 4 # 1 "/usr/include/wchar.h" 1 3 4 # 82 "/usr/include/wchar.h" 3 4 typedef struct { int __count; union { unsigned int __wch; char __wchb[4]; } __value; } __mbstate_t; # 21 "/usr/include/_G_config.h" 2 3 4 typedef struct { __off_t __pos; __mbstate_t __state; } _G_fpos_t; typedef struct { __off64_t __pos; __mbstate_t __state; } _G_fpos64_t; # 32 "/usr/include/libio.h" 2 3 4 # 49 "/usr/include/libio.h" 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stdarg.h" 1 3 4 # 40 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stdarg.h" 3 4 typedef __builtin_va_list __gnuc_va_list; # 50 "/usr/include/libio.h" 2 3 4 # 144 "/usr/include/libio.h" 3 4 struct _IO_jump_t; struct _IO_FILE; typedef void _IO_lock_t; struct _IO_marker { struct _IO_marker *_next; struct _IO_FILE *_sbuf; int _pos; # 173 "/usr/include/libio.h" 3 4 }; enum __codecvt_result { __codecvt_ok, __codecvt_partial, __codecvt_error, __codecvt_noconv }; # 241 "/usr/include/libio.h" 3 4 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; # 289 "/usr/include/libio.h" 3 4 __off64_t _offset; void *__pad1; void *__pad2; void *__pad3; void *__pad4; size_t __pad5; int _mode; char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)]; }; typedef struct _IO_FILE _IO_FILE; struct _IO_FILE_plus; extern struct _IO_FILE_plus _IO_2_1_stdin_; extern struct _IO_FILE_plus _IO_2_1_stdout_; extern struct _IO_FILE_plus _IO_2_1_stderr_; # 333 "/usr/include/libio.h" 3 4 typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes); typedef __ssize_t __io_write_fn (void *__cookie, const char *__buf, size_t __n); typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w); typedef int __io_close_fn (void *__cookie); # 385 "/usr/include/libio.h" 3 4 extern int __underflow (_IO_FILE *); extern int __uflow (_IO_FILE *); extern int __overflow (_IO_FILE *, int); # 429 "/usr/include/libio.h" 3 4 extern int _IO_getc (_IO_FILE *__fp); extern int _IO_putc (int __c, _IO_FILE *__fp); extern int _IO_feof (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__)); extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__)); extern int _IO_peekc_locked (_IO_FILE *__fp); extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__)); extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__)); extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__)); # 459 "/usr/include/libio.h" 3 4 extern int _IO_vfscanf (_IO_FILE * __restrict, const char * __restrict, __gnuc_va_list, int *__restrict); extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict, __gnuc_va_list); extern __ssize_t _IO_padn (_IO_FILE *, int, __ssize_t); extern size_t _IO_sgetn (_IO_FILE *, void *, size_t); extern __off64_t _IO_seekoff (_IO_FILE *, __off64_t, int, int); extern __off64_t _IO_seekpos (_IO_FILE *, __off64_t, int); extern void _IO_free_backup_area (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__)); # 75 "/usr/include/stdio.h" 2 3 4 # 108 "/usr/include/stdio.h" 3 4 typedef _G_fpos_t fpos_t; # 164 "/usr/include/stdio.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/stdio_lim.h" 1 3 4 # 165 "/usr/include/stdio.h" 2 3 4 extern struct _IO_FILE *stdin; extern struct _IO_FILE *stdout; extern struct _IO_FILE *stderr; extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__)); extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__)); extern FILE *tmpfile (void) ; # 209 "/usr/include/stdio.h" 3 4 extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ; # 232 "/usr/include/stdio.h" 3 4 extern int fclose (FILE *__stream); extern int fflush (FILE *__stream); # 266 "/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) ; # 295 "/usr/include/stdio.h" 3 4 # 329 "/usr/include/stdio.h" 3 4 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__)); # 351 "/usr/include/stdio.h" 3 4 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))); # 420 "/usr/include/stdio.h" 3 4 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__)); # 443 "/usr/include/stdio.h" 3 4 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__)) ; # 463 "/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))); # 494 "/usr/include/stdio.h" 3 4 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))); # 522 "/usr/include/stdio.h" 3 4 extern int fgetc (FILE *__stream); extern int getc (FILE *__stream); extern int getchar (void); # 565 "/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); # 617 "/usr/include/stdio.h" 3 4 extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream) ; # 638 "/usr/include/stdio.h" 3 4 extern char *gets (char *__s) __attribute__ ((__deprecated__)); # 684 "/usr/include/stdio.h" 3 4 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); # 744 "/usr/include/stdio.h" 3 4 extern int fseek (FILE *__stream, long int __off, int __whence); extern long int ftell (FILE *__stream) ; extern void rewind (FILE *__stream); # 792 "/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); # 815 "/usr/include/stdio.h" 3 4 # 824 "/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__)) ; # 841 "/usr/include/stdio.h" 3 4 extern void perror (const char *__s); # 1 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 1 3 4 # 854 "/usr/include/stdio.h" 2 3 4 # 942 "/usr/include/stdio.h" 3 4 # 2 "sumRange.c" 2 # 1 "/usr/include/stdlib.h" 1 3 4 # 32 "/usr/include/stdlib.h" 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 1 3 4 # 328 "/usr/lib/gcc/x86_64-linux-gnu/5/include/stddef.h" 3 4 typedef int wchar_t; # 33 "/usr/include/stdlib.h" 2 3 4 # 95 "/usr/include/stdlib.h" 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; # 139 "/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))); 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))); # 206 "/usr/include/stdlib.h" 3 4 __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))); # 372 "/usr/include/stdlib.h" 3 4 extern int rand (void) __attribute__ ((__nothrow__ , __leaf__)); extern void srand (unsigned int __seed) __attribute__ ((__nothrow__ , __leaf__)); # 464 "/usr/include/stdlib.h" 3 4 extern void *malloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ; extern void *calloc (size_t __nmemb, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ; extern void *realloc (void *__ptr, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__)); extern void free (void *__ptr) __attribute__ ((__nothrow__ , __leaf__)); # 513 "/usr/include/stdlib.h" 3 4 extern void abort (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); # 530 "/usr/include/stdlib.h" 3 4 # 539 "/usr/include/stdlib.h" 3 4 extern void 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))) ; # 711 "/usr/include/stdlib.h" 3 4 extern int system (const char *__command) ; # 741 "/usr/include/stdlib.h" 3 4 typedef int (*__compar_fn_t) (const void *, const void *); # 751 "/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))); # 774 "/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__)) ; # 859 "/usr/include/stdlib.h" 3 4 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__)); # 954 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/stdlib-float.h" 1 3 4 # 955 "/usr/include/stdlib.h" 2 3 4 # 967 "/usr/include/stdlib.h" 3 4 # 3 "sumRange.c" 2 # 6 "sumRange.c" int sumRange(int start, int end) { int i; int sum; sum = 0; for(i = start; i < end; i++) { sum += i; } return sum; } int main(int argc, char **argv) { int start; int end; # 45 "sumRange.c" if(argc != 3) { fprintf( # 46 "sumRange.c" 3 4 stderr # 46 "sumRange.c" , "Usage: %s\n start end", argv[0]); return 1; } start = atoi(argv[1]); end = atoi(argv[2]); printf("sumRange(%d, %d) = %d\n", start, end, sumRange(start, end)); return 0; }
the_stack_data/132953735.c
/* * Copyright (c) 1988 University of Utah. * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * This code is derived from software contributed to Berkeley by * the Systems Programming Group of the University of Utah Computer * Science Department. Originally from the University of Wisconsin. * * %sccs.include.proprietary.c% * * from: Utah $Hdr: uipc_shm.c 1.11 92/04/23$ * * @(#)sysv_shm.c 8.7 (Berkeley) 02/14/95 */ /* * System V shared memory routines. * TEMPORARY, until mmap is in place; * needed now for HP-UX compatibility and X server (yech!). */ #ifdef SYSVSHM #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/shm.h> #include <sys/malloc.h> #include <sys/mman.h> #include <sys/stat.h> #include <vm/vm.h> #include <vm/vm_kern.h> #include <vm/vm_inherit.h> #include <vm/vm_pager.h> int shmat(), shmctl(), shmdt(), shmget(); int (*shmcalls[])() = { shmat, shmctl, shmdt, shmget }; int shmtot = 0; /* * Per process internal structure for managing segments. * Each process using shm will have an array of ``shmseg'' of these. */ struct shmdesc { vm_offset_t shmd_uva; int shmd_id; }; /* * Per segment internal structure (shm_handle). */ struct shmhandle { vm_offset_t shmh_kva; caddr_t shmh_id; }; vm_map_t shm_map; /* address space for shared memory segments */ shminit() { register int i; vm_offset_t whocares1, whocares2; shm_map = kmem_suballoc(kernel_map, &whocares1, &whocares2, shminfo.shmall * NBPG, TRUE); if (shminfo.shmmni > SHMMMNI) shminfo.shmmni = SHMMMNI; for (i = 0; i < shminfo.shmmni; i++) { shmsegs[i].shm_perm.mode = 0; shmsegs[i].shm_perm.seq = 0; } } /* * Entry point for all SHM calls */ struct shmsys_args { u_int which; }; compat_43_shmsys(p, uap, retval) struct proc *p; struct shmsys_args *uap; int *retval; { if (uap->which >= sizeof(shmcalls)/sizeof(shmcalls[0])) return (EINVAL); return ((*shmcalls[uap->which])(p, &uap[1], retval)); } /* * Get a shared memory segment */ struct shmget_args { key_t key; int size; int shmflg; }; shmget(p, uap, retval) struct proc *p; register struct shmget_args *uap; int *retval; { register struct shmid_ds *shp; register struct ucred *cred = p->p_ucred; register int i; int error, size, rval = 0; register struct shmhandle *shmh; /* look up the specified shm_id */ if (uap->key != IPC_PRIVATE) { for (i = 0; i < shminfo.shmmni; i++) if ((shmsegs[i].shm_perm.mode & SHM_ALLOC) && shmsegs[i].shm_perm.key == uap->key) { rval = i; break; } } else i = shminfo.shmmni; /* create a new shared segment if necessary */ if (i == shminfo.shmmni) { if ((uap->shmflg & IPC_CREAT) == 0) return (ENOENT); if (uap->size < shminfo.shmmin || uap->size > shminfo.shmmax) return (EINVAL); for (i = 0; i < shminfo.shmmni; i++) if ((shmsegs[i].shm_perm.mode & SHM_ALLOC) == 0) { rval = i; break; } if (i == shminfo.shmmni) return (ENOSPC); size = clrnd(btoc(uap->size)); if (shmtot + size > shminfo.shmall) return (ENOMEM); shp = &shmsegs[rval]; /* * We need to do a couple of things to ensure consistency * in case we sleep in malloc(). We mark segment as * allocated so that other shmgets() will not allocate it. * We mark it as "destroyed" to insure that shmvalid() is * false making most operations fail (XXX). We set the key, * so that other shmget()s will fail. */ shp->shm_perm.mode = SHM_ALLOC | SHM_DEST; shp->shm_perm.key = uap->key; shmh = (struct shmhandle *) malloc(sizeof(struct shmhandle), M_SHM, M_WAITOK); shmh->shmh_kva = 0; shmh->shmh_id = (caddr_t)(0xc0000000|rval); /* XXX */ error = vm_mmap(shm_map, &shmh->shmh_kva, ctob(size), VM_PROT_ALL, VM_PROT_ALL, MAP_ANON, shmh->shmh_id, 0); if (error) { free((caddr_t)shmh, M_SHM); shp->shm_perm.mode = 0; return(ENOMEM); } shp->shm_handle = (void *) shmh; shmtot += size; shp->shm_perm.cuid = shp->shm_perm.uid = cred->cr_uid; shp->shm_perm.cgid = shp->shm_perm.gid = cred->cr_gid; shp->shm_perm.mode = SHM_ALLOC | (uap->shmflg & ACCESSPERMS); shp->shm_segsz = uap->size; shp->shm_cpid = p->p_pid; shp->shm_lpid = shp->shm_nattch = 0; shp->shm_atime = shp->shm_dtime = 0; shp->shm_ctime = time.tv_sec; } else { shp = &shmsegs[rval]; /* XXX: probably not the right thing to do */ if (shp->shm_perm.mode & SHM_DEST) return (EBUSY); if (error = ipcaccess(&shp->shm_perm, uap->shmflg & ACCESSPERMS, cred)) return (error); if (uap->size && uap->size > shp->shm_segsz) return (EINVAL); if ((uap->shmflg&IPC_CREAT) && (uap->shmflg&IPC_EXCL)) return (EEXIST); } *retval = shp->shm_perm.seq * SHMMMNI + rval; return (0); } /* * Shared memory control */ struct shmctl_args { int shmid; int cmd; caddr_t buf; }; /* ARGSUSED */ shmctl(p, uap, retval) struct proc *p; register struct shmctl_args *uap; int *retval; { register struct shmid_ds *shp; register struct ucred *cred = p->p_ucred; struct shmid_ds sbuf; int error; if (error = shmvalid(uap->shmid)) return (error); shp = &shmsegs[uap->shmid % SHMMMNI]; switch (uap->cmd) { case IPC_STAT: if (error = ipcaccess(&shp->shm_perm, IPC_R, cred)) return (error); return (copyout((caddr_t)shp, uap->buf, sizeof(*shp))); case IPC_SET: if (cred->cr_uid && cred->cr_uid != shp->shm_perm.uid && cred->cr_uid != shp->shm_perm.cuid) return (EPERM); if (error = copyin(uap->buf, (caddr_t)&sbuf, sizeof sbuf)) return (error); shp->shm_perm.uid = sbuf.shm_perm.uid; shp->shm_perm.gid = sbuf.shm_perm.gid; shp->shm_perm.mode = (shp->shm_perm.mode & ~ACCESSPERMS) | (sbuf.shm_perm.mode & ACCESSPERMS); shp->shm_ctime = time.tv_sec; break; case IPC_RMID: if (cred->cr_uid && cred->cr_uid != shp->shm_perm.uid && cred->cr_uid != shp->shm_perm.cuid) return (EPERM); /* set ctime? */ shp->shm_perm.key = IPC_PRIVATE; shp->shm_perm.mode |= SHM_DEST; if (shp->shm_nattch <= 0) shmfree(shp); break; default: return (EINVAL); } return (0); } /* * Attach to shared memory segment. */ struct shmat_args { int shmid; caddr_t shmaddr; int shmflg; }; shmat(p, uap, retval) struct proc *p; register struct shmat_args *uap; int *retval; { register struct shmid_ds *shp; register int size; caddr_t uva; int error; int flags; vm_prot_t prot; struct shmdesc *shmd; /* * Allocate descriptors now (before validity check) * in case malloc() blocks. */ shmd = (struct shmdesc *)p->p_vmspace->vm_shm; size = shminfo.shmseg * sizeof(struct shmdesc); if (shmd == NULL) { shmd = (struct shmdesc *)malloc(size, M_SHM, M_WAITOK); bzero((caddr_t)shmd, size); p->p_vmspace->vm_shm = (caddr_t)shmd; } if (error = shmvalid(uap->shmid)) return (error); shp = &shmsegs[uap->shmid % SHMMMNI]; if (shp->shm_handle == NULL) panic("shmat NULL handle"); if (error = ipcaccess(&shp->shm_perm, (uap->shmflg&SHM_RDONLY) ? IPC_R : IPC_R|IPC_W, p->p_ucred)) return (error); uva = uap->shmaddr; if (uva && ((int)uva & (SHMLBA-1))) { if (uap->shmflg & SHM_RND) uva = (caddr_t) ((int)uva & ~(SHMLBA-1)); else return (EINVAL); } /* * Make sure user doesn't use more than their fair share */ for (size = 0; size < shminfo.shmseg; size++) { if (shmd->shmd_uva == 0) break; shmd++; } if (size >= shminfo.shmseg) return (EMFILE); size = ctob(clrnd(btoc(shp->shm_segsz))); prot = VM_PROT_READ; if ((uap->shmflg & SHM_RDONLY) == 0) prot |= VM_PROT_WRITE; flags = MAP_ANON|MAP_SHARED; if (uva) flags |= MAP_FIXED; else uva = (caddr_t)0x1000000; /* XXX */ error = vm_mmap(&p->p_vmspace->vm_map, (vm_offset_t *)&uva, (vm_size_t)size, prot, VM_PROT_ALL, flags, ((struct shmhandle *)shp->shm_handle)->shmh_id, 0); if (error) return(error); shmd->shmd_uva = (vm_offset_t)uva; shmd->shmd_id = uap->shmid; /* * Fill in the remaining fields */ shp->shm_lpid = p->p_pid; shp->shm_atime = time.tv_sec; shp->shm_nattch++; *retval = (int) uva; return (0); } /* * Detach from shared memory segment. */ struct shmdt_args { caddr_t shmaddr; }; /* ARGSUSED */ shmdt(p, uap, retval) struct proc *p; struct shmdt_args *uap; int *retval; { register struct shmdesc *shmd; register int i; shmd = (struct shmdesc *)p->p_vmspace->vm_shm; for (i = 0; i < shminfo.shmseg; i++, shmd++) if (shmd->shmd_uva && shmd->shmd_uva == (vm_offset_t)uap->shmaddr) break; if (i == shminfo.shmseg) return (EINVAL); shmufree(p, shmd); shmsegs[shmd->shmd_id % SHMMMNI].shm_lpid = p->p_pid; return (0); } shmfork(p1, p2, isvfork) struct proc *p1, *p2; int isvfork; { register struct shmdesc *shmd; register int size; /* * Copy parents descriptive information */ size = shminfo.shmseg * sizeof(struct shmdesc); shmd = (struct shmdesc *)malloc(size, M_SHM, M_WAITOK); bcopy((caddr_t)p1->p_vmspace->vm_shm, (caddr_t)shmd, size); p2->p_vmspace->vm_shm = (caddr_t)shmd; /* * Increment reference counts */ for (size = 0; size < shminfo.shmseg; size++, shmd++) if (shmd->shmd_uva) shmsegs[shmd->shmd_id % SHMMMNI].shm_nattch++; } shmexit(p) struct proc *p; { register struct shmdesc *shmd; register int i; shmd = (struct shmdesc *)p->p_vmspace->vm_shm; for (i = 0; i < shminfo.shmseg; i++, shmd++) if (shmd->shmd_uva) shmufree(p, shmd); free((caddr_t)p->p_vmspace->vm_shm, M_SHM); p->p_vmspace->vm_shm = NULL; } shmvalid(id) register int id; { register struct shmid_ds *shp; if (id < 0 || (id % SHMMMNI) >= shminfo.shmmni) return(EINVAL); shp = &shmsegs[id % SHMMMNI]; if (shp->shm_perm.seq == (id / SHMMMNI) && (shp->shm_perm.mode & (SHM_ALLOC|SHM_DEST)) == SHM_ALLOC) return(0); return(EINVAL); } /* * Free user resources associated with a shared memory segment */ shmufree(p, shmd) struct proc *p; struct shmdesc *shmd; { register struct shmid_ds *shp; shp = &shmsegs[shmd->shmd_id % SHMMMNI]; (void) vm_deallocate(&p->p_vmspace->vm_map, shmd->shmd_uva, ctob(clrnd(btoc(shp->shm_segsz)))); shmd->shmd_id = 0; shmd->shmd_uva = 0; shp->shm_dtime = time.tv_sec; if (--shp->shm_nattch <= 0 && (shp->shm_perm.mode & SHM_DEST)) shmfree(shp); } /* * Deallocate resources associated with a shared memory segment */ shmfree(shp) register struct shmid_ds *shp; { if (shp->shm_handle == NULL) panic("shmfree"); /* * Lose our lingering object reference by deallocating space * in kernel. Pager will also be deallocated as a side-effect. */ vm_deallocate(shm_map, ((struct shmhandle *)shp->shm_handle)->shmh_kva, ctob(clrnd(btoc(shp->shm_segsz)))); free((caddr_t)shp->shm_handle, M_SHM); shp->shm_handle = NULL; shmtot -= clrnd(btoc(shp->shm_segsz)); shp->shm_perm.mode = 0; /* * Increment the sequence number to ensure that outstanding * shmids for this segment will be invalid in the event that * the segment is reallocated. Note that shmids must be * positive as decreed by SVID. */ shp->shm_perm.seq++; if ((int)(shp->shm_perm.seq * SHMMMNI) < 0) shp->shm_perm.seq = 0; } /* * XXX This routine would be common to all sysV style IPC * (if the others were implemented). */ ipcaccess(ipc, mode, cred) register struct ipc_perm *ipc; int mode; register struct ucred *cred; { register int m; if (cred->cr_uid == 0) return(0); /* * Access check is based on only one of owner, group, public. * If not owner, then check group. * If not a member of the group, then check public access. */ mode &= 0700; m = ipc->mode; if (cred->cr_uid != ipc->uid && cred->cr_uid != ipc->cuid) { m <<= 3; if (!groupmember(ipc->gid, cred) && !groupmember(ipc->cgid, cred)) m <<= 3; } if ((mode&m) == mode) return (0); return (EACCES); } #endif /* SYSVSHM */
the_stack_data/132384.c
#include <stdint.h> #include <math.h> //hace lo mismo que la versión en asm void equalizer(float* buffer, float* prev_vals, uint32_t sample_count, float psuma0, float psuma2, float psuma3, float ssuma0, float ssuma1, float ssuma2, float ssuma3, float factorSuma2){ float psuma1 = psuma0 *2; for (int i = 0; i < sample_count; i++) { //low-pass filter float temp = buffer[i]; buffer[i] *= psuma0; //psuma0 == factorsuma1 buffer[i] += psuma0 * prev_vals[0] + psuma1 * prev_vals[1] + psuma2 * prev_vals[2] + psuma3* prev_vals[3]; prev_vals[0] = prev_vals[1]; prev_vals[1] = temp; // peaking EQ (resonance) float temp2 = buffer[i]; buffer[i] *= factorSuma2; buffer[i] += ssuma0 * prev_vals[2] + ssuma1 * prev_vals[3] + ssuma2 * prev_vals[4] + ssuma3 * prev_vals[5]; prev_vals[2] = prev_vals[3]; prev_vals[3] = temp; prev_vals[4] = prev_vals[5]; prev_vals[5] = buffer[i]; } }
the_stack_data/220455856.c
//c.search for a given word in a file #include<stdio.h> #include<string.h> int main() { FILE *fp; fp=fopen("C-Assignments/c.txt","r"); char word[100],fword[100]; printf("\nEnter a word for search in the file:"); scanf("%s",word); while((fscanf(fp,"%s",fword))!=EOF) { if(strcmp(word,fword)==0) { printf("\n%s-word is found in the given file",word); break; } } fclose(fp); }
the_stack_data/198579734.c
#include <stdio.h> #include <string.h> int extract_xml_value(const char *data, char *result, const char *search_str) { char *s, *e; s = strstr(data, search_str); if (!s) return -1; s = s + strlen(search_str) + 1; e = strchr(s, '"'); if(!e) return -1; strncpy(result, s, e - s); result[e - s] = '\0'; return 0; } int main(int argc, char *argv[]) { char *filename = argv[1]; FILE *fp; char line[1024]; char lat[16], lon[16], id[16]; char city[128], country[128], sponsor[128]; char url[256]; int count =0; fp = fopen(filename, "r"); if (fp == NULL) { return 1; } while(fgets(line, 1024, fp) != NULL) { if (strncmp(line, "<server", 7) != 0) continue; if (extract_xml_value(line, url, " url=") != 0) continue; if (extract_xml_value(line, lat, " lat=") != 0) continue; if (extract_xml_value(line, lon, " lon=") != 0) continue; if (extract_xml_value(line, city, " name=") != 0) continue; if (extract_xml_value(line, country, " country=") != 0) continue; if (extract_xml_value(line, sponsor, " sponsor=") != 0) continue; if (extract_xml_value(line, id, " id=") != 0) continue; printf("server:\n\turl: %s, lat: %s, lon: %s, country: %s, city: %s, sponsor: %s, id: %s\n", url, lat, lon, country, city, sponsor, id); count ++; } printf("Number of server: %d\n", count); }
the_stack_data/59512454.c
int MAIN() { write("hello world!\n"); }
the_stack_data/827358.c
#include<stdio.h> int main(){ printf("enter 2 numbers with space in between: "); float a, b; scanf("%f %f", &a, &b); float max= a>b?a:b; printf("\n%0.1f is bigger",max); (a>b)?printf("\na is bigger"):printf("\nb is bigger"); return 0; }
the_stack_data/150140097.c
#include <stdio.h> #include <stdlib.h> typedef struct node_t { int Value; struct node_t *Next; } node; typedef struct { int Top; node *Node; } stack; int GetStackTop(stack *Stack) { int Top = 0; node *Node = Stack->Node; while (Node) { Node = Node->Next; Top++; } return Top; } void PrintStack(stack *Stack) { node *Node = Stack->Node; while (Node) { printf("%d", Node->Value); Node = Node->Next; if (Node) printf(" "); } printf("\n"); } void StackAdd(stack *Stack, int Value) { if (GetStackTop(Stack) == Stack->Top) printf("Stack Full\n"); else { node *Node = Stack->Node, *NewNode = (node *) malloc(sizeof(node)); NewNode->Value = Value; NewNode->Next = NULL; while (Node && Node->Next) Node = Node->Next; Node ? (Node->Next = NewNode) : (Stack->Node = NewNode); PrintStack(Stack); } } void StackPop(stack *Stack) { if (!GetStackTop(Stack)) printf("Stack Empty\n"); else { node *Node = Stack->Node; while (Node->Next && Node->Next->Next) Node = Node->Next; if (Node->Next) { free(Node->Next); Node->Next = NULL; PrintStack(Stack); } else { free(Stack->Node); Stack->Node = NULL; printf("Stack Empty\n"); } } } int main() { int Func = 0, Value = 0; stack *Stack = (stack*)malloc(sizeof(stack)); Stack->Top = 4; Stack->Node = NULL; while (scanf("%d", &Func) != EOF) { if (Func == 1 && scanf("%d", &Value) != EOF) StackAdd(Stack, Value); else if (Func == 2) StackPop(Stack); } return 0; }
the_stack_data/183902.c
/* SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2018-2019 Dimitar Dimitrov <[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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> /* GCC will not generate code calling this function, since the corresponding builtin will produce code that uses simple ops only. In order to support linking against TI CLPRU objects, though, provide the function mandated by TI ABI. */ int __pruabi_isnan(double a) { return isnan(a); }
the_stack_data/89199253.c
#include <stdio.h> int main(){ int num, base; int a[32]; int i=0; printf("please enter(usage: num base(2,6,16)):\n"); scanf("%d%d", &num,&base); printf("num=%d--base=%d\n",num,base); if (!(base == 2 || base == 4 || base == 16)){ return -1; } do { a[i] = num % base; i++; num /= base; printf("i=%d, a[%d]=%d\n",i,i,a[i]); }while(num != 0); for(i=i-1; i>=0;i--){ if(a[i] >= 10){ printf("%c",a[i]-10+'A'); }else{ printf("%d",a[i]); } } return 0; }
the_stack_data/86076671.c
/** ****************************************************************************** * @Company: Eder Andrade Ltda. * @file : ea_drv_i2c.c * @author : Eder Andrade * @version: V0.0 * @date : 26/04/2021 * @brief : Source file of driver that controls I2C peripheral ***************************************************************************** */ #ifdef I2C_ENABLED /* Includes ------------------------------------------------------------------*/ // C language standard library // Eder Andrade driver library #include "ea_drv_i2c.h" // Application /******************************************************************************* HOW TO USE THIS DRIVER ******************************************************************************** 1. First, you should include in your .c file: "ea_drv_i2c.h" and call I2C object, after that, you can use the follow resources of the driver - I2C: this is the object that will control the peripheral; Data ----------------------------------------------------------------------- - I2C.bFlagEnable ===================> It informs if GPIO driver is enabled Methods -------------------------------------------------------------------- - I2C.Open() =========================> Initializes the I2C driver; - I2C.Close() ========================> Finishes the I2C driver; - I2C.Write() ========================> Writes a value in a specific memory location - I2C.Read() =========================> Reads a value from a specific memory location *******************************************************************************/ /* Private define ------------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ static I2C_HandleTypeDef hi2c1; /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static int8_t ea_i2c_open (void); static int8_t ea_i2c_close (void); static int8_t ea_i2c_write (uint16_t, uint8_t, uint8_t); static int8_t ea_i2c_read (uint16_t, uint8_t); /* Public objects ------------------------------------------------------------*/ st_i2c_t I2C = { /* Peripheral disabled ****************************************************/ .bFlagEnable = RESET, /* All axis values resetted ***********************************************/ .uiXyz[eAxisX] = 0, .uiXyz[eAxisY] = 0, .uiXyz[eAxisZ] = 0, /* Function pointers loaded ***********************************************/ .Open = &ea_i2c_open , .Close = &ea_i2c_close , .Write = &ea_i2c_write , .Read = &ea_i2c_read , }; /* Body of private functions -------------------------------------------------*/ /** * @Func : I2C1_EV_IRQHandler * @brief : This function handles I2C1 event global interrupt / I2C1 wake-up interrupt through EXTI line 23. * @pre-cond. : ea_i2c_open() must be called first * @post-cond. : Callback related to hardware event is attended * @parameters : Void * @retval : Void */ void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(&hi2c1); } /** * @Func : I2C1_ER_IRQHandler * @brief : This function handles I2C1 error interrupt. * @pre-cond. : ea_i2c_open() must be called first * @post-cond. : Callback related to hardware event is attended * @parameters : Void * @retval : Void */ void I2C1_ER_IRQHandler(void) { HAL_I2C_ER_IRQHandler(&hi2c1); } /** * @Func : ea_i2c_open * @brief : Initializes I2C peripheral * @pre-cond. : System Clock Config must be called first * @post-cond. : I2C peripheral and its related source clock is enabled * @parameters : void * @retval : int8_t -> (value == 0) = OK; (value < 0) = ERROR */ static int8_t ea_i2c_open(void) { hi2c1.Instance = I2C1; //hi2c1.Init.Timing = 0x2000090E; hi2c1.Init.OwnAddress1 = 0x32; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; // hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; /* Config is OK? **********************************************************/ if(HAL_I2C_Init(&hi2c1) != HAL_OK) { return -1; } /** Configure Analogue filter *********************************************/ if(HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK) { return -2; } /** Configure Digital filter **********************************************/ if(HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK) { return -3; } // Enabling GPIO peripheral I2C.bFlagEnable = SET; // GPIO enabled! return 0; } /** * @Func : ea_i2c_close * @brief : Disable I2C peripheral * @pre-cond. : ea_i2c_open() must be called first * @post-cond. : I2C is disabled and it is not possible to communicate. * @parameters : void * @retval : int8_t -> (value == 0) = OK; (value < 0) = ERROR */ static int8_t ea_i2c_close(void) { // Check if GPIO was enabled if(I2C.bFlagEnable != RESET) { if(HAL_I2C_DeInit(&hi2c1) != HAL_OK) { return -1; } // IOs disable I2C.bFlagEnable = RESET; // OK return 0; } // GPIO is disabled return -2; } /** * @Func : ea_i2c_write * @brief : Write a data in a specific memory area * @pre-cond. : ea_i2c_open() must be called first * @post-cond. : Data written in a memory area informed * @parameters : ucDeviceAddr -> device * @parameters : ucRegisterAddr -> register * @parameters : ucRegisterAddr -> value * @retval : int8_t -> (value == 0) = OK; (value < 0) = ERROR */ static int8_t ea_i2c_write(uint16_t ucDeviceAddr, uint8_t ucRegisterAddr, uint8_t ucValue) { // Check if GPIO is enabled if(I2C.bFlagEnable != RESET) { // Writes in a specific memory if(HAL_I2C_Mem_Write(&hi2c1 , ucDeviceAddr , (uint16_t)ucRegisterAddr , I2C_MEMADD_SIZE_8BIT , &ucValue , 1 , 0x10000) != HAL_OK) { // Error return -1; } // OK return 0; } // GPIO is disabled return -2; } /** * @Func : ea_i2c_read * @brief : Read a data from a specific memory area * @pre-cond. : ea_i2c_open() must be called first * @post-cond. : Data read from a memory area informed * @parameters : uiAddress -> address * @parameters : ucValue -> value * @retval : int8_t -> (value == 0) = OK; (value < 0) = ERROR */ static int8_t ea_i2c_read(uint16_t ucDeviceAddr, uint8_t ucRegisterAddr) { // Check if GPIO was enabled if(I2C.bFlagEnable != RESET) { // Local uint8_t ucValue = 0; HAL_StatusTypeDef status = HAL_OK; // Read memory informed status = HAL_I2C_Mem_Read ( &hi2c1 , ucDeviceAddr , ucRegisterAddr , I2C_MEMADD_SIZE_8BIT , &ucValue , 1 , 0x10000); if(status != HAL_OK) { /* Execute user timeout callback */ return -1; } return ucValue; } // GPIO is disabled return -2; } #endif /* GPIO_ENABLED <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /*****************************END OF FILE**************************************/
the_stack_data/25779.c
/* Include Mathematical Functions */ /* Add commands to - print top element of the stack,without poping - duplicate it - swap the top two elements - Clear the stack */ /* IMPORTANT: compile with -lm flag(the static math library) For eg: gcc -lm rpn-3.c */ #include<stdio.h> #include<stdlib.h> #include<math.h> #define MAXOP 100 #define NUMBER '0' #define NAME 'n' int getop(char []); void push(double); double pop(void); void mathfnc(char []); /* reverse polish calculator */ int main(void) { int type; double op2,op1; char s[MAXOP]; void clearsp(void); while((type = getop(s)) != EOF) { switch(type) { case NUMBER: push(atof(s)); break; case NAME: mathfnc(s); break; case '+': push(pop()+pop()); break; case '*': push(pop()*pop()); break; case '-': op2 = pop(); push(pop()-op2); break; case '/': op2 = pop(); if(op2 != 0.0) push(pop()/op2); else printf("error:zero divisor\n"); break; case '%': op2 = pop(); if(op2 != 0.0) push(fmod(pop(),op2)); else printf("erro:zero divisor\n"); break; case '?': op2=pop(); printf("\t%.8g\n",op2); push(op2); break; case 'c': clearsp(); break; case 'd': op2=pop(); push(op2); push(op2); break; case 's': op1=pop(); op2=pop(); push(op1); push(op2); break; case '\n': printf("\t%.8g\n",pop()); break; default: printf("error: unknown command %s\n",s); break; } } return 0; } #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double f) { if(sp < MAXVAL) val[sp++]=f; else printf("error:stack full, cant push %g\n",f); } double pop(void) { if(sp>0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } void clearsp(void) { sp = 0; } #include<ctype.h> #include<string.h> int getch(void); void ungetch(int); int getop(char s[]) { int i,c; while((s[0] = c = getch()) == ' ' || c =='\t') ; s[1] = '\0'; i = 0; if(islower(c)) { while(islower(s[++i]=c=getch())); ; s[i]='\0'; if(c!=EOF) ungetch(c); if(strlen(s)>1) return NAME; else /*return c; this line was bad since when s < 1, the array s only has one character s[0], therofore, this character must be retorned in order to see if it is d,?,s etc. The character c instead contain whatever non-lower value wich always will result in a command uknown*/ return s[0]; } if(!isdigit(c) && c!='.' && c!='-') return c; if(c=='-') if(isdigit(c=getch()) || c == '.') s[++i]=c; else { if(c!=EOF) ungetch(c); return '-'; } if(isdigit(c)) while(isdigit(s[++i] =c =getch())) ; if(c=='.') while(isdigit(s[++i] = c=getch())) ; s[i] = '\0'; if(c!=EOF) ungetch(c); return NUMBER; } #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if(bufp >= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } /* mathfnc: check the string s for supported math function */ void mathfnc(char s[]) { double op2; if(strcmp(s,"sin")==0) push(sin(pop())); else if(strcmp(s,"cos")==0) push(cos(pop())); else if(strcmp(s,"exp")==0) push(exp(pop())); else if(strcmp(s,"pow")==0) { op2 = pop(); push(pow(pop(),op2)); } else printf("error: %s is not supported\n",s); }
the_stack_data/181394075.c
#include <stdio.h> #include <stdlib.h> int main() { float a,b,c; printf("Enter 3 numbers [SEPERATED BY A TAB]: "); scanf("%f%f%f",&a,&b,&c); a>b&&a>c ? printf("\n%.2f is the greatest.\n",a) : b>a&&b>c ? printf("\n%.2f is the greatest.\n",b) : printf("\n%.2f is the greatest.\n",c); return 0; }
the_stack_data/248582006.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <linux/videodev2.h> #include <linux/uvcvideo.h> #include <linux/usb/video.h> #include <sys/ioctl.h> const char* usage = "Usage: %s [-d DEVICE] <on|off>\n"; int main(int argc, char *argv[]) { const char * device = "/dev/video2"; int opt; while ((opt = getopt(argc, argv, "d:")) != -1) { switch(opt) { case 'd': device = optarg; break; case '?': fprintf(stderr, usage, argv[0]); exit(-1); return -1; } } if (optind + 1 > argc) { /* need at least one argument */ fprintf(stderr, usage, argv[0]); exit(-1); } __u8 setbuffer[256] = {}; if (strcmp(argv[optind], "on") == 0) { setbuffer[0] = 0x01; } struct uvc_xu_control_query set_query = { .unit = 0x00, .selector = 0x02, .query = UVC_SET_CUR, .size = 1, .data = 0x01, }; int result = 0; int fd = open(device, O_WRONLY); result = ioctl(fd, UVCIOC_CTRL_QUERY, &set_query); if (result < 0) { printf("Test: Error code: %d, errno: %d, error: %s\n", result, errno, strerror(errno)); } close(fd); return 0; }
the_stack_data/649011.c
#include<stdio.h> int main(void) { printf("Content-Type: text/plain\n\n"); printf("hello cgi(c) world.\n"); }
the_stack_data/61075365.c
/* * Disassociate from controling terminal and process * group. Close all open files. */ #include <stdio.h> #include <signal.h> #include <sys/param.h> bedaemon() { int child_pid; int fd; /* cron does its own sigsetup. Do it to be standard module for all * daemon processes do this extra signal here */ signal(SIGHUP, SIG_IGN); /* immune from the group leader death */ /* When we did not start from background fork and let parent die. */ if ((child_pid = fork()) < 0) { fprintf(stderr, "cron: cannot fork\n"); exit(1); } else if (child_pid > 0) /* parent */ exit(0); /* Disassociate from controlling terminal & process group */ setpgrp(); /* This fork should garantee that process can't reacquire a new * controlling terminal. */ if ((child_pid = fork()) < 0) { fprintf(stderr, "cron: cannot fork\n"); exit(1); } else if (child_pid > 0) /* parent */ exit(0); /* Close all open files, chdir "/", and umask(0). */ for (fd = 0; fd < NOFILE; fd++) close(fd); chdir("/"); umask(0); /* We do not want any surprise with file creation */ }
the_stack_data/306548.c
/* This file is part of ToyOS and is released under the terms * of the NCSA / University of Illinois License - see LICENSE.md * Copyright (C) 2013 Kevin Lange */ /* vim: tabstop=4 shiftwidth=4 noexpandtab * * Sample application which triggers a stack overflow * by means of a simple infinitely recursive function. */ #include <stdio.h> #include <syscall.h> void overflow() { int i[1024] = {0xff}; printf("Stack is at 0x%x\n", &i); overflow(); } int main(int argc, char ** argv) { overflow(); return 0; }
the_stack_data/88323.c
// https://www.hackerrank.com/challenges/hello-world-c #include <stdio.h> int main_hello_world_in_c() { char s[100]; scanf("%99[^\n]", s); printf("Hello, World!\n%s\n", s); return 0; }
the_stack_data/108996.c
/* * Mach Operating System * Copyright (c) 1992,1991,1990,1989 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or [email protected] * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* * HISTORY * $Log: strlen.c,v $ * Revision 2.4 93/01/24 13:24:25 danner * Created! * [92/10/22 rvb] * * * File: limach/strlen.c * Author: Robert V. Baron at Carnegie Mellon * Date: Oct 13, 1992 * Abstract: * strlen returns the number of characters in "string" preceeding * the terminating null character. */ int strlen(string) register char *string; { register char *ret = string; while (*string++); return string - 1 - ret; }
the_stack_data/237642067.c
#if defined(__ppc__) || defined(__ppc64__) /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 1998 Geoffrey Keating PowerPC Foreign Function Interface Darwin ABI support (c) 2001 John Hornkvist AIX ABI support (c) 2002 Free Software Foundation, Inc. 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 AUTHOR 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. ----------------------------------------------------------------------- */ #include "ffi.h" #include "ffi_common.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "ppc-darwin.h" #include <architecture/ppc/mode_independent_asm.h> #if 0 #if defined(POWERPC_DARWIN) #include <libkern/OSCacheControl.h> // for sys_icache_invalidate() #endif #else /* Explicit prototype instead of including a header to allow compilation * on Tiger systems. */ #pragma weak sys_icache_invalidate extern void sys_icache_invalidate(void *start, size_t len); #endif extern void ffi_closure_ASM(void); // The layout of a function descriptor. A C function pointer really // points to one of these. typedef struct aix_fd_struct { void* code_pointer; void* toc; } aix_fd; /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments. The stack layout we want looks like this: | Return address from ffi_call_DARWIN | higher addresses |--------------------------------------------| | Previous backchain pointer 4/8 | stack pointer here |--------------------------------------------|-\ <<< on entry to | Saved r28-r31 (4/8)*4 | | ffi_call_DARWIN |--------------------------------------------| | | Parameters (at least 8*(4/8)=32/64) | | (176) +112 - +288 |--------------------------------------------| | | Space for GPR2 4/8 | | |--------------------------------------------| | stack | | Reserved (4/8)*2 | | grows | |--------------------------------------------| | down V | Space for callee's LR 4/8 | | |--------------------------------------------| | lower addresses | Saved CR 4/8 | | |--------------------------------------------| | stack pointer here | Current backchain pointer 4/8 | | during |--------------------------------------------|-/ <<< ffi_call_DARWIN Note: ppc64 CR is saved in the low word of a long on the stack. */ /*@-exportheader@*/ void ffi_prep_args( extended_cif* inEcif, unsigned *const stack) /*@=exportheader@*/ { /* Copy the ecif to a local var so we can trample the arg. BC note: test this with GP later for possible problems... */ volatile extended_cif* ecif = inEcif; const unsigned bytes = ecif->cif->bytes; const unsigned flags = ecif->cif->flags; /* Cast the stack arg from int* to long*. sizeof(long) == 4 in 32-bit mode and 8 in 64-bit mode. */ unsigned long *const longStack = (unsigned long *const)stack; /* 'stacktop' points at the previous backchain pointer. */ #if defined(__ppc64__) // In ppc-darwin.s, an extra 96 bytes is reserved for the linkage area, // saved registers, and an extra FPR. unsigned long *const stacktop = (unsigned long *)(unsigned long)((char*)longStack + bytes + 96); #elif defined(__ppc__) unsigned long *const stacktop = longStack + (bytes / sizeof(long)); #else #error undefined architecture #endif /* 'fpr_base' points at the space for fpr1, and grows upwards as we use FPR registers. */ double* fpr_base = (double*)(stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS; #if defined(__ppc64__) // 64-bit saves an extra register, and uses an extra FPR. Knock fpr_base // down a couple pegs. fpr_base -= 2; #endif unsigned int fparg_count = 0; /* 'next_arg' grows up as we put parameters in it. */ unsigned long* next_arg = longStack + 6; /* 6 reserved positions. */ int i; double double_tmp; void** p_argv = ecif->avalue; unsigned long gprvalue; ffi_type** ptr = ecif->cif->arg_types; /* Check that everything starts aligned properly. */ FFI_ASSERT(stack == SF_ROUND(stack)); FFI_ASSERT(stacktop == SF_ROUND(stacktop)); FFI_ASSERT(bytes == SF_ROUND(bytes)); /* Deal with return values that are actually pass-by-reference. Rule: Return values are referenced by r3, so r4 is the first parameter. */ if (flags & FLAG_RETVAL_REFERENCE) *next_arg++ = (unsigned long)(char*)ecif->rvalue; /* Now for the arguments. */ for (i = ecif->cif->nargs; i > 0; i--, ptr++, p_argv++) { switch ((*ptr)->type) { /* If a floating-point parameter appears before all of the general- purpose registers are filled, the corresponding GPRs that match the size of the floating-point parameter are shadowed for the benefit of vararg and pre-ANSI functions. */ case FFI_TYPE_FLOAT: double_tmp = *(float*)*p_argv; if (fparg_count < NUM_FPR_ARG_REGISTERS) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg++; fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; case FFI_TYPE_DOUBLE: double_tmp = *(double*)*p_argv; if (fparg_count < NUM_FPR_ARG_REGISTERS) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg += MODE_CHOICE(2,1); fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (fparg_count < NUM_FPR_ARG_REGISTERS) *(long double*)fpr_base = *(long double*)*p_argv; #elif defined(__ppc__) if (fparg_count < NUM_FPR_ARG_REGISTERS - 1) *(long double*)fpr_base = *(long double*)*p_argv; else if (fparg_count == NUM_FPR_ARG_REGISTERS - 1) *(double*)fpr_base = *(double*)*p_argv; #else #error undefined architecture #endif *(long double*)next_arg = *(long double*)*p_argv; fparg_count += 2; fpr_base += 2; next_arg += MODE_CHOICE(4,2); FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: #if defined(__ppc64__) gprvalue = *(long long*)*p_argv; goto putgpr; #elif defined(__ppc__) *(long long*)next_arg = *(long long*)*p_argv; next_arg += 2; break; #else #error undefined architecture #endif case FFI_TYPE_POINTER: gprvalue = *(unsigned long*)*p_argv; goto putgpr; case FFI_TYPE_UINT8: gprvalue = *(unsigned char*)*p_argv; goto putgpr; case FFI_TYPE_SINT8: gprvalue = *(signed char*)*p_argv; goto putgpr; case FFI_TYPE_UINT16: gprvalue = *(unsigned short*)*p_argv; goto putgpr; case FFI_TYPE_SINT16: gprvalue = *(signed short*)*p_argv; goto putgpr; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; ffi64_struct_to_reg_form(*ptr, (char*)*p_argv, NULL, &fparg_count, (char*)next_arg, &gprSize, (char*)fpr_base, &fprSize); next_arg += gprSize / sizeof(long); fpr_base += fprSize / sizeof(double); #elif defined(__ppc__) char* dest_cpy = (char*)next_arg; /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. Structures with 3 byte in size are padded upwards. */ unsigned size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); if (ecif->cif->abi == FFI_DARWIN) { if (size_al < 3) dest_cpy += 4 - size_al; } memcpy((char*)dest_cpy, (char*)*p_argv, size_al); next_arg += (size_al + 3) / 4; #else #error undefined architecture #endif break; } case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: gprvalue = *(unsigned*)*p_argv; putgpr: *next_arg++ = gprvalue; break; default: break; } } /* Check that we didn't overrun the stack... */ //FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS); //FFI_ASSERT((unsigned *)fpr_base // <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS); //FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); } #if defined(__ppc64__) bool ffi64_struct_contains_fp( const ffi_type* inType) { bool containsFP = false; unsigned int i; for (i = 0; inType->elements[i] != NULL && !containsFP; i++) { if (inType->elements[i]->type == FFI_TYPE_FLOAT || inType->elements[i]->type == FFI_TYPE_DOUBLE || inType->elements[i]->type == FFI_TYPE_LONGDOUBLE) containsFP = true; else if (inType->elements[i]->type == FFI_TYPE_STRUCT) containsFP = ffi64_struct_contains_fp(inType->elements[i]); } return containsFP; } #endif // defined(__ppc64__) /* Perform machine dependent cif processing. */ ffi_status ffi_prep_cif_machdep( ffi_cif* cif) { /* All this is for the DARWIN ABI. */ int i; ffi_type** ptr; int intarg_count = 0; int fparg_count = 0; unsigned int flags = 0; unsigned int size_al = 0; /* All the machine-independent calculation of cif->bytes will be wrong. Redo the calculation for DARWIN. */ /* Space for the frame pointer, callee's LR, CR, etc, and for the asm's temp regs. */ unsigned int bytes = (6 + ASM_NEEDS_REGISTERS) * sizeof(long); /* Return value handling. The rules are as follows: - 32-bit (or less) integer values are returned in gpr3; - Structures of size <= 4 bytes also returned in gpr3; - 64-bit integer values and structures between 5 and 8 bytes are returned in gpr3 and gpr4; - Single/double FP values are returned in fpr1; - Long double FP (if not equivalent to double) values are returned in fpr1 and fpr2; - Larger structures values are allocated space and a pointer is passed as the first argument. */ switch (cif->rtype->type) { #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: flags |= FLAG_RETURNS_128BITS; flags |= FLAG_RETURNS_FP; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_DOUBLE: flags |= FLAG_RETURNS_64BITS; /* Fall through. */ case FFI_TYPE_FLOAT: flags |= FLAG_RETURNS_FP; break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: flags |= FLAG_RETURNS_64BITS; break; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) if (ffi64_stret_needs_ptr(cif->rtype, NULL, NULL)) { flags |= FLAG_RETVAL_REFERENCE; flags |= FLAG_RETURNS_NOTHING; intarg_count++; } else { flags |= FLAG_RETURNS_STRUCT; if (ffi64_struct_contains_fp(cif->rtype)) flags |= FLAG_STRUCT_CONTAINS_FP; } #elif defined(__ppc__) flags |= FLAG_RETVAL_REFERENCE; flags |= FLAG_RETURNS_NOTHING; intarg_count++; #else #error undefined architecture #endif break; } case FFI_TYPE_VOID: flags |= FLAG_RETURNS_NOTHING; break; default: /* Returns 32-bit integer, or similar. Nothing to do here. */ break; } /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest goes on the stack. Structures are passed as a pointer to a copy of the structure. Stuff on the stack needs to keep proper alignment. */ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) { switch ((*ptr)->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: fparg_count++; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if (fparg_count > NUM_FPR_ARG_REGISTERS && intarg_count % 2 != 0) intarg_count++; break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: fparg_count += 2; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if ( #if defined(__ppc64__) fparg_count > NUM_FPR_ARG_REGISTERS + 1 #elif defined(__ppc__) fparg_count > NUM_FPR_ARG_REGISTERS #else #error undefined architecture #endif && intarg_count % 2 != 0) intarg_count++; intarg_count += 2; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: /* 'long long' arguments are passed as two words, but either both words must fit in registers or both go on the stack. If they go on the stack, they must be 8-byte-aligned. */ if (intarg_count == NUM_GPR_ARG_REGISTERS - 1 || (intarg_count >= NUM_GPR_ARG_REGISTERS && intarg_count % 2 != 0)) intarg_count++; intarg_count += MODE_CHOICE(2,1); break; case FFI_TYPE_STRUCT: size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); #if defined(__ppc64__) // Look for FP struct members. unsigned int j; for (j = 0; (*ptr)->elements[j] != NULL; j++) { if ((*ptr)->elements[j]->type == FFI_TYPE_FLOAT || (*ptr)->elements[j]->type == FFI_TYPE_DOUBLE) { fparg_count++; if (fparg_count > NUM_FPR_ARG_REGISTERS) intarg_count++; } else if ((*ptr)->elements[j]->type == FFI_TYPE_LONGDOUBLE) { fparg_count += 2; if (fparg_count > NUM_FPR_ARG_REGISTERS + 1) intarg_count += 2; } else intarg_count++; } #elif defined(__ppc__) intarg_count += (size_al + 3) / 4; #else #error undefined architecture #endif break; default: /* Everything else is passed as a 4/8-byte word in a GPR, either the object itself or a pointer to it. */ intarg_count++; break; } } /* Space for the FPR registers, if needed. */ if (fparg_count != 0) { flags |= FLAG_FP_ARGUMENTS; #if defined(__ppc64__) bytes += (NUM_FPR_ARG_REGISTERS + 1) * sizeof(double); #elif defined(__ppc__) bytes += NUM_FPR_ARG_REGISTERS * sizeof(double); #else #error undefined architecture #endif } /* Stack space. */ #if defined(__ppc64__) if ((intarg_count + fparg_count) > NUM_GPR_ARG_REGISTERS) bytes += (intarg_count + fparg_count) * sizeof(long); #elif defined(__ppc__) if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS) bytes += (intarg_count + 2 * fparg_count) * sizeof(long); #else #error undefined architecture #endif else bytes += NUM_GPR_ARG_REGISTERS * sizeof(long); /* The stack space allocated needs to be a multiple of 16/32 bytes. */ bytes = SF_ROUND(bytes); cif->flags = flags; cif->bytes = bytes; return FFI_OK; } /*@-declundef@*/ /*@-exportheader@*/ extern void ffi_call_AIX( /*@out@*/ extended_cif*, unsigned, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); extern void ffi_call_DARWIN( /*@out@*/ extended_cif*, unsigned long, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); /*@=declundef@*/ /*@=exportheader@*/ void ffi_call( /*@dependent@*/ ffi_cif* cif, void (*fn)(void), /*@out@*/ void* rvalue, /*@dependent@*/ void** avalue) { extended_cif ecif; ecif.cif = cif; ecif.avalue = avalue; /* If the return value is a struct and we don't have a return value address then we need to make one. */ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; switch (cif->abi) { case FFI_AIX: /*@-usedef@*/ ffi_call_AIX(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; case FFI_DARWIN: /*@-usedef@*/ ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; default: FFI_ASSERT(0); break; } } /* here I'd like to add the stack frame layout we use in darwin_closure.S and aix_clsoure.S SP previous -> +---------------------------------------+ <--- child frame | back chain to caller 4 | +---------------------------------------+ 4 | saved CR 4 | +---------------------------------------+ 8 | saved LR 4 | +---------------------------------------+ 12 | reserved for compilers 4 | +---------------------------------------+ 16 | reserved for binders 4 | +---------------------------------------+ 20 | saved TOC pointer 4 | +---------------------------------------+ 24 | always reserved 8*4=32 (previous GPRs)| | according to the linkage convention | | from AIX | +---------------------------------------+ 56 | our FPR area 13*8=104 | | f1 | | . | | f13 | +---------------------------------------+ 160 | result area 8 | +---------------------------------------+ 168 | alignement to the next multiple of 16 | SP current --> +---------------------------------------+ 176 <- parent frame | back chain to caller 4 | +---------------------------------------+ 180 | saved CR 4 | +---------------------------------------+ 184 | saved LR 4 | +---------------------------------------+ 188 | reserved for compilers 4 | +---------------------------------------+ 192 | reserved for binders 4 | +---------------------------------------+ 196 | saved TOC pointer 4 | +---------------------------------------+ 200 | always reserved 8*4=32 we store our | | GPRs here | | r3 | | . | | r10 | +---------------------------------------+ 232 | overflow part | +---------------------------------------+ xxx | ???? | +---------------------------------------+ xxx */ #if !defined(POWERPC_DARWIN) #define MIN_LINE_SIZE 32 static void flush_icache( char* addr) { #ifndef _AIX __asm__ volatile ( "dcbf 0,%0\n" "sync\n" "icbi 0,%0\n" "sync\n" "isync" : : "r" (addr) : "memory"); #endif } static void flush_range( char* addr, int size) { int i; for (i = 0; i < size; i += MIN_LINE_SIZE) flush_icache(addr + i); flush_icache(addr + size - 1); } #endif // !defined(POWERPC_DARWIN) ffi_status ffi_prep_closure( ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*, void*, void**, void*), void* user_data) { switch (cif->abi) { case FFI_DARWIN: { FFI_ASSERT (cif->abi == FFI_DARWIN); unsigned int* tramp = (unsigned int*)&closure->tramp[0]; #if defined(__ppc64__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0xe98b0018; // ld r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0xe96b0020; // ld r11,32(r11) tramp[7] = 0x4e800420; // bctr *(unsigned long*)&tramp[8] = (unsigned long)ffi_closure_ASM; *(unsigned long*)&tramp[10] = (unsigned long)closure; #elif defined(__ppc__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0x818b0018; // lwz r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0x816b001c; // lwz r11,28(r11) tramp[7] = 0x4e800420; // bctr tramp[8] = (unsigned long)ffi_closure_ASM; tramp[9] = (unsigned long)closure; #else #error undefined architecture #endif closure->cif = cif; closure->fun = fun; closure->user_data = user_data; // Flush the icache. Only necessary on Darwin. #if defined(POWERPC_DARWIN) if (sys_icache_invalidate) { sys_icache_invalidate(closure->tramp, FFI_TRAMPOLINE_SIZE); } #else flush_range(closure->tramp, FFI_TRAMPOLINE_SIZE); #endif break; } case FFI_AIX: { FFI_ASSERT (cif->abi == FFI_AIX); ffi_aix_trampoline_struct* tramp_aix = (ffi_aix_trampoline_struct*)(closure->tramp); aix_fd* fd = (aix_fd*)(void*)ffi_closure_ASM; tramp_aix->code_pointer = fd->code_pointer; tramp_aix->toc = fd->toc; tramp_aix->static_chain = closure; closure->cif = cif; closure->fun = fun; closure->user_data = user_data; break; } default: return FFI_BAD_ABI; } return FFI_OK; } #if defined(__ppc__) typedef double ldbits[2]; typedef union { ldbits lb; long double ld; } ldu; #endif /* The trampoline invokes ffi_closure_ASM, and on entry, r11 holds the address of the closure. After storing the registers that could possibly contain parameters to be passed into the stack frame and setting up space for a return value, ffi_closure_ASM invokes the following helper function to do most of the work. */ int ffi_closure_helper_DARWIN( ffi_closure* closure, void* rvalue, unsigned long* pgr, ffi_dblfl* pfr) { /* rvalue is the pointer to space for return value in closure assembly pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */ #if defined(__ppc__) ldu temp_ld; #endif double temp; unsigned int i; unsigned int nf = 0; /* number of FPRs already used. */ unsigned int ng = 0; /* number of GPRs already used. */ ffi_cif* cif = closure->cif; unsigned int avn = cif->nargs; void** avalue = alloca(cif->nargs * sizeof(void*)); ffi_type** arg_types = cif->arg_types; /* Copy the caller's structure return value address so that the closure returns the data directly to the caller. */ #if defined(__ppc64__) if (cif->rtype->type == FFI_TYPE_STRUCT && ffi64_stret_needs_ptr(cif->rtype, NULL, NULL)) #elif defined(__ppc__) if (cif->rtype->type == FFI_TYPE_STRUCT) #else #error undefined architecture #endif { rvalue = (void*)*pgr; pgr++; ng++; } /* Grab the addresses of the arguments from the stack frame. */ for (i = 0; i < avn; i++) { switch (arg_types[i]->type) { case FFI_TYPE_SINT8: case FFI_TYPE_UINT8: avalue[i] = (char*)pgr + MODE_CHOICE(3,7); ng++; pgr++; break; case FFI_TYPE_SINT16: case FFI_TYPE_UINT16: avalue[i] = (char*)pgr + MODE_CHOICE(2,6); ng++; pgr++; break; #if defined(__ppc__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: avalue[i] = (char*)pgr + MODE_CHOICE(0,4); ng++; pgr++; break; case FFI_TYPE_STRUCT: if (cif->abi == FFI_DARWIN) { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; unsigned int savedFPRSize = fprSize; avalue[i] = alloca(arg_types[i]->size); ffi64_struct_to_ram_form(arg_types[i], (const char*)pgr, &gprSize, (const char*)pfr, &fprSize, &nf, avalue[i], NULL); ng += gprSize / sizeof(long); pgr += gprSize / sizeof(long); pfr += (fprSize - savedFPRSize) / sizeof(double); #elif defined(__ppc__) /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. */ unsigned int size_al = size_al = arg_types[i]->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN(arg_types[i]->size, 8); if (size_al < 3) avalue[i] = (char*)pgr + MODE_CHOICE(4,8) - size_al; else avalue[i] = (char*)pgr; ng += (size_al + 3) / sizeof(long); pgr += (size_al + 3) / sizeof(long); #else #error undefined architecture #endif } break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: /* Long long ints are passed in 1 or 2 GPRs. */ avalue[i] = pgr; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; case FFI_TYPE_FLOAT: /* A float value consumes a GPR. There are 13 64-bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS) { temp = pfr->d; pfr->f = (float)temp; avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng++; pgr++; break; case FFI_TYPE_DOUBLE: /* A double value consumes one or two GPRs. There are 13 64bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS) { avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (nf < NUM_FPR_ARG_REGISTERS) { avalue[i] = pfr; pfr += 2; } #elif defined(__ppc__) /* A long double value consumes 2/4 GPRs and 2 FPRs. There are 13 64bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS - 1) { avalue[i] = pfr; pfr += 2; } /* Here we have the situation where one part of the long double is stored in fpr13 and the other part is already on the stack. We use a union to pass the long double to avalue[i]. */ else if (nf == NUM_FPR_ARG_REGISTERS - 1) { memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits)); memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits)); avalue[i] = &temp_ld.ld; } #else #error undefined architecture #endif else avalue[i] = pgr; nf += 2; ng += MODE_CHOICE(4,2); pgr += MODE_CHOICE(4,2); break; #endif /* FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE */ default: FFI_ASSERT(0); break; } } (closure->fun)(cif, rvalue, avalue, closure->user_data); /* Tell ffi_closure_ASM to perform return type promotions. */ return cif->rtype->type; } #if defined(__ppc64__) /* ffi64_struct_to_ram_form Rebuild a struct's natural layout from buffers of concatenated registers. Return the number of registers used. inGPRs[0-7] == r3, inFPRs[0-7] == f1 ... */ void ffi64_struct_to_ram_form( const ffi_type* inType, const char* inGPRs, unsigned int* ioGPRMarker, const char* inFPRs, unsigned int* ioFPRMarker, unsigned int* ioFPRsUsed, char* outStruct, // caller-allocated unsigned int* ioStructMarker) { unsigned int srcGMarker = 0; unsigned int srcFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; unsigned int destMarker = 0; static unsigned int recurseCount = 0; if (ioGPRMarker) srcGMarker = *ioGPRMarker; if (ioFPRMarker) { srcFMarker = *ioFPRMarker; savedFMarker = srcFMarker; } if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioStructMarker) destMarker = *ioStructMarker; size_t i; switch (inType->size) { case 1: case 2: case 4: srcGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: srcFMarker = ALIGN(srcFMarker, 4); srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { *(float*)&outStruct[destMarker] = (float)*(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(float*)&outStruct[destMarker] = (float)*(double*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcFMarker = ALIGN(srcFMarker, 8); destMarker = ALIGN(destMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { *(double*)&outStruct[destMarker] = *(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(double*)&outStruct[destMarker] = *(double*)&inGPRs[srcGMarker]; destMarker += 8; // Skip next GPR srcGMarker += 8; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: destMarker = ALIGN(destMarker, 16); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { srcFMarker = ALIGN(srcFMarker, 8); srcGMarker = ALIGN(srcGMarker, 8); *(long double*)&outStruct[destMarker] = *(long double*)&inFPRs[srcFMarker]; srcFMarker += 16; fprsUsed += 2; } else { srcFMarker = ALIGN(srcFMarker, 16); srcGMarker = ALIGN(srcGMarker, 16); *(long double*)&outStruct[destMarker] = *(long double*)&inGPRs[srcGMarker]; } destMarker += 16; // Skip next 2 GPRs srcGMarker += 16; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { if (inType->alignment == 1) // chars only { if (inType->size == 1) outStruct[destMarker++] = inGPRs[srcGMarker++]; else if (inType->size == 2) { outStruct[destMarker++] = inGPRs[srcGMarker++]; outStruct[destMarker++] = inGPRs[srcGMarker++]; i++; } else { memcpy(&outStruct[destMarker], &inGPRs[srcGMarker], inType->size); srcGMarker += inType->size; destMarker += inType->size; i += inType->size - 1; } } else // chars and other stuff { outStruct[destMarker++] = inGPRs[srcGMarker++]; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, inType->alignment); // was 8 } } break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcGMarker = ALIGN(srcGMarker, 2); destMarker = ALIGN(destMarker, 2); *(short*)&outStruct[destMarker] = *(short*)&inGPRs[srcGMarker]; srcGMarker += 2; destMarker += 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); *(int*)&outStruct[destMarker] = *(int*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcGMarker = ALIGN(srcGMarker, 8); destMarker = ALIGN(destMarker, 8); *(long long*)&outStruct[destMarker] = *(long long*)&inGPRs[srcGMarker]; srcGMarker += 8; destMarker += 8; break; case FFI_TYPE_STRUCT: recurseCount++; ffi64_struct_to_ram_form(inType->elements[i], inGPRs, &srcGMarker, inFPRs, &srcFMarker, &fprsUsed, outStruct, &destMarker); recurseCount--; break; default: FFI_ASSERT(0); // unknown element type break; } } srcGMarker = ALIGN(srcGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && srcGMarker == 16) { *(long double*)&outStruct[0] = *(long double*)&inGPRs[0]; srcFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioGPRMarker) *ioGPRMarker = ALIGN(srcGMarker, 8); if (ioFPRMarker) *ioFPRMarker = srcFMarker; if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioStructMarker) *ioStructMarker = ALIGN(destMarker, 8); } /* ffi64_struct_to_reg_form Copy a struct's elements into buffers that can be sliced into registers. Return the sizes of the output buffers in bytes. Pass NULL buffer pointers to calculate size only. outGPRs[0-7] == r3, outFPRs[0-7] == f1 ... */ void ffi64_struct_to_reg_form( const ffi_type* inType, const char* inStruct, unsigned int* ioStructMarker, unsigned int* ioFPRsUsed, char* outGPRs, // caller-allocated unsigned int* ioGPRSize, char* outFPRs, // caller-allocated unsigned int* ioFPRSize) { size_t i; unsigned int srcMarker = 0; unsigned int destGMarker = 0; unsigned int destFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; static unsigned int recurseCount = 0; if (ioStructMarker) srcMarker = *ioStructMarker; if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioGPRSize) destGMarker = *ioGPRSize; if (ioFPRSize) { destFMarker = *ioFPRSize; savedFMarker = destFMarker; } switch (inType->size) { case 1: case 2: case 4: destGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { // Shadow floating-point types in GPRs for vararg and pre-ANSI // functions. case FFI_TYPE_FLOAT: // Nudge markers to next 4/8-byte boundary srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = (double)*(float*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = (double)*(float*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcMarker = ALIGN(srcMarker, 8); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = *(double*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = *(double*)&inStruct[srcMarker]; srcMarker += 8; // Skip next GPR destGMarker += 8; destGMarker = ALIGN(destGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: srcMarker = ALIGN(srcMarker, 16); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { destFMarker = ALIGN(destFMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outFPRs != NULL && inStruct != NULL) *(long double*)&outFPRs[destFMarker] = *(long double*)&inStruct[srcMarker]; if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; destFMarker += 16; fprsUsed += 2; } else { destGMarker = ALIGN(destGMarker, 16); if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; } srcMarker += 16; destGMarker += 16; // Skip next 2 GPRs destGMarker = ALIGN(destGMarker, 8); // was 16 break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: if (inType->alignment == 1) // bytes only { if (inType->size == 1) { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; } else if (inType->size == 2) { if (outGPRs != NULL && inStruct != NULL) { outGPRs[destGMarker] = inStruct[srcMarker]; outGPRs[destGMarker + 1] = inStruct[srcMarker + 1]; } srcMarker += 2; destGMarker += 2; i++; } else { if (outGPRs != NULL && inStruct != NULL) { // Avoid memcpy for small chunks. if (inType->size <= sizeof(long)) *(long*)&outGPRs[destGMarker] = *(long*)&inStruct[srcMarker]; else memcpy(&outGPRs[destGMarker], &inStruct[srcMarker], inType->size); } srcMarker += inType->size; destGMarker += inType->size; i += inType->size - 1; } } else // bytes and other stuff { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, inType->alignment); // was 8 } } break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcMarker = ALIGN(srcMarker, 2); destGMarker = ALIGN(destGMarker, 2); if (outGPRs != NULL && inStruct != NULL) *(short*)&outGPRs[destGMarker] = *(short*)&inStruct[srcMarker]; srcMarker += 2; destGMarker += 2; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); if (outGPRs != NULL && inStruct != NULL) *(int*)&outGPRs[destGMarker] = *(int*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcMarker = ALIGN(srcMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outGPRs != NULL && inStruct != NULL) *(long long*)&outGPRs[destGMarker] = *(long long*)&inStruct[srcMarker]; srcMarker += 8; destGMarker += 8; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_STRUCT: recurseCount++; ffi64_struct_to_reg_form(inType->elements[i], inStruct, &srcMarker, &fprsUsed, outGPRs, &destGMarker, outFPRs, &destFMarker); recurseCount--; break; default: FFI_ASSERT(0); break; } } destGMarker = ALIGN(destGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && destGMarker == 16) { if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[0] = *(long double*)&inStruct[0]; destFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioStructMarker) *ioStructMarker = ALIGN(srcMarker, 8); if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioGPRSize) *ioGPRSize = ALIGN(destGMarker, 8); if (ioFPRSize) *ioFPRSize = ALIGN(destFMarker, 8); } /* ffi64_stret_needs_ptr Determine whether a returned struct needs a pointer in r3 or can fit in registers. */ bool ffi64_stret_needs_ptr( const ffi_type* inType, unsigned short* ioGPRCount, unsigned short* ioFPRCount) { // Obvious case first- struct is larger than combined FPR size. if (inType->size > 14 * 8) return true; // Now the struct can physically fit in registers, determine if it // also fits logically. bool needsPtr = false; unsigned short gprsUsed = 0; unsigned short fprsUsed = 0; size_t i; if (ioGPRCount) gprsUsed = *ioGPRCount; if (ioFPRCount) fprsUsed = *ioFPRCount; for (i = 0; inType->elements[i] != NULL && !needsPtr; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: gprsUsed++; fprsUsed++; if (fprsUsed > 13) needsPtr = true; break; case FFI_TYPE_LONGDOUBLE: gprsUsed += 2; fprsUsed += 2; if (fprsUsed > 14) needsPtr = true; break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { gprsUsed++; if (gprsUsed > 8) { needsPtr = true; break; } if (inType->elements[i + 1] == NULL) // last byte in the struct break; // Count possible contiguous bytes ahead, up to 8. unsigned short j; for (j = 1; j < 8; j++) { if (inType->elements[i + j] == NULL || !FFI_TYPE_1_BYTE(inType->elements[i + j]->type)) break; } i += j - 1; // allow for i++ before the test condition break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: gprsUsed++; if (gprsUsed > 8) needsPtr = true; break; case FFI_TYPE_STRUCT: needsPtr = ffi64_stret_needs_ptr( inType->elements[i], &gprsUsed, &fprsUsed); break; default: FFI_ASSERT(0); break; } } if (ioGPRCount) *ioGPRCount = gprsUsed; if (ioFPRCount) *ioFPRCount = fprsUsed; return needsPtr; } /* ffi64_data_size Calculate the size in bytes of an ffi type. */ unsigned int ffi64_data_size( const ffi_type* inType) { unsigned int size = 0; switch (inType->type) { case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: size = 1; break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: size = 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_FLOAT: size = 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: size = 8; break; case FFI_TYPE_LONGDOUBLE: size = 16; break; case FFI_TYPE_STRUCT: ffi64_struct_to_reg_form( inType, NULL, NULL, NULL, NULL, &size, NULL, NULL); break; case FFI_TYPE_VOID: break; default: FFI_ASSERT(0); break; } return size; } #endif /* defined(__ppc64__) */ #endif /* __ppc__ || __ppc64__ */
the_stack_data/175142060.c
#include <stdio.h> typedef struct oldV { int x; long y; int z; }ejhash; ejhash constructor(int x, long y, int z) { ejhash obj; obj.x = x; obj.y = y; obj.z = z; return obj; } int hashCode(ejhash obj) { int h = obj.x; h = h * 31 + (int) (obj.y ^ (obj.y >> 32)); h = h * 31 + obj.z; return h; } void testCollision1(int x1, long y1, int z1,int x2, long y2, int z2) { ejhash o1 = constructor(x1, y1, z1); ejhash o2 = constructor(x2, y2, z2); if (hashCode(o1) == hashCode(o2)) { printf("%s\n","Solved hash collision 1"); } }
the_stack_data/767722.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ /* * This test verifies that the application can set up an alternate stack for * its signal handler. */ #include <stdio.h> #include <signal.h> #include <stdlib.h> char Stack[SIGSTKSZ]; static void Handle(int); int main() { struct sigaction act; stack_t ss; ss.ss_sp = Stack; ss.ss_size = sizeof(Stack); ss.ss_flags = 0; if (sigaltstack(&ss, 0) != 0) { fprintf(stderr, "Unable to set alternate stack\n"); return 1; } printf("Alternate stack is %p - %p\n", Stack, &Stack[SIGSTKSZ]); act.sa_handler = Handle; act.sa_flags = SA_ONSTACK; sigemptyset(&act.sa_mask); if (sigaction(SIGUSR1, &act, 0) != 0) { fprintf(stderr, "Unable to set up USR1 handler\n"); return 1; } raise(SIGUSR1); return 0; } static void Handle(int sig) { char *sp = (char *)&sig; printf("Got signal %d with SP=%p\n", sig, sp); if (sp < Stack || sp > &Stack[SIGSTKSZ]) { fprintf(stderr, "Handler not running on alternate stack\n"); exit(1); } }
the_stack_data/1270564.c
#include <stdio.h> int main(){ int inp = 0, i; scanf("%d", &inp); for(i=1; i<=inp; i++) printf("%d\n", i); return 0; }
the_stack_data/184517964.c
#define BITSLICE(x, a, b) ((x) >> (b)) & ((1 << ((a)-(b)+1)) - 1) #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include<assert.h> int symbol; int assert_forward = 1; int action_run; void end_assertions(); int hdr_tcp_ack_453638; int traverse_453638 = 0; int meta_stats_metadata_dupack_le_3_454027; int traverse_454027 = 0; int hdr_ipv4_ttl_eq_0_455545; uint64_t constant_hdr_tcp_dstPort_455552; uint64_t constant_hdr_tcp_seqNo_455559; uint64_t constant_hdr_tcp_ackNo_455566; uint64_t constant_hdr_tcp_dataOffset_455573; uint64_t constant_hdr_tcp_res_455580; uint64_t constant_hdr_tcp_ecn_455587; uint64_t constant_hdr_tcp_urg_455594; uint64_t constant_hdr_tcp_ack_455601; uint64_t constant_hdr_tcp_push_455608; uint64_t constant_hdr_tcp_rst_455615; uint64_t constant_hdr_tcp_syn_455622; uint64_t constant_hdr_tcp_fin_455629; uint64_t constant_hdr_tcp_window_455636; uint64_t constant_hdr_tcp_checksum_455643; uint64_t constant_hdr_tcp_urgentPtr_455650; void lookup_reverse_455435(); void update_flow_dupack_0_453843(); void NoAction_30_453274(); void _drop_4_454454(); void set_nhop_0_454574(); void accept(); void _drop_1_454438(); void flow_retx_3dupack_455113(); void NoAction_28_453272(); void lookup_flow_map_0_454610(); void record_IP_0_454487(); void set_dmac_0_454420(); void NoAction_20_453264(); void NoAction_26_453270(); void sample_rtt_sent_455503(); void parse_ethernet(); void parse_sack(); void NoAction_29_453273(); void parse_tcp(); void lookup_455401(); void update_flow_rcvd_0_453896(); void debug_454943(); void increase_mincwnd_0_454461(); void start(); void send_frame_453170(); void lookup_flow_map_reverse_0_454672(); void _drop_0_453154(); void reject(); void direction_454977(); void NoAction_23_453267(); void sample_new_rtt_0_454900(); void update_flow_retx_timeout_0_454141(); void NoAction_0_453126(); void NoAction_31_453275(); void use_sample_rtt_0_459912(); void parse_mss(); void parse_ts(); void use_sample_rtt_first_0_458416(); void ipv4_lpm_455342(); void NoAction_22_453266(); void parse_end(); void NoAction_19_453263(); void init_455308(); void increase_cwnd_455274(); void forward_455215(); void parse_ipv4(); void flow_sent_455181(); void NoAction_21_453265(); void get_sender_IP_0_453622(); void flow_dupack_455045(); void rewrite_mac_0_453136(); void flow_retx_timeout_455147(); void NoAction_27_453271(); void NoAction_25_453269(); void flow_rcvd_455079(); void NoAction_24_453268(); void NoAction_32_453276(); void save_source_IP_0_453564(); void parse_tcp_options(); void NoAction_1_453262(); void parse_nop(); void parse_wscale(); void update_flow_retx_3dupack_0_454011(); void first_rtt_sample_455011(); void update_flow_sent_0_454233(); void sample_rtt_rcvd_455469(); void NoAction_33_453277(); typedef struct { uint32_t ingress_port : 9; uint32_t egress_spec : 9; uint32_t egress_port : 9; uint32_t clone_spec : 32; uint32_t instance_type : 32; uint8_t drop : 1; uint32_t recirculate_port : 16; uint32_t packet_length : 32; uint32_t enq_timestamp : 32; uint32_t enq_qdepth : 19; uint32_t deq_timedelta : 32; uint32_t deq_qdepth : 19; uint64_t ingress_global_timestamp : 48; uint32_t lf_field_list : 32; uint32_t mcast_grp : 16; uint8_t resubmit_flag : 1; uint32_t egress_rid : 16; uint8_t checksum_error : 1; } standard_metadata_t; void mark_to_drop() { assert_forward = 0; end_assertions(); exit(0); } typedef struct { uint64_t ingress_global_timestamp : 48; uint32_t lf_field_list : 32; uint32_t mcast_grp : 16; uint32_t egress_rid : 16; } intrinsic_metadata_t; typedef struct { uint8_t parse_tcp_options_counter : 8; } my_metadata_t; typedef struct { uint32_t nhop_ipv4 : 32; } routing_metadata_t; typedef struct { uint32_t dummy : 32; uint32_t dummy2 : 32; uint8_t flow_map_index : 2; uint32_t senderIP : 32; uint32_t seqNo : 32; uint32_t ackNo : 32; uint32_t sample_rtt_seq : 32; uint32_t rtt_samples : 32; uint32_t mincwnd : 32; uint32_t dupack : 32; } stats_metadata_t; typedef struct { uint8_t isValid : 1; uint64_t dstAddr : 48; uint64_t srcAddr : 48; uint32_t etherType : 16; } ethernet_t; typedef struct { uint8_t isValid : 1; uint8_t version : 4; uint8_t ihl : 4; uint8_t diffserv : 8; uint32_t totalLen : 16; uint32_t identification : 16; uint8_t flags : 3; uint32_t fragOffset : 13; uint8_t ttl : 8; uint8_t protocol : 8; uint32_t hdrChecksum : 16; uint32_t srcAddr : 32; uint32_t dstAddr : 32; } ipv4_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; } options_end_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; uint8_t len : 8; uint32_t MSS : 16; } options_mss_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; uint8_t len : 8; } options_sack_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; uint8_t len : 8; uint64_t ttee : 64; } options_ts_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; uint8_t len : 8; uint8_t wscale : 8; } options_wscale_t; typedef struct { uint8_t isValid : 1; uint32_t srcPort : 16; uint32_t dstPort : 16; uint32_t seqNo : 32; uint32_t ackNo : 32; uint8_t dataOffset : 4; uint8_t res : 3; uint8_t ecn : 3; uint8_t urg : 1; uint8_t ack : 1; uint8_t push : 1; uint8_t rst : 1; uint8_t syn : 1; uint8_t fin : 1; uint32_t window : 16; uint32_t checksum : 16; uint32_t urgentPtr : 16; } tcp_t; typedef struct { uint8_t isValid : 1; uint8_t kind : 8; } options_nop_t; typedef struct { intrinsic_metadata_t intrinsic_metadata; my_metadata_t my_metadata; routing_metadata_t routing_metadata; stats_metadata_t stats_metadata; } metadata; typedef struct { ethernet_t ethernet; ipv4_t ipv4; options_end_t options_end; options_mss_t options_mss; options_sack_t options_sack; options_ts_t options_ts; options_wscale_t options_wscale; tcp_t tcp; int options_nop_index; options_nop_t options_nop[3]; } headers; headers hdr; metadata meta; standard_metadata_t standard_metadata; uint8_t tmp_0; void parse_end() { //Extract hdr.options_end hdr.options_end.isValid = 1; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 255; parse_tcp_options(); } void parse_ethernet() { //Extract hdr.ethernet hdr.ethernet.isValid = 1; klee_assume(hdr.ethernet.etherType == 2048); parse_ipv4(); } void parse_ipv4() { //Extract hdr.ipv4 hdr.ipv4.isValid = 1; klee_assume(hdr.ipv4.protocol == 6); parse_tcp(); } void parse_mss() { //Extract hdr.options_mss hdr.options_mss.isValid = 1; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 252; parse_tcp_options(); } void parse_nop() { //Extract hdr.options_nop.next hdr.options_nop[hdr.options_nop_index].isValid = 1; hdr.options_nop_index++; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 255; parse_tcp_options(); } void parse_sack() { //Extract hdr.options_sack hdr.options_sack.isValid = 1; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 254; parse_tcp_options(); } void parse_tcp() { //Extract hdr.tcp hdr.tcp.isValid = 1; meta.my_metadata.parse_tcp_options_counter = (uint8_t) hdr.tcp.dataOffset << 2 + 12; klee_assume(!(hdr.tcp.syn == 1)); accept(); } void parse_tcp_options() { klee_make_symbolic(&tmp_0, sizeof(tmp_0), "tmp_0"); if(((meta.my_metadata.parse_tcp_options_counter & 255) == (0 & 255)) && ((BITSLICE(tmp_0, 7, 0) & 0) == (0 & 0))){ accept(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (0 & 255))){ parse_end(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (1 & 255))){ parse_nop(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (2 & 255))){ parse_mss(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (3 & 255))){ parse_wscale(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (4 & 255))){ parse_sack(); } else if(((meta.my_metadata.parse_tcp_options_counter & 0) == (0 & 0)) && ((BITSLICE(tmp_0, 7, 0) & 255) == (8 & 255))){ parse_ts(); } } void parse_ts() { //Extract hdr.options_ts hdr.options_ts.isValid = 1; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 246; parse_tcp_options(); } void parse_wscale() { //Extract hdr.options_wscale hdr.options_wscale.isValid = 1; meta.my_metadata.parse_tcp_options_counter = meta.my_metadata.parse_tcp_options_counter + 253; parse_tcp_options(); } void start() { parse_ethernet(); } void accept() { } void reject() { assert_forward = 0; end_assertions(); exit(0); } void ParserImpl() { klee_make_symbolic(&hdr, sizeof(hdr), "hdr"); klee_make_symbolic(&meta, sizeof(meta), "meta"); klee_make_symbolic(&standard_metadata, sizeof(standard_metadata), "standard_metadata"); start(); } //Control void egress() { send_frame_453170(); } // Action void NoAction_0_453126() { action_run = 453126; } // Action void rewrite_mac_0_453136() { action_run = 453136; uint64_t smac; klee_make_symbolic(&smac, sizeof(smac), "smac"); hdr.ethernet.srcAddr = smac; } // Action void _drop_0_453154() { action_run = 453154; mark_to_drop(); } //Table void send_frame_453170() { // int symbol; // klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); // switch(symbol) { //switch(klee_int("symbol")){ // case 0: rewrite_mac_0_453136(); break; _drop_0_453154(); // default: NoAction_0_453126(); break; // } // keys: standard_metadata.egress_port:exact // size 256 // default_action NoAction_0(); } typedef struct { uint32_t field : 32; uint32_t field_0 : 32; uint8_t field_1 : 8; uint32_t field_2 : 16; uint32_t field_3 : 16; } tuple_0; //Control void ingress() { hdr_ipv4_ttl_eq_0_455545 = (hdr.ipv4.ttl == 0); constant_hdr_tcp_dstPort_455552 = hdr.tcp.dstPort; constant_hdr_tcp_seqNo_455559 = hdr.tcp.seqNo; constant_hdr_tcp_ackNo_455566 = hdr.tcp.ackNo; constant_hdr_tcp_dataOffset_455573 = hdr.tcp.dataOffset; constant_hdr_tcp_res_455580 = hdr.tcp.res; constant_hdr_tcp_ecn_455587 = hdr.tcp.ecn; constant_hdr_tcp_urg_455594 = hdr.tcp.urg; constant_hdr_tcp_ack_455601 = hdr.tcp.ack; constant_hdr_tcp_push_455608 = hdr.tcp.push; constant_hdr_tcp_rst_455615 = hdr.tcp.rst; constant_hdr_tcp_syn_455622 = hdr.tcp.syn; constant_hdr_tcp_fin_455629 = hdr.tcp.fin; constant_hdr_tcp_window_455636 = hdr.tcp.window; constant_hdr_tcp_checksum_455643 = hdr.tcp.checksum; constant_hdr_tcp_urgentPtr_455650 = hdr.tcp.urgentPtr; if((hdr.ipv4.protocol == 6)) { if(hdr.ipv4.srcAddr > hdr.ipv4.dstAddr) { lookup_455401(); } else { lookup_reverse_455435(); } if((hdr.tcp.syn == 1) && (hdr.tcp.ack == 0)) { init_455308(); } else { direction_454977(); } if((hdr.ipv4.srcAddr == meta.stats_metadata.senderIP)) { if(hdr.tcp.seqNo > meta.stats_metadata.seqNo) { flow_sent_455181(); if((meta.stats_metadata.sample_rtt_seq == 0)) { sample_rtt_sent_455503(); } if(meta.stats_metadata.dummy > meta.stats_metadata.mincwnd) { increase_cwnd_455274(); } } else { if((meta.stats_metadata.dupack == 3)) { flow_retx_3dupack_455113(); } else { flow_retx_timeout_455147(); } } } else { if((hdr.ipv4.dstAddr == meta.stats_metadata.senderIP)) { if(hdr.tcp.ackNo > meta.stats_metadata.ackNo) { flow_rcvd_455079(); if(hdr.tcp.ackNo >= meta.stats_metadata.sample_rtt_seq && meta.stats_metadata.sample_rtt_seq > 0) { if((meta.stats_metadata.rtt_samples == 0)) { first_rtt_sample_455011(); } else { sample_rtt_rcvd_455469(); } } } else { flow_dupack_455045(); } } else { debug_454943(); } } } ipv4_lpm_455342(); forward_455215(); } // Action void NoAction_1_453262() { action_run = 453262; } // Action void NoAction_19_453263() { action_run = 453263; } // Action void NoAction_20_453264() { action_run = 453264; } // Action void NoAction_21_453265() { action_run = 453265; } // Action void NoAction_22_453266() { action_run = 453266; } // Action void NoAction_23_453267() { action_run = 453267; } // Action void NoAction_24_453268() { action_run = 453268; } // Action void NoAction_25_453269() { action_run = 453269; } // Action void NoAction_26_453270() { action_run = 453270; } // Action void NoAction_27_453271() { action_run = 453271; } // Action void NoAction_28_453272() { action_run = 453272; } // Action void NoAction_29_453273() { action_run = 453273; } // Action void NoAction_30_453274() { action_run = 453274; } // Action void NoAction_31_453275() { action_run = 453275; } // Action void NoAction_32_453276() { action_run = 453276; } // Action void NoAction_33_453277() { action_run = 453277; } // Action void save_source_IP_0_453564() { action_run = 453564; } // Action void get_sender_IP_0_453622() { action_run = 453622; hdr_tcp_ack_453638 = (hdr.tcp.ack == 1); traverse_453638 = 1; uint64_t t84710467_540e_4c78_b9f4_a4a8cde883cd; klee_make_symbolic(&t84710467_540e_4c78_b9f4_a4a8cde883cd, sizeof(t84710467_540e_4c78_b9f4_a4a8cde883cd), "t84710467_540e_4c78_b9f4_a4a8cde883cd"); meta.stats_metadata.senderIP = t84710467_540e_4c78_b9f4_a4a8cde883cd; uint64_t tc2657781_89c5_4494_8e21_499aa8caec4b; klee_make_symbolic(&tc2657781_89c5_4494_8e21_499aa8caec4b, sizeof(tc2657781_89c5_4494_8e21_499aa8caec4b), "tc2657781_89c5_4494_8e21_499aa8caec4b"); meta.stats_metadata.seqNo = tc2657781_89c5_4494_8e21_499aa8caec4b; uint64_t t397c4235_0d25_461d_a146_a5548f85870c; klee_make_symbolic(&t397c4235_0d25_461d_a146_a5548f85870c, sizeof(t397c4235_0d25_461d_a146_a5548f85870c), "t397c4235_0d25_461d_a146_a5548f85870c"); meta.stats_metadata.ackNo = t397c4235_0d25_461d_a146_a5548f85870c; uint64_t t33d4b0dc_4a79_4d9a_8866_01d06bbeaa6d; klee_make_symbolic(&t33d4b0dc_4a79_4d9a_8866_01d06bbeaa6d, sizeof(t33d4b0dc_4a79_4d9a_8866_01d06bbeaa6d), "t33d4b0dc_4a79_4d9a_8866_01d06bbeaa6d"); meta.stats_metadata.sample_rtt_seq = t33d4b0dc_4a79_4d9a_8866_01d06bbeaa6d; uint64_t t0042b193_6254_498c_9290_8b199fb35363; klee_make_symbolic(&t0042b193_6254_498c_9290_8b199fb35363, sizeof(t0042b193_6254_498c_9290_8b199fb35363), "t0042b193_6254_498c_9290_8b199fb35363"); meta.stats_metadata.rtt_samples = t0042b193_6254_498c_9290_8b199fb35363; uint64_t tdd4becaa_adba_48c2_b312_88bc177dfe51; klee_make_symbolic(&tdd4becaa_adba_48c2_b312_88bc177dfe51, sizeof(tdd4becaa_adba_48c2_b312_88bc177dfe51), "tdd4becaa_adba_48c2_b312_88bc177dfe51"); meta.stats_metadata.mincwnd = tdd4becaa_adba_48c2_b312_88bc177dfe51; uint64_t t543c8d31_64cb_4a09_aedb_760122b697d0; klee_make_symbolic(&t543c8d31_64cb_4a09_aedb_760122b697d0, sizeof(t543c8d31_64cb_4a09_aedb_760122b697d0), "t543c8d31_64cb_4a09_aedb_760122b697d0"); meta.stats_metadata.dupack = t543c8d31_64cb_4a09_aedb_760122b697d0; } // Action void use_sample_rtt_first_0_458416() { action_run = 458416; uint64_t t8fd99da7_2390_4faa_b72e_1c8d2fe8ec76; klee_make_symbolic(&t8fd99da7_2390_4faa_b72e_1c8d2fe8ec76, sizeof(t8fd99da7_2390_4faa_b72e_1c8d2fe8ec76), "t8fd99da7_2390_4faa_b72e_1c8d2fe8ec76"); meta.stats_metadata.dummy = t8fd99da7_2390_4faa_b72e_1c8d2fe8ec76; meta.stats_metadata.dummy2 = (uint32_t) meta.intrinsic_metadata.ingress_global_timestamp; meta.stats_metadata.dummy2 = meta.intrinsic_metadata.ingress_global_timestamp - meta.stats_metadata.dummy; } // Action void update_flow_dupack_0_453843() { action_run = 453843; uint64_t td57b7426_1259_40f2_b38e_53c8db694035; klee_make_symbolic(&td57b7426_1259_40f2_b38e_53c8db694035, sizeof(td57b7426_1259_40f2_b38e_53c8db694035), "td57b7426_1259_40f2_b38e_53c8db694035"); meta.stats_metadata.dummy = td57b7426_1259_40f2_b38e_53c8db694035; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; } // Action void update_flow_rcvd_0_453896() { action_run = 453896; uint64_t t027c3367_c295_4744_92d9_7f71fe8da4cf; klee_make_symbolic(&t027c3367_c295_4744_92d9_7f71fe8da4cf, sizeof(t027c3367_c295_4744_92d9_7f71fe8da4cf), "t027c3367_c295_4744_92d9_7f71fe8da4cf"); meta.stats_metadata.dummy = t027c3367_c295_4744_92d9_7f71fe8da4cf; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; } // Action void update_flow_retx_3dupack_0_454011() { action_run = 454011; meta_stats_metadata_dupack_le_3_454027 = (meta.stats_metadata.dupack < 3); traverse_454027 = 1; uint64_t t6cdeb88d_183a_496b_bd1c_7545b4500045; klee_make_symbolic(&t6cdeb88d_183a_496b_bd1c_7545b4500045, sizeof(t6cdeb88d_183a_496b_bd1c_7545b4500045), "t6cdeb88d_183a_496b_bd1c_7545b4500045"); meta.stats_metadata.dummy = t6cdeb88d_183a_496b_bd1c_7545b4500045; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; uint64_t t1eef1073_2268_4adb_9b9f_f0c4a478783b; klee_make_symbolic(&t1eef1073_2268_4adb_9b9f_f0c4a478783b, sizeof(t1eef1073_2268_4adb_9b9f_f0c4a478783b), "t1eef1073_2268_4adb_9b9f_f0c4a478783b"); meta.stats_metadata.dummy = t1eef1073_2268_4adb_9b9f_f0c4a478783b; meta.stats_metadata.dummy = meta.stats_metadata.dummy >> 1; } // Action void update_flow_retx_timeout_0_454141() { action_run = 454141; uint64_t t7814ce3c_d0d1_42be_ac04_b1119828690e; klee_make_symbolic(&t7814ce3c_d0d1_42be_ac04_b1119828690e, sizeof(t7814ce3c_d0d1_42be_ac04_b1119828690e), "t7814ce3c_d0d1_42be_ac04_b1119828690e"); meta.stats_metadata.dummy = t7814ce3c_d0d1_42be_ac04_b1119828690e; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; } // Action void update_flow_sent_0_454233() { action_run = 454233; uint64_t te1b91cfe_5d0f_4530_a884_0be722efb1a8; klee_make_symbolic(&te1b91cfe_5d0f_4530_a884_0be722efb1a8, sizeof(te1b91cfe_5d0f_4530_a884_0be722efb1a8), "te1b91cfe_5d0f_4530_a884_0be722efb1a8"); meta.stats_metadata.dummy = te1b91cfe_5d0f_4530_a884_0be722efb1a8; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; meta.stats_metadata.dummy = (uint32_t) meta.intrinsic_metadata.ingress_global_timestamp; uint64_t t3a4972fa_fbbd_4235_b9aa_fd47bb2f6e52; klee_make_symbolic(&t3a4972fa_fbbd_4235_b9aa_fd47bb2f6e52, sizeof(t3a4972fa_fbbd_4235_b9aa_fd47bb2f6e52), "t3a4972fa_fbbd_4235_b9aa_fd47bb2f6e52"); meta.stats_metadata.dummy2 = t3a4972fa_fbbd_4235_b9aa_fd47bb2f6e52; meta.stats_metadata.dummy = meta.stats_metadata.dummy - meta.stats_metadata.dummy2; uint64_t t5ed0309f_6b03_4d51_8a63_e7eb5084dca2; klee_make_symbolic(&t5ed0309f_6b03_4d51_8a63_e7eb5084dca2, sizeof(t5ed0309f_6b03_4d51_8a63_e7eb5084dca2), "t5ed0309f_6b03_4d51_8a63_e7eb5084dca2"); meta.stats_metadata.dummy = t5ed0309f_6b03_4d51_8a63_e7eb5084dca2; uint64_t tc41b4e19_7e83_4d1c_b753_4eb7539bdea3; klee_make_symbolic(&tc41b4e19_7e83_4d1c_b753_4eb7539bdea3, sizeof(tc41b4e19_7e83_4d1c_b753_4eb7539bdea3), "tc41b4e19_7e83_4d1c_b753_4eb7539bdea3"); meta.stats_metadata.dummy2 = tc41b4e19_7e83_4d1c_b753_4eb7539bdea3; meta.stats_metadata.dummy = meta.stats_metadata.dummy - meta.stats_metadata.dummy2; } // Action void set_dmac_0_454420() { action_run = 454420; uint64_t dmac; klee_make_symbolic(&dmac, sizeof(dmac), "dmac"); hdr.ethernet.dstAddr = dmac; } // Action void _drop_1_454438() { action_run = 454438; mark_to_drop(); } // Action void _drop_4_454454() { action_run = 454454; mark_to_drop(); } // Action void increase_mincwnd_0_454461() { action_run = 454461; } // Action void record_IP_0_454487() { action_run = 454487; uint64_t tc9585c7b_790e_494a_9f60_75e1b3890aab; klee_make_symbolic(&tc9585c7b_790e_494a_9f60_75e1b3890aab, sizeof(tc9585c7b_790e_494a_9f60_75e1b3890aab), "tc9585c7b_790e_494a_9f60_75e1b3890aab"); meta.stats_metadata.senderIP = tc9585c7b_790e_494a_9f60_75e1b3890aab; } // Action void set_nhop_0_454574() { action_run = 454574; uint32_t nhop_ipv4; klee_make_symbolic(&nhop_ipv4, sizeof(nhop_ipv4), "nhop_ipv4"); uint32_t port; klee_make_symbolic(&port, sizeof(port), "port"); meta.routing_metadata.nhop_ipv4 = nhop_ipv4; standard_metadata.egress_spec = port; hdr.ipv4.ttl = hdr.ipv4.ttl + 255; } // Action void lookup_flow_map_0_454610() { action_run = 454610; uint64_t t12faf59b_7eed_401f_8b88_85a14fdc44c3; klee_make_symbolic(&t12faf59b_7eed_401f_8b88_85a14fdc44c3, sizeof(t12faf59b_7eed_401f_8b88_85a14fdc44c3), "t12faf59b_7eed_401f_8b88_85a14fdc44c3"); meta.stats_metadata.flow_map_index = t12faf59b_7eed_401f_8b88_85a14fdc44c3; } // Action void lookup_flow_map_reverse_0_454672() { action_run = 454672; uint64_t t4e5dad2d_c703_4505_91bd_095317cef223; klee_make_symbolic(&t4e5dad2d_c703_4505_91bd_095317cef223, sizeof(t4e5dad2d_c703_4505_91bd_095317cef223), "t4e5dad2d_c703_4505_91bd_095317cef223"); meta.stats_metadata.flow_map_index = t4e5dad2d_c703_4505_91bd_095317cef223; } // Action void use_sample_rtt_0_459912() { action_run = 459912; uint64_t t1bc1f8cd_431f_40a1_a56a_30b3fb7aee68; klee_make_symbolic(&t1bc1f8cd_431f_40a1_a56a_30b3fb7aee68, sizeof(t1bc1f8cd_431f_40a1_a56a_30b3fb7aee68), "t1bc1f8cd_431f_40a1_a56a_30b3fb7aee68"); meta.stats_metadata.dummy = t1bc1f8cd_431f_40a1_a56a_30b3fb7aee68; meta.stats_metadata.dummy2 = (uint32_t) meta.intrinsic_metadata.ingress_global_timestamp; meta.stats_metadata.dummy2 = meta.intrinsic_metadata.ingress_global_timestamp - meta.stats_metadata.dummy; uint64_t t5cf0c290_3447_4bec_982f_ad887f31367e; klee_make_symbolic(&t5cf0c290_3447_4bec_982f_ad887f31367e, sizeof(t5cf0c290_3447_4bec_982f_ad887f31367e), "t5cf0c290_3447_4bec_982f_ad887f31367e"); meta.stats_metadata.dummy = t5cf0c290_3447_4bec_982f_ad887f31367e; meta.stats_metadata.dummy = 7 * meta.stats_metadata.dummy + meta.stats_metadata.dummy2; meta.stats_metadata.dummy = meta.stats_metadata.dummy >> 3; uint64_t t41623da2_e52b_4cf5_9c2d_ef3958befb03; klee_make_symbolic(&t41623da2_e52b_4cf5_9c2d_ef3958befb03, sizeof(t41623da2_e52b_4cf5_9c2d_ef3958befb03), "t41623da2_e52b_4cf5_9c2d_ef3958befb03"); meta.stats_metadata.dummy = t41623da2_e52b_4cf5_9c2d_ef3958befb03; meta.stats_metadata.dummy = meta.stats_metadata.dummy + 1; } // Action void sample_new_rtt_0_454900() { action_run = 454900; } //Table void debug_454943() { klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: save_source_IP_0_453564(); break; default: NoAction_1_453262(); break; } } //Table void direction_454977() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: get_sender_IP_0_453622(); break; default: NoAction_19_453263(); break; } // default_action NoAction_19(); } //Table void first_rtt_sample_455011() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: use_sample_rtt_first_0_458416(); break; default: NoAction_20_453264(); break; } // default_action NoAction_20(); } //Table void flow_dupack_455045() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: update_flow_dupack_0_453843(); break; default: NoAction_21_453265(); break; } // default_action NoAction_21(); } //Table void flow_rcvd_455079() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: update_flow_rcvd_0_453896(); break; default: NoAction_22_453266(); break; } // default_action NoAction_22(); } //Table void flow_retx_3dupack_455113() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: update_flow_retx_3dupack_0_454011(); break; default: NoAction_23_453267(); break; } // default_action NoAction_23(); } //Table void flow_retx_timeout_455147() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: update_flow_retx_timeout_0_454141(); break; default: NoAction_24_453268(); break; } // default_action NoAction_24(); } //Table void flow_sent_455181() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: update_flow_sent_0_454233(); break; default: NoAction_25_453269(); break; } // default_action NoAction_25(); } //Table void forward_455215() { // int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: set_dmac_0_454420(); break; case 1: _drop_1_454438(); break; default: NoAction_26_453270(); break; } // keys: meta.routing_metadata.nhop_ipv4:exact // size 512 // default_action NoAction_26(); } //Table void increase_cwnd_455274() { // int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: increase_mincwnd_0_454461(); break; default: NoAction_27_453271(); break; } // default_action NoAction_27(); } //Table void init_455308() { //int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: record_IP_0_454487(); break; default: NoAction_28_453272(); break; } // default_action NoAction_28(); } //Table void ipv4_lpm_455342() { // int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: set_nhop_0_454574(); break; case 1: _drop_4_454454(); break; default: NoAction_29_453273(); break; } // keys: hdr.ipv4.dstAddr:lpm // size 1024 // default_action NoAction_29(); } //Table void lookup_455401() { // int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: lookup_flow_map_0_454610(); break; default: NoAction_30_453274(); break; } // default_action NoAction_30(); } //Table void lookup_reverse_455435() { klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: lookup_flow_map_reverse_0_454672(); break; default: NoAction_31_453275(); break; } // default_action NoAction_31(); } //Table void sample_rtt_rcvd_455469() { klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: use_sample_rtt_0_459912(); break; default: NoAction_32_453276(); break; } // default_action NoAction_32(); } //Table void sample_rtt_sent_455503() { // int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { //switch(klee_int("symbol")){ case 0: sample_new_rtt_0_454900(); break; default: NoAction_33_453277(); break; } // default_action NoAction_33(); } typedef struct { uint8_t field_4 : 4; uint8_t field_5 : 4; uint8_t field_6 : 8; uint32_t field_7 : 16; uint32_t field_8 : 16; uint8_t field_9 : 3; uint32_t field_10 : 13; uint8_t field_11 : 8; uint8_t field_12 : 8; uint32_t field_13 : 32; uint32_t field_14 : 32; } tuple_1; //Control void verifyChecksum() { verify_checksum(); } //Control void computeChecksum() { update_checksum(); } int main() { ParserImpl(); ingress(); egress(); end_assertions(); return 0; } void end_assertions(){ if(!(!(hdr_tcp_ack_453638) || (traverse_453638))) klee_print_once(0 , "!(hdr_tcp_ack_453638) || (traverse_453638)"); if(!(!(meta_stats_metadata_dupack_le_3_454027) || (!traverse_454027))) klee_print_once(1, "!(meta_stats_metadata_dupack_le_3_454027) || (!traverse_454027)"); if(!(!(hdr_ipv4_ttl_eq_0_455545) || (!assert_forward))) klee_print_once(2, "!(hdr_ipv4_ttl_eq_0_455545) || (!assert_forward)"); ///if(!(constant_hdr_tcp_dstPort_455552 == hdr.tcp.dstPort)) assert_error("constant_hdr_tcp_dstPort_455552 == hdr.tcp.dstPort"); ///if(!(constant_hdr_tcp_seqNo_455559 == hdr.tcp.seqNo)) assert_error("constant_hdr_tcp_seqNo_455559 == hdr.tcp.seqNo"); ///if(!(constant_hdr_tcp_ackNo_455566 == hdr.tcp.ackNo)) assert_error("constant_hdr_tcp_ackNo_455566 == hdr.tcp.ackNo"); ///if(!(constant_hdr_tcp_dataOffset_455573 == hdr.tcp.dataOffset)) assert_error("constant_hdr_tcp_dataOffset_455573 == hdr.tcp.dataOffset"); ///if(!(constant_hdr_tcp_res_455580 == hdr.tcp.res)) assert_error("constant_hdr_tcp_res_455580 == hdr.tcp.res"); ///if(!(constant_hdr_tcp_ecn_455587 == hdr.tcp.ecn)) assert_error("constant_hdr_tcp_ecn_455587 == hdr.tcp.ecn"); ///if(!(constant_hdr_tcp_urg_455594 == hdr.tcp.urg)) assert_error("constant_hdr_tcp_urg_455594 == hdr.tcp.urg"); ///if(!(constant_hdr_tcp_ack_455601 == hdr.tcp.ack)) assert_error("constant_hdr_tcp_ack_455601 == hdr.tcp.ack"); ///if(!(constant_hdr_tcp_push_455608 == hdr.tcp.push)) assert_error("constant_hdr_tcp_push_455608 == hdr.tcp.push"); ///if(!(constant_hdr_tcp_rst_455615 == hdr.tcp.rst)) assert_error("constant_hdr_tcp_rst_455615 == hdr.tcp.rst"); ///if(!(constant_hdr_tcp_syn_455622 == hdr.tcp.syn)) assert_error("constant_hdr_tcp_syn_455622 == hdr.tcp.syn"); ///if(!(constant_hdr_tcp_fin_455629 == hdr.tcp.fin)) assert_error("constant_hdr_tcp_fin_455629 == hdr.tcp.fin"); ///if(!(constant_hdr_tcp_window_455636 == hdr.tcp.window)) assert_error("constant_hdr_tcp_window_455636 == hdr.tcp.window"); ///if(!(constant_hdr_tcp_checksum_455643 == hdr.tcp.checksum)) assert_error("constant_hdr_tcp_checksum_455643 == hdr.tcp.checksum"); ///if(!(constant_hdr_tcp_urgentPtr_455650 == hdr.tcp.urgentPtr)) assert_error("constant_hdr_tcp_urgentPtr_455650 == hdr.tcp.urgentPtr"); }
the_stack_data/25136873.c
/* PR debug/36690 */ /* { dg-do compile } */ /* { dg-options "-O0 -gdwarf -dA" } */ int cnt; void bar (int i) { cnt += i; } void foo (int i, int j) { if (j) { bar (i + 1); goto f1; } bar (i + 2); goto f2; f1: if (i > 10) goto f3; f2: if (i > 40) goto f4; else goto f5; f3: bar (i); f4: bar (i); f5: bar (i); } int main (void) { foo (0, 1); foo (11, 1); foo (21, 0); foo (41, 0); return 0; } /* { dg-final { scan-assembler "pr36690-3.c:19" } } */ /* { dg-final { scan-assembler "pr36690-3.c:22" } } */ /* { dg-final { scan-assembler "pr36690-3.c:25" } } */ /* { dg-final { scan-assembler "pr36690-3.c:28" } } */ /* { dg-final { scan-assembler "pr36690-3.c:30" } } */
the_stack_data/147492.c
int main() { int x=0; while(1) { assert(x==0); } assert(x!=0); }
the_stack_data/648399.c
int main() { __label__ x, z; goto y; int bar() { goto y; y: ; goto x; int baz() { __label__ x; goto x; x: ; goto z; y: ; goto y; } } x: ; y: ; z: ; }
the_stack_data/68665.c
// REQUIRES: x86-registered-target // RUN: %clang -### -target x86_64-scei-ps4 %s -o - 2>&1 | \ // RUN: FileCheck %s // RUN: %clang -### -target x86_64-scei-ps4 -Wa,-mrelax-relocations=yes %s -o - 2>&1 | \ // RUN: FileCheck %s // RUN: %clang -### -target x86_64-scei-ps4 -Wa,-mrelax-relocations=no %s -o - 2>&1 | \ // RUN: FileCheck -check-prefix=UNSET %s // RUN: %clang -### -x assembler -target x86_64-scei-ps4 %s -o - 2>&1 | \ // RUN: FileCheck %s // RUN: %clang -### -x assembler -target x86_64-scei-ps4 -Wa,-mrelax-relocations=yes %s -o - 2>&1 | \ // RUN: FileCheck %s // RUN: %clang -### -x assembler -target x86_64-scei-ps4 -Wa,-mrelax-relocations=no %s -o - 2>&1 | \ // RUN: FileCheck -check-prefix=UNSET %s // CHECK: "--mrelax-relocations" // UNSET-NOT: "--mrelax-relocations"
the_stack_data/240839.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; unsigned char local1 ; { state[0UL] = (input[0UL] + 51238316UL) + (unsigned char)234; local1 = 0UL; while (local1 < 1UL) { if (state[0UL] < local1) { if (state[0UL] == local1) { state[local1] = state[0UL] + state[local1]; } else { state[local1] += state[local1]; } } else { state[0UL] *= state[local1]; } local1 += 2UL; } output[0UL] = (state[0UL] - 883537325UL) + (unsigned char)204; } } int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 128) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/20450497.c
// Check passing PowerPC ABI options to the backend. // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv1 %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1 | FileCheck -check-prefix=CHECK-ELFv1 %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1-qpx | FileCheck -check-prefix=CHECK-ELFv1-QPX %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2q | FileCheck -check-prefix=CHECK-ELFv1-QPX %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2 -mqpx | FileCheck -check-prefix=CHECK-ELFv1-QPX %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2q -mno-qpx | FileCheck -check-prefix=CHECK-ELFv1 %s // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv2 | FileCheck -check-prefix=CHECK-ELFv2-BE %s // RUN: %clang -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv2 %s // RUN: %clang -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1 | FileCheck -check-prefix=CHECK-ELFv1-LE %s // RUN: %clang -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv2 | FileCheck -check-prefix=CHECK-ELFv2 %s // RUN: %clang -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=altivec | FileCheck -check-prefix=CHECK-ELFv2 %s // RUN: %clang -target powerpc64-unknown-freebsd11 %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv1 %s // RUN: %clang -target powerpc64-unknown-freebsd12 %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv1 %s // RUN: %clang -target powerpc64-unknown-freebsd13 %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv2-BE %s // RUN: %clang -target powerpc64-unknown-freebsd14 %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv2-BE %s // RUN: %clang -target powerpc64-unknown-openbsd %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv2-BE-PIE %s // RUN: %clang -target powerpc64-linux-musl %s -### 2>&1 | FileCheck --check-prefix=CHECK-ELFv2-BE-PIE %s // CHECK-ELFv1: "-mrelocation-model" "static" // CHECK-ELFv1: "-target-abi" "elfv1" // CHECK-ELFv1-LE: "-mrelocation-model" "static" // CHECK-ELFv1-LE: "-target-abi" "elfv1" // CHECK-ELFv1-QPX: "-mrelocation-model" "static" // CHECK-ELFv1-QPX: "-target-abi" "elfv1-qpx" // CHECK-ELFv2: "-mrelocation-model" "static" // CHECK-ELFv2: "-target-abi" "elfv2" // CHECK-ELFv2-BE: "-mrelocation-model" "static" // CHECK-ELFv2-BE: "-target-abi" "elfv2" // CHECK-ELFv2-BE-PIE: "-mrelocation-model" "pic" "-pic-level" "2" "-pic-is-pie" // CHECK-ELFv2-BE-PIE: "-target-abi" "elfv2" // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv1-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1 | FileCheck -check-prefix=CHECK-ELFv1-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1-qpx | FileCheck -check-prefix=CHECK-ELFv1-QPX-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2q | FileCheck -check-prefix=CHECK-ELFv1-QPX-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2 -mqpx | FileCheck -check-prefix=CHECK-ELFv1-QPX-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mcpu=a2q -mno-qpx | FileCheck -check-prefix=CHECK-ELFv1-PIC %s // RUN: %clang -fPIC -target powerpc64-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv2 | FileCheck -check-prefix=CHECK-ELFv2-PIC %s // RUN: %clang -fPIC -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv2-PIC %s // RUN: %clang -fPIC -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv1 | FileCheck -check-prefix=CHECK-ELFv1-PIC %s // RUN: %clang -fPIC -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=elfv2 | FileCheck -check-prefix=CHECK-ELFv2-PIC %s // RUN: %clang -fPIC -target powerpc64le-unknown-linux-gnu %s -### -o %t.o 2>&1 \ // RUN: -mabi=altivec | FileCheck -check-prefix=CHECK-ELFv2-PIC %s // CHECK-ELFv1-PIC: "-mrelocation-model" "pic" "-pic-level" "2" // CHECK-ELFv1-PIC: "-target-abi" "elfv1" // CHECK-ELFv1-QPX-PIC: "-mrelocation-model" "pic" "-pic-level" "2" // CHECK-ELFv1-QPX-PIC: "-target-abi" "elfv1-qpx" // CHECK-ELFv2-PIC: "-mrelocation-model" "pic" "-pic-level" "2" // CHECK-ELFv2-PIC: "-target-abi" "elfv2" // Check -mabi=ieeelongdouble is passed through but it does not change -target-abi. // RUN: %clang -target powerpc64le-linux-gnu %s -mabi=ieeelongdouble -mabi=elfv1 -### 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv1-IEEE %s // RUN: %clang -target powerpc64le-linux-gnu %s -mabi=elfv1 -mabi=ieeelongdouble -### 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv1-IEEE %s // RUN: %clang -target powerpc64le-linux-gnu %s -mabi=elfv2 -mabi=elfv1 -mabi=ibmlongdouble -mabi=ieeelongdouble -### 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv1-IEEE %s // CHECK-ELFv1-IEEE: "-mabi=ieeelongdouble" // CHECK-ELFv1-IEEE: "-target-abi" "elfv1" // Check -mabi=ibmlongdouble is the default. // RUN: %clang -target powerpc64le-linux-gnu %s -### 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv2-IBM128 %s // RUN: %clang -target powerpc64le-linux-gnu %s -mabi=ibmlongdouble -### 2>&1 \ // RUN: | FileCheck -check-prefix=CHECK-ELFv2-IBM128 %s // CHECK-ELFv2-IBM128-NOT: "-mabi=ieeelongdouble" // CHECK-ELFv2-IBM128: "-target-abi" "elfv2"
the_stack_data/170452402.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // inet_ntop #include <sys/epoll.h> #define BUFSIZE 1024 #define INFTIM -1 void error(char *msg) { perror(msg); exit(1); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "use: %s <port>\n", argv[0]); exit(1); } int port = atoi(argv[1]); puts(":: START ::"); int main_fd = socket(AF_INET, SOCK_STREAM, 0); if (main_fd < 0) { error("ERROR opening socket"); } // Avoid "ERROR on binding: Address already in use". int optval = 1; setsockopt(main_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); struct sockaddr_in srv_addr; memset(&srv_addr, 0, sizeof(srv_addr)); srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); srv_addr.sin_port = htons((unsigned short)port); if (bind(main_fd, (struct sockaddr *) &srv_addr, sizeof(srv_addr)) < 0) { error("ERROR on binding"); } if (listen(main_fd, 5) < 0) { error("ERROR on listen"); } const int MAX_CLIENTS = FOPEN_MAX; int events_fd = epoll_create(MAX_CLIENTS); if (events_fd == -1) { close(main_fd); error("ERROR on epoll_create"); } struct epoll_event ev; ev.data.fd = 0; ev.events = EPOLLIN; if (epoll_ctl(events_fd, EPOLL_CTL_ADD, 0, &ev) == -1) { close(main_fd); close(events_fd); error("ERROR on epoll_ctl for stdin");; } ev.data.fd = main_fd; ev.events = EPOLLIN; if (epoll_ctl(events_fd, EPOLL_CTL_ADD, main_fd, &ev) == -1) { close(main_fd); close(events_fd); error("ERROR on epoll_ctl for main_fd");; } struct epoll_event events[MAX_CLIENTS]; int nevents = 2; char buf[BUFSIZE]; int len; for (;;) { int nready = epoll_wait(events_fd, events, nevents, INFTIM); printf("there are %d ready descriptors\n", nready); for (int i = 0; i < nready; ++i) { struct epoll_event * pev = &events[i]; if (pev->data.fd == 0 && pev->events & EPOLLIN) { puts("** exiting **"); goto end; // goto is usually considered harmful } else if (pev->data.fd == main_fd && pev->events & EPOLLIN) { puts("** new connection **"); struct sockaddr_in cli_addr; unsigned int cli_addr_len = sizeof cli_addr; int conn_fd = accept(main_fd, (struct sockaddr *)&cli_addr, &cli_addr_len); if (conn_fd < 0) { error("ERROR on accept"); } char cli_addr_str[INET_ADDRSTRLEN]; if (!inet_ntop(AF_INET, &(cli_addr.sin_addr), cli_addr_str, INET_ADDRSTRLEN)) { error("ERROR on inet_ntoa\n"); } printf("server established connection with %s at port %d\n", cli_addr_str, ntohs(cli_addr.sin_port)); if (nevents == MAX_CLIENTS) { puts("** maximum clients exceeded"); close(conn_fd); } else { ev.data.fd = conn_fd; ev.events = EPOLLIN; if (epoll_ctl(events_fd, EPOLL_CTL_ADD, conn_fd, &ev) == -1) { close(conn_fd); error("ERROR on epoll_ctl for conn_fd");; } else { nevents++; } } } else if (pev->events & (EPOLLIN | EPOLLERR)) { int conn_fd = pev->data.fd; printf("** event occurred on client %d **\n", conn_fd); len = read(conn_fd, buf, BUFSIZE); if (len < 0) { close(conn_fd); error("ERROR reading from socket"); } buf[len] = 0; printf("server received %d bytes: %s\n", len, buf); if (len > 0) { int wlen = write(conn_fd, buf, len); if (wlen < 0) { error("ERROR writing to socket"); } } if (len == 0 || (strncmp(buf, "quit", 4) == 0 && buf[4] < ' ')) { printf("** client %d closing **\n", conn_fd); ev.data.fd = conn_fd; ev.events = EPOLLIN; if (epoll_ctl(events_fd, EPOLL_CTL_DEL, conn_fd, &ev) == -1) { close(main_fd); close(events_fd); error("ERROR on epoll_ctl for conn_fd"); } close(conn_fd); } } } } end: puts("** closing **"); close(events_fd); close(main_fd); puts(":: END ::"); return 0; }
the_stack_data/159656.c
#ifdef COMPILE_FOR_TEST #include <assert.h> #define assume(cond) assert(cond) #endif void main(int argc, char* argv[]) { int x_0_0;//sh_buf.outcnt int x_0_1;//sh_buf.outcnt int x_0_2;//sh_buf.outcnt int x_0_3;//sh_buf.outcnt int x_0_4;//sh_buf.outcnt int x_0_5;//sh_buf.outcnt int x_0_6;//sh_buf.outcnt int x_0_7;//sh_buf.outcnt int x_1_0;//sh_buf.outbuf[0] int x_1_1;//sh_buf.outbuf[0] int x_2_0;//sh_buf.outbuf[1] int x_2_1;//sh_buf.outbuf[1] int x_3_0;//sh_buf.outbuf[2] int x_3_1;//sh_buf.outbuf[2] int x_4_0;//sh_buf.outbuf[3] int x_4_1;//sh_buf.outbuf[3] int x_5_0;//sh_buf.outbuf[4] int x_5_1;//sh_buf.outbuf[4] int x_6_0;//sh_buf.outbuf[5] int x_7_0;//sh_buf.outbuf[6] int x_8_0;//sh_buf.outbuf[7] int x_9_0;//sh_buf.outbuf[8] int x_10_0;//sh_buf.outbuf[9] int x_11_0;//LOG_BUFSIZE int x_11_1;//LOG_BUFSIZE int x_12_0;//CREST_scheduler::lock_0 int x_13_0;//t3 T0 int x_14_0;//t2 T0 int x_15_0;//arg T0 int x_16_0;//functioncall::param T0 int x_16_1;//functioncall::param T0 int x_17_0;//buffered T0 int x_18_0;//functioncall::param T0 int x_18_1;//functioncall::param T0 int x_19_0;//functioncall::param T0 int x_19_1;//functioncall::param T0 int x_20_0;//functioncall::param T0 int x_20_1;//functioncall::param T0 int x_21_0;//functioncall::param T0 int x_21_1;//functioncall::param T0 int x_22_0;//direction T0 int x_23_0;//functioncall::param T0 int x_23_1;//functioncall::param T0 int x_24_0;//functioncall::param T0 int x_24_1;//functioncall::param T0 int x_25_0;//functioncall::param T0 int x_25_1;//functioncall::param T0 int x_26_0;//functioncall::param T0 int x_26_1;//functioncall::param T0 int x_27_0;//functioncall::param T0 int x_27_1;//functioncall::param T0 int x_28_0;//functioncall::param T0 int x_28_1;//functioncall::param T0 int x_29_0;//functioncall::param T0 int x_29_1;//functioncall::param T0 int x_30_0;//functioncall::param T0 int x_30_1;//functioncall::param T0 int x_31_0;//functioncall::param T0 int x_31_1;//functioncall::param T0 int x_32_0;//functioncall::param T0 int x_32_1;//functioncall::param T0 int x_33_0;//functioncall::param T0 int x_33_1;//functioncall::param T0 int x_34_0;//functioncall::param T0 int x_34_1;//functioncall::param T0 int x_35_0;//functioncall::param T1 int x_35_1;//functioncall::param T1 int x_36_0;//functioncall::param T1 int x_36_1;//functioncall::param T1 int x_37_0;//i T1 int x_37_1;//i T1 int x_37_2;//i T1 int x_38_0;//rv T1 int x_39_0;//rv T1 int x_39_1;//rv T1 int x_40_0;//functioncall::param T1 int x_40_1;//functioncall::param T1 int x_41_0;//functioncall::param T1 int x_41_1;//functioncall::param T1 int x_42_0;//functioncall::param T1 int x_42_1;//functioncall::param T1 int x_43_0;//functioncall::param T1 int x_43_1;//functioncall::param T1 int x_44_0;//functioncall::param T1 int x_44_1;//functioncall::param T1 int x_45_0;//functioncall::param T1 int x_45_1;//functioncall::param T1 int x_46_0;//functioncall::param T1 int x_46_1;//functioncall::param T1 int x_47_0;//functioncall::param T1 int x_47_1;//functioncall::param T1 int x_48_0;//functioncall::param T1 int x_48_1;//functioncall::param T1 int x_49_0;//functioncall::param T2 int x_49_1;//functioncall::param T2 int x_50_0;//functioncall::param T2 int x_50_1;//functioncall::param T2 int x_51_0;//i T2 int x_51_1;//i T2 int x_51_2;//i T2 int x_51_3;//i T2 int x_52_0;//rv T2 int x_53_0;//rv T2 int x_53_1;//rv T2 int x_54_0;//functioncall::param T2 int x_54_1;//functioncall::param T2 int x_55_0;//functioncall::param T2 int x_55_1;//functioncall::param T2 int x_56_0;//functioncall::param T2 int x_56_1;//functioncall::param T2 int x_57_0;//functioncall::param T2 int x_57_1;//functioncall::param T2 int x_58_0;//functioncall::param T2 int x_58_1;//functioncall::param T2 int x_59_0;//functioncall::param T2 int x_59_1;//functioncall::param T2 int x_59_2;//functioncall::param T2 int x_60_0;//functioncall::param T2 int x_60_1;//functioncall::param T2 T_0_0_0: x_0_0 = 0; T_0_1_0: x_1_0 = 0; T_0_2_0: x_2_0 = 0; T_0_3_0: x_3_0 = 0; T_0_4_0: x_4_0 = 0; T_0_5_0: x_5_0 = 0; T_0_6_0: x_6_0 = 0; T_0_7_0: x_7_0 = 0; T_0_8_0: x_8_0 = 0; T_0_9_0: x_9_0 = 0; T_0_10_0: x_10_0 = 0; T_0_11_0: x_11_0 = 0; T_0_12_0: x_13_0 = 116958752; T_0_13_0: x_14_0 = 3123393120; T_0_14_0: x_15_0 = 0; T_0_15_0: x_16_0 = 260790031; T_0_16_0: x_16_1 = -1; T_0_17_0: x_17_0 = 0; T_0_18_0: x_18_0 = 686176536; T_0_19_0: x_18_1 = x_17_0; T_0_20_0: x_19_0 = 2032840956; T_0_21_0: x_19_1 = 97; T_0_22_0: x_20_0 = 979495058; T_0_23_0: x_20_1 = 0; T_0_24_0: x_21_0 = 1268872150; T_0_25_0: x_21_1 = 0; T_0_26_0: x_22_0 = -1171578816; T_0_27_0: x_23_0 = 304966238; T_0_28_0: x_23_1 = x_22_0; T_0_29_0: x_24_0 = 1818414327; T_0_30_0: x_24_1 = 0; T_0_31_0: x_12_0 = -1; T_0_32_0: x_0_1 = 5; T_0_33_0: x_1_1 = 72; T_0_34_0: x_2_1 = 69; T_0_35_0: x_3_1 = 76; T_0_36_0: x_4_1 = 76; T_0_37_0: x_5_1 = 79; T_0_38_0: x_25_0 = 949556484; T_0_39_0: x_25_1 = 83; T_0_40_0: x_26_0 = 1631178373; T_0_41_0: x_26_1 = 1; T_0_42_0: x_27_0 = 320649845; T_0_43_0: x_27_1 = 1; T_0_44_0: x_28_0 = 730662018; T_0_45_0: x_28_1 = 1; T_0_46_0: x_29_0 = 936940727; T_0_47_0: x_29_1 = 82; T_0_48_0: x_30_0 = 127453753; T_0_49_0: x_30_1 = 90; T_0_50_0: x_31_0 = 304813265; T_0_51_0: x_31_1 = 1; T_0_52_0: x_32_0 = 1248297238; T_0_53_0: x_32_1 = 1; T_0_54_0: x_33_0 = 268497715; T_0_55_0: x_33_1 = 2; T_0_56_0: x_34_0 = 1404758262; T_0_57_0: x_34_1 = 2; T_0_58_0: x_11_1 = 5; T_2_59_2: x_49_0 = 1077936412; T_2_60_2: x_49_1 = x_33_1; T_2_61_2: x_50_0 = 1238490165; T_2_62_2: x_50_1 = x_34_1; T_2_63_2: x_51_0 = 0; T_2_64_2: x_52_0 = 1120915969; T_2_65_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_53_0 = -1164511312; T_2_66_2: x_35_0 = 552469697; T_1_67_1: x_35_1 = x_27_1; T_1_68_1: x_36_0 = 779880553; T_1_69_1: x_36_1 = x_28_1; T_1_70_1: x_37_0 = 0; T_1_71_1: x_38_0 = 1123017217; T_1_72_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_39_0 = -1164511312; T_1_73_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_54_0 = 1764739384; T_1_74_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_54_1 = -1; T_2_75_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_53_1 = x_54_1; T_2_76_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_53_1 + 1 == 0) x_0_2 = 0; T_2_77_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_0 = 178442407; T_2_78_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_1 = -1; T_2_79_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_39_1 = x_40_1; T_1_80_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_39_1 + 1 == 0) x_0_3 = 0; T_1_81_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_0 = 1373516023; T_1_82_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_1 = 9; T_1_83_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_0 = 1555035536; T_1_84_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_1 = x_41_1; T_1_85_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_0_4 = 0; T_1_86_1: if (x_36_1 < x_11_1) x_43_0 = 1890965614; T_1_87_1: if (x_36_1 < x_11_1) x_43_1 = 47969366714112; T_1_88_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_55_0 = 1473243422; T_1_89_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_55_1 = 9; T_1_90_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_56_0 = 87261679; T_1_91_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_56_1 = x_55_1; T_2_92_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_0_5 = 0; T_2_93_2: if (x_50_1 < x_11_1) x_57_0 = 1063025979; T_2_94_2: if (x_50_1 < x_11_1) x_57_1 = 47969368815360; T_2_95_2: if (x_36_1 < x_11_1) x_44_0 = 837262843; T_2_96_2: if (x_36_1 < x_11_1) x_44_1 = x_0_4 + x_36_1; T_2_97_2: if (x_36_1 < x_11_1) x_37_1 = 0; T_1_98_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_0 = 900973062; T_1_99_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_1 = 47969366714112; T_1_100_1: if (x_36_1 < x_11_1) x_37_2 = 1 + x_37_1; T_1_101_1: if (x_36_1 < x_11_1) x_46_0 = 1323816010; T_1_102_1: if (x_36_1 < x_11_1) x_46_1 = 47969366714112; T_1_103_1: if (x_36_1 < x_11_1) x_0_6 = x_0_5 + x_36_1; T_1_104_1: if (x_50_1 < x_11_1) x_58_0 = 1523439380; T_1_105_1: if (x_50_1 < x_11_1) x_58_1 = x_0_5 + x_50_1; T_1_106_1: if (x_50_1 < x_11_1) x_51_1 = 0; T_2_107_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_59_0 = 786330371; T_2_108_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_59_1 = 47969368815360; T_2_109_2: if (x_50_1 < x_11_1) x_51_2 = 1 + x_51_1; T_2_110_2: if (x_50_1 < x_11_1 && x_51_2 < x_49_1) x_59_2 = 47969368815360; T_2_111_2: if (x_50_1 < x_11_1) x_51_3 = 1 + x_51_2; T_2_112_2: if (x_50_1 < x_11_1) x_60_0 = 155827421; T_2_113_2: if (x_50_1 < x_11_1) x_60_1 = 47969368815360; T_2_114_2: if (x_36_1 < x_11_1) x_47_0 = 644827882; T_2_115_2: if (x_36_1 < x_11_1) x_47_1 = 47969366714112; T_2_116_2: if (x_50_1 < x_11_1) x_0_7 = x_0_6 + x_50_1; T_2_117_2: if (x_36_1 < x_11_1) x_48_0 = 1091296609; T_1_118_1: if (x_36_1 < x_11_1) x_48_1 = 47969366714112; T_1_119_1: if (x_36_1 < x_11_1) assert(x_0_7 == x_44_1); }
the_stack_data/319404.c
/* ============================================================================ Name : Prompt.c Author : Alex Lucchesi Version : 1.0001 Copyright : The Unlicense Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct _node{ int value; struct _node *succ; } typedef Node; Node *list; void listl(); void put(char *arg){ int num; sscanf(arg, "%d", &num); Node *new = (Node*) calloc(1, sizeof(Node)); new->succ = NULL; new->value = num; if(!list) list = new; else{ Node *it = list; while(it->succ) it = it->succ; it->succ = new; } listl(); } void get(char *arg){ int num; sscanf(arg, "%d", &num); Node *it = list; while(it && --num) it = it->succ; printf("%d\n", it->value); } void listl(){ Node *it = list; for(; it; it = it->succ){ printf("%d ", it->value); } printf("\n"); } void removel(char *arg){ int num; sscanf(arg, "%d", &num); Node *rem; if(num == 1){ rem = list; list = list->succ; } else{ Node *it = list; num -= 2; while(it->succ && num--) it = it->succ; rem = it->succ; it->succ = it->succ->succ; } if(rem){ printf("%d\n", rem->value); free(rem); } } // XXX Please checkout c075177074c145fa6561853a039cdb19b16025a3 to get the 90 min test. void clear(){ Node *it; while(list){ it = list; list = list->succ; free(it); } list = NULL; } void first(){ if(list) printf("%d\n", list->value); } void last(){ Node *it = list; if(!it->succ) printf("%d\n", it->value); else{ while(it->succ) it = it->succ; printf("%d\n", it->value); } } // XXX Please checkout c075177074c145fa6561853a039cdb19b16025a3 to get the 90 min test. void sort(){ Node *new = NULL; Node *old = list; while(old){ if(!new){ new = old; old = old->succ; new->succ = NULL; } else{ Node *it = old; old = old->succ; if(it->value < new->value){ it->succ = new; new = it; } else{ Node *it2 = new; while(it2->succ){ if(it->value < it2->succ->value){ it->succ = it2->succ; it2->succ = it; it = NULL; break; } it2 = it2->succ; } if(it){ it2->succ = it; it->succ = NULL; } } } } list = new; listl(); } void process_cmd(char *input){ char cmd[7]; sscanf(input, "%s", cmd); if(strncmp(input, "put", 3) == 0) put(input + strlen(cmd)); if(strncmp(input, "get", 3) == 0) get(input + strlen(cmd)); if(strncmp(input, "list", 4) == 0) listl(); if(strncmp(input, "remove", 6) == 0) removel(input + strlen(cmd)); if(strncmp(input, "clear", 5) == 0) clear(); if(strncmp(input, "first", 5) == 0) first(); if(strncmp(input, "last", 4) == 0) last(); if(strncmp(input, "sort", 4) == 0) sort(); } // void print_entry(char *entry) { // printf("You entered: %s\n", entry); // } int main(int argc, char *argv[]) { list = NULL; char input[201]; while(1) { printf("prompt> "); if (fgets(input, 200, stdin) == NULL) { printf("An error ocurred.\n"); break; } if (strncmp(input, "exit\n", 5) == 0) { printf("Leaving. Good bye.\n"); break; } // print_entry(input); process_cmd(input); } return EXIT_SUCCESS; }
the_stack_data/983777.c
/* * The MIT License * * Copyright 2017 azarias. * * 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. */ /* * File: main.c * Author: azarias.boutin * * Created on 4 mai 2017, 14:18 */ #include <stdio.h> #include <stdlib.h> /* * */ int main(int argc, char** argv) { return (EXIT_SUCCESS); }
the_stack_data/167330378.c
/* { dg-do compile } */ /* { dg-options "-O2 -mavx -mtune=generic -dp" } */ extern void exit (int) __attribute__ ((__noreturn__)); extern void bar (void); int foo (int i) { if (i == 0) { bar (); exit (1); } return 0; } /* { dg-final { scan-assembler-not "avx_vzeroupper" } } */
the_stack_data/8168.c
// Simulate genetic inheritance of blood type #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <time.h> // Each person has two parents and two alleles typedef struct person { struct person *parents[2]; char alleles[2]; } person; const int GENERATIONS = 3; const int INDENT_LENGTH = 4; person *create_family(int generations); void print_family(person *p, int generation); void free_family(person *p); char random_allele(); int main(void) { // Seed random number generator srand(time(0)); // Create a new family with three generations person *p = create_family(GENERATIONS); // Print family tree of blood types print_family(p, 0); // Free memory free_family(p); } // Create a new individual with `generations` person *create_family(int generations) { // TODO: Allocate memory for new person // Generation with parent data if (generations > 1) { // TODO: Recursively create blood type histories for parents create_family(generations - 1); // TODO: Randomly assign child alleles based on parents } // Generation without parent data else { // TODO: Set parent pointers to NULL // TODO: Randomly assign alleles } // TODO: Return newly created person return NULL; } // Free `p` and all ancestors of `p`. void free_family(person *p) { // TODO: Handle base case if (p == NULL) { return; } // TODO: Free parents // TODO: Free child } // Print each family member and their alleles. void print_family(person *p, int generation) { // Handle base case if (p == NULL) { return; } // Print indentation for (int i = 0; i < generation * INDENT_LENGTH; i++) { printf(" "); } // Print person printf("Generation %i, blood type %c%c\n", generation, p->alleles[0], p->alleles[1]); print_family(p->parents[0], generation + 1); print_family(p->parents[1], generation + 1); } // Randomly chooses a blood type allele. char random_allele() { int r = rand() % 3; if (r == 0) { return 'A'; } else if (r == 1) { return 'B'; } else { return 'O'; } }