file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/140765256.c
#include <stdio.h> int main() { double a, b, c,media; scanf("%lf%lf%lf", &a, &b,&c); media = ((a*2)+(b*3)+(c*5)) / ((2+3+5)); printf("MEDIA = %.1lf\n", media); return 0; }
the_stack_data/36054.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <assert.h> #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <pthread.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #define BUFFER_SIZE 13 int create_listener_socket(uint16_t port) { int ret = -1; int sock = -1; const int opt = 1; const socklen_t n = sizeof(opt); struct sockaddr_in addr; const int backlog = 10; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) goto done; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, n) != 0) goto done; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) goto done; if (listen(sock, backlog) != 0) goto done; ret = sock; sock = -1; done: if (sock != -1) close(sock); return ret; } typedef struct _client { int sock; uint8_t* data; size_t size; } client_t; #define MAX_CLIENTS 8 typedef struct _clients { client_t data[MAX_CLIENTS]; size_t size; } clients_t; client_t* find_client(clients_t* clients, int sock) { for (size_t i = 0; i < clients->size; i++) { if (clients->data[i].sock == sock) return &clients->data[i]; } /* Not found */ return NULL; } int client_append(client_t* client, const void* data, size_t size) { size_t n = client->size + size; if (!(client->data = realloc(client->data, n))) return -1; memcpy(client->data + client->size, data, size); client->size = n; return 0; } int client_remove_leading(client_t* client, size_t size) { if (size > client->size) return -1; size_t n = client->size - size; memcpy(client->data, client->data + size, n); client->size -= size; return 0; } static int set_blocking(int sock, bool blocking) { int flags; if ((flags = fcntl(sock, F_GETFL, 0)) == -1) return -1; if (blocking) flags &= ~O_NONBLOCK; else flags |= O_NONBLOCK; if (fcntl(sock, F_SETFL, flags) == -1) return -1; return 0; } static int add_events(int epfd, int sock, uint32_t events) { int r; struct epoll_event ev = {.data.fd = sock, .events = events}; return epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev); } static int mod_events(int epfd, int sock, uint32_t events) { int r; struct epoll_event ev = {.data.fd = sock, .events = events}; return epoll_ctl(epfd, EPOLL_CTL_MOD, sock, &ev); } static int del_events(int epfd, int sock) { int r; struct epoll_event ev = {.data.fd = sock, .events = 0}; return epoll_ctl(epfd, EPOLL_CTL_DEL, sock, &ev); } void run_server(uint16_t port, size_t num_clients) { int lsock; bool quit = false; clients_t clients; size_t num_disconnects = 0; int epfd; assert((epfd = epoll_create1(0)) >= 0); memset(&clients, 0, sizeof(clients)); if ((lsock = create_listener_socket(port)) == -1) { assert("create_listener_socket() failed" == NULL); } /* Watch for read events on the lsock socket (i.e., connects). */ assert(add_events(epfd, lsock, EPOLLIN) == 0); while (!quit) { client_t* client; const static int maxevents = MAX_CLIENTS; struct epoll_event events[maxevents]; int timeout = 1000; /* Wait for events. */ printf("wait for events...\n"); int n = epoll_wait(epfd, events, maxevents, timeout); assert(n >= 0); for (size_t i = 0; i < n; i++) { struct epoll_event* event = &events[i]; if (event->events == 0) continue; /* Handle client connection. */ if (events->data.fd == lsock) { if ((event->events & EPOLLIN)) { int sock; if ((sock = accept(lsock, NULL, NULL)) < 0) assert("accept() failed" == NULL); printf("accepted connection\n"); client_t client; client.sock = sock; client.data = NULL; client.size = 0; clients.data[clients.size++] = client; set_blocking(sock, false); assert(add_events(epfd, sock, EPOLLIN) == 0); printf("client %d connect\n", sock); fflush(stdout); } else { assert(false); } continue; } /* Find the client for this event. */ assert((client = find_client(&clients, events->data.fd))); /* Handle client input. */ if ((event->events & EPOLLIN)) { /* Read until EAGAIN is encountered. */ for (;;) { uint8_t buf[BUFFER_SIZE]; ssize_t n; errno = 0; n = recv(client->sock, buf, sizeof(buf), 0); if (n > 0) { printf("client %d input: %zd bytes\n", client->sock, n); fflush(stdout); assert(client_append(client, buf, n) == 0); uint32_t events = EPOLLIN | EPOLLOUT; assert(mod_events(epfd, client->sock, events) == 0); } else if (n == 0) { printf("client %d disconnect\n", client->sock); fflush(stdout); /* Client disconnect. */ del_events(epfd, client->sock); close(client->sock); num_disconnects++; if (num_disconnects == num_clients) { quit = true; break; } break; } else if (errno == EAGAIN) { break; } else { assert(false); } } if (quit) break; } /* Handle client input. */ if ((event->events & EPOLLOUT)) { /* Write until output is exhausted or EAGAIN encountered. */ for (;;) { ssize_t n; assert(client->size > 0); errno = 0; /* Send data to client. */ n = send(client->sock, client->data, client->size, 0); if (n > 0) { printf( "client %d output: %zd bytes\n", client->sock, n); fflush(stdout); assert(client_remove_leading(client, n) == 0); if (client->size == 0) { uint32_t events = EPOLLIN; mod_events(epfd, event->data.fd, events); break; } } else if (errno == EAGAIN) { break; } else { assert(false); } } } } } close(lsock); close(epfd); }
the_stack_data/7899.c
/* $NetBSD: calc2.tab.c,v 1.1.1.4 2013/04/06 14:45:28 christos Exp $ */ #ifndef lint static const char yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93"; #endif #define YYBYACC 1 #define YYMAJOR 1 #define YYMINOR 9 #define YYEMPTY (-1) #define yyclearin (yychar = YYEMPTY) #define yyerrok (yyerrflag = 0) #define YYRECOVERING() (yyerrflag != 0) #ifndef yyparse #define yyparse calc2_parse #endif /* yyparse */ #ifndef yylex #define yylex calc2_lex #endif /* yylex */ #ifndef yyerror #define yyerror calc2_error #endif /* yyerror */ #ifndef yychar #define yychar calc2_char #endif /* yychar */ #ifndef yyval #define yyval calc2_val #endif /* yyval */ #ifndef yylval #define yylval calc2_lval #endif /* yylval */ #ifndef yydebug #define yydebug calc2_debug #endif /* yydebug */ #ifndef yynerrs #define yynerrs calc2_nerrs #endif /* yynerrs */ #ifndef yyerrflag #define yyerrflag calc2_errflag #endif /* yyerrflag */ #ifndef yylhs #define yylhs calc2_lhs #endif /* yylhs */ #ifndef yylen #define yylen calc2_len #endif /* yylen */ #ifndef yydefred #define yydefred calc2_defred #endif /* yydefred */ #ifndef yydgoto #define yydgoto calc2_dgoto #endif /* yydgoto */ #ifndef yysindex #define yysindex calc2_sindex #endif /* yysindex */ #ifndef yyrindex #define yyrindex calc2_rindex #endif /* yyrindex */ #ifndef yygindex #define yygindex calc2_gindex #endif /* yygindex */ #ifndef yytable #define yytable calc2_table #endif /* yytable */ #ifndef yycheck #define yycheck calc2_check #endif /* yycheck */ #ifndef yyname #define yyname calc2_name #endif /* yyname */ #ifndef yyrule #define yyrule calc2_rule #endif /* yyrule */ #define YYPREFIX "calc2_" #define YYPURE 0 #line 7 "calc2.y" # include <stdio.h> # include <ctype.h> #ifdef YYBISON #define YYLEX_PARAM base #define YYLEX_DECL() yylex(int *YYLEX_PARAM) #define YYERROR_DECL() yyerror(int regs[26], int *base, const char *s) int YYLEX_DECL(); static void YYERROR_DECL(); #endif #line 111 "calc2.tab.c" #ifndef YYSTYPE typedef int YYSTYPE; #endif /* compatibility with bison */ #ifdef YYPARSE_PARAM /* compatibility with FreeBSD */ # ifdef YYPARSE_PARAM_TYPE # define YYPARSE_DECL() yyparse(YYPARSE_PARAM_TYPE YYPARSE_PARAM) # else # define YYPARSE_DECL() yyparse(void *YYPARSE_PARAM) # endif #else # define YYPARSE_DECL() yyparse(int regs[26], int * base) #endif /* Parameters sent to lex. */ #ifdef YYLEX_PARAM # define YYLEX_DECL() yylex(void *YYLEX_PARAM) # define YYLEX yylex(YYLEX_PARAM) #else # define YYLEX_DECL() yylex(int * base) # define YYLEX yylex(base) #endif /* Parameters sent to yyerror. */ #ifndef YYERROR_DECL #define YYERROR_DECL() yyerror(int regs[26], int * base, const char *s) #endif #ifndef YYERROR_CALL #define YYERROR_CALL(msg) yyerror(regs, base, msg) #endif extern int YYPARSE_DECL(); #define DIGIT 257 #define LETTER 258 #define UMINUS 259 #define YYERRCODE 256 static const short calc2_lhs[] = { -1, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, }; static const short calc2_len[] = { 2, 0, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 1, 2, }; static const short calc2_defred[] = { 1, 0, 0, 17, 0, 0, 0, 0, 0, 0, 3, 0, 15, 14, 0, 2, 0, 0, 0, 0, 0, 0, 0, 18, 0, 6, 0, 0, 0, 0, 9, 10, 11, }; static const short calc2_dgoto[] = { 1, 7, 8, 9, }; static const short calc2_sindex[] = { 0, -40, -7, 0, -55, -38, -38, 1, -29, -247, 0, -38, 0, 0, 22, 0, -38, -38, -38, -38, -38, -38, -38, 0, -29, 0, 51, 60, -20, -20, 0, 0, 0, }; static const short calc2_rindex[] = { 0, 0, 0, 0, 2, 0, 0, 0, 9, -9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, -6, 14, 5, 13, 0, 0, 0, }; static const short calc2_gindex[] = { 0, 0, 65, 0, }; #define YYTABLESIZE 220 static const short calc2_table[] = { 6, 16, 6, 10, 13, 5, 11, 5, 22, 17, 23, 15, 15, 20, 18, 7, 19, 22, 21, 4, 5, 0, 20, 8, 12, 0, 0, 21, 16, 16, 0, 0, 16, 16, 16, 13, 16, 0, 16, 15, 15, 0, 0, 7, 15, 15, 7, 15, 7, 15, 7, 8, 12, 0, 8, 12, 8, 0, 8, 22, 17, 0, 0, 25, 20, 18, 0, 19, 0, 21, 13, 14, 0, 0, 0, 0, 24, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 22, 17, 0, 0, 0, 20, 18, 16, 19, 22, 21, 0, 0, 0, 20, 18, 0, 19, 0, 21, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 8, 12, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 3, 12, }; static const short calc2_check[] = { 40, 10, 40, 10, 10, 45, 61, 45, 37, 38, 257, 10, 10, 42, 43, 10, 45, 37, 47, 10, 10, -1, 42, 10, 10, -1, -1, 47, 37, 38, -1, -1, 41, 42, 43, 41, 45, -1, 47, 37, 38, -1, -1, 38, 42, 43, 41, 45, 43, 47, 45, 38, 38, -1, 41, 41, 43, -1, 45, 37, 38, -1, -1, 41, 42, 43, -1, 45, -1, 47, 5, 6, -1, -1, -1, -1, 11, -1, -1, -1, -1, 16, 17, 18, 19, 20, 21, 22, 37, 38, -1, -1, -1, 42, 43, 124, 45, 37, 47, -1, -1, -1, 42, 43, -1, 45, -1, 47, -1, -1, -1, -1, -1, -1, -1, 124, -1, -1, 124, -1, -1, -1, -1, -1, -1, -1, 124, -1, -1, 124, -1, -1, -1, -1, -1, -1, -1, 124, 124, -1, -1, -1, -1, -1, -1, -1, 124, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 256, 257, 258, 257, 258, }; #define YYFINAL 1 #ifndef YYDEBUG #define YYDEBUG 0 #endif #define YYMAXTOKEN 259 #if YYDEBUG static const char *yyname[] = { "end-of-file",0,0,0,0,0,0,0,0,0,"'\\n'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,"'%'","'&'",0,"'('","')'","'*'","'+'",0,"'-'",0,"'/'",0,0,0,0,0,0,0, 0,0,0,0,0,0,"'='",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"'|'",0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,"DIGIT","LETTER","UMINUS", }; static const char *yyrule[] = { "$accept : list", "list :", "list : list stat '\\n'", "list : list error '\\n'", "stat : expr", "stat : LETTER '=' expr", "expr : '(' expr ')'", "expr : expr '+' expr", "expr : expr '-' expr", "expr : expr '*' expr", "expr : expr '/' expr", "expr : expr '%' expr", "expr : expr '&' expr", "expr : expr '|' expr", "expr : '-' expr", "expr : LETTER", "expr : number", "number : DIGIT", "number : number DIGIT", }; #endif int yydebug; int yynerrs; int yyerrflag; int yychar; YYSTYPE yyval; YYSTYPE yylval; /* define the initial stack-sizes */ #ifdef YYSTACKSIZE #undef YYMAXDEPTH #define YYMAXDEPTH YYSTACKSIZE #else #ifdef YYMAXDEPTH #define YYSTACKSIZE YYMAXDEPTH #else #define YYSTACKSIZE 500 #define YYMAXDEPTH 500 #endif #endif #define YYINITSTACKSIZE 500 typedef struct { unsigned stacksize; short *s_base; short *s_mark; short *s_last; YYSTYPE *l_base; YYSTYPE *l_mark; } YYSTACKDATA; /* variables for the parser stack */ static YYSTACKDATA yystack; #line 73 "calc2.y" /* start of programs */ #ifdef YYBYACC extern int YYLEX_DECL(); #endif int main (void) { int regs[26]; int base = 10; while(!feof(stdin)) { yyparse(regs, &base); } return 0; } static void YYERROR_DECL() { fprintf(stderr, "%s\n", s); } int YYLEX_DECL() { /* lexical analysis routine */ /* returns LETTER for a lower case letter, yylval = 0 through 25 */ /* return DIGIT for a digit, yylval = 0 through 9 */ /* all other characters are returned immediately */ int c; while( (c=getchar()) == ' ' ) { /* skip blanks */ } /* c is now nonblank */ if( islower( c )) { yylval = c - 'a'; return ( LETTER ); } if( isdigit( c )) { yylval = (c - '0') % (*base); return ( DIGIT ); } return( c ); } #line 356 "calc2.tab.c" #if YYDEBUG #include <stdio.h> /* needed for printf */ #endif #include <stdlib.h> /* needed for malloc, etc */ #include <string.h> /* needed for memset */ /* allocate initial stack or double stack size, up to YYMAXDEPTH */ static int yygrowstack(YYSTACKDATA *data) { int i; unsigned newsize; short *newss; YYSTYPE *newvs; if ((newsize = data->stacksize) == 0) newsize = YYINITSTACKSIZE; else if (newsize >= YYMAXDEPTH) return -1; else if ((newsize *= 2) > YYMAXDEPTH) newsize = YYMAXDEPTH; i = (int) (data->s_mark - data->s_base); newss = (short *)realloc(data->s_base, newsize * sizeof(*newss)); if (newss == 0) return -1; data->s_base = newss; data->s_mark = newss + i; newvs = (YYSTYPE *)realloc(data->l_base, newsize * sizeof(*newvs)); if (newvs == 0) return -1; data->l_base = newvs; data->l_mark = newvs + i; data->stacksize = newsize; data->s_last = data->s_base + newsize - 1; return 0; } #if YYPURE || defined(YY_NO_LEAKS) static void yyfreestack(YYSTACKDATA *data) { free(data->s_base); free(data->l_base); memset(data, 0, sizeof(*data)); } #else #define yyfreestack(data) /* nothing */ #endif #define YYABORT goto yyabort #define YYREJECT goto yyabort #define YYACCEPT goto yyaccept #define YYERROR goto yyerrlab int YYPARSE_DECL() { int yym, yyn, yystate; #if YYDEBUG const char *yys; if ((yys = getenv("YYDEBUG")) != 0) { yyn = *yys; if (yyn >= '0' && yyn <= '9') yydebug = yyn - '0'; } #endif yynerrs = 0; yyerrflag = 0; yychar = YYEMPTY; yystate = 0; #if YYPURE memset(&yystack, 0, sizeof(yystack)); #endif if (yystack.s_base == NULL && yygrowstack(&yystack)) goto yyoverflow; yystack.s_mark = yystack.s_base; yystack.l_mark = yystack.l_base; yystate = 0; *yystack.s_mark = 0; yyloop: if ((yyn = yydefred[yystate]) != 0) goto yyreduce; if (yychar < 0) { if ((yychar = YYLEX) < 0) yychar = 0; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, reading %d (%s)\n", YYPREFIX, yystate, yychar, yys); } #endif } if ((yyn = yysindex[yystate]) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { #if YYDEBUG if (yydebug) printf("%sdebug: state %d, shifting to state %d\n", YYPREFIX, yystate, yytable[yyn]); #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack)) { goto yyoverflow; } yystate = yytable[yyn]; *++yystack.s_mark = yytable[yyn]; *++yystack.l_mark = yylval; yychar = YYEMPTY; if (yyerrflag > 0) --yyerrflag; goto yyloop; } if ((yyn = yyrindex[yystate]) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { yyn = yytable[yyn]; goto yyreduce; } if (yyerrflag) goto yyinrecovery; yyerror(regs, base, "syntax error"); goto yyerrlab; yyerrlab: ++yynerrs; yyinrecovery: if (yyerrflag < 3) { yyerrflag = 3; for (;;) { if ((yyn = yysindex[*yystack.s_mark]) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { #if YYDEBUG if (yydebug) printf("%sdebug: state %d, error recovery shifting\ to state %d\n", YYPREFIX, *yystack.s_mark, yytable[yyn]); #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack)) { goto yyoverflow; } yystate = yytable[yyn]; *++yystack.s_mark = yytable[yyn]; *++yystack.l_mark = yylval; goto yyloop; } else { #if YYDEBUG if (yydebug) printf("%sdebug: error recovery discarding state %d\n", YYPREFIX, *yystack.s_mark); #endif if (yystack.s_mark <= yystack.s_base) goto yyabort; --yystack.s_mark; --yystack.l_mark; } } } else { if (yychar == 0) goto yyabort; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, error recovery discards token %d (%s)\n", YYPREFIX, yystate, yychar, yys); } #endif yychar = YYEMPTY; goto yyloop; } yyreduce: #if YYDEBUG if (yydebug) printf("%sdebug: state %d, reducing by rule %d (%s)\n", YYPREFIX, yystate, yyn, yyrule[yyn]); #endif yym = yylen[yyn]; if (yym) yyval = yystack.l_mark[1-yym]; else memset(&yyval, 0, sizeof yyval); switch (yyn) { case 3: #line 35 "calc2.y" { yyerrok ; } break; case 4: #line 39 "calc2.y" { printf("%d\n",yystack.l_mark[0]);} break; case 5: #line 41 "calc2.y" { regs[yystack.l_mark[-2]] = yystack.l_mark[0]; } break; case 6: #line 45 "calc2.y" { yyval = yystack.l_mark[-1]; } break; case 7: #line 47 "calc2.y" { yyval = yystack.l_mark[-2] + yystack.l_mark[0]; } break; case 8: #line 49 "calc2.y" { yyval = yystack.l_mark[-2] - yystack.l_mark[0]; } break; case 9: #line 51 "calc2.y" { yyval = yystack.l_mark[-2] * yystack.l_mark[0]; } break; case 10: #line 53 "calc2.y" { yyval = yystack.l_mark[-2] / yystack.l_mark[0]; } break; case 11: #line 55 "calc2.y" { yyval = yystack.l_mark[-2] % yystack.l_mark[0]; } break; case 12: #line 57 "calc2.y" { yyval = yystack.l_mark[-2] & yystack.l_mark[0]; } break; case 13: #line 59 "calc2.y" { yyval = yystack.l_mark[-2] | yystack.l_mark[0]; } break; case 14: #line 61 "calc2.y" { yyval = - yystack.l_mark[0]; } break; case 15: #line 63 "calc2.y" { yyval = regs[yystack.l_mark[0]]; } break; case 17: #line 68 "calc2.y" { yyval = yystack.l_mark[0]; (*base) = (yystack.l_mark[0]==0) ? 8 : 10; } break; case 18: #line 70 "calc2.y" { yyval = (*base) * yystack.l_mark[-1] + yystack.l_mark[0]; } break; #line 622 "calc2.tab.c" } yystack.s_mark -= yym; yystate = *yystack.s_mark; yystack.l_mark -= yym; yym = yylhs[yyn]; if (yystate == 0 && yym == 0) { #if YYDEBUG if (yydebug) printf("%sdebug: after reduction, shifting from state 0 to\ state %d\n", YYPREFIX, YYFINAL); #endif yystate = YYFINAL; *++yystack.s_mark = YYFINAL; *++yystack.l_mark = yyval; if (yychar < 0) { if ((yychar = YYLEX) < 0) yychar = 0; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, reading %d (%s)\n", YYPREFIX, YYFINAL, yychar, yys); } #endif } if (yychar == 0) goto yyaccept; goto yyloop; } if ((yyn = yygindex[yym]) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; else yystate = yydgoto[yym]; #if YYDEBUG if (yydebug) printf("%sdebug: after reduction, shifting from state %d \ to state %d\n", YYPREFIX, *yystack.s_mark, yystate); #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack)) { goto yyoverflow; } *++yystack.s_mark = (short) yystate; *++yystack.l_mark = yyval; goto yyloop; yyoverflow: yyerror(regs, base, "yacc stack overflow"); yyabort: yyfreestack(&yystack); return (1); yyaccept: yyfreestack(&yystack); return (0); }
the_stack_data/99816.c
/******************************************************************************* * * Intel Ethernet Controller XL710 Family Linux Driver * Copyright(c) 2013 - 2014 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Contact Information: * e1000-devel Mailing List <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * ******************************************************************************/ #ifdef CONFIG_I40E_DCB #include "i40e.h" #include <net/dcbnl.h> /** * i40e_get_pfc_delay - retrieve PFC Link Delay * @hw: pointer to hardware struct * @delay: holds the PFC Link delay value * * Returns PFC Link Delay from the PRTDCB_GENC.PFCLDA **/ static void i40e_get_pfc_delay(struct i40e_hw *hw, u16 *delay) { u32 val; val = rd32(hw, I40E_PRTDCB_GENC); *delay = (u16)((val & I40E_PRTDCB_GENC_PFCLDA_MASK) >> I40E_PRTDCB_GENC_PFCLDA_SHIFT); } /** * i40e_dcbnl_ieee_getets - retrieve local IEEE ETS configuration * @netdev: the corresponding netdev * @ets: structure to hold the ETS information * * Returns local IEEE ETS configuration **/ static int i40e_dcbnl_ieee_getets(struct net_device *dev, struct ieee_ets *ets) { struct i40e_pf *pf = i40e_netdev_to_pf(dev); struct i40e_dcbx_config *dcbxcfg; struct i40e_hw *hw = &pf->hw; if (!(pf->dcbx_cap & DCB_CAP_DCBX_VER_IEEE)) return -EINVAL; dcbxcfg = &hw->local_dcbx_config; ets->willing = dcbxcfg->etscfg.willing; ets->ets_cap = dcbxcfg->etscfg.maxtcs; ets->cbs = dcbxcfg->etscfg.cbs; memcpy(ets->tc_tx_bw, dcbxcfg->etscfg.tcbwtable, sizeof(ets->tc_tx_bw)); memcpy(ets->tc_rx_bw, dcbxcfg->etscfg.tcbwtable, sizeof(ets->tc_rx_bw)); memcpy(ets->tc_tsa, dcbxcfg->etscfg.tsatable, sizeof(ets->tc_tsa)); memcpy(ets->prio_tc, dcbxcfg->etscfg.prioritytable, sizeof(ets->prio_tc)); memcpy(ets->tc_reco_bw, dcbxcfg->etsrec.tcbwtable, sizeof(ets->tc_reco_bw)); memcpy(ets->tc_reco_tsa, dcbxcfg->etsrec.tsatable, sizeof(ets->tc_reco_tsa)); memcpy(ets->reco_prio_tc, dcbxcfg->etscfg.prioritytable, sizeof(ets->reco_prio_tc)); return 0; } /** * i40e_dcbnl_ieee_getpfc - retrieve local IEEE PFC configuration * @netdev: the corresponding netdev * @ets: structure to hold the PFC information * * Returns local IEEE PFC configuration **/ static int i40e_dcbnl_ieee_getpfc(struct net_device *dev, struct ieee_pfc *pfc) { struct i40e_pf *pf = i40e_netdev_to_pf(dev); struct i40e_dcbx_config *dcbxcfg; struct i40e_hw *hw = &pf->hw; int i; if (!(pf->dcbx_cap & DCB_CAP_DCBX_VER_IEEE)) return -EINVAL; dcbxcfg = &hw->local_dcbx_config; pfc->pfc_cap = dcbxcfg->pfc.pfccap; pfc->pfc_en = dcbxcfg->pfc.pfcenable; pfc->mbc = dcbxcfg->pfc.mbc; i40e_get_pfc_delay(hw, &pfc->delay); /* Get Requests/Indicatiosn */ for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) { pfc->requests[i] = pf->stats.priority_xoff_tx[i]; pfc->indications[i] = pf->stats.priority_xoff_rx[i]; } return 0; } /** * i40e_dcbnl_getdcbx - retrieve current DCBx capability * @netdev: the corresponding netdev * * Returns DCBx capability features **/ static u8 i40e_dcbnl_getdcbx(struct net_device *dev) { struct i40e_pf *pf = i40e_netdev_to_pf(dev); return pf->dcbx_cap; } /** * i40e_dcbnl_get_perm_hw_addr - MAC address used by DCBx * @netdev: the corresponding netdev * * Returns the SAN MAC address used for LLDP exchange **/ static void i40e_dcbnl_get_perm_hw_addr(struct net_device *dev, u8 *perm_addr) { struct i40e_pf *pf = i40e_netdev_to_pf(dev); int i, j; memset(perm_addr, 0xff, MAX_ADDR_LEN); for (i = 0; i < dev->addr_len; i++) perm_addr[i] = pf->hw.mac.perm_addr[i]; for (j = 0; j < dev->addr_len; j++, i++) perm_addr[i] = pf->hw.mac.san_addr[j]; } static const struct dcbnl_rtnl_ops dcbnl_ops = { .ieee_getets = i40e_dcbnl_ieee_getets, .ieee_getpfc = i40e_dcbnl_ieee_getpfc, .getdcbx = i40e_dcbnl_getdcbx, .getpermhwaddr = i40e_dcbnl_get_perm_hw_addr, }; /** * i40e_dcbnl_set_all - set all the apps and ieee data from DCBx config * @vsi: the corresponding vsi * * Set up all the IEEE APPs in the DCBNL App Table and generate event for * other settings **/ void i40e_dcbnl_set_all(struct i40e_vsi *vsi) { struct net_device *dev = vsi->netdev; struct i40e_pf *pf = i40e_netdev_to_pf(dev); struct i40e_dcbx_config *dcbxcfg; struct i40e_hw *hw = &pf->hw; struct dcb_app sapp; u8 prio, tc_map; int i; /* DCB not enabled */ if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) return; /* MFP mode but not an iSCSI PF so return */ if ((pf->flags & I40E_FLAG_MFP_ENABLED) && !(pf->hw.func_caps.iscsi)) return; dcbxcfg = &hw->local_dcbx_config; /* Set up all the App TLVs if DCBx is negotiated */ for (i = 0; i < dcbxcfg->numapps; i++) { prio = dcbxcfg->app[i].priority; tc_map = BIT(dcbxcfg->etscfg.prioritytable[prio]); /* Add APP only if the TC is enabled for this VSI */ if (tc_map & vsi->tc_config.enabled_tc) { sapp.selector = dcbxcfg->app[i].selector; sapp.protocol = dcbxcfg->app[i].protocolid; sapp.priority = prio; dcb_ieee_setapp(dev, &sapp); } } /* Notify user-space of the changes */ dcbnl_ieee_notify(dev, RTM_SETDCB, DCB_CMD_IEEE_SET, 0, 0); } /** * i40e_dcbnl_vsi_del_app - Delete APP for given VSI * @vsi: the corresponding vsi * @app: APP to delete * * Delete given APP from the DCBNL APP table for given * VSI **/ static int i40e_dcbnl_vsi_del_app(struct i40e_vsi *vsi, struct i40e_dcb_app_priority_table *app) { struct net_device *dev = vsi->netdev; struct dcb_app sapp; if (!dev) return -EINVAL; sapp.selector = app->selector; sapp.protocol = app->protocolid; sapp.priority = app->priority; return dcb_ieee_delapp(dev, &sapp); } /** * i40e_dcbnl_del_app - Delete APP on all VSIs * @pf: the corresponding PF * @app: APP to delete * * Delete given APP from all the VSIs for given PF **/ static void i40e_dcbnl_del_app(struct i40e_pf *pf, struct i40e_dcb_app_priority_table *app) { int v, err; for (v = 0; v < pf->num_alloc_vsi; v++) { if (pf->vsi[v] && pf->vsi[v]->netdev) { err = i40e_dcbnl_vsi_del_app(pf->vsi[v], app); if (err) dev_info(&pf->pdev->dev, "%s: Failed deleting app for VSI seid=%d err=%d sel=%d proto=0x%x prio=%d\n", __func__, pf->vsi[v]->seid, err, app->selector, app->protocolid, app->priority); } } } /** * i40e_dcbnl_find_app - Search APP in given DCB config * @cfg: DCBX configuration data * @app: APP to search for * * Find given APP in the DCB configuration **/ static bool i40e_dcbnl_find_app(struct i40e_dcbx_config *cfg, struct i40e_dcb_app_priority_table *app) { int i; for (i = 0; i < cfg->numapps; i++) { if (app->selector == cfg->app[i].selector && app->protocolid == cfg->app[i].protocolid && app->priority == cfg->app[i].priority) return true; } return false; } /** * i40e_dcbnl_flush_apps - Delete all removed APPs * @pf: the corresponding PF * @old_cfg: old DCBX configuration data * @new_cfg: new DCBX configuration data * * Find and delete all APPs that are not present in the passed * DCB configuration **/ void i40e_dcbnl_flush_apps(struct i40e_pf *pf, struct i40e_dcbx_config *old_cfg, struct i40e_dcbx_config *new_cfg) { struct i40e_dcb_app_priority_table app; int i; /* MFP mode but not an iSCSI PF so return */ if ((pf->flags & I40E_FLAG_MFP_ENABLED) && !(pf->hw.func_caps.iscsi)) return; for (i = 0; i < old_cfg->numapps; i++) { app = old_cfg->app[i]; /* The APP is not available anymore delete it */ if (!i40e_dcbnl_find_app(new_cfg, &app)) i40e_dcbnl_del_app(pf, &app); } } /** * i40e_dcbnl_setup - DCBNL setup * @vsi: the corresponding vsi * * Set up DCBNL ops and initial APP TLVs **/ void i40e_dcbnl_setup(struct i40e_vsi *vsi) { struct net_device *dev = vsi->netdev; struct i40e_pf *pf = i40e_netdev_to_pf(dev); /* Not DCB capable */ if (!(pf->flags & I40E_FLAG_DCB_CAPABLE)) return; dev->dcbnl_ops = &dcbnl_ops; /* Set initial IEEE DCB settings */ i40e_dcbnl_set_all(vsi); } #endif /* CONFIG_I40E_DCB */
the_stack_data/97013319.c
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { // create an array of length 10 int *nums = (int *)malloc(10 * sizeof(int)); char c; // initialize every index to be zero for (int i = 0; i < 10; i++) { *(nums + i) = 0; } // read the input and increment the corresponding index if the character is a number while (scanf("%c", &c) == 1) { if (c >= '0' && c <= '9') { (*(nums + (c - '0')))++; } } for (int i = 0; i < 10; i++) { printf("%d ", *(nums + i)); } return 0; }
the_stack_data/11712.c
#include <stdio.h> int main (){ int x,y; printf("Informe Um Valor: "); scanf("%d",&x); printf("Informe Um Valor: "); scanf("%d",&y); if ( x>=0){ if(x==0){ printf("NQ\n"); } else if(x>0){ if(y>0){ printf("I\n"); } else { printf("IV\n"); } } } else if (y==0){ printf("NQ\n"); } else if (y>0){ printf("II\n"); } else { printf("III\n"); } return 0; }
the_stack_data/242331475.c
// Test this without pch. // RUN: %clang_cc1 %s -include %s -verify -fsyntax-only // Test with pch. // RUN: %clang_cc1 %s -emit-pch -o %t // RUN: %clang_cc1 %s -include-pch %t -verify -fsyntax-only #ifndef HEADER #define HEADER #pragma clang diagnostic ignored "-Wtautological-compare" #else void f() { int a = 0; int b = a==a; } #endif
the_stack_data/4642.c
#include <stdio.h> #include <stdlib.h> /*1. Napište funkci, která vezme dva řetězce A a B. Zřetězí je do třetího řetězce C.*/ void slouceni(char a[], char b[], char c[]) { int i=0, j=0; while(a[i] != '\0') { c[i] = a[i]; i++; } while(b[j] != '\0') { c[i] = b[j]; i++; j++; } c[i] = '\0'; } int main() { char a[20], b[20], c[40]; printf("Zadej neco do retezce a: "); scanf("%19s", a); printf("Zadej neco do retezce b: "); scanf("%19s", b); slouceni(a, b, c); puts(c); return 0; }
the_stack_data/72013716.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_str_is_alpha.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpadovan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/08 21:20:57 by dpadovan #+# #+# */ /* Updated: 2021/04/11 13:41:24 by dpadovan ### ########.fr */ /* */ /* ************************************************************************** */ int ft_str_is_alpha(char *str) { int count; count = 0; while (str[count] != '\0') { if ((str[count] < 65 || str[count] > 90) && (str[count] < 97 || str[count] > 122)) { return (0); } count++; } return (1); }
the_stack_data/1263302.c
int x; int main(void){ char x=0; while(x==0){ break; } return 0; }
the_stack_data/193894149.c
#include<stdio.h> #include<stdlib.h> typedef struct b{ /*cor v= vermelho e p = preto*/ int info; char cor; /*cor v= vermelho e p = preto*/ struct b *esq,*dir; }arvoreVP; void aloca(arvoreVP **No , int valor){ arvoreVP *novo; novo = (arvoreVP *)malloc(sizeof(arvoreVP)); novo->info = valor; novo->cor = 'v'; novo->dir = novo->esq = NULL; *No = novo; } struct b* rotacionaesq(arvoreVP *A){ arvoreVP *B = A->dir; A->dir = B->esq; B->esq = A; B->cor = A->cor; A->cor = 'v'; return B; } struct b* rotacionadir(arvoreVP *A){ arvoreVP *B = A->esq; A->esq = B->dir; B->dir = A; B->cor = A->cor; A->cor = 'v'; return B; } char inverte_cor(arvoreVP *No){ if (No != NULL){ if (No->cor == 'p') No->cor = 'v'; else No->cor = 'p'; } } void TrocarCor(arvoreVP *RAIZ){ inverte_cor(RAIZ); inverte_cor(RAIZ->dir); inverte_cor(RAIZ->esq); } char cor(arvoreVP *No){ char c; if (No == NULL) c = 'p'; else c = No->cor; return c; } /*Arvore vermelha e preta caida para esquerda Regra o filho da direita de um No nunca pode ser vermelho casos de implementação: -quando o filho da direita de um No for vermelho e o filho da esquerda for preto ou nulo devemos rotacionar o No para esquerda -quando o filho da esuqerda de um No for vermelho e o neto da esuquerda tambem for vermelho devemos rotacionar o No para esquerda -quando o filho da direita e o da esquerda um No for vermelho devemos trocar cor do No */ struct b* balancear(arvoreVP *No){ //No vermelho é sempre o filho da esquerda if ( cor(No->dir) == 'v'){ No = rotacionaesq(No); //printf("entrou balancear\n"); } //filho da esquerda e neto sao vermelhos if (No->esq != NULL && cor(No->esq) == 'v' && cor(No->esq->esq) == 'v'){ No = rotacionadir(No); } //dois filhos sao vermelhos troca cor if (cor(No->esq) == 'v' && cor(No->dir) == 'v'){ TrocarCor(No); } return No; } void insere(arvoreVP **Raiz ,arvoreVP *No){ if (*Raiz == NULL){ *Raiz = No; //se a raiz for null ela recebe o No }else if (No->info < (*Raiz)->info){ insere(&(*Raiz)->esq,No); }else if (No->info > (*Raiz)->info){ insere(&(*Raiz)->dir,No); } //verifica_balanceamento_VP(Raiz); *Raiz = balancear(*Raiz); } struct b* moveEsqRed(arvoreVP *No){ TrocarCor(No); if (cor(No->dir->esq) == 'v'){ No->dir = rotacionadir(No->dir); No = rotacionaesq(No); TrocarCor(No); } return No; } struct b* moveDirRed(arvoreVP *No){ TrocarCor(No); if (cor(No->esq->esq) == 'v'){ No = rotacionadir(No); TrocarCor(No); } return No; } struct b* remover_menor(arvoreVP *No){ if (No->esq == NULL){ free(No); No = NULL; }else{ if (cor(No->esq) == 'p' && cor(No->esq->esq) == 'p') No = moveEsqRed(No); No->esq = remover_menor(No->esq); No = balancear(No); } return No; } struct b* procura_menor(arvoreVP *Raiz){ if (Raiz->esq != NULL){ Raiz = procura_menor(Raiz->esq); } return Raiz; } struct b* remover(arvoreVP *Raiz, int valor){ if (valor < Raiz->info){ if (cor(Raiz->esq) == 'p' && cor(Raiz->esq->esq) == 'p'){ Raiz = moveEsqRed(Raiz); printf("entoru move esq\n"); } Raiz->esq = remover(Raiz->esq,valor); }else{ if (cor(Raiz->esq) == 'v'){ Raiz = rotacionadir(Raiz); printf("entoru dir\n"); } if (valor == Raiz->info && Raiz->dir == NULL){ free(Raiz); Raiz = NULL; }else{ if (cor(Raiz->dir) == 'p' && cor(Raiz->dir->esq) == 'p'){ Raiz = moveDirRed(Raiz); printf("entoru move\n"); } if (valor == Raiz->info){ arvoreVP *x; x = procura_menor(Raiz->dir); Raiz->info = x->info; Raiz->dir = remover_menor(Raiz->dir); }else{ Raiz->dir = remover(Raiz->dir,valor); } } } if (Raiz != NULL){ Raiz = balancear(Raiz); } return Raiz; } void busca(arvoreVP *Raiz ,int valor, int *flag){ if (Raiz != NULL){ if (valor == Raiz->info){ //verifica se o valor da raiz *flag = 1; // é o valor buscado }else if(valor < Raiz->info){ // se o valor for menor que o valor da raiz raiz busca(Raiz->esq,valor,flag); // faz a chamda recursiva fazendo que a raiz va para esquerda }else{ // se o valor for maior que o valor da raiz raiz busca(Raiz->dir,valor,flag); // faz a chamda recursiva fazendo que a raiz va para esquerda } } } int remover_info(arvoreVP **Raiz, int valor){ int flag = 0; busca(*Raiz,valor,&flag); if (flag == 1){ *Raiz = remover(*Raiz,valor); if ((*Raiz)->cor != 'p') (*Raiz)->cor = 'p'; } return flag; } void inserir_valores(arvoreVP **Raiz){ int n; arvoreVP *No; printf("\ndigite -1 para parar!!\n"); printf("digite um valor: "); scanf("%d",&n); if (n > 0){ aloca(&No,n); insere(Raiz,No); if ((*Raiz)->cor != 'p'){ (*Raiz)->cor = 'p'; } inserir_valores(Raiz); } } void imprimir(arvoreVP *Raiz){ if (Raiz != NULL){ printf("%d %c- ",Raiz->info,Raiz->cor); imprimir(Raiz->esq); //printf("%d ",Raiz->info); imprimir(Raiz->dir); } } int menu(){ //imprime menu int op; printf("\n1- Inserir dados na arvore\n"); printf("2- imprimir arvore \n"); printf("3- remover valor \n"); printf("4- sair \n"); printf("\ndigite opcao: "); scanf("%d",&op); return op; } int main(){ arvoreVP *Raiz = NULL,*aux; int op,n,flag; do{ op = menu(); switch (op){ case 1: inserir_valores(&Raiz); break; case 2: printf("\n"); imprimir(Raiz); printf("\n"); break; case 3: flag = 0; printf("\ndigite um valor: "); scanf("%d",&n); remover_info(&Raiz,n); break; case 4: printf("\nSaindo.....\n"); default: printf("\nopcao invalida!!!\n"); break; } }while(op != 4); return 0; }
the_stack_data/85781.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { while (1) { int ret; ret = access("/etc/xdg/autostart/piwiz.desktop", F_OK); if (ret != 0) break; usleep(500000); } if (fork() == 0) { execv("/usr/local/bin/carbidemotion", argv); } else { #ifdef FULLSCREEN while (1) { int ret; ret = system("wmctrl -r \"Carbide Motion\" -b toggle,fullscreen"); if (ret == 0) break; usleep(500000); } #endif } }
the_stack_data/43609.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; unsigned long local1 ; char copy11 ; char copy12 ; char copy13 ; unsigned short copy14 ; unsigned short copy15 ; { state[0UL] = (input[0UL] + 51238316UL) + 274866410UL; local1 = 0UL; while (local1 < 0UL) { if (state[0UL] < local1) { if (state[0UL] == local1) { copy11 = *((char *)(& state[local1]) + 7); *((char *)(& state[local1]) + 7) = *((char *)(& state[local1]) + 3); *((char *)(& state[local1]) + 3) = copy11; copy11 = *((char *)(& state[local1]) + 6); *((char *)(& state[local1]) + 6) = *((char *)(& state[local1]) + 5); *((char *)(& state[local1]) + 5) = copy11; state[0UL] -= state[local1]; } else { copy12 = *((char *)(& state[0UL]) + 5); *((char *)(& state[0UL]) + 5) = *((char *)(& state[0UL]) + 1); *((char *)(& state[0UL]) + 1) = copy12; copy12 = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 5); *((char *)(& state[0UL]) + 5) = copy12; copy13 = *((char *)(& state[0UL]) + 1); *((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = copy13; } } else { copy14 = *((unsigned short *)(& state[local1]) + 1); *((unsigned short *)(& state[local1]) + 1) = *((unsigned short *)(& state[local1]) + 2); *((unsigned short *)(& state[local1]) + 2) = copy14; copy15 = *((unsigned short *)(& state[0UL]) + 2); *((unsigned short *)(& state[0UL]) + 2) = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = copy15; } local1 += 2UL; } output[0UL] = (state[0UL] + 116928511UL) + 399227303UL; } } int main(int argc , char *argv[] ) { unsigned long input[1] ; unsigned long output[1] ; int randomFuns_i5 ; unsigned long randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242UL) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%lu\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/70449326.c
/* This file was automatically generated by CasADi. The CasADi copyright holders make no ownership claim of its contents. */ #ifdef __cplusplus extern "C" { #endif /* How to prefix internal symbols */ #ifdef CASADI_CODEGEN_PREFIX #define CASADI_NAMESPACE_CONCAT(NS, ID) _CASADI_NAMESPACE_CONCAT(NS, ID) #define _CASADI_NAMESPACE_CONCAT(NS, ID) NS ## ID #define CASADI_PREFIX(ID) CASADI_NAMESPACE_CONCAT(CODEGEN_PREFIX, ID) #else #define CASADI_PREFIX(ID) usv_model_guidance_ca1_expl_vde_forw_ ## ID #endif #include <math.h> #ifndef casadi_real #define casadi_real double #endif #ifndef casadi_int #define casadi_int int #endif /* Add prefix to internal symbols */ #define casadi_copy CASADI_PREFIX(copy) #define casadi_f0 CASADI_PREFIX(f0) #define casadi_project CASADI_PREFIX(project) #define casadi_s0 CASADI_PREFIX(s0) #define casadi_s1 CASADI_PREFIX(s1) #define casadi_s2 CASADI_PREFIX(s2) #define casadi_s3 CASADI_PREFIX(s3) #define casadi_s4 CASADI_PREFIX(s4) #define casadi_s5 CASADI_PREFIX(s5) #define casadi_s6 CASADI_PREFIX(s6) #define casadi_s7 CASADI_PREFIX(s7) #define casadi_sq CASADI_PREFIX(sq) /* Symbol visibility in DLLs */ #ifndef CASADI_SYMBOL_EXPORT #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) #if defined(STATIC_LINKED) #define CASADI_SYMBOL_EXPORT #else #define CASADI_SYMBOL_EXPORT __declspec(dllexport) #endif #elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) #define CASADI_SYMBOL_EXPORT __attribute__ ((visibility ("default"))) #else #define CASADI_SYMBOL_EXPORT #endif #endif void casadi_copy(const casadi_real* x, casadi_int n, casadi_real* y) { casadi_int i; if (y) { if (x) { for (i=0; i<n; ++i) *y++ = *x++; } else { for (i=0; i<n; ++i) *y++ = 0.; } } } casadi_real casadi_sq(casadi_real x) { return x*x;} void casadi_project(const casadi_real* x, const casadi_int* sp_x, casadi_real* y, const casadi_int* sp_y, casadi_real* w) { casadi_int ncol_x, ncol_y, i, el; const casadi_int *colind_x, *row_x, *colind_y, *row_y; ncol_x = sp_x[1]; colind_x = sp_x+2; row_x = sp_x + 2 + ncol_x+1; ncol_y = sp_y[1]; colind_y = sp_y+2; row_y = sp_y + 2 + ncol_y+1; for (i=0; i<ncol_x; ++i) { for (el=colind_y[i]; el<colind_y[i+1]; ++el) w[row_y[el]] = 0; for (el=colind_x[i]; el<colind_x[i+1]; ++el) w[row_x[el]] = x[el]; for (el=colind_y[i]; el<colind_y[i+1]; ++el) y[el] = w[row_y[el]]; } } static const casadi_int casadi_s0[5] = {8, 1, 0, 1, 4}; static const casadi_int casadi_s1[10] = {8, 1, 0, 6, 2, 3, 4, 5, 6, 7}; static const casadi_int casadi_s2[9] = {8, 1, 0, 5, 2, 3, 5, 6, 7}; static const casadi_int casadi_s3[12] = {8, 1, 0, 8, 0, 1, 2, 3, 4, 5, 6, 7}; static const casadi_int casadi_s4[75] = {8, 8, 0, 8, 16, 24, 32, 40, 48, 56, 64, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static const casadi_int casadi_s5[5] = {1, 1, 0, 1, 0}; static const casadi_int casadi_s6[20] = {16, 1, 0, 16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; static const casadi_int casadi_s7[51] = {8, 8, 0, 5, 10, 15, 20, 25, 30, 35, 40, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7, 2, 3, 5, 6, 7}; /* usv_model_guidance_ca1_expl_vde_forw:(i0[8],i1[8x8],i2[8],i3,i4[16])->(o0[8],o1[8x8,40nz],o2[8x1,6nz]) */ static int casadi_f0(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, int mem) { casadi_int i; casadi_real *rr, *ss; const casadi_real *cs; casadi_real w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, *w14=w+22, *w15=w+86, *w16=w+94, *w17=w+102, *w18=w+110, *w19=w+118, *w20=w+126, *w21=w+134, *w22=w+142, w23, w24, w25, w26, w27, w28, w29, w30, w31, w32, w33, w34, w35, *w36=w+163, *w40=w+169, *w41=w+174; /* #0: @0 = 0 */ w0 = 0.; /* #1: output[0][0] = @0 */ if (res[0]) res[0][0] = w0; /* #2: @0 = 0 */ w0 = 0.; /* #3: output[0][1] = @0 */ if (res[0]) res[0][1] = w0; /* #4: @0 = input[0][0] */ w0 = arg[0] ? arg[0][0] : 0; /* #5: @1 = input[0][3] */ w1 = arg[0] ? arg[0][3] : 0; /* #6: @2 = input[0][1] */ w2 = arg[0] ? arg[0][1] : 0; /* #7: @3 = 0.001 */ w3 = 1.0000000000000000e-03; /* #8: @3 = (@3+@0) */ w3 += w0; /* #9: @4 = atan2(@2,@3) */ w4 = atan2(w2,w3); /* #10: @1 = (@1-@4) */ w1 -= w4; /* #11: @4 = sin(@1) */ w4 = sin( w1 ); /* #12: @5 = (@0*@4) */ w5 = (w0*w4); /* #13: @6 = cos(@1) */ w6 = cos( w1 ); /* #14: @7 = (@2*@6) */ w7 = (w2*w6); /* #15: @5 = (@5+@7) */ w5 += w7; /* #16: output[0][2] = @5 */ if (res[0]) res[0][2] = w5; /* #17: @5 = input[0][4] */ w5 = arg[0] ? arg[0][4] : 0; /* #18: @7 = (@5-@1) */ w7 = (w5-w1); /* #19: output[0][3] = @7 */ if (res[0]) res[0][3] = w7; /* #20: @7 = input[3][0] */ w7 = arg[3] ? arg[3][0] : 0; /* #21: output[0][4] = @7 */ if (res[0]) res[0][4] = w7; /* #22: @7 = input[0][7] */ w7 = arg[0] ? arg[0][7] : 0; /* #23: @8 = cos(@7) */ w8 = cos( w7 ); /* #24: @9 = (@0*@8) */ w9 = (w0*w8); /* #25: @10 = sin(@7) */ w10 = sin( w7 ); /* #26: @11 = (@2*@10) */ w11 = (w2*w10); /* #27: @9 = (@9-@11) */ w9 -= w11; /* #28: output[0][5] = @9 */ if (res[0]) res[0][5] = w9; /* #29: @9 = sin(@7) */ w9 = sin( w7 ); /* #30: @11 = (@0*@9) */ w11 = (w0*w9); /* #31: @12 = cos(@7) */ w12 = cos( w7 ); /* #32: @13 = (@2*@12) */ w13 = (w2*w12); /* #33: @11 = (@11+@13) */ w11 += w13; /* #34: output[0][6] = @11 */ if (res[0]) res[0][6] = w11; /* #35: @5 = (@5-@1) */ w5 -= w1; /* #36: output[0][7] = @5 */ if (res[0]) res[0][7] = w5; /* #37: @14 = input[1][0] */ casadi_copy(arg[1], 64, w14); /* #38: {@15, @16, @17, @18, @19, @20, @21, @22} = horzsplit(@14) */ casadi_copy(w14, 8, w15); casadi_copy(w14+8, 8, w16); casadi_copy(w14+16, 8, w17); casadi_copy(w14+24, 8, w18); casadi_copy(w14+32, 8, w19); casadi_copy(w14+40, 8, w20); casadi_copy(w14+48, 8, w21); casadi_copy(w14+56, 8, w22); /* #39: {@5, @11, NULL, @13, @23, NULL, NULL, @24} = vertsplit(@15) */ w5 = w15[0]; w11 = w15[1]; w13 = w15[3]; w23 = w15[4]; w24 = w15[7]; /* #40: @25 = (@4*@5) */ w25 = (w4*w5); /* #41: @26 = cos(@1) */ w26 = cos( w1 ); /* #42: @27 = sq(@2) */ w27 = casadi_sq( w2 ); /* #43: @28 = sq(@3) */ w28 = casadi_sq( w3 ); /* #44: @27 = (@27+@28) */ w27 += w28; /* #45: @28 = (@3/@27) */ w28 = (w3/w27); /* #46: @29 = (@28*@11) */ w29 = (w28*w11); /* #47: @27 = (@2/@27) */ w27 = (w2/w27); /* #48: @30 = (@27*@5) */ w30 = (w27*w5); /* #49: @29 = (@29-@30) */ w29 -= w30; /* #50: @13 = (@13-@29) */ w13 -= w29; /* #51: @29 = (@26*@13) */ w29 = (w26*w13); /* #52: @29 = (@0*@29) */ w29 = (w0*w29); /* #53: @25 = (@25+@29) */ w25 += w29; /* #54: @29 = (@6*@11) */ w29 = (w6*w11); /* #55: @30 = sin(@1) */ w30 = sin( w1 ); /* #56: @31 = (@30*@13) */ w31 = (w30*w13); /* #57: @31 = (@2*@31) */ w31 = (w2*w31); /* #58: @29 = (@29-@31) */ w29 -= w31; /* #59: @25 = (@25+@29) */ w25 += w29; /* #60: output[1][0] = @25 */ if (res[1]) res[1][0] = w25; /* #61: @25 = (@23-@13) */ w25 = (w23-w13); /* #62: output[1][1] = @25 */ if (res[1]) res[1][1] = w25; /* #63: @25 = (@8*@5) */ w25 = (w8*w5); /* #64: @29 = sin(@7) */ w29 = sin( w7 ); /* #65: @31 = (@29*@24) */ w31 = (w29*w24); /* #66: @31 = (@0*@31) */ w31 = (w0*w31); /* #67: @25 = (@25-@31) */ w25 -= w31; /* #68: @31 = (@10*@11) */ w31 = (w10*w11); /* #69: @32 = cos(@7) */ w32 = cos( w7 ); /* #70: @33 = (@32*@24) */ w33 = (w32*w24); /* #71: @33 = (@2*@33) */ w33 = (w2*w33); /* #72: @31 = (@31+@33) */ w31 += w33; /* #73: @25 = (@25-@31) */ w25 -= w31; /* #74: output[1][2] = @25 */ if (res[1]) res[1][2] = w25; /* #75: @5 = (@9*@5) */ w5 = (w9*w5); /* #76: @25 = cos(@7) */ w25 = cos( w7 ); /* #77: @31 = (@25*@24) */ w31 = (w25*w24); /* #78: @31 = (@0*@31) */ w31 = (w0*w31); /* #79: @5 = (@5+@31) */ w5 += w31; /* #80: @11 = (@12*@11) */ w11 = (w12*w11); /* #81: @31 = sin(@7) */ w31 = sin( w7 ); /* #82: @24 = (@31*@24) */ w24 = (w31*w24); /* #83: @24 = (@2*@24) */ w24 = (w2*w24); /* #84: @11 = (@11-@24) */ w11 -= w24; /* #85: @5 = (@5+@11) */ w5 += w11; /* #86: output[1][3] = @5 */ if (res[1]) res[1][3] = w5; /* #87: @23 = (@23-@13) */ w23 -= w13; /* #88: output[1][4] = @23 */ if (res[1]) res[1][4] = w23; /* #89: {@23, @13, NULL, @5, @11, NULL, NULL, @24} = vertsplit(@16) */ w23 = w16[0]; w13 = w16[1]; w5 = w16[3]; w11 = w16[4]; w24 = w16[7]; /* #90: @33 = (@4*@23) */ w33 = (w4*w23); /* #91: @34 = (@28*@13) */ w34 = (w28*w13); /* #92: @35 = (@27*@23) */ w35 = (w27*w23); /* #93: @34 = (@34-@35) */ w34 -= w35; /* #94: @5 = (@5-@34) */ w5 -= w34; /* #95: @34 = (@26*@5) */ w34 = (w26*w5); /* #96: @34 = (@0*@34) */ w34 = (w0*w34); /* #97: @33 = (@33+@34) */ w33 += w34; /* #98: @34 = (@6*@13) */ w34 = (w6*w13); /* #99: @35 = (@30*@5) */ w35 = (w30*w5); /* #100: @35 = (@2*@35) */ w35 = (w2*w35); /* #101: @34 = (@34-@35) */ w34 -= w35; /* #102: @33 = (@33+@34) */ w33 += w34; /* #103: output[1][5] = @33 */ if (res[1]) res[1][5] = w33; /* #104: @33 = (@11-@5) */ w33 = (w11-w5); /* #105: output[1][6] = @33 */ if (res[1]) res[1][6] = w33; /* #106: @33 = (@8*@23) */ w33 = (w8*w23); /* #107: @34 = (@29*@24) */ w34 = (w29*w24); /* #108: @34 = (@0*@34) */ w34 = (w0*w34); /* #109: @33 = (@33-@34) */ w33 -= w34; /* #110: @34 = (@10*@13) */ w34 = (w10*w13); /* #111: @35 = (@32*@24) */ w35 = (w32*w24); /* #112: @35 = (@2*@35) */ w35 = (w2*w35); /* #113: @34 = (@34+@35) */ w34 += w35; /* #114: @33 = (@33-@34) */ w33 -= w34; /* #115: output[1][7] = @33 */ if (res[1]) res[1][7] = w33; /* #116: @23 = (@9*@23) */ w23 = (w9*w23); /* #117: @33 = (@25*@24) */ w33 = (w25*w24); /* #118: @33 = (@0*@33) */ w33 = (w0*w33); /* #119: @23 = (@23+@33) */ w23 += w33; /* #120: @13 = (@12*@13) */ w13 = (w12*w13); /* #121: @24 = (@31*@24) */ w24 = (w31*w24); /* #122: @24 = (@2*@24) */ w24 = (w2*w24); /* #123: @13 = (@13-@24) */ w13 -= w24; /* #124: @23 = (@23+@13) */ w23 += w13; /* #125: output[1][8] = @23 */ if (res[1]) res[1][8] = w23; /* #126: @11 = (@11-@5) */ w11 -= w5; /* #127: output[1][9] = @11 */ if (res[1]) res[1][9] = w11; /* #128: {@11, @5, NULL, @23, @13, NULL, NULL, @24} = vertsplit(@17) */ w11 = w17[0]; w5 = w17[1]; w23 = w17[3]; w13 = w17[4]; w24 = w17[7]; /* #129: @33 = (@4*@11) */ w33 = (w4*w11); /* #130: @34 = (@28*@5) */ w34 = (w28*w5); /* #131: @35 = (@27*@11) */ w35 = (w27*w11); /* #132: @34 = (@34-@35) */ w34 -= w35; /* #133: @23 = (@23-@34) */ w23 -= w34; /* #134: @34 = (@26*@23) */ w34 = (w26*w23); /* #135: @34 = (@0*@34) */ w34 = (w0*w34); /* #136: @33 = (@33+@34) */ w33 += w34; /* #137: @34 = (@6*@5) */ w34 = (w6*w5); /* #138: @35 = (@30*@23) */ w35 = (w30*w23); /* #139: @35 = (@2*@35) */ w35 = (w2*w35); /* #140: @34 = (@34-@35) */ w34 -= w35; /* #141: @33 = (@33+@34) */ w33 += w34; /* #142: output[1][10] = @33 */ if (res[1]) res[1][10] = w33; /* #143: @33 = (@13-@23) */ w33 = (w13-w23); /* #144: output[1][11] = @33 */ if (res[1]) res[1][11] = w33; /* #145: @33 = (@8*@11) */ w33 = (w8*w11); /* #146: @34 = (@29*@24) */ w34 = (w29*w24); /* #147: @34 = (@0*@34) */ w34 = (w0*w34); /* #148: @33 = (@33-@34) */ w33 -= w34; /* #149: @34 = (@10*@5) */ w34 = (w10*w5); /* #150: @35 = (@32*@24) */ w35 = (w32*w24); /* #151: @35 = (@2*@35) */ w35 = (w2*w35); /* #152: @34 = (@34+@35) */ w34 += w35; /* #153: @33 = (@33-@34) */ w33 -= w34; /* #154: output[1][12] = @33 */ if (res[1]) res[1][12] = w33; /* #155: @11 = (@9*@11) */ w11 = (w9*w11); /* #156: @33 = (@25*@24) */ w33 = (w25*w24); /* #157: @33 = (@0*@33) */ w33 = (w0*w33); /* #158: @11 = (@11+@33) */ w11 += w33; /* #159: @5 = (@12*@5) */ w5 = (w12*w5); /* #160: @24 = (@31*@24) */ w24 = (w31*w24); /* #161: @24 = (@2*@24) */ w24 = (w2*w24); /* #162: @5 = (@5-@24) */ w5 -= w24; /* #163: @11 = (@11+@5) */ w11 += w5; /* #164: output[1][13] = @11 */ if (res[1]) res[1][13] = w11; /* #165: @13 = (@13-@23) */ w13 -= w23; /* #166: output[1][14] = @13 */ if (res[1]) res[1][14] = w13; /* #167: {@13, @23, NULL, @11, @5, NULL, NULL, @24} = vertsplit(@18) */ w13 = w18[0]; w23 = w18[1]; w11 = w18[3]; w5 = w18[4]; w24 = w18[7]; /* #168: @33 = (@4*@13) */ w33 = (w4*w13); /* #169: @34 = (@28*@23) */ w34 = (w28*w23); /* #170: @35 = (@27*@13) */ w35 = (w27*w13); /* #171: @34 = (@34-@35) */ w34 -= w35; /* #172: @11 = (@11-@34) */ w11 -= w34; /* #173: @34 = (@26*@11) */ w34 = (w26*w11); /* #174: @34 = (@0*@34) */ w34 = (w0*w34); /* #175: @33 = (@33+@34) */ w33 += w34; /* #176: @34 = (@6*@23) */ w34 = (w6*w23); /* #177: @35 = (@30*@11) */ w35 = (w30*w11); /* #178: @35 = (@2*@35) */ w35 = (w2*w35); /* #179: @34 = (@34-@35) */ w34 -= w35; /* #180: @33 = (@33+@34) */ w33 += w34; /* #181: output[1][15] = @33 */ if (res[1]) res[1][15] = w33; /* #182: @33 = (@5-@11) */ w33 = (w5-w11); /* #183: output[1][16] = @33 */ if (res[1]) res[1][16] = w33; /* #184: @33 = (@8*@13) */ w33 = (w8*w13); /* #185: @34 = (@29*@24) */ w34 = (w29*w24); /* #186: @34 = (@0*@34) */ w34 = (w0*w34); /* #187: @33 = (@33-@34) */ w33 -= w34; /* #188: @34 = (@10*@23) */ w34 = (w10*w23); /* #189: @35 = (@32*@24) */ w35 = (w32*w24); /* #190: @35 = (@2*@35) */ w35 = (w2*w35); /* #191: @34 = (@34+@35) */ w34 += w35; /* #192: @33 = (@33-@34) */ w33 -= w34; /* #193: output[1][17] = @33 */ if (res[1]) res[1][17] = w33; /* #194: @13 = (@9*@13) */ w13 = (w9*w13); /* #195: @33 = (@25*@24) */ w33 = (w25*w24); /* #196: @33 = (@0*@33) */ w33 = (w0*w33); /* #197: @13 = (@13+@33) */ w13 += w33; /* #198: @23 = (@12*@23) */ w23 = (w12*w23); /* #199: @24 = (@31*@24) */ w24 = (w31*w24); /* #200: @24 = (@2*@24) */ w24 = (w2*w24); /* #201: @23 = (@23-@24) */ w23 -= w24; /* #202: @13 = (@13+@23) */ w13 += w23; /* #203: output[1][18] = @13 */ if (res[1]) res[1][18] = w13; /* #204: @5 = (@5-@11) */ w5 -= w11; /* #205: output[1][19] = @5 */ if (res[1]) res[1][19] = w5; /* #206: {@5, @11, NULL, @13, @23, NULL, NULL, @24} = vertsplit(@19) */ w5 = w19[0]; w11 = w19[1]; w13 = w19[3]; w23 = w19[4]; w24 = w19[7]; /* #207: @33 = (@4*@5) */ w33 = (w4*w5); /* #208: @34 = (@28*@11) */ w34 = (w28*w11); /* #209: @35 = (@27*@5) */ w35 = (w27*w5); /* #210: @34 = (@34-@35) */ w34 -= w35; /* #211: @13 = (@13-@34) */ w13 -= w34; /* #212: @34 = (@26*@13) */ w34 = (w26*w13); /* #213: @34 = (@0*@34) */ w34 = (w0*w34); /* #214: @33 = (@33+@34) */ w33 += w34; /* #215: @34 = (@6*@11) */ w34 = (w6*w11); /* #216: @35 = (@30*@13) */ w35 = (w30*w13); /* #217: @35 = (@2*@35) */ w35 = (w2*w35); /* #218: @34 = (@34-@35) */ w34 -= w35; /* #219: @33 = (@33+@34) */ w33 += w34; /* #220: output[1][20] = @33 */ if (res[1]) res[1][20] = w33; /* #221: @33 = (@23-@13) */ w33 = (w23-w13); /* #222: output[1][21] = @33 */ if (res[1]) res[1][21] = w33; /* #223: @33 = (@8*@5) */ w33 = (w8*w5); /* #224: @34 = (@29*@24) */ w34 = (w29*w24); /* #225: @34 = (@0*@34) */ w34 = (w0*w34); /* #226: @33 = (@33-@34) */ w33 -= w34; /* #227: @34 = (@10*@11) */ w34 = (w10*w11); /* #228: @35 = (@32*@24) */ w35 = (w32*w24); /* #229: @35 = (@2*@35) */ w35 = (w2*w35); /* #230: @34 = (@34+@35) */ w34 += w35; /* #231: @33 = (@33-@34) */ w33 -= w34; /* #232: output[1][22] = @33 */ if (res[1]) res[1][22] = w33; /* #233: @5 = (@9*@5) */ w5 = (w9*w5); /* #234: @33 = (@25*@24) */ w33 = (w25*w24); /* #235: @33 = (@0*@33) */ w33 = (w0*w33); /* #236: @5 = (@5+@33) */ w5 += w33; /* #237: @11 = (@12*@11) */ w11 = (w12*w11); /* #238: @24 = (@31*@24) */ w24 = (w31*w24); /* #239: @24 = (@2*@24) */ w24 = (w2*w24); /* #240: @11 = (@11-@24) */ w11 -= w24; /* #241: @5 = (@5+@11) */ w5 += w11; /* #242: output[1][23] = @5 */ if (res[1]) res[1][23] = w5; /* #243: @23 = (@23-@13) */ w23 -= w13; /* #244: output[1][24] = @23 */ if (res[1]) res[1][24] = w23; /* #245: {@23, @13, NULL, @5, @11, NULL, NULL, @24} = vertsplit(@20) */ w23 = w20[0]; w13 = w20[1]; w5 = w20[3]; w11 = w20[4]; w24 = w20[7]; /* #246: @33 = (@4*@23) */ w33 = (w4*w23); /* #247: @34 = (@28*@13) */ w34 = (w28*w13); /* #248: @35 = (@27*@23) */ w35 = (w27*w23); /* #249: @34 = (@34-@35) */ w34 -= w35; /* #250: @5 = (@5-@34) */ w5 -= w34; /* #251: @34 = (@26*@5) */ w34 = (w26*w5); /* #252: @34 = (@0*@34) */ w34 = (w0*w34); /* #253: @33 = (@33+@34) */ w33 += w34; /* #254: @34 = (@6*@13) */ w34 = (w6*w13); /* #255: @35 = (@30*@5) */ w35 = (w30*w5); /* #256: @35 = (@2*@35) */ w35 = (w2*w35); /* #257: @34 = (@34-@35) */ w34 -= w35; /* #258: @33 = (@33+@34) */ w33 += w34; /* #259: output[1][25] = @33 */ if (res[1]) res[1][25] = w33; /* #260: @33 = (@11-@5) */ w33 = (w11-w5); /* #261: output[1][26] = @33 */ if (res[1]) res[1][26] = w33; /* #262: @33 = (@8*@23) */ w33 = (w8*w23); /* #263: @34 = (@29*@24) */ w34 = (w29*w24); /* #264: @34 = (@0*@34) */ w34 = (w0*w34); /* #265: @33 = (@33-@34) */ w33 -= w34; /* #266: @34 = (@10*@13) */ w34 = (w10*w13); /* #267: @35 = (@32*@24) */ w35 = (w32*w24); /* #268: @35 = (@2*@35) */ w35 = (w2*w35); /* #269: @34 = (@34+@35) */ w34 += w35; /* #270: @33 = (@33-@34) */ w33 -= w34; /* #271: output[1][27] = @33 */ if (res[1]) res[1][27] = w33; /* #272: @23 = (@9*@23) */ w23 = (w9*w23); /* #273: @33 = (@25*@24) */ w33 = (w25*w24); /* #274: @33 = (@0*@33) */ w33 = (w0*w33); /* #275: @23 = (@23+@33) */ w23 += w33; /* #276: @13 = (@12*@13) */ w13 = (w12*w13); /* #277: @24 = (@31*@24) */ w24 = (w31*w24); /* #278: @24 = (@2*@24) */ w24 = (w2*w24); /* #279: @13 = (@13-@24) */ w13 -= w24; /* #280: @23 = (@23+@13) */ w23 += w13; /* #281: output[1][28] = @23 */ if (res[1]) res[1][28] = w23; /* #282: @11 = (@11-@5) */ w11 -= w5; /* #283: output[1][29] = @11 */ if (res[1]) res[1][29] = w11; /* #284: {@11, @5, NULL, @23, @13, NULL, NULL, @24} = vertsplit(@21) */ w11 = w21[0]; w5 = w21[1]; w23 = w21[3]; w13 = w21[4]; w24 = w21[7]; /* #285: @33 = (@4*@11) */ w33 = (w4*w11); /* #286: @34 = (@28*@5) */ w34 = (w28*w5); /* #287: @35 = (@27*@11) */ w35 = (w27*w11); /* #288: @34 = (@34-@35) */ w34 -= w35; /* #289: @23 = (@23-@34) */ w23 -= w34; /* #290: @34 = (@26*@23) */ w34 = (w26*w23); /* #291: @34 = (@0*@34) */ w34 = (w0*w34); /* #292: @33 = (@33+@34) */ w33 += w34; /* #293: @34 = (@6*@5) */ w34 = (w6*w5); /* #294: @35 = (@30*@23) */ w35 = (w30*w23); /* #295: @35 = (@2*@35) */ w35 = (w2*w35); /* #296: @34 = (@34-@35) */ w34 -= w35; /* #297: @33 = (@33+@34) */ w33 += w34; /* #298: output[1][30] = @33 */ if (res[1]) res[1][30] = w33; /* #299: @33 = (@13-@23) */ w33 = (w13-w23); /* #300: output[1][31] = @33 */ if (res[1]) res[1][31] = w33; /* #301: @33 = (@8*@11) */ w33 = (w8*w11); /* #302: @34 = (@29*@24) */ w34 = (w29*w24); /* #303: @34 = (@0*@34) */ w34 = (w0*w34); /* #304: @33 = (@33-@34) */ w33 -= w34; /* #305: @34 = (@10*@5) */ w34 = (w10*w5); /* #306: @35 = (@32*@24) */ w35 = (w32*w24); /* #307: @35 = (@2*@35) */ w35 = (w2*w35); /* #308: @34 = (@34+@35) */ w34 += w35; /* #309: @33 = (@33-@34) */ w33 -= w34; /* #310: output[1][32] = @33 */ if (res[1]) res[1][32] = w33; /* #311: @11 = (@9*@11) */ w11 = (w9*w11); /* #312: @33 = (@25*@24) */ w33 = (w25*w24); /* #313: @33 = (@0*@33) */ w33 = (w0*w33); /* #314: @11 = (@11+@33) */ w11 += w33; /* #315: @5 = (@12*@5) */ w5 = (w12*w5); /* #316: @24 = (@31*@24) */ w24 = (w31*w24); /* #317: @24 = (@2*@24) */ w24 = (w2*w24); /* #318: @5 = (@5-@24) */ w5 -= w24; /* #319: @11 = (@11+@5) */ w11 += w5; /* #320: output[1][33] = @11 */ if (res[1]) res[1][33] = w11; /* #321: @13 = (@13-@23) */ w13 -= w23; /* #322: output[1][34] = @13 */ if (res[1]) res[1][34] = w13; /* #323: {@13, @23, NULL, @11, @5, NULL, NULL, @24} = vertsplit(@22) */ w13 = w22[0]; w23 = w22[1]; w11 = w22[3]; w5 = w22[4]; w24 = w22[7]; /* #324: @33 = (@4*@13) */ w33 = (w4*w13); /* #325: @28 = (@28*@23) */ w28 *= w23; /* #326: @27 = (@27*@13) */ w27 *= w13; /* #327: @28 = (@28-@27) */ w28 -= w27; /* #328: @11 = (@11-@28) */ w11 -= w28; /* #329: @26 = (@26*@11) */ w26 *= w11; /* #330: @26 = (@0*@26) */ w26 = (w0*w26); /* #331: @33 = (@33+@26) */ w33 += w26; /* #332: @26 = (@6*@23) */ w26 = (w6*w23); /* #333: @30 = (@30*@11) */ w30 *= w11; /* #334: @30 = (@2*@30) */ w30 = (w2*w30); /* #335: @26 = (@26-@30) */ w26 -= w30; /* #336: @33 = (@33+@26) */ w33 += w26; /* #337: output[1][35] = @33 */ if (res[1]) res[1][35] = w33; /* #338: @33 = (@5-@11) */ w33 = (w5-w11); /* #339: output[1][36] = @33 */ if (res[1]) res[1][36] = w33; /* #340: @33 = (@8*@13) */ w33 = (w8*w13); /* #341: @29 = (@29*@24) */ w29 *= w24; /* #342: @29 = (@0*@29) */ w29 = (w0*w29); /* #343: @33 = (@33-@29) */ w33 -= w29; /* #344: @29 = (@10*@23) */ w29 = (w10*w23); /* #345: @32 = (@32*@24) */ w32 *= w24; /* #346: @32 = (@2*@32) */ w32 = (w2*w32); /* #347: @29 = (@29+@32) */ w29 += w32; /* #348: @33 = (@33-@29) */ w33 -= w29; /* #349: output[1][37] = @33 */ if (res[1]) res[1][37] = w33; /* #350: @13 = (@9*@13) */ w13 = (w9*w13); /* #351: @25 = (@25*@24) */ w25 *= w24; /* #352: @25 = (@0*@25) */ w25 = (w0*w25); /* #353: @13 = (@13+@25) */ w13 += w25; /* #354: @23 = (@12*@23) */ w23 = (w12*w23); /* #355: @31 = (@31*@24) */ w31 *= w24; /* #356: @31 = (@2*@31) */ w31 = (w2*w31); /* #357: @23 = (@23-@31) */ w23 -= w31; /* #358: @13 = (@13+@23) */ w13 += w23; /* #359: output[1][38] = @13 */ if (res[1]) res[1][38] = w13; /* #360: @5 = (@5-@11) */ w5 -= w11; /* #361: output[1][39] = @5 */ if (res[1]) res[1][39] = w5; /* #362: @5 = zeros(1x8,1nz) */ w5 = 0.; /* #363: @11 = 1 */ w11 = 1.; /* #364: (@5[0] = @11) */ for (rr=(&w5)+0, ss=(&w11); rr!=(&w5)+1; rr+=1) *rr = *ss++; /* #365: @5 = @5' */ /* #366: @36 = project(@5) */ casadi_project((&w5), casadi_s0, w36, casadi_s1, w); /* #367: @37 = 00 */ /* #368: @38 = 00 */ /* #369: @22 = input[2][0] */ casadi_copy(arg[2], 8, w22); /* #370: {@5, @11, NULL, @13, @23, NULL, NULL, @31} = vertsplit(@22) */ w5 = w22[0]; w11 = w22[1]; w13 = w22[3]; w23 = w22[4]; w31 = w22[7]; /* #371: @4 = (@4*@5) */ w4 *= w5; /* #372: @24 = cos(@1) */ w24 = cos( w1 ); /* #373: @25 = sq(@2) */ w25 = casadi_sq( w2 ); /* #374: @33 = sq(@3) */ w33 = casadi_sq( w3 ); /* #375: @25 = (@25+@33) */ w25 += w33; /* #376: @3 = (@3/@25) */ w3 /= w25; /* #377: @3 = (@3*@11) */ w3 *= w11; /* #378: @25 = (@2/@25) */ w25 = (w2/w25); /* #379: @25 = (@25*@5) */ w25 *= w5; /* #380: @3 = (@3-@25) */ w3 -= w25; /* #381: @13 = (@13-@3) */ w13 -= w3; /* #382: @24 = (@24*@13) */ w24 *= w13; /* #383: @24 = (@0*@24) */ w24 = (w0*w24); /* #384: @4 = (@4+@24) */ w4 += w24; /* #385: @6 = (@6*@11) */ w6 *= w11; /* #386: @1 = sin(@1) */ w1 = sin( w1 ); /* #387: @1 = (@1*@13) */ w1 *= w13; /* #388: @1 = (@2*@1) */ w1 = (w2*w1); /* #389: @6 = (@6-@1) */ w6 -= w1; /* #390: @4 = (@4+@6) */ w4 += w6; /* #391: @6 = (@23-@13) */ w6 = (w23-w13); /* #392: @39 = 00 */ /* #393: @8 = (@8*@5) */ w8 *= w5; /* #394: @1 = sin(@7) */ w1 = sin( w7 ); /* #395: @1 = (@1*@31) */ w1 *= w31; /* #396: @1 = (@0*@1) */ w1 = (w0*w1); /* #397: @8 = (@8-@1) */ w8 -= w1; /* #398: @10 = (@10*@11) */ w10 *= w11; /* #399: @1 = cos(@7) */ w1 = cos( w7 ); /* #400: @1 = (@1*@31) */ w1 *= w31; /* #401: @1 = (@2*@1) */ w1 = (w2*w1); /* #402: @10 = (@10+@1) */ w10 += w1; /* #403: @8 = (@8-@10) */ w8 -= w10; /* #404: @9 = (@9*@5) */ w9 *= w5; /* #405: @5 = cos(@7) */ w5 = cos( w7 ); /* #406: @5 = (@5*@31) */ w5 *= w31; /* #407: @0 = (@0*@5) */ w0 *= w5; /* #408: @9 = (@9+@0) */ w9 += w0; /* #409: @12 = (@12*@11) */ w12 *= w11; /* #410: @7 = sin(@7) */ w7 = sin( w7 ); /* #411: @7 = (@7*@31) */ w7 *= w31; /* #412: @2 = (@2*@7) */ w2 *= w7; /* #413: @12 = (@12-@2) */ w12 -= w2; /* #414: @9 = (@9+@12) */ w9 += w12; /* #415: @23 = (@23-@13) */ w23 -= w13; /* #416: @40 = vertcat(@37, @38, @4, @6, @39, @8, @9, @23) */ rr=w40; *rr++ = w4; *rr++ = w6; *rr++ = w8; *rr++ = w9; *rr++ = w23; /* #417: @41 = project(@40) */ casadi_project(w40, casadi_s2, w41, casadi_s1, w); /* #418: @36 = (@36+@41) */ for (i=0, rr=w36, cs=w41; i<6; ++i) (*rr++) += (*cs++); /* #419: output[2][0] = @36 */ casadi_copy(w36, 6, res[2]); return 0; } CASADI_SYMBOL_EXPORT int usv_model_guidance_ca1_expl_vde_forw(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, int mem){ return casadi_f0(arg, res, iw, w, mem); } CASADI_SYMBOL_EXPORT int usv_model_guidance_ca1_expl_vde_forw_alloc_mem(void) { return 0; } CASADI_SYMBOL_EXPORT int usv_model_guidance_ca1_expl_vde_forw_init_mem(int mem) { return 0; } CASADI_SYMBOL_EXPORT void usv_model_guidance_ca1_expl_vde_forw_free_mem(int mem) { } CASADI_SYMBOL_EXPORT int usv_model_guidance_ca1_expl_vde_forw_checkout(void) { return 0; } CASADI_SYMBOL_EXPORT void usv_model_guidance_ca1_expl_vde_forw_release(int mem) { } CASADI_SYMBOL_EXPORT void usv_model_guidance_ca1_expl_vde_forw_incref(void) { } CASADI_SYMBOL_EXPORT void usv_model_guidance_ca1_expl_vde_forw_decref(void) { } CASADI_SYMBOL_EXPORT casadi_int usv_model_guidance_ca1_expl_vde_forw_n_in(void) { return 5;} CASADI_SYMBOL_EXPORT casadi_int usv_model_guidance_ca1_expl_vde_forw_n_out(void) { return 3;} CASADI_SYMBOL_EXPORT casadi_real usv_model_guidance_ca1_expl_vde_forw_default_in(casadi_int i){ switch (i) { default: return 0; } } CASADI_SYMBOL_EXPORT const char* usv_model_guidance_ca1_expl_vde_forw_name_in(casadi_int i){ switch (i) { case 0: return "i0"; case 1: return "i1"; case 2: return "i2"; case 3: return "i3"; case 4: return "i4"; default: return 0; } } CASADI_SYMBOL_EXPORT const char* usv_model_guidance_ca1_expl_vde_forw_name_out(casadi_int i){ switch (i) { case 0: return "o0"; case 1: return "o1"; case 2: return "o2"; default: return 0; } } CASADI_SYMBOL_EXPORT const casadi_int* usv_model_guidance_ca1_expl_vde_forw_sparsity_in(casadi_int i) { switch (i) { case 0: return casadi_s3; case 1: return casadi_s4; case 2: return casadi_s3; case 3: return casadi_s5; case 4: return casadi_s6; default: return 0; } } CASADI_SYMBOL_EXPORT const casadi_int* usv_model_guidance_ca1_expl_vde_forw_sparsity_out(casadi_int i) { switch (i) { case 0: return casadi_s3; case 1: return casadi_s7; case 2: return casadi_s1; default: return 0; } } CASADI_SYMBOL_EXPORT int usv_model_guidance_ca1_expl_vde_forw_work(casadi_int *sz_arg, casadi_int* sz_res, casadi_int *sz_iw, casadi_int *sz_w) { if (sz_arg) *sz_arg = 13; if (sz_res) *sz_res = 11; if (sz_iw) *sz_iw = 0; if (sz_w) *sz_w = 180; return 0; } #ifdef __cplusplus } /* extern "C" */ #endif
the_stack_data/57949621.c
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdarg.h> /*--------------------------------------------------------------------------*/ /* */ /* OPTIC FLOW */ /* */ /* (Copyright by Joachim Weickert, 8/2014) */ /* */ /*--------------------------------------------------------------------------*/ /* features: - explicit scheme - Charbonnier diffusivity */ /*--------------------------------------------------------------------------*/ void alloc_matrix (float ***matrix, /* matrix */ long n1, /* size in direction 1 */ long n2) /* size in direction 2 */ /* allocates memory for matrix of size n1 * n2 */ { long i; *matrix = (float **) malloc (n1 * sizeof(float *)); if (*matrix == NULL) { printf("alloc_matrix: not enough memory available\n"); exit(1); } for (i=0; i<n1; i++) { (*matrix)[i] = (float *) malloc (n2 * sizeof(float)); if ((*matrix)[i] == NULL) { printf("alloc_matrix: not enough memory available\n"); exit(1); } } return; } /*--------------------------------------------------------------------------*/ void alloc_cubix (float ****cubix, /* cubix */ long n1, /* size in direction 1 */ long n2, /* size in direction 2 */ long n3) /* size in direction 3 */ /* allocates memory for cubix of size n1 * n2 * n3 */ { long i, j; *cubix = (float ***) malloc (n1 * sizeof(float **)); if (*cubix == NULL) { printf("alloc_cubix: not enough memory available\n"); exit(1); } for (i=0; i<n1; i++) { (*cubix)[i] = (float **) malloc (n2 * sizeof(float *)); if ((*cubix)[i] == NULL) { printf("alloc_cubix: not enough memory available\n"); exit(1); } for (j=0; j<n2; j++) { (*cubix)[i][j] = (float *) malloc (n3 * sizeof(float)); if ((*cubix)[i][j] == NULL) { printf("alloc_cubix: not enough memory available\n"); exit(1); } } } return; } /*--------------------------------------------------------------------------*/ void disalloc_matrix (float **matrix, /* matrix */ long n1, /* size in direction 1 */ long n2) /* size in direction 2 */ /* disallocates memory for matrix of size n1 * n2 */ { long i; for (i=0; i<n1; i++) free(matrix[i]); free(matrix); return; } /*----------------------------------------------------------------------------*/ void disalloc_cubix (float ***cubix, /* cubix */ long n1, /* size in direction 1 */ long n2, /* size in direction 2 */ long n3) /* size in direction 3 */ /* disallocates memory for cubix of size n1 * n2 * n3 */ { long i, j; for (i=0; i<n1; i++) for (j=0; j<n2; j++) free(cubix[i][j]); for (i=0; i<n1; i++) free(cubix[i]); free(cubix); return; } /*--------------------------------------------------------------------------*/ void read_string (char *v) /* string to be read */ /* reads a long value v */ { fgets (v, 80, stdin); if (v[strlen(v)-1] == '\n') v[strlen(v)-1] = 0; return; } /*--------------------------------------------------------------------------*/ void read_long (long *v) /* value to be read */ /* reads a long value v */ { char row[80]; /* string for reading data */ fgets (row, 80, stdin); if (row[strlen(row)-1] == '\n') row[strlen(row)-1] = 0; sscanf(row, "%ld", &*v); return; } /*--------------------------------------------------------------------------*/ void read_float (float *v) /* value to be read */ /* reads a float value v */ { char row[80]; /* string for reading data */ fgets (row, 80, stdin); if (row[strlen(row)-1] == '\n') row[strlen(row)-1] = 0; sscanf(row, "%f", &*v); return; } /*--------------------------------------------------------------------------*/ void read_pgm_and_allocate_memory (const char *file_name, /* name of pgm file */ long *nx, /* image size in x direction, output */ long *ny, /* image size in y direction, output */ float ***u) /* image, output */ /* reads a greyscale image that has been encoded in pgm format P5; allocates memory for the image u; adds boundary layers of size 1 such that - the relevant image pixels in x direction use the indices 1,...,nx - the relevant image pixels in y direction use the indices 1,...,ny */ { FILE *inimage; /* input file */ char row[80]; /* for reading data */ long i, j; /* loop variables */ /* open file */ inimage = fopen (file_name, "rb"); if (NULL == inimage) { printf ("could not open file '%s' for reading, aborting.\n", file_name); exit (1); } /* read header */ fgets (row, 80, inimage); /* skip format definition */ fgets (row, 80, inimage); while (row[0]=='#') /* skip comments */ fgets (row, 80, inimage); sscanf (row, "%ld %ld", nx, ny); /* read image size */ fgets (row, 80, inimage); /* read maximum grey value */ /* allocate memory */ alloc_matrix (u, (*nx)+2, (*ny)+2); /* read image data row by row */ for (j=1; j<=(*ny); j++) for (i=1; i<=(*nx); i++) (*u)[i][j] = (float) getc(inimage); /* close file */ fclose(inimage); return; } /* read_pgm_and_allocate_memory */ /*----------------------------------------------------------------------------*/ float maxf(float a,float b) { return a>b ? a : b; } /*---------------------------------------------------------------------------*/ float minf(float a,float b) { return a<b ? a : b; } /*---------------------------------------------------------------------------*/ int maxi(int a,int b) { return (a>b) ? a : b; } /*---------------------------------------------------------------------------*/ int mini(int a,int b) { return (a<b) ? a : b; } /*---------------------------------------------------------------------------*/ int clamped (int min, int val, int max) { assert(min<=max); return mini(maxi(min,val),max); } /*----------------------------------------------------------------------------*/ int byte_range(int a) /* restricts number to unsigned char range */ { return clamped(0,a,255); } /*----------------------------------------------------------------------------*/ void vector_to_RGB (float x, /* x-component */ float y, /* y-component */ int *R, /* red component */ int *G, /* green component */ int *B) /* blue component */ /* Computes the color representation of a vector. */ { float Pi; /* pi */ float amp; /* amplitude (magnitude) */ float phi; /* phase (angle) */ float alpha, beta; /* weights for linear interpolation */ /* set pi */ Pi = 2.0 * acos(0.0); /* determine amplitude and phase (cut amp at 1) */ amp = sqrt (x * x + y * y); if (amp > 1) amp = 1; if (x == 0.0) if (y >= 0.0) phi = 0.5 * Pi; else phi = 1.5 * Pi; else if (x > 0.0) if (y >= 0.0) phi = atan (y/x); else phi = 2.0 * Pi + atan (y/x); else phi = Pi + atan (y/x); phi = phi / 2.0; // interpolation between red (0) and blue (0.25 * Pi) if ((phi >= 0.0) && (phi < 0.125 * Pi)) { beta = phi / (0.125 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); *G = (int)floor(amp * (alpha * 0.0 + beta * 0.0)); *B = (int)floor(amp * (alpha * 0.0 + beta * 255.0)); } if ((phi >= 0.125 * Pi) && (phi < 0.25 * Pi)) { beta = (phi-0.125 * Pi) / (0.125 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 255.0 + beta * 64.0)); *G = (int)floor(amp * (alpha * 0.0 + beta * 64.0)); *B = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); } // interpolation between blue (0.25 * Pi) and green (0.5 * Pi) if ((phi >= 0.25 * Pi) && (phi < 0.375 * Pi)) { beta = (phi - 0.25 * Pi) / (0.125 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 64.0 + beta * 0.0)); *G = (int)floor(amp * (alpha * 64.0 + beta * 255.0)); *B = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); } if ((phi >= 0.375 * Pi) && (phi < 0.5 * Pi)) { beta = (phi - 0.375 * Pi) / (0.125 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 0.0 + beta * 0.0)); *G = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); *B = (int)floor(amp * (alpha * 255.0 + beta * 0.0)); } // interpolation between green (0.5 * Pi) and yellow (0.75 * Pi) if ((phi >= 0.5 * Pi) && (phi < 0.75 * Pi)) { beta = (phi - 0.5 * Pi) / (0.25 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 0.0 + beta * 255.0)); *G = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); *B = (int)floor(amp * (alpha * 0.0 + beta * 0.0)); } // interpolation between yellow (0.75 * Pi) and red (Pi) if ((phi >= 0.75 * Pi) && (phi <= Pi)) { beta = (phi - 0.75 * Pi) / (0.25 * Pi); alpha = 1.0 - beta; *R = (int)floor(amp * (alpha * 255.0 + beta * 255.0)); *G = (int)floor(amp * (alpha * 255.0 + beta * 0.0)); *B = (int)floor(amp * (alpha * 0.0 + beta * 0.0)); } /* check RGB range */ *R = byte_range(*R); *G = byte_range(*G); *B = byte_range(*B); return; } /* vector_to_RGB */ /*----------------------------------------------------------------------------*/ void flow_to_color (float **u, /* flow field, first channel (input) */ float **v, /* flow field, second channel (input) */ float ***color_img, /* color representation (output) */ float max_disp, /* maximal disparity (set to -1 if not used) */ int nx, /* size in x direction */ int ny) /* size in y direction */ /* Computes a color representation of a flow field. */ { int i,j; int R,G,B; float maximum_length = 0; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) maximum_length = maxf(maximum_length, u[i][j] * u[i][j] + v[i][j] * v[i][j]); if(max_disp==-1.0f) maximum_length = 1.0f / sqrt(maximum_length); else maximum_length = 1.0f / max_disp; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { if(u[i][j]!=100.0f && v[i][j]!=100.0f) vector_to_RGB(maximum_length*u[i][j], maximum_length*v[i][j],&R,&G,&B); else R=G=B=128.0f; color_img[i][j][0]=(float)R; color_img[i][j][1]=(float)G; color_img[i][j][2]=(float)B; } return; } /* flow_to_color */ /*--------------------------------------------------------------------------*/ void comment_line (char* comment, /* comment string (output) */ char* lineformat, /* format string for comment line */ ...) /* optional arguments */ /* Add a line to the comment string comment. The string line can contain plain text and format characters that are compatible with sprintf. Example call: print_comment_line(comment,"Text %f %d",float_var,int_var); If no line break is supplied at the end of the input string, it is added automatically. */ { char line[80]; va_list arguments; /* get list of optional function arguments */ va_start(arguments,lineformat); /* convert format string and arguments to plain text line string */ vsprintf(line,lineformat,arguments); /* add line to total commentary string */ strncat(comment,line,80); /* add line break if input string does not end with one */ if (line[strlen(line)-1] != '\n') sprintf(comment,"%s\n",comment); /* close argument list */ va_end(arguments); return; } /* comment_line */ /*----------------------------------------------------------------------------*/ void write_ppm (float ***u, /* colour image, unchanged */ int nx, /* size in x direction */ int ny, /* size in y direction */ char *file_name, /* name of ppm file */ char *comments) /* comment string (set 0 for no comments) */ /* writes an image into a pgm P5 (greyscale) or ppm P6 (colour) file */ { FILE *outimage; /* output file */ int i, j, m; /* loop variables */ float aux; /* auxiliary variable */ unsigned char byte; /* for data conversion */ /* open file */ outimage = fopen (file_name, "wb"); if (NULL == outimage) { printf("Could not open file '%s' for writing, aborting\n", file_name); exit(1); } fprintf (outimage, "P6\n"); /* colour format */ if (comments != 0) fprintf (outimage, comments); /* comments */ fprintf (outimage, "%d %d\n", nx, ny); /* image size */ fprintf (outimage, "255\n"); /* maximal value */ /* write image data */ for (j = 1; j <= ny; j++) for (i = 1; i <= nx; i++) for (m = 0; m < 3; m++) { aux = u[i][j][m] + 0.499999; /* for correct rounding */ if (aux < 0.0) byte = (unsigned char)(0.0); else if (aux > 255.0) byte = (unsigned char)(255.0); else byte = (unsigned char)(aux); fwrite (&byte, sizeof(unsigned char), 1, outimage); } /* close file */ fclose (outimage); return; } /* write_ppm */ /*--------------------------------------------------------------------------*/ void dummies (float **u, /* image matrix */ long nx, /* size in x direction */ long ny) /* size in y direction */ /* creates dummy boundaries by mirroring */ { long i, j; /* loop variables */ for (i=1; i<=nx; i++) { u[i][0] = u[i][1]; u[i][ny+1] = u[i][ny]; } for (j=0; j<=ny+1; j++) { u[0][j] = u[1][j]; u[nx+1][j] = u[nx][j]; } return; } /*--------------------------------------------------------------------------*/ void flow (float ht, /* time step size, 0 < ht <= 0.25 */ long nx, /* image dimension in x direction */ long ny, /* image dimension in y direction */ float hx, /* pixel size in x direction */ float hy, /* pixel size in y direction */ float **fx, /* x derivative of image */ float **fy, /* y derivative of image */ float **ft, /* theta derivative of image */ float alpha, /* smoothness weight */ float lambda, /* contrast parameter */ float **u, /* x component of optic flow */ float **v) /* v component of optic flow */ /* Optic flow iteration by regarding it as a coupled system of two nonlinear diffusion-reaction equations. Isotropic nonlinear diffusion with explicit discretization. */ { long i, j; /* loop variables */ float rx, ry; /* mesh ratios, time savers */ float **u1, **v1; /* intermediate results */ float **dc; /* diffusion coefficient */ float **rhs; /* right hand side of linear system */ float **diag1; /* summand of diagonal part of system matrix */ float ux, uy, vx, vy; /* derivatives */ float help, rxx, ryy; /* time savers */ float two_hx, two_hy; /* time savers */ float grad_sqr; /* |grad(v)|^2 */ float lambda_sqr; /* lambda^2 */ float n, s, w, e, c; /* stencil coefficients: north, south, west, east, centre */ /* ---- allocate storage ---- */ alloc_matrix (&u1, nx+2, ny+2); alloc_matrix (&v1, nx+2, ny+2); alloc_matrix (&dc, nx+2, ny+2); alloc_matrix (&rhs, nx+2, ny+2); alloc_matrix (&diag1, nx+2, ny+2); /* ---- copy u, v into u1, v1 ---- */ for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { u1[i][j] = u[i][j]; v1[i][j] = v[i][j]; } /* ---- calculate diffusivity ---- */ two_hx = 2.0 * hx; two_hy = 2.0 * hy; lambda_sqr = lambda * lambda; dummies (u1, nx, ny); dummies (v1, nx, ny); for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { /* calculate grad(f) */ ux = (u1[i+1][j] - u1[i-1][j]) / two_hx; uy = (u1[i][j+1] - u1[i][j-1]) / two_hy; vx = (v1[i+1][j] - v1[i-1][j]) / two_hx; vy = (v1[i][j+1] - v1[i][j-1]) / two_hy; grad_sqr = ux * ux + uy * uy + vx * vx + vy * vy; dc[i][j] = 1.0 / sqrt (1.0 + grad_sqr / lambda_sqr); } /* create reflecting dummy boundaries */ dummies (dc, nx, ny); /* ---- calculate diffusion of the first equation ---- */ help = ht / alpha; rxx = ht / (2.0 * hx * hx); ryy = ht / (2.0 * hy * hy); /* create reflecting dummy boundaries */ dummies (u1, nx, ny); printf("\nCommented dc terms\n"); for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { /* SUPPLEMENT CODE */ u[i][j] = (u1[i][j] + rxx * ( (/*(dc[i+1][j] + dc[i][j]) */ (u1[i+1][j] - u1[i][j]) + /*(dc[i-1][j] + dc[i][j]) */ (u1[i-1][j] - u1[i][j])) ) + ryy * ( (/*(dc[i][j+1] + dc[i][j]) */ (u1[i+1][j] - u1[i][j]) + /*(dc[i][j-1] + dc[i][j]) */ (u1[i-1][j] - u1[i][j]))) - help * fx[i][j] * (fy[i][j] * v1[i][j] + ft[i][j]) ) / (1 + help * fx[i][j]*fx[i][j]); } /* ---- calculate diffusion of the second equation ---- */ /* create reflecting dummy boundaries */ dummies (v1, nx, ny); for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { /* SUPPLEMENT CODE */ v[i][j] = (v1[i][j] + rxx * ( (/*(dc[i+1][j] + dc[i][j]) */ (v1[i+1][j] - v1[i][j]) + /*(dc[i-1][j] + dc[i][j]) */ (v1[i-1][j] - v1[i][j])) ) + ryy * ( (/*(dc[i][j+1] + dc[i][j]) */ (v1[i+1][j] - v1[i][j]) + /*(dc[i][j-1] + dc[i][j]) */ (v1[i-1][j] - v1[i][j])) ) - help * fy[i][j] * (fx[i][j] * u1[i][j] + ft[i][j]) ) / (1 + help * fy[i][j]*fy[i][j]); } /* ---- disallocate storage ---- */ disalloc_matrix (u1, nx+2, ny+2); disalloc_matrix (v1, nx+2, ny+2); disalloc_matrix (dc, nx+2, ny+2); disalloc_matrix (rhs, nx+2, ny+2); disalloc_matrix (diag1, nx+2, ny+2); return; } /* flow */ /*--------------------------------------------------------------------------*/ void analyse (float **u, /* image, unchanged */ long nx, /* pixel number in x direction */ long ny, /* pixel number in y direction */ float *min, /* minimum, output */ float *max, /* maximum, output */ float *mean, /* mean, output */ float *std) /* standard deviation, output */ /* computes minimum, maximum, mean, and standard deviation of an image u */ { long i, j; /* loop variables */ double help1; /* auxiliary variable */ float help2; /* auxiliary variable */ *min = u[1][1]; *max = u[1][1]; help1 = 0.0; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { if (u[i][j] < *min) *min = u[i][j]; if (u[i][j] > *max) *max = u[i][j]; help1 = help1 + (double)u[i][j]; } *mean = (float)help1 / (nx * ny); *std = 0.0; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { help2 = u[i][j] - *mean; *std = *std + help2 * help2; } *std = sqrt(*std / (nx * ny)); return; } /* analyse */ /*--------------------------------------------------------------------------*/ int main () { char in1[80], in2[80]; /* for reading data */ char out[80]; /* for reading data */ float **f1, **f2; /* images */ float **fx, **fy, **ft; /* image derivatives */ float **u, **v; /* optic flow components */ float **w; /* optic flow magnitude */ float ***color_img; /* color representation of optic flow field */ long dtype; /* type of diffusivity */ long i, j, k; /* loop variables */ long kmax; /* max. no. of iterations */ long nx, ny; /* image size in x, y direction */ float hx, hy; /* pixel sizes */ float ht; /* time step size */ float alpha; /* smoothness weight */ float lambda; /* contrast parameter */ float max, min; /* largest, smallest grey value */ float mean; /* average grey value */ float std; /* standard deviation */ char comments[1600]; /* string for comments */ printf ("\n"); printf ("OPTIC FLOW WITH CHARBONNIER SMOOTHNESS TERM, EXPLICIT SCHEME\n\n"); printf ("************************************************************\n\n"); printf (" Copyright 2014 by Joachim Weickert \n"); printf (" Dept. of Mathematics and Computer Science \n"); printf (" Saarland University, Saarbruecken, Germany \n\n"); printf (" All rights reserved. Unauthorized usage, \n"); printf (" copying, hiring, and selling prohibited. \n\n"); printf (" Send bug reports to \n"); printf (" [email protected] \n\n"); printf ("************************************************************\n\n"); /* ---- read input image f1 (pgm format P5) ---- */ printf ("input image 1 (pgm): "); read_string (in1); read_pgm_and_allocate_memory (in1, &nx, &ny, &f1); /* ---- read input image f2 (pgm format P5) ---- */ printf ("input image 2 (pgm): "); read_string (in2); read_pgm_and_allocate_memory (in2, &nx, &ny, &f2); /* ---- read parameters ---- */ printf ("smoothnes weight alpha (>0) (float): "); read_float (&alpha); printf ("contrast parameter lambda (>0) (float): "); read_float (&lambda); printf ("time step size (<=0.25) (float): "); read_float (&ht); printf ("number of iterations (>0) (integer): "); read_long (&kmax); printf ("output image (colour coded flow) (ppm): "); read_string (out); printf ("\n"); /* ---- initializations ---- */ /* allocate storage for image derivatives fx, fy, ft */ alloc_matrix (&fx, nx+2, ny+2); alloc_matrix (&fy, nx+2, ny+2); alloc_matrix (&ft, nx+2, ny+2); /* calculate image derivatives fx, fy and ft */ dummies (f1, nx, ny); dummies (f2, nx, ny); hx = 1.0; hy = 1.0; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { fx[i][j] = (f1[i+1][j] - f1[i-1][j] + f2[i+1][j] - f2[i-1][j]) / (4.0 * hx); fy[i][j] = (f1[i][j+1] - f1[i][j-1] + f2[i][j+1] - f2[i][j-1]) / (4.0 * hy); ft[i][j] = f2[i][j] - f1[i][j]; /* frame distance 1 assumed */ } /* allocate storage for optic flow and its magnitude */ alloc_matrix (&u, nx+2, ny+2); alloc_matrix (&v, nx+2, ny+2); alloc_matrix (&w, nx+2, ny+2); /* allocate storage for output */ alloc_cubix (&color_img, nx+2, ny+2, 3); /* initialize (u,v) with 0 */ for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { u[i][j] = 0.0; v[i][j] = 0.0; } /* ---- process image ---- */ for (k=1; k<=kmax; k++) { /* perform one iteration */ printf ("iteration number: %5ld \n", k); flow (ht, nx, ny, hx, hy, fx, fy, ft, alpha, lambda, u, v); /* calculate flow magnitude */ for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) w[i][j] = sqrt (u[i][j] * u[i][j] + v[i][j] * v[i][j]); /* check maximum, mean, standard deviation of flow magnitude */ analyse (w, nx, ny, &min, &max, &mean, &std); printf ("maximum: %8.2f \n", max); printf ("mean: %8.2f \n", mean); printf ("standard dev.: %8.2f \n\n", std); } /* ---- write output image (color representation of flow) ---- */ flow_to_color(u, v, color_img, -1, nx, ny); /* generate comment string */ comments[0]='\0'; comment_line (comments, "# optic flow (color coded), Charbonnier smoothness\n"); comment_line (comments, "# initial image 1: %s\n", in1); comment_line (comments, "# initial image 2: %s\n", in2); comment_line (comments, "# alpha: %8.4f\n", alpha); comment_line (comments, "# lambda: %8.4f\n", lambda); comment_line (comments, "# ht: %8.4f\n", ht); comment_line (comments, "# iterations: %8ld\n", kmax); comment_line (comments, "# min: %8.4f\n", min); comment_line (comments, "# max: %8.4f\n", max); comment_line (comments, "# mean: %8.4f\n", mean); comment_line (comments, "# standard dev.: %8.4f\n", std); /* write image */ write_ppm (color_img, nx, ny, out, comments); printf ("output image %s successfully written\n\n", out); /* ---- free memory ---- */ disalloc_matrix (f1, nx+2, ny+2); disalloc_matrix (f2, nx+2, ny+2); disalloc_matrix (fx, nx+2, ny+2); disalloc_matrix (fy, nx+2, ny+2); disalloc_matrix (ft, nx+2, ny+2); disalloc_matrix (u, nx+2, ny+2); disalloc_matrix (v, nx+2, ny+2); disalloc_matrix (w, nx+2, ny+2); disalloc_cubix (color_img, nx+2, ny+2, 3); return(0); }
the_stack_data/165766062.c
// RUN: %clang_cc1 -fsyntax-only -verify -fdouble-square-bracket-attributes %s int var __attribute__((internal_linkage)); int var2 __attribute__((internal_linkage,common)); // expected-error{{'common' and 'internal_linkage' attributes are not compatible}} \ // expected-note{{conflicting attribute is here}} int var3 __attribute__((common,internal_linkage)); // expected-error{{'internal_linkage' and 'common' attributes are not compatible}} \ // expected-note{{conflicting attribute is here}} int var4 __attribute__((common)); // expected-error{{'common' and 'internal_linkage' attributes are not compatible}} \ // expected-note{{previous definition is here}} int var4 __attribute__((internal_linkage)); // expected-note{{conflicting attribute is here}} \ // expected-error{{'internal_linkage' attribute does not appear on the first declaration of 'var4'}} int var5 __attribute__((internal_linkage)); // expected-error{{'internal_linkage' and 'common' attributes are not compatible}} int var5 __attribute__((common)); // expected-note{{conflicting attribute is here}} __attribute__((internal_linkage)) int f() {} struct __attribute__((internal_linkage)) S { // expected-warning{{'internal_linkage' attribute only applies to variables, functions, and classes}} }; __attribute__((internal_linkage("foo"))) int g() {} // expected-error{{'internal_linkage' attribute takes no arguments}} int var6 [[clang::internal_linkage]]; int var7 [[clang::internal_linkage]] __attribute__((common)); // expected-error{{'internal_linkage' and 'common' attributes are not compatible}} \ // expected-note{{conflicting attribute is here}} __attribute__((common)) int var8 [[clang::internal_linkage]]; // expected-error{{'internal_linkage' and 'common' attributes are not compatible}} \ // expected-note{{conflicting attribute is here}}
the_stack_data/42581.c
#include <menu.h> #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) #define CTRLD 4 char *choices[] = { "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit", (char *)NULL, }; void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color); int main() { ITEM **my_items; int c; MENU *my_menu; WINDOW *my_menu_win; int n_choices, i; /* Initialize curses. */ initscr(); start_color(); cbreak(); noecho(); keypad(stdscr, TRUE); init_pair(1, COLOR_RED, COLOR_BLACK); /* Create items. */ n_choices = ARRAY_SIZE(choices); my_items = (ITEM **)calloc(n_choices, sizeof(ITEM *)); for(i = 0; i < n_choices; ++i) my_items[i] = new_item(choices[i], choices[i]); /* Create menu. */ my_menu = new_menu((ITEM **)my_items); /* Create the window to be associated with the menu. */ my_menu_win = newwin(10, 40, 4, 4); keypad(my_menu_win, TRUE); /* Set main window and sub window */ set_menu_win(my_menu, my_menu_win); set_menu_sub(my_menu, derwin(my_menu_win, 6, 38, 3, 1)); /* Set menu mark to the string " * " */ set_menu_mark(my_menu, " * "); /* Print a border around the main window and print a title */ box(my_menu_win, 0, 0); print_in_middle(my_menu_win, 1, 0, 40, "My Menu", COLOR_PAIR(1)); mvwaddch(my_menu_win, 2, 0, ACS_LTEE); mvwhline(my_menu_win, 2, 1, ACS_HLINE, 38); mvwaddch(my_menu_win, 2, 39, ACS_RTEE); /* Post the menu */ post_menu(my_menu); wrefresh(my_menu_win); while ( (c = wgetch(my_menu_win)) != 'q' ) { switch ( c ) { case KEY_DOWN: menu_driver(my_menu, REQ_DOWN_ITEM); break; case KEY_UP: menu_driver(my_menu, REQ_UP_ITEM); break; } wrefresh(my_menu_win); } /* Unpost and free all the memory taken up */ unpost_menu(my_menu); free_menu(my_menu); for(i = 0; i < n_choices; ++i) free_item(my_items[i]); endwin(); } void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color) { int length, x, y; float temp; if(win == NULL) win = stdscr; getyx(win, y, x); if(startx != 0) x = startx; if(starty != 0) y = starty; if(width == 0) width = 80; length = strlen(string); temp = (width - length)/ 2; x = startx + (int)temp; wattron(win, color); mvwprintw(win, y, x, "%s", string); wattroff(win, color); refresh(); }
the_stack_data/84409.c
/* This testcase is part of GDB, the GNU debugger. Copyright (C) 2013-2020 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> int main () { sleep (3); return 0; }
the_stack_data/61076459.c
/* * Copyright (C) 1984-2012 Mark Nudelman * Modified for use with illumos by Garrett D'Amore. * Copyright 2014 Garrett D'Amore <[email protected]> * * You may distribute under the terms of either the GNU General Public * License or the Less License, as specified in the README file. * * For more information, see the README file. */ /* * Silly little program to generate the help.c source file * from the less.hlp text file. * help.c just contains a char array whose contents are * the contents of less.hlp. */ #include <stdio.h> int main(int argc, char **argv) { int ch; int prevch; int col; (void) printf("/*\n"); (void) printf(" * This file was generated by mkhelp from less.hlp\n"); (void) printf(" */\n"); (void) printf("#include \"less.h\"\n"); (void) printf("const char helpdata[] = {\n"); ch = 0; col = 0; while (prevch = ch, (ch = getchar()) != EOF) { if (col >= 74) { (void) printf(",\n"); col = 0; } else if (col) { col += printf(", "); } switch (ch) { case '\'': col += printf("'\\''"); break; case '\\': col += printf("'\\'"); break; case '\b': col += printf("'\\b'"); break; case '\t': col += printf("'\\t'"); break; case '\"': col += printf("'\"'"); break; case '\n': if (prevch != '\r') { (void) printf("'\\n',\n"); col = 0; } break; case '\r': if (prevch != '\n') { (void) printf("'\\n',\n"); col = 0; } break; default: if (ch >= ' ' && ch < 0x7f) col += printf("'%c'", ch); else col += printf("0x%02x", ch); break; } } /* Add an extra null char to avoid having a trailing comma. */ (void) printf("0\n"); (void) printf("};\n"); (void) printf("int size_helpdata = sizeof (helpdata) - 1;\n"); return (0); }
the_stack_data/145026.c
/* * hwsim_test - Data connectivity test for mac80211_hwsim * Copyright (c) 2009, Atheros Communications * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/select.h> #include <netpacket/packet.h> #include <net/ethernet.h> #include <net/if.h> #include <arpa/inet.h> #define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] #define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" #define HWSIM_ETHERTYPE ETHERTYPE_IP #define HWSIM_PACKETLEN 1500 static unsigned char addr1[ETH_ALEN], addr2[ETH_ALEN], bcast[ETH_ALEN]; static void tx(int s, const char *ifname, int ifindex, const unsigned char *src, const unsigned char *dst) { char buf[HWSIM_PACKETLEN], *pos; struct ether_header *eth; int i; printf("TX: %s(ifindex=%d) " MACSTR " -> " MACSTR "\n", ifname, ifindex, MAC2STR(src), MAC2STR(dst)); eth = (struct ether_header *) buf; memcpy(eth->ether_dhost, dst, ETH_ALEN); memcpy(eth->ether_shost, src, ETH_ALEN); eth->ether_type = htons(HWSIM_ETHERTYPE); pos = (char *) (eth + 1); for (i = 0; i < sizeof(buf) - sizeof(*eth); i++) *pos++ = i; if (send(s, buf, sizeof(buf), 0) < 0) perror("send"); } struct rx_result { int rx_unicast1:1; int rx_broadcast1:1; int rx_unicast2:1; int rx_broadcast2:1; }; static void rx(int s, int iface, const char *ifname, int ifindex, struct rx_result *res) { char buf[HWSIM_PACKETLEN + 1], *pos; struct ether_header *eth; int len, i; len = recv(s, buf, sizeof(buf), 0); if (len < 0) { perror("recv"); return; } eth = (struct ether_header *) buf; printf("RX: %s(ifindex=%d) " MACSTR " -> " MACSTR " (len=%d)\n", ifname, ifindex, MAC2STR(eth->ether_shost), MAC2STR(eth->ether_dhost), len); if (len != HWSIM_PACKETLEN) { printf("Ignore frame with unexpected RX length\n"); return; } pos = (char *) (eth + 1); for (i = 0; i < sizeof(buf) - 1 - sizeof(*eth); i++) { if ((unsigned char) *pos != (unsigned char) i) { printf("Ignore frame with unexpected contents\n"); printf("i=%d received=0x%x expected=0x%x\n", i, (unsigned char) *pos, (unsigned char) i); return; } pos++; } if (iface == 1 && memcmp(eth->ether_dhost, addr1, ETH_ALEN) == 0 && memcmp(eth->ether_shost, addr2, ETH_ALEN) == 0) res->rx_unicast1 = 1; else if (iface == 1 && memcmp(eth->ether_dhost, bcast, ETH_ALEN) == 0 && memcmp(eth->ether_shost, addr2, ETH_ALEN) == 0) res->rx_broadcast1 = 1; else if (iface == 2 && memcmp(eth->ether_dhost, addr2, ETH_ALEN) == 0 && memcmp(eth->ether_shost, addr1, ETH_ALEN) == 0) res->rx_unicast2 = 1; else if (iface == 2 && memcmp(eth->ether_dhost, bcast, ETH_ALEN) == 0 && memcmp(eth->ether_shost, addr1, ETH_ALEN) == 0) res->rx_broadcast2 = 1; } int main(int argc, char *argv[]) { int s1 = -1, s2 = -1, ret = -1; struct ifreq ifr; int ifindex1, ifindex2; struct sockaddr_ll ll; fd_set rfds; struct timeval tv; struct rx_result res; if (argc != 3) { fprintf(stderr, "usage: hwsim_test <ifname1> <ifname2>\n"); return -1; } memset(bcast, 0xff, ETH_ALEN); s1 = socket(PF_PACKET, SOCK_RAW, htons(HWSIM_ETHERTYPE)); if (s1 < 0) { perror("socket"); goto fail; } s2 = socket(PF_PACKET, SOCK_RAW, htons(HWSIM_ETHERTYPE)); if (s2 < 0) { perror("socket"); goto fail; } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, argv[1], sizeof(ifr.ifr_name)); if (ioctl(s1, SIOCGIFINDEX, &ifr) < 0) { perror("ioctl[SIOCGIFINDEX]"); goto fail; } ifindex1 = ifr.ifr_ifindex; if (ioctl(s1, SIOCGIFHWADDR, &ifr) < 0) { perror("ioctl[SIOCGIFHWADDR]"); goto fail; } memcpy(addr1, ifr.ifr_hwaddr.sa_data, ETH_ALEN); memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, argv[2], sizeof(ifr.ifr_name)); if (ioctl(s2, SIOCGIFINDEX, &ifr) < 0) { perror("ioctl[SIOCGIFINDEX]"); goto fail; } ifindex2 = ifr.ifr_ifindex; if (ioctl(s2, SIOCGIFHWADDR, &ifr) < 0) { perror("ioctl[SIOCGIFHWADDR]"); goto fail; } memcpy(addr2, ifr.ifr_hwaddr.sa_data, ETH_ALEN); memset(&ll, 0, sizeof(ll)); ll.sll_family = PF_PACKET; ll.sll_ifindex = ifindex1; ll.sll_protocol = htons(HWSIM_ETHERTYPE); if (bind(s1, (struct sockaddr *) &ll, sizeof(ll)) < 0) { perror("bind"); goto fail; } memset(&ll, 0, sizeof(ll)); ll.sll_family = PF_PACKET; ll.sll_ifindex = ifindex2; ll.sll_protocol = htons(HWSIM_ETHERTYPE); if (bind(s2, (struct sockaddr *) &ll, sizeof(ll)) < 0) { perror("bind"); goto fail; } tx(s1, argv[1], ifindex1, addr1, addr2); tx(s1, argv[1], ifindex1, addr1, bcast); tx(s2, argv[2], ifindex2, addr2, addr1); tx(s2, argv[2], ifindex2, addr2, bcast); tv.tv_sec = 1; tv.tv_usec = 0; memset(&res, 0, sizeof(res)); for (;;) { int r; FD_ZERO(&rfds); FD_SET(s1, &rfds); FD_SET(s2, &rfds); r = select(s2 + 1, &rfds, NULL, NULL, &tv); if (r < 0) { perror("select"); goto fail; } if (r == 0) break; /* timeout */ if (FD_ISSET(s1, &rfds)) rx(s1, 1, argv[1], ifindex1, &res); if (FD_ISSET(s2, &rfds)) rx(s2, 2, argv[2], ifindex2, &res); if (res.rx_unicast1 && res.rx_broadcast1 && res.rx_unicast2 && res.rx_broadcast2) { ret = 0; break; } } if (ret) { printf("Did not receive all expected frames:\n" "rx_unicast1=%d rx_broadcast1=%d " "rx_unicast2=%d rx_broadcast2=%d\n", res.rx_unicast1, res.rx_broadcast1, res.rx_unicast2, res.rx_broadcast2); } else { printf("Both unicast and broadcast working in both " "directions\n"); } fail: close(s1); close(s2); return ret; }
the_stack_data/743758.c
int NumDigits(int i) { int num; if (i<0) { printf("internal error: negative number passed to NumDigits\n"); exit(1); } num = 0; while (i>0) { num++; i = i/10; } return(num); } char *IntToStr(int i) { char *s; int len; if (i <= 0) { printf("internal error: non-positive number passed to IntToStr\n"); exit(1); } len = NumDigits(i); s = (char *)malloc(len+1); s[len] = '\0'; len--; while (len >= 0) { s[len] = i % 10 + '0'; len--; i = i/10; } return(s); }
the_stack_data/839930.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2012-2015 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ static int v; static void callee (void) { v++; } int main (void) { callee (); return 0; }
the_stack_data/45450983.c
//If there are only two(type ) of numbers to sort. #include <stdio.h> int main() { int a[100],low,high,n,i; printf("Enter the length of array:"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } low=0; high=n-1; while(low<high) { if(a[low]==0) { low++; } else { i=a[low]; a[low]=a[high]; a[high]=i; high--; } } printf("\nSorted order\n"); for(i=0;i<n;i++){ printf("%d\n",a[i]);} return 0; }
the_stack_data/26700030.c
/* Copyright (c) 2014, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <openssl/rand.h> #if defined(OPENSSL_WINDOWS) && !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) #include <limits.h> #include <stdlib.h> OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include <windows.h> #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #include <bcrypt.h> OPENSSL_MSVC_PRAGMA(comment(lib, "bcrypt.lib")) #else // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the // "Community Additions" comment on MSDN here: // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx #define SystemFunction036 NTAPI SystemFunction036 #include <ntsecapi.h> #undef SystemFunction036 #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP OPENSSL_MSVC_PRAGMA(warning(pop)) #include "../fipsmodule/rand/internal.h" void CRYPTO_sysrand(uint8_t *out, size_t requested) { while (requested > 0) { ULONG output_bytes_this_pass = ULONG_MAX; if (requested < output_bytes_this_pass) { output_bytes_this_pass = (ULONG)requested; } // On non-UWP configurations, use RtlGenRandom instead of BCryptGenRandom // to avoid accessing resources that may be unavailable inside the // Chromium sandbox. See https://crbug.com/boringssl/307 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) if (!BCRYPT_SUCCESS(BCryptGenRandom( /*hAlgorithm=*/NULL, out, output_bytes_this_pass, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { #else if (RtlGenRandom(out, output_bytes_this_pass) == FALSE) { #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP abort(); } requested -= output_bytes_this_pass; out += output_bytes_this_pass; } return; } #endif // OPENSSL_WINDOWS && !BORINGSSL_UNSAFE_DETERMINISTIC_MODE
the_stack_data/182226.c
struct __attribute__((__packed__)) s { char c; unsigned long long x; }; void __attribute__((__noinline__)) foo (struct s *s) { s->x = 0; } int main (void) { struct s s = { 1, ~0ULL }; foo (&s); return s.x != 0; }
the_stack_data/89198977.c
unsigned int c = 0; int main(void) { unsigned int a = 10; unsigned int b = 3; c = plus(a, b); return 0; } int plus(unsigned int a, unsigned int b) { return a + b; }
the_stack_data/165769074.c
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } long long n, m, q, x, u1, v1, u2, v2; main() { scanf("%lld%lld%lld", &n, &m, &q); for (x = gcd(n, m); q--;) { scanf("%lld%lld%lld%lld", &u1, &v1, &u2, &v2), v1--, v2--; int p, q; if (u1 == 1) p = v1 / (n / x); if (u1 == 2) p = v1 / (m / x); if (u2 == 1) q = v2 / (n / x); if (u2 == 2) q = v2 / (m / x); puts(p == q ? "YES" : "NO"); } }
the_stack_data/1125133.c
#include <stdio.h> #include <unistd.h> int main() { int pid_1 = fork(); if (pid_1 != 0) { int pid_2 = fork(); if (pid_2 != 0) { puts("a"); } else { puts("c"); // second sub process print "c" } } else { puts("b"); // first sub process print "b" } }
the_stack_data/94553.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; static doublereal c_b6 = -1.; static doublereal c_b8 = 1.; /* > \brief \b DLA_GBRFSX_EXTENDED improves the computed solution to a system of linear equations for general banded matrices by performing extra-precise iterative refinement and provides error bounds and backwar d error estimates for the solution. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DLA_GBRFSX_EXTENDED + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dla_gbr fsx_extended.f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dla_gbr fsx_extended.f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dla_gbr fsx_extended.f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DLA_GBRFSX_EXTENDED( PREC_TYPE, TRANS_TYPE, N, KL, KU, */ /* NRHS, AB, LDAB, AFB, LDAFB, IPIV, */ /* COLEQU, C, B, LDB, Y, LDY, */ /* BERR_OUT, N_NORMS, ERR_BNDS_NORM, */ /* ERR_BNDS_COMP, RES, AYB, DY, */ /* Y_TAIL, RCOND, ITHRESH, RTHRESH, */ /* DZ_UB, IGNORE_CWISE, INFO ) */ /* INTEGER INFO, LDAB, LDAFB, LDB, LDY, N, KL, KU, NRHS, */ /* $ PREC_TYPE, TRANS_TYPE, N_NORMS, ITHRESH */ /* LOGICAL COLEQU, IGNORE_CWISE */ /* DOUBLE PRECISION RTHRESH, DZ_UB */ /* INTEGER IPIV( * ) */ /* DOUBLE PRECISION AB( LDAB, * ), AFB( LDAFB, * ), B( LDB, * ), */ /* $ Y( LDY, * ), RES(*), DY(*), Y_TAIL(*) */ /* DOUBLE PRECISION C( * ), AYB(*), RCOND, BERR_OUT(*), */ /* $ ERR_BNDS_NORM( NRHS, * ), */ /* $ ERR_BNDS_COMP( NRHS, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > */ /* > DLA_GBRFSX_EXTENDED improves the computed solution to a system of */ /* > linear equations by performing extra-precise iterative refinement */ /* > and provides error bounds and backward error estimates for the solution. */ /* > This subroutine is called by DGBRFSX to perform iterative refinement. */ /* > In addition to normwise error bound, the code provides maximum */ /* > componentwise error bound if possible. See comments for ERR_BNDS_NORM */ /* > and ERR_BNDS_COMP for details of the error bounds. Note that this */ /* > subroutine is only resonsible for setting the second fields of */ /* > ERR_BNDS_NORM and ERR_BNDS_COMP. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] PREC_TYPE */ /* > \verbatim */ /* > PREC_TYPE is INTEGER */ /* > Specifies the intermediate precision to be used in refinement. */ /* > The value is defined by ILAPREC(P) where P is a CHARACTER and P */ /* > = 'S': Single */ /* > = 'D': Double */ /* > = 'I': Indigenous */ /* > = 'X' or 'E': Extra */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS_TYPE */ /* > \verbatim */ /* > TRANS_TYPE is INTEGER */ /* > Specifies the transposition operation on A. */ /* > The value is defined by ILATRANS(T) where T is a CHARACTER and T */ /* > = 'N': No transpose */ /* > = 'T': Transpose */ /* > = 'C': Conjugate transpose */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of linear equations, i.e., the order of the */ /* > matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] KL */ /* > \verbatim */ /* > KL is INTEGER */ /* > The number of subdiagonals within the band of A. KL >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] KU */ /* > \verbatim */ /* > KU is INTEGER */ /* > The number of superdiagonals within the band of A. KU >= 0 */ /* > \endverbatim */ /* > */ /* > \param[in] NRHS */ /* > \verbatim */ /* > NRHS is INTEGER */ /* > The number of right-hand-sides, i.e., the number of columns of the */ /* > matrix B. */ /* > \endverbatim */ /* > */ /* > \param[in] AB */ /* > \verbatim */ /* > AB is DOUBLE PRECISION array, dimension (LDAB,N) */ /* > On entry, the N-by-N matrix AB. */ /* > \endverbatim */ /* > */ /* > \param[in] LDAB */ /* > \verbatim */ /* > LDAB is INTEGER */ /* > The leading dimension of the array AB. LDBA >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] AFB */ /* > \verbatim */ /* > AFB is DOUBLE PRECISION array, dimension (LDAFB,N) */ /* > The factors L and U from the factorization */ /* > A = P*L*U as computed by DGBTRF. */ /* > \endverbatim */ /* > */ /* > \param[in] LDAFB */ /* > \verbatim */ /* > LDAFB is INTEGER */ /* > The leading dimension of the array AF. LDAFB >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] IPIV */ /* > \verbatim */ /* > IPIV is INTEGER array, dimension (N) */ /* > The pivot indices from the factorization A = P*L*U */ /* > as computed by DGBTRF; row i of the matrix was interchanged */ /* > with row IPIV(i). */ /* > \endverbatim */ /* > */ /* > \param[in] COLEQU */ /* > \verbatim */ /* > COLEQU is LOGICAL */ /* > If .TRUE. then column equilibration was done to A before calling */ /* > this routine. This is needed to compute the solution and error */ /* > bounds correctly. */ /* > \endverbatim */ /* > */ /* > \param[in] C */ /* > \verbatim */ /* > C is DOUBLE PRECISION array, dimension (N) */ /* > The column scale factors for A. If COLEQU = .FALSE., C */ /* > is not accessed. If C is input, each element of C should be a power */ /* > of the radix to ensure a reliable solution and error estimates. */ /* > Scaling by powers of the radix does not cause rounding errors unless */ /* > the result underflows or overflows. Rounding errors during scaling */ /* > lead to refining with a matrix that is not equivalent to the */ /* > input matrix, producing error estimates that may not be */ /* > reliable. */ /* > \endverbatim */ /* > */ /* > \param[in] B */ /* > \verbatim */ /* > B is DOUBLE PRECISION array, dimension (LDB,NRHS) */ /* > The right-hand-side matrix B. */ /* > \endverbatim */ /* > */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of the array B. LDB >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in,out] Y */ /* > \verbatim */ /* > Y is DOUBLE PRECISION array, dimension (LDY,NRHS) */ /* > On entry, the solution matrix X, as computed by DGBTRS. */ /* > On exit, the improved solution matrix Y. */ /* > \endverbatim */ /* > */ /* > \param[in] LDY */ /* > \verbatim */ /* > LDY is INTEGER */ /* > The leading dimension of the array Y. LDY >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] BERR_OUT */ /* > \verbatim */ /* > BERR_OUT is DOUBLE PRECISION array, dimension (NRHS) */ /* > On exit, BERR_OUT(j) contains the componentwise relative backward */ /* > error for right-hand-side j from the formula */ /* > f2cmax(i) ( abs(RES(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) ) */ /* > where abs(Z) is the componentwise absolute value of the matrix */ /* > or vector Z. This is computed by DLA_LIN_BERR. */ /* > \endverbatim */ /* > */ /* > \param[in] N_NORMS */ /* > \verbatim */ /* > N_NORMS is INTEGER */ /* > Determines which error bounds to return (see ERR_BNDS_NORM */ /* > and ERR_BNDS_COMP). */ /* > If N_NORMS >= 1 return normwise error bounds. */ /* > If N_NORMS >= 2 return componentwise error bounds. */ /* > \endverbatim */ /* > */ /* > \param[in,out] ERR_BNDS_NORM */ /* > \verbatim */ /* > ERR_BNDS_NORM is DOUBLE PRECISION array, dimension (NRHS, N_ERR_BNDS) */ /* > For each right-hand side, this array contains information about */ /* > various error bounds and condition numbers corresponding to the */ /* > normwise relative error, which is defined as follows: */ /* > */ /* > Normwise relative error in the ith solution vector: */ /* > max_j (abs(XTRUE(j,i) - X(j,i))) */ /* > ------------------------------ */ /* > max_j abs(X(j,i)) */ /* > */ /* > The array is indexed by the type of error information as described */ /* > below. There currently are up to three pieces of information */ /* > returned. */ /* > */ /* > The first index in ERR_BNDS_NORM(i,:) corresponds to the ith */ /* > right-hand side. */ /* > */ /* > The second index in ERR_BNDS_NORM(:,err) contains the following */ /* > three fields: */ /* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */ /* > reciprocal condition number is less than the threshold */ /* > sqrt(n) * slamch('Epsilon'). */ /* > */ /* > err = 2 "Guaranteed" error bound: The estimated forward error, */ /* > almost certainly within a factor of 10 of the true error */ /* > so long as the next entry is greater than the threshold */ /* > sqrt(n) * slamch('Epsilon'). This error bound should only */ /* > be trusted if the previous boolean is true. */ /* > */ /* > err = 3 Reciprocal condition number: Estimated normwise */ /* > reciprocal condition number. Compared with the threshold */ /* > sqrt(n) * slamch('Epsilon') to determine if the error */ /* > estimate is "guaranteed". These reciprocal condition */ /* > numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some */ /* > appropriately scaled matrix Z. */ /* > Let Z = S*A, where S scales each row by a power of the */ /* > radix so all absolute row sums of Z are approximately 1. */ /* > */ /* > This subroutine is only responsible for setting the second field */ /* > above. */ /* > See Lapack Working Note 165 for further details and extra */ /* > cautions. */ /* > \endverbatim */ /* > */ /* > \param[in,out] ERR_BNDS_COMP */ /* > \verbatim */ /* > ERR_BNDS_COMP is DOUBLE PRECISION array, dimension (NRHS, N_ERR_BNDS) */ /* > For each right-hand side, this array contains information about */ /* > various error bounds and condition numbers corresponding to the */ /* > componentwise relative error, which is defined as follows: */ /* > */ /* > Componentwise relative error in the ith solution vector: */ /* > abs(XTRUE(j,i) - X(j,i)) */ /* > max_j ---------------------- */ /* > abs(X(j,i)) */ /* > */ /* > The array is indexed by the right-hand side i (on which the */ /* > componentwise relative error depends), and the type of error */ /* > information as described below. There currently are up to three */ /* > pieces of information returned for each right-hand side. If */ /* > componentwise accuracy is not requested (PARAMS(3) = 0.0), then */ /* > ERR_BNDS_COMP is not accessed. If N_ERR_BNDS < 3, then at most */ /* > the first (:,N_ERR_BNDS) entries are returned. */ /* > */ /* > The first index in ERR_BNDS_COMP(i,:) corresponds to the ith */ /* > right-hand side. */ /* > */ /* > The second index in ERR_BNDS_COMP(:,err) contains the following */ /* > three fields: */ /* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */ /* > reciprocal condition number is less than the threshold */ /* > sqrt(n) * slamch('Epsilon'). */ /* > */ /* > err = 2 "Guaranteed" error bound: The estimated forward error, */ /* > almost certainly within a factor of 10 of the true error */ /* > so long as the next entry is greater than the threshold */ /* > sqrt(n) * slamch('Epsilon'). This error bound should only */ /* > be trusted if the previous boolean is true. */ /* > */ /* > err = 3 Reciprocal condition number: Estimated componentwise */ /* > reciprocal condition number. Compared with the threshold */ /* > sqrt(n) * slamch('Epsilon') to determine if the error */ /* > estimate is "guaranteed". These reciprocal condition */ /* > numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some */ /* > appropriately scaled matrix Z. */ /* > Let Z = S*(A*diag(x)), where x is the solution for the */ /* > current right-hand side and S scales each row of */ /* > A*diag(x) by a power of the radix so all absolute row */ /* > sums of Z are approximately 1. */ /* > */ /* > This subroutine is only responsible for setting the second field */ /* > above. */ /* > See Lapack Working Note 165 for further details and extra */ /* > cautions. */ /* > \endverbatim */ /* > */ /* > \param[in] RES */ /* > \verbatim */ /* > RES is DOUBLE PRECISION array, dimension (N) */ /* > Workspace to hold the intermediate residual. */ /* > \endverbatim */ /* > */ /* > \param[in] AYB */ /* > \verbatim */ /* > AYB is DOUBLE PRECISION array, dimension (N) */ /* > Workspace. This can be the same workspace passed for Y_TAIL. */ /* > \endverbatim */ /* > */ /* > \param[in] DY */ /* > \verbatim */ /* > DY is DOUBLE PRECISION array, dimension (N) */ /* > Workspace to hold the intermediate solution. */ /* > \endverbatim */ /* > */ /* > \param[in] Y_TAIL */ /* > \verbatim */ /* > Y_TAIL is DOUBLE PRECISION array, dimension (N) */ /* > Workspace to hold the trailing bits of the intermediate solution. */ /* > \endverbatim */ /* > */ /* > \param[in] RCOND */ /* > \verbatim */ /* > RCOND is DOUBLE PRECISION */ /* > Reciprocal scaled condition number. This is an estimate of the */ /* > reciprocal Skeel condition number of the matrix A after */ /* > equilibration (if done). If this is less than the machine */ /* > precision (in particular, if it is zero), the matrix is singular */ /* > to working precision. Note that the error may still be small even */ /* > if this number is very small and the matrix appears ill- */ /* > conditioned. */ /* > \endverbatim */ /* > */ /* > \param[in] ITHRESH */ /* > \verbatim */ /* > ITHRESH is INTEGER */ /* > The maximum number of residual computations allowed for */ /* > refinement. The default is 10. For 'aggressive' set to 100 to */ /* > permit convergence using approximate factorizations or */ /* > factorizations other than LU. If the factorization uses a */ /* > technique other than Gaussian elimination, the guarantees in */ /* > ERR_BNDS_NORM and ERR_BNDS_COMP may no longer be trustworthy. */ /* > \endverbatim */ /* > */ /* > \param[in] RTHRESH */ /* > \verbatim */ /* > RTHRESH is DOUBLE PRECISION */ /* > Determines when to stop refinement if the error estimate stops */ /* > decreasing. Refinement will stop when the next solution no longer */ /* > satisfies norm(dx_{i+1}) < RTHRESH * norm(dx_i) where norm(Z) is */ /* > the infinity norm of Z. RTHRESH satisfies 0 < RTHRESH <= 1. The */ /* > default value is 0.5. For 'aggressive' set to 0.9 to permit */ /* > convergence on extremely ill-conditioned matrices. See LAWN 165 */ /* > for more details. */ /* > \endverbatim */ /* > */ /* > \param[in] DZ_UB */ /* > \verbatim */ /* > DZ_UB is DOUBLE PRECISION */ /* > Determines when to start considering componentwise convergence. */ /* > Componentwise convergence is only considered after each component */ /* > of the solution Y is stable, which we definte as the relative */ /* > change in each component being less than DZ_UB. The default value */ /* > is 0.25, requiring the first bit to be stable. See LAWN 165 for */ /* > more details. */ /* > \endverbatim */ /* > */ /* > \param[in] IGNORE_CWISE */ /* > \verbatim */ /* > IGNORE_CWISE is LOGICAL */ /* > If .TRUE. then ignore componentwise convergence. Default value */ /* > is .FALSE.. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: Successful exit. */ /* > < 0: if INFO = -i, the ith argument to DGBTRS had an illegal */ /* > value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2017 */ /* > \ingroup doubleGBcomputational */ /* ===================================================================== */ /* Subroutine */ int dla_gbrfsx_extended_(integer *prec_type__, integer * trans_type__, integer *n, integer *kl, integer *ku, integer *nrhs, doublereal *ab, integer *ldab, doublereal *afb, integer *ldafb, integer *ipiv, logical *colequ, doublereal *c__, doublereal *b, integer *ldb, doublereal *y, integer *ldy, doublereal *berr_out__, integer *n_norms__, doublereal *err_bnds_norm__, doublereal * err_bnds_comp__, doublereal *res, doublereal *ayb, doublereal *dy, doublereal *y_tail__, doublereal *rcond, integer *ithresh, doublereal *rthresh, doublereal *dz_ub__, logical *ignore_cwise__, integer *info) { /* System generated locals */ integer ab_dim1, ab_offset, afb_dim1, afb_offset, b_dim1, b_offset, y_dim1, y_offset, err_bnds_norm_dim1, err_bnds_norm_offset, err_bnds_comp_dim1, err_bnds_comp_offset, i__1, i__2, i__3; doublereal d__1, d__2; char ch__1[1]; /* Local variables */ doublereal dx_x__, dz_z__; extern /* Subroutine */ int dla_lin_berr_(integer *, integer *, integer * , doublereal *, doublereal *, doublereal *); doublereal ymin; extern /* Subroutine */ int blas_dgbmv_x_(integer *, integer *, integer * , integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); doublereal dxratmax, dzratmax; integer y_prec_state__; extern /* Subroutine */ int blas_dgbmv2_x_(integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); integer i__, j, m; extern /* Subroutine */ int dla_gbamv_(integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dgbmv_(char *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); doublereal dxrat; logical incr_prec__; doublereal dzrat; extern /* Subroutine */ int daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); char trans[1]; doublereal normx, normy, myhugeval, prev_dz_z__; extern doublereal dlamch_(char *); doublereal yk; extern /* Subroutine */ int dgbtrs_(char *, integer *, integer *, integer *, integer *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); doublereal final_dx_x__; extern /* Subroutine */ int dla_wwaddw_(integer *, doublereal *, doublereal *, doublereal *); doublereal final_dz_z__, normdx; extern /* Character */ VOID chla_transtype_(char *, integer *); doublereal prevnormdx; integer cnt; doublereal dyk, eps; integer x_state__, z_state__; doublereal incr_thresh__; /* -- LAPACK computational routine (version 3.7.1) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2017 */ /* ===================================================================== */ /* Parameter adjustments */ err_bnds_comp_dim1 = *nrhs; err_bnds_comp_offset = 1 + err_bnds_comp_dim1 * 1; err_bnds_comp__ -= err_bnds_comp_offset; err_bnds_norm_dim1 = *nrhs; err_bnds_norm_offset = 1 + err_bnds_norm_dim1 * 1; err_bnds_norm__ -= err_bnds_norm_offset; ab_dim1 = *ldab; ab_offset = 1 + ab_dim1 * 1; ab -= ab_offset; afb_dim1 = *ldafb; afb_offset = 1 + afb_dim1 * 1; afb -= afb_offset; --ipiv; --c__; b_dim1 = *ldb; b_offset = 1 + b_dim1 * 1; b -= b_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1 * 1; y -= y_offset; --berr_out__; --res; --ayb; --dy; --y_tail__; /* Function Body */ if (*info != 0) { return 0; } chla_transtype_(ch__1, trans_type__); *(unsigned char *)trans = *(unsigned char *)&ch__1[0]; eps = dlamch_("Epsilon"); myhugeval = dlamch_("Overflow"); /* Force MYHUGEVAL to Inf */ myhugeval *= myhugeval; /* Using MYHUGEVAL may lead to spurious underflows. */ incr_thresh__ = (doublereal) (*n) * eps; m = *kl + *ku + 1; i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { y_prec_state__ = 1; if (y_prec_state__ == 2) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { y_tail__[i__] = 0.; } } dxrat = 0.; dxratmax = 0.; dzrat = 0.; dzratmax = 0.; final_dx_x__ = myhugeval; final_dz_z__ = myhugeval; prevnormdx = myhugeval; prev_dz_z__ = myhugeval; dz_z__ = myhugeval; dx_x__ = myhugeval; x_state__ = 1; z_state__ = 0; incr_prec__ = FALSE_; i__2 = *ithresh; for (cnt = 1; cnt <= i__2; ++cnt) { /* Compute residual RES = B_s - op(A_s) * Y, */ /* op(A) = A, A**T, or A**H depending on TRANS (and type). */ dcopy_(n, &b[j * b_dim1 + 1], &c__1, &res[1], &c__1); if (y_prec_state__ == 0) { dgbmv_(trans, &m, n, kl, ku, &c_b6, &ab[ab_offset], ldab, &y[ j * y_dim1 + 1], &c__1, &c_b8, &res[1], &c__1); } else if (y_prec_state__ == 1) { blas_dgbmv_x__(trans_type__, n, n, kl, ku, &c_b6, &ab[ ab_offset], ldab, &y[j * y_dim1 + 1], &c__1, &c_b8, & res[1], &c__1, prec_type__); } else { blas_dgbmv2_x__(trans_type__, n, n, kl, ku, &c_b6, &ab[ ab_offset], ldab, &y[j * y_dim1 + 1], &y_tail__[1], & c__1, &c_b8, &res[1], &c__1, prec_type__); } /* XXX: RES is no longer needed. */ dcopy_(n, &res[1], &c__1, &dy[1], &c__1); dgbtrs_(trans, n, kl, ku, &c__1, &afb[afb_offset], ldafb, &ipiv[1] , &dy[1], n, info); /* Calculate relative changes DX_X, DZ_Z and ratios DXRAT, DZRAT. */ normx = 0.; normy = 0.; normdx = 0.; dz_z__ = 0.; ymin = myhugeval; i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { yk = (d__1 = y[i__ + j * y_dim1], abs(d__1)); dyk = (d__1 = dy[i__], abs(d__1)); if (yk != 0.) { /* Computing MAX */ d__1 = dz_z__, d__2 = dyk / yk; dz_z__ = f2cmax(d__1,d__2); } else if (dyk != 0.) { dz_z__ = myhugeval; } ymin = f2cmin(ymin,yk); normy = f2cmax(normy,yk); if (*colequ) { /* Computing MAX */ d__1 = normx, d__2 = yk * c__[i__]; normx = f2cmax(d__1,d__2); /* Computing MAX */ d__1 = normdx, d__2 = dyk * c__[i__]; normdx = f2cmax(d__1,d__2); } else { normx = normy; normdx = f2cmax(normdx,dyk); } } if (normx != 0.) { dx_x__ = normdx / normx; } else if (normdx == 0.) { dx_x__ = 0.; } else { dx_x__ = myhugeval; } dxrat = normdx / prevnormdx; dzrat = dz_z__ / prev_dz_z__; /* Check termination criteria. */ if (! (*ignore_cwise__) && ymin * *rcond < incr_thresh__ * normy && y_prec_state__ < 2) { incr_prec__ = TRUE_; } if (x_state__ == 3 && dxrat <= *rthresh) { x_state__ = 1; } if (x_state__ == 1) { if (dx_x__ <= eps) { x_state__ = 2; } else if (dxrat > *rthresh) { if (y_prec_state__ != 2) { incr_prec__ = TRUE_; } else { x_state__ = 3; } } else { if (dxrat > dxratmax) { dxratmax = dxrat; } } if (x_state__ > 1) { final_dx_x__ = dx_x__; } } if (z_state__ == 0 && dz_z__ <= *dz_ub__) { z_state__ = 1; } if (z_state__ == 3 && dzrat <= *rthresh) { z_state__ = 1; } if (z_state__ == 1) { if (dz_z__ <= eps) { z_state__ = 2; } else if (dz_z__ > *dz_ub__) { z_state__ = 0; dzratmax = 0.; final_dz_z__ = myhugeval; } else if (dzrat > *rthresh) { if (y_prec_state__ != 2) { incr_prec__ = TRUE_; } else { z_state__ = 3; } } else { if (dzrat > dzratmax) { dzratmax = dzrat; } } if (z_state__ > 1) { final_dz_z__ = dz_z__; } } /* Exit if both normwise and componentwise stopped working, */ /* but if componentwise is unstable, let it go at least two */ /* iterations. */ if (x_state__ != 1) { if (*ignore_cwise__) { goto L666; } if (z_state__ == 3 || z_state__ == 2) { goto L666; } if (z_state__ == 0 && cnt > 1) { goto L666; } } if (incr_prec__) { incr_prec__ = FALSE_; ++y_prec_state__; i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { y_tail__[i__] = 0.; } } prevnormdx = normdx; prev_dz_z__ = dz_z__; /* Update soluton. */ if (y_prec_state__ < 2) { daxpy_(n, &c_b8, &dy[1], &c__1, &y[j * y_dim1 + 1], &c__1); } else { dla_wwaddw_(n, &y[j * y_dim1 + 1], &y_tail__[1], &dy[1]); } } /* Target of "IF (Z_STOP .AND. X_STOP)". Sun's f77 won't CALL MYEXIT. */ L666: /* Set final_* when cnt hits ithresh. */ if (x_state__ == 1) { final_dx_x__ = dx_x__; } if (z_state__ == 1) { final_dz_z__ = dz_z__; } /* Compute error bounds. */ if (*n_norms__ >= 1) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = final_dx_x__ / ( 1 - dxratmax); } if (*n_norms__ >= 2) { err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = final_dz_z__ / ( 1 - dzratmax); } /* Compute componentwise relative backward error from formula */ /* f2cmax(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) ) */ /* where abs(Z) is the componentwise absolute value of the matrix */ /* or vector Z. */ /* Compute residual RES = B_s - op(A_s) * Y, */ /* op(A) = A, A**T, or A**H depending on TRANS (and type). */ dcopy_(n, &b[j * b_dim1 + 1], &c__1, &res[1], &c__1); dgbmv_(trans, n, n, kl, ku, &c_b6, &ab[ab_offset], ldab, &y[j * y_dim1 + 1], &c__1, &c_b8, &res[1], &c__1); i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { ayb[i__] = (d__1 = b[i__ + j * b_dim1], abs(d__1)); } /* Compute abs(op(A_s))*abs(Y) + abs(B_s). */ dla_gbamv_(trans_type__, n, n, kl, ku, &c_b8, &ab[ab_offset], ldab, & y[j * y_dim1 + 1], &c__1, &c_b8, &ayb[1], &c__1); dla_lin_berr_(n, n, &c__1, &res[1], &ayb[1], &berr_out__[j]); /* End of loop for each RHS */ } return 0; } /* dla_gbrfsx_extended__ */
the_stack_data/218894189.c
#include <stdio.h> int main (void) { int a = 20; int *ptr = &a; printf("ptr: %p\n", ptr); printf("a: %d\n", a); ptr++; /* pointer'ı bir sonraki bloğa kaydırdık. */ printf("ptr: %p\n", ptr); printf("*ptr: %d\n", *ptr); ptr = &a; /* pointer'ımız tekrar a'yı göstersin. */ *ptr = 48; /* bu sefer pointer'ın gösterdiği değer ile oynuyoruz. */ printf("*ptr: %d\n", *ptr); printf("a: %d\n", a); /* pointer'ımız a'yı gösteriyordu. pointer'ın değeri ile oynayınca a ile de oynamış olduk. */ return 0; }
the_stack_data/161081111.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> //function prototype int minimum(int x, int y); int maximum(int x, int y); int multiply(int x, int y); //function main begins program execution int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; }//end function main //function implementation //function to find the minimum int minimum(int x, int y) { if( x > y ) { return y; } else { return x; } } //function to find the maximim int maximum(int x, int y) { if( x > y ) { return x; } else { return y; } } //function to multiply the two numbers int multiply(int x, int y) { return x * y; }
the_stack_data/220454372.c
/* { dg-do compile } */ /* { dg-options "-O2 -march=k8" } */ /* { dg-final { scan-assembler "sbb" } } */ /* This conditional move is fastest to be done using sbb. */ int t(unsigned int a, unsigned int b) { return (a<=b?5:-5); }
the_stack_data/156393759.c
typedef enum {false,true} bool; extern int __VERIFIER_nondet_int(void); int main() { int x; int y; int ytmp; int res; x = __VERIFIER_nondet_int(); y = __VERIFIER_nondet_int(); res = 0; while (x >= y && y > 0) { ytmp = y; while (ytmp != 0) { if (ytmp > 0) { ytmp = ytmp - 1; x = x - 1; } else { ytmp = ytmp + 1; x = x + 1; } } res = res + 1; } return 0; }
the_stack_data/68889057.c
/**************************************************************************** * * gxfgen.c * * Generate feature registry data for gxv `feat' validator. * This program is derived from gxfeatreg.c in gxlayout. * * Copyright (C) 2004-2022 by * Masatake YAMATO and Redhat K.K. * * This file may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /**************************************************************************** * * gxfeatreg.c * * Database of font features pre-defined by Apple Computer, Inc. * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html * (body). * * Copyright 2003 by * Masatake YAMATO and Redhat K.K. * * This file may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /**************************************************************************** * * Development of gxfeatreg.c is supported by * Information-technology Promotion Agency, Japan. * */ /**************************************************************************** * * This file is compiled as a stand-alone executable. * This file is never compiled into `libfreetype2'. * The output of this file is used in `gxvfeat.c'. * ----------------------------------------------------------------------- * Compile: gcc `pkg-config --cflags freetype2` gxvfgen.c -o gxvfgen * Run: ./gxvfgen > tmp.c * */ /******************************************************************** * WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING */ /* * If you add a new setting to a feature, check the number of settings * in the feature. If the number is greater than the value defined as * FEATREG_MAX_SETTING, update the value. */ #define FEATREG_MAX_SETTING 12 /******************************************************************** * WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING */ #include <stdio.h> #include <string.h> /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define APPLE_RESERVED "Apple Reserved" #define APPLE_RESERVED_LENGTH 14 typedef struct GX_Feature_RegistryRec_ { const char* feat_name; char exclusive; char* setting_name[FEATREG_MAX_SETTING]; } GX_Feature_RegistryRec; #define EMPTYFEAT {0, 0, {NULL}} static GX_Feature_RegistryRec featreg_table[] = { { /* 0 */ "All Typographic Features", 0, { "All Type Features", NULL } }, { /* 1 */ "Ligatures", 0, { "Required Ligatures", "Common Ligatures", "Rare Ligatures", "Logos", "Rebus Pictures", "Diphthong Ligatures", "Squared Ligatures", "Squared Ligatures, Abbreviated", NULL } }, { /* 2 */ "Cursive Connection", 1, { "Unconnected", "Partially Connected", "Cursive", NULL } }, { /* 3 */ "Letter Case", 1, { "Upper & Lower Case", "All Caps", "All Lower Case", "Small Caps", "Initial Caps", "Initial Caps & Small Caps", NULL } }, { /* 4 */ "Vertical Substitution", 0, { /* "Substitute Vertical Forms", */ "Turns on the feature", NULL } }, { /* 5 */ "Linguistic Rearrangement", 0, { /* "Linguistic Rearrangement", */ "Turns on the feature", NULL } }, { /* 6 */ "Number Spacing", 1, { "Monospaced Numbers", "Proportional Numbers", NULL } }, { /* 7 */ APPLE_RESERVED " 1", 0, {NULL} }, { /* 8 */ "Smart Swashes", 0, { "Word Initial Swashes", "Word Final Swashes", "Line Initial Swashes", "Line Final Swashes", "Non-Final Swashes", NULL } }, { /* 9 */ "Diacritics", 1, { "Show Diacritics", "Hide Diacritics", "Decompose Diacritics", NULL } }, { /* 10 */ "Vertical Position", 1, { /* "Normal Position", */ "No Vertical Position", "Superiors", "Inferiors", "Ordinals", NULL } }, { /* 11 */ "Fractions", 1, { "No Fractions", "Vertical Fractions", "Diagonal Fractions", NULL } }, { /* 12 */ APPLE_RESERVED " 2", 0, {NULL} }, { /* 13 */ "Overlapping Characters", 0, { /* "Prevent Overlap", */ "Turns on the feature", NULL } }, { /* 14 */ "Typographic Extras", 0, { "Hyphens to Em Dash", "Hyphens to En Dash", "Unslashed Zero", "Form Interrobang", "Smart Quotes", "Periods to Ellipsis", NULL } }, { /* 15 */ "Mathematical Extras", 0, { "Hyphens to Minus", "Asterisk to Multiply", "Slash to Divide", "Inequality Ligatures", "Exponents", NULL } }, { /* 16 */ "Ornament Sets", 1, { "No Ornaments", "Dingbats", "Pi Characters", "Fleurons", "Decorative Borders", "International Symbols", "Math Symbols", NULL } }, { /* 17 */ "Character Alternatives", 1, { "No Alternates", /* TODO */ NULL } }, { /* 18 */ "Design Complexity", 1, { "Design Level 1", "Design Level 2", "Design Level 3", "Design Level 4", "Design Level 5", /* TODO */ NULL } }, { /* 19 */ "Style Options", 1, { "No Style Options", "Display Text", "Engraved Text", "Illuminated Caps", "Tilling Caps", "Tall Caps", NULL } }, { /* 20 */ "Character Shape", 1, { "Traditional Characters", "Simplified Characters", "JIS 1978 Characters", "JIS 1983 Characters", "JIS 1990 Characters", "Traditional Characters, Alternative Set 1", "Traditional Characters, Alternative Set 2", "Traditional Characters, Alternative Set 3", "Traditional Characters, Alternative Set 4", "Traditional Characters, Alternative Set 5", "Expert Characters", NULL /* count => 12 */ } }, { /* 21 */ "Number Case", 1, { "Lower Case Numbers", "Upper Case Numbers", NULL } }, { /* 22 */ "Text Spacing", 1, { "Proportional", "Monospaced", "Half-width", "Normal", NULL } }, /* Here after Newer */ { /* 23 */ "Transliteration", 1, { "No Transliteration", "Hanja To Hangul", "Hiragana to Katakana", "Katakana to Hiragana", "Kana to Romanization", "Romanization to Hiragana", "Romanization to Katakana", "Hanja to Hangul, Alternative Set 1", "Hanja to Hangul, Alternative Set 2", "Hanja to Hangul, Alternative Set 3", NULL } }, { /* 24 */ "Annotation", 1, { "No Annotation", "Box Annotation", "Rounded Box Annotation", "Circle Annotation", "Inverted Circle Annotation", "Parenthesis Annotation", "Period Annotation", "Roman Numeral Annotation", "Diamond Annotation", NULL } }, { /* 25 */ "Kana Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 26 */ "Ideographic Spacing", 1, { "Full Width", "Proportional", NULL } }, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 27-30 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 31-35 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 36-40 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 40-45 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 46-50 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 51-55 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 56-60 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 61-65 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 66-70 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 71-75 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 76-80 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 81-85 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 86-90 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 91-95 */ EMPTYFEAT, EMPTYFEAT, EMPTYFEAT, /* 96-98 */ EMPTYFEAT, /* 99 */ { /* 100 => 22 */ "Text Spacing", 1, { "Proportional", "Monospaced", "Half-width", "Normal", NULL } }, { /* 101 => 25 */ "Kana Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 102 => 26 */ "Ideographic Spacing", 1, { "Full Width", "Proportional", NULL } }, { /* 103 */ "CJK Roman Spacing", 1, { "Half-width", "Proportional", "Default Roman", "Full-width Roman", NULL } }, { /* 104 => 1 */ "All Typographic Features", 0, { "All Type Features", NULL } } }; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Generator *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ int main( void ) { int i; printf( " {\n" ); printf( " /* Generated from %s */\n", __FILE__ ); for ( i = 0; i < sizeof ( featreg_table ) / sizeof ( GX_Feature_RegistryRec ); i++ ) { const char* feat_name; int nSettings; feat_name = featreg_table[i].feat_name; for ( nSettings = 0; featreg_table[i].setting_name[nSettings]; nSettings++) ; /* Do nothing */ printf( " {%1d, %1d, %1d, %2d}, /* %s */\n", feat_name ? 1 : 0, ( feat_name && ( ft_strncmp( feat_name, APPLE_RESERVED, APPLE_RESERVED_LENGTH ) == 0 ) ) ? 1 : 0, featreg_table[i].exclusive ? 1 : 0, nSettings, feat_name ? feat_name : "__EMPTY__" ); } printf( " };\n" ); return 0; } /* END */
the_stack_data/161080299.c
/* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer volt_max the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int ZEXPORT uncompress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { z_stream stream; int err; stream.next_in = (z_const Bytef *)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; }
the_stack_data/53753.c
#include<stdio.h> //Input Output #include<math.h> #define PI 3.1416 //Definiendo una constante void main(){ float area, radio; // Declarando variables de tipo flotante radio = 5; //Asignando valor a variable radio area = PI * pow(5,2); //Asignando resultado de la operacion variable printf("Area\n"); //Imprimiendo Titulo // Imprimiendo resultado printf("%s%f\n\n", "Area de Circulo con radio 5: %f", area); }
the_stack_data/74015.c
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // SPDX-FileCopyrightText: 2014-2017 Université Grenoble Alpes // // SPDX-License-Identifier: Apache-2.0 void assert(int cond) { if (!cond) { ERROR: return; } } extern int __VERIFIER_nondet_int(); int main() { char in[11]; int i = 0; int j = 0; int c = 0; while (__VERIFIER_nondet_int()) { j = c; i = i * 10U + j; c = in[i]; } if (!(i>=0)) { goto ERROR; } return 0; ERROR: return -1; }
the_stack_data/179830150.c
#include <stdio.h> int main() { double euros; double dollars; dollars = 100; euros = dollars * 0.92; printf("%lf dollars are %lf euros.\n", dollars, euros); return 0; }
the_stack_data/87636974.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <sys/time.h> #define TOLERANCE 0.001 /* termination criterion */ #define MAGIC 0.8 /* magic factor */ int even (int i) { return !(i & 1); } double stencil (double** G, int row, int col) { return (G[row-1][col] + G[row+1][col] + G[row][col-1] + G[row][col+1] ) / 4.0; } void alloc_grid(double ***Gptr, int N) { int i; double** G = (double**)malloc(N*sizeof(double*)); if ( G == 0 ) { fprintf(stderr, "malloc failed\n"); exit(42); } for (i = 0; i<N; i++) { /* malloc the own range plus one more line */ /* of overlap on each side */ G[i] = (double*)malloc(N*sizeof(double)); if ( G[i] == 0 ) { fprintf(stderr, "malloc failed\n"); exit(42); } } *Gptr = G; } void init_grid(double **G, int N) { int i, j; /* initialize the grid */ for (i = 0; i < N; i++){ for (j = 0; j < N; j++){ if (i == 0) G[i][j] = 4.56; else if (i == N-1) G[i][j] = 9.85; else if (j == 0) G[i][j] = 7.32; else if (j == N-1) G[i][j] = 6.88; else G[i][j] = 0.0; } } } void print_grid(double** G, int N) { int i, j; for ( i = 1 ; i < N-1 ; i++ ) { for ( j = 1 ; j < N-1 ; j++ ) { printf("%10.3f ", G[i][j]); } printf("\n"); } } int main (int argc, char *argv[]) { int N; /* problem size */ int ncol,nrow; /* number of rows and columns */ double Gnew,r,omega, /* some float values */ stopdiff,maxdiff,diff; /* differences btw grid points in iters */ double **G; /* the grid */ int i,j,phase,iteration; /* counters */ struct timeval start; struct timeval end; double time; int print = 0; /* set up problem size */ N = 100; for(i=1; i<argc; i++) { if(!strcmp(argv[i], "-print")) { print = 1; } else { N = atoi(argv[i]); } } fprintf(stderr, "Running %d x %d SOR\n", N, N); N += 2; /* add the two border lines */ /* finally N*N (from argv) array points will be computed */ /* set up a quadratic grid */ ncol = nrow = N; r = 0.5 * ( cos( M_PI / ncol ) + cos( M_PI / nrow ) ); omega = 2.0 / ( 1 + sqrt( 1 - r * r ) ); stopdiff = TOLERANCE / ( 2.0 - omega ); omega *= MAGIC; alloc_grid(&G, N); init_grid(G, N); if(gettimeofday(&start, 0) != 0) { fprintf(stderr, "could not do timing\n"); exit(1); } /* now the "real" computation */ iteration = 0; do { maxdiff = 0.0; for ( phase = 0; phase < 2 ; phase++){ for ( i = 1 ; i < N-1 ; i++ ){ for ( j = 1 + (even(i) ^ phase); j < N-1 ; j += 2 ){ Gnew = stencil(G,i,j); diff = fabs(Gnew - G[i][j]); if ( diff > maxdiff ) maxdiff = diff; G[i][j] = G[i][j] + omega * (Gnew-G[i][j]); } } } iteration++; } while (maxdiff > stopdiff); if(gettimeofday(&end, 0) != 0) { fprintf(stderr, "could not do timing\n"); exit(1); } time = (end.tv_sec + (end.tv_usec / 1000000.0)) - (start.tv_sec + (start.tv_usec / 1000000.0)); fprintf(stderr, "SOR took %10.3f seconds\n", time); printf("Used %5d iterations, diff is %10.6f, allowed diff is %10.6f\n", iteration,maxdiff,stopdiff); if(print == 1) { print_grid(G, N); } return 0; }
the_stack_data/869578.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/fdtd-2d/kernel.c' as parsed by frontend compiler rose void kernel_fdtd_2d(int tmax, int nx, int ny, double ex[1000 + 0][1200 + 0], double ey[1000 + 0][1200 + 0], double hz[1000 + 0][1200 + 0], double _fict_[500 + 0]) { int t10; int t8; int t6; int t4; int t2; for (t2 = 0; t2 <= tmax - 1; t2 += 1) { for (t4 = 0; t4 <= ny - 1; t4 += 1) ey[0][t4] = _fict_[t2]; for (t4 = 1; t4 <= nx - 1; t4 += 30) for (t6 = t4; t6 <= (t4 + 29 < nx - 1 ? t4 + 29 : nx - 1); t6 += 1) for (t8 = 0; t8 <= ny - 1; t8 += 30) for (t10 = t8; t10 <= (ny - 1 < t8 + 29 ? ny - 1 : t8 + 29); t10 += 1) ey[t6][t10] = ey[t6][t10] - 0.5 * (hz[t6][t10] - hz[t6 - 1][t10]); for (t4 = 0; t4 <= nx - 1; t4 += 30) for (t6 = t4; t6 <= (t4 + 29 < nx - 1 ? t4 + 29 : nx - 1); t6 += 1) for (t8 = 1; t8 <= ny - 1; t8 += 30) for (t10 = t8; t10 <= (ny - 1 < t8 + 29 ? ny - 1 : t8 + 29); t10 += 1) ex[t6][t10] = ex[t6][t10] - 0.5 * (hz[t6][t10] - hz[t6][t10 - 1]); for (t4 = 0; t4 <= nx - 2; t4 += 30) for (t6 = t4; t6 <= (t4 + 29 < nx - 2 ? t4 + 29 : nx - 2); t6 += 1) for (t8 = 0; t8 <= ny - 2; t8 += 30) for (t10 = t8; t10 <= (ny - 2 < t8 + 29 ? ny - 2 : t8 + 29); t10 += 1) hz[t6][t10] = hz[t6][t10] - 0.69999999999999996 * (ex[t6][t10 + 1] - ex[t6][t10] + ey[t6 + 1][t10] - ey[t6][t10]); } }
the_stack_data/23575448.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define PORT 1234 static int listen_new(unsigned ip, unsigned short port) { struct sockaddr_in ser; int listen_fd, rv; ser.sin_family = AF_INET; ser.sin_addr.s_addr = ip; ser.sin_port = port; listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (listen_fd == -1) return -1; rv = bind(listen_fd, (struct sockaddr *)&ser, sizeof(struct sockaddr_in)); if (rv == -1) return -1; if (listen(listen_fd, 0) == -1) { close(listen_fd); return -1; } return listen_fd; } int file2mem(const char *fname, char **p, int *size) { char *mem = NULL; struct stat sb; int fd = -1; if(stat(fname, &sb) == -1) { perror("stat"); return -1; } mem = (char *)malloc(sb.st_size); if (!mem) { perror("malloc"); return -1; } fd = open(fname, O_RDONLY, 0644); if (fd == -1) { perror("open"); free(mem); return -1; } read(fd, mem, sb.st_size); *p = mem; *size = sb.st_size; close(fd); return 0; } #define RSP_BODY_MEDIA "HTTP/1.0 200 OK\r\n" \ "Content-Type: audio/mpeg\r\n" \ "Content-Length: %d\r\n" \ "Connection: close\r\n\r\n" #define RSP_BODY_FILE "HTTP/1.0 200 OK\r\n" \ "Content-Length: %d\r\n" \ "Connection: close\r\n\r\n" void *do_work(void *argv) { char header[4096] = ""; char rsp[4096] = ""; char path[1024] = "."; int connfd = -1; int rv = -1; char *pos, *p; int size = 0; connfd = (intptr_t)argv; rv = recv(connfd, header, sizeof(header) - 1, MSG_PEEK); if (rv == -1) { printf("recv peek fail %s\n", strerror(errno)); goto done; } printf("===%s===\n", header); if (strncmp("GET", header, 3)) { printf("header is %s\n", header); goto done; } pos = strstr(header, "\r\n\r\n"); if (pos == NULL) { printf("not found \\r\\n\\r\\n \n"); goto done; } /*read */ rv = recv(connfd, header, pos - header + 4, 0); sscanf(header, "GET %[^ ]", path + 1); printf("path(%s)\n", path); rv = file2mem(path, &p, &size); if (rv == -1) { printf("file2mem fail\n"); return 0; } if (strncmp(path + strlen(path) - 4, ".mp3", 4) == 0) { printf("mp3 type"); rv = snprintf(rsp, sizeof(rsp) - 1, RSP_BODY_MEDIA, size); } else { rv = snprintf(rsp, sizeof(rsp) - 1, RSP_BODY_FILE, size); } /*write rsp*/ write(connfd, rsp, rv); /*write body*/ write(connfd, p, size); done: close(connfd); return 0; } void main_loop() { int listen_fd = listen_new(0, htons(PORT)); int connfd = -1; if (listen_fd == -1) { printf("listen error\n"); return ; } printf("listen port = %d\n", PORT); for (;;) { connfd = accept(listen_fd, NULL, NULL); printf("connfd = %d\n", connfd); do_work((void *)(intptr_t)connfd); } } int main(int argc, char **argv) { main_loop(); return 0; }
the_stack_data/167331917.c
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ /* * See COPYRIGHT in top-level directory. */ #include <assert.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define NUM_TASKS 50000 #define NUM_REPS 1 int o = 0; void sscal(float value, float *a) { *a = *a * value; } void na(float value) { o++; } void presscal(float value, float *a) { #pragma omp task { sscal(value, a); } #pragma omp task { na(value); } } int main(int argc, char *argv[]) { int i, r, nthreads; double *time, avg_time = 0.0; char *str, *endptr; float *a; double time2 = 0.0; #pragma omp parallel { #pragma omp master { nthreads = omp_get_num_threads(); } } if (argc > 1) { str = argv[1]; } int ntasks = argc > 1 ? strtoll(str, &endptr, 10) : NUM_TASKS; if (ntasks < nthreads) ntasks = nthreads; int rep = (argc > 2) ? atoi(argv[2]) : NUM_REPS; time = malloc(sizeof(double) * rep); a = malloc(sizeof(float) * ntasks); for (i = 0; i < ntasks; i++) { a[i] = i + 100.0f; } for (r = 0; r < rep; r++) { time[r] = omp_get_wtime(); #pragma omp parallel { #pragma omp single { time2 = omp_get_wtime(); for (i = 0; i < ntasks; i++) { #pragma omp task firstprivate(i) { presscal(0.9f, &a[i]); } } time2 = omp_get_wtime() - time2; } } time[r] = omp_get_wtime() - time[r]; avg_time += time[r]; } // TODO: Just works with one repetition for (i = 0; i < ntasks; i++) { if (a[i] != (i + 100.0f) * 0.9f) { printf("error: a[%d]=%2.f expected %2.f\n", i, a[i], (i + 100.0f) * 0.9f); } } avg_time /= rep; printf("nthreads: %d\nntasks: %d\nTime(s):%f\nCreation Time: %f\n", nthreads, ntasks, avg_time, time2); printf("o=%d deberia valer %d\n", o, ntasks); return EXIT_SUCCESS; }
the_stack_data/50988.c
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <unistd.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> volatile sig_atomic_t stop_flag = 0; void sigterm_handler(int sig) { stop_flag = 1; } int start_server(in_port_t port) { int sock = socket(AF_INET, SOCK_STREAM, 0); int flags = fcntl(sock, F_GETFL); fcntl(sock, F_SETFL, flags | O_NONBLOCK); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = port; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(sock, (struct sockaddr*)&addr, sizeof(addr)); listen(sock, SOMAXCONN); signal(SIGPIPE, SIG_IGN); signal(SIGTERM, sigterm_handler); signal(SIGINT, sigterm_handler); return sock; } void respond(int client, char* root) { const int buff_size = 8192; char buff[buff_size]; read(client, buff, buff_size); int p = strstr(buff, "HTTP/1.1") - buff - 5; char file_name[buff_size]; strncpy(file_name, buff + 4, buff_size); file_name[p] = 0; char path[buff_size]; strcpy(path, root); strcat(path, "/"); strcat(path, file_name); int fd = open(path, O_RDONLY); if (fd == -1) { if (access(path, F_OK) == -1) dprintf(client, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"); else if (access(path, R_OK) == -1) dprintf(client, "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"); return; } struct stat st; lstat(path, &st); dprintf(client, "HTTP/1.1 200 OK\r\n"); dprintf(client, "Content-Length: %ld\r\n\r\n", st.st_size); int n = 0; while ((n = read(fd, buff, buff_size)) > 0) write(client, buff, n); } int main(int argc, char* argv[]) { int sock = start_server(htons(atoi(argv[1]))); struct sockaddr_in cli_addr; socklen_t addr_len = sizeof(cli_addr); while (!stop_flag) { int client = accept(sock, (struct sockaddr*)&cli_addr, &addr_len); if (client == -1) continue; respond(client, argv[2]); shutdown(client, SHUT_RDWR); close(client); } close(sock); return 0; }
the_stack_data/96800.c
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9.0 -emit-llvm -O1 -mdisable-tail-calls -o - < %s | FileCheck %s typedef struct List { struct List *next; int data; } List; // CHECK-LABEL: define %struct.List* @find List *find(List *head, int data) { if (!head) return 0; if (head->data == data) return head; // CHECK: call %struct.List* @find return find(head->next, data); }
the_stack_data/39042.c
/*numPass=8, numTotal=8 Verdict:ACCEPTED, Visibility:1, Input:"3 4 0 1 1 0 1 0 0 1 1 0 2 3", ExpOutput:"2 1 3 ", Output:"2 1 3" Verdict:ACCEPTED, Visibility:1, Input:"5 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1", ExpOutput:"5 1 1 ", Output:"5 1 1" Verdict:ACCEPTED, Visibility:1, Input:"2 2 0 2 3 4", ExpOutput:"0 -1 -1 ", Output:"0 -1 -1" Verdict:ACCEPTED, Visibility:1, Input:"1 1 0", ExpOutput:"0 -1 -1 ", Output:"0 -1 -1" Verdict:ACCEPTED, Visibility:1, Input:"5 5 3 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 23 5 5 5 -1 2 3 4 5", ExpOutput:"1 2 1 ", Output:"1 2 1" Verdict:ACCEPTED, Visibility:0, Input:"5 2 1 0 0 1 0 0 1 0 0 1", ExpOutput:"2 1 1 ", Output:"2 1 1" Verdict:ACCEPTED, Visibility:0, Input:"1 1 1", ExpOutput:"1 1 1 ", Output:"1 1 1" Verdict:ACCEPTED, Visibility:0, Input:"10 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0", ExpOutput:"3 8 1 ", Output:"3 8 1" */ #include <stdio.h> int good(int a[20][20],int i,int j,int m,int n,int d);//This is the prototype for good() which will check whether the square matrix of dimension d*d with a[i][j] as the top left element is an identity matrix,if yes,then it will return d else 0 int good(int a[20][20],int i,int j,int m,int n,int d){ int p,q,check=-1; for(p=0;p<=d;p++) for(q=0;q<=d;q++) if(!(((p==q)&&(a[i+p][j+q]==1))||((p!=q)&&(a[i+p][j+q]==0)))){ check=0; return 0; break; } if(check==-1) return d+1; } int main(){ int a[20][20],m,n,i,j,d,g=0,l,i1,j1; scanf("%d %d",&m,&n); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d ",&a[i][j]); for(i=0;i<m;i++) for(j=0;j<n;j++){ if(a[i][j]==1){//good will be called only when a[i][j]=1 for(l=0;(i+l)<m&&(j+l)<n;l++){ d=good(a,i,j,m,n,l); if(d!=0){ if(d>g){ g=d; i1=i; j1=j; } else if(g==d){ if((i<i1)||((i==i1)&&(j<j1))) i1=i;j1=j; } } } } } if(g==0){ printf("%d %d %d",g,-1,-1); } else{ printf("%d %d %d",g,i1+1,j1+1); } return 0; }
the_stack_data/1061111.c
#include<sys/syscall.h> #include<stdio.h> #include <string.h> void main() { char * hello_with_syscall = "Hello World with syscall\n"; char * hello_without_syscall = "Hello World without syscall\n"; char * hello_with_printf = "Hello World with printf\n"; write( 1, hello_without_syscall, strlen( hello_without_syscall )); syscall( SYS_write, 1, hello_with_syscall, strlen( hello_with_syscall )); printf( "%s", hello_with_printf ); }
the_stack_data/551411.c
#include <stdio.h> int main() { double X,Y,Z,C; int N; scanf("%d",&N); for(C = 1;C <= N;C++){ scanf("%lf%lf%lf",&X,&Y,&Z); printf("%.1lf\n",((X*2)+(Y*3)+(Z*5))/10); } return 0; }
the_stack_data/40762302.c
/************************************************************ * Nom : export_bulle.c * Langage : C * Auteur : Guillaume MICHON 21/08/2009 (v 1.0 - Création initiale) * Modif. : Guillaume MICHON 05/10/2009 (v 1.1 - Fournit le ruid en paramètre supplémentaire au script suivant) * Modif. : Guillaume MICHON 24/02/2010 (v 1.2) * * Ajout message d'erreur en cas d'échec du execvp * * Correction bug du new_argv : doit se terminer par un NULL * Modif. : Guillaume MICHON 09/09/2010 (v 1.3) * * Correction bug "!" * * Description : * Script Client pour SE Transfert en bulle internet * Wrapper pour le setuid * * Paramètres & retour : Voir le script appelé ***********************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { int i; char **new_argv; /* Changement des uid d'exécution */ uid_t ruid; /* Réel */ uid_t euid; /* Effectif */ uid_t suid; /* Sauvé */ getresuid(&ruid, &euid, &suid); setreuid(geteuid(),geteuid()); setregid(getegid(),getegid()); /* Ajout du ruid dans le tableau des arguments */ new_argv = calloc(argc+2, sizeof(char*)); new_argv[0] = calloc(15, sizeof(char)); new_argv[1] = calloc(10, sizeof(char)); sprintf(new_argv[0], "export_bulle.pl"); sprintf(new_argv[1], "%d", ruid); for (i=1 ; i<argc ; i++) { new_argv[i+1] = calloc(strlen(argv[i])+1, sizeof(char)); strcpy(new_argv[i+1], argv[i]); } new_argv[argc+1] = (char *)NULL; if (execvp("export_bulle.pl", new_argv) == -1) { perror("Impossible de lancer export_bulle.pl "); return 3; } }
the_stack_data/28264036.c
/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ /* $Id$ */ #include <ctype.h> /* We do not use strtol here for backwards compatibility in behaviour on overflow. */ int atoi(register const char *nptr) { int total = 0; int minus = 0; while (isspace(*nptr)) nptr++; if (*nptr == '+') nptr++; else if (*nptr == '-') { minus = 1; nptr++; } while (isdigit(*nptr)) { total *= 10; total += (*nptr++ - '0'); } return minus ? -total : total; }
the_stack_data/150142568.c
#include<stdio.h> typedef signed int T; T f(T(T)); T f(T a(T)) { T b; return 1; } T f1(T(x)); T f1(T x) { return x; } int g(int x) { T:; T y; T T; T=1; return 1; } void h() { for(int T; ;) if(1) ; T *x; x = 0; } void h2() { for(int T; ;) if(1) ; else T; } struct S { const T:3; unsigned T:3; const T:3; }; struct S stru; void i() { struct S s = stru; s.T = -1; if(s.T < 0) printf("ERROR i\n"); } /* These ones are parsed correctly, but rejected by the elaborator. */ /* void j() { */ /* typedef int I; */ /* {sizeof(enum{I=2}); return I;} */ /* {do sizeof(enum{I=2}); while((I)1);} */ /* {if(1) return sizeof(enum{I=2}); */ /* else return (I)1;} */ /* {if(sizeof(enum{I=2})) return I; */ /* else return I;} */ /* {sizeof(enum{I=2})+I;} */ /* {for(int i = sizeof(enum{I=2}); I; I) I; (I)1;} */ /* } */ /* int f2(enum{I=2} x) { */ /* return I; */ /* } */ /* void k(A, B) */ /* int B; */ /* int A[B]; */ /* { } */ /* int l(A) */ /* enum {T=1} A; */ /* { return T * A; } */ void m() { if(0) if(1); else printf("ERROR m\n"); if(0) for(int i; ; ) if(1); else printf("ERROR m\n"); if(0) for(1; ; ) if(1); else printf("ERROR m\n"); if(0) while(1) if(1); else printf("ERROR m\n"); if(0) L: if(1); else printf("ERROR m\n"); if(0) LL:for(1;;) for(int i;;) while(1) switch(1) case 1: if(1); else printf("ERROR m\n"); } int j() { T T; } T k() { { T T; } T t; for(T T; ; ); T u; } void krf(a) int a; { printf("%d\n", a); } void krg(); void krg(int a) { printf("%d\n", a); } void krh(int); void krh(b) T b; { printf("%d\n", b); } void kri(); void kri(b, c) int b; double c; { printf("%d %f %f\n", b, c, 2*c); } void krj(); void krj(a, aa) int a[]; void aa(int); { printf("%d\n", *a); aa(3); } void aa(int x) { printf("%d\n", x); } void (*krk(a, b, c))(int) int b, a, c; { printf("%d %d %d\n", a, b, c); return aa; } int hhh(int()); int (testparen)(int T) { return T; } int (testparen2(int T)) { return T; } int ((testparen3)(int T)) { return T; } int ((((((((((testparen10))))))))))(int T) { return T; } int main () { f(g); i(); m(); krf(2); krg(3); krh(4); kri(5.5, 4.5); int x = 23; krj(&x, aa); krk(12, 13, 14)(4); (*krk(12, 13, 14))(4); printf("aaa" "bbb\n"); return 0; }
the_stack_data/370429.c
/* miniz.c v1.11 - 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 May 27, 2011 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 May 15, v1.09 - Initial stable release. May 27, 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). May 28, v1.11 - Added statement from unlicense.org * 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 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 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 */ #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. //#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(_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. typedef unsigned long mz_ulong; // 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_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 #define MZ_VERSION "9.1.11" #define MZ_VERNUM 0x91B0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 11 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other stuff is for advanced use. 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. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, 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) // Works around MSVC's spammy "warning C4127: conditional expression is constant" message. #define MZ_MACRO_END while (0, 0) // ------------------- 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_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. 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. 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. 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. 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 free() 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 // 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_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. 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. // 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 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(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; 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. 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 input as possible, and writing as much compressed data 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 valid 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); // 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); #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) 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 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__forceinline) #ifdef __cplusplus #define __forceinline inline #else #define __forceinline #endif #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, MZ_FREE(address); } static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque; return MZ_REALLOC(address, items * size); } 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 }; if (!ptr) return MZ_CRC32_INIT; crc = ~crc; while (buf_len--) { mz_uint8 b = *ptr++; crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b & 0xF)]; crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b >> 4)]; } return ~crc; } #ifndef MINIZ_NO_ZLIB_APIS 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) { 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 __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 __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 __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 __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]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; 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[cur_pos]); 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[cur_pos]; 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; } 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) : 6] | ((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; } #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/. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { 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, TDEFL_DEFAULT_MAX_PROBES | 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 + 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; { 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,"\0\0\04\02\06"[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; } #ifdef _MSC_VER #pragma warning (pop) #endif // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #ifndef MINIZ_NO_TIME #include <time.h> #endif #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) #include <sys/utime.h> #define MZ_FILE FILE #define MZ_FOPEN 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 freopen #define MZ_DELETE_FILE remove #else #include <utime.h> #define MZ_FILE FILE #define MZ_FOPEN fopen #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 freopen #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 __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 __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 __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 __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 __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) { struct tm *tm = localtime(&time); *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; 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; } static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { #ifndef MINIZ_NO_TIME struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); #else pFilename, access_time, modified_time; return MZ_TRUE; #endif // #ifndef MINIZ_NO_TIME } #endif 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 __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 i, n, 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; // 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) { // 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)) || (!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); 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 ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) 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; pZip->m_pState->m_pMem = (void *)pMem; 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)) 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 __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, internal_attr, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((!internal_attr) && ((external_attr & 0x10) != 0)) return MZ_TRUE; 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; } 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 __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 __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_p)) 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; if (!file_stat.m_comp_size) 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_uncomp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) 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; if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) 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; if (!file_stat.m_comp_size) 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) { if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) 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; } 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); } // ------------------- .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); if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) 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 = level_and_flags & 0xF, 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 = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); mz_zip_internal_state *pState; 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 > 10)) 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 = level_and_flags & 0xF, 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 ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > 10)) 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))) 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)pState->m_central_dir.m_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 ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > 9)) 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.) status = status && mz_zip_writer_finalize_archive(&zip_archive); status = status && mz_zip_writer_end(&zip_archive); if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. MZ_DELETE_FILE(pZip_filename); } 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/7949737.c
/* * Copyright (c) 2002-2007 Niels Provos <[email protected]> * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson * * 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 "event2/event-config.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #include <sys/time.h> #endif #include <errno.h> #include "event2/event.h" #include "event2/event_compat.h" #include "event2/event_struct.h" int called = 0; #define NEVENT 20000 struct event *ev[NEVENT]; static int rand_int(int n) { #ifdef _WIN32 return (int)(rand() % n); #else return (int)(random() % n); #endif } static void time_cb(evutil_socket_t fd, short event, void *arg) { struct timeval tv; int i, j; called++; if (called < 10*NEVENT) { for (i = 0; i < 10; i++) { j = rand_int(NEVENT); tv.tv_sec = 0; tv.tv_usec = rand_int(50000); if (tv.tv_usec % 2) evtimer_add(ev[j], &tv); else evtimer_del(ev[j]); } } } int main(int argc, char **argv) { struct timeval tv; int i; #ifdef _WIN32 WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); (void) WSAStartup(wVersionRequested, &wsaData); #endif /* Initalize the event library */ event_init(); for (i = 0; i < NEVENT; i++) { ev[i] = malloc(sizeof(struct event)); /* Initalize one event */ evtimer_set(ev[i], time_cb, ev[i]); tv.tv_sec = 0; tv.tv_usec = rand_int(50000); evtimer_add(ev[i], &tv); } event_dispatch(); return (called < NEVENT); }
the_stack_data/248581671.c
// 级数求和 #include <stdio.h> #include <math.h> #define N 100 //精度控制 //e num=1;den=k; //pi/2 num=k;den=2*k+1; #define num(k) (1) #define den(k) (k) int a = 10, k, n = N * 10 / 3, d, e, f[N * 10 / 3]; // int main() { for (int i = 0; i < n; i++) f[i] = a / 10; for (int i = 0; i < N / 4; i++) { for (d = 0, k = n; k >= 1; k--) { //printf("(%d %d %d) ",f[k],2*k-1,d); d += f[k - 1] * a; f[k - 1] = d % den(k); d = d / den(k) * num(k); //n/(2n+1); } if (i != 0) printf("%.1d", e + d / a); e = d % a; } }
the_stack_data/153268306.c
/* * Loopback test application * * Copyright 2015 Google Inc. * Copyright 2015 Linaro Ltd. * * Provided under the three clause BSD license found in the LICENSE file. */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <poll.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <dirent.h> #include <signal.h> #define MAX_NUM_DEVICES 10 #define MAX_SYSFS_PREFIX 0x80 #define MAX_SYSFS_PATH 0x200 #define CSV_MAX_LINE 0x1000 #define SYSFS_MAX_INT 0x20 #define MAX_STR_LEN 255 #define DEFAULT_ASYNC_TIMEOUT 200000 struct dict { char *name; int type; }; static struct dict dict[] = { {"ping", 2}, {"transfer", 3}, {"sink", 4}, {NULL,} /* list termination */ }; struct loopback_results { float latency_avg; uint32_t latency_max; uint32_t latency_min; uint32_t latency_jitter; float request_avg; uint32_t request_max; uint32_t request_min; uint32_t request_jitter; float throughput_avg; uint32_t throughput_max; uint32_t throughput_min; uint32_t throughput_jitter; float apbridge_unipro_latency_avg; uint32_t apbridge_unipro_latency_max; uint32_t apbridge_unipro_latency_min; uint32_t apbridge_unipro_latency_jitter; float gbphy_firmware_latency_avg; uint32_t gbphy_firmware_latency_max; uint32_t gbphy_firmware_latency_min; uint32_t gbphy_firmware_latency_jitter; uint32_t error; }; struct loopback_device { char name[MAX_STR_LEN]; char sysfs_entry[MAX_SYSFS_PATH]; char debugfs_entry[MAX_SYSFS_PATH]; struct loopback_results results; }; struct loopback_test { int verbose; int debug; int raw_data_dump; int porcelain; int mask; int size; int iteration_max; int aggregate_output; int test_id; int device_count; int list_devices; int use_async; int async_timeout; int async_outstanding_operations; int us_wait; int file_output; int stop_all; int poll_count; char test_name[MAX_STR_LEN]; char sysfs_prefix[MAX_SYSFS_PREFIX]; char debugfs_prefix[MAX_SYSFS_PREFIX]; struct timespec poll_timeout; struct loopback_device devices[MAX_NUM_DEVICES]; struct loopback_results aggregate_results; struct pollfd fds[MAX_NUM_DEVICES]; }; struct loopback_test t; /* Helper macros to calculate the aggregate results for all devices */ static inline int device_enabled(struct loopback_test *t, int dev_idx); #define GET_MAX(field) \ static int get_##field##_aggregate(struct loopback_test *t) \ { \ uint32_t max = 0; \ int i; \ for (i = 0; i < t->device_count; i++) { \ if (!device_enabled(t, i)) \ continue; \ if (t->devices[i].results.field > max) \ max = t->devices[i].results.field; \ } \ return max; \ } \ #define GET_MIN(field) \ static int get_##field##_aggregate(struct loopback_test *t) \ { \ uint32_t min = ~0; \ int i; \ for (i = 0; i < t->device_count; i++) { \ if (!device_enabled(t, i)) \ continue; \ if (t->devices[i].results.field < min) \ min = t->devices[i].results.field; \ } \ return min; \ } \ #define GET_AVG(field) \ static int get_##field##_aggregate(struct loopback_test *t) \ { \ uint32_t val = 0; \ uint32_t count = 0; \ int i; \ for (i = 0; i < t->device_count; i++) { \ if (!device_enabled(t, i)) \ continue; \ count++; \ val += t->devices[i].results.field; \ } \ if (count) \ val /= count; \ return val; \ } \ GET_MAX(throughput_max); GET_MAX(request_max); GET_MAX(latency_max); GET_MAX(apbridge_unipro_latency_max); GET_MAX(gbphy_firmware_latency_max); GET_MIN(throughput_min); GET_MIN(request_min); GET_MIN(latency_min); GET_MIN(apbridge_unipro_latency_min); GET_MIN(gbphy_firmware_latency_min); GET_AVG(throughput_avg); GET_AVG(request_avg); GET_AVG(latency_avg); GET_AVG(apbridge_unipro_latency_avg); GET_AVG(gbphy_firmware_latency_avg); void abort() { _exit(1); } void usage(void) { fprintf(stderr, "Usage: loopback_test TEST [SIZE] ITERATIONS [SYSPATH] [DBGPATH]\n\n" " Run TEST for a number of ITERATIONS with operation data SIZE bytes\n" " TEST may be \'ping\' \'transfer\' or \'sink\'\n" " SIZE indicates the size of transfer <= greybus max payload bytes\n" " ITERATIONS indicates the number of times to execute TEST at SIZE bytes\n" " Note if ITERATIONS is set to zero then this utility will\n" " initiate an infinite (non terminating) test and exit\n" " without logging any metrics data\n" " SYSPATH indicates the sysfs path for the loopback greybus entries e.g.\n" " /sys/bus/greybus/devices\n" " DBGPATH indicates the debugfs path for the loopback greybus entries e.g.\n" " /sys/kernel/debug/gb_loopback/\n" " Mandatory arguments\n" " -t must be one of the test names - sink, transfer or ping\n" " -i iteration count - the number of iterations to run the test over\n" " Optional arguments\n" " -S sysfs location - location for greybus 'endo' entires default /sys/bus/greybus/devices/\n" " -D debugfs location - location for loopback debugfs entries default /sys/kernel/debug/gb_loopback/\n" " -s size of data packet to send during test - defaults to zero\n" " -m mask - a bit mask of connections to include example: -m 8 = 4th connection -m 9 = 1st and 4th connection etc\n" " default is zero which means broadcast to all connections\n" " -v verbose output\n" " -d debug output\n" " -r raw data output - when specified the full list of latency values are included in the output CSV\n" " -p porcelain - when specified printout is in a user-friendly non-CSV format. This option suppresses writing to CSV file\n" " -a aggregate - show aggregation of all enabled devices\n" " -l list found loopback devices and exit\n" " -x Async - Enable async transfers\n" " -o Async Timeout - Timeout in uSec for async operations\n" " -O Poll loop time out in seconds(max time a test is expected to last, default: 30sec)\n" " -c Max number of outstanding operations for async operations\n" " -w Wait in uSec between operations\n" " -z Enable output to a CSV file (incompatible with -p)\n" " -f When starting new loopback test, stop currently running tests on all devices\n" "Examples:\n" " Send 10000 transfers with a packet size of 128 bytes to all active connections\n" " loopback_test -t transfer -s 128 -i 10000 -S /sys/bus/greybus/devices/ -D /sys/kernel/debug/gb_loopback/\n" " loopback_test -t transfer -s 128 -i 10000 -m 0\n" " Send 10000 transfers with a packet size of 128 bytes to connection 1 and 4\n" " loopback_test -t transfer -s 128 -i 10000 -m 9\n" " loopback_test -t ping -s 0 128 -i -S /sys/bus/greybus/devices/ -D /sys/kernel/debug/gb_loopback/\n" " loopback_test -t sink -s 2030 -i 32768 -S /sys/bus/greybus/devices/ -D /sys/kernel/debug/gb_loopback/\n"); abort(); } static inline int device_enabled(struct loopback_test *t, int dev_idx) { if (!t->mask || (t->mask & (1 << dev_idx))) return 1; return 0; } static void show_loopback_devices(struct loopback_test *t) { int i; if (t->device_count == 0) { printf("No loopback devices.\n"); return; } for (i = 0; i < t->device_count; i++) printf("device[%d] = %s\n", i, t->devices[i].name); } int open_sysfs(const char *sys_pfx, const char *node, int flags) { int fd; char path[MAX_SYSFS_PATH]; snprintf(path, sizeof(path), "%s%s", sys_pfx, node); fd = open(path, flags); if (fd < 0) { fprintf(stderr, "unable to open %s\n", path); abort(); } return fd; } int read_sysfs_int_fd(int fd, const char *sys_pfx, const char *node) { char buf[SYSFS_MAX_INT]; if (read(fd, buf, sizeof(buf)) < 0) { fprintf(stderr, "unable to read from %s%s %s\n", sys_pfx, node, strerror(errno)); close(fd); abort(); } return atoi(buf); } float read_sysfs_float_fd(int fd, const char *sys_pfx, const char *node) { char buf[SYSFS_MAX_INT]; if (read(fd, buf, sizeof(buf)) < 0) { fprintf(stderr, "unable to read from %s%s %s\n", sys_pfx, node, strerror(errno)); close(fd); abort(); } return atof(buf); } int read_sysfs_int(const char *sys_pfx, const char *node) { int fd, val; fd = open_sysfs(sys_pfx, node, O_RDONLY); val = read_sysfs_int_fd(fd, sys_pfx, node); close(fd); return val; } float read_sysfs_float(const char *sys_pfx, const char *node) { int fd; float val; fd = open_sysfs(sys_pfx, node, O_RDONLY); val = read_sysfs_float_fd(fd, sys_pfx, node); close(fd); return val; } void write_sysfs_val(const char *sys_pfx, const char *node, int val) { int fd, len; char buf[SYSFS_MAX_INT]; fd = open_sysfs(sys_pfx, node, O_RDWR); len = snprintf(buf, sizeof(buf), "%d", val); if (write(fd, buf, len) < 0) { fprintf(stderr, "unable to write to %s%s %s\n", sys_pfx, node, strerror(errno)); close(fd); abort(); } close(fd); } static int get_results(struct loopback_test *t) { struct loopback_device *d; struct loopback_results *r; int i; for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; d = &t->devices[i]; r = &d->results; r->error = read_sysfs_int(d->sysfs_entry, "error"); r->request_min = read_sysfs_int(d->sysfs_entry, "requests_per_second_min"); r->request_max = read_sysfs_int(d->sysfs_entry, "requests_per_second_max"); r->request_avg = read_sysfs_float(d->sysfs_entry, "requests_per_second_avg"); r->latency_min = read_sysfs_int(d->sysfs_entry, "latency_min"); r->latency_max = read_sysfs_int(d->sysfs_entry, "latency_max"); r->latency_avg = read_sysfs_float(d->sysfs_entry, "latency_avg"); r->throughput_min = read_sysfs_int(d->sysfs_entry, "throughput_min"); r->throughput_max = read_sysfs_int(d->sysfs_entry, "throughput_max"); r->throughput_avg = read_sysfs_float(d->sysfs_entry, "throughput_avg"); r->apbridge_unipro_latency_min = read_sysfs_int(d->sysfs_entry, "apbridge_unipro_latency_min"); r->apbridge_unipro_latency_max = read_sysfs_int(d->sysfs_entry, "apbridge_unipro_latency_max"); r->apbridge_unipro_latency_avg = read_sysfs_float(d->sysfs_entry, "apbridge_unipro_latency_avg"); r->gbphy_firmware_latency_min = read_sysfs_int(d->sysfs_entry, "gbphy_firmware_latency_min"); r->gbphy_firmware_latency_max = read_sysfs_int(d->sysfs_entry, "gbphy_firmware_latency_max"); r->gbphy_firmware_latency_avg = read_sysfs_float(d->sysfs_entry, "gbphy_firmware_latency_avg"); r->request_jitter = r->request_max - r->request_min; r->latency_jitter = r->latency_max - r->latency_min; r->throughput_jitter = r->throughput_max - r->throughput_min; r->apbridge_unipro_latency_jitter = r->apbridge_unipro_latency_max - r->apbridge_unipro_latency_min; r->gbphy_firmware_latency_jitter = r->gbphy_firmware_latency_max - r->gbphy_firmware_latency_min; } /*calculate the aggregate results of all enabled devices */ if (t->aggregate_output) { r = &t->aggregate_results; r->request_min = get_request_min_aggregate(t); r->request_max = get_request_max_aggregate(t); r->request_avg = get_request_avg_aggregate(t); r->latency_min = get_latency_min_aggregate(t); r->latency_max = get_latency_max_aggregate(t); r->latency_avg = get_latency_avg_aggregate(t); r->throughput_min = get_throughput_min_aggregate(t); r->throughput_max = get_throughput_max_aggregate(t); r->throughput_avg = get_throughput_avg_aggregate(t); r->apbridge_unipro_latency_min = get_apbridge_unipro_latency_min_aggregate(t); r->apbridge_unipro_latency_max = get_apbridge_unipro_latency_max_aggregate(t); r->apbridge_unipro_latency_avg = get_apbridge_unipro_latency_avg_aggregate(t); r->gbphy_firmware_latency_min = get_gbphy_firmware_latency_min_aggregate(t); r->gbphy_firmware_latency_max = get_gbphy_firmware_latency_max_aggregate(t); r->gbphy_firmware_latency_avg = get_gbphy_firmware_latency_avg_aggregate(t); r->request_jitter = r->request_max - r->request_min; r->latency_jitter = r->latency_max - r->latency_min; r->throughput_jitter = r->throughput_max - r->throughput_min; r->apbridge_unipro_latency_jitter = r->apbridge_unipro_latency_max - r->apbridge_unipro_latency_min; r->gbphy_firmware_latency_jitter = r->gbphy_firmware_latency_max - r->gbphy_firmware_latency_min; } return 0; } void log_csv_error(int len, int err) { fprintf(stderr, "unable to write %d bytes to csv %s\n", len, strerror(err)); } int format_output(struct loopback_test *t, struct loopback_results *r, const char *dev_name, char *buf, int buf_len, struct tm *tm) { int len = 0; memset(buf, 0x00, buf_len); len = snprintf(buf, buf_len, "%u-%u-%u %u:%u:%u", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); if (t->porcelain) { len += snprintf(&buf[len], buf_len - len, "\n test:\t\t\t%s\n path:\t\t\t%s\n size:\t\t\t%u\n iterations:\t\t%u\n errors:\t\t%u\n async:\t\t\t%s\n", t->test_name, dev_name, t->size, t->iteration_max, r->error, t->use_async ? "Enabled" : "Disabled"); len += snprintf(&buf[len], buf_len - len, " requests per-sec:\tmin=%u, max=%u, average=%f, jitter=%u\n", r->request_min, r->request_max, r->request_avg, r->request_jitter); len += snprintf(&buf[len], buf_len - len, " ap-throughput B/s:\tmin=%u max=%u average=%f jitter=%u\n", r->throughput_min, r->throughput_max, r->throughput_avg, r->throughput_jitter); len += snprintf(&buf[len], buf_len - len, " ap-latency usec:\tmin=%u max=%u average=%f jitter=%u\n", r->latency_min, r->latency_max, r->latency_avg, r->latency_jitter); len += snprintf(&buf[len], buf_len - len, " apbridge-latency usec:\tmin=%u max=%u average=%f jitter=%u\n", r->apbridge_unipro_latency_min, r->apbridge_unipro_latency_max, r->apbridge_unipro_latency_avg, r->apbridge_unipro_latency_jitter); len += snprintf(&buf[len], buf_len - len, " gbphy-latency usec:\tmin=%u max=%u average=%f jitter=%u\n", r->gbphy_firmware_latency_min, r->gbphy_firmware_latency_max, r->gbphy_firmware_latency_avg, r->gbphy_firmware_latency_jitter); } else { len += snprintf(&buf[len], buf_len- len, ",%s,%s,%u,%u,%u", t->test_name, dev_name, t->size, t->iteration_max, r->error); len += snprintf(&buf[len], buf_len - len, ",%u,%u,%f,%u", r->request_min, r->request_max, r->request_avg, r->request_jitter); len += snprintf(&buf[len], buf_len - len, ",%u,%u,%f,%u", r->latency_min, r->latency_max, r->latency_avg, r->latency_jitter); len += snprintf(&buf[len], buf_len - len, ",%u,%u,%f,%u", r->throughput_min, r->throughput_max, r->throughput_avg, r->throughput_jitter); len += snprintf(&buf[len], buf_len - len, ",%u,%u,%f,%u", r->apbridge_unipro_latency_min, r->apbridge_unipro_latency_max, r->apbridge_unipro_latency_avg, r->apbridge_unipro_latency_jitter); len += snprintf(&buf[len], buf_len - len, ",%u,%u,%f,%u", r->gbphy_firmware_latency_min, r->gbphy_firmware_latency_max, r->gbphy_firmware_latency_avg, r->gbphy_firmware_latency_jitter); } printf("\n%s\n", buf); return len; } static int log_results(struct loopback_test *t) { int fd, i, len, ret; struct tm tm; time_t local_time; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; char file_name[MAX_SYSFS_PATH]; char data[CSV_MAX_LINE]; local_time = time(NULL); tm = *localtime(&local_time); /* * file name will test_name_size_iteration_max.csv * every time the same test with the same parameters is run we will then * append to the same CSV with datestamp - representing each test * dataset. */ if (t->file_output && !t->porcelain) { snprintf(file_name, sizeof(file_name), "%s_%d_%d.csv", t->test_name, t->size, t->iteration_max); fd = open(file_name, O_WRONLY | O_CREAT | O_APPEND, mode); if (fd < 0) { fprintf(stderr, "unable to open %s for appendation\n", file_name); abort(); } } for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; len = format_output(t, &t->devices[i].results, t->devices[i].name, data, sizeof(data), &tm); if (t->file_output && !t->porcelain) { ret = write(fd, data, len); if (ret == -1) fprintf(stderr, "unable to write %d bytes to csv.\n", len); } } if (t->aggregate_output) { len = format_output(t, &t->aggregate_results, "aggregate", data, sizeof(data), &tm); if (t->file_output && !t->porcelain) { ret = write(fd, data, len); if (ret == -1) fprintf(stderr, "unable to write %d bytes to csv.\n", len); } } if (t->file_output && !t->porcelain) close(fd); return 0; } int is_loopback_device(const char *path, const char *node) { char file[MAX_SYSFS_PATH]; snprintf(file, MAX_SYSFS_PATH, "%s%s/iteration_count", path, node); if (access(file, F_OK) == 0) return 1; return 0; } int find_loopback_devices(struct loopback_test *t) { struct dirent **namelist; int i, n, ret; unsigned int dev_id; struct loopback_device *d; n = scandir(t->sysfs_prefix, &namelist, NULL, alphasort); if (n < 0) { perror("scandir"); ret = -ENODEV; goto baddir; } /* Don't include '.' and '..' */ if (n <= 2) { ret = -ENOMEM; goto done; } for (i = 0; i < n; i++) { ret = sscanf(namelist[i]->d_name, "gb_loopback%u", &dev_id); if (ret != 1) continue; if (!is_loopback_device(t->sysfs_prefix, namelist[i]->d_name)) continue; if (t->device_count == MAX_NUM_DEVICES) { fprintf(stderr, "max number of devices reached!\n"); break; } d = &t->devices[t->device_count++]; snprintf(d->name, MAX_STR_LEN, "gb_loopback%u", dev_id); snprintf(d->sysfs_entry, MAX_SYSFS_PATH, "%s%s/", t->sysfs_prefix, d->name); snprintf(d->debugfs_entry, MAX_SYSFS_PATH, "%sraw_latency_%s", t->debugfs_prefix, d->name); if (t->debug) printf("add %s %s\n", d->sysfs_entry, d->debugfs_entry); } ret = 0; done: for (i = 0; i < n; i++) free(namelist[n]); free(namelist); baddir: return ret; } static int open_poll_files(struct loopback_test *t) { struct loopback_device *dev; char buf[MAX_SYSFS_PATH + MAX_STR_LEN]; char dummy; int fds_idx = 0; int i; for (i = 0; i < t->device_count; i++) { dev = &t->devices[i]; if (!device_enabled(t, i)) continue; snprintf(buf, sizeof(buf), "%s%s", dev->sysfs_entry, "iteration_count"); t->fds[fds_idx].fd = open(buf, O_RDONLY); if (t->fds[fds_idx].fd < 0) { fprintf(stderr, "Error opening poll file!\n"); goto err; } read(t->fds[fds_idx].fd, &dummy, 1); t->fds[fds_idx].events = POLLERR|POLLPRI; t->fds[fds_idx].revents = 0; fds_idx++; } t->poll_count = fds_idx; return 0; err: for (i = 0; i < fds_idx; i++) close(t->fds[fds_idx].fd); return -1; } static int close_poll_files(struct loopback_test *t) { int i; for (i = 0; i < t->poll_count; i++) close(t->fds[i].fd); return 0; } static int is_complete(struct loopback_test *t) { int iteration_count; int i; for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; iteration_count = read_sysfs_int(t->devices[i].sysfs_entry, "iteration_count"); /* at least one device did not finish yet */ if (iteration_count != t->iteration_max) return 0; } return 1; } static void stop_tests(struct loopback_test *t) { int i; for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; write_sysfs_val(t->devices[i].sysfs_entry, "type", 0); } } static void handler(int sig) { /* do nothing */ } static int wait_for_complete(struct loopback_test *t) { int number_of_events = 0; char dummy; int ret; int i; struct timespec *ts = NULL; struct sigaction sa; sigset_t mask_old, mask; sigemptyset(&mask); sigemptyset(&mask_old); sigaddset(&mask, SIGINT); sigprocmask(SIG_BLOCK, &mask, &mask_old); sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); if (sigaction(SIGINT, &sa, NULL) == -1) { fprintf(stderr, "sigaction error\n"); return -1; } if (t->poll_timeout.tv_sec != 0) ts = &t->poll_timeout; while (1) { ret = ppoll(t->fds, t->poll_count, ts, &mask_old); if (ret <= 0) { stop_tests(t); fprintf(stderr, "Poll exit with errno %d\n", errno); return -1; } for (i = 0; i < t->poll_count; i++) { if (t->fds[i].revents & POLLPRI) { /* Dummy read to clear the event */ read(t->fds[i].fd, &dummy, 1); number_of_events++; } } if (number_of_events == t->poll_count) break; } if (!is_complete(t)) { fprintf(stderr, "Iteration count did not finish!\n"); return -1; } return 0; } static void prepare_devices(struct loopback_test *t) { int i; /* Cancel any running tests on enabled devices. If * stop_all option is given, stop test on all devices. */ for (i = 0; i < t->device_count; i++) if (t->stop_all || device_enabled(t, i)) write_sysfs_val(t->devices[i].sysfs_entry, "type", 0); for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; write_sysfs_val(t->devices[i].sysfs_entry, "us_wait", t->us_wait); /* Set operation size */ write_sysfs_val(t->devices[i].sysfs_entry, "size", t->size); /* Set iterations */ write_sysfs_val(t->devices[i].sysfs_entry, "iteration_max", t->iteration_max); if (t->use_async) { write_sysfs_val(t->devices[i].sysfs_entry, "async", 1); write_sysfs_val(t->devices[i].sysfs_entry, "timeout", t->async_timeout); write_sysfs_val(t->devices[i].sysfs_entry, "outstanding_operations_max", t->async_outstanding_operations); } else write_sysfs_val(t->devices[i].sysfs_entry, "async", 0); } } static int start(struct loopback_test *t) { int i; /* the test starts by writing test_id to the type file. */ for (i = 0; i < t->device_count; i++) { if (!device_enabled(t, i)) continue; write_sysfs_val(t->devices[i].sysfs_entry, "type", t->test_id); } return 0; } void loopback_run(struct loopback_test *t) { int i; int ret; for (i = 0; dict[i].name != NULL; i++) { if (strstr(dict[i].name, t->test_name)) t->test_id = dict[i].type; } if (!t->test_id) { fprintf(stderr, "invalid test %s\n", t->test_name); usage(); return; } prepare_devices(t); ret = open_poll_files(t); if (ret) goto err; start(t); ret = wait_for_complete(t); close_poll_files(t); if (ret) goto err; get_results(t); log_results(t); return; err: printf("Error running test\n"); return; } static int sanity_check(struct loopback_test *t) { int i; if (t->device_count == 0) { fprintf(stderr, "No loopback devices found\n"); return -1; } for (i = 0; i < MAX_NUM_DEVICES; i++) { if (!device_enabled(t, i)) continue; if (t->mask && !strcmp(t->devices[i].name, "")) { fprintf(stderr, "Bad device mask %x\n", (1 << i)); return -1; } } return 0; } int main(int argc, char *argv[]) { int o, ret; char *sysfs_prefix = "/sys/class/gb_loopback/"; char *debugfs_prefix = "/sys/kernel/debug/gb_loopback/"; memset(&t, 0, sizeof(t)); while ((o = getopt(argc, argv, "t:s:i:S:D:m:v::d::r::p::a::l::x::o:O:c:w:z::f::")) != -1) { switch (o) { case 't': snprintf(t.test_name, MAX_STR_LEN, "%s", optarg); break; case 's': t.size = atoi(optarg); break; case 'i': t.iteration_max = atoi(optarg); break; case 'S': snprintf(t.sysfs_prefix, MAX_SYSFS_PREFIX, "%s", optarg); break; case 'D': snprintf(t.debugfs_prefix, MAX_SYSFS_PREFIX, "%s", optarg); break; case 'm': t.mask = atol(optarg); break; case 'v': t.verbose = 1; break; case 'd': t.debug = 1; break; case 'r': t.raw_data_dump = 1; break; case 'p': t.porcelain = 1; break; case 'a': t.aggregate_output = 1; break; case 'l': t.list_devices = 1; break; case 'x': t.use_async = 1; break; case 'o': t.async_timeout = atoi(optarg); break; case 'O': t.poll_timeout.tv_sec = atoi(optarg); break; case 'c': t.async_outstanding_operations = atoi(optarg); break; case 'w': t.us_wait = atoi(optarg); break; case 'z': t.file_output = 1; break; case 'f': t.stop_all = 1; break; default: usage(); return -EINVAL; } } if (!strcmp(t.sysfs_prefix, "")) snprintf(t.sysfs_prefix, MAX_SYSFS_PREFIX, "%s", sysfs_prefix); if (!strcmp(t.debugfs_prefix, "")) snprintf(t.debugfs_prefix, MAX_SYSFS_PREFIX, "%s", debugfs_prefix); ret = find_loopback_devices(&t); if (ret) return ret; ret = sanity_check(&t); if (ret) return ret; if (t.list_devices) { show_loopback_devices(&t); return 0; } if (t.test_name[0] == '\0' || t.iteration_max == 0) usage(); if (t.async_timeout == 0) t.async_timeout = DEFAULT_ASYNC_TIMEOUT; loopback_run(&t); return 0; }
the_stack_data/173576755.c
/* *Name: Nikhil Ranjan Nayak *Regd No: 1641012040 *Desc: zombie process *Check with: ps aux | grep a.out */ #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main() { pid_t childpid = fork(); if(childpid > 0) { printf("Parent Process"); sleep(10); } else printf("Child Process: %ld", (long)getpid()); return 0; }
the_stack_data/184517083.c
/** ****************************************************************************** * @file stm32f1xx_ll_rtc.c * @author MCD Application Team * @brief RTC LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_ll_rtc.h" #include "stm32f1xx_ll_cortex.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F1xx_LL_Driver * @{ */ #if defined(RTC) /** @addtogroup RTC_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Constants * @{ */ /* Default values used for prescaler */ #define RTC_ASYNCH_PRESC_DEFAULT 0x00007FFFU /* Values used for timeout */ #define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */ #define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Macros * @{ */ #define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0xFFFFFU) #define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ || ((__VALUE__) == LL_RTC_FORMAT_BCD)) #define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) #define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) #define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) #define IS_LL_RTC_CALIB_OUTPUT(__OUTPUT__) (((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_NONE) || \ ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_RTCCLOCK) || \ ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_ALARM) || \ ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_SECOND)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_LL_Exported_Functions * @{ */ /** @addtogroup RTC_LL_EF_Init * @{ */ /** * @brief De-Initializes the RTC registers to their default reset values. * @note This function doesn't reset the RTC Clock source and RTC Backup Data * registers. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are de-initialized * - ERROR: RTC registers are not de-initialized */ ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) { ErrorStatus status = ERROR; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { LL_RTC_WriteReg(RTCx,CNTL, 0x0000); LL_RTC_WriteReg(RTCx,CNTH, 0x0000); LL_RTC_WriteReg(RTCx,PRLH, 0x0000); LL_RTC_WriteReg(RTCx,PRLL, 0x8000); LL_RTC_WriteReg(RTCx,CRH, 0x0000); LL_RTC_WriteReg(RTCx,CRL, 0x0020); /* Reset Tamper and alternate functions configuration register */ LL_RTC_WriteReg(BKP,RTCCR, 0x00000000U); LL_RTC_WriteReg(BKP,CR, 0x00000000U); LL_RTC_WriteReg(BKP,CSR, 0x00000000U); /* Exit Initialization Mode */ if(LL_RTC_ExitInitMode(RTCx) == ERROR) { return ERROR; } /* Wait till the RTC RSF flag is set */ status = LL_RTC_WaitForSynchro(RTCx); /* Clear RSF Flag */ LL_RTC_ClearFlag_RS(RTCx); } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Initializes the RTC registers according to the specified parameters * in RTC_InitStruct. * @param RTCx RTC Instance * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains * the configuration information for the RTC peripheral. * @note The RTC Prescaler register is write protected and can be written in * initialization mode only. * @note the user should call LL_RTC_StructInit() or the structure of Prescaler * need to be initialized before RTC init() * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are initialized * - ERROR: RTC registers are not initialized */ ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); assert_param(IS_LL_RTC_CALIB_OUTPUT(RTC_InitStruct->OutPutSource)); /* Waiting for synchro */ if(LL_RTC_WaitForSynchro(RTCx) != ERROR) { /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Clear Flag Bits */ LL_RTC_ClearFlag_ALR(RTCx); LL_RTC_ClearFlag_OW(RTCx); LL_RTC_ClearFlag_SEC(RTCx); if(RTC_InitStruct->OutPutSource != LL_RTC_CALIB_OUTPUT_NONE) { /* Disable the selected Tamper Pin */ LL_RTC_TAMPER_Disable(BKP); } /* Set the signal which will be routed to RTC Tamper Pin */ LL_RTC_SetOutputSource(BKP, RTC_InitStruct->OutPutSource); /* Configure Synchronous and Asynchronous prescaler factor */ LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); /* Exit Initialization Mode */ LL_RTC_ExitInitMode(RTCx); status = SUCCESS; } } return status; } /** * @brief Set each @ref LL_RTC_InitTypeDef field to default value. * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. * @retval None */ void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) { /* Set RTC_InitStruct fields to default values */ RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; RTC_InitStruct->OutPutSource = LL_RTC_CALIB_OUTPUT_NONE; } /** * @brief Set the RTC current time. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains * the time configuration information for the RTC. * @note The user should call LL_RTC_TIME_StructInit() or the structure * of time need to be initialized before time init() * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Time register is configured * - ERROR: RTC Time register is not configured */ ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) { ErrorStatus status = ERROR; uint32_t counter_time = 0U; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if (RTC_Format == LL_RTC_FORMAT_BIN) { assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); } else { assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); } /* Enter Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { counter_time = (uint32_t)(((uint32_t)RTC_TimeStruct->Hours * 3600U) + \ ((uint32_t)RTC_TimeStruct->Minutes * 60U) + \ ((uint32_t)RTC_TimeStruct->Seconds)); LL_RTC_TIME_Set(RTCx, counter_time); } else { counter_time = (((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)) * 3600U) + \ ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes)) * 60U) + \ ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds)))); LL_RTC_TIME_Set(RTCx, counter_time); } status = SUCCESS; } /* Exit Initialization mode */ LL_RTC_ExitInitMode(RTCx); return status; } /** * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. * @retval None */ void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) { /* Time = 00h:00min:00sec */ RTC_TimeStruct->Hours = 0U; RTC_TimeStruct->Minutes = 0U; RTC_TimeStruct->Seconds = 0U; } /** * @brief Set the RTC Alarm. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that * contains the alarm configuration parameters. * @note the user should call LL_RTC_ALARM_StructInit() or the structure * of Alarm need to be initialized before Alarm init() * @retval An ErrorStatus enumeration value: * - SUCCESS: ALARM registers are configured * - ERROR: ALARM registers are not configured */ ErrorStatus LL_RTC_ALARM_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { ErrorStatus status = ERROR; uint32_t counter_alarm = 0U; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if (RTC_Format == LL_RTC_FORMAT_BIN) { assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); } else { assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); } /* Enter Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { counter_alarm = (uint32_t)(((uint32_t)RTC_AlarmStruct->AlarmTime.Hours * 3600U) + \ ((uint32_t)RTC_AlarmStruct->AlarmTime.Minutes * 60U) + \ ((uint32_t)RTC_AlarmStruct->AlarmTime.Seconds)); LL_RTC_ALARM_Set(RTCx, counter_alarm); } else { counter_alarm = (((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)) * 3600U) + \ ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes)) * 60U) + \ ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds)))); LL_RTC_ALARM_Set(RTCx, counter_alarm); } status = SUCCESS; } /* Exit Initialization mode */ LL_RTC_ExitInitMode(RTCx); return status; } /** * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARM field to default value (Time = 00h:00mn:00sec / * Day = 1st day of the month/Mask = all fields are masked). * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. * @retval None */ void LL_RTC_ALARM_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Alarm Time Settings : Time = 00h:00mn:00sec */ RTC_AlarmStruct->AlarmTime.Hours = 0U; RTC_AlarmStruct->AlarmTime.Minutes = 0U; RTC_AlarmStruct->AlarmTime.Seconds = 0U; } /** * @brief Enters the RTC Initialization mode. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC is in Init mode * - ERROR: RTC is not in Init mode */ ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Wait till RTC is in INIT state and if Time out is reached exit */ tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout --; } tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); if (timeout == 0U) { status = ERROR; } } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); return status; } /** * @brief Exit the RTC Initialization mode. * @note When the initialization sequence is complete, the calendar restarts * counting after 4 RTCCLK cycles. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC exited from in Init mode * - ERROR: Not applicable */ ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable initialization mode */ LL_RTC_EnableWriteProtection(RTCx); /* Wait till RTC is in INIT state and if Time out is reached exit */ tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout --; } tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); if (timeout == 0U) { status = ERROR; } } return status; } /** * @brief Set the Time Counter * @param RTCx RTC Instance * @param TimeCounter this value can be from 0 to 0xFFFFFFFF * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Counter register configured * - ERROR: Not applicable */ ErrorStatus LL_RTC_TIME_SetCounter(RTC_TypeDef *RTCx, uint32_t TimeCounter) { ErrorStatus status = ERROR; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Enter Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { LL_RTC_TIME_Set(RTCx, TimeCounter); status = SUCCESS; } /* Exit Initialization mode */ LL_RTC_ExitInitMode(RTCx); return status; } /** * @brief Set Alarm Counter. * @param RTCx RTC Instance * @param AlarmCounter this value can be from 0 to 0xFFFFFFFF * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC exited from in Init mode * - ERROR: Not applicable */ ErrorStatus LL_RTC_ALARM_SetCounter(RTC_TypeDef *RTCx, uint32_t AlarmCounter) { ErrorStatus status = ERROR; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Enter Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { LL_RTC_ALARM_Set(RTCx, AlarmCounter); status = SUCCESS; } /* Exit Initialization mode */ LL_RTC_ExitInitMode(RTCx); return status; } /** * @brief Waits until the RTC registers are synchronized with RTC APB clock. * @note The RTC Resynchronization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are synchronised * - ERROR: RTC registers are not synchronised */ ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Clear RSF flag */ LL_RTC_ClearFlag_RS(RTCx); /* Wait the registers to be synchronised */ tmp = LL_RTC_IsActiveFlag_RS(RTCx); while ((timeout != 0U) && (tmp != 0U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout--; } tmp = LL_RTC_IsActiveFlag_RS(RTCx); if (timeout == 0U) { status = ERROR; } } return (status); } /** * @} */ /** * @} */ /** * @} */ #endif /* defined(RTC) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/175142987.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <unistd.h> int main() { int n_threads, i; /* Schedule allows you to create the scheme with which the threads distribute the work of an iteration of a cycle. "dynamic": scheduling works on a "first come, first served" basis. In this way each thread has an iteration, when it ends it will be assigned the next iteration */ #pragma omp parallel for private(i) schedule(dynamic) num_threads(4) for(i=0; i<16; i++) { //wait i second sleep(i); printf("The thread %d has completed the iteration %d\n", omp_get_thread_num(), i); } printf("All threads have ended!!\n"); return 0; }
the_stack_data/241256.c
/*- * Copyright (c) 2011 UCHIYAMA Yasushi. 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. */ #define ELF_NOTE_NETBSD_NAMESZ 7 #define ELF_NOTE_NETBSD_DESCSZ 4 #define ELF_NOTE_TYPE_NETBSD_TAG 1 #define ELF_NOTE_NETBSD_NAME "NetBSD\0\0" #define __NetBSD_Version__ 599002400 /* NetBSD 5.99.24 */ #define __STRING(x) #x #define __S(x) __STRING(x) __asm( ".section\t\".note.netbsd.ident\", \"a\"\n" "\t.p2align\t2\n\n" "\t.long\t" __S(ELF_NOTE_NETBSD_NAMESZ) "\n" "\t.long\t" __S(ELF_NOTE_NETBSD_DESCSZ) "\n" "\t.long\t" __S(ELF_NOTE_TYPE_NETBSD_TAG) "\n" "\t.ascii\t" __S(ELF_NOTE_NETBSD_NAME) "\n" "\t.long\t" __S(__NetBSD_Version__) "\n\n" "\t.previous\n" "\t.p2align\t2\n" ); #define SYSCALL_NETBSD(n, x) \ __asm (".text; \ .align 8; \ .global " #x "; \ " #x ":; \ mov $ " #n ", %eax; \ mov %rcx, %r10; \ syscall; \ retq"); SYSCALL_NETBSD (4, sys_write); SYSCALL_NETBSD (3, sys_read);
the_stack_data/86075006.c
/* { dg-do compile } */ /* { dg-options "-O2 -g" } */ void foo(register char *p) { char c, *q, *sp; while (1) { *p++=0; sp=p+1; c=*sp; *p++=0; } }
the_stack_data/237642980.c
/***************************************************************** * Analisador Sintatico LL(1) * * Exemplo p/ Disciplina de Compiladores * * Cristiano Damiani Vasconcellos * ******************************************************************/ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <assert.h> /* Nao terminais o bit mais significativo ligado indica que se trata de um nao terminal */ #define EXPR_A 0x8001 #define EXPR_AL 0x8002 #define EXPR_B 0x8003 #define EXPR_BL 0x8004 #define EXPR_C 0x8005 #define EXPR_CL 0x8006 #define EXPR_D 0x8007 /* Terminais */ #define ERRO 0x0000 #define BIIMP 0x0100 #define IMPLI 0x0200 #define LOG_E 0X0300 #define LOG_OU 0x0400 #define LOG_NEG 0x0500 #define APAR 0x0600 #define FPAR 0x0700 #define CONST 0x0800 #define FIM 0x0900 //Mascaras #define NTER 0x8000 #define NNTER 0x7FFF #define TAMPILHA 100 struct Pilha { int topo; int dado[TAMPILHA]; }; /* Producoes a primeira posicao do vetor indica quantos simbolos gramaticais a producao possui em seu lado direito */ const int PROD1[] = {2, EXPR_B, EXPR_AL}; // A -> BA' const int PROD2[] = {3, BIIMP, EXPR_B, EXPR_AL}; // A' -> <->BA' const int PROD3[] = {0}; // A' -> vazio const int PROD4[] = {2, EXPR_C,EXPR_BL}; // B -> CB' const int PROD5[] = {3, IMPLI, EXPR_C, EXPR_BL}; // B' -> ->CB' const int PROD6[] = {0}; // B' -> vazio' const int PROD7[] = {2, EXPR_D, EXPR_CL }; // C -> DC' const int PROD8[] = {3, LOG_E, EXPR_D, EXPR_CL}; // C' -> ^DC' const int PROD9[] = {3, LOG_OU, EXPR_D, EXPR_CL}; // C' -> vDC' const int PROD10[] = {0}; // C' -> vazio const int PROD11[]= {2, LOG_NEG, EXPR_D}; // D -> ~D const int PROD12[]= {3, APAR, EXPR_A, FPAR}; // D -> (A) const int PROD13[]= {1, CONST}; // D -> c // vetor utilizado para mapear um numero e uma producao. const int *PROD[] = {NULL, PROD1, PROD2, PROD3, PROD4, PROD5, PROD6, PROD7, PROD8, PROD9, PROD10, PROD11, PROD12, PROD13}; // Tabela sintatica LL(1). Os numeros correspondem as producoes acima. const int STAB[7][10] = { { 0, 0, 0, 0, 1, 1, 0, 1, 0}, { 2, 0, 0, 0, 0, 0, 3, 0, 3}, { 0, 0, 0, 0, 4, 4, 0, 4, 0}, { 6, 5, 0, 0, 0, 0, 6, 0, 6}, { 0, 0, 0, 0, 7,7, 0, 7, 0}, { 10, 10, 8, 9, 0,0, 10, 0, 10}, { 0, 0, 0, 0, 11,12, 0, 13, 0}}; /***************************************************************** * int lex (char *str, int *pos) * * procura o proximo token dentro de str a partir de *pos,incre- * * menta o valor de *pos a medida que faz alguma tranzicao de * * estados. * * Retorna o inteiro que identifica o token encontrado. * ******************************************************************/ int lex (char *str, int *pos) { int estado = 0; char c; while (1) { c = str[*pos]; switch(estado) { case 0: if (isdigit(c)) { (*pos)++; estado = 1; } else switch (c) { case ' ': (*pos)++; break; case '.': (*pos)++; estado = 2; break; case '<': //equivalente ao <-> (*pos)++; return BIIMP; case '>': //equivalente ao -> (*pos)++; return IMPLI; case '^': (*pos)++; return LOG_E; case 'v': (*pos)++; return LOG_OU; case '~': (*pos)++; return LOG_NEG; case '(': (*pos)++; return APAR; case ')': (*pos)++; return FPAR; case 'c': (*pos)++; return CONST; case '\0': return FIM; default: (*pos)++; return ERRO; } break; case 1: if(isdigit(c)) (*pos)++; else if (c == '.') { estado = 3; (*pos)++; } else { //Adicionar constante na tabela de simbolos. return CONST; } break; case 2: if (isdigit(c)) { (*pos)++; estado = 3; } else { (*pos)++; return ERRO; } break; case 3: if (isdigit(c)) (*pos)++; else { //Adicionar a constante na tabela de simbolos. return CONST; } break; default: printf("Lex:Estado indefinido"); exit(1); } } } /***************************************************************** * void erro (char *erro, char *expr, int pos) * * imprime a mensagem apontado por erro, a expressao apontada por * * expr, e uma indicacao de que o erro ocorreu na posicao pos de * * expr. Encerra a execucao do programa. * ******************************************************************/ void erro (char *erro, char *expr, int pos) { int i; printf("%s", erro); printf("\n%s\n", expr); for (i = 0; i < pos-1; i++) putchar(' '); putchar('^'); printf("\n"); exit(1); } /***************************************************************** * void inicializa(struct Pilha *p) * * inicializa o topo da pilha em -1, valor que indica que a pilha * * esta vazia. * ******************************************************************/ void inicializa(struct Pilha *p) { p->topo = -1; } /***************************************************************** * void insere (struct Pilha *p, int elemento * * Insere o valor de elemento no topo da pilha apontada por p. * ******************************************************************/ void insere (struct Pilha *p, int elemento) { if (p->topo < TAMPILHA) { /* printf("ele %x\n",elemento); */ p->topo++; p->dado[p->topo] = elemento; } else { printf("estouro de pilha %d\n", p->topo); exit (1); } } /***************************************************************** * int remover (struct Pilha *p) * * Remove e retorna o valor armazenado no topo da pilha apontada * * por p * ******************************************************************/ int remover (struct Pilha *p) { int aux; if (p->topo >= 0) { aux = p->dado[p->topo]; p->topo--; return aux; } else { printf("Pilha vazia"); exit(1); } return 0; } /***************************************************************** * int consulta (struct Pilha *p) * * Retorna o valor armazenado no topo da pilha apontada por p * ******************************************************************/ int consulta (struct Pilha *p) { if (p->topo >= 0) return p->dado[p->topo]; printf("Pilha vazia"); exit(1); } /***************************************************************** * void parser (char *expr) * * Verifica se a string apontada por expr esta sintaticamente * * correta. * * Variaveis Globais Consultadas: STAB e PROD * ******************************************************************/ void parser(char *expr) { struct Pilha pilha; int x, a, nProd, i, *producao; int pos = 0; inicializa(&pilha); insere(&pilha, FIM); insere(&pilha, EXPR_A); if ((a = lex(expr, &pos)) == ERRO) erro("Erro lexico", expr, pos); do { x = consulta(&pilha); if (!(x&NTER)) { if (x == a) { remover (&pilha); if ((a = lex(expr, &pos)) == ERRO) erro("Erro lexico", expr, pos); } else erro("Erro sintatico",expr, pos); } if (x&NTER) { nProd = STAB[(x&NNTER)-1][(a>>8) - 1]; if (nProd) { remover (&pilha); producao = PROD[nProd]; for (i = producao[0]; i > 0; i--) insere (&pilha, producao[i]); } else erro ("Erro sintatico", expr, pos); } } while (x != FIM); } void main() { char expr[100]; printf("\nDigite uma expressao: "); gets(expr); parser(expr); printf("Expressao sintaticamente correta"); printf("\n"); }
the_stack_data/27286.c
/** * Description : Contains Duplicate * Given an array of integers, find if the array contains any * duplicates. Your function should return true if any value * appears at least twice in the array, and it should return false * if every element is distinct. * Author : Evan Lau * Date : 2016/04/17 */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include <assert.h> bool containsDuplicate(int* nums, int numsSize) { int arr[1000000]; int i; memset(arr, 0, 1000000); for (i = 0; i < numsSize; i++) { if (arr[nums[i]] == 1) return true; arr[nums[i]] = 1; } return false; } int main(void) { int arr1[] = {3, 3}; int arr2[] = {}; int arr3[] = {0}; assert(containsDuplicate(arr1, 2) == true); assert(containsDuplicate(arr2, 0) == false); assert(containsDuplicate(arr3, 1) == false); printf("All passed\n"); return 0; }
the_stack_data/108071.c
// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -analyzer-constraints=basic -verify -Wno-unreachable-code -ffreestanding %s // RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -analyzer-constraints=range -verify -Wno-unreachable-code -ffreestanding %s #include <stdint.h> void f1(int * p) { // This branch should be infeasible // because __imag__ p is 0. if (!p && __imag__ (intptr_t) p) *p = 1; // no-warning // If p != 0 then this branch is feasible; otherwise it is not. if (__real__ (intptr_t) p) *p = 1; // no-warning *p = 2; // expected-warning{{Dereference of null pointer}} }
the_stack_data/15764036.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_recursive_power.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkalnins <[email protected]. +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/23 13:16:52 by kkalnins #+# #+# */ /* Updated: 2021/02/24 21:43:30 by kkalnins ### ########.fr */ /* */ /* ************************************************************************** */ int ft_recursive_power(int nb, int power) { if (power == 0) return (1); if (power < 0) return (0); return (nb * ft_recursive_power(nb, power - 1)); }
the_stack_data/117329408.c
/* Copyright (C) 2002 Free Software Foundation, Inc. */ /* { dg-do run } */ /* { dg-options "-fshort-wchar" } */ /* Source: Neil Booth, 10 Dec 2002. Test that __WCHAR_MAX__ is correct with -fshort-wchar. */ int main () { __WCHAR_TYPE__ w = ~(__WCHAR_TYPE__) 0; if (w != __WCHAR_MAX__) abort (); return 0; }
the_stack_data/67324501.c
/***************************************\ Puyan Lotfi gtg945h CS 4803 \***************************************/ #include <stdio.h> #ifdef DO_DES #include "my_des.h" #endif #ifdef DO_IDEA #include "my_idea.h" #endif int main(int argv, char **argc) { #ifdef DO_DES int i; long long puyan; char clearText[8]; char cypherText[8]; char *nayup; #endif #ifdef DO_IDEA long long input; #endif #ifdef DO_DES #ifdef TEST char test = {0, 0, 0, 0, 0, 0, 12, 171}; #endif printf("Enter input in decimal: "); scanf("%lld", &puyan); nayup = (char *)(&puyan); const int a = 0x1; if (((const char *)&a)[0]) { clearText[0] = nayup[7]; clearText[1] = nayup[6]; clearText[2] = nayup[5]; clearText[3] = nayup[4]; clearText[4] = nayup[3]; clearText[5] = nayup[2]; clearText[6] = nayup[1]; clearText[7] = nayup[0]; } else { for (i = 0; i < 8; i++) { clearText[i] = nayup[i]; } } des_e(cypherText, clearText); #ifdef TEST des_e(cypherText, test); #endif #endif #ifdef CRYPT_ASCII_DES for (i = 0; i < 8; i++) { printf("%c", clearText[i]); } printf("\n"); for (i = 0; i < 8; i++) { printf("%c", cypherText[i]); } printf("\n"); #endif #ifdef CRYPT_BINARY_DES printf("Clear Text (Binary): "); for (i = 0; i < 64; i++) { printf("%d", GETBIT(clearText, i)); } printf("\n"); printf("Cypher Text (Binary): "); for (i = 0; i < 64; i++) { printf("%d", GETBIT(cypherText, i)); } printf("\n"); #endif #ifdef DO_IDEA printf("Enter data in decimal: "); scanf("%lld", &input); printf("Clear Text (Decimal): %lld\n", input); printf("Cypher Text (Decimal): %lld\n", idea_e(input)); #endif return 0; }
the_stack_data/67325689.c
#include <stdio.h> int main() { int n, i, j; while (scanf("%d", &n), n != 0) { int matriz[n][n]; for (i = 0; i < n; i++) { int valor = 1; for (j = i; j < n; j++) { matriz[i][j] = valor; matriz[j][i] = valor; valor++; } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (j != 0) printf(" "); printf("%3d", matriz[i][j]); } printf("\n"); } printf("\n"); } return 0; }
the_stack_data/117328780.c
// Part of the Adafruit_GFX library #ifndef FONT5X7_H #define FONT5X7_H #ifdef __AVR__ #include <avr/io.h> #include <avr/pgmspace.h> #else #define PROGMEM #endif // Standard ASCII 5x7 font static const unsigned char font[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, 0x18, 0x3C, 0x7E, 0x3C, 0x18, 0x1C, 0x57, 0x7D, 0x57, 0x1C, 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, 0x00, 0x18, 0x3C, 0x18, 0x00, 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, 0x00, 0x18, 0x24, 0x18, 0x00, 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, 0x30, 0x48, 0x3A, 0x06, 0x0E, 0x26, 0x29, 0x79, 0x29, 0x26, 0x40, 0x7F, 0x05, 0x05, 0x07, 0x40, 0x7F, 0x05, 0x25, 0x3F, 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, 0x7F, 0x3E, 0x1C, 0x1C, 0x08, 0x08, 0x1C, 0x1C, 0x3E, 0x7F, 0x14, 0x22, 0x7F, 0x22, 0x14, 0x5F, 0x5F, 0x00, 0x5F, 0x5F, 0x06, 0x09, 0x7F, 0x01, 0x7F, 0x00, 0x66, 0x89, 0x95, 0x6A, 0x60, 0x60, 0x60, 0x60, 0x60, 0x94, 0xA2, 0xFF, 0xA2, 0x94, 0x08, 0x04, 0x7E, 0x04, 0x08, 0x10, 0x20, 0x7E, 0x20, 0x10, 0x08, 0x08, 0x2A, 0x1C, 0x08, 0x08, 0x1C, 0x2A, 0x08, 0x08, 0x1E, 0x10, 0x10, 0x10, 0x10, 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, 0x30, 0x38, 0x3E, 0x38, 0x30, 0x06, 0x0E, 0x3E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x14, 0x7F, 0x14, 0x7F, 0x14, 0x24, 0x2A, 0x7F, 0x2A, 0x12, 0x23, 0x13, 0x08, 0x64, 0x62, 0x36, 0x49, 0x56, 0x20, 0x50, 0x00, 0x08, 0x07, 0x03, 0x00, 0x00, 0x1C, 0x22, 0x41, 0x00, 0x00, 0x41, 0x22, 0x1C, 0x00, 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x80, 0x70, 0x30, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x60, 0x60, 0x00, 0x20, 0x10, 0x08, 0x04, 0x02, 0x3E, 0x51, 0x49, 0x45, 0x3E, 0x00, 0x42, 0x7F, 0x40, 0x00, 0x72, 0x49, 0x49, 0x49, 0x46, 0x21, 0x41, 0x49, 0x4D, 0x33, 0x18, 0x14, 0x12, 0x7F, 0x10, 0x27, 0x45, 0x45, 0x45, 0x39, 0x3C, 0x4A, 0x49, 0x49, 0x31, 0x41, 0x21, 0x11, 0x09, 0x07, 0x36, 0x49, 0x49, 0x49, 0x36, 0x46, 0x49, 0x49, 0x29, 0x1E, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x40, 0x34, 0x00, 0x00, 0x00, 0x08, 0x14, 0x22, 0x41, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x41, 0x22, 0x14, 0x08, 0x02, 0x01, 0x59, 0x09, 0x06, 0x3E, 0x41, 0x5D, 0x59, 0x4E, 0x7C, 0x12, 0x11, 0x12, 0x7C, 0x7F, 0x49, 0x49, 0x49, 0x36, 0x3E, 0x41, 0x41, 0x41, 0x22, 0x7F, 0x41, 0x41, 0x41, 0x3E, 0x7F, 0x49, 0x49, 0x49, 0x41, 0x7F, 0x09, 0x09, 0x09, 0x01, 0x3E, 0x41, 0x41, 0x51, 0x73, 0x7F, 0x08, 0x08, 0x08, 0x7F, 0x00, 0x41, 0x7F, 0x41, 0x00, 0x20, 0x40, 0x41, 0x3F, 0x01, 0x7F, 0x08, 0x14, 0x22, 0x41, 0x7F, 0x40, 0x40, 0x40, 0x40, 0x7F, 0x02, 0x1C, 0x02, 0x7F, 0x7F, 0x04, 0x08, 0x10, 0x7F, 0x3E, 0x41, 0x41, 0x41, 0x3E, 0x7F, 0x09, 0x09, 0x09, 0x06, 0x3E, 0x41, 0x51, 0x21, 0x5E, 0x7F, 0x09, 0x19, 0x29, 0x46, 0x26, 0x49, 0x49, 0x49, 0x32, 0x03, 0x01, 0x7F, 0x01, 0x03, 0x3F, 0x40, 0x40, 0x40, 0x3F, 0x1F, 0x20, 0x40, 0x20, 0x1F, 0x3F, 0x40, 0x38, 0x40, 0x3F, 0x63, 0x14, 0x08, 0x14, 0x63, 0x03, 0x04, 0x78, 0x04, 0x03, 0x61, 0x59, 0x49, 0x4D, 0x43, 0x00, 0x7F, 0x41, 0x41, 0x41, 0x02, 0x04, 0x08, 0x10, 0x20, 0x00, 0x41, 0x41, 0x41, 0x7F, 0x04, 0x02, 0x01, 0x02, 0x04, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0x03, 0x07, 0x08, 0x00, 0x20, 0x54, 0x54, 0x78, 0x40, 0x7F, 0x28, 0x44, 0x44, 0x38, 0x38, 0x44, 0x44, 0x44, 0x28, 0x38, 0x44, 0x44, 0x28, 0x7F, 0x38, 0x54, 0x54, 0x54, 0x18, 0x00, 0x08, 0x7E, 0x09, 0x02, 0x18, 0xA4, 0xA4, 0x9C, 0x78, 0x7F, 0x08, 0x04, 0x04, 0x78, 0x00, 0x44, 0x7D, 0x40, 0x00, 0x20, 0x40, 0x40, 0x3D, 0x00, 0x7F, 0x10, 0x28, 0x44, 0x00, 0x00, 0x41, 0x7F, 0x40, 0x00, 0x7C, 0x04, 0x78, 0x04, 0x78, 0x7C, 0x08, 0x04, 0x04, 0x78, 0x38, 0x44, 0x44, 0x44, 0x38, 0xFC, 0x18, 0x24, 0x24, 0x18, 0x18, 0x24, 0x24, 0x18, 0xFC, 0x7C, 0x08, 0x04, 0x04, 0x08, 0x48, 0x54, 0x54, 0x54, 0x24, 0x04, 0x04, 0x3F, 0x44, 0x24, 0x3C, 0x40, 0x40, 0x20, 0x7C, 0x1C, 0x20, 0x40, 0x20, 0x1C, 0x3C, 0x40, 0x30, 0x40, 0x3C, 0x44, 0x28, 0x10, 0x28, 0x44, 0x4C, 0x90, 0x90, 0x90, 0x7C, 0x44, 0x64, 0x54, 0x4C, 0x44, 0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x36, 0x08, 0x00, 0x02, 0x01, 0x02, 0x04, 0x02, 0x3C, 0x26, 0x23, 0x26, 0x3C, 0x1E, 0xA1, 0xA1, 0x61, 0x12, 0x3A, 0x40, 0x40, 0x20, 0x7A, 0x38, 0x54, 0x54, 0x55, 0x59, 0x21, 0x55, 0x55, 0x79, 0x41, 0x22, 0x54, 0x54, 0x78, 0x42, // a-umlaut 0x21, 0x55, 0x54, 0x78, 0x40, 0x20, 0x54, 0x55, 0x79, 0x40, 0x0C, 0x1E, 0x52, 0x72, 0x12, 0x39, 0x55, 0x55, 0x55, 0x59, 0x39, 0x54, 0x54, 0x54, 0x59, 0x39, 0x55, 0x54, 0x54, 0x58, 0x00, 0x00, 0x45, 0x7C, 0x41, 0x00, 0x02, 0x45, 0x7D, 0x42, 0x00, 0x01, 0x45, 0x7C, 0x40, 0x7D, 0x12, 0x11, 0x12, 0x7D, // A-umlaut 0xF0, 0x28, 0x25, 0x28, 0xF0, 0x7C, 0x54, 0x55, 0x45, 0x00, 0x20, 0x54, 0x54, 0x7C, 0x54, 0x7C, 0x0A, 0x09, 0x7F, 0x49, 0x32, 0x49, 0x49, 0x49, 0x32, 0x3A, 0x44, 0x44, 0x44, 0x3A, // o-umlaut 0x32, 0x4A, 0x48, 0x48, 0x30, 0x3A, 0x41, 0x41, 0x21, 0x7A, 0x3A, 0x42, 0x40, 0x20, 0x78, 0x00, 0x9D, 0xA0, 0xA0, 0x7D, 0x3D, 0x42, 0x42, 0x42, 0x3D, // O-umlaut 0x3D, 0x40, 0x40, 0x40, 0x3D, 0x3C, 0x24, 0xFF, 0x24, 0x24, 0x48, 0x7E, 0x49, 0x43, 0x66, 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, 0xFF, 0x09, 0x29, 0xF6, 0x20, 0xC0, 0x88, 0x7E, 0x09, 0x03, 0x20, 0x54, 0x54, 0x79, 0x41, 0x00, 0x00, 0x44, 0x7D, 0x41, 0x30, 0x48, 0x48, 0x4A, 0x32, 0x38, 0x40, 0x40, 0x22, 0x7A, 0x00, 0x7A, 0x0A, 0x0A, 0x72, 0x7D, 0x0D, 0x19, 0x31, 0x7D, 0x26, 0x29, 0x29, 0x2F, 0x28, 0x26, 0x29, 0x29, 0x29, 0x26, 0x30, 0x48, 0x4D, 0x40, 0x20, 0x38, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x38, 0x2F, 0x10, 0xC8, 0xAC, 0xBA, 0x2F, 0x10, 0x28, 0x34, 0xFA, 0x00, 0x00, 0x7B, 0x00, 0x00, 0x08, 0x14, 0x2A, 0x14, 0x22, 0x22, 0x14, 0x2A, 0x14, 0x08, 0xAA, 0x00, 0x55, 0x00, 0xAA, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x10, 0x10, 0x10, 0xFF, 0x00, 0x14, 0x14, 0x14, 0xFF, 0x00, 0x10, 0x10, 0xFF, 0x00, 0xFF, 0x10, 0x10, 0xF0, 0x10, 0xF0, 0x14, 0x14, 0x14, 0xFC, 0x00, 0x14, 0x14, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x14, 0x14, 0xF4, 0x04, 0xFC, 0x14, 0x14, 0x17, 0x10, 0x1F, 0x10, 0x10, 0x1F, 0x10, 0x1F, 0x14, 0x14, 0x14, 0x1F, 0x00, 0x10, 0x10, 0x10, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x10, 0x10, 0x10, 0x10, 0xF0, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x14, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x1F, 0x10, 0x17, 0x00, 0x00, 0xFC, 0x04, 0xF4, 0x14, 0x14, 0x17, 0x10, 0x17, 0x14, 0x14, 0xF4, 0x04, 0xF4, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xF7, 0x00, 0xF7, 0x14, 0x14, 0x14, 0x17, 0x14, 0x10, 0x10, 0x1F, 0x10, 0x1F, 0x14, 0x14, 0x14, 0xF4, 0x14, 0x10, 0x10, 0xF0, 0x10, 0xF0, 0x00, 0x00, 0x1F, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x1F, 0x14, 0x00, 0x00, 0x00, 0xFC, 0x14, 0x00, 0x00, 0xF0, 0x10, 0xF0, 0x10, 0x10, 0xFF, 0x10, 0xFF, 0x14, 0x14, 0x14, 0xFF, 0x14, 0x10, 0x10, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x38, 0x44, 0x44, 0x38, 0x44, 0xFC, 0x4A, 0x4A, 0x4A, 0x34, // sharp-s or beta 0x7E, 0x02, 0x02, 0x06, 0x06, 0x02, 0x7E, 0x02, 0x7E, 0x02, 0x63, 0x55, 0x49, 0x41, 0x63, 0x38, 0x44, 0x44, 0x3C, 0x04, 0x40, 0x7E, 0x20, 0x1E, 0x20, 0x06, 0x02, 0x7E, 0x02, 0x02, 0x99, 0xA5, 0xE7, 0xA5, 0x99, 0x1C, 0x2A, 0x49, 0x2A, 0x1C, 0x4C, 0x72, 0x01, 0x72, 0x4C, 0x30, 0x4A, 0x4D, 0x4D, 0x30, 0x30, 0x48, 0x78, 0x48, 0x30, 0xBC, 0x62, 0x5A, 0x46, 0x3D, 0x3E, 0x49, 0x49, 0x49, 0x00, 0x7E, 0x01, 0x01, 0x01, 0x7E, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x44, 0x44, 0x5F, 0x44, 0x44, 0x40, 0x51, 0x4A, 0x44, 0x40, 0x40, 0x44, 0x4A, 0x51, 0x40, 0x00, 0x00, 0xFF, 0x01, 0x03, 0xE0, 0x80, 0xFF, 0x00, 0x00, 0x08, 0x08, 0x6B, 0x6B, 0x08, 0x36, 0x12, 0x36, 0x24, 0x36, 0x06, 0x0F, 0x09, 0x0F, 0x06, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x30, 0x40, 0xFF, 0x01, 0x01, 0x00, 0x1F, 0x01, 0x01, 0x1E, 0x00, 0x19, 0x1D, 0x17, 0x12, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00 }; #endif // FONT5X7_H
the_stack_data/1254455.c
#include <stdio.h> int main() { float nA, nB, nM; char m; int continuar = 0; int se = 0; printf("Média Ponderada\n"); do{ printf("\nDigite a Nota A: "); scanf("%f", &nA); printf("\nDigite a Nota B: "); scanf("%f", &nB); nM=((nA+nB)/2); printf("\nMédia do Aluno: %.2f\n", nM); do{ printf("\nContinuar ? s/n"); scanf(" %c", &m); switch(m){ case 's': se = 1; continuar = 1; break; case 'n': se = 1; continuar = 0; break; default: se = 0; printf("Resposta Invalida\n"); break; } } while (se != 1); } while (continuar != 0); return 0; }
the_stack_data/896039.c
#include<stdio.h> void main(){ printf("Hello World!!"); }
the_stack_data/524307.c
/* strcasecmp.c -- case insensitive string comparator Copyright (C) 1998, 1999 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #if HAVE_CONFIG_H # include <config.h> #endif #define LENGTH_LIMIT #ifdef LENGTH_LIMIT # define STRXCASECMP_FUNCTION strncasecmp # define STRXCASECMP_DECLARE_N , size_t n # define LENGTH_LIMIT_EXPR(Expr) Expr #else # define STRXCASECMP_FUNCTION strcasecmp # define STRXCASECMP_DECLARE_N /* empty */ # define LENGTH_LIMIT_EXPR(Expr) 0 #endif #include <stddef.h> #include <ctype.h> #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch)) /* Compare {{no more than N characters of }}strings S1 and S2, ignoring case, returning less than, equal to or greater than zero if S1 is lexicographically less than, equal to or greater than S2. */ int STRXCASECMP_FUNCTION (const char *s1, const char *s2 STRXCASECMP_DECLARE_N) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; unsigned char c1, c2; if (p1 == p2 || LENGTH_LIMIT_EXPR (n == 0)) return 0; do { c1 = TOLOWER (*p1); c2 = TOLOWER (*p2); if (LENGTH_LIMIT_EXPR (--n == 0) || c1 == '\0') break; ++p1; ++p2; } while (c1 == c2); return c1 - c2; }
the_stack_data/61076512.c
#include <stdio.h> #include <stdlib.h> /*************************************Prototypes************************************/ int testFloatEquality(double number1, double number2, double accuracy);//Tests a floats equality to a specified precision void clearScreen();//Clears the screen if system is a variable name int kelvinToCelcius(unsigned int kelvin);//Converts Kelvin to Celcius float newAverage(float newSample, float currentAverage, int newCount); float runningAverage(float newSample, int count, float oldAverage);//Adds a new value to a running average float sumOfAverages(float average1, float average2, int count1, int count2);//Adds two averaged numbers together void floatBubbleSort(float array[], int numberElements, int sortDirection);//Bubble Sort for Floats /************************************Functions**************************************/ //Compares two floats for equality to a specified degree of precision //A 1 is returned if the two numbers are equal //A 0 is returned if they are not equal (At least to the level of precision desired) int testFloatEquality(double number1, double number2, double accuracy) { if((number1 > (number2 - accuracy)) && (number1 < (number2 + accuracy))) return 1; //They are equal to this level of accuracy else return 0; //They are not equal to this level of accuracy return 0;//Uh oh... } void clearScreen() { //system("cls"); return; } //Converts Kelvin to Celcius int kelvinToCelcius(unsigned int kelvin) { return kelvin - 273;//I dropped the 0.15, so the conversion will accept integers and then return them } //Adds a single number to an existing average //Requires the new number, the average, and the number of values in the average (Inlcuding the new number) float newAverage(float newSample, float currentAverage, int newCount) { float average; average = currentAverage + (newSample - currentAverage) / newCount; return average; } //Adds a new value to a running average float runningAverage(float newSample, int count, float oldAverage) { if(count == 0) count = 1; return oldAverage + (newSample - oldAverage) / count; } //Adds two averaged numbers together float sumOfAverages(float average1, float average2, int count1, int count2) { if(count1 == 0) count1 = 1; if(count2 == 0) count2 = 1; return (average1 * count1 + average2 * count2) / (count1 + count2); } //sortDirection = 1 then highest to lowest, sortDirection = 0 then lowest to highest //This is a Bubble Sort implementation I borrowed from the internet and modified slightly void floatBubbleSort(float array[], int numberElements, int sortDirection) { int i, j; float temp; if(sortDirection == 1) { for(i = (numberElements - 1); i < 0; ++i) for(j = (numberElements - ( i + 1 )); j < 0; ++j) if(array[j] < array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } else if(sortDirection == 0) { for(i = 0; i < (numberElements - 1); ++i) for(j = 0; j < (numberElements - ( i + 1 )); ++j) if(array[j] < array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } else printf("Invalid sorting chosen\n"); return; }
the_stack_data/150140970.c
/* * Copyright (c) 2019 Bose Corporation * Copyright (c) 2020-2021 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifdef CONFIG_BT_CSIS_CLIENT #include <zephyr/bluetooth/addr.h> #include <zephyr/bluetooth/audio/csis.h> #include "common.h" extern enum bst_result_t bst_result; static volatile bool is_connected; static volatile bool discovered; static volatile bool members_discovered; static volatile bool set_locked; static volatile bool set_unlocked; static volatile bool set_read_locked; static volatile bool set_read_unlocked; static struct bt_csis_client_csis_inst *inst; static uint8_t members_found; static struct k_work_delayable discover_members_timer; static bt_addr_le_t addr_found[CONFIG_BT_MAX_CONN]; static struct bt_csis_client_set_member set_members[CONFIG_BT_MAX_CONN]; static void csis_client_lock_set_cb(int err); static void csis_client_lock_release_cb(int err) { printk("%s\n", __func__); if (err != 0) { FAIL("Release sets failed (%d)\n", err); return; } set_unlocked = true; } static void csis_client_lock_set_cb(int err) { printk("%s\n", __func__); if (err != 0) { FAIL("Lock sets failed (%d)\n", err); return; } set_locked = true; } static void csis_discover_cb(struct bt_csis_client_set_member *member, int err, uint8_t set_count) { printk("%s\n", __func__); if (err != 0) { FAIL("Init failed (%d)\n", err); return; } inst = &member->insts[0]; discovered = true; } static void csis_lock_changed_cb(struct bt_csis_client_csis_inst *inst, bool locked) { printk("Inst %p %s\n", inst, locked ? "locked" : "released"); } static void csis_client_lock_state_read_cb(const struct bt_csis_client_set_info *set_info, int err, bool locked) { printk("%s\n", __func__); if (err != 0) { FAIL("read lock state failed (%d)\n", err); return; } if (locked) { set_read_locked = true; } else { set_read_unlocked = true; } } static void connected(struct bt_conn *conn, uint8_t err) { char addr[BT_ADDR_LE_STR_LEN]; if (is_connected) { return; } bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); if (err != 0) { bt_conn_unref(default_conn); default_conn = NULL; FAIL("Failed to connect to %s (%u)\n", addr, err); return; } printk("Connected to %s\n", addr); is_connected = true; } static struct bt_conn_cb conn_callbacks = { .connected = connected, }; static struct bt_csis_client_cb cbs = { .lock_set = csis_client_lock_set_cb, .release_set = csis_client_lock_release_cb, .discover = csis_discover_cb, .lock_changed = csis_lock_changed_cb, .lock_state_read = csis_client_lock_state_read_cb, }; static bool is_discovered(const bt_addr_le_t *addr) { for (int i = 0; i < members_found; i++) { if (bt_addr_le_cmp(addr, &addr_found[i]) == 0) { return true; } } return false; } static bool csis_found(struct bt_data *data, void *user_data) { if (bt_csis_client_is_set_member(inst->info.set_sirk, data)) { const bt_addr_le_t *addr = user_data; char addr_str[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(addr, addr_str, sizeof(addr_str)); printk("Found CSIS advertiser with address %s\n", addr_str); if (is_discovered(addr)) { printk("Set member already found\n"); /* Stop parsing */ return false; } bt_addr_le_copy(&addr_found[members_found++], addr); printk("Found member (%u / %u)\n", members_found, inst->info.set_size); /* Stop parsing */ return false; } /* Continue parsing */ return true; } static void csis_client_scan_recv(const struct bt_le_scan_recv_info *info, struct net_buf_simple *ad) { /* We're only interested in connectable events */ if (info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) { if (inst == NULL) { /* Scanning for the first device */ if (members_found == 0) { bt_addr_le_copy(&addr_found[members_found++], info->addr); } } else { /* Scanning for set members */ bt_data_parse(ad, csis_found, (void *)info->addr); } } } static struct bt_le_scan_cb csis_client_scan_callbacks = { .recv = csis_client_scan_recv }; static void discover_members_timer_handler(struct k_work *work) { FAIL("Could not find all members (%u / %u)\n", members_found, inst->info.set_size); } static void read_set_lock_state(const struct bt_csis_client_set_member **members, uint8_t count, bool expect_locked) { int err; printk("Reading set state, expecting %s\n", expect_locked ? "locked" : "unlocked"); if (expect_locked) { set_read_locked = false; } else { set_read_unlocked = false; } err = bt_csis_client_get_lock_state(members, count, &inst->info); if (err != 0) { FAIL("Failed to do CSIS client read lock state (%d)", err); return; } if (expect_locked) { WAIT_FOR_COND(set_read_locked); } else { WAIT_FOR_COND(set_read_unlocked); } } static void test_main(void) { int err; char addr[BT_ADDR_LE_STR_LEN]; const struct bt_csis_client_set_member *locked_members[CONFIG_BT_MAX_CONN]; uint8_t connected_member_count = 0; err = bt_enable(NULL); if (err != 0) { FAIL("Bluetooth init failed (err %d)\n", err); return; } printk("Audio Client: Bluetooth initialized\n"); bt_conn_cb_register(&conn_callbacks); bt_csis_client_register_cb(&cbs); k_work_init_delayable(&discover_members_timer, discover_members_timer_handler); bt_le_scan_cb_register(&csis_client_scan_callbacks); err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, NULL); if (err != 0) { FAIL("Scanning failed to start (err %d)\n", err); return; } printk("Scanning successfully started\n"); WAIT_FOR_COND(members_found == 1); printk("Stopping scan\n"); err = bt_le_scan_stop(); if (err != 0) { FAIL("Could not stop scan"); return; } bt_addr_le_to_str(&addr_found[0], addr, sizeof(addr)); err = bt_conn_le_create(&addr_found[0], BT_CONN_LE_CREATE_CONN, BT_LE_CONN_PARAM_DEFAULT, &set_members[0].conn); if (err != 0) { FAIL("Failed to connect to %s: %d\n", err); return; } printk("Connecting to %s\n", addr); WAIT_FOR_COND(is_connected); connected_member_count++; err = bt_csis_client_discover(&set_members[0]); if (err != 0) { FAIL("Failed to initialize CSIS client for connection %d\n", err); return; } WAIT_FOR_COND(discovered); err = bt_le_scan_start(BT_LE_SCAN_ACTIVE, NULL); if (err != 0) { FAIL("Could not start scan: %d", err); return; } err = k_work_reschedule(&discover_members_timer, CSIS_CLIENT_DISCOVER_TIMER_VALUE); if (err < 0) { /* Can return 0, 1 and 2 for success */ FAIL("Could not schedule discover_members_timer %d", err); return; } WAIT_FOR_COND(members_found == inst->info.set_size); (void)k_work_cancel_delayable(&discover_members_timer); err = bt_le_scan_stop(); if (err != 0) { FAIL("Scanning failed to stop (err %d)\n", err); return; } for (uint8_t i = 1; i < members_found; i++) { bt_addr_le_to_str(&addr_found[i], addr, sizeof(addr)); is_connected = false; printk("Connecting to member[%d] (%s)", i, addr); err = bt_conn_le_create(&addr_found[i], BT_CONN_LE_CREATE_CONN, BT_LE_CONN_PARAM_DEFAULT, &set_members[i].conn); if (err != 0) { FAIL("Failed to connect to %s: %d\n", addr, err); return; } printk("Connected to %s\n", addr); WAIT_FOR_COND(is_connected); connected_member_count++; discovered = false; printk("Doing discovery on member[%u]", i); err = bt_csis_client_discover(&set_members[i]); if (err != 0) { FAIL("Failed to initialize CSIS client for connection %d\n", err); return; } WAIT_FOR_COND(discovered); } for (size_t i = 0; i < ARRAY_SIZE(locked_members); i++) { locked_members[i] = &set_members[i]; } read_set_lock_state(locked_members, connected_member_count, false); printk("Locking set\n"); err = bt_csis_client_lock(locked_members, connected_member_count, &inst->info); if (err != 0) { FAIL("Failed to do CSIS client lock (%d)", err); return; } WAIT_FOR_COND(set_locked); read_set_lock_state(locked_members, connected_member_count, true); k_sleep(K_MSEC(1000)); /* Simulate doing stuff */ printk("Releasing set\n"); err = bt_csis_client_release(locked_members, connected_member_count, &inst->info); if (err != 0) { FAIL("Failed to do CSIS client release (%d)", err); return; } WAIT_FOR_COND(set_unlocked); read_set_lock_state(locked_members, connected_member_count, false); /* Lock and unlock again */ set_locked = false; set_unlocked = false; printk("Locking set\n"); err = bt_csis_client_lock(locked_members, connected_member_count, &inst->info); if (err != 0) { FAIL("Failed to do CSIS client lock (%d)", err); return; } WAIT_FOR_COND(set_locked); k_sleep(K_MSEC(1000)); /* Simulate doing stuff */ printk("Releasing set\n"); err = bt_csis_client_release(locked_members, connected_member_count, &inst->info); if (err != 0) { FAIL("Failed to do CSIS client release (%d)", err); return; } WAIT_FOR_COND(set_unlocked); for (uint8_t i = 0; i < members_found; i++) { printk("Disconnecting member[%u] (%s)", i, addr); err = bt_conn_disconnect(set_members[i].conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); (void)memset(&set_members[i], 0, sizeof(set_members[i])); if (err != 0) { FAIL("Failed to do disconnect\n", err); return; } } PASS("All members disconnected\n"); } static const struct bst_test_instance test_connect[] = { { .test_id = "csis_client", .test_post_init_f = test_init, .test_tick_f = test_tick, .test_main_f = test_main }, BSTEST_END_MARKER }; struct bst_test_list *test_csis_client_install(struct bst_test_list *tests) { return bst_add_tests(tests, test_connect); } #else struct bst_test_list *test_csis_client_install(struct bst_test_list *tests) { return tests; } #endif /* CONFIG_BT_CSIS_CLIENT */
the_stack_data/68888294.c
# include<stdio.h> void knapsack(int n, float weight[], float profit[], float capacity) { float x[20], tp = 0; int i, j, u; u = capacity; for (i = 0; i < n; i++) x[i] = 0.0; for (i = 0; i < n; i++) { if (weight[i] > u) break; else { x[i] = 1.0; tp = tp + profit[i]; u = u - weight[i]; } } if (i < n) x[i] = u / weight[i]; tp = tp + (x[i] * profit[i]); printf("\nThe result vector is:- "); for (i = 0; i < n; i++) printf("%f\t", x[i]); printf("\nMaximum profit is:- %f", tp); } int main() { float weight[20], profit[20], capacity; int num, i, j; float ratio[20], temp; printf("\nEnter the no. of objects:- "); scanf("%d", &num); printf("\nEnter the wts and profits of each object:- "); for (i = 0; i < num; i++) { scanf("%f %f", &weight[i], &profit[i]); } printf("\nEnter the capacityacity of knapsack:- "); scanf("%f", &capacity); for (i = 0; i < num; i++) { ratio[i] = profit[i] / weight[i]; } for (i = 0; i < num; i++) { for (j = i + 1; j < num; j++) { if (ratio[i] < ratio[j]) { temp = ratio[j]; ratio[j] = ratio[i]; ratio[i] = temp; temp = weight[j]; weight[j] = weight[i]; weight[i] = temp; temp = profit[j]; profit[j] = profit[i]; profit[i] = temp; } } } knapsack(num, weight, profit, capacity); return(0); }
the_stack_data/53618.c
#include <stdio.h> #include <stdlib.h> struct v_table{ double (*value_at)(); }; struct Unary_Function{ int lower_bound; int upper_bound; double a; double b; struct v_table value_at_v_table; }; void tabulate(struct Unary_Function* f){ for(int x = f->lower_bound; x <= f->upper_bound; x++) { printf("f(%d)=%lf\n", x, f->value_at_v_table.value_at(f, (double)x)); } } double square_value_at(struct Unary_Function* f, double x){ return x*x; } double linear_value_at(struct Unary_Function* f, double x){ return f->a * x + f->b; } void generate_square(struct Unary_Function* f, int lower_bound, int upper_bound){ f->lower_bound = lower_bound; f->upper_bound = upper_bound; f->a = 0; f->b = 0; f->value_at_v_table.value_at = &square_value_at; } void generate_linear(struct Unary_Function* f, int lower_bound, int upper_bound, double a, double b){ f->lower_bound = lower_bound; f->upper_bound = upper_bound; f->a = a; f->b = b; f->value_at_v_table.value_at = &linear_value_at; } struct Unary_Function* Square(int lower_bound, int upper_bound){ struct Unary_Function* f = malloc(sizeof(struct Unary_Function)); generate_square(f, lower_bound, upper_bound); return f; } struct Unary_Function* Linear(int lower_bound, int upper_bound, double a, double b){ struct Unary_Function* f = malloc(sizeof(struct Unary_Function)); generate_linear(f, lower_bound, upper_bound, a, b); return f; } double value_at(struct Unary_Function* f1, double x){ return f1->value_at_v_table.value_at(x); } double negative_value_at(struct Unary_Function* f1, double x){ return -(f1->value_at_v_table.value_at(x)); } int same_functions_for_ints(struct Unary_Function *f1, struct Unary_Function *f2, double tolerance) { if(f1->lower_bound != f2->lower_bound) return 0; if(f1->upper_bound != f2->upper_bound) return 0; for(int x = f1->lower_bound; x <= f1->upper_bound; x++) { double delta = value_at(f1, x) - value_at(f2, x); if(delta < 0) delta = -delta; if(delta > tolerance) return 0; } return 1; }; int main(void){ struct Unary_Function *f1 = Square(-2, 2); tabulate(f1); struct Unary_Function *f2 = Linear(-2, 2, 5, -2); tabulate(f2); printf("f1==f2: %s\n", same_functions_for_ints(f1, f2, 1E-6) ? "DA" : "NE"); printf("neg_val f2(1) = %lf\n", negative_value_at(f2, 1.0)); free(f1); free(f2); return 0; }
the_stack_data/372831.c
#include <stdio.h> #include <stdlib.h> #include <string.h> /* s : a char array */ char* sdstrim(char *s, const char *cset) { char *start, *end, *sp, *ep; size_t len; sp = start = s; /*searched start pointer*/ ep = end = s+strlen(s)-1; /*searched end pointer*/ while(sp <= end && strchr(cset, *sp)) sp++; while(ep > sp && strchr(cset, *ep)) ep--; len = (sp > ep) ? 0 : ((ep-sp)+1); if (s != sp) memmove(s, sp, len); s[len] = '\0'; return s; } int main(int argc, char *argv[]){ char s[128]="AAAA.... heallo ...aaa"; char *p = sdstrim(s, "A. a"); printf("strim:%s\n",p); return 0; }
the_stack_data/95790.c
/* text version of maze 'mazefiles/binary/kpnu1.maz' generated by mazetool (c) Peter Harrison 2018 o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o | | | | o o---o o---o o---o o---o o o o o o---o o---o | | | | | | | | | | | o---o o---o o---o o---o o---o o o o o---o o---o | | | | | | | | | o o---o o---o o---o o---o o---o---o---o---o---o o---o | | | | | | | | | | o o o---o o---o o---o o o o o o o---o o---o | | | | | | | | | | o o---o o---o o---o o o o o o---o---o o o---o | | | | | | | | | | o o o---o o---o o---o o o---o o---o o---o o---o | | | | | | | | | | | | o o o o o o o o o---o o o o---o o o o | | | | | | | | | | | o o o o---o o---o o o o---o---o---o---o---o---o---o | | | | | | | o o o o o o---o o---o---o---o o---o o---o---o o | | | | | | | | | | | o o o o o o o---o o o o---o o---o o o o | | | | | | | | | | | | | o o o o o o o o---o---o---o o---o o---o o o | | | | | | | | | | | | o o o---o o o o---o o o o---o o---o o---o o | | | | | | o---o---o---o---o o o---o o---o o---o---o o---o o o | | | | | | | | | o o---o o o---o o o---o o---o---o o---o o---o o | | | | | | | | | o o o o---o o---o o o---o o o---o o---o o---o | | | | | | | | o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o */ int kpnu1_maz[] ={ 0x0E, 0x0A, 0x09, 0x0C, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x09, 0x0E, 0x09, 0x0E, 0x0B, 0x05, 0x04, 0x0A, 0x0A, 0x02, 0x08, 0x0A, 0x0A, 0x09, 0x06, 0x09, 0x06, 0x09, 0x05, 0x0C, 0x0A, 0x03, 0x05, 0x0C, 0x0A, 0x0A, 0x00, 0x0A, 0x09, 0x06, 0x09, 0x06, 0x09, 0x06, 0x01, 0x05, 0x0C, 0x09, 0x04, 0x02, 0x0A, 0x0A, 0x03, 0x0E, 0x02, 0x09, 0x06, 0x09, 0x06, 0x09, 0x05, 0x06, 0x01, 0x04, 0x02, 0x0A, 0x0A, 0x08, 0x08, 0x0A, 0x09, 0x06, 0x09, 0x06, 0x09, 0x06, 0x01, 0x0D, 0x06, 0x02, 0x0A, 0x0A, 0x0A, 0x03, 0x05, 0x0E, 0x02, 0x09, 0x06, 0x09, 0x06, 0x09, 0x05, 0x04, 0x0A, 0x09, 0x0D, 0x0C, 0x0B, 0x0C, 0x02, 0x0A, 0x0B, 0x06, 0x0B, 0x06, 0x09, 0x06, 0x01, 0x06, 0x09, 0x06, 0x00, 0x03, 0x0C, 0x03, 0x0C, 0x08, 0x0A, 0x08, 0x0A, 0x0B, 0x06, 0x09, 0x05, 0x0D, 0x04, 0x0B, 0x04, 0x0B, 0x04, 0x0B, 0x06, 0x03, 0x0E, 0x02, 0x08, 0x0A, 0x0B, 0x06, 0x01, 0x04, 0x03, 0x0C, 0x00, 0x09, 0x06, 0x09, 0x0D, 0x0E, 0x09, 0x0E, 0x02, 0x09, 0x0C, 0x0A, 0x03, 0x06, 0x09, 0x07, 0x05, 0x06, 0x09, 0x06, 0x01, 0x0C, 0x02, 0x08, 0x08, 0x03, 0x06, 0x0A, 0x09, 0x0D, 0x04, 0x09, 0x06, 0x09, 0x06, 0x09, 0x05, 0x04, 0x09, 0x07, 0x06, 0x09, 0x0C, 0x0A, 0x03, 0x06, 0x01, 0x06, 0x09, 0x06, 0x09, 0x06, 0x03, 0x05, 0x04, 0x09, 0x0E, 0x03, 0x06, 0x0A, 0x09, 0x0D, 0x06, 0x09, 0x06, 0x09, 0x06, 0x09, 0x0D, 0x04, 0x03, 0x06, 0x09, 0x0D, 0x0D, 0x0D, 0x05, 0x04, 0x09, 0x06, 0x09, 0x06, 0x0A, 0x03, 0x05, 0x04, 0x0A, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x06, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x03, 0x06, 0x0B, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, }; /* end of mazefile */
the_stack_data/156393612.c
#include <sys/socket.h> #include <linux/if_packet.h> #include <linux/if_ether.h> #include <linux/if_arp.h> #include <stdlib.h> #include <string.h> #include <stdio.h> //#include <net/if.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> int main(int argc, char **argv) { int j=0; int s; struct ifreq ifr; FILE *fp; struct stat fileStatus; char segment[50]; srand ( time(NULL) ); int colorCode; struct sockaddr_ll socket_address; bzero(&socket_address, sizeof(socket_address)); bzero(&ifr, sizeof(ifr)); /*buffer for ethernet frame*/ void* buffer = (void*)malloc(ETH_FRAME_LEN); /*pointer to ethenet header*/ unsigned char* etherhead = (unsigned char*)buffer; unsigned char* data = (unsigned char*)buffer + 14; struct ethhdr *eh = (struct ethhdr *)etherhead; int res = 0; unsigned char src_mac[6] = {0x00, 0x15, 0x17, 0x1E, 0x04, 0x12}; unsigned char dest_mac[6] = {0x00, 0x4E, 0x46, 0x32, 0x43, 0x00}; s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (s == -1) { printf("Error creating raw socket!\n"); exit(0); } memset(&ifr,0, sizeof(struct ifreq)); strncpy((char *)ifr.ifr_name,"eth2",IFNAMSIZ); if(ioctl(s, SIOCGIFINDEX, &ifr) < 0) { perror("ioctl SIOCGIFINDEX"); exit(1); } printf("index %d\n",ifr.ifr_ifindex); /*RAW communication*/ socket_address.sll_family = AF_PACKET; socket_address.sll_ifindex = ifr.ifr_ifindex; /*we don't use a protocoll above ethernet layer ->just use anything here*/ socket_address.sll_protocol = htons(ETH_P_ALL); /*ARP hardware identifier is ethernet*/ socket_address.sll_hatype = ARPHRD_ETHER; /*target is another host*/ socket_address.sll_pkttype = PACKET_OTHERHOST; /*address length*/ socket_address.sll_halen = ETH_ALEN; /*MAC - begin*/ socket_address.sll_addr[0] = 0x00; socket_address.sll_addr[1] = 0x4E; socket_address.sll_addr[2] = 0x46; socket_address.sll_addr[3] = 0x32; socket_address.sll_addr[4] = 0x43; socket_address.sll_addr[5] = 0x00; /*MAC - end*/ socket_address.sll_addr[6] = 0x00;/*not used*/ socket_address.sll_addr[7] = 0x00;/*not used*/ /*set the frame header*/ memcpy((void*)buffer, (void*)dest_mac, ETH_ALEN); memcpy((void*)(buffer+ETH_ALEN), (void*)src_mac, ETH_ALEN); eh->h_proto = 0x00; int counter=0,result; memset(segment,'\0',50); while(1) { memset(segment,'\0',50); memset(data,'\0',1500); /* generate color code: */ colorCode = rand() % 4 + 1; printf("Color: %d\n",colorCode); switch(colorCode) { case 1:memcpy(segment,"RED",3); result=3;break; case 2:memcpy(segment,"BLUE",4); result=4;break; case 3:memcpy(segment,"GREEN",5); result=5;break; case 4:memcpy(segment,"YELLOW",6); result=6;break; } /*fill the frame with some data*/ for (j = 0; j < result; j++) { data[j] = segment[j]; } printf("Packet: %s\n",data); /*send the packet*/ res = sendto(s, buffer, ETH_FRAME_LEN, 0, (struct sockaddr*)&socket_address, sizeof(socket_address)); if (res == -1) { printf("Error sending data!\n"); perror(NULL); exit(0); } if(counter % 1000 ==0) { printf("Enter here... \n"); usleep(1000000); } counter++; } close(s); return 0; }
the_stack_data/94418.c
/* Copyright (c) 2016 InternetWide.org and the ARPA2.net project All rights reserved. See file LICENSE for exact terms (2-clause BSD license). Adriaan de Groot <[email protected]> */ /** * This file is for use with C programs that call into write_logger() * but don't actually link with swcommon (which is the bridge from * write_logger() to log4cpp). So instead of logging, this just goes * back to printf(). */ #include <stdio.h> void write_logger(const char* logname, const char* message) { printf("%s: %s\n", logname, message); }
the_stack_data/52590.c
/**ARGS: symbols --locate -d -u --must -DFOO -UBAR */ /**SYSCODE: = 2 */ #ifdef FOO #undef FOO #else #define FOO 1 #endif #ifndef BAR #define BAR 1 #else #undef BAR #endif
the_stack_data/179831393.c
#pragma bss-name(push, "ZEROPAGE") unsigned char arg1; unsigned char arg2; unsigned char pad1; unsigned char pad1_new; unsigned char temp, i, temp_x, temp_y, temp_char, temp_attr, temp_bank; unsigned int temp_int, temp_int_x, temp_int_y; #pragma bss-name(pop)
the_stack_data/130730.c
#include <string.h> int mx_strlen(const char *s) { int res = 0; while (s[res] != '\0') { res++; } return res; }
the_stack_data/117076.c
//#include<mpi.h> double * u; int nx = 10; /*@ @ requires \valid(u + (0 .. 10)); @ requires nx > 10; @*/ void update(int x) { for (int i = 0; i < nx; i++) u[i] = u[i]*2; } int main() { int dummy = 7; update(0); dummy=8; return 0; }
the_stack_data/38281.c
#include <stdio.h> int main(int argc, char *argv[]) { int i = 0; if (argc == 1) { printf("You only have one argument. You suck.\n"); } else if (argc > 1 && argc < 4) { printf("Here's your arguments:\n"); for (i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); } else { printf("You have too many arguments. You suck.\n"); } return 0; }
the_stack_data/370562.c
#include<stdio.h> #include<math.h> void main(){ int a[10],o=0,e=0,i,y; for(i=0;i<=9;i++){ printf("Enter the %d No.",(i+1)); scanf("%d",&y); a[i]=y; if((i+1)%2==0) { o=o+a[i]; } else{ e=e+a[i]; } } printf("Sum of\n Even No.s is %d \n Odd No. is %d \n",e,o); }
the_stack_data/212642424.c
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <string.h> #define MAXLINE 1024 #define ARGV_N 64 void pr_exit(int status); void main() { char buf[MAXLINE]; char *args[ARGV_N]; pid_t pid; int status, i; // Print promp printf("%%> "); // Reads while read != NULL while( fgets(buf, MAXLINE, stdin)){ printf("-------------------------------\n"); // fputs( buf, stdout); // Change newline smybol to null buf[strlen(buf) - 1] = 0; // Create a child pid = vfork(); if ( pid < 0) { // Error perror("fork"); exit(1); } else if ( pid == 0) { // child printf("Izpis argumentov:\n"); // Split and save the first word args[i] = strtok(buf," "); i = 0; // While there are other words, split and save while(args[i]!=NULL) { args[++i] = strtok(NULL," "); } // Save null at the end of the string args[i + 1] = 0; i = 0; // Output arguments while(args[i]!=NULL) { printf("args[%d]: ",i); printf("%s\n", args[i++]); } printf("-------------------------------\n"); printf("\n"); // Run command execvp( args[0], args); // If this part of the code gets accessed, there must be an error. perror("exec"); exit(1); } else { // parent if ( (pid = waitpid(pid, &status, 0)) < 0) { perror("waitpid"); } printf("\n-------------------------------\n"); printf("Otrok je vrnil status %d (0x%X)\n", status, status); pr_exit(status); printf("-------------------------------\n"); printf("%%> "); } } exit(0); } void pr_exit(int status) { if (WIFEXITED(status)) printf("normal termination, exit status = %d\n", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (core file generated)" : ""); else if (WIFSTOPPED(status)) printf("child stopped, signal number = %d\n", WSTOPSIG(status)); }
the_stack_data/150142423.c
#include <stdio.h> #include <sys/mman.h> #include <stdlib.h> int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0); int foo_value = 0; unsigned char code[256]; // = "\xb8\x0a\x00\x00\x00\xc3"; printf("Input your function:\n"); scanf("%s", &code); int (*foo)(int) = (int(*)())code; foo_value = foo(1); if (foo(10) == 16 && foo(32) == 64) { system("/bin/cat /flag"); } printf("result: %d\n", foo_value); }
the_stack_data/40762249.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* getnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tdragos <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/10 13:40:54 by tdragos #+# #+# */ /* Updated: 2018/02/10 13:40:56 by tdragos ### ########.fr */ /* */ /* ************************************************************************** */ int getnbr(char *s) { int i; int n; int sign; i = 0; n = 0; sign = 1; if (s[0] == '-') sign = -1; while (s[i] != '\0' && s[i] != '\n') { if (s[i] >= '0' && s[i] <= '9') n = n * 10 + ((int)(s[i]) - (int)('0')); i++; } return (n * sign); }
the_stack_data/39109.c
// // main.c // DNA-Edit-Distance-Calculator // // Created by MTX on 2022/3/10. // #include <stdio.h> #define M 4 #define N 6 //char A[M] = "CTGA"; //char B[N] = "ACGCTA"; char A[M]; char B[N]; int d[M+1][N+1]; // d[row][column] int min(int a, int b) { return a < b ? a : b; } void print2DArr(int d[M+1][N+1]) { for (int i = 0; i < M+1; i++) { for (int j = 0; j < N+1; j++) { printf("%d ", d[i][j]); } printf("\n"); } printf("\n"); } int editdistance(char *str1, int len1, char *str2, int len2) { int i,j; // int diff; int temp; for(i = 0; i <= len1; i++) { d[i][0] = i; } print2DArr(d); for(j = 0; j <= len2; j++) { d[0][j] = j; } print2DArr(d); for(i = 1; i <= len1; i++) { for(j = 1; j<= len2; j++) { if(str1[i-1] == str2[j-1]) { d[i][j] = d[i-1][j-1]; // print2DArr(d); }else{ temp = min(d[i-1][j] + 1, d[i][j-1] + 1); d[i][j] = min(temp, d[i-1][j-1] + 1); // print2DArr(d); } } } print2DArr(d); return d[len1][len2]; } int main(int argc, const char * argv[]) { printf("input char[%d]:", M); scanf("%s", A);//CTGA printf("input char[%d]:", N); scanf("%s", B);//ACGCTA int distance = editdistance(A, M, B, N); printf("distance:%d\n", distance); return 0; } /* input char[4]:CTGA input char[6]:ACGCTA 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 4 0 0 0 0 0 0 0 1 2 3 4 5 6 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 4 0 0 0 0 0 0 0 1 2 3 4 5 6 1 1 1 2 3 4 5 2 2 2 2 3 3 4 3 3 3 2 3 4 4 4 3 4 3 3 4 4 distance:4 Program ended with exit code: 0 */
the_stack_data/23575503.c
#ifdef TEST #include "unity.h" #include <string/string.h> void setUp(void) { } void tearDown(void) { } void test_string_notEmpty(void) { char* message = "This is a message"; TEST_ASSERT_EQUAL_INT(strlen(message), 17); } void test_string_empty(void) { char* message = ""; TEST_ASSERT_EQUAL_INT(strlen(message), 0); } #endif // TEST
the_stack_data/1150625.c
typedef struct a { int x; } b; typedef struct b { double x; double y; } a;
the_stack_data/460325.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* wdmatch.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vokrut <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/23 20:04:21 by vokrut #+# #+# */ /* Updated: 2019/03/24 22:24:50 by vokrut ### ########.fr */ /* */ /* ************************************************************************** */ /* Assignment name : wdmatch Expected files : wdmatch.c Allowed functions: write -------------------------------------------------------------------------------- Write a program that takes two strings and checks whether it's possible to write the first string with characters from the second string, while respecting the order in which these characters appear in the second string. If it's possible, the program displays the string, followed by a \n, otherwise it simply displays a \n. If the number of arguments is not 2, the program displays a \n. Examples: $>./wdmatch "faya" "fgvvfdxcacpolhyghbreda" | cat -e faya$ $>./wdmatch "faya" "fgvvfdxcacpolhyghbred" | cat -e $ $>./wdmatch "quarante deux" "qfqfsudf arzgsayns tsregfdgs sjytdekuoixq " | cat -e quarante deux$ $>./wdmatch "error" rrerrrfiiljdfxjyuifrrvcoojh | cat -e $ $>./wdmatch | cat -e $ */ #include <unistd.h> int main(int argc, char const **argv) { int i; int j; if (argc == 3) { i = 0; j = 0; while (argv[2][j]) if (argv[1][i] == argv[2][j++]) i++; if (!argv[1][i]) { j = 0; while (argv[1][j]) write(1, &argv[1][j++], 1); } } write(1, "\n", 1); return (0); }
the_stack_data/173577596.c
#include <stdio.h> int main() { // Read the input n, k int n, k; scanf("%d %d", &n, &k); // ans denotes number of integers n divisible by k int ans = 0; for (int i = 0; i < n; i++) { int t; scanf("%d", &t); if (t % k == 0) { ans++; } } // Print the ans. printf("%d\n", ans); return 0; }
the_stack_data/25137357.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void printArray(double ** arr, int dim) { for(int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { printf("%.2f ", arr[i][j]); } printf("\n"); } } double getDeterminant(double ** arr, int dim) { for(int i = 0; i < dim; i++) { for(int j = 0; j < dim - i - 1; j++) { double temp = arr[i + j + 1][i]; temp *= -1; for(int k = 0; k < dim; k++) { arr[i + j + 1][k] += arr[i][k] * (temp/ *&arr[i][i]); } } } printf("-----------------\n"); printArray(arr, dim); double det = 1; for(int i = 0; i < dim; i++) { det *= arr[i][i]; } return det; } int main() { srand(time(NULL)); int dim = (rand() % 6) + 2; printf("%d\n", dim); double **arr = (double **)malloc(dim * sizeof(double *)); for (int i = 0; i < dim; i++) arr[i] = (double *)malloc(dim * sizeof(double)); for (int i = 0; i < dim; i++) for (int j = 0; j < dim; j++) arr[i][j] = (rand() % 9) + 1; printArray(arr, dim); printf("Determinant of Matrix is: %f", getDeterminant(arr, dim)); for (int i = 0; i < dim; i++) free(arr[i]); free(arr); return 0; }
the_stack_data/26045.c
#include <stdio.h> void scilab_rt_champ1_d2d2i2d2i0i2s0_(int in00, int in01, double matrixin0[in00][in01], int in10, int in11, double matrixin1[in10][in11], int in20, int in21, int matrixin2[in20][in21], int in30, int in31, double matrixin3[in30][in31], int scalarin0, int in40, int in41, int matrixin4[in40][in41], char* scalarin1) { int i; int j; double val0 = 0; double val1 = 0; int val2 = 0; double val3 = 0; int val4 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%f", val0); for (i = 0; i < in10; ++i) { for (j = 0; j < in11; ++j) { val1 += matrixin1[i][j]; } } printf("%f", val1); for (i = 0; i < in20; ++i) { for (j = 0; j < in21; ++j) { val2 += matrixin2[i][j]; } } printf("%d", val2); for (i = 0; i < in30; ++i) { for (j = 0; j < in31; ++j) { val3 += matrixin3[i][j]; } } printf("%f", val3); printf("%d", scalarin0); for (i = 0; i < in40; ++i) { for (j = 0; j < in41; ++j) { val4 += matrixin4[i][j]; } } printf("%d", val4); printf("%s", scalarin1); }
the_stack_data/61074841.c
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <inttypes.h> double function(double c, int n, double array[]){ double sum=0; int index=0; double temp; while(n>=0){ temp=pow(c,n); temp=temp*(array[index]); sum+=temp; index++; n--; } return sum; } int main(int argc, char** argv){ // printf("app1 start \n"); FILE *input; input=fopen(*(argv+1),"r"); double e,a,b,c; int n; fscanf(input,"%d %lf %lf %lf",&n,&e,&a,&b); // printf("n= %d, e= %lf, A= %lf, B= %lf\n",n,e,a,b); double array[n+1]; int i=0; while(i<n+1){ fscanf(input,"%lf",&array[i]); // printf("array[%d]=%lf ",i,array[i]); i++; } //psuedocode! while(1){ c=(a+b)/2; double fOfC=function(c,n,array); if(fOfC==0) break; if(((b-a)/2)<e) break; //if sign (f(c))=sign(f(a)) then a<-c else b<- c double fOfA=function(a,n,array); if( fOfC*fOfA>0){ a=c; } else b=c; } // printf("%lf\n",c); FILE *solver=fopen("part2_solver.dat","w+"); fprintf(solver,"%lf",c); fclose(solver); return 0; }
the_stack_data/89807.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); #include <stdlib.h> #include <string.h> static void *calloc_model(size_t nmemb, size_t size) { void *ptr = malloc(nmemb * size); return memset(ptr, 0, nmemb * size); } extern int __VERIFIER_nondet_int(void); struct L4 { struct L4 *next; struct L5 *down; }; struct L3 { struct L4 *down; struct L3 *next; }; struct L2 { struct L2 *next; struct L3 *down; }; struct L1 { struct L2 *down; struct L1 *next; }; struct L0 { struct L0 *next; struct L1 *down; }; static void* zalloc_or_die(unsigned size) { void *ptr = calloc_model(1U, size); if (ptr) return ptr; abort(); } static void l4_insert(struct L4 **list) { struct L4 *item = zalloc_or_die(sizeof *item); item->down = zalloc_or_die(119U); item->next = *list; *list = item; } static void l3_insert(struct L3 **list) { struct L3 *item = zalloc_or_die(sizeof *item); int c = 0; do { c++; l4_insert(&item->down); } while (c < 1); item->next = *list; *list = item; } static void l2_insert(struct L2 **list) { struct L2 *item = zalloc_or_die(sizeof *item); int c = 0; do { c++; l3_insert(&item->down); } while (c < 2); item->next = *list; *list = item; } static void l1_insert(struct L1 **list) { struct L1 *item = zalloc_or_die(sizeof *item); int c = 0; do { c++; l2_insert(&item->down); } while (c < 1); item->next = *list; *list = item; } static void l0_insert(struct L0 **list) { struct L0 *item = zalloc_or_die(sizeof *item); int c = 0; do { c++; l1_insert(&item->down); } while (c < 2); item->next = *list; *list = item; } static void l4_destroy(struct L4 *list, int level) { do { if (5 == level) free(list->down); struct L4 *next = list->next; if (4 == level) free(list); list = next; } while (list); } static void l3_destroy(struct L3 *list, int level) { do { if (3 < level) l4_destroy(list->down, level); struct L3 *next = list->next; if (3 == level) free(list); list = next; } while (list); } static void l2_destroy(struct L2 *list, int level) { do { if (2 < level) l3_destroy(list->down, level); struct L2 *next = list->next; if (2 == level) free(list); list = next; } while (list); } static void l1_destroy(struct L1 *list, int level) { do { if (1 < level) l2_destroy(list->down, level); struct L1 *next = list->next; if (1 == level) free(list); list = next; } while (list); } static void l0_destroy(struct L0 *list, int level) { do { if (0 < level) l1_destroy(list->down, level); struct L0 *next = list->next; if (0 == level) free(list); list = next; } while (list); } int main() { static struct L0 *list; int c = 0; do { c++; l0_insert(&list); } while (c < 3 && __VERIFIER_nondet_int()); l0_destroy(list, /* level */ 4); l0_destroy(list, /* level */ 3); l0_destroy(list, /* level */ 2); l0_destroy(list, /* level */ 1); l0_destroy(list, /* level */ 0); return !!list; }
the_stack_data/1197425.c
#include <ncurses.h> #define CENTER 1 #define LCOUNT 8 int main(void) { char labels[LCOUNT][19] = { "Help!", "File", "Print", "Text", "Edit", "Quick", "Config", "System" }; int x; slk_init(0); initscr(); for(x=0;x<LCOUNT;x++) slk_set(x+1,labels[x],CENTER); slk_attron(A_BOLD); slk_refresh(); getch(); endwin(); return 0; }
the_stack_data/86811.c
/* * Copyright 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * Hello world with floating point in the mix. */ #include <stdio.h> int main(int argc, char* argv[]) { /* The constant 2.0 causes the compiler to generate floating point * instructions. Compiler flags are used to control what kind of * instructions (x87, SSE etc.) are generated. */ if (argc < 2.0) printf("Hello, World!\n"); return 0; }
the_stack_data/29053.c
#include <stdio.h> #include <stdlib.h> #include <malloc.h> //----------|Status|----------- typedef int Status; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 //----------------------------- //---------|Typedef|----------- #define MAXSIZE 100 typedef int ElemType; struct component{ ElemType data; int cur; }; typedef struct component SLinkList[MAXSIZE]; //----------------------------- //---------|FuncList|---------- int Malloc_SL(SLinkList space) { //若备用空间链表非空,则返回分配的节点下标,否则返回0 int i; i = space[0].cur; if(space[0].cur) space[0].cur = space[i].cur; return i; }//Malloc_SL int Free_SL(SLinkList space, int k) { //将下标为k的空闲节点回收到备用链表 space[k].cur = space[0].cur; space[0].cur = k; }//Free_SL Status InitList_SL(SLinkList space) { //构造一个空的静态链表 //将一维数组space中各分量链成一个备用链表,space[0].cur为头指针 //"0"表示空指针 int i; for(i = 0; i < MAXSIZE - 1; i++) space[i].cur = i + 1; space[MAXSIZE - 1].cur = 0; return OK; } int CreateList(SLinkList space, int n) { //创建一个含有n个结点的静态链表,返回表头在存储数组的位置 int head, k, s, i; k = Malloc_SL(space); //从空闲链表中取得一个空结点 head = k; for(i = 0; i < n; i++) { s = Malloc_SL(space); space[s].data = 5 * i; //scanf("%d", &space[s].data); space[k].cur = s; k = s; } space[k].cur = 0; return head; } // Status ClearList_SL(SLinkList space) // //重置为空表 // Status ListEmpty_SL(SLinkList space, int head) // //静态链表判空 // int ListLength_SL(SLinkList space, int head) // //求静态链表长度 // Status Locatepos_SL(SLinkList space, int head, int i, ElemType *e) // //用e返回链表第i个节点的元素值,其中head为表头指针 // int Prior_SL(SLinkList space, int head, int i) // //改变当前指针指向其前驱,错误则返回0 // int Next_SL(SLinkList space, int head, int i) // //改变当前指针指向其后继,错误则返回0 // Status ListTraverse_SL(SLinkList space, int head, Status (*visit)(ElemType*)) // //对每个元素调用函数visit,一旦visit()失败,则操作失败 // Status LocateElem_SL(SLinkList *space, ElemType e, int(*compare)(ElemType, ElemType)) // //若存在与e满足函数compare()判定关系的元素,则移动当前指针指向第一个满足条件的元素,并返回OK,否则返回ERROR // ElemType GetCurElem_SL(SLinkList space, int i) // //返回当前指针所指数据元素 // Status SetCurElem_SL(SLinkList space, int i, ElemType e) // //更新当前指针所指数据元素 // Status Append_SL(SLinkList space, int head, SLinkList s) // //s指向的一串节点连接在最后一个节点之后 // Status InsAfter_SL(SLinkList space, int i) // //将元素e插入在当前指针之后 // Status DelAfter_SL(SLinkList space, int i) // //删除当前指针之后的节点 // void MergeList_SL(SLinkList spacea, SLinkList spaceb, SLinkList spacec, int (*compare)(ElemType, ElemType)) // //在La和Lb有序的前提下,合并出Lc // void Difference_SL(SLinkList space, int s) // //见教材算法2.16 // int compare(ElemType a, ElemType b) // //元素比较函数, 返回a-b void PrintList_SL(SLinkList space, int head) { //从头结点开始,依次输出以后所有结点值 int pos; #include <stdio.h> #include <stdlib.h> #include <malloc.h> //----------|Status|----------- typedef int Status; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 //----------------------------- //---------|Typedef|----------- #define MAXSIZE 100 typedef int ElemType; struct component{ ElemType data; int cur; }; typedef struct component SLinkList[MAXSIZE]; //----------------------------- //---------|FuncList|---------- int Malloc_SL(SLinkList space) { //若备用空间链表非空,则返回分配的节点下标,否则返回0 int i; i = space[0].cur; if(space[0].cur) space[0].cur = space[i].cur; return i; }//Malloc_SL int Free_SL(SLinkList space, int k) { //将下标为k的空闲节点回收到备用链表 space[k].cur = space[0].cur; space[0].cur = k; }//Free_SL Status InitList_SL(SLinkList space) { //构造一个空的静态链表 //将一维数组space中各分量链成一个备用链表,space[0].cur为头指针 //"0"表示空指针 int i; for(i = 0; i < MAXSIZE - 1; i++) space[i].cur = i + 1; space[MAXSIZE - 1].cur = 0; return OK; } int CreateList(SLinkList space, int n) { //创建一个含有n个结点的静态链表,返回表头在存储数组的位置 int head, k, s, i; k = Malloc_SL(space); //从空闲链表中取得一个空结点 head = k; for(i = 0; i < n; i++) { s = Malloc_SL(space); space[s].data = 5 * i; //scanf("%d", &space[s].data); space[k].cur = s; k = s; } space[k].cur = 0; return head; } // Status ClearList_SL(SLinkList space) // //重置为空表 // Status ListEmpty_SL(SLinkList space, int head) // //静态链表判空 // int ListLength_SL(SLinkList space, int head) // //求静态链表长度 // Status Locatepos_SL(SLinkList space, int head, int i, ElemType *e) // //用e返回链表第i个节点的元素值,其中head为表头指针 // int Prior_SL(SLinkList space, int head, int i) // //改变当前指针指向其前驱,错误则返回0 // int Next_SL(SLinkList space, int head, int i) // //改变当前指针指向其后继,错误则返回0 // Status ListTraverse_SL(SLinkList space, int head, Status (*visit)(ElemType*)) // //对每个元素调用函数visit,一旦visit()失败,则操作失败 // Status LocateElem_SL(SLinkList *space, ElemType e, int(*compare)(ElemType, ElemType)) // //若存在与e满足函数compare()判定关系的元素,则移动当前指针指向第一个满足条件的元素,并返回OK,否则返回ERROR // ElemType GetCurElem_SL(SLinkList space, int i) // //返回当前指针所指数据元素 // Status SetCurElem_SL(SLinkList space, int i, ElemType e) // //更新当前指针所指数据元素 // Status Append_SL(SLinkList space, int head, SLinkList s) // //s指向的一串节点连接在最后一个节点之后 // Status InsAfter_SL(SLinkList space, int i) // //将元素e插入在当前指针之后 // Status DelAfter_SL(SLinkList space, int i) // //删除当前指针之后的节点 // void MergeList_SL(SLinkList spacea, SLinkList spaceb, SLinkList spacec, int (*compare)(ElemType, ElemType)) // //在La和Lb有序的前提下,合并出Lc // void Difference_SL(SLinkList space, int s) // //见教材算法2.16 // int compare(ElemType a, ElemType b) // //元素比较函数, 返回a-b void PrintList_SL(SLinkList space, int head) { //从头结点开始,依次输出以后所有结点值 int pos; pos = space[head].cur; while(pos) { printf("%d\t", space[pos].data); pos = space[pos].cur; } printf("\n"); } //----------------------------- int main() { int head; SLinkList test; InitList_SL(test); head = CreateList(test, 10); PrintList_SL(test, head); return 0; } //----------------------------------------- Status ClearList_SL(SLinkList space) { //重置为空表 if(!space[0].cur) return ERROR;//已是空表 return initList_SL(space); }//ClearList_SL Status ListEmpty_SL(SLinkList space, int head) { //静态链表判空 if(!space[0].cur) return TRUE; else return FALSE; }//ListEmpty_SL int ListLength_SL(SLinkList space, int head) { //求静态链表长度 int i = 0; int k = space[head].cur; while(!space[k].cur) { k = space[k].cur; i++; } return i; }//ListLength_SL Status Locatepos_SL(SLinkList space, int head, int i, ElemType *e) { //用e返回链表第i个节点的元素值,其中head为表头指针 //i的合法值为1<=i<=SLinkLength_Sq(SLinkList space) int j; int k = head; if((i < 1) || (i > SLinkLength_Sq(space))) return ERROR; //i值不合法 for(j = 1; j <= i; k++) { k = space[k].cur; } e = space[k].data; return OK; }//Locatepos_SL int Prior_SL(SLinkList space, int head, int i){ //改变当前指针指向其前驱,错误则返回0 if(i < 0 || i > MAXSIZE - 1) return 0; //i不合法 int pr; int k = head; for(pr = 0; space[k].cur != i; ) { pr = k; k = space[k].cur; } return k; }//Prior_SL int Next_SL(SLinkList space, int head, int i) { //改变当前指针指向其后继,错误则返回0 if(i < 0 || i > MAXSIZE - 1) return 0; //i不合法 return space[i].cur; }//Next_SL Status ListTraverse_SL(SLinkList space, int head, Status (*visit)(ElemType*)) { //对每个元素调用函数visit,一旦visit()失败,则操作失败 int i,k = space[head].cur; for(i = 0; i < ListLength_SL(space,head) && visit(space[k].data); i++, k = space[k].cur) ; if(i < ListLength_SL(space,head)) return ERROR; else return OK; }//ListTraverse_SL Status LocateElem_SL(SLinkList* space, ElemType e, int(*compare)(ElemType, ElemType)) { //若存在与e满足函数compare()判定关系的元素,则移动当前指针指向第一个满足条件的元素,并返回OK,否则返回ERROR int i,k; for(i = 0,k = space[0]->cur; !compare(e,space[k]->data); i++,k = space[k]->cur) ; if(i < ListLength_SL(space,0)) { space = space[k]; return OK; } else return ERROR; }//LocateElem_SL ElemType GetCurElem_SL(SLinkList space, int i) { //返回当前指针所指数据元素 if(i < 0 || i > MAXSIZE - 1) return ERROR; //i不合法 return space[i].data; }//GetCurElem_SL Status SetCurElem_SL(SLinkList space, int i, ElemType e) { //更新当前指针所指数据元素 if(i < 0 || i > MAXSIZE - 1) return ERROR; //i不合法 space[i].data = e; return OK; }//SetCurElem_SL pos = space[head].cur; while(pos) { printf("%d\t", space[pos].data); pos = space[pos].cur; } printf("\n"); } //----------------------------- int main() { int head; SLinkList test; InitList_SL(test); head = CreateList(test, 10); PrintList_SL(test, head); return 0; }
the_stack_data/40999.c
/* +++Date last modified: 05-Jul-1997 */ /* ** A Pratt-Boyer-Moore string search, written by Jerry Coffin ** sometime or other in 1991. Removed from original program, and ** (incorrectly) rewritten for separate, generic use in early 1992. ** Corrected with help from Thad Smith, late March and early ** April 1992...hopefully it's correct this time. Revised by Bob Stout. ** ** This is hereby placed in the Public Domain by its author. ** ** 10/21/93 rdg Fixed bug found by Jeff Dunlop */ #include <stddef.h> #include <string.h> #include <limits.h> static size_t table[UCHAR_MAX + 1]; static size_t len; static char *findme; /* ** Call this with the string to locate to initialize the table */ void init_search(const char *string) { size_t i; len = strlen(string); for (i = 0; i <= UCHAR_MAX; i++) /* rdg 10/93 */ table[i] = len; for (i = 0; i < len; i++) table[(unsigned char)string[i]] = len - i - 1; findme = (char *)string; } /* ** Call this with a buffer to search */ char *strsearch(const char *string) { register size_t shift; register size_t pos = len - 1; char *here; size_t limit=strlen(string); while (pos < limit) { while( pos < limit && (shift = table[(unsigned char)string[pos]]) > 0) { pos += shift; } if (0 == shift) { if (0 == strncmp(findme, here = (char *)&string[pos-len+1], len)) { return(here); } else pos++; } } return NULL; } #include <stdio.h> startup() { char *here; char *find_strings[] = { "Kur", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", "gent", "lass", "suns", "for", "xxx", "long", "have", "where", "xxxxxx", "xxxxxx", "pense", "pow", "xxxxx", "Yo", "and", "faded", "20", "you", "bac", "an", "way", "possibili", "an", "fat", "imag", "th", "wor", "xxx", "xxx", "yo", "bxx", "wo", "kind", "4", "idle", "Do", "scare", "people", "wit", "xxx", "xxx", "Th", "xxx", "yourself", "Forget", "succeed", "Kee", "lov", "yo", "Stretc", "what", "life", "kno", "wha", "xxx", "xxx", "40", "Get", "xxx", "them", "Maybe", "may", "you", "the", "your", "congratulate", "much", "either", "are", "Enjoy", "it", "be", "other", "it", "xxx", "greatest", "own", "nowhere", "room", "you", "beauty", "feel", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "it", "Northern", "before", "Accept", "Politicians", "get", "size", "reasonable", "their", "Dont", "support", "trust", "spouse", "one", "too", "time", "careful", "with", "Dispensing", "past", "the", "parts", "more", "me", NULL}; char *search_strings[] = { "Kurt Vonneguts Commencement Address at", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen", "MIT Ladies and gentlemen of", "the class of 97 Wear", "sunscreen If I could offer", "you only one tip for", "the future sunscreen would be", "it The longterm benefits of", "sunscreen have been proved by", "scientists whereas the rest of", "my advice has no basis", "more reliable than my own meandering experience", "I will dispense this advice", "now Enjoy the power and beauty", "of your youth Oh never mind", "You will not understand the power", "and beauty of your youth until theyve", "faded But trust me in", "20 years", "youll look", "back at photos of yourself", "and recall in a", "way you cant grasp now how much", "possibility lay before you", "and how fabulous you really looked You", "are not as fat", "as you imagine Dont worry about", "the future Or", "worry but know that worrying is as effective", "as trying to solve an algebra equation", "by chewing bubble gum The real troubles in", "your life are apt to", "be things that never crossed your", "worried mind the", "kind that blindside you at", "4 pm on some", "idle Tuesday", "Do one thing every day that", "scares you Sing Dont be reckless with other", "peoples hearts Dont put up", "with people who are reckless", "with yours Floss Dont waste your time", "on jealousy Sometimes youre ahead sometimes youre behind", "The race is long and in", "the end its only with", "yourself Remember compliments you receive", "Forget the insults If you", "succeed in doing this tell me how", "Keep your old", "love letters Throw away", "your old bank statements", "Stretch Dont feel guilty if you dont know", "what you want to do with your", "life The most interesting people I", "know didnt know at 22", "what they wanted", "to do with their lives Some of", "the most interesting", "40yearolds I know still dont", "Get plenty of calcium", "Be kind to your knees Youll miss", "them when theyre gone", "Maybe youll marry", "maybe you wont Maybe youll have children maybe", "you wont Maybe youll divorce at 40 maybe youll dance", "the funky chicken on", "your 75th wedding anniversary Whatever", "you do dont congratulate yourself too", "much or berate yourself", "either Your choices are half chance So", "are everybody elses", "Enjoy your body Use", "it every way you can Dont", "be afraid of it or of what", "other people think of", "it Its", "the", "greatest instrument youll ever", "own Dance even if you have", "nowhere to do it but your living", "room Read the directions even if", "you dont follow them Do not read", "beauty magazines They will only make you", "feel ugly Get to know your parents You never", "know when theyll be gone for good Be", "nice to your siblings Theyre your", "best link to your", "past and the people most likely", "to stick with you", "in the future Understand that", "friends come and go but", "with a precious few you should hold", "on Work hard to bridge", "the gaps in geography and lifestyle", "because the older", "you get the more you need the", "people who knew you when you", "were young Live", "in New York City once but leave before", "it makes you hard Live in", "Northern California once but leave", "before it makes you soft Travel", "Accept certain inalienable truths Prices will rise", "Politicians will philander You too will", "get old And when you do youll", "fantasize that when you were young prices were", "reasonable politicians were noble and children respected", "their elders Respect your elders", "Dont expect anyone else to", "support you Maybe you have a", "trust fund Maybe youll have a wealthy", "spouse But you never know when either", "one might run out Dont mess", "too much with your hair or by the", "time youre 40 it will look 85 Be", "careful whose advice you buy but be patient", "with those who supply it Advice is a", "form of nostalgia Dispensing it is", "a way of fishing the past from", "the disposal wiping it off painting", "over the ugly parts", "and recycling it for more than its", "worth But trust me on the sunscreen" }; int i; for (i = 0; find_strings[i]; i++) { init_search(find_strings[i]); here = strsearch(search_strings[i]); printf("\"%s\" is%s in \"%s\"", find_strings[i], here ? "" : " not", search_strings[i]); if (here) printf(" [\"%s\"]", here); putchar('\n'); } return 0; }