file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/148577927.c
#include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> ssize_t s_send(int fd, char* buffer, size_t len){ size_t sent = 0; while (sent < len) { ssize_t current = send(fd,buffer+sent,len-sent,MSG_NOSIGNAL); if (current == -1){ return -1; }else if(current == 0 ){ break; } sent+=current; } return sent; } int main(int argc, char* argv[]) { char* port = argv[1]; struct addrinfo hints; struct addrinfo *result, *rp; int s_fd, peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if (getaddrinfo(NULL, port, &hints, &result) == 0) { fprintf(stderr,"Problemas con la conexión\n"); return -1; } for(rp=result; rp != NULL; rp = rp->ai_next) { s_fd = socket(rp->ai_family,rp->ai_socktype, rp->ai_protocol); if(s_fd == -1) { continue; } if(connect(s_fd,rp->ai_addr,rp->ai_addrlen)) { break; } } freeaddrinfo(result); if (rp == NULL) { fprintf(perror,"Couldnt bind"); return -1; } listen(s_fd, 20); // Cantidad que quiero escuchar. while (1) { peer = accept(s_fd, NULL, NULL); if (peer == -1) { break; } char mensaje[50]; strcpy(mensaje, "Conexion rechazada"); s_send(peer,mensaje,strlen(mensaje)+1); shutdown(peer,SHUT_RDWR); close(peer); } shutdown(s_fd,SHUT_RDWR); close(s_fd); }
the_stack_data/428625.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lgavalda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/19 14:43:03 by lgavalda #+# #+# */ /* Updated: 2019/07/23 00:42:55 by lgavalda ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int ft_strlen(char *str) { char *str_save; str_save = str; while (*str) str++; return (str - str_save); } int error_(int value, char *str) { while (*str) write(2, str++, 1); return (value); } int main(int ac, char **av) { int fd; int r; char c; if (ac <= 1) { return (error_(-1, "File name missing.\n")); } if (ac > 2) { return (error_(-1, "Too many arguments.\n")); } fd = open(av[1], O_RDONLY); if (fd == -1) { return (error_(-1, "Cannot read file.\n")); } while ((r = read(fd, &c, 1))) { write(1, &c, 1); } close(fd); return (0); }
the_stack_data/206392081.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strncat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmasstou <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/05 18:51:58 by mmasstou #+# #+# */ /* Updated: 2021/07/05 19:23:33 by mmasstou ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strncat(char *dest, char *src, unsigned int nb) { unsigned int dsize; unsigned int index ; dsize = 0; while(dest[dsize] != '\0') dsize++; index = -1; while(src[++index] != '\0' && index < nb) dest[dsize++ ] = src[index]; while (index <= nb) { dest[dsize] = '\0'; index++; } return (dest); }
the_stack_data/176706731.c
int main() { struct { int val0; union { int val1; int val2; }; int val3; } x; x.val2 = 1024; x.val0 = 10; x.val3 = 20; print(x.val0); print(x.val1); print(x.val2); print(x.val3); return 0; }
the_stack_data/28263979.c
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> const char *arr[]={ "-", "\\", "|", "/", 0 }; void sigint(int signo) { //_exit(0); - _exit does not call atexit handlers - and apparently it does not call destructors. exit(0); // this one works! } main() { // turns out the destructor of the shared library is only called when exit is called. // so signal handler that does not do exit - no destructor. // in older systems this was different (maybe this is Redhat feature?) signal( SIGINT, sigint); //signal( SIGINT, SIG_DFL ); int i = 0; while(1) { fprintf(stderr,"%s\r", arr[ i++ ] ); if (arr[i]==0) { i = 0; } sleep(1); } return 0; }
the_stack_data/215767630.c
//=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== // DEFINE / INCLUDE //=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== #define fp float #define EQUATIONS 91 #define PARAMETERS 16
the_stack_data/100139576.c
// Implement strStr() #include <stdio.h> #include <string.h> int strStr(char *haystack, char *needle) { if (strlen(needle) == 0) return 0; for (int i = 0; haystack[i + strlen(needle) - 1] != '\0'; ++i) { int j; for (j = 0; needle[j] != '\0'; ++j) { if (haystack[i + j] != needle[j]) break; } if (j == strlen(needle)) return i; } return -1; } int main() { char haystack[] = "ababc"; char needle[] = "ab3"; printf("%d\n", strStr(haystack, needle)); return 0; }
the_stack_data/110872.c
#include <X11/Xlib.h> #define M typedef #define N( a)=r=(a)+j #define S f(; G; )D[B[R=i[--G]]=F+=F<p]++ #define f for #define g [H] M short a; M int b; M unsigned c ; M unsigned char*d; M XPoint *e; M void _; b*h,*i,j,k,l,m,n,o,p ; b O; d A ,B,C; _*q,*r,*calloc(); e s ,t; Window u,v; GC x[256]; b D[256]; b w,y, z;_ Q(b E) { XMapWindow(q,v=XCreateSimpleWindow(q, XRootWindow (q,z=XDefaultScreen(q)),!v*n,0,n,n,0,0,0)); XSelectInput ( q,v,E); } _ P(){ C N(h N(i N(s N(t N(A N(B=calloc(C-B+256,1) ) )) ))); } _ J(){ b F,G,H; c R =w %4; F=G=m; f(H=0; H<j ; H++){ h g =l+(R-2?R?R-1?(G-F*F/n)+F*n:(G*G-F*F) /m*n+2*F*G/ m: 2*(F*F- G*G)/m+4*F*G/m*n:G+ F*n);( s g. x= m-F--,s +H) ->y=m-G;F= F+m?F:(G--, m);}} _ K(){ b H,R; f(H=0;H<j;H ++)D[ B g=(c)(R =h g+k)< j? (A[ R]<p)+A [R ]: 1] ++ ; } _ I ( d F) { F?(_)0:(_ ) (F=B, gets( B)) ; y=atoi(F);} _ Y(){ b F, G; c R ; F = G = 0; K( ); f( R = k + l ; R < j && ( F = B[ R ] ) < p; R = h [R ] + k) { D [ F ] -- ; B [ i [ G ++ ] =R ] =p; } if ( R >= j) F = 1; S; } _ L() { b H, F,G; c R ; f( H =0; H < j; H ++) B g =0; O =-1; f( G = R = 0; R < j; R++ ){ f(; R < j && !( F = B[ R ]); R = h[ R ] + k) B [i[ G ++] = R ] = p; S; } } _ U() { e X [ 256 ] ,W; b H; W = t; f ( H = 0; H < o; H ++ ) { X g = W; W +=D g ;} f( H =0; H < j; H ++) if( A g - B g) * X[ B g ] ++ = s g; { XMotionEvent * V = r = t ; W = t; f ( H = 0; H < o ; H ++ ) { XDrawPoints (q , v ,x g, W,X g -W, CoordModeOrigin ) ; W += D g ; D g = 0 ; } f(; XPending(q)+! ++O; V->type- ButtonPress?( k =V ->x+ V -> y * n - l) : ( O = - 42 ) ) XNextEvent ( q , r = V ) ; } } _ main ( b X , d * W ) { b H, F ,G; c R; if ( X < 3 ) { puts( "tvr: mode size < cmap" ); exit(0);} P(); I(*++ W); w = y %12; I(*++ W); n = y *2; j = n * n ; P ( ) ; m = y ; l = j / 2 + m ; q=XOpenDisplay ( 0 ) ; Q ( 0 ) ; u = v ; Q ( PointerMotionMask |ButtonPressMask ) ; I ( 0 ) ; o =y ; p = o -1 ; { XColor F ; Colormap G; f ( H = 0 ; H < o ; H++){ I(0); XParseColor(q,G =XDefaultColormap ( q , z ) , r = B , & F ) ; XAllocColor (q , G , & F ) ; XSetForeground (q,x g = XCreateGC ( q, u ,0 , 0 ) , F .pixel ) ; } } P ( ); J (); f ( F =R = G =H = 0; H < j; ) if(++F >= p || ( R = h [ R ] +G)>=j ) { D [ B g = F ] ++; R = l + k; G= ++H -R; F =0; } H=j; U(); v= u; f(F=w/4; ; A+=H-=H+H,B-=H )(O<0?L:*("[email protected]." +7*F)?F^1?Y:K:L)() ,(U)(); }
the_stack_data/71409.c
/* ========================================================================== */ /* === ccolamd_global.c ===================================================== */ /* ========================================================================== */ /* ---------------------------------------------------------------------------- * CCOLAMD Copyright (C), Univ. of Florida. Authors: Timothy A. Davis, * Sivasankaran Rajamanickam, and Stefan Larimore * See License.txt for the Version 2.1 of the GNU Lesser General Public License * http://www.cise.ufl.edu/research/sparse * -------------------------------------------------------------------------- */ /* Global variables for CCOLAMD */ #ifndef NPRINT #ifdef MATLAB_MEX_FILE #include "mex.h" int (*ccolamd_printf) (const char *, ...) = mexPrintf ; #else #include <stdio.h> int (*ccolamd_printf) (const char *, ...) = printf ; #endif #else int (*ccolamd_printf) (const char *, ...) = ((void *) 0) ; #endif
the_stack_data/103264816.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, Z. Vasicek and R. Hrbacek, "Role of circuit representation in evolutionary design of energy-efficient approximate circuits" in IET Computers & Digital Techniques, vol. 12, no. 4, pp. 139-149, 7 2018. doi: 10.1049/iet-cdt.2017.0188 * This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and mse parameters ***/ // MAE% = 6.25 % // MAE = 512 // WCE% = 12.50 % // WCE = 1024 // WCRE% = 100.00 % // EP% = 100.00 % // MRE% = 16.24 % // MSE = 325756 // PDK45_PWR = 0.0032 mW // PDK45_AREA = 8.9 um2 // PDK45_DELAY = 0.12 ns #include <stdint.h> #include <stdlib.h> uint64_t add12u_1KC(uint64_t a, uint64_t b) { uint64_t o = 0; int n_415=0, n_414=0, n_36=0, n_42=0, n_37=0, n_23=0, n_22=0, n_21=0, n_20=0, n_27=0; int n_26=0, n_25=0, n_24=0, n_29=0, n_28=0, n_39=0, n_38=0, n_8=0, n_9=0, n_4=0; int n_5=0, n_6=0, n_7=0, n_0=0, n_1=0, n_2=0, n_3=0, n_30=0, n_31=0, n_32=0; int n_33=0, n_34=0, n_35=0, n_18=0, n_19=0, n_16=0, n_17=0, n_14=0, n_15=0, n_12=0; int n_13=0, n_10=0, n_11=0, n_45=0, n_44=0, n_43=0, n_47=0, n_46=0, n_41=0, n_40=0; n_0 = (a >> 0) & 0x1; n_1 = (a >> 0) & 0x1; n_2 = (a >> 1) & 0x1; n_3 = (a >> 1) & 0x1; n_4 = (a >> 2) & 0x1; n_5 = (a >> 2) & 0x1; n_6 = (a >> 3) & 0x1; n_7 = (a >> 3) & 0x1; n_8 = (a >> 4) & 0x1; n_9 = (a >> 4) & 0x1; n_10 = (a >> 5) & 0x1; n_11 = (a >> 5) & 0x1; n_12 = (a >> 6) & 0x1; n_13 = (a >> 6) & 0x1; n_14 = (a >> 7) & 0x1; n_15 = (a >> 7) & 0x1; n_16 = (a >> 8) & 0x1; n_17 = (a >> 8) & 0x1; n_18 = (a >> 9) & 0x1; n_19 = (a >> 9) & 0x1; n_20 = (a >> 10) & 0x1; n_21 = (a >> 10) & 0x1; n_22 = (a >> 11) & 0x1; n_23 = (a >> 11) & 0x1; n_24 = (b >> 0) & 0x1; n_25 = (b >> 0) & 0x1; n_26 = (b >> 1) & 0x1; n_27 = (b >> 1) & 0x1; n_28 = (b >> 2) & 0x1; n_29 = (b >> 2) & 0x1; n_30 = (b >> 3) & 0x1; n_31 = (b >> 3) & 0x1; n_32 = (b >> 4) & 0x1; n_33 = (b >> 4) & 0x1; n_34 = (b >> 5) & 0x1; n_35 = (b >> 5) & 0x1; n_36 = (b >> 6) & 0x1; n_37 = (b >> 6) & 0x1; n_38 = (b >> 7) & 0x1; n_39 = (b >> 7) & 0x1; n_40 = (b >> 8) & 0x1; n_41 = (b >> 8) & 0x1; n_42 = (b >> 9) & 0x1; n_43 = (b >> 9) & 0x1; n_44 = (b >> 10) & 0x1; n_45 = (b >> 10) & 0x1; n_46 = (b >> 11) & 0x1; n_47 = (b >> 11) & 0x1; n_414 = n_22 ^ n_46 ^n_44; n_415 = (n_22 & n_46) | (n_46 & n_44) | (n_22 & n_44); o |= (n_30 & 0x01) << 0; o |= (n_18 & 0x01) << 1; o |= (n_36 & 0x01) << 2; o |= (n_8 & 0x01) << 3; o |= (n_10 & 0x01) << 4; o |= (n_12 & 0x01) << 5; o |= (n_18 & 0x01) << 6; o |= (n_16 & 0x01) << 7; o |= (n_40 & 0x01) << 8; o |= (n_42 & 0x01) << 9; o |= (n_20 & 0x01) << 10; o |= (n_414 & 0x01) << 11; o |= (n_415 & 0x01) << 12; return o; }
the_stack_data/18888788.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; } int __global_lock; void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; } void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; } #include <assert.h> #include <pthread.h> #ifndef TRUE #define TRUE (_Bool)1 #endif #ifndef FALSE #define FALSE (_Bool)0 #endif #ifndef NULL #define NULL ((void*)0) #endif #ifndef FENCE #define FENCE(x) ((void)0) #endif #ifndef IEEE_FLOAT_EQUAL #define IEEE_FLOAT_EQUAL(x,y) (x==y) #endif #ifndef IEEE_FLOAT_NOTEQUAL #define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y) #endif void * P0(void *arg); void * P1(void *arg); void * P2(void *arg); void fence(); void isync(); void lwfence(); int __unbuffered_cnt; int __unbuffered_cnt = 0; int __unbuffered_p2_EAX; int __unbuffered_p2_EAX = 0; _Bool main$tmp_guard0; _Bool main$tmp_guard1; int x; int x = 0; int y; int y = 0; void * P0(void *arg) { __VERIFIER_atomic_begin(); y = 2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P1(void *arg) { __VERIFIER_atomic_begin(); x = 2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P2(void *arg) { __VERIFIER_atomic_begin(); __unbuffered_p2_EAX = x; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void fence() { } void isync() { } void lwfence() { } int main() { pthread_create(NULL, NULL, P0, NULL); pthread_create(NULL, NULL, P1, NULL); pthread_create(NULL, NULL, P2, NULL); __VERIFIER_atomic_begin(); main$tmp_guard0 = __unbuffered_cnt == 3; __VERIFIER_atomic_end(); __VERIFIER_assume(main$tmp_guard0); __VERIFIER_atomic_begin(); __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ main$tmp_guard1 = !(x == 2 && y == 2 && __unbuffered_p2_EAX == 2); __VERIFIER_atomic_end(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ __VERIFIER_assert(main$tmp_guard1); return 0; }
the_stack_data/570990.c
/* v3_pcia.c -*- mode:C; c-file-style: "eay" -*- */ /* * Contributed to the OpenSSL Project 2004 by Richard Levitte * ([email protected]) */ /* Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> ASN1_SEQUENCE(PROXY_POLICY) = { ASN1_SIMPLE(PROXY_POLICY,policyLanguage,ASN1_OBJECT), ASN1_OPT(PROXY_POLICY,policy,ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(PROXY_POLICY) IMPLEMENT_ASN1_FUNCTIONS(PROXY_POLICY) ASN1_SEQUENCE(PROXY_CERT_INFO_EXTENSION) = { ASN1_OPT(PROXY_CERT_INFO_EXTENSION,pcPathLengthConstraint,ASN1_INTEGER), ASN1_SIMPLE(PROXY_CERT_INFO_EXTENSION,proxyPolicy,PROXY_POLICY) } ASN1_SEQUENCE_END(PROXY_CERT_INFO_EXTENSION) IMPLEMENT_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION)
the_stack_data/206393309.c
#include <stdio.h> int remove12(int x) { int digit = 0; int res = 0; int factor = 1; while (x != 0){ digit = x % 10; if (digit != 1 && digit != 2){ res += digit*factor; factor *= 10; } x = x / 10; } return res; } int main() { int x; int res; printf("Enter number: "); scanf("%d", &x); res = remove12(x); if (res != 0){ printf("Number with no 1's and 2's: %d\n", res); } else printf("Number consists only of the 1's and 2's\n"); return 0; }
the_stack_data/70781.c
#define _XOPEN_SOURCE 500 #include <sys/resource.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> static struct { const char *argv0; int nice; } opt; static int parse_nice(const char *str) { long val; char *ptr; val = strtol(str, &ptr, 10); if (!*str || *ptr || errno) { fprintf(stderr, "%s: invalid niceness value: %s\n", opt.argv0, str); return -1; } opt.nice = val; return 0; } /* Usage: nice [-n ADJUSTMENT] [COMMAND [ARG]...] */ int main(int argc, char *argv[]) { int ch; opt.argv0 = argv[0]; opt.nice = 10; while ((ch = getopt(argc, argv, "n:")) != -1) { switch (ch) { case 'n': if (parse_nice(optarg)) return 1; break; case '?': return 1; default: abort(); } } if (argc < 2) { /* No arguments, get current niceness */ printf("%d\n", getpriority(PRIO_PROCESS, 0)); return 0; } /* Nice self, and exec to new process */ errno = 0; nice(opt.nice); if (errno) { fprintf(stderr, "%s: unable to increase niceness: %s\n", argv[0], strerror(errno)); return 1; } execvp(argv[optind], &argv[optind]); fprintf(stderr, "%s: %s: unable to exec: %s\n", argv[0], argv[optind], strerror(errno)); return 1; }
the_stack_data/397820.c
#include <stdio.h> struct Employee { long id; short hours; float rate; }; typedef struct Employee Emp; void EmployeeInit(Emp* emp, short h, float r) { static long count = 0; emp->id = 101 + count++; emp->hours = h; emp->rate = r; } double GetNetIncome(const Emp* emp) { double income = emp->hours * emp->rate; int ot = emp->hours - 180; if(ot > 0) income += 50 * ot; return income; } int main(void) { Emp jack; Emp jill; EmployeeInit(&jack, 180, 100); EmployeeInit(&jill, 190, 100); printf("Jack's id = %ld and income = %.2lf\n", jack.id, GetNetIncome(&jack)); printf("Jill's id = %ld and income = %.2lf\n", jill.id, GetNetIncome(&jill)); }
the_stack_data/103266545.c
/* * @f ccnl-ext-localrpc.c * @b CCN-lite - local RPC processing logic * * Copyright (C) 2014-2018, Christian Tschudin, University of Basel * * 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. * * File history: * 2014-06-18 created */ #ifdef USE_SUITE_LOCALRPC #include "ccnl-localrpc.h" #include <string.h> #include <stdio.h> #include <time.h> #include "ccnl-os-time.h" #include "ccnl-fwd.h" #include "ccnl-malloc.h" #include "ccnl-pkt-localrpc.h" #include "ccnl-pkt-ccnb.h" #include "ccnl-pkt-ccntlv.h" #include "ccnl-pkt-ndntlv.h" #include "ccnl-pkt-switch.h" #include "ccnl-logging.h" #ifdef CCNL_ARDUINO static const char compile_string[] PROGMEM = "" #else static const char *compile_string = "" #endif #ifdef USE_CCNxDIGEST "CCNxDIGEST, " #endif #ifdef USE_DEBUG "DEBUG, " #endif #ifdef USE_DEBUG_MALLOC "DEBUG_MALLOC, " #endif #ifdef USE_ECHO "ECHO, " #endif #ifdef USE_LINKLAYER "ETHERNET, " #endif #ifdef USE_WPAN "WPAN, " #endif #ifdef USE_FRAG "FRAG, " #endif #ifdef USE_HMAC256 "HMAC256, " #endif #ifdef USE_HTTP_STATUS "HTTP_STATUS, " #endif #ifdef USE_KITE "KITE, " #endif #ifdef USE_LOGGING "LOGGING, " #endif #ifdef USE_MGMT "MGMT, " #endif #ifdef USE_SCHEDULER "SCHEDULER, " #endif #ifdef USE_SIGNATURES "SIGNATURES, " #endif #ifdef USE_SUITE_CCNB "SUITE_CCNB, " #endif #ifdef USE_SUITE_CCNTLV "SUITE_CCNTLV, " #endif #ifdef USE_SUITE_LOCALRPC "SUITE_LOCALRPC, " #endif #ifdef USE_SUITE_NDNTLV "SUITE_NDNTLV, " #endif #ifdef USE_UNIXSOCKET "UNIXSOCKET, " #endif ; int ccnl_rdr_dump(int lev, struct rdr_ds_s *x) { int i, t; char *n; //, tmp[20]; t = ccnl_rdr_getType(x); if (t < LRPC_NOT_SERIALIZED) return t; /* if (t < LRPC_APPLICATION) { sprintf(tmp, "v%02x", t); n = tmp; } else */ switch (t) { case LRPC_PT_REQUEST: n = "REQ"; break; case LRPC_PT_REPLY: n = "REP"; break; case LRPC_APPLICATION: n = "APP"; break; case LRPC_LAMBDA: n = "LBD"; break; case LRPC_SEQUENCE: n = "SEQ"; break; case LRPC_FLATNAME: n = "VAR"; break; case LRPC_NONNEGINT: n = "INT"; break; case LRPC_BIN: n = "BIN"; break; case LRPC_STR: n = "STR"; break; case LRPC_NONCE: n = "NCE"; break; default: n = "???"; break; } for (i = 0; i < lev; i++) fprintf(stderr, " "); if (t == LRPC_FLATNAME) fprintf(stderr, "%s (0x%x, len=%zu)\n", n, t, x->u.namelen); else fprintf(stderr, "%s (0x%x)\n", n, t); switch (t) { case LRPC_PT_REQUEST: case LRPC_PT_REPLY: case LRPC_APPLICATION: ccnl_rdr_dump(lev+1, x->u.fct); break; case LRPC_LAMBDA: ccnl_rdr_dump(lev+1, x->u.lambdavar); break; case LRPC_SEQUENCE: break; case LRPC_FLATNAME: case LRPC_NONNEGINT: case LRPC_BIN: case LRPC_STR: case LRPC_NONCE: default: return 0; } x = x->aux; while (x) { ccnl_rdr_dump(lev+1, x); x = x->nextinseq; } return 0; } // ---------------------------------------------------------------------- int8_t ccnl_emit_RpcReturn(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, int rc, char *reason, struct rdr_ds_s *content) { struct ccnl_buf_s *pkt; struct rdr_ds_s *seq, *element; size_t len = 0, switchlen = 0; unsigned char tmp[10]; len = strlen(reason) + 50; // add some headroom if (content) { if (ccnl_rdr_getFlatLen(content, &len)) { return -1; } } pkt = ccnl_buf_new(NULL, len); if (!pkt) { return -1; } // we build a sequence, and later change the type in the flattened bytes seq = ccnl_rdr_mkSeq(); element = ccnl_rdr_mkNonce((uint8_t*)nonce->aux, nonce->u.binlen); ccnl_rdr_seqAppend(seq, element); element = ccnl_rdr_mkNonNegInt((uint64_t) rc); ccnl_rdr_seqAppend(seq, element); element = ccnl_rdr_mkStr(reason); ccnl_rdr_seqAppend(seq, element); if (content) { ccnl_rdr_seqAppend(seq, content); } len = sizeof(tmp); if (ccnl_switch_prependCoding(CCNL_ENC_LOCALRPC, &len, tmp, &switchlen)) { ccnl_rdr_free(seq); ccnl_free(pkt); return -1; } memcpy(pkt->data, tmp + len, switchlen); if (ccnl_rdr_serialize(seq, pkt->data + switchlen, pkt->datalen - switchlen, &len)) { ccnl_rdr_free(seq); ccnl_free(pkt); return -1; } ccnl_rdr_free(seq); // fprintf(stderr, "%d bytes to return face=%p\n", len, from); *(pkt->data + switchlen) = LRPC_PT_REPLY; pkt->datalen = switchlen + len; ccnl_face_enqueue(relay, from, pkt); return 0; } // ---------------------------------------------------------------------- struct rpc_exec_s* rpc_exec_new(void) { return ccnl_calloc(1, sizeof(struct rpc_exec_s)); } void rpc_exec_free(struct rpc_exec_s *exec) { if (!exec) return; if (exec->ostack) ccnl_rdr_free(exec->ostack); ccnl_free(exec); } // ---------------------------------------------------------------------- int rpc_syslog(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, struct rpc_exec_s *exec, struct rdr_ds_s *param) { DEBUGMSG(DEBUG, "rpc_syslog\n"); (void)exec; if (ccnl_rdr_getType(param) == LRPC_STR) { char *cp = ccnl_malloc(param->u.strlen + 1); memcpy(cp, param->aux, param->u.strlen); cp[param->u.strlen] = '\0'; DEBUGMSG(DEBUG, "rpc_syslog: \"%s\"\n", cp); ccnl_free(cp); ccnl_emit_RpcReturn(relay, from, nonce, 200, "ok", NULL); } else { DEBUGMSG(DEBUG, "rpc_syslog: unknown param type\n"); ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_syslog: unknown param type", NULL); } return 0; } int rpc_cacheAdd(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, struct rpc_exec_s *exec, struct rdr_ds_s *param) { int len, cnt = 0; (void) exec; DEBUGMSG(DEBUG, "rpc_cacheAdd\n"); if (!ccnl_is_local_addr(&from->peer)) { ccnl_emit_RpcReturn(relay, from, nonce, 403, "invalid access: non-local address", NULL); return 0; } while (param) { if (ccnl_rdr_getType(param) != LRPC_BIN) { ccnl_emit_RpcReturn(relay, from, nonce, 415, "invalid or no data", NULL); return 0; } /* ucp = (unsigned char*) param->aux; */ len = param->u.binlen; // not implemented yet ... // len = param->u.binlen; DEBUGMSG(INFO, "not implemented: rpc_cacheAdd (%d bytes)\n", len); // first convert aux bits to ccnl_content_s ... // then call ccnl_content_add2cache(); cnt++; param = param->nextinseq; } ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_cacheAdd: not implemented yet", NULL); return 0; } int rpc_cacheRemove(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, struct rpc_exec_s *exec, struct rdr_ds_s *param) { int cnt = 0; (void)exec; DEBUGMSG(DEBUG, "rpc_cacheRemove\n"); if (!ccnl_is_local_addr(&from->peer)) { ccnl_emit_RpcReturn(relay, from, nonce, 403, "invalid access: non-local address", NULL); return 0; } while (param) { struct ccnl_content_s *c = relay->contents; char *p; struct ccnl_prefix_s *prefix; if (ccnl_rdr_getType(param) != LRPC_FLATNAME) { ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_cacheRemove: invalid name", NULL); return 0; } p = ccnl_malloc(param->u.strlen + 1); memcpy(p, param->aux, param->u.strlen); p[param->u.strlen] = '\0'; prefix = ccnl_URItoPrefix(p, CCNL_SUITE_DEFAULT, NULL); while (c) { if (!ccnl_prefix_cmp(c->pkt->pfx, NULL, prefix, CMP_EXACT)) { struct ccnl_content_s *tmp = c->next; ccnl_content_remove(relay, c); DEBUGMSG(DEBUG, "content %s removed\n", ccnl_prefix_to_path(prefix)); cnt++; c = tmp; } else c = c->next; } ccnl_free(p); ccnl_prefix_free(prefix); param = param->nextinseq; } { char *p = ccnl_malloc(100); sprintf(p, "rpc_cacheRemove: removed %d entries\n", cnt); ccnl_emit_RpcReturn(relay, from, nonce, 415, p, NULL); ccnl_free(p); } return 0; } int rpc_forward(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, struct rpc_exec_s *exec, struct rdr_ds_s *param) { int encoding; size_t len; char *cp; unsigned char *ucp; (void)exec; DEBUGMSG(DEBUG, "rpc_forward\n"); if (ccnl_rdr_getType(param) != LRPC_FLATNAME) { ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_forward: expected encoding name", NULL); return 0; } cp = ccnl_malloc(param->u.namelen + 1); memcpy(cp, param->aux, param->u.namelen); cp[param->u.namelen] = '\0'; #ifdef CCNL_SUITE_CCNB if (!strcmp(cp, "/rpc/const/encoding/ccnb")) encoding = CCNL_SUITE_CCNB; else #endif #ifdef CCNL_SUITE_CCNTLV if (!strcmp(cp, "/rpc/const/encoding/ccnx2014")) encoding = CCNL_SUITE_CCNTLV; else #endif #ifdef CCNL_SUITE_NDNTLV if (!strcmp(cp, "/rpc/const/encoding/ndn2013")) encoding = CCNL_SUITE_NDNTLV; else #endif encoding = -1; ccnl_free(cp); if (encoding < 0) { ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_forward: no such encoding", NULL); return 0; } while (param->nextinseq) { param = param->nextinseq; if (ccnl_rdr_getType(param) != LRPC_BIN) { ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_forward: invalid or no data", NULL); return 0; } ucp = (unsigned char*) param->aux; len = param->u.binlen; switch(encoding) { #ifdef USE_SUITE_CCNB case CCNL_SUITE_CCNB: ccnl_ccnb_forwarder(relay, from, &ucp, &len); break; #endif #ifdef USE_SUITE_CCNTLV case CCNL_SUITE_CCNTLV: ccnl_ccntlv_forwarder(relay, from, &ucp, &len); break; #endif #ifdef USE_SUITE_NDNTLV case CCNL_SUITE_NDNTLV: ccnl_ndntlv_forwarder(relay, from, &ucp, &len); break; #endif default: break; } } return 0; } int rpc_lookup(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *nonce, struct rpc_exec_s *exec, struct rdr_ds_s *param) { DEBUGMSG(DEBUG, "rpc_lookup\n"); (void)exec; if (ccnl_rdr_getType(param) == LRPC_FLATNAME) { char *cp = ccnl_malloc(param->u.namelen + 1); struct rdr_ds_s *val = 0; memcpy(cp, param->aux, param->u.namelen); cp[param->u.namelen] = '\0'; if (!strcmp(cp, "/rpc/config/compileString")) { val = ccnl_rdr_mkStr((char*)compile_string); } else if (!strcmp(cp, "/rpc/config/localTime")) { time_t t = time(NULL); char *p = ctime(&t); p[strlen(p) - 1] = '\0'; val = ccnl_rdr_mkStr(p); } ccnl_free(cp); if (val) ccnl_emit_RpcReturn(relay, from, nonce, 200, "ok", val); else ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_lookup: no such variable", NULL); } else { ccnl_emit_RpcReturn(relay, from, nonce, 415, "rpc_lookup: not a variable name", NULL); } return 0; } struct x_s { char *name; rpcBuiltinFct *fct; } builtin[] = { {"/rpc/builtin/cache/add", rpc_cacheAdd}, {"/rpc/builtin/cache/remove", rpc_cacheRemove}, {"/rpc/builtin/forward", rpc_forward}, {"/rpc/builtin/lookup", rpc_lookup}, {"/rpc/builtin/syslog", rpc_syslog}, {NULL, NULL} }; rpcBuiltinFct* rpc_getBuiltinFct(struct rdr_ds_s *var) { struct x_s *x = builtin; if (var->type != LRPC_FLATNAME) return NULL; while (x->name) { if (strlen(x->name) == var->u.namelen && !memcmp(x->name, var->aux, var->u.namelen)) return x->fct; x++; } return NULL; } int ccnl_localrpc_handleReply(struct ccnl_relay_s *relay, struct ccnl_face_s *from, struct rdr_ds_s *aux) { (void) relay; (void) from; DEBUGMSG(DEBUG, "ccnl_localrpc_handleReply %d %d\n", ccnl_rdr_getType(aux), ccnl_rdr_getType(aux->nextinseq)); return 0; } int ccnl_localrpc_handleRequest(struct ccnl_relay_s *relay, struct ccnl_face_s *from, // struct rdr_ds_s *fexpr, struct rdr_ds_s *args) struct rdr_ds_s *req) { struct rdr_ds_s *nonce, *fexpr; struct rpc_exec_s *exec; int ftype, ntype, rc = -1; rpcBuiltinFct *fct; DEBUGMSG(DEBUG, "ccnl_localrpc_handleRequest face=%p\n", (void*) from); nonce = req->aux; if (!nonce) return -1; fexpr = nonce->nextinseq; ntype = ccnl_rdr_getType(nonce); ftype = ccnl_rdr_getType(fexpr); if (ntype != LRPC_NONCE || ftype != LRPC_APPLICATION) { DEBUGMSG(DEBUG, " malformed RPC request (%02x %02x)\n", ntype, ftype); ccnl_emit_RpcReturn(relay, from, nonce, 404, "malformed RPC request", NULL); goto done; } ftype = ccnl_rdr_getType(fexpr->u.fct); if (ftype != LRPC_FLATNAME) { DEBUGMSG(DEBUG, " (%02x) only constant fct names supported yet\n", ftype); ccnl_emit_RpcReturn(relay, from, nonce, 404, "only constant fct names supported yet", NULL); goto done; } fct = rpc_getBuiltinFct(fexpr->u.fct); if (!fct) { DEBUGMSG(DEBUG, " unknown RPC builtin function (type=0x%02x)\n", ftype); ccnl_emit_RpcReturn(relay, from, nonce, 501, "unknown function", NULL); goto done; } exec = rpc_exec_new(); rc = fct(relay, from, nonce, exec, fexpr->aux); rpc_exec_free(exec); done: return rc; } int8_t ccnl_localrpc_exec(struct ccnl_relay_s *relay, struct ccnl_face_s *from, uint8_t **buf, size_t *buflen) { struct rdr_ds_s *a; // , *fct; int rc = 0, type; DEBUGMSG(DEBUG, "ccnl_localrpc_exec: %zu bytes from face=%p (id=%d.%d)\n", *buflen, (void*)from, relay->id, from ? from->faceid : -1); while (rc == 0 && *buflen > 0) { if (**buf && **buf != LRPC_PT_REQUEST && **buf != LRPC_PT_REPLY) { DEBUGMSG(DEBUG, " not an RPC packet\n"); return -1; } a = ccnl_rdr_unserialize(*buf, *buflen); if (!a) { DEBUGMSG(DEBUG, " unserialization error\n"); return -1; } // ccnl_rdr_dump(0, a); type = ccnl_rdr_getType(a); // fprintf(stderr, "type=%d\n", type); if (type == LRPC_PT_REQUEST) { rc = ccnl_localrpc_handleRequest(relay, from, a); } else if (type == LRPC_PT_REPLY) { rc = ccnl_localrpc_handleReply(relay, from, a); } else { DEBUGMSG(DEBUG, " unserialization error %d\n", type); return -1; } /* fct = a->u.fct; if (ccnl_rdr_getType(fct) == LRPC_NONNEGINT) // RPC return msg else */ if (rc < 0) { // DEBUGMSG(WARNING, " error processing RPC msg\n"); // return rc; } ccnl_rdr_free(a); *buf += a->flatlen; if (a->flatlen > *buflen) { *buflen -= a->flatlen; break; } *buflen -= a->flatlen; } return 0; } #endif //USE_SUITE_LOCALRPC /* suppress empty translation unit error */ typedef int unused_typedef; // eof
the_stack_data/135267.c
#include <signal.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #define DIM 50 int main(int argc,char** argv){ if(argc!=2) exit(0); pid_t pid; int f[2]; if(!pipe(f)){ pid=fork(); if(!pid){ close(f[0]); int fp=open(argv[1],O_RDONLY); int rd=1; char buf[DIM]; while(rd>0){ strcpy(buf,""); rd=read(fp,&buf[0],DIM); if(rd==(-1)){ printf("Errore in lettura file\n"); break; } if(rd>0) write(f[1],&buf[0],rd); } close(f[1]); close(fp); exit(1); } else{ close(f[1]); int rd=1; char buf[DIM]; while(rd>0){ strcpy(buf,""); rd=read(f[0],&buf[0],DIM); if(rd==(-1)){ printf("Errore in lettura dalla pipe\n"); break; } if(rd>0) write(1,&buf[0],rd); } close(f[0]); exit(1); } } else exit(0); }
the_stack_data/112521.c
#include <stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; }*first=NULL,*last; void create(int A[],int n){ int i; struct node *t,*last; first=(struct node *)malloc(sizeof(struct node)); first->data=A[0]; first->next=NULL; last=first; for(int i=1;i<n;i++){ t=(struct node *)malloc(sizeof(struct node)); t->data=A[i]; t->next=NULL; last->next=t; last=t; } } void display( struct node *p){ while(p!=NULL){ printf("%d ",p->data); p=p->next; } } int count1(struct node *p){ int count=0; while(p){ count++; p=p->next; } return(count); } void append(struct node *p,int x){ struct node *t; t=(struct node *)malloc(sizeof(struct node)); t->data=x; t->next=NULL; if(first==NULL){ first=last=t; } else{ last->next=t; last=t; } } void insert1(struct node *p,int pos,int x){ struct node *t; int count=count1(first); t=(struct node *)malloc(sizeof(struct node)); if(pos==0){ t->data=x; t->next=first; first=t; } else if(pos>0 && pos<= count){ t->data=x; p=first; for(int i=0;i< pos- 1;i++){ p=p->next; } t->next=p->next; p->next=t; } else{ printf("enter a valid position"); } } int to_find_pos_sorted_list(struct node *p,int x){ int count=0; int count1=0; while(p!=NULL){ if(p->data<x){ count++; } count1++; p=p->next; } if(count<count1){ return(count); } else{ return(count1); } }// sir code /*void SortedInsert(struct Node *p,int x) { struct Node *t,*q=NULL; t=(struct Node*)malloc(sizeof(struct Node)); t->data=x; t->next=NULL; if(first==NULL) first=t; else { while(p && p->data<x) { q=p; p=p->next; } if(p==first) { t->next=first; first=t; } else { t->next=q->next; q->next=t; } } }*/ void del(struct node *p,int pos){ struct node *q; q=first; int count=count1(first); printf("%d",count); if(pos == 0){ first=first->next; int x=p->data; free(p); printf("deleted %d at pos %d\n",x,pos); } else if(pos>0 && pos< count){ for(int i=0;i<=pos;i++){ p=p->next; } for(int i=0;i<=pos-1;i++){ q=q->next; } q->next=p->next; int x=p->data; free(p); printf("deleted %d at pos %d\n",x,pos); } else{ printf("invalid pos"); } } int delete(struct node *p,int index) { struct node *q=NULL; int x=-1,i; if(index==1) { q=first; x=first->data; first=first->next; free(q); return x; } else { for(i=0;i<index-1;i++) { q=p; p=p->next; } q->next=p->next; x=p->data; free(p); return x; } } int main() { struct node *temp; int a[]={3,5,7,15,20}; create(a,5); int b; printf("enter the element to be append in the list\n"); scanf("%d",&b); int position=to_find_pos_sorted_list(first,b); insert1(first,position,b); display(first); printf("\n"); //del(first,5); delete(first,5); display(first); }
the_stack_data/45449208.c
#include <stdio.h> int maxProfit(int* prices, int pricesSize) { int max = 0; int left = 0; int right = 1; while (right < pricesSize) { int now = prices[right] - prices[left]; if (prices[left] < prices[right]) max = max > now ? max : now; else left = right; right++; } return max; } int main() { int a[] = {7, 1, 5, 3, 6, 4}; printf("%d", maxProfit(a, 6)); return 0; }
the_stack_data/200142138.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define STACK_SIZE 100 #define STACK_INCREAMENT 10 int n,A[101]={}; typedef struct stackelement{ int value; int index; }element; typedef struct node { element *top; element *base; int stacksize; }stack; void stackinit(stack *s){ s->base=(element*)malloc(STACK_SIZE*sizeof(element)); if(NULL==s->base){ printf("No memory for stack!\n"); return ; } s->top=s->base; s->stacksize=STACK_SIZE; for(int i=0;i<STACK_SIZE;i++){ s->base[i].value=0; s->base[i].index=-1; } return ; } void push(stack *s,int value,int index){ element tmp; if(s->top-s->base>=s->stacksize){ s->base=(element*)realloc(s->base,(s->stacksize+STACK_INCREAMENT)*sizeof(element)); if(NULL==s->base){ printf("No memory for stack increament!\n"); return ; } s->top=s->base; s->stacksize+=STACK_INCREAMENT; } tmp.value=value; tmp.index=index; *s->top=tmp; *s->top++; return ; } element* pop(stack *s){ if(s->top==s->base){ return NULL; } s->top--; return s->top; } int isempty(stack *s){ if(s->top==s->base) return 1; return 0; } void destroy(stack *s){ s->top=s->base; free(s->base); s->base=NULL; s->stacksize=0; return ; } element* top(stack *s){ element* tmp; if(s->base==s->top){ return NULL; } tmp=(s->top-1); return tmp; } int area(stack *s,int *B,int n){ int i,j,res=0; element* tmp; int value ,index=0; if(n<3) return 0; for(i=0;i<n;i++){ while(!isempty(s)){ tmp=top(s); /*This is interesting ,because i-tmp.index-1,means B[i] need two number to decide the next number's water!while the B[i]<tmp.value,that means i-tmp.index-1=0,and i will push the number to the stack .while B[i]>tmp.value ,i will set the value to value and pop then another min(top(s),B[i]) to decide the water next to the B[i],add it to res!quite nice */ res+=(min(B[i],tmp->value)-value)*(i-tmp->index-1); value=tmp->value; if(B[i]>tmp->value){ pop(s); }else{ break; } } push(s,B[i],i); } return res; } int main(int argc,int **argv){ int i; stack s; stackinit(&s); printf("Please input the number of the array: \n"); scanf("%d",&n); /* printf("Please input the k number :\n"); scanf("%d",&target);*/ printf("Please input the array :\n"); for(i=0;i<n;i++){ scanf("%d",&A[i]); } /* fastsort(1,n); printf("The sorted array is :\n"); for(i=1;i<=n;i++){ printf("%d ",A[i]); } printf("\n");*/ printf("The area is %d \n",area(&s,A,n)); /* while((i=permutation(&A[1],n,target))){ if(i==2){ printf("Kth array is found!\n"); return 0; } }*/ destroy(&s); // printf("The permutation_nr is %d\n",permutation_nr); return 0; }
the_stack_data/26699742.c
/* shishi.c -- functions to use Heimdal's and MIT's Kerberos V Copyright (C) 2014, 2015 Free Software Foundation, Inc. This file is part of GNU Inetutils. GNU Inetutils 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. GNU Inetutils 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/'. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef KRB5 # include <stdio.h> # include <stdlib.h> # include <string.h> # include <unistd.h> # include <krb5.h> # include "kerberos5_def.h" /* authentication, client side */ int kerberos_auth (krb5_context *ctx, int verbose, char **cname, const char *sname, int sock, char *cmd, unsigned short port, krb5_keyblock **key, const char *realm) { int rc; char *out, *p; size_t outlen; int krb5len, msglen; char *tmpserver; char auth; /* KERBEROS 5 SENDAUTH MESSAGE */ char krb5sendauth[] = "KRB5_SENDAUTH_V1.0"; /* PROTOCOL VERSION */ char krb5sendclient[] = "KCMDV0.2"; /* to store error msg sent by server */ char errormsg[101]; char cksumdata[101]; krb5_data cksum_data; krb5_principal server; krb5_auth_context auth_ctx = NULL; krb5_flags authopts = AP_OPTS_USE_SUBKEY; if (krb5_sname_to_principal (*ctx, sname, "host", KRB5_NT_SRV_HST, &server)) return (-1); /* If realm is null, look up from table */ if (realm == NULL || realm[0] == '\0') # ifdef KRB5_GENERAL__ /* MIT */ realm = (char *) krb5_princ_realm (*ctx, server); # else /* Heimdal */ realm = krb5_principal_get_realm (*ctx, server); # endif /* size of KRB5 auth message */ krb5len = strlen (krb5sendauth) + 1; msglen = htonl (krb5len); write (sock, &msglen, sizeof (int)); /* KRB5 authentication message */ write (sock, krb5sendauth, krb5len); /* size of client message */ krb5len = strlen (krb5sendclient) + 1; msglen = htonl (krb5len); write (sock, &msglen, sizeof (int)); /* KRB5 client message */ write (sock, krb5sendclient, krb5len); /* get answer from server 0 = ok, 1 = error with message */ read (sock, &auth, 1); if (auth) { ssize_t n; errormsg[0] = '\0'; n = read (sock, errormsg, sizeof (errormsg) - 1); if (n >= 0 && n < (ssize_t) sizeof (errormsg)) errormsg[n] = '\0'; else errormsg[sizeof (errormsg) -1] = '\0'; fprintf (stderr, "Error during server authentication : %s\n", errormsg); return -1; } if (verbose) { printf ("Client: %s\n", *cname); printf ("Server: %s\n", sname); } /* Get a ticket for the server. */ tmpserver = malloc (strlen (SERVICE) + strlen (sname) + 2); if (!tmpserver) { perror ("kerberos_auth()"); return -1; } p = strchr (sname, '/'); if (p && (p != sname)) strcpy (tmpserver, sname); /* Non-empty prefix. */ else sprintf (tmpserver, "%s/%s", SERVICE, sname + (p ? 1 : 0)); /* Retrieve realm assigned to this server as per configuration, * unless an explicit domain was passed in the call. */ if (!realm) { if (!p) p = (char *) sname; else if (*p == '/') ++p; } /* checksum = port: terminal name */ cksum_data.length = snprintf (cksumdata, sizeof (cksumdata) - 1, "%u:%s%s", ntohs (port), cmd, *cname); if (strncmp (cmd, "-x ", 3) == 0) authopts |= AP_OPTS_MUTUAL_REQUIRED; cksum_data.data = cksumdata; rc = krb5_sendauth (*ctx, &auth_ctx, &sock, "KCMDV0.2", NULL, server, authopts, &cksum_data, NULL, NULL, NULL, NULL, NULL); if (rc == KRB5_SENDAUTH_REJECTED) { fprintf (stderr, "server rejected authentication"); return rc; } krb5_free_principal (*ctx, server); # if 0 krb5_data_free (&cksum_data); # endif rc = krb5_auth_con_getlocalsubkey (*ctx, auth_ctx, key); /* send size of AP-REQ to the server */ msglen = outlen; msglen = htonl (msglen); write (sock, (char *) &msglen, sizeof (int)); /* send AP-REQ to the server */ write (sock, out, outlen); /* read response from server - what ? */ read (sock, &rc, sizeof (rc)); if (rc) return -1 /* SHISHI_APREP_VERIFY_FAILED */; /* For mutual authentication, wait for server reply. */ /* We are now authenticated. */ if (verbose) printf ("User authenticated.\n"); return 0; } /* authentication, server side */ int get_auth (int infd, krb5_context *ctx, krb5_auth_context *actx, krb5_keyblock **key, const char **err_msg, int *protoversion, int *cksumtype, char **cksum, size_t *cksumlen, char *srvname) { char *out; size_t outlen; char *buf; int buflen; int len; int rc; int error; /* KERBEROS 5 SENDAUTH MESSAGE */ char krb5sendauth[] = "KRB5_SENDAUTH_V1.0"; /* PROTOCOL VERSION */ char krb5kcmd1[] = "KCMDV0.1"; char krb5kcmd2[] = "KCMDV0.2"; char *servername, *server = NULL, *realm = NULL; *err_msg = NULL; /* Get key for the server. */ # if 0 /* * XXX: Taken straight from the version for libshishi. * XXX: No adaptions yet. */ rc = shishi_init_server (handle); if (rc != SHISHI_OK) return rc; if (srvname && *srvname) { rc = shishi_parse_name (*handle, srvname, &server, &realm); if (rc != SHISHI_OK) { *err_msg = shishi_strerror (rc); return rc; } } if (server && *server) { char *p; servername = malloc (sizeof (SERVICE) + strlen (server) + 2); if (!servername) { *err_msg = "Not enough memory"; return SHISHI_TOO_SMALL_BUFFER; } p = strchr (server, '/'); if (p && (p != server)) sprintf (servername, "%s", server); /* Non-empty prefix. */ else sprintf (servername, "%s/%s", SERVICE, server + (p ? 1 : 0)); /* Remove initial slash. */ } else servername = shishi_server_for_local_service (*handle, SERVICE); if (realm && *realm) shishi_realm_default_set (*handle, realm); free (server); free (realm); /* Enable use of `~/.k5login'. */ if (shishi_check_version ("1.0.2")) /* Faulty in version 1.0.1. */ { rc = shishi_cfg_authorizationtype_set (*handle, "k5login basic"); if (rc != SHISHI_OK) { *err_msg = shishi_error (*handle); return rc; } } key = shishi_hostkeys_for_serverrealm (*handle, servername, shishi_realm_default (*handle)); free (servername); if (!key) { *err_msg = shishi_error (*handle); return SHISHI_INVALID_KEY; } /* Read Kerberos 5 sendauth message */ rc = read (infd, &len, sizeof (int)); if (rc != sizeof (int)) { *err_msg = "Error reading message size"; return SHISHI_IO_ERROR; } buflen = ntohl (len); buf = malloc (buflen); if (!buf) { *err_msg = "Not enough memory"; return SHISHI_TOO_SMALL_BUFFER; } rc = read (infd, buf, buflen); if (rc != buflen) { *err_msg = "Error reading authentication message"; return SHISHI_IO_ERROR; } len = strlen (krb5sendauth); rc = strncmp (buf, krb5sendauth, buflen >= len ? len : buflen); if (rc) { *err_msg = "Invalid authentication type"; /* Authentication type is wrong. */ write (infd, "\001", 1); return SHISHI_VERIFY_FAILED; } free (buf); /* Read protocol version */ rc = read (infd, &len, sizeof (int)); if (rc != sizeof (int)) { *err_msg = "Error reading protocol message size"; return SHISHI_IO_ERROR; } buflen = ntohl (len); buf = malloc (buflen); if (!buf) { *err_msg = "Not enough memory"; return SHISHI_TOO_SMALL_BUFFER; } rc = read (infd, buf, buflen); if (rc != buflen) { *err_msg = "Error reading protocol message"; return SHISHI_IO_ERROR; } len = strlen (krb5kcmd1); rc = strncmp (buf, krb5kcmd1, buflen >= len ? len : buflen); if (rc) { len = strlen (krb5kcmd2); rc = strncmp (buf, krb5kcmd2, buflen >= len ? len : buflen); if (rc) { *err_msg = "Protocol version not supported"; /* Protocol version is wrong. */ write (infd, "\002", 1); return SHISHI_VERIFY_FAILED; } *protoversion = 2; } else *protoversion = 1; free (buf); /* Authentication type is ok */ write (infd, "\0", 1); /* Read Authentication request from client */ rc = read (infd, &len, sizeof (int)); if (rc != sizeof (int)) { *err_msg = "Error reading authentication request size"; return SHISHI_IO_ERROR; } buflen = ntohl (len); buf = malloc (buflen); if (!buf) { *err_msg = "Not enough memory"; return SHISHI_TOO_SMALL_BUFFER; } rc = read (infd, buf, buflen); if (rc != buflen) { *err_msg = "Error reading authentication request"; return SHISHI_IO_ERROR; } /* Create Authentication context */ rc = shishi_ap_nosubkey (*handle, ap); if (rc != SHISHI_OK) return rc; /* Store request in context */ rc = shishi_ap_req_der_set (*ap, buf, buflen); if (rc != SHISHI_OK) return rc; free (buf); /* Process authentication request */ rc = shishi_ap_req_process (*ap, key); if (rc != SHISHI_OK) return rc; # ifdef ENCRYPTION /* extract subkey if present from ap exchange for secure connection */ if (*protoversion == 2) { *enckey = NULL; shishi_authenticator_get_subkey (*handle, shishi_ap_authenticator (*ap), enckey); } # endif /* Get authenticator checksum */ rc = shishi_authenticator_cksum (*handle, shishi_ap_authenticator (*ap), cksumtype, cksum, cksumlen); if (rc != SHISHI_OK) return rc; /* User is authenticated. */ error = 0; write (infd, &error, sizeof (int)); /* Authenticate ourself to client, if requested. */ if (shishi_apreq_mutual_required_p (*handle, shishi_ap_req (*ap))) { int len; rc = shishi_ap_rep_der (*ap, &out, &outlen); if (rc != SHISHI_OK) return rc; len = outlen; len = htonl (len); rc = write (infd, &len, sizeof (len)); if (rc != sizeof (int)) { *err_msg = "Error sending AP-REP"; free (out); return SHISHI_IO_ERROR; } rc = write (infd, out, ntohl (len)); if (rc != (int) ntohl (len)) { *err_msg = "Error sending AP-REP"; free (out); return SHISHI_IO_ERROR; } free (out); /* We are authenticated to client */ } # ifdef ENCRYPTION if (*protoversion == 1) { Shishi_tkt *tkt; tkt = shishi_ap_tkt (*ap); if (tkt == NULL) { *err_msg = "Could not get tkt from AP-REQ"; return SHISHI_INVALID_TICKET; } rc = shishi_encticketpart_get_key (*handle, shishi_tkt_encticketpart (tkt), enckey); if (rc != SHISHI_OK) return rc; } # endif /* ENCRYPTION */ return 0; # else return -1; # endif } #endif /* KRB5 */
the_stack_data/1065685.c
#include <stdio.h> int main(){ char check[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'}; char alpha; int i,j, chec; printf("WHat is your letter between A-J: "); scanf("%c",&alpha); fflush(stdin); chec = (sizeof(check)/sizeof(char)); for(int i=0; i<chec; i++){ if(alpha==check[i]){ for(int j=0; j<6; j++){ printf("%c",check[(i+1)+j]);; } } } return 0; }
the_stack_data/1155372.c
#include <stdio.h> #include <stdlib.h> int main() { char nome; double V; double SB; double SL ; scanf("%s", &nome); scanf("%lf", &SB); scanf("%lf", &V); SL = (SB + (15 * V) / 100); printf("TOTAL = R$ %.2lf\n", SL); return 0; }
the_stack_data/181393196.c
#include <stdio.h> #include <stdlib.h> void sort(int n, int arr[]){ int step=n-1,c; while(step>=1){ for(int i=0;i<n-step;i++){ if(arr[i]>arr[i+step]){ c=arr[i]; arr[i]=arr[i+step]; arr[i+step]=c; } } step--; } } int main(){ int n; scanf("%d",&n); int arr[n]; for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } sort(n,arr); for(int i=0;i<n;i++){ printf("%d ", arr[i]); } printf("\n"); return 0; }
the_stack_data/151706555.c
extern float __VERIFIER_nondet_float(void); extern int __VERIFIER_nondet_int(void); typedef enum {false, true} bool; bool __VERIFIER_nondet_bool(void) { return __VERIFIER_nondet_int() != 0; } int main() { bool _J887, _x__J887; bool _J881, _x__J881; bool _EL_U_854, _x__EL_U_854; float x_13, _x_x_13; float x_0, _x_x_0; bool _EL_X_852, _x__EL_X_852; bool _EL_U_858, _x__EL_U_858; float x_11, _x_x_11; float x_2, _x_x_2; float x_14, _x_x_14; float x_3, _x_x_3; float x_15, _x_x_15; float x_4, _x_x_4; float x_5, _x_x_5; float x_6, _x_x_6; float x_1, _x_x_1; float x_7, _x_x_7; float x_10, _x_x_10; float x_8, _x_x_8; float x_9, _x_x_9; float x_12, _x_x_12; int __steps_to_fair = __VERIFIER_nondet_int(); _J887 = __VERIFIER_nondet_bool(); _J881 = __VERIFIER_nondet_bool(); _EL_U_854 = __VERIFIER_nondet_bool(); x_13 = __VERIFIER_nondet_float(); x_0 = __VERIFIER_nondet_float(); _EL_X_852 = __VERIFIER_nondet_bool(); _EL_U_858 = __VERIFIER_nondet_bool(); x_11 = __VERIFIER_nondet_float(); x_2 = __VERIFIER_nondet_float(); x_14 = __VERIFIER_nondet_float(); x_3 = __VERIFIER_nondet_float(); x_15 = __VERIFIER_nondet_float(); x_4 = __VERIFIER_nondet_float(); x_5 = __VERIFIER_nondet_float(); x_6 = __VERIFIER_nondet_float(); x_1 = __VERIFIER_nondet_float(); x_7 = __VERIFIER_nondet_float(); x_10 = __VERIFIER_nondet_float(); x_8 = __VERIFIER_nondet_float(); x_9 = __VERIFIER_nondet_float(); x_12 = __VERIFIER_nondet_float(); bool __ok = (1 && ((( !(_EL_U_858 || ( !(( !_EL_X_852) || (( !((x_0 + (-1.0 * x_13)) <= -4.0)) && _EL_U_854))))) && ( !_J881)) && ( !_J887))); while (__steps_to_fair >= 0 && __ok) { if ((_J881 && _J887)) { __steps_to_fair = __VERIFIER_nondet_int(); } else { __steps_to_fair--; } _x__J887 = __VERIFIER_nondet_bool(); _x__J881 = __VERIFIER_nondet_bool(); _x__EL_U_854 = __VERIFIER_nondet_bool(); _x_x_13 = __VERIFIER_nondet_float(); _x_x_0 = __VERIFIER_nondet_float(); _x__EL_X_852 = __VERIFIER_nondet_bool(); _x__EL_U_858 = __VERIFIER_nondet_bool(); _x_x_11 = __VERIFIER_nondet_float(); _x_x_2 = __VERIFIER_nondet_float(); _x_x_14 = __VERIFIER_nondet_float(); _x_x_3 = __VERIFIER_nondet_float(); _x_x_15 = __VERIFIER_nondet_float(); _x_x_4 = __VERIFIER_nondet_float(); _x_x_5 = __VERIFIER_nondet_float(); _x_x_6 = __VERIFIER_nondet_float(); _x_x_1 = __VERIFIER_nondet_float(); _x_x_7 = __VERIFIER_nondet_float(); _x_x_10 = __VERIFIER_nondet_float(); _x_x_8 = __VERIFIER_nondet_float(); _x_x_9 = __VERIFIER_nondet_float(); _x_x_12 = __VERIFIER_nondet_float(); __ok = ((((((((((((((((((((x_15 + (-1.0 * _x_x_0)) <= -18.0) && (((x_13 + (-1.0 * _x_x_0)) <= -5.0) && (((x_12 + (-1.0 * _x_x_0)) <= -5.0) && (((x_11 + (-1.0 * _x_x_0)) <= -14.0) && (((x_10 + (-1.0 * _x_x_0)) <= -4.0) && (((x_8 + (-1.0 * _x_x_0)) <= -18.0) && (((x_0 + (-1.0 * _x_x_0)) <= -2.0) && ((x_7 + (-1.0 * _x_x_0)) <= -11.0)))))))) && (((x_15 + (-1.0 * _x_x_0)) == -18.0) || (((x_13 + (-1.0 * _x_x_0)) == -5.0) || (((x_12 + (-1.0 * _x_x_0)) == -5.0) || (((x_11 + (-1.0 * _x_x_0)) == -14.0) || (((x_10 + (-1.0 * _x_x_0)) == -4.0) || (((x_8 + (-1.0 * _x_x_0)) == -18.0) || (((x_0 + (-1.0 * _x_x_0)) == -2.0) || ((x_7 + (-1.0 * _x_x_0)) == -11.0))))))))) && ((((x_13 + (-1.0 * _x_x_1)) <= -6.0) && (((x_12 + (-1.0 * _x_x_1)) <= -1.0) && (((x_9 + (-1.0 * _x_x_1)) <= -11.0) && (((x_8 + (-1.0 * _x_x_1)) <= -20.0) && (((x_5 + (-1.0 * _x_x_1)) <= -12.0) && (((x_2 + (-1.0 * _x_x_1)) <= -9.0) && (((x_0 + (-1.0 * _x_x_1)) <= -2.0) && ((x_1 + (-1.0 * _x_x_1)) <= -12.0)))))))) && (((x_13 + (-1.0 * _x_x_1)) == -6.0) || (((x_12 + (-1.0 * _x_x_1)) == -1.0) || (((x_9 + (-1.0 * _x_x_1)) == -11.0) || (((x_8 + (-1.0 * _x_x_1)) == -20.0) || (((x_5 + (-1.0 * _x_x_1)) == -12.0) || (((x_2 + (-1.0 * _x_x_1)) == -9.0) || (((x_0 + (-1.0 * _x_x_1)) == -2.0) || ((x_1 + (-1.0 * _x_x_1)) == -12.0)))))))))) && ((((x_14 + (-1.0 * _x_x_2)) <= -5.0) && (((x_9 + (-1.0 * _x_x_2)) <= -13.0) && (((x_8 + (-1.0 * _x_x_2)) <= -15.0) && (((x_7 + (-1.0 * _x_x_2)) <= -8.0) && (((x_6 + (-1.0 * _x_x_2)) <= -6.0) && (((x_3 + (-1.0 * _x_x_2)) <= -1.0) && (((x_0 + (-1.0 * _x_x_2)) <= -18.0) && ((x_1 + (-1.0 * _x_x_2)) <= -15.0)))))))) && (((x_14 + (-1.0 * _x_x_2)) == -5.0) || (((x_9 + (-1.0 * _x_x_2)) == -13.0) || (((x_8 + (-1.0 * _x_x_2)) == -15.0) || (((x_7 + (-1.0 * _x_x_2)) == -8.0) || (((x_6 + (-1.0 * _x_x_2)) == -6.0) || (((x_3 + (-1.0 * _x_x_2)) == -1.0) || (((x_0 + (-1.0 * _x_x_2)) == -18.0) || ((x_1 + (-1.0 * _x_x_2)) == -15.0)))))))))) && ((((x_15 + (-1.0 * _x_x_3)) <= -18.0) && (((x_13 + (-1.0 * _x_x_3)) <= -13.0) && (((x_10 + (-1.0 * _x_x_3)) <= -18.0) && (((x_7 + (-1.0 * _x_x_3)) <= -18.0) && (((x_6 + (-1.0 * _x_x_3)) <= -5.0) && (((x_4 + (-1.0 * _x_x_3)) <= -19.0) && (((x_0 + (-1.0 * _x_x_3)) <= -2.0) && ((x_1 + (-1.0 * _x_x_3)) <= -15.0)))))))) && (((x_15 + (-1.0 * _x_x_3)) == -18.0) || (((x_13 + (-1.0 * _x_x_3)) == -13.0) || (((x_10 + (-1.0 * _x_x_3)) == -18.0) || (((x_7 + (-1.0 * _x_x_3)) == -18.0) || (((x_6 + (-1.0 * _x_x_3)) == -5.0) || (((x_4 + (-1.0 * _x_x_3)) == -19.0) || (((x_0 + (-1.0 * _x_x_3)) == -2.0) || ((x_1 + (-1.0 * _x_x_3)) == -15.0)))))))))) && ((((x_15 + (-1.0 * _x_x_4)) <= -11.0) && (((x_11 + (-1.0 * _x_x_4)) <= -13.0) && (((x_10 + (-1.0 * _x_x_4)) <= -14.0) && (((x_7 + (-1.0 * _x_x_4)) <= -12.0) && (((x_6 + (-1.0 * _x_x_4)) <= -19.0) && (((x_5 + (-1.0 * _x_x_4)) <= -16.0) && (((x_0 + (-1.0 * _x_x_4)) <= -5.0) && ((x_3 + (-1.0 * _x_x_4)) <= -15.0)))))))) && (((x_15 + (-1.0 * _x_x_4)) == -11.0) || (((x_11 + (-1.0 * _x_x_4)) == -13.0) || (((x_10 + (-1.0 * _x_x_4)) == -14.0) || (((x_7 + (-1.0 * _x_x_4)) == -12.0) || (((x_6 + (-1.0 * _x_x_4)) == -19.0) || (((x_5 + (-1.0 * _x_x_4)) == -16.0) || (((x_0 + (-1.0 * _x_x_4)) == -5.0) || ((x_3 + (-1.0 * _x_x_4)) == -15.0)))))))))) && ((((x_15 + (-1.0 * _x_x_5)) <= -13.0) && (((x_13 + (-1.0 * _x_x_5)) <= -6.0) && (((x_10 + (-1.0 * _x_x_5)) <= -12.0) && (((x_9 + (-1.0 * _x_x_5)) <= -1.0) && (((x_8 + (-1.0 * _x_x_5)) <= -11.0) && (((x_6 + (-1.0 * _x_x_5)) <= -6.0) && (((x_3 + (-1.0 * _x_x_5)) <= -5.0) && ((x_4 + (-1.0 * _x_x_5)) <= -2.0)))))))) && (((x_15 + (-1.0 * _x_x_5)) == -13.0) || (((x_13 + (-1.0 * _x_x_5)) == -6.0) || (((x_10 + (-1.0 * _x_x_5)) == -12.0) || (((x_9 + (-1.0 * _x_x_5)) == -1.0) || (((x_8 + (-1.0 * _x_x_5)) == -11.0) || (((x_6 + (-1.0 * _x_x_5)) == -6.0) || (((x_3 + (-1.0 * _x_x_5)) == -5.0) || ((x_4 + (-1.0 * _x_x_5)) == -2.0)))))))))) && ((((x_14 + (-1.0 * _x_x_6)) <= -4.0) && (((x_13 + (-1.0 * _x_x_6)) <= -14.0) && (((x_11 + (-1.0 * _x_x_6)) <= -4.0) && (((x_10 + (-1.0 * _x_x_6)) <= -16.0) && (((x_8 + (-1.0 * _x_x_6)) <= -7.0) && (((x_5 + (-1.0 * _x_x_6)) <= -18.0) && (((x_3 + (-1.0 * _x_x_6)) <= -20.0) && ((x_4 + (-1.0 * _x_x_6)) <= -3.0)))))))) && (((x_14 + (-1.0 * _x_x_6)) == -4.0) || (((x_13 + (-1.0 * _x_x_6)) == -14.0) || (((x_11 + (-1.0 * _x_x_6)) == -4.0) || (((x_10 + (-1.0 * _x_x_6)) == -16.0) || (((x_8 + (-1.0 * _x_x_6)) == -7.0) || (((x_5 + (-1.0 * _x_x_6)) == -18.0) || (((x_3 + (-1.0 * _x_x_6)) == -20.0) || ((x_4 + (-1.0 * _x_x_6)) == -3.0)))))))))) && ((((x_15 + (-1.0 * _x_x_7)) <= -17.0) && (((x_14 + (-1.0 * _x_x_7)) <= -16.0) && (((x_13 + (-1.0 * _x_x_7)) <= -20.0) && (((x_10 + (-1.0 * _x_x_7)) <= -15.0) && (((x_7 + (-1.0 * _x_x_7)) <= -20.0) && (((x_6 + (-1.0 * _x_x_7)) <= -3.0) && (((x_3 + (-1.0 * _x_x_7)) <= -6.0) && ((x_4 + (-1.0 * _x_x_7)) <= -11.0)))))))) && (((x_15 + (-1.0 * _x_x_7)) == -17.0) || (((x_14 + (-1.0 * _x_x_7)) == -16.0) || (((x_13 + (-1.0 * _x_x_7)) == -20.0) || (((x_10 + (-1.0 * _x_x_7)) == -15.0) || (((x_7 + (-1.0 * _x_x_7)) == -20.0) || (((x_6 + (-1.0 * _x_x_7)) == -3.0) || (((x_3 + (-1.0 * _x_x_7)) == -6.0) || ((x_4 + (-1.0 * _x_x_7)) == -11.0)))))))))) && ((((x_14 + (-1.0 * _x_x_8)) <= -6.0) && (((x_13 + (-1.0 * _x_x_8)) <= -13.0) && (((x_11 + (-1.0 * _x_x_8)) <= -10.0) && (((x_6 + (-1.0 * _x_x_8)) <= -3.0) && (((x_5 + (-1.0 * _x_x_8)) <= -20.0) && (((x_3 + (-1.0 * _x_x_8)) <= -9.0) && (((x_0 + (-1.0 * _x_x_8)) <= -16.0) && ((x_2 + (-1.0 * _x_x_8)) <= -4.0)))))))) && (((x_14 + (-1.0 * _x_x_8)) == -6.0) || (((x_13 + (-1.0 * _x_x_8)) == -13.0) || (((x_11 + (-1.0 * _x_x_8)) == -10.0) || (((x_6 + (-1.0 * _x_x_8)) == -3.0) || (((x_5 + (-1.0 * _x_x_8)) == -20.0) || (((x_3 + (-1.0 * _x_x_8)) == -9.0) || (((x_0 + (-1.0 * _x_x_8)) == -16.0) || ((x_2 + (-1.0 * _x_x_8)) == -4.0)))))))))) && ((((x_15 + (-1.0 * _x_x_9)) <= -13.0) && (((x_13 + (-1.0 * _x_x_9)) <= -19.0) && (((x_11 + (-1.0 * _x_x_9)) <= -17.0) && (((x_10 + (-1.0 * _x_x_9)) <= -20.0) && (((x_9 + (-1.0 * _x_x_9)) <= -11.0) && (((x_8 + (-1.0 * _x_x_9)) <= -6.0) && (((x_1 + (-1.0 * _x_x_9)) <= -11.0) && ((x_6 + (-1.0 * _x_x_9)) <= -7.0)))))))) && (((x_15 + (-1.0 * _x_x_9)) == -13.0) || (((x_13 + (-1.0 * _x_x_9)) == -19.0) || (((x_11 + (-1.0 * _x_x_9)) == -17.0) || (((x_10 + (-1.0 * _x_x_9)) == -20.0) || (((x_9 + (-1.0 * _x_x_9)) == -11.0) || (((x_8 + (-1.0 * _x_x_9)) == -6.0) || (((x_1 + (-1.0 * _x_x_9)) == -11.0) || ((x_6 + (-1.0 * _x_x_9)) == -7.0)))))))))) && ((((x_15 + (-1.0 * _x_x_10)) <= -12.0) && (((x_12 + (-1.0 * _x_x_10)) <= -10.0) && (((x_11 + (-1.0 * _x_x_10)) <= -13.0) && (((x_10 + (-1.0 * _x_x_10)) <= -12.0) && (((x_8 + (-1.0 * _x_x_10)) <= -7.0) && (((x_6 + (-1.0 * _x_x_10)) <= -16.0) && (((x_1 + (-1.0 * _x_x_10)) <= -6.0) && ((x_5 + (-1.0 * _x_x_10)) <= -3.0)))))))) && (((x_15 + (-1.0 * _x_x_10)) == -12.0) || (((x_12 + (-1.0 * _x_x_10)) == -10.0) || (((x_11 + (-1.0 * _x_x_10)) == -13.0) || (((x_10 + (-1.0 * _x_x_10)) == -12.0) || (((x_8 + (-1.0 * _x_x_10)) == -7.0) || (((x_6 + (-1.0 * _x_x_10)) == -16.0) || (((x_1 + (-1.0 * _x_x_10)) == -6.0) || ((x_5 + (-1.0 * _x_x_10)) == -3.0)))))))))) && ((((x_14 + (-1.0 * _x_x_11)) <= -7.0) && (((x_11 + (-1.0 * _x_x_11)) <= -11.0) && (((x_9 + (-1.0 * _x_x_11)) <= -12.0) && (((x_5 + (-1.0 * _x_x_11)) <= -11.0) && (((x_3 + (-1.0 * _x_x_11)) <= -17.0) && (((x_2 + (-1.0 * _x_x_11)) <= -2.0) && (((x_0 + (-1.0 * _x_x_11)) <= -1.0) && ((x_1 + (-1.0 * _x_x_11)) <= -10.0)))))))) && (((x_14 + (-1.0 * _x_x_11)) == -7.0) || (((x_11 + (-1.0 * _x_x_11)) == -11.0) || (((x_9 + (-1.0 * _x_x_11)) == -12.0) || (((x_5 + (-1.0 * _x_x_11)) == -11.0) || (((x_3 + (-1.0 * _x_x_11)) == -17.0) || (((x_2 + (-1.0 * _x_x_11)) == -2.0) || (((x_0 + (-1.0 * _x_x_11)) == -1.0) || ((x_1 + (-1.0 * _x_x_11)) == -10.0)))))))))) && ((((x_13 + (-1.0 * _x_x_12)) <= -10.0) && (((x_12 + (-1.0 * _x_x_12)) <= -10.0) && (((x_10 + (-1.0 * _x_x_12)) <= -17.0) && (((x_7 + (-1.0 * _x_x_12)) <= -1.0) && (((x_6 + (-1.0 * _x_x_12)) <= -5.0) && (((x_4 + (-1.0 * _x_x_12)) <= -17.0) && (((x_0 + (-1.0 * _x_x_12)) <= -8.0) && ((x_1 + (-1.0 * _x_x_12)) <= -20.0)))))))) && (((x_13 + (-1.0 * _x_x_12)) == -10.0) || (((x_12 + (-1.0 * _x_x_12)) == -10.0) || (((x_10 + (-1.0 * _x_x_12)) == -17.0) || (((x_7 + (-1.0 * _x_x_12)) == -1.0) || (((x_6 + (-1.0 * _x_x_12)) == -5.0) || (((x_4 + (-1.0 * _x_x_12)) == -17.0) || (((x_0 + (-1.0 * _x_x_12)) == -8.0) || ((x_1 + (-1.0 * _x_x_12)) == -20.0)))))))))) && ((((x_14 + (-1.0 * _x_x_13)) <= -8.0) && (((x_12 + (-1.0 * _x_x_13)) <= -3.0) && (((x_11 + (-1.0 * _x_x_13)) <= -14.0) && (((x_9 + (-1.0 * _x_x_13)) <= -13.0) && (((x_6 + (-1.0 * _x_x_13)) <= -9.0) && (((x_3 + (-1.0 * _x_x_13)) <= -2.0) && (((x_0 + (-1.0 * _x_x_13)) <= -5.0) && ((x_2 + (-1.0 * _x_x_13)) <= -15.0)))))))) && (((x_14 + (-1.0 * _x_x_13)) == -8.0) || (((x_12 + (-1.0 * _x_x_13)) == -3.0) || (((x_11 + (-1.0 * _x_x_13)) == -14.0) || (((x_9 + (-1.0 * _x_x_13)) == -13.0) || (((x_6 + (-1.0 * _x_x_13)) == -9.0) || (((x_3 + (-1.0 * _x_x_13)) == -2.0) || (((x_0 + (-1.0 * _x_x_13)) == -5.0) || ((x_2 + (-1.0 * _x_x_13)) == -15.0)))))))))) && ((((x_13 + (-1.0 * _x_x_14)) <= -3.0) && (((x_12 + (-1.0 * _x_x_14)) <= -8.0) && (((x_10 + (-1.0 * _x_x_14)) <= -8.0) && (((x_9 + (-1.0 * _x_x_14)) <= -8.0) && (((x_8 + (-1.0 * _x_x_14)) <= -10.0) && (((x_7 + (-1.0 * _x_x_14)) <= -9.0) && (((x_4 + (-1.0 * _x_x_14)) <= -2.0) && ((x_5 + (-1.0 * _x_x_14)) <= -15.0)))))))) && (((x_13 + (-1.0 * _x_x_14)) == -3.0) || (((x_12 + (-1.0 * _x_x_14)) == -8.0) || (((x_10 + (-1.0 * _x_x_14)) == -8.0) || (((x_9 + (-1.0 * _x_x_14)) == -8.0) || (((x_8 + (-1.0 * _x_x_14)) == -10.0) || (((x_7 + (-1.0 * _x_x_14)) == -9.0) || (((x_4 + (-1.0 * _x_x_14)) == -2.0) || ((x_5 + (-1.0 * _x_x_14)) == -15.0)))))))))) && ((((x_10 + (-1.0 * _x_x_15)) <= -15.0) && (((x_7 + (-1.0 * _x_x_15)) <= -2.0) && (((x_6 + (-1.0 * _x_x_15)) <= -14.0) && (((x_5 + (-1.0 * _x_x_15)) <= -17.0) && (((x_4 + (-1.0 * _x_x_15)) <= -13.0) && (((x_3 + (-1.0 * _x_x_15)) <= -7.0) && (((x_0 + (-1.0 * _x_x_15)) <= -7.0) && ((x_2 + (-1.0 * _x_x_15)) <= -8.0)))))))) && (((x_10 + (-1.0 * _x_x_15)) == -15.0) || (((x_7 + (-1.0 * _x_x_15)) == -2.0) || (((x_6 + (-1.0 * _x_x_15)) == -14.0) || (((x_5 + (-1.0 * _x_x_15)) == -17.0) || (((x_4 + (-1.0 * _x_x_15)) == -13.0) || (((x_3 + (-1.0 * _x_x_15)) == -7.0) || (((x_0 + (-1.0 * _x_x_15)) == -7.0) || ((x_2 + (-1.0 * _x_x_15)) == -8.0)))))))))) && ((((_EL_U_858 == (_x__EL_U_858 || ( !((_x__EL_U_854 && ( !((_x_x_0 + (-1.0 * _x_x_13)) <= -4.0))) || ( !_x__EL_X_852))))) && ((_EL_X_852 == (_x_x_13 <= _x_x_4)) && (_EL_U_854 == ((_x__EL_U_854 && ( !((_x_x_0 + (-1.0 * _x_x_13)) <= -4.0))) || ( !_x__EL_X_852))))) && (_x__J881 == (( !(_J881 && _J887)) && ((_J881 && _J887) || ((( !_EL_X_852) || ( !(( !_EL_X_852) || (( !((x_0 + (-1.0 * x_13)) <= -4.0)) && _EL_U_854)))) || _J881))))) && (_x__J887 == (( !(_J881 && _J887)) && ((_J881 && _J887) || ((( !(( !_EL_X_852) || (( !((x_0 + (-1.0 * x_13)) <= -4.0)) && _EL_U_854))) || ( !(_EL_U_858 || ( !(( !_EL_X_852) || (( !((x_0 + (-1.0 * x_13)) <= -4.0)) && _EL_U_854)))))) || _J887)))))); _J887 = _x__J887; _J881 = _x__J881; _EL_U_854 = _x__EL_U_854; x_13 = _x_x_13; x_0 = _x_x_0; _EL_X_852 = _x__EL_X_852; _EL_U_858 = _x__EL_U_858; x_11 = _x_x_11; x_2 = _x_x_2; x_14 = _x_x_14; x_3 = _x_x_3; x_15 = _x_x_15; x_4 = _x_x_4; x_5 = _x_x_5; x_6 = _x_x_6; x_1 = _x_x_1; x_7 = _x_x_7; x_10 = _x_x_10; x_8 = _x_x_8; x_9 = _x_x_9; x_12 = _x_x_12; } }
the_stack_data/198580155.c
// Ввести три целых числа. Вычислить и вывести произведение первого и второго числа #include <stdio.h> void main() { int a, b, c; scanf("%d %d %d", &a, &b, &c); printf("%d", a * b); }
the_stack_data/15763832.c
#include <sys/wait.h> #include <stdio.h> #include <unistd.h> /** * A simple forking example. Forks and both child and * parent print out different messages. */ int main(int argc, char *argv[]) { pid_t PID = 0; // Create the child. PID = fork(); // Not the child or parent if (PID == -1) { return 0; } //Is it a child process or the parent? if (PID == 0) { //Child process: printf("Child Says Hi!\n"); //Finish on success return 0; } else { //Parent process: printf("Parent Says Hello\n"); } return 0; }
the_stack_data/23512.c
#include<stdio.h> int main() { int n = 10; fac_recursion(n); printf("fac_recursion : %d", fac_recursion(n)); return 0; } int fac_recursion(int n) { if (n == 1) return 1; else return n * fac_recursion(n - 1); }
the_stack_data/1192172.c
/** ****************************************************************************** * @file stm32f0xx_hal_timebase_TIM.c * @brief HAL time base based on the hardware TIM. ****************************************************************************** * * Copyright (c) 2017 STMicroelectronics International N.V. * 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. Redistribution 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 other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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. * ****************************************************************************** * modify: [email protected] 2017.5.4 */ #if defined(STM32F0) /* Includes ------------------------------------------------------------------*/ #include <Arduino.h> /** @addtogroup HAL_TimeBase * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ TIM_HandleTypeDef htim17; uint32_t uwIncrementState = 0; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief This function configures the TIM17 as a time base source. * The time source is configured to have 1ms time base with a dedicated * Tick interrupt priority. * @note This function is called automatically at the beginning of program after * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). * @param TickPriority: Tick interrupt priorty. * @retval HAL status */ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { RCC_ClkInitTypeDef clkconfig; uint32_t uwTimclock = 0; uint32_t uwPrescalerValue = 0; uint32_t pFLatency; /*Configure the TIM17 IRQ priority */ HAL_NVIC_SetPriority(TIM17_IRQn, TickPriority ,0); /* Enable the TIM17 global Interrupt */ HAL_NVIC_EnableIRQ(TIM17_IRQn); /* Enable TIM17 clock */ __HAL_RCC_TIM17_CLK_ENABLE(); /* Get clock configuration */ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); /* Compute TIM17 clock */ uwTimclock = HAL_RCC_GetPCLK1Freq(); /* Compute the prescaler value to have TIM17 counter clock equal to 1MHz */ uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1); /* Initialize TIM17 */ htim17.Instance = TIM17; /* Initialize TIMx peripheral as follow: + Period = [(TIM17CLK/1000) - 1]. to have a (1/1000) s time base. + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + ClockDivision = 0 + Counter direction = Up */ htim17.Init.Period = (1000000 / 1000) - 1; htim17.Init.Prescaler = uwPrescalerValue; htim17.Init.ClockDivision = 0; htim17.Init.CounterMode = TIM_COUNTERMODE_UP; if(HAL_TIM_Base_Init(&htim17) == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ return HAL_TIM_Base_Start_IT(&htim17); } /* Return function status */ return HAL_ERROR; } /** * @brief Suspend Tick increment. * @note Disable the tick increment by disabling TIM17 update interrupt. * @param None * @retval None */ void HAL_SuspendTick(void) { /* Disable TIM17 update Interrupt */ __HAL_TIM_DISABLE_IT(&htim17, TIM_IT_UPDATE); } /** * @brief Resume Tick increment. * @note Enable the tick increment by Enabling TIM17 update interrupt. * @param None * @retval None */ void HAL_ResumeTick(void) { /* Enable TIM17 Update interrupt */ __HAL_TIM_ENABLE_IT(&htim17, TIM_IT_UPDATE); } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM17) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } #elif defined(STM32L0) #include <Arduino.h> TIM_HandleTypeDef htim6; uint32_t uwIncrementState = 0; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief This function configures the TIM17 as a time base source. * The time source is configured to have 1ms time base with a dedicated * Tick interrupt priority. * @note This function is called automatically at the beginning of program after * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). * @param TickPriority: Tick interrupt priorty. * @retval HAL status */ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { RCC_ClkInitTypeDef clkconfig; uint32_t uwTimclock = 0; uint32_t uwPrescalerValue = 0; uint32_t pFLatency; /*Configure the TIM17 IRQ priority */ HAL_NVIC_SetPriority(TIM6_IRQn, TickPriority ,0); /* Enable the TIM17 global Interrupt */ HAL_NVIC_EnableIRQ(TIM6_IRQn); /* Enable TIM17 clock */ __HAL_RCC_TIM6_CLK_ENABLE(); /* Get clock configuration */ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); /* Compute TIM17 clock */ uwTimclock = HAL_RCC_GetPCLK1Freq(); /* Compute the prescaler value to have TIM17 counter clock equal to 1MHz */ uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1); /* Initialize TIM17 */ htim6.Instance = TIM6; /* Initialize TIMx peripheral as follow: + Period = [(TIM17CLK/1000) - 1]. to have a (1/1000) s time base. + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + ClockDivision = 0 + Counter direction = Up */ htim6.Init.Period = (1000000 / 1000) - 1; htim6.Init.Prescaler = uwPrescalerValue; htim6.Init.ClockDivision = 0; htim6.Init.CounterMode = TIM_COUNTERMODE_UP; if(HAL_TIM_Base_Init(&htim6) == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ return HAL_TIM_Base_Start_IT(&htim6); } /* Return function status */ return HAL_ERROR; } /** * @brief Suspend Tick increment. * @note Disable the tick increment by disabling TIM17 update interrupt. * @param None * @retval None */ void HAL_SuspendTick(void) { /* Disable TIM17 update Interrupt */ __HAL_TIM_DISABLE_IT(&htim6, TIM_IT_UPDATE); } /** * @brief Resume Tick increment. * @note Enable the tick increment by Enabling TIM17 update interrupt. * @param None * @retval None */ void HAL_ResumeTick(void) { /* Enable TIM17 Update interrupt */ __HAL_TIM_ENABLE_IT(&htim6, TIM_IT_UPDATE); } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM6) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ #endif
the_stack_data/92328349.c
// // main.c // PrimDemo // // Created by SK on 2020/5/8. // Copyright © 2020 SK_Wang. All rights reserved. // #include <stdio.h> #include <stdlib.h> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXEDGE 20 #define MAXVEX 20 #define INFINITYC 65535 typedef int Status; typedef struct MGraph { int arc[MAXVEX][MAXVEX]; int numVertexes, numEdges; } MGraph; void CreateMGraph(MGraph *G) { int i, j; G->numEdges=15; G->numVertexes=9; for (i = 0; i < G->numVertexes; i++) { for (j = 0; j < G->numVertexes; j++) { if (i == j) G->arc[i][j] = 0; else G->arc[i][j] = G->arc[j][i] = INFINITYC; } } G->arc[0][1] = 10; G->arc[0][5] = 11; G->arc[1][2] = 18; G->arc[1][8] = 12; G->arc[1][6] = 16; G->arc[2][8] = 8; G->arc[2][3] = 22; G->arc[3][8] = 21; G->arc[3][6] = 24; G->arc[3][7] = 16; G->arc[3][4] = 20; G->arc[4][7] =7 ; G->arc[4][5] = 26; G->arc[5][6] = 17; G->arc[6][7] = 19; for(i = 0; i < G->numVertexes; i++) { for(j = i; j < G->numVertexes; j++) { G->arc[j][i] = G->arc[i][j]; } } } /* Prim算法生成最小生成树 */ void MiniSpanTree_Prim(MGraph G) { int min, i, j, k; int sum = 0; int adjvex[MAXVEX]; int lowcost[MAXVEX]; lowcost[0] = 0; adjvex[0] = 0; for (i = 1; i < G.numVertexes; i++) { lowcost[i] = G.arc[0][i]; adjvex[i] = 0; } for (i = 1; i < G.numVertexes; i++) { min = INFINITYC; j = 1; k = 0; for (j = 1; j < G.numVertexes; j++) { if (lowcost[j] != 0 && lowcost[j] < min) { min = lowcost[j]; k = j; } } printf("(V%d, V%d) = %d\n", adjvex[k], k , G.arc[adjvex[k]][k]); sum += G.arc[adjvex[k]][k]; lowcost[k] = 0; for (j = 1; j < G.numVertexes; j++) { if (lowcost[j] != 0 && G.arc[k][j] < lowcost[j]) { lowcost[j] = G.arc[k][j]; adjvex[j] = k; } } } printf("sum = %d\n", sum); } int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); MGraph G; CreateMGraph(&G); MiniSpanTree_Prim(G); return 0; }
the_stack_data/104828859.c
// A, B, func are in an SCC // C is called indirectly from A/B // The indirect call site in C is resolved, once we process the SCC // But since, we never process the SCC graph again, // we never inline func into the SCC graph(of A, B, and func) at that // call site. // when we inline the SCCGraph into D(due to call to A), the unresolved // call site is also inlined. As it is complete and can be resolved // we inline the SCC graph again, pulling in the unresolved call site // again. This causes an infinte looping in BU. //RUN: clang %s -c -emit-llvm -o - | \ //RUN: dsaopt -dsa-bu -dsa-td -disable-output typedef int* (*funcptr)(int *); static int* A(void); static int* func(int * arg) { A(); return arg; } static int* C(funcptr f, int *arg) { (*f)(arg); } static int *B() { func(A()); return C(func, A()); } static int* A() { return func(B()); } static int* D() { return A(); }
the_stack_data/142969.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): PRABAKARAN B. S., MRAZEK V., VASICEK Z., SEKANINA L., SHAFIQUE M. ApproxFPGAs: Embracing ASIC-based Approximate Arithmetic Components for FPGA-Based Systems. DAC 2020. ***/ // MAE% = 4.16 % // MAE = 2728 // WCE% = 15.19 % // WCE = 9953 // WCRE% = 100.00 % // EP% = 99.20 % // MRE% = 41.93 % // MSE = 11489.87e3 // FPGA_POWER = 0.28 // FPGA_DELAY = 6.2 // FPGA_LUT = 5.0 #include <stdint.h> #include <stdlib.h> uint64_t mul8u_L42(const uint64_t B,const uint64_t A) { uint64_t O, dout_117, dout_207, dout_253, dout_285, dout_286, dout_288, dout_289, dout_296, dout_297, dout_298, dout_326, dout_327, dout_328, dout_329, dout_330, dout_331, dout_333, dout_334, dout_335; int avg=0; dout_117=((B >> 6)&1)&((A >> 6)&1); dout_207=((B >> 7)&1)&((A >> 5)&1); dout_253=((B >> 7)&1)&((A >> 6)&1); dout_285=dout_253&((A >> 5)&1); dout_286=dout_207|dout_253; dout_288=((A >> 7)&1)&dout_285; dout_289=dout_286^dout_285; dout_296=((B >> 5)&1)&((A >> 7)&1); dout_297=((B >> 6)&1)&((A >> 7)&1); dout_298=((B >> 7)&1)&((A >> 7)&1); dout_326=dout_289^dout_297; dout_327=dout_289&dout_297; dout_328=dout_326&dout_296; dout_329=dout_326^dout_296; dout_330=dout_327|dout_328; dout_331=dout_285^dout_298; dout_333=((B >> 7)&1)&dout_330; dout_334=dout_331^dout_330; dout_335=dout_288|dout_333; O = 0; O |= (0&1) << 0; O |= (0&1) << 1; O |= (0&1) << 2; O |= (0&1) << 3; O |= (0&1) << 4; O |= (0&1) << 5; O |= (0&1) << 6; O |= (0&1) << 7; O |= (0&1) << 8; O |= (dout_117&1) << 9; O |= (dout_298&1) << 10; O |= (dout_117&1) << 11; O |= (dout_117&1) << 12; O |= (dout_329&1) << 13; O |= (dout_334&1) << 14; O |= (dout_335&1) << 15; return O; }
the_stack_data/73575195.c
#include <stdio.h> #include <stdlib.h> // Initialising the Linked list struct Node { int data; struct Node *next; }; // Traversing through linked list void LinkedListTraverse(struct Node *ptr) { while (ptr != NULL) { printf("%d \n", ptr->data); ptr = ptr->next; } printf("\n"); } // Insertion in linked list // There are 4 cases possible for insretion // 1. Insert at begining // 2. Insert in between // 3. Insert at the end // 4. Insert after the Node // Case1 - Insert at beginning struct Node *insertatfirst(struct Node *head, int data) { struct Node *ptr = (struct Node *)malloc(sizeof(struct Node)); ptr->next = head; ptr->data = data; head = ptr; return head; } // Case2 - Insert in between struct Node *insertatindex(struct Node *head, int data, int index) { struct Node *ptr = (struct Node *)malloc(sizeof(struct Node)); //Won't work for index = 0 struct Node *p = head; int i = 0; while (i != index - 1) { p = p->next; i++; } ptr->data = data; ptr->next = p->next; p->next = ptr; return head; } // Case3 - Insert at the end struct Node *insertatend(struct Node *head, int data) { struct Node *ptr = (struct Node *)malloc(sizeof(struct Node)); struct Node *p = head; while (p->next != NULL) { p = p->next; } ptr->data = data; p->next = ptr; ptr->next = NULL; return head; } // Case4 - Insert after a node struct Node *insertafternode(struct Node *head, struct Node *prevNode, int data) { struct Node *ptr = (struct Node *)malloc(sizeof(struct Node)); ptr->data = data; ptr->next = prevNode->next; prevNode->next = ptr; return head; } // Deletion in a linked List // Just like Insertion here also 4 cases are possible // 1. Deleting the first node // 2. Deleting the node at the index // 3. Deleting the Last Node // 4. Deleting the first node with a given index //Case1 - Deleting the first node struct Node *Deleteatfirst(struct Node *head) { struct Node *p = head; head = head->next; free(p); return head; } //Case2 - Deleting the note at the index struct Node *Deleteatindex(struct Node *head, int index) { struct Node *p = head; int i = 0; while (i != index - 1) { p = p->next; i++; } struct Node *q = p->next; p->next = q->next; free(q); return head; } //Case3 - Deleting the last node struct Node *Deleteatlast(struct Node *head) { struct Node *p = head; struct Node *q = head->next; while (q->next != NULL) { p = p->next; q = q->next; } p->next = q->next; free(q); return head; } //Case4 - Deleting the first node of a given value struct Node *Deleteaftervalue(struct Node *head, struct Node *prevNode){ struct Node *p = prevNode; struct Node *q = prevNode->next; p->next = q->next; free(q); return head; } int main() { struct Node *head; struct Node *first; struct Node *second; struct Node *third; struct Node *fourth; head = (struct Node *)malloc(sizeof(struct Node)); first = (struct Node *)malloc(sizeof(struct Node)); second = (struct Node *)malloc(sizeof(struct Node)); third = (struct Node *)malloc(sizeof(struct Node)); fourth = (struct Node *)malloc(sizeof(struct Node)); head->data = 10; head->next = first; first->data = 23; first->next = second; second->data = 12; second->next = third; third->data = 1; third->next = fourth; fourth->data = 23; fourth->next = NULL; LinkedListTraverse(head); // Insertion in a linked list head = insertatfirst(head, 56); //Case1 LinkedListTraverse(head); head = insertatindex(head, 39, 3); //Case2 LinkedListTraverse(head); head = insertatend(head, 92); //Case3 LinkedListTraverse(head); head = insertafternode(head, second, 37); //Case4 LinkedListTraverse(head); // Deletion in a linked list head = Deleteatfirst(head); //Case1 LinkedListTraverse(head); head = Deleteatindex(head, 4); //Case2 LinkedListTraverse(head); head = Deleteatlast(head); //Case3 LinkedListTraverse(head); head = Deleteaftervalue(head, third); //Case4 LinkedListTraverse(head); return 0; }
the_stack_data/51701401.c
/* XPM */ static const char *const xpm_icon_0[] = { /* columns rows colors chars-per-pixel */ "16 16 80 1", " c #555452", ". c #60605D", "X c #686764", "o c #7A7876", "O c #9A9895", "+ c #A09E9B", "@ c #A09F9B", "# c #A2A19D", "$ c #A6A5A1", "% c #A9A8A4", "& c #ABA9A5", "* c #ADACA8", "= c #B2B0AC", "- c #B9B7B3", "; c #BEBCB7", ": c #BFBDB9", "> c #C2C0BB", ", c #C7C5C1", "< c #C7C6C1", "1 c #C8C6C1", "2 c #C8C6C2", "3 c #C9C7C2", "4 c #CAC8C3", "5 c #CAC8C4", "6 c #CAC9C4", "7 c #CBC9C4", "8 c #CBC9C5", "9 c #CBCAC5", "0 c #CCCAC5", "q c #CCCBC6", "w c #CDCBC6", "e c #CDCBC7", "r c #CECCC7", "t c #CECDC8", "y c #CFCDC8", "u c #CFCEC9", "i c #D0CEC9", "p c #D0CECA", "a c #D0CFCA", "s c #D1CFCA", "d c #D1D0CB", "f c #D2D0CB", "g c #D2D0CC", "h c #D3D1CC", "j c #D4D2CD", "k c #D5D2CD", "l c #D4D3CE", "z c #D5D3CE", "x c #D5D3CF", "c c #D6D3CE", "v c #D6D3CF", "b c #D6D4CE", "n c #D6D4CF", "m c #D6D5D0", "M c #D7D5D0", "N c #D7D6D0", "B c #D8D6D1", "V c #D9D7D2", "C c #D9D8D3", "Z c #DAD8D3", "A c #DBD9D3", "S c #DAD8D4", "D c #DBD9D4", "F c #DBDAD4", "G c #DCDAD4", "H c #DCDAD5", "J c #DDDBD5", "K c #DDDBD6", "L c #DEDCD7", "P c #DFDCD7", "I c #DFDDD7", "U c #DFDDD8", "Y c #E0DED8", "T c #E0DED9", "R c #E0DFD9", "E c #E1DFD9", "W c #E2E0DA", "Q c #E2E0DB", "! c #E4E2DD", "~ c #E7E5DF", /* pixels */ "jiyryy0yyyyyyyyg", "j77ii7gy7dy777gB", "i7BQBM=,ZbCRCjUC", "g2UHiZo*HiCMBSRC", "d4Wgbj#7MjHjHjRD", "igUidjUMiBBs%2RB", "ijBjjiijjZjjX$~B", "d0bHBbb0BjMi&2RZ", "syjO>BjyHiijHjYB", "i5M.+R0jMBMjffjH", "s7B>sMrBjHMBB0jH", "i5jBMyMBr+ijB0HA", "s,idjsHS; :Hy0YB", "s5jy0Bjss-0j2iPB", "iMRURBSPR!RHBRWB", "jBBBBBBMBMBBBBBb" }; /* XPM */ static const char *const xpm_icon_1[] = { /* columns rows colors chars-per-pixel */ "32 32 182 2", " c #2C2C2B", ". c #353433", "X c #3C3C3A", "o c #454443", "O c #535250", "+ c #595856", "@ c #5C5B59", "# c #656461", "$ c #656462", "% c #676663", "& c #676664", "* c #686765", "= c #696865", "- c #6B6A68", "; c #6C6B68", ": c #6C6B69", "> c #6D6C6A", ", c #6F6E6B", "< c #72716F", "1 c #767572", "2 c #7B7A77", "3 c #7D7C79", "4 c #7F7E7B", "5 c #81807D", "6 c #868481", "7 c #868582", "8 c #878683", "9 c #888784", "0 c #8D8B88", "q c #92908D", "w c #989793", "e c #999794", "r c #9A9995", "t c #9B9A96", "y c #A5A39F", "u c #A8A7A3", "i c #ADABA7", "p c #B0AEAA", "a c #B3B1AD", "s c #B4B2AE", "d c #B5B4AF", "f c #B7B5B1", "g c #B8B7B2", "h c #BAB9B4", "j c #BAB9B5", "k c #BBB9B5", "l c #BBBAB5", "z c #BBBAB6", "x c #BCBAB6", "c c #BDBCB7", "v c #BEBCB8", "b c #BEBDB8", "n c #BEBDB9", "m c #BFBDB9", "M c #BFBEB9", "N c #C0BEBA", "B c #C0BFBA", "V c #C1BFBB", "C c #C1C0BB", "Z c #C2C0BB", "A c #C2C0BC", "S c #C2C1BC", "D c #C3C1BD", "F c #C3C2BD", "G c #C4C2BE", "H c #C4C3BE", "J c #C5C3BE", "K c #C5C3BF", "L c #C5C4BF", "P c #C6C4C0", "I c #C6C5C0", "U c #C7C5C0", "Y c #C7C5C1", "T c #C7C6C1", "R c #C8C6C2", "E c #C8C7C2", "W c #C9C7C2", "Q c #C9C7C3", "! c #C9C8C3", "~ c #CAC8C3", "^ c #CAC8C4", "/ c #CAC9C4", "( c #CBC9C4", ") c #CBC9C5", "_ c #CBCAC5", "` c #CCCAC5", "' c #CCCBC5", "] c #CCCAC6", "[ c #CCCBC6", "{ c #CDCBC6", "} c #CDCBC7", "| c #CDCCC7", " . c #CECCC7", ".. c #CECCC8", "X. c #CECDC8", "o. c #CFCDC8", "O. c #CFCEC9", "+. c #D0CEC9", "@. c #D0CECA", "#. c #D1CFCA", "$. c #D1CFCB", "%. c #D1D0CB", "&. c #D2D0CA", "*. c #D2D0CB", "=. c #D2D0CC", "-. c #D2D1CC", ";. c #D3D1CC", ":. c #D3D1CD", ">. c #D3D2CD", ",. c #D4D1CC", "<. c #D4D2CD", "1. c #D5D2CD", "2. c #D5D3CD", "3. c #D5D3CE", "4. c #D6D3CE", "5. c #D5D4CF", "6. c #D6D4CE", "7. c #D6D4CF", "8. c #D7D5CF", "9. c #D7D4D0", "0. c #D7D5D0", "q. c #D7D5D1", "w. c #D8D5D0", "e. c #D8D6D0", "r. c #D8D6D1", "t. c #D9D7D2", "y. c #D9D8D2", "u. c #D9D8D3", "i. c #DAD8D2", "p. c #DAD8D3", "a. c #DBD9D3", "s. c #DBD8D4", "d. c #DAD9D4", "f. c #DBD9D4", "g. c #DBDAD4", "h. c #DBDAD5", "j. c #DCD9D4", "k. c #DCDAD4", "l. c #DCDAD5", "z. c #DDDAD5", "x. c #DDDBD5", "c. c #DDDBD6", "v. c #DDDBD7", "b. c #DEDBD6", "n. c #DDDCD7", "m. c #DEDCD6", "M. c #DEDCD7", "N. c #DFDDD7", "B. c #DEDDD8", "V. c #DFDDD8", "C. c #E0DED9", "Z. c #E1DED9", "A. c #E1DFD9", "S. c #E1DFDA", "D. c #E2E0DA", "F. c #E2E0DB", "G. c #E3E0DB", "H. c #E3E1DB", "J. c #E4E1DC", "K. c #E4E2DD", "L. c #E4E3DD", "P. c #E5E3DE", "I. c #E5E4DE", "U. c #E6E4DF", "Y. c #E6E5DF", "T. c #E7E5DF", "R. c #E7E5E0", "E. c #E8E6E0", "W. c #E8E6E1", "Q. c #E8E7E1", "!. c #E9E7E1", "~. c #E9E7E2", "^. c #EAE8E2", "/. c #EAE8E3", "(. c #EBE9E3", "). c #EAE9E4", "_. c #EBE9E4", "`. c #ECEAE4", "'. c #ECEAE5", "]. c #EDEAE5", "[. c #EDEBE6", "{. c #EEECE6", /* pixels */ "<.<.e.7.7.7.7.7.0.7.7.7.7.7.7.7.7.7.0.0.<.e.<.e.9.<.0.9.9.0.7.-.", "<.<.] ] ] . . .] } ] .O.] ] . .] ] ] O.] } } } } } } _ ] <.7.", "<.7.] m B B m H ^ m N V m N C C m C ~ L N N V C N N N V m ] e.<.", "<.0.T 7.7.0.7.(.S.<.e.e.7.7.7.7.0.0.a.D.S.k.<.<.e.e.e.e.7.).z.-.", "<.<.l <.7.%.a.R.#.<.<.<.f.z.e.%.<.<.-.<.<.<.P.e.%.<.<.<.#.T.k.,.", "7.<.c <.7.%.(.k.-.0.<.e.6 + p z.-.<.<.0._ S.P.M.S.a.<.-.%.Q.z.%.", "<.<.c <.%.z.(.#.<.<.<.$.e.7 1 P.-.<.7.<.] Q.#.<.e.S.S.a.%.T.z.%.", "7.<.c <.%.`.k.%.<.<.<.z.t o N e.-.<.e.^ S.C.$.<.<.%.7.C.m.`.k.<.", "<.<.N #.V.].%.<.<.<.<.z.- O u k.<.<.$.] `.$.<.<.<.<.<.<.<.].z.%.", "7.<.N #.Q.7.<.7.<.<.7.%.S.S.9.<.<.e.E S.C.-.<.<.#.<.<.<.#.Q.z.<.", "<.<.l e.]. .E #.7.<.<.<.-.-.<.7.<.<._ Q.#.<.<.9.S.z.a.-.#.Q.a.-.", "7.<.k ].S.f.f. .~ #.7.7.<.<.<.<.<.E z.S.#.<.e.] 3 < s z.#.Q.k.<.", "<.<.K ].-.-.7.z.a.] _ %.7.<.-.<.<.E /.$.<.<.<.<.9 0 S.} R.z.#.", "<.#.T z.<.<.<.-.7.z.7._ ( <.0.e.K z.S.$.9.<.<.-.D - 4 P.#.Q.z.<.", "7.<.l <.<.<.<.<.<.<.0.z.<._ ] O.E ].#.<.<.<.e.E - * f s.#.Q.k.#.", "<.<.K <.7.<.<.z.<.<.<.-.e.a.7.C z.z.<.<.<.<.<.e.e.e.e.<.#.Q.z.<.", "<.0.#.-.<.e.#.f a.<.<.7.<.<.<.D Q.] _ #.<.<.<.<.<.<.<.<.-.Q.z.<.", "<.<.k <.<.<.- # t z.<.<.<.e.D -.S.m.a.O._ -.0.<.<.<.<.0.$.Q.z.<.", "7.<.v <.0.#.# 2 + S.#.<.<.-.V P.#.<.e.V.f.O.] $.0.<.<.<.O.S.z.#.", "<.<.m <.-.z.w . 4 S.-.<.e.D e.z.-.<.<.-.e.V.f.#.} -.7.e.P e.V.#.", "7.<.m -.<.f.s t 0.<.<.0.#.K P.%.<.9.<.<.<.<.e.M.e.#. .<.k R.z.-.", "<.<.c <.<.<.f.S.<.<.<.e.V f.f.-.<.<.<.e.<.<.<.<.e.z.s.E P ).z.-.", "7.<.m <.<.<.<.-.<.<.9.O.T R.-.<.<.e.<.E <.<.<.0.<.<.<.K #.Q.f.-.", "<.<.k #.0.<.<.<.<.<.e.V z.z.<.<.7.#.* = $.0.<.<.<.e.E ^ <.Q.k.<.", "7.-.l E ] ,.7.<.<.7. .~ Q.#.7.-.z.u X , g a.<.<.<.-.V 9.$.Q.z.$.", "7.<.m <.#.E .<.7.e.C D.z.-.<.<.z.i = * q D.%.<.0.P _ e.#.Q.z.<.", "<.<.c <.7.7.O.~ .] ] (.#.<.7.<.<.f.e 8 <.<.<.<.$.N <.<.#.Q.k.%.", "7.<.c <.-.<.<.7.#.T P.9.<.<.<.<.<.-.m.P.<.<.<.7.K E e.<.#.Q.z.<.", "<.-.k <.7.<.7.<.<.e.<.T ] <.<.0.<.<.<.-.<.7.7.#.m 7.<.7.<.Q.z.<.", "<.<.m.{.(.(.).].`.`.].).U.Q.].P.].].].).(.].).Q.T.].`.].Q._.k.$.", "<.0.<.e.7.<.<.7.7.<.<.7.7.<.7.<.0.<.<.<.7.<.<.7.7.7.<.7.<.<.<.<.", "<.-.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.9.<.<.<." }; /* XPM */ static const char *const xpm_icon_2[] = { /* columns rows colors chars-per-pixel */ "48 48 62 1", " c #020202", ". c #1E1E1D", "X c #292827", "o c #2C2C2B", "O c #343332", "+ c #3E3E3C", "@ c #444342", "# c #494847", "$ c #4D4D4B", "% c #555452", "& c #585755", "* c #5A5957", "= c #5E5D5A", "- c #605F5C", "; c #62615E", ": c #646361", "> c #696866", ", c #6E6D6A", "< c #73726F", "1 c #757471", "2 c #787774", "3 c #7A7976", "4 c #7D7C79", "5 c #82817E", "6 c #868582", "7 c #8F8E8B", "8 c #918F8C", "9 c #969491", "0 c #989693", "q c #9A9995", "w c #9E9D99", "e c #A09F9B", "r c #A3A29E", "t c #A7A6A2", "y c #ABA9A5", "u c #B4B3AE", "i c #B6B4B0", "p c #B8B7B3", "a c #BBB9B5", "s c #BEBDB9", "d c #C0BFBA", "f c #C4C3BE", "g c #C6C5C0", "h c #C8C7C2", "j c #CBC9C5", "k c #CFCDC8", "l c #D1CFCA", "z c #D5D3CE", "x c #D7D5D0", "c c #D8D6D1", "v c #DCDAD5", "b c #DFDDD8", "n c #E1DED9", "m c #E5E3DD", "M c #E7E5E0", "N c #E9E7E1", "B c #ECEAE4", "V c #EFEEE8", "C c #F0EEE8", "Z c #F3F1EC", "A c #F6F5F0", "S c #F9F7F1", /* pixels */ "zzzxzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzxzz", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "zzzzzzxzczzczzczczzczcczzzczczczzczczzczzcczzzzz", "zzzzjkklkkkkkkkkkkkkkkkkkkkjkkkkkkkkkkkkklzfzzzz", "zzzzgpuipuiuapupuiiiiiiiiupapuiiiiiiiiiiiiufczxz", "zzzvnlczzzczZbzzzczzczzzczcnmnczzcxzzzxzzczZclzz", "zzzzuhczzzkmNzzzzzzzlzzzzzzzznmvzlzzzzzzzzzZvzzz", "zzzcpjzzzzzZczzzzzznmzzzzzzzzzcjvmzzzzzzzzlZczzz", "zzzcpjxzzlmBzzzzzzl08lxxzzzzzzlfZmmnzzzzzzlZczzz", "zzzcijxzzzZczzzzlbw#@%vlzzzzzchbBkcnmnclzzzZczzc", "zzzcpjzzzmBzzzzzzzlCiOczzzzzzzfZczzzznmnclzZvzzz", "zzzxpjzzzZczzzzzxlnpOtbzzzzzcfbBlzzzzlznmmzZclzz", "zzzcpjvzNBlzzzzclvy #exlxllxlfCczzzzzzzzzvmZczzz", "zzzcijzzZvzzzzzzlby::<czzxzcfvBlzzzzzzzzlzzZczzz", "zzzcpjzBBzzzzzzzzzvMMmzzzzxldAxzzzzzzzzzzzzZczzz", "zxzcpjcBjfzzzzzzzzllllzzxlxdvBlzzzzzllzzzzlZvzzz", "xzzcpgMZblfjzxzzzzzzzzzzzzlsZxxzzzznmmvzzzzZvzzz", "zzzcpjSbznbjfjzxzzzzzzxzzcsbBlxlzzce-;rczzzZclzz", "zzzxivZlzzcnvjfjzzzzzzzzzlsZxzxzzlv5<-OczzlZvzzz", "zzzciBblzzzzcnvhflzxzzzzcavBkxlzzzzn-.&nzzlZczzc", "xzzxpvxzzzzzzzcnchfkzzzzkaAxzxxzzzzkmpozzzzZczzz", "zzzxpjxzzzzzzzzlcnchflxcacBlxlzzzln>#+;vzzlZclzz", "zzzxuhxzzzzxxzzzzzcbzhhjaAxzxxzxzzcf0rczzzzZvzzz", "zzzzdlzzzzzllzzzzzzzvvzabMlxllzzzzzcmnzzzzlZczzz", "zzlcnlxzzlbMnzzzzxzzlxzpVjgjxxlxzzzzlzzzzzzZczzz", "zzzcihxzzvw@4czzzlxxxcijVMvggjxxzzzzzzzzzzzZczzx", "zzzxpjxlvsOy*7nlxlxlxjiBlxbMvhgjczzzzzzzzzcZvzzz", "zxzxpjxlcsoe$:MlzxzxcixMlxlxbMvgfkxzzzxzzcfBvlzz", "xxxcpjxxlv0:X4mlxzlxjpVzzxlxxzbMcffzzzzzzvdmvzzx", "lxlcphxzzv3$$fxzzzzcicMkxlxlxlllnmnjfzzczfiZclzz", "xxlcphxlzxfehclxzzxhaVlxzzxxlxxzkznmvffzcifSvzzz", "xlxcphxxzzcnxzzzzxcivMkzxlxlxlzxzzzzmmvkfdzZczzx", "xxlxajxzzzzlzzzzzxfaVzzzzzzzxlzxzzzzlznmfkzZczzz", "lxxcihxzzzzzzzzxzvpmmlzzzzzbkxxlzxzzxzlfdxlZczzx", "xllcajxzzzzzzzzzxffVzzzzzlz<+<czzzzzxlzdkxlZvlzz", "xxzcisjzxzzzzzzzzummzzzzlm9o3qbzzzxzzcfdxlzZclxz", "lxlxpgjgjzzzzzzxffSzxzzzlm1o>+fczzzlxxpkxxzZczzz", "lxxcpjclhgkxzzzxpmmlzzzzlm5;BOrblzxlxfdxzzlZvzxz", "xxzcphxxxzhgkzxgfSzzzzzxzzl=X,czzzzzxpkxlzlZclzz", "xllcpjxzzzxljhlimmkzxzzzzzcvzbzzxzzxfdxzzxzZvzzz", "zzzxajzzzzzzzlfzCzxxzzzzxzzzxzzzzzzzilzzzzzZczzz", "zzzzufzlzlzzzzzvfffzzllllllkllllllzfdzlzzlkZczzx", "zzzzsxmvvbbbbbbvmxkkvmvbbbnbmbbbnnnfcnnvnnvZczzz", "zzzvmVZVCCVVVVVVCCZCCCCmCZVCCBVVVCCCCBCCCCmVvlxz", "zzzzlzzlllzzlllllllllklkzlllzllzklllllllllkzzzzz", "zzzzxzzzzzzzzzzzzzzxxxzxzzzzzzzzzzzxxzzzzzczzzzz", "zzzzzzzzzzzzzzzzzxxzzzzzzzzzxzzxzzzzzzzzzzzzzzzz", "zxzzzzzzzzzxzzzzzzzzzzzzxzzxzzzzzzxzzxzzxzzzzzxz" }; const char *const *const xpm_icons[] = { xpm_icon_0, xpm_icon_1, xpm_icon_2, }; const int n_xpm_icons = 3;
the_stack_data/115764966.c
#include<stdio.h> #include<ctype.h> int htoi(char *s) { int p = 0; while (*s++ != '\0') { if (isdigit(*s)) { p = p * 16 + (*s - '0'); } else { switch (*s) { case 'a': case 'A': p = p * 16 + 10; break; case 'b': case 'B': p = p * 16 + 11; break; case 'c': case 'C': p = p * 16 + 12; break; case 'd': case 'D': p = p * 16 + 13; break; case 'e': case 'E': p = p * 16 + 14; break; case 'f': case 'F': p = p * 16 + 15; break; } } } return p; } int main() { char * hexNum = (char *) "0xff"; int decimelNum = htoi(hexNum); printf("The decimel number of %s is %d\n", hexNum, decimelNum); }
the_stack_data/1052099.c
/* Samuele Allegranza @ Polimi Fondamenti di informatica - Esercitazione > Esercizio: Si scriva un programma che visualizzi la tabella pitagorica */ #include <stdio.h> #define ROWS 12 #define COLUMNS 12 int main(int argc, char * argv[]) { int i, j; i=1; while(i<=ROWS){ j=1; while(j<=COLUMNS){ printf("%6d", j*i); j++; } printf("\n"); i++; } return 0; }
the_stack_data/90762623.c
#include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); char** split_string(char*); // Complete the kangaroo function below. // Please either make the string static or allocate on the heap. For example, // static char str[] = "hello world"; // return str; // // OR // // char* str = "hello world"; // return str; // char* kangaroo(int x1, int v1, int x2, int v2) { char *a = "YES"; char *b = "NO"; int i ; int d, s; for(i=0; i<100000; i++){ d = x1 + (i-1)*v1; s = x2 + (i-1)*v2; if(d == s){ return a; break; } } return b; } int main() { FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); char** x1V1X2V2 = split_string(readline()); char* x1_endptr; char* x1_str = x1V1X2V2[0]; int x1 = strtol(x1_str, &x1_endptr, 10); if (x1_endptr == x1_str || *x1_endptr != '\0') { exit(EXIT_FAILURE); } char* v1_endptr; char* v1_str = x1V1X2V2[1]; int v1 = strtol(v1_str, &v1_endptr, 10); if (v1_endptr == v1_str || *v1_endptr != '\0') { exit(EXIT_FAILURE); } char* x2_endptr; char* x2_str = x1V1X2V2[2]; int x2 = strtol(x2_str, &x2_endptr, 10); if (x2_endptr == x2_str || *x2_endptr != '\0') { exit(EXIT_FAILURE); } char* v2_endptr; char* v2_str = x1V1X2V2[3]; int v2 = strtol(v2_str, &v2_endptr, 10); if (v2_endptr == v2_str || *v2_endptr != '\0') { exit(EXIT_FAILURE); } char* result = kangaroo(x1, v1, x2, v2); fprintf(fptr, "%s\n", result); fclose(fptr); return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } size_t new_length = alloc_length << 1; data = realloc(data, new_length); if (!data) { break; } alloc_length = new_length; } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; } data = realloc(data, data_length); return data; } char** split_string(char* str) { char** splits = NULL; char* token = strtok(str, " "); int spaces = 0; while (token) { splits = realloc(splits, sizeof(char*) * ++spaces); if (!splits) { return splits; } splits[spaces - 1] = token; token = strtok(NULL, " "); } return splits; }
the_stack_data/51700789.c
/* * POK header * * The following file is a part of the POK project. Any modification should * be made according to the POK licence. You CANNOT use this file or a part * of a file for your own project. * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2022 POK team */ #ifdef POK_NEEDS_PCI #include <arch/x86/pci.h> pok_ret_t pci_register(s_pci_device *dev) { return pok_syscall2(POK_SYSCALL_PCI_REGISTER, (uint32_t)dev, NULL); } #endif /* POK_NEEDS_PCI */
the_stack_data/63800.c
/* Cutting sticks */ #include <stdio.h> #define MAXCUTS 52 #define MAXVALUE 10000 int main() { unsigned m[MAXCUTS][MAXCUTS]; unsigned sticks[MAXCUTS][MAXCUTS]; unsigned L, n, x, y; int i, j, k, l, q, t; while (scanf("%u", &L)) { if (L == 0) break; scanf("%u", &n); y = 0; for (i = 1; i <= n; i++) { scanf("%u", &x); sticks[i][i] = x - y; y = x; } sticks[i][i] = L - y; n++; for (i = 1; i <= n; i++) for (j = i+1; j <= n; j++) sticks[i][j] = sticks[i][j-1] + sticks[j][j]; m[0][0] = 0; for (i = 1; i <= n; i++) { m[i][i+1] = sticks[i][i] + sticks[i+1][i+1]; m[i][i] = 0; } for (l = 3; l <= n; l++) for (i = 1; i <= n-l+1; i++) { j = i + l - 1; m[i][j] = MAXVALUE; for (k = i; k <= j-1; k++) { q = m[i][k] + m[k+1][j] + sticks[i][j]; if (q < m[i][j]) m[i][j] = q; } } printf("The minimum cutting is %u.\n", m[1][n]); } return 0; }
the_stack_data/563611.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ultimate_range.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gcusuman <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/06 10:44:03 by gcusuman #+# #+# */ /* Updated: 2020/11/06 10:44:05 by gcusuman ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> int *ft_range(int min, int max) { int *out; int i; int size; i = 0; size = max - min; if ((out = (int *)malloc(sizeof(int) * size))) { while (i < size) out[i++] = min++; } return (out); } int ft_ultimate_range(int **range, int min, int max) { int size; if (min >= max) { *range = NULL; return (0); } size = max - min; if (!(*range = ft_range(min, max))) return (-1); return (size); }
the_stack_data/152833.c
#include <sys/syscall.h> #include <errno.h> // extern long errno; #define NULL 0 int linux_write(int fd, const void *data, unsigned long len); int linux_read(int fd, char *buffer, unsigned long bufferlen); int linux_open(const char *pathname, unsigned long flags, unsigned long mode); int linux_close(int fd); int linux_stat(const char *filename, void *buf); void linux_exit(int code); int linux_print_long(int fd, unsigned long i); int linux_print_hex(int fd, unsigned long i); int linux_print_string(int fd, char *s); int linux_to_decimal(unsigned long x, char *p); int linux_to_hex(unsigned long x, char *p); void *linux_mmap(void *start, unsigned long length, int prot, int flags, int fd, unsigned long offset); unsigned long int linux_strtoul(const char *nptr, char **endptr, int base); int linux_munmap(void *start, unsigned long length); int linux_mprotect(void *addr, unsigned long len, int prot); unsigned long linux_file_size(char *filename); int linux_getpagesize(void); void linux_brk(unsigned long addr); unsigned long linux_strlen(const char *s); char *linux_strchr(const char *s, int c); char *linux_strstr(const char *str, char *substr); void *linux_memcpy(void *dest, const void *src, unsigned long n); char *linux_strcat(char *dest, const char *src); #define PGSZ 0x1000 int linux_close(int fd) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_close), "D" (fd): "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int)ret; } void linux_exit(int code) { asm volatile ("syscall" : : "a" (__NR_exit), "D" (code)); } int linux_open(const char *pathname, unsigned long flags, unsigned long mode) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_open), "D" (pathname), "S" (flags), "d" (mode) : "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int) ret; } int linux_read(int fd, char *buffer, unsigned long bufferlen) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_read), "D" (fd), "S" (buffer), "d" (bufferlen) : "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int)ret; } int linux_write(int fd, const void *data, unsigned long len) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_write), "D" (fd), "S" (data), "d" (len) : "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int)ret; } /* void * linux_mmap( void *start, unsigned long length, int prot, int flags, int fd, unsigned long offset ) */ asm ( ".text\n" ".global linux_mmap\n" ".type linux_mmap,@function\n" "linux_mmap:\n\t" "mov %rcx,%r10\n\t" "mov $0x9,%eax\n\t" "syscall \n\t" "cmp $0xfffffffffffff001,%rax\n\t" "jae .Lx1\n\t" ".Lx2:\n\t" "retq \n\t" ".Lx1:\n\t" "mov 2623486(%rip),%rcx\n\t" "xor %edx,%edx\n\t" "sub %rax,%rdx\n\t" "mov %edx,%fs:(%rcx)\n\t" "or $0xffffffffffffffff,%rax\n\t" "jmp .Lx2\n" ); int linux_munmap(void *start, unsigned long length) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_munmap), "D" (start), "S" (length) : "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int)ret; } // int stat(const char *path, struct stat *buf); int linux_stat(const char *path, void *buf) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (4), "D" (path), "S" (buf) : "memory" ); if (ret < 0) { errno = -ret; ret = -1; } return (int)ret; } void * linux_memcpy(void *dest, const void *src, unsigned long n) { unsigned long i; unsigned char *d = (unsigned char *)dest; unsigned char *s = (unsigned char *)src; for (i = 0; i < n; ++i) d[i] = s[i]; return dest; } int linux_print_long(int fd, unsigned long i) { char i_buff[32]; int l, r; linux_to_decimal(i, i_buff); for (l = 0; i_buff[l]; ++l); r = linux_write(fd, i_buff, l); return r; } int linux_print_hex(int fd, unsigned long i) { char i_buff[64]; int l, r; linux_to_hex(i, i_buff); for (l = 0; i_buff[l]; ++l); r = linux_write(fd, i_buff, l); return r; } int linux_print_string(int fd, char *s) { int i, r; for (i = 0; s[i]; ++i); r = linux_write(fd, s, i); return r; } int linux_to_decimal(unsigned long x, char *p) { int count = 0; if (x == 0) *p++ ='0'; else { unsigned long q, r, b; int f = 0; b = 10000000000000000000U; do { q = x/b; if (q || f) { *p++ = ('0' + q); ++count; f = 1; x = x%b; } b /= 10; } while (b > 0); } *p = '\0'; return count; } int linux_to_hex(unsigned long n, char *p) { int i; int count = 0; for (i = 0; i < 16; ++i) { char x = ((n >> 60) & 0xf); if (x < (char)10) *p++ = x + '0'; else *p++ = (x - 10) + 'a'; ++count; n <<= 4; } *p = '\0'; return count; } // long errno = 0; unsigned long int linux_strtoul(const char *nptr, char **endptr, int base) { unsigned long ret = 0; int i; for (i = 0; nptr[i]; ++i) { char digit = nptr[i]; unsigned int value; if (digit <= '9') { value = '0'; } else if (digit <= 'Z') { value = 'A' - 10; } else if (digit <= 'z') { value = 'a' - 10; } ret *= base; ret += (digit - value); if (endptr) *endptr = &(nptr[i]); } return ret; } unsigned long linux_file_size(char *filename) { char sbuf[144]; unsigned long ret; if (0 > (long)(ret = linux_stat(filename, (void *)&sbuf))) { linux_print_string(2, "stat problem: "); linux_print_long(2, errno); linux_print_string(2, "\n"); } else { ret = *(unsigned long *)(sbuf+48); } return ret; } unsigned long linux_strlen(const char *s) { unsigned long r = 0; for (; s && *s; ++s, ++r); return r; } char *linux_strchr(const char *s, int c) { char *r = NULL; for (; s && *s; ++s) { if (*s == c) { r = (char *)s; break; } } return r; } char * linux_strcat(char *dest, const char *src) { if (dest && src) { char *p = dest; while (*p) ++p; for (; *src; ++p, ++src) *p = *src; } return dest; } char *linux_strstr(const char *str, char *substr) { char *r = NULL; int substrl = linux_strlen(substr); int linux_strl = linux_strlen(str); if (substrl < linux_strl) { int i; for (i = 0; i <= linux_strl - substrl; ++i) { char *p = (char *)&str[i]; int j; for (j = 0; j < substrl; ++j) { if (p[j] != substr[j]) break; } if (j == substrl) { r = p; break; } } } else if (substrl == linux_strl) { int i; char *p = (char *)&str[0]; for (i = 0; i < substrl; ++i) { if (p[i] != substr[i]) break; } if (i == substrl) r = p; } return r; } int linux_mprotect(void *addr, unsigned long len, int prot) { long ret; asm volatile ("syscall" : "=a" (ret) : "a" (__NR_mprotect), "D" (addr), "S" (len), "d" (prot) : "cc", "memory", "rcx", "r8", "r9", "r10", "r11" ); if (ret < 0) { errno = -ret; ret = -1; } return (int) ret; } void linux_brk(unsigned long addr) { asm volatile ("syscall" : : "a" (__NR_brk), "D" (addr)); }
the_stack_data/89201145.c
/* ******************************************************************************* * Copyright (c) 2020-2021, STMicroelectronics * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* */ #if defined(ARDUINO_GENERIC_L476MEYX) || defined(ARDUINO_GENERIC_L476MGYX) #include "pins_arduino.h" /** * @brief System Clock Configuration * @param None * @retval None */ WEAK void SystemClock_Config(void) { /* SystemClock_Config can be generated by STM32CubeMX */ #warning "SystemClock_Config() is empty. Default clock at reset is used." } #endif /* ARDUINO_GENERIC_* */
the_stack_data/33448.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993 * This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published. ***/ #include <stdint.h> #include <stdlib.h> /// Approximate function add8_449 /// Library = EvoApprox8b /// Circuit = add8_449 /// Area (180) = 1720 /// Delay (180) = 1.010 /// Power (180) = 552.60 /// Area (45) = 113 /// Delay (45) = 0.420 /// Power (45) = 44.70 /// Nodes = 36 /// HD = 65280 /// MAE = 0.71875 /// MSE = 2.25000 /// MRE = 0.38 % /// WCE = 5 /// WCRE = 50 % /// EP = 34.4 % uint16_t add8_449(uint8_t a, uint8_t b) { uint16_t c = 0; uint8_t n0 = (a >> 0) & 0x1; uint8_t n2 = (a >> 1) & 0x1; uint8_t n4 = (a >> 2) & 0x1; uint8_t n6 = (a >> 3) & 0x1; uint8_t n8 = (a >> 4) & 0x1; uint8_t n10 = (a >> 5) & 0x1; uint8_t n12 = (a >> 6) & 0x1; uint8_t n14 = (a >> 7) & 0x1; uint8_t n16 = (b >> 0) & 0x1; uint8_t n18 = (b >> 1) & 0x1; uint8_t n20 = (b >> 2) & 0x1; uint8_t n22 = (b >> 3) & 0x1; uint8_t n24 = (b >> 4) & 0x1; uint8_t n26 = (b >> 5) & 0x1; uint8_t n28 = (b >> 6) & 0x1; uint8_t n30 = (b >> 7) & 0x1; uint8_t n32; uint8_t n40; uint8_t n41; uint8_t n50; uint8_t n51; uint8_t n58; uint8_t n59; uint8_t n68; uint8_t n69; uint8_t n78; uint8_t n86; uint8_t n87; uint8_t n88; uint8_t n96; uint8_t n97; uint8_t n107; uint8_t n110; uint8_t n124; uint8_t n134; uint8_t n143; uint8_t n152; uint8_t n163; uint8_t n170; uint8_t n180; uint8_t n198; uint8_t n199; uint8_t n208; uint8_t n209; uint8_t n226; uint8_t n227; uint8_t n236; uint8_t n245; uint8_t n254; uint8_t n292; uint8_t n320; uint8_t n328; uint8_t n338; uint8_t n349; uint8_t n366; uint8_t n376; uint8_t n384; uint8_t n394; uint8_t n404; uint8_t n412; uint8_t n413; uint8_t n422; n32 = n0 | n16; n40 = n2 ^ n18; n41 = n2 & n18; n50 = n4 ^ n20; n51 = n4 & n20; n58 = n6 ^ n22; n59 = n6 & n22; n68 = n8 ^ n24; n69 = n8 & n24; n78 = n10 ^ n26; n86 = n12 ^ n28; n87 = n12 & n28; n88 = n24 | n8; n96 = n14 ^ n30; n97 = n14 & n30; n107 = n20 & n41; n110 = n10 & n26; n124 = n51 | n107; n134 = n88 & n59; n143 = n68 & n58; n152 = n69 | n134; n163 = n86 & n110; n170 = n86 & n78; n180 = n87 | n163; n198 = n124; n199 = n124; n208 = n143 & n124; n209 = n143 & n124; n226 = n152 | n208; n227 = n152 | n208; n236 = n170 & n152; n245 = n170 & n209; n254 = n180 | n236; n292 = n254 | n245; n320 = n58 & n199; n328 = n59 | n320; n338 = n78 & n227; n349 = n110 | n338; n366 = n50 | n41; n376 = n58 ^ n198; n384 = n68 ^ n328; n394 = n78 ^ n226; n404 = n86 ^ n349; n412 = n96 ^ n292; n413 = n96 & n292; n422 = n97 | n413; c |= (n32 & 0x1) << 0; c |= (n40 & 0x1) << 1; c |= (n366 & 0x1) << 2; c |= (n376 & 0x1) << 3; c |= (n384 & 0x1) << 4; c |= (n394 & 0x1) << 5; c |= (n404 & 0x1) << 6; c |= (n412 & 0x1) << 7; c |= (n422 & 0x1) << 8; return c; }
the_stack_data/34512033.c
void reach_error(){} void main() { int x = 0; while (x >= 0) { x--; } reach_error(); }
the_stack_data/75136449.c
#include <stdio.h> #include <math.h> #include <getopt.h> #include <stdlib.h> #include <sys/time.h> #include <omp.h> #include <string.h> #define MIN_NUM_OF_NEURONS (1L) #define DEF_NUM_OF_NEURONS (1000L) #define MIN_NUM_OF_NEIGHBORS (0L) #define DEF_NUM_OF_NEIGHBORS (300L) #define DEF_DT (1.0e-04) #define DEF_MU (1.0) #define DEF_UTH (0.98) #define DEF_S_MIN (0.7) #define DEF_S_MAX (0.7) #define DEF_SIM_TIME (20L) #define DEF_TTRANSIENT (-1L) void print_thread(); static struct option long_options[] = { {"dt", required_argument, 0, 'a'}, {"mu", required_argument, 0, 'b'}, {"uth", required_argument, 0, 'c'}, {"time", required_argument, 0, 'd'}, {"transient", required_argument, 0, 'e'}, {"s_min", required_argument, 0, 'f'}, {"s_max", required_argument, 0, 'g'}, {"n", required_argument, 0, 'n'}, {"r", required_argument, 0, 'r'}, {0, 0, 0, 0} }; int main(int argc, char *argv[]) { FILE *output1, *output2; long n, r; long i, j; long it; double divide; double dt; double tstep; long ntstep; long sim_time; long ttransient; long itime; double uth; double mu; double s_min; double s_max; double *u, *uplus, *sigma, *omega, *omega1, *temp_u; // double sum; double time; struct timeval global_start, global_end, IO_start, IO_end; double global_usec, IO_usec = 0.0; int c, option_index; char *end_ptr; n = DEF_NUM_OF_NEURONS; r = DEF_NUM_OF_NEIGHBORS; dt = DEF_DT; mu = DEF_MU; uth = DEF_UTH; s_min = DEF_S_MIN; s_max = DEF_S_MAX; sim_time = DEF_SIM_TIME; ttransient = DEF_TTRANSIENT; while (1) { c = getopt_long (argc, argv, "+n:r:", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'a': dt = strtod(optarg, &end_ptr); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (dt <= 0.0) { printf("Option \"%s\": \"dt\" must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'b': mu = strtod(optarg, &end_ptr); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (mu <= 0.0) { printf("Option \"%s\": \"mu\" must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'c': uth = strtod(optarg, &end_ptr); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (uth <= 0.0) { printf("Option \"%s\": \"uth\" must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'd': sim_time = strtol(optarg, &end_ptr, 10); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (sim_time < 1) { printf("Option \"%s\": Total simulation time must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'e': ttransient = strtol(optarg, &end_ptr, 10); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (ttransient < 0) { printf("Option \"%s\": \"ttransient\" must be larger or equal than zero.\n", long_options[option_index].name); exit(1); } break; case 'f': s_min = strtod(optarg, &end_ptr); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (s_min <= 0.0) { printf("Option \"%s\": \"s_min\" must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'g': s_max = strtod(optarg, &end_ptr); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (s_max <= 0.0) { printf("Option \"%s\": \"s_max\" must be larger than zero.\n", long_options[option_index].name); exit(1); } break; case 'n': n = strtol(optarg, &end_ptr, 10); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (n < MIN_NUM_OF_NEURONS) { printf("Option \"%s\": Number of neurons must be at least %ld.\n", long_options[option_index].name, MIN_NUM_OF_NEURONS); exit(1); } break; case 'r': r = strtol(optarg, &end_ptr, 10); if (*end_ptr != '\0') { printf("Option \"%s\": Invalid argument \"%s\".\n", long_options[option_index].name, optarg); exit(1); } if (r < MIN_NUM_OF_NEIGHBORS) { printf("Option \"%s\": Number of neighbors must be at least %ld.\n", long_options[option_index].name, MIN_NUM_OF_NEIGHBORS); exit(1); } break; case '?': default: exit(1); break; } } if (optind != argc) { printf("Unknown option \"%s\".\n", argv[optind]); exit(1); } if (2 * r + 1 > n) { printf("Total number of neighbors and reference neuron (2 * %ld + 1 = %ld) cannot exceed number of neurons (%ld).\n", r, 2 * r + 1, n); exit(1); } if (s_min > s_max) { printf("s_min (%17.15f) must be smaller or equal than s_max (%17.15f).\n", s_min, s_max); exit(1); } divide = (double)(2 * r); tstep = 1.0 / dt; ntstep = (long)tstep; if (ttransient == DEF_TTRANSIENT) { ttransient = (sim_time * ntstep) / 2; } else { ttransient *= ntstep; } itime = sim_time * ntstep; printf("Running simulation with following parameters:\n"); printf(" Number of neurons : %ld\n", n); printf(" Numger of neighbours: %ld\n", r); printf(" Simulation time : %ld seconds (%ld time steps)\n", sim_time, itime); printf(" Transient time : %ld seconds (%ld time steps)\n", ttransient / ntstep, ttransient); printf(" dt : %.1e seconds \n", dt); printf(" mu : %17.15f\n", mu); printf(" uth : %17.15f\n", uth); printf(" s_min : %17.15f\n", s_min); printf(" s_max : %17.15f\n", s_max); output1 = fopen("spacetime.out", "w"); if (output1 == NULL) { printf("Could not open file \"spacetime.out\""); exit(1); } output2 = fopen("omega.out", "w"); if (output2 == NULL) { printf("Could not open file \"omega.out\""); exit(1); } u = (double *)calloc(n, sizeof(double)); if (u == NULL) { printf("Could not allocate memory for \"u\".\n"); exit(1); } uplus = (double *)calloc(n, sizeof(double)); if (uplus == NULL) { printf("Could not allocate memory for \"uplus\".\n"); exit(1); } sigma = (double *)calloc(n * n, sizeof(double)); if (sigma == NULL) { printf("Could not allocate memory for \"sigma\".\n"); exit(1); } omega = (double *)calloc(n, sizeof(double)); if (omega == NULL) { printf("Could not allocate memory for \"omega\".\n"); exit(1); } omega1 = (double *)calloc(n, sizeof(double)); if (omega1 == NULL) { printf("Could not allocate memory for \"omega1\".\n"); exit(1); } temp_u = (double *)calloc(n, sizeof(double)); if (temp_u == NULL) { printf("Could not allocate memory for \"temp_u\".\n"); exit(1); } for (i = 0; i < n;) { u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; u[i] = drand48(); // temp_u[i] = u[i] + dt * (mu - u[i]); printf("%ld\t%f\n", i, u[i]); i++; } /* Read connectivity matrix sigma[n][n] from file or construct connectivity matrix. */ for (i = 0; i < r; i++) { for (j = 0; j < i + r + 1; j++) { sigma[i * n + j] = s_min + (s_max - s_min) * drand48(); } for (j = n - r + i; j < n; j++) { sigma[i * n + j] = s_min + (s_max - s_min) * drand48(); } } for (i = r; i < n - r; i++) { for (j = 0; j < 2 * r + 1; j++) { sigma[i * n + j + i - r] = s_min + (s_max - s_min) * drand48(); } } for (i = n - r; i < n; i++) { for (j = 0; j < i - n + r + 1; j++) { sigma[i * n + j] = s_min + (s_max - s_min) * drand48(); } for (j = i - r; j < n; j++) { sigma[i * n + j] = s_min + (s_max - s_min) * drand48(); } } #if 0 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%4.1f", sigma[i * n + j]); } printf("\n"); } #endif /* Temporal iteration. */ gettimeofday(&global_start, NULL); double sum; double temp; int step; double semi_sum=0.0; // omp_set_num_threads(8); // Use 4 threads for all consecutive parallel regions for (i = 0; i < n;i++) { semi_sum+=sigma[i]; } #pragma omp parallel private(i,j,it) firstprivate(n,sigma,dt,mu,semi_sum) { for (it = 0; it < itime; it++) { for (i = 0; i < n; i++) { sum = 0.0; temp = u[i]; step = i * n; #pragma omp atomic write uplus[i] = temp + dt * (mu - temp); #pragma omp for firstprivate(sum) for (j = 0; j < n;j++) { sum = sum + sigma[step + j] * u[j]; } #pragma omp single { #pragma omp atomic uplus[i]+= dt * (sum - semi_sum*temp) / divide; // // temp_u[i] = uplus[i]; if (uplus[i] > uth) { #pragma omp atomic write uplus[i] = 0.0; if (it >= ttransient) { #pragma omp atomic omega1[i] += 1.0; } } } } memcpy(u, uplus, n * sizeof *u); #if !defined(ALL_RESULTS) if (it % ntstep == 0) { #endif #pragma omp single { printf("Time is %ld\n", it); gettimeofday(&IO_start, NULL); fprintf(output1, "%ld\t", it); for (i = 0; i < n; i++) { // printf("write to ouput1 i: %d\n",i); fprintf(output1, "%19.15f", u[i]); } fprintf(output1, "\n"); time = (double)it * dt; fprintf(output2, "%ld\t", it); for (i = 0; i < n; i++) { omega[i] = 2.0 * M_PI * omega1[i] / (time - ttransient * dt); fprintf(output2, "%19.15f", omega[i]); } fprintf(output2, "\n"); gettimeofday(&IO_end, NULL); IO_usec += ((IO_end.tv_sec - IO_start.tv_sec) * 1000000.0 + (IO_end.tv_usec - IO_start.tv_usec)); }//master end #if !defined(ALL_RESULTS) } #endif } }//omp parallel gettimeofday(&global_end, NULL); global_usec = ((global_end.tv_sec - global_start.tv_sec) * 1000000.0 + (global_end.tv_usec - global_start.tv_usec)); printf("Time for calculations = %13.6f sec\n", (global_usec - IO_usec) / 1000000.0); printf("Time for I/O = %13.6f sec\n", IO_usec / 1000000.0); printf("Total execution time = %13.6f sec\n", global_usec / 1000000.0); fclose(output1); fclose(output2); return 0; }
the_stack_data/193893806.c
#include <stdio.h> void say_hi(void) { printf("B: hi\n"); }
the_stack_data/192330351.c
//***************************************************************************** // strncpy.c : string function // 2002/02/04 by Gaku : this is rough sketch //***************************************************************************** #include <stddef.h> //============================================================================= // copy no more SZ bytes S to D //============================================================================= char* strncpy (char *d, const char *s, size_t sz) { char *tmp = d; while ('\0' != *s) { if (0 == sz) break; sz--; *d++ = *s++; } while (sz--) *d++ = '\0'; return tmp; }
the_stack_data/15086.c
#include <stdio.h> #include <stdlib.h> #define NDEBUG int **generate(int size) { int n, i, j; int flag = 0; int **matrix; matrix = (int **) malloc(size * sizeof(*matrix)); if (!matrix) { fputs("generate(): malloc fail\n", stderr); exit(1); } *matrix = (int *) calloc(size * size, sizeof(**matrix)); if (!*matrix) { fputs("generate(): calloc fail\n", stderr); exit(1); } for (i = 0; i < size; i++) { matrix[i] = (*matrix) + i * size; } n = size * size; i = 0; j = size - 1; while (n >= 1) { while (j >= 0 && matrix[i][j] == 0) { matrix[i][j--] = n--; flag = 1; } if (flag) { j++; i++; flag = 0; } while (i < size && matrix[i][j] == 0) { matrix[i++][j] = n--; flag = 1; } if (flag) { i--; j++; flag = 0; } while (j < size && matrix[i][j] == 0) { matrix[i][j++] = n--; flag = 1; } if (flag) { j--; i--; flag = 0; } while (i >= 0 && matrix[i][j] == 0) { matrix[i--][j] = n--; flag = 1; } if (flag) { i++; j--; flag = 0; } } return matrix; } int sum_diag(int **matrix, int size) { int i; int sum = 0; for (i = 0; i < size; i++) { sum += matrix[i][i]; } for (i = size - 1; i >= 0; i--) { sum += matrix[i][size - i - 1]; } return sum - 1; /* counted the entry at the center (1) twice */ } int main() { int **matrix; int size; scanf("%d", &size); matrix = generate(size); printf("%d\n", sum_diag(matrix, size)); free(*matrix); free(matrix); return 0; }
the_stack_data/32950959.c
#include <stdio.h>//AC 0.2S #define SIZE 10001 int binarySearch(int *array,int taget,int left,int right){ int mid=(left+right)>>1; if(left>right)return 0; if(array[mid]==taget)return 1; else if(array[mid]>taget){ return binarySearch(array,taget,left,mid-1); } else{ return binarySearch(array,taget,mid+1,right); } } int main(){ int n,m; scanf("%d%d",&n,&m); while(n--){ int list1[SIZE]; int count=0; int temp; for(int i=0;i<m;++i)scanf("%d",&list1[i]); for(int i=0;i<m;++i){ scanf("%d",&temp); if(binarySearch(list1,temp,0,m))++count; } printf("%d\n",count); } }
the_stack_data/54826601.c
//sort the input, the find max count int cmp(const void* a, const void* b) { return *(int*)a < *(int*)b ? 0 : 1; } int findLHS(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), cmp); int result = 0; int i; int j; for(i = 0; i<numsSize - 1;i++) { int count = 1; int temp = nums[i]; for(j = i+1; j<numsSize;j++) { if((nums[j] - temp) <= 1) count++; else break; } if(result < count && nums[j-1] - temp == 1) result = count; } return result; }
the_stack_data/125141281.c
/* Authors: Takeshi I. */ #include <math.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #define PI 3.14159265 /* Define func as a function type that takes a double and returns a double. */ typedef double (*func)(double); /* Calculates the area under a curve */ double area(func, double, double, int); double area_seq(func, double, double, int); double square(double); double trig_sin(double); double trig_2_plus_sin(double); int main(int argc, char* argv[]) { int a = 0, b = 4, n = 500000000, threads = 4, t_enable = 0; // if (argc == 6) { // a = atoi(argv[1]); // b = atoi(argv[2]); // n = atoi(argv[3]); // threads = atoi(argv[4]); // t_enable = atoi(argv[5]); // } printf("Riemann Sum LHS approximation for f(x) = x^2 using:\n"); printf("start x: %d to ending x: %d, with %d rectangles (%d threads)\n", a, b, n, threads); // Switches between threads and sequential // if (t_enable == 1) { //use threads // omp_set_num_threads(threads); //set number of threads // printf("Parallel with %d threads\n\n", threads); // printf("Area of x^2 is %f\n\n", area(square, a, b, n)); // } else { //sequential don't use threads // printf("Sequential\n\n"); // printf("Area of x^2 is %f\n\n", area_seq(square, a, b, n)); // } // //printf("area of 2 + sin is %f\n\n", area(trig_2_plus_sin, a, b, n)); // //printf("area of e^x is %f\n\n", area(exp, a, b, n)); // Will run parallel then sequential omp_set_num_threads(threads); clock_t start = clock(); printf("Parallel: %f\n", area(square, a, b, n)); clock_t stop = clock(); printf("\tParallel time: %f~\n", (((stop - start) / (double)CLOCKS_PER_SEC)) / threads); clock_t start_s = clock(); printf("Serial: %f\n", area_seq(square, a, b, n)); clock_t stop_s = clock(); printf("\tSerial time: %f\n", (stop_s - start_s) / (double)CLOCKS_PER_SEC); return 0; } /* Equavalent to pow(x, 2) */ double square(double x) { return x * x; } double trig_sin(double x) { return sin(x * PI / 180); } double trig_2_plus_sin(double x) { return 2.0 + sin(x * PI / 180.0); } double sum = 0; /*Left Riemann Sum */ double area(func f, double a, double b, int n) { double x = 0, deltaX = fabs(b - a) / n; #pragma omp parallel for reduction(+: sum) for (int i = 0; i < n; i++) { x = a + i * deltaX; sum += f(x) * deltaX; // sleep(1); //printf("thread id: %d, sum: %f\n", omp_get_thread_num(), sum); } return sum; } /*Left Riemann Sum */ double area_seq(func f, double a, double b, int n) { sum = 0; double x = 0, deltaX = fabs(b - a) / n; for (int i = 0; i < n; i++) { x = a + i * deltaX; sum += f(x) * deltaX; // sleep(1); } return sum; }
the_stack_data/150560.c
#include <stdio.h> #include <stdlib.h> int my_strcmp(const char *s, const char *t); int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Provide just two strings to compare.\n"); exit(EXIT_FAILURE); } printf("%d\n", my_strcmp(argv[1], argv[2])); return 0; } int my_strcmp(const char *s, const char *t) { for (;*s == *t; s++, t++) { if (!*s) { return 0; } } return *s - *t; }
the_stack_data/844634.c
#include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <unistd.h> static bool failed = false; static void cat(const char* path) { int fd; if (strcmp(path, "-") == 0) { fd = 0; } else { fd = open(path, O_RDONLY); if (fd < 0) { perror("open"); failed = true; return; } } while (true) { char buffer[1]; ssize_t readSize = read(fd, buffer, sizeof(buffer)); if (readSize < 0) { perror("read"); failed = true; break; } else if (readSize == 0) { break; } ssize_t writtenSize = write(1, buffer, readSize); if (writtenSize < 0) { perror("write"); } } if (fd != 0) { close(fd); } } int main(int argc, char *argv[]) { if (argc >= 2) { for (int i = 1; i < argc; i++) { cat(argv[i]); } } else { cat("-"); } return failed ? 1: 0; }
the_stack_data/59359.c
/* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to [email protected] before changing it! Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. Ditto for AIX 3.2 and <stdlib.h>. */ #ifndef _NO_PROTO # define _NO_PROTO #endif #ifdef HAVE_CONFIG_H # include <config.h> #endif #if !defined __STDC__ || !__STDC__ /* This is a separate conditional since some stdc systems reject `defined (const)'. */ # ifndef const # define const # endif #endif #include <stdio.h> /* Comment out all this code if we are using the GNU C Library, and are not actually compiling the library itself. This code is part of the GNU C Library, but also included in many other GNU distributions. Compiling and linking in this code is a waste when using the GNU C library (especially if it is a shared library). Rather than having every GNU program understand `configure --with-gnu-libc' and omit the object files, it is simpler to just do this in the source for each such file. */ #define GETOPT_INTERFACE_VERSION 2 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 # include <gnu-versions.h> # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION # define ELIDE_CODE # endif #endif #ifndef ELIDE_CODE /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ /* Don't include stdlib.h for non-GNU C libraries because some of them contain conflicting prototypes for getopt. */ # include <stdlib.h> # include <unistd.h> #endif /* GNU C library. */ #ifdef VMS # include <unixlib.h> # if HAVE_STRING_H - 0 # include <string.h> # endif #endif #ifndef _ /* This is for other GNU distributions with internationalized messages. When compiling libc, the _ macro is predefined. */ # ifdef HAVE_LIBINTL_H # include <libintl.h> # define _(msgid) gettext (msgid) # else # define _(msgid) (msgid) # endif #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Formerly, initialization of getopt depended on optind==0, which causes problems with re-calling getopt as programs generally don't know that. */ int __getopt_initialized; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return -1 with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #ifdef __GNU_LIBRARY__ /* We want to avoid inclusion of string.h with non-GNU libraries because there are many ways it can cause trouble. On some systems, it contains special magic macros that don't work in GCC. */ # include <string.h> # define my_index strchr #else #include <string.h> /* Avoid depending on library functions or files whose names are inconsistent. */ #ifndef getenv extern char *getenv (); #endif static char * my_index (str, chr) const char *str; int chr; { while (*str) { if (*str == chr) return (char *) str; str++; } return 0; } /* If using GCC, we can safely declare strlen this way. If not using GCC, it is ok not to declare it. */ #ifdef __GNUC__ /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. That was relevant to code that was here before. */ # if (!defined __STDC__ || !__STDC__) && !defined strlen /* gcc with -traditional declares the built-in strlen to return int, and has done so at least since version 2.4.5. -- rms. */ extern int strlen (const char *); # endif /* not __STDC__ */ #endif /* __GNUC__ */ #endif /* not __GNU_LIBRARY__ */ /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; #ifdef _LIBC /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ /* Defined in getopt_init.c */ extern char *__getopt_nonoption_flags; static int nonoption_flags_max_len; static int nonoption_flags_len; static int original_argc; static char *const *original_argv; /* Make sure the environment variable bash 2.0 puts in the environment is valid for the getopt call we must make sure that the ARGV passed to getopt is that one passed to the process. */ static void __attribute__ ((unused)) store_args_and_env (int argc, char *const *argv) { /* XXX This is no good solution. We should rather copy the args so that we can compare them later. But we must not use malloc(3). */ original_argc = argc; original_argv = argv; } # ifdef text_set_element text_set_element (__libc_subinit, store_args_and_env); # endif /* text_set_element */ # define SWAP_FLAGS(ch1, ch2) \ if (nonoption_flags_len > 0) \ { \ char __tmp = __getopt_nonoption_flags[ch1]; \ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ __getopt_nonoption_flags[ch2] = __tmp; \ } #else /* !_LIBC */ # define SWAP_FLAGS(ch1, ch2) #endif /* _LIBC */ /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ #if defined __STDC__ && __STDC__ static void exchange (char **); #endif static void exchange (argv) char **argv; { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ #ifdef _LIBC /* First make sure the handling of the `__getopt_nonoption_flags' string can work normally. Our top argument must be in the range of the string. */ if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) { /* We must extend the array. The user plays games with us and presents new arguments. */ char *new_str = malloc (top + 1); if (new_str == NULL) nonoption_flags_len = nonoption_flags_max_len = 0; else { memset (__mempcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len), '\0', top + 1 - nonoption_flags_max_len); nonoption_flags_max_len = top + 1; __getopt_nonoption_flags = new_str; } } #endif while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; SWAP_FLAGS (bottom + i, middle + i); } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ #if defined __STDC__ && __STDC__ static const char *_getopt_initialize (int, char *const *, const char *); #endif static const char * _getopt_initialize (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind; nextchar = NULL; posixly_correct = getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; #ifdef _LIBC if (posixly_correct == NULL && argc == original_argc && argv == original_argv) { if (nonoption_flags_max_len == 0) { if (__getopt_nonoption_flags == NULL || __getopt_nonoption_flags[0] == '\0') nonoption_flags_max_len = -1; else { const char *orig_str = __getopt_nonoption_flags; int len = nonoption_flags_max_len = strlen (orig_str); if (nonoption_flags_max_len < argc) nonoption_flags_max_len = argc; __getopt_nonoption_flags = (char *) malloc (nonoption_flags_max_len); if (__getopt_nonoption_flags == NULL) nonoption_flags_max_len = -1; else memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), '\0', nonoption_flags_max_len - len); } } nonoption_flags_len = nonoption_flags_max_len; } else nonoption_flags_len = 0; #endif return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal (argc, argv, optstring, longopts, longind, long_only) int argc; char *const *argv; const char *optstring; const struct option *longopts; int *longind; int long_only; { optarg = NULL; if (optind == 0 || !__getopt_initialized) { if (optind == 0) optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize (argc, argv, optstring); __getopt_initialized = 1; } /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. The later information is only used when the used in the GNU libc. */ #ifdef _LIBC # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ || (optind < nonoption_flags_len \ && __getopt_nonoption_flags[optind] == '1')) #else # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') #endif if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp (argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return -1; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = -1; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == (unsigned int) strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (opterr) fprintf (stderr, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (opterr) { if (argv[optind - 1][1] == '-') /* --option */ fprintf (stderr, _("%s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); else /* +option or -option */ fprintf (stderr, _("%s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); } nextchar += strlen (nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (opterr) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || my_index (optstring, *nextchar) == NULL) { if (opterr) { if (argv[optind][1] == '-') /* --option */ fprintf (stderr, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); else /* +option or -option */ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); } nextchar = (char *) ""; optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; char *temp = my_index (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (opterr) { if (posixly_correct) /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); else fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); } optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (opterr) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (opterr) fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (opterr) fprintf (stderr, _("\ %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->name); nextchar += strlen (nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (opterr) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (opterr) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } int getopt (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0); } #endif /* Not ELIDE_CODE. */ #ifdef TEST /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */ int main (argc, argv) int argc; char **argv; { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == -1) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
the_stack_data/215768626.c
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -S -o - %s -emit-llvm | FileCheck %s // RUN: %clang_cc1 -triple nvptx64-unknown-unknown -S -o - %s -emit-llvm | FileCheck %s typedef struct float4_s { float x, y, z, w; } float4_t; float4_t my_function(void) { // CHECK-LABEL: define{{.*}} %struct.float4_s @my_function float4_t t; return t; }; float bar(void) { float4_t ret; // CHECK-LABEL: @bar // CHECK: call %struct.float4_s @my_function ret = my_function(); return ret.x; } void foo(float4_t x) { // CHECK-LABEL: @foo // CHECK: %struct.float4_s* noundef byval(%struct.float4_s) align 4 %x } void fooN(float4_t x, float4_t y, float4_t z) { // CHECK-LABEL: @fooN // CHECK: %struct.float4_s* noundef byval(%struct.float4_s) align 4 %x // CHECK: %struct.float4_s* noundef byval(%struct.float4_s) align 4 %y // CHECK: %struct.float4_s* noundef byval(%struct.float4_s) align 4 %z } typedef struct nested_s { unsigned long long x; float z[64]; float4_t t; } nested_t; void baz(nested_t x) { // CHECK-LABEL: @baz // CHECK: %struct.nested_s* noundef byval(%struct.nested_s) align 8 %x) }
the_stack_data/637829.c
// no output from test machine // https://syzkaller.appspot.com/bug?id=8bf9a9a2638fc9e95348d4398decb1b5c80beecb // status:invalid // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <pthread.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> const int kFailStatus = 67; const int kRetryStatus = 69; __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } __attribute__((noreturn)) static void fail(const char* msg, ...) { int e = errno; fflush(stdout); va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } __attribute__((noreturn)) static void exitf(const char* msg, ...) { int e = errno; fflush(stdout); va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit(kRetryStatus); } #define BITMASK_LEN(type, bf_len) (type)((1ull << (bf_len)) - 1) #define BITMASK_LEN_OFF(type, bf_off, bf_len) \ (type)(BITMASK_LEN(type, (bf_len)) << (bf_off)) #define STORE_BY_BITMASK(type, addr, val, bf_off, bf_len) \ if ((bf_off) == 0 && (bf_len) == 0) { \ *(type*)(addr) = (type)(val); \ } else { \ type new_val = *(type*)(addr); \ new_val &= ~BITMASK_LEN_OFF(type, (bf_off), (bf_len)); \ new_val |= ((type)(val)&BITMASK_LEN(type, (bf_len))) << (bf_off); \ *(type*)(addr) = new_val; \ } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } #define COMMAND_MAX_LEN 128 static void execute_command(const char* format, ...) { va_list args; char command[COMMAND_MAX_LEN]; int rv; va_start(args, format); vsnprintf_check(command, sizeof(command), format, args); rv = system(command); if (rv != 0) fail("tun: command \"%s\" failed with code %d", &command[0], rv); va_end(args); } static int tunfd = -1; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define MAX_PIDS 32 #define ADDR_MAX_LEN 32 #define LOCAL_MAC "aa:aa:aa:aa:aa:%02hx" #define REMOTE_MAC "bb:bb:bb:bb:bb:%02hx" #define LOCAL_IPV4 "172.20.%d.170" #define REMOTE_IPV4 "172.20.%d.187" #define LOCAL_IPV6 "fe80::%02hxaa" #define REMOTE_IPV6 "fe80::%02hxbb" static void initialize_tun(uint64_t pid) { if (pid >= MAX_PIDS) fail("tun: no more than %d executors", MAX_PIDS); int id = pid; tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) fail("tun: can't open /dev/net/tun"); char iface[IFNAMSIZ]; snprintf_check(iface, sizeof(iface), "syz%d", id); struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, iface, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); char local_mac[ADDR_MAX_LEN]; snprintf_check(local_mac, sizeof(local_mac), LOCAL_MAC, id); char remote_mac[ADDR_MAX_LEN]; snprintf_check(remote_mac, sizeof(remote_mac), REMOTE_MAC, id); char local_ipv4[ADDR_MAX_LEN]; snprintf_check(local_ipv4, sizeof(local_ipv4), LOCAL_IPV4, id); char remote_ipv4[ADDR_MAX_LEN]; snprintf_check(remote_ipv4, sizeof(remote_ipv4), REMOTE_IPV4, id); char local_ipv6[ADDR_MAX_LEN]; snprintf_check(local_ipv6, sizeof(local_ipv6), LOCAL_IPV6, id); char remote_ipv6[ADDR_MAX_LEN]; snprintf_check(remote_ipv6, sizeof(remote_ipv6), REMOTE_IPV6, id); execute_command("sysctl -w net.ipv6.conf.%s.accept_dad=0", iface); execute_command("sysctl -w net.ipv6.conf.%s.router_solicitations=0", iface); execute_command("ip link set dev %s address %s", iface, local_mac); execute_command("ip addr add %s/24 dev %s", local_ipv4, iface); execute_command("ip -6 addr add %s/120 dev %s", local_ipv6, iface); execute_command("ip neigh add %s lladdr %s dev %s nud permanent", remote_ipv4, remote_mac, iface); execute_command("ip -6 neigh add %s lladdr %s dev %s nud permanent", remote_ipv6, remote_mac, iface); execute_command("ip link set dev %s up", iface); } static void setup_tun(uint64_t pid, bool enable_tun) { if (enable_tun) initialize_tun(pid); } static int read_tun(char* data, int size) { int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; fail("tun: read failed with %d, errno: %d", rv, errno); } return rv; } struct csum_inet { uint32_t acc; }; static void csum_inet_init(struct csum_inet* csum) { csum->acc = 0; } static void csum_inet_update(struct csum_inet* csum, const uint8_t* data, size_t length) { if (length == 0) return; size_t i; for (i = 0; i < length - 1; i += 2) csum->acc += *(uint16_t*)&data[i]; if (length & 1) csum->acc += (uint16_t)data[length - 1]; while (csum->acc > 0xffff) csum->acc = (csum->acc & 0xffff) + (csum->acc >> 16); } static uint16_t csum_inet_digest(struct csum_inet* csum) { return ~csum->acc; } static uintptr_t syz_emit_ethernet(uintptr_t a0, uintptr_t a1) { if (tunfd < 0) return (uintptr_t)-1; int64_t length = a0; char* data = (char*)a1; return write(tunfd, data, length); } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) ; } static uint64_t current_time_ms() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) fail("clock_gettime failed"); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void test(); void loop() { int iter; for (iter = 0;; iter++) { int pid = fork(); if (pid < 0) fail("clone failed"); if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); flush_tun(); test(); doexit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { int res = waitpid(-1, &status, __WALL | WNOHANG); if (res == pid) break; usleep(1000); if (current_time_ms() - start > 5 * 1000) { kill(-pid, SIGKILL); kill(pid, SIGKILL); while (waitpid(-1, &status, __WALL) != pid) { } break; } } } } long r[105]; void* thr(void* arg) { switch ((long)arg) { case 0: r[0] = syscall(__NR_mmap, 0x20000000ul, 0xf07000ul, 0x3ul, 0x32ul, 0xfffffffffffffffful, 0x0ul); break; case 1: r[1] = syscall(__NR_socket, 0x2ul, 0x2ul, 0x0ul); break; case 2: *(uint16_t*)0x20f01000 = (uint16_t)0x2; *(uint16_t*)0x20f01002 = (uint16_t)0x224e; *(uint32_t*)0x20f01004 = (uint32_t)0x10000e0; *(uint8_t*)0x20f01008 = (uint8_t)0x0; *(uint8_t*)0x20f01009 = (uint8_t)0x0; *(uint8_t*)0x20f0100a = (uint8_t)0x0; *(uint8_t*)0x20f0100b = (uint8_t)0x0; *(uint8_t*)0x20f0100c = (uint8_t)0x0; *(uint8_t*)0x20f0100d = (uint8_t)0x0; *(uint8_t*)0x20f0100e = (uint8_t)0x0; *(uint8_t*)0x20f0100f = (uint8_t)0x0; r[13] = syscall(__NR_bind, r[1], 0x20f01000ul, 0x10ul); break; case 3: *(uint16_t*)0x20647000 = (uint16_t)0x2; *(uint16_t*)0x20647002 = (uint16_t)0x204e; *(uint32_t*)0x20647004 = (uint32_t)0xfeffffff; *(uint8_t*)0x20647008 = (uint8_t)0x0; *(uint8_t*)0x20647009 = (uint8_t)0x0; *(uint8_t*)0x2064700a = (uint8_t)0x0; *(uint8_t*)0x2064700b = (uint8_t)0x0; *(uint8_t*)0x2064700c = (uint8_t)0x0; *(uint8_t*)0x2064700d = (uint8_t)0x0; *(uint8_t*)0x2064700e = (uint8_t)0x0; *(uint8_t*)0x2064700f = (uint8_t)0x0; r[25] = syscall(__NR_recvfrom, r[1], 0x20f04000ul, 0x0ul, 0x2ul, 0x20647000ul, 0x10ul); break; case 4: *(uint8_t*)0x20df2fce = (uint8_t)0xbb; *(uint8_t*)0x20df2fcf = (uint8_t)0xbb; *(uint8_t*)0x20df2fd0 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd1 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd2 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd3 = (uint8_t)0x0; *(uint8_t*)0x20df2fd4 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd5 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd6 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd7 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd8 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd9 = (uint8_t)0x0; *(uint16_t*)0x20df2fda = (uint16_t)0x8; STORE_BY_BITMASK(uint8_t, 0x20df2fdc, 0x5, 0, 4); STORE_BY_BITMASK(uint8_t, 0x20df2fdc, 0x4, 4, 4); STORE_BY_BITMASK(uint8_t, 0x20df2fdd, 0x101, 0, 2); STORE_BY_BITMASK(uint8_t, 0x20df2fdd, 0x0, 2, 6); *(uint16_t*)0x20df2fde = (uint16_t)0x2310; *(uint16_t*)0x20df2fe0 = (uint16_t)0x6400; *(uint16_t*)0x20df2fe2 = (uint16_t)0x0; *(uint8_t*)0x20df2fe4 = (uint8_t)0x2; *(uint8_t*)0x20df2fe5 = (uint8_t)0x11; *(uint16_t*)0x20df2fe6 = (uint16_t)0x0; *(uint8_t*)0x20df2fe8 = (uint8_t)0xac; *(uint8_t*)0x20df2fe9 = (uint8_t)0x14; *(uint8_t*)0x20df2fea = (uint8_t)0x0; *(uint8_t*)0x20df2feb = (uint8_t)0xbb; *(uint32_t*)0x20df2fec = (uint32_t)0x10000e0; *(uint16_t*)0x20df2ff0 = (uint16_t)0x204e; *(uint16_t*)0x20df2ff2 = (uint16_t)0x224e; *(uint8_t*)0x20df2ff4 = (uint8_t)0x4; STORE_BY_BITMASK(uint8_t, 0x20df2ff5, 0x1, 0, 4); STORE_BY_BITMASK(uint8_t, 0x20df2ff5, 0x51, 4, 4); *(uint16_t*)0x20df2ff6 = (uint16_t)0x0; STORE_BY_BITMASK(uint8_t, 0x20df2ff8, 0x0, 0, 1); STORE_BY_BITMASK(uint8_t, 0x20df2ff8, 0xb, 1, 4); STORE_BY_BITMASK(uint8_t, 0x20df2ff8, 0x6, 5, 3); memcpy((void*)0x20df2ff9, "\xd2\x2b\x30", 3); *(uint8_t*)0x20df2ffc = (uint8_t)0x10000; memcpy((void*)0x20df2ffd, "\x29\x9d\x28", 3); memcpy( (void*)0x20df3000, "\x06\x29\x9a\x9b\x46\x91\x35\xfa\xec\x24\x89\x45\x34\xaf\xf5" "\x6d\xe2\x6a\xd5\x40\x2e\xe0\xe7\x20\x04\x4e\x3d\x78\xe1\x61" "\x23\xb9\xd9\xb8\xca\x3d\xc8\xc2\xfe\xa5\xff\x3d\x08\xf4\x09" "\x8d\x53\x62\xf0\xb8\x1b\x8b\x7f\x04\x28\x64\x89\x03\x18\x3e" "\x20\x2e\x69\xfd\x7a\x75\xdc\x05\x79\xab\x10\xb9\x65\x54\x01" "\xd9\x30\x81\x26\xae\x0b\x65\x12\x95\xc3\x24\xe2\xfc\xaf\xa9" "\xc8\x49\x21\x32\xdf\x00\x3f\x4d\x04\x7d\xa7\x19\xaa\x28\x9f" "\x55\x9f\xf2\x34\x82\x11\x20\xec\xf5\x5e\xf0\x64\x6e\xf3\x64" "\x8b\x20\x27\x79\x92\xd2\xb0\xe6\xe0\xb1\x45\xec\x61\x54\x6b" "\xf2\x6f\x2c\xdb\xa0\x2f\x46\x9f\xef\xec\x03\x69\x83\xe3\x9e" "\x02\xb0\xd7\x06\xc2\x24\xfa\x44\x6b\x9d\x1d\xb3\xed\xb8\x08" "\xdf\x9a\x1e\x79\xa2\x69\xb3\x06\x3f\x67\x1c\xc8\xc2\xad\x25" "\x6b\x11\x56\x28\x7f\x7a\x7d\x74\xfc\x77\x57\x29\x7b\xd3\x00" "\x51\x09\x51\x02\x94\x3f\x6e\xb4\x87\x45\x68\xa4\xe1\x28\x9e" "\xb4\x04\x37\xdf\x08\xc6\x03\x31\x80\xc1\x89\x0d\x5e\x0c\x80" "\x58\xac\xfa\x56\x63\xb5\x7c\x10\x1f\x3c\xdc\x45\xae\xb4\x3c" "\x0b\xe1\xfa\xd9\xad\x2b\x27\x41\x96\xd1\xa5\xf7\xd1\xc0\x1d" "\x3a\xdb\x4a\x1a\xbe\x54\xf5\xd5\xf6\xe6\xa0\x2c\xc7\x59\x07" "\x81\xe3\xd6\x2f\xc1\x52\x74\x31\x5d\x24\x69\x61\xfc\x44\x8d" "\x74\x2b\x85\xe0\x22\x9a\xf7\xcb\xd5\x01\xd6\x38\x4c\x00\x9d" "\x9c\xd2\xfa\xfc\x9d\xfc\xfb\xbf\x4c\x63\x3c\x3e\xd4\xed\x68" "\xb1\xbf\x2a\xeb\xaf\x35\x24\xe2\x14\x5f\x84\x14\xaf\xb9\x42" "\xa8\x7c\xe9\x49\xaa\x8d\x42\xf7\x0f\x4a\x81\xdb\x54\x0d\xd7" "\x37\x53\x16\xb5\x14\x4f\x1b\x97\xd6\xb4\x4b\xf9\xd2\x4b\x2d" "\x0f\xf3\xaa\xbf\x78\xb3\xf9\x50\xcc\xf4\x9f\x3a\x2e\x9f\xd9" "\x1a\x8e\x37\x7e\xd5\x20\x9e\xfd\x42\x34\xc2\x11\x82\x66\x91" "\x3d\x36\x41\x6f\xcc\x39\x4b\xd2\xd1\x6d\xfb\xd2\x5b\x84\x12" "\x4e\x86\x3c\xcb\xe8\x7d\xde\xcc\xd1\x90\xb8\xc7\xa1\x42\xe0" "\xcd\x8c\xa5\xfe\xd7\xbb\x21\x6e\x59\x84\x35\xc9\xf5\x8d\x16" "\xe2\x6b\xad\xf7\x38\xa7\x80\x5b\xb6\x07\xe7\x87\x1a\x84\xeb" "\xb2\xcc\xc2\x1b\x08\x90\x9f\xaa\xa0\x79\x34\xe4\x29\xd9\x95" "\xa5\xb8\x62\x98\x1a\xd6\x92\xa9\x07\x67\xb3\x12\xed\xc6\x2d" "\x05\x6f\xe6\x27\xbf\xba\x4a\xf7\x26\x52\xae\x4f\x78\x49\xce" "\x19\x12\xab\xec\x3a\x2f\x3f\x73\xba\x44\x67\xf5\x95\xd7\x6d" "\x27\xb2\x1a\x86\xe2\xcc\x05\x67\x1a\x29\x8c\x1a\x83\x5d\xbb" "\x98\xd5\x35\x4f\x97\x52\xf0\x29\x6c\x9d\xe6\x69\x81\x86\x91" "\xda\xff\x8b\xde\xdd\x58\x50\xda\x12\x44\xa7\xec\xab\xdb\x3d" "\x9e\x0d\x8a\xd3\x6d\x4f\xb9\x1d\x12\xab\x40\x55\xb6\x0c\xbe" "\xf4\xeb\x6a\x8f\x67\x4c\x25\xab\xe6\xa0\x43\x24\xbc\x14\x65" "\x16\x6f\xfc\x22\x2e\xfd\x17\xe0\x74\xb2\x35\x90\xf5\x21\xb9" "\x5e\x6e\x6c\x45\xa4\x10\x1e\xb1\xb7\xdd\x93\x56\xdb\xb6\xd5" "\x40\x31\x61\x7c\x88\xc5\xaa\x82\x32\x86\x6c\x17\xe2\x2b\xe0" "\xf2\x4f\x7c\x4d\x6c\x8b\x21\x9c\x6d\xd3\x09\x96\x32\x67\xfc" "\x2d\x45\xd8\x58\x96\x2c\x88\x63\x74\x00\xee\xfa\x50\x4d\x90" "\x87\x8e\xf6\xc7\x3a\x59\xae\xed\x68\xb4\xd0\x4b\xe3\xd7\xd8" "\xd5\x2f\x22\x07\xec\x91\xcd\xc1\xae\x5f\xf3\x80\x9b\x1d\xda" "\x36\x06\x04\xaf\x88\x54\xa8\x9f\x05\x42\xa0\x39\x84\x75\x17" "\xf9\x0b\xbd\xfb\x16\xd6\x97\x8e\x46\x72\x90\x38\x19\x07\x74" "\x0f\xe3\xdb\x16\x3b\xb6\x7f\x93\xb1\xc7\x24\x33\x4b\xe4\xcb" "\x09\x8b\xda\x91\x1a\xb6\x03\x0c\x46\xbe\x85\xa8\x97\xf9\xb1" "\xdd\xb3\x30\x6f\xf2\xca\xc6\xc2\x6a\x21\xfd\xe8\x76\xa8\x94" "\xe3\xe7\xeb\xcc\x00\x63\xf4\x19\xc9\x5d\xed\x5d\xad\x1b\xfb" "\xd5\x3f\x89\xef\x75\xc7\xac\x4d\xdd\x5b\x90\x9a\xa4\x09\x8f" "\x80\xd4\x12\xc2\x51\x08\x50\xe8\x5c\x41\x2c\x01\xdd\x54\x1e" "\x08\xcc\xf9\x7f\xe0\xb4\x7d\x91\x5c\x87\xb9\x1b\x0b\xab\x1d" "\x2b\x9c\xc7\xac\x6b\x96\x53\xc5\xfc\xb4\x74\x75\x60\xbd\x65" "\xd6\x49\x9a\x39\x99\x1e\xcc\x72\x2d\x20\x84\x94\xcc\x6a\x66" "\x53\xe5\x0a\x0d\x41\xbc\x40\x68\xd9\x61\xfa\x32\x07\x2b\x65" "\xec\x07\x5a\x8a\x35\xc5\x4d\x25\xf3\xf4\xe1\x78\x2f\x08\x87" "\x39\xdb\x3e\xa2\x2d\xa5\x09\xfc\xf1\x2f\x63\x54\x20\x64\xe2" "\xb7\x2d\xb6\x2a\x9c\x7c\xea\x08\x5e\x1c\x98\x0a\xcf\x05\x56" "\x7e\xca\x39\x6b\x19\xc6\xc1\x48\xeb\xb2\x4f\x23\x36\x12\xdc" "\x65\xad\x15\x9c\x3d\xb0\x09\xe2\xd5\x98\x37\x13\x42\x13\x43" "\xf2\x22\x59\xb0\x84\x2f\xdf\x24\xe5\xe3\x76\xc3\xaf\x0e\x17" "\x71\xd2\x25\x2f\xd8\x4f\xdd\x98\x48\x52\x5f\x7e\xf6\x9a\x89" "\x51\x6a\xb6\x34\x39\x5d\xd5\x31\x64\xce\x0c\x1b\x92\x2e\x35" "\x5b\x3c\x36\x20\x66\x41\xa8\x79\xed\xc0\x03\x7d\x01\x6f\x06" "\x1d\x52\xc6\xdc\xe7\x5e\xa3\x69\x3d\x40\xd8\x2e\x3c\x63\x75" "\x68\x8a\x6a\xa4\x54\x72\x4f\xbf\x56\x6b\xc1\x41\xdd\x1f\x57" "\xd0\x2d\xca\xad\xdc\x79\xe3\xe2\xce\xa2\x10\x02\x04\x6d\xb8" "\x63\x22\xe3\x5c\x59\x0d\xdb\x27\x94\x6f\x69\xe6\xec\x30\x45" "\x44\x83\xc3\x65\xfd\xec\x58\xf6\xc1\xb3\x80\x76\x18\xbe\xaa" "\xe5\xbc\xd2\x1b\xb9\xbf\xac\xe5\x23\x64\xb9\x1c\x42\x03\x12" "\x31\xfd\xcc\x7b\x15\x11\x7a\x84\xa9\xff\xb1\x36\xe3\xb4\xe9" "\x1b\x01\xcd\xcb\xdf\x72\xa6\xc0\xd1\xe6\xf9\x0f\xec\x8a\xfc" "\xe7\x94\xf2\x6d\x69\x67\xc8\xda\x92\x75\xb8\x70\xb3\xea\x5c" "\x73\xc8\x4b\x56\x89\xe1\x1b\x10\xc4\xd8\x04\xd1\x4d\x31\x52" "\x42\x4d\x2f\x25\x86\x19\xe0\xcc\xb3\x94\xd0\x5e\x7f\x1d\x72" "\x33\x0f\x23\x0d\xe4\xc3\xe8\x90\x68\x55\x98\xc5\x68\xbe\xb6" "\xb5\xa6\x99\xa2\x87\x4d\xd0\x30\x36\xbd\x6a\x19\xb0\x66\x03" "\xaa\xc4\x12\xf5\xa2\x37\x55\x9c\x1e\x76\x28\x79\xa8\x55\xc4" "\xf9\xf0\xd7\x48\xfd\x0f\x85\xc4\x60\x40\xa1\x6d\xa9\x21\x45" "\xe1\x95\x84\x88\xb4\x50\x10\xcb\x9f\x59\xe5\xb4\xde\x80\x1b" "\x63\x6d\x93\xe8\x9c\x1e\x30\x67\xa2\xae\x89\xfa\xfb\x94\x7f" "\x07\x2f\x23\x56\x8c\x84\xb1\xed\xd0\x9f\x41\x28\x1a\xb1\x6b" "\x69\x23\xd6\x69\x35\x9e\xb4\xbc\x8d\xc6\x70\x2a\xd1\xa6\xf0" "\xea\xc2\x68\xe8\x25\x88\x7f\x8b\x78\x54\x6f\xdf\xc0\x69\xe1" "\xe2\x62\xf8\x09\xb2\x40\xc5\xd6\x84\xa0\xde\xe5\x78\xa7\x90" "\x4b\xe0\x49\x9b\x3b\xeb\xd0\x69\xf1\xb7\x3e\xd0\x25\xe8\x79" "\x9d\xf7\x69\x78\xcf\xa7\x30\x07\x77\x32\x88\xdc\x6a\x83\x83" "\x5f\x7d\x2f\x8d\x53\xcc\xcd\x97\x73\xdc\x55\x16\x2e\x7f\xde" "\xac\x24\x10\x19\x74\x75\x10\xf8\xf8\x66\x51\xa9\x62\xa5\x4f" "\xad\x12\xd6\x78\xae\xe9\xc6\xb4\xb1\x30\xb0\x46\xad\xa6\x5d" "\xca\xe6\x8c\x81\x38\xfc\xfd\xea\x3b\xdb\x9c\xe3\x7d\x08\x59" "\x0f\x2c\x88\x75\xa5\x9f\x74\x91\xae\x15\x8f\xa4\x8c\x82\x62" "\xa9\xb8\x0c\x5e\x58\xdb\x43\xb2\xb6\xa8\x79\x1e\x2b\x24\x23" "\x7b\xd1\xe7\xa8\x6f\xe0\x72\xba\x0c\x83\xca\x02\x74\x64\x38" "\x95\xdf\x3b\x4a\x73\x04\x09\xda\x33\xdb\x3d\x77\x7a\xaa\x81" "\x89\xc7\xfe\xdd\xcb\x3d\x5a\x8e\x3f\xb0\x27\x54\x3b\x75\x9f" "\x9c\x49\xa5\x72\x20\xe0\xd0\x37\xea\xc4\x67\x8e\xe6\xab\x6a" "\x9a\x50\xa8\x35\xb5\xe8\x6b\x6c\x7e\xc7\xf5\x3c\xd6\xd0\xbc" "\x3c\x9c\xb4\x6e\x3c\x98\x3f\x1a\xe9\x6a\xd2\xbc\x75\x4a\x42" "\xe6\x47\xce\x2a\x65\x36\x33\xf1\x31\xc6\x89\x0e\x4f\x4b\x0b" "\xef\x4a\xa2\x7c\x65\xe9\xad\x28\xc0\x0e\x6c\x11\xf5\x50\x4f" "\xb6\x8a\x67\xad\x71\x77\x00\x96\x5a\xa4\xbb\x51\xa4\x4c\x77" "\x08\xbc\x40\x61\x58\x92\x93\x04\xaa\x7c\x0a\xbe\xfe\xb4\x16" "\xdc\x76\x9d\x66\x72\x77\xd1\x97\x27\x07\x8a\x57\xe7\x49\x12" "\xa9\x7d\x1b\xf8\xd8\x7e\xed\xfa\xf7\xe4\x5f\x90\x2b\x45\xa7" "\xc3\x5c\x8e\xb9\x92\x02\xbc\x56\x37\x3c\xc8\x4f\xa5\xd6\x85" "\xeb\x9f\xee\x01\x30\x71\x44\xa3\xda\xa6\xd5\xdf\x34\x8c\x31" "\x48\x60\xaf\x17\x43\x31\x12\x0b\xaa\x10\x0b\x3e\x8c\x6e\x41" "\x15\xc6\xb0\xd2\xbc\xc7\x7c\x7f\xc0\x4f\x39\xc7\xf5\xda\x3f" "\xbb\xd9\x86\x45\x47\x1f\x8a\x5c\x46\xad\x68\xd5\x3b\x8a\xb0" "\xe6\x1b\xc6\xfb\x0f\x70\x89\xd8\x10\x2d\xcb\xb9\xf3\xa3\xd4" "\x23\xd5\xb1\xb5\x9b\x92\x8b\xe2\x40\x85\xec\xf6\x71\xc2\x45" "\x4b\x31\xa5\xcb\xc5\x46\x5a\x98\xfb\x48\x9d\x42\x06\x51\x0c" "\x1f\x39\xfa\x7b\xe9\x39\x3f\x06\xa5\xe4\xc8\x92\x43\x65\xff" "\x4e\xa4\x6d\x97\xd6\xc4\x62\x2d\x00\x5c\x71\xde\x47\x5a\x99" "\x3f\x3b\xf9\xcf\xc5\xa8\xe8\xf8\x8f\x79\x62\x8a\xde\xcc\x3e" "\x25\x55\x02\x05\x73\x24\xf2\x3f\xd8\xbd\x70\xb8\xa3\xed\xab" "\x08\xad\xff\xf7\x35\x2e\x0f\xfb\x45\xe6\xd3\xfd\xdf\xaa\x6e" "\xc1\x33\x69\xf2\xf8\x40\x5f\xda\x84\x70\xbe\x1d\xf2\xd6\x56" "\x91\xf0\x24\x33\x89\xf3\x52\x0c\x84\x1f\x0f\xf5\xcb\x1c\x44" "\xa5\x5d\xbc\x9b\xc1\x7c\xbc\x00\x26\xec\x46\x9a\x3b\x25\xa1" "\x62\xa0\xd7\x72\x31\xe6\x7a\xa6\xf4\xed\xb3\x8b\x3b\x44\xca" "\x86\x8a\x3a\xc3\x2f\x86\x62\xfc\x55\x56\x2f\x96\x99\x1b\x1e" "\xf1\xb6\xd2\x95\x03\x7f\xa4\x55\x6a\xa4\x7b\xbf\xbb\x53\xc8" "\xfa\x46\x65\xab\x09\xd0\xe4\x92\x69\x4e\x55\x1a\x6b\xab\x64" "\xd5\x6b\x16\xc0\x08\x3f\x62\x23\x7a\xad\x47\x95\xe1\x75\x2f" "\x44\xac\x11\x3a\xaf\x2a\x6f\xb4\x30\xf5\x4f\x68\x7f\x41\x3e" "\x27\x62\x1b\x25\x5d\x0a\xa5\xc4\x4f\x17\xaf\x13\x7a\xff\x48" "\x18\xe0\xc6\x15\x9b\xa4\xa8\x34\x81\xa3\x4d\x86\x3d\xc4\xb1" "\x5a\xf4\x7e\x86\x7b\x00\x62\xae\x68\x03\x90\x29\x4c\xa0\xa8" "\xa1\x73\x8c\xf8\xd7\x03\x96\xab\xd2\xdc\xd0\xf7\x45\x87\x7e" "\xe1\xee\xf0\x9d\x42\x53\x8b\x15\xc1\xb4\xab\x45\x59\x5a\x40" "\x58\xf5\xa4\xda\x26\xd0\x40\x8f\xd0\xc0\x85\xdb\xa0\x23\x94" "\xef\xd3\xb8\x6a\x60\x1c\x4a\x97\x8f\x91\x68\x70\xec\x1c\x97" "\x62\x97\x40\x99\xb9\x3a\x9b\x52\x60\x3c\xb2\xdc\xc6\x4a\xec" "\x7e\x2a\x22\x82\x57\x81\x81\xfd\x2c\xed\xc6\x83\x41\x62\x3c" "\x90\xd1\xc2\xfc\xa9\x09\x8f\x42\xe6\xd1\xfa\x65\x41\xf5\x08" "\xb6\x3d\xe5\x77\x9b\x8f\xce\xd9\x9c\x88\xc1\x6d\x8b\x7b\x73" "\x92\x12\x80\x7c\x2e\x79\xd7\x5d\x30\x2a\x3d\xbf\x2b\x60\x84" "\xa5\xf8\x5d\xd7\xeb\x1a\x58\x79\xb5\xa4\x0c\x2b\x20\xa5\xbc" "\x01\xce\xd8\xd5\xd6\x45\xb3\x79\x29\xde\x62\x3f\x04\x57\x57" "\xa7\x88\x2f\xe7\x07\x21\x4c\x8d\xe7\x52\xc7\xe1\xa5\x12\x19" "\x5f\x0f\x19\x9e\x92\xdd\xb3\xc5\x10\x46\xea\xfc\xe1\x59\xc4" "\xe8\xb6\x22\xd3\x1f\x2d\x9d\x7f\xdc\xc9\x96\xf2\x7e\xdf\xbc" "\xe8\xff\x86\x3d\x93\x5b\x4d\x59\xa7\x8a\xad\x09\x73\x3c\x62" "\x77\x25\x9d\xb7\x8d\x61\xcd\x21\x67\x34\x7e\xe2\x1a\x6b\x69" "\xb1\x3b\x10\x68\x85\x9c\x9b\x86\x44\x96\x36\xb1\x15\x92\x29" "\x18\x6a\x86\x39\x28\x0b\xb8\xc3\x60\x12\xc5\xac\x35\xa3\x35" "\xf6\xb1\xb3\xdf\x00\xfb\x3a\xed\xca\x46\x7d\x8f\xa3\x4d\x77" "\x05\xd7\xb8\xa8\xe3\xca\xdd\xfe\x2d\x12\x5b\x08\xd4\x36\xa1" "\xa0\x07\xa8\x2d\x31\x2f\x8a\x0d\xec\x07\x8a\xe0\x31\x0f\xb4" "\xb1\x51\x60\xa8\xc7\x5b\x3f\x83\xf2\xfb\x4d\x2a\x24\xf3\x52" "\x2c\xa1\x83\x58\x08\x03\xdf\x04\x6c\x40\x1e\x25\x83\x0c\x74" "\xc2\x93\x89\xc1\x31\x74\x8f\x77\xbb\x7b\x78\x15\x26\x06\x89" "\xe7\x47\x04\x22\x14\x28\xfc\xf7\xae\xfc\xd9\xbc\x95\x5d\x92" "\x42\x52\x7a\x94\x85\x3f\x11\xdb\xca\xc7\xa8\x62\x30\xaa\x66" "\x1a\xf4\xd5\x1d\xf1\x4d\xba\x53\xce\xda\x63\xa4\x4f\x30\xfe" "\x04\x1d\xf4\x5e\x9c\x4a\x83\xf3\xc7\x58\x71\xea\xd2\x1b\x26" "\x66\x8c\x90\xfe\xae\x82\x43\x97\x79\x1d\x6c\x21\x1f\xc1\x19" "\x89\xc8\x15\xc4\x7a\x06\x3e\x98\x11\x71\xc0\x70\x45\x19\xed" "\x2a\x31\x28\x54\xda\x36\xe3\x38\x3a\x70\x60\xd1\xc2\xa7\xfc" "\x08\x46\x0b\x82\xf2\x48\x74\x82\xce\x74\xf1\x0e\xaf\x11\x99" "\x73\xcc\x70\x73\x3a\xcb\x07\x1a\xe6\x88\x1d\xd6\x11\x0f\x06" "\xc9\x93\x92\x0d\xbf\xb9\xd6\x7f\x17\x9f\xb7\x6a\xb4\x23\x37" "\x84\x10\xe4\x70\xf6\x64\x30\x7f\xe3\x01\x31\x4d\x67\x1a\x43" "\x7e\xe0\x7f\x32\xd6\x32\x9d\xfd\x77\xcf\x84\x69\x52\x28\xd0" "\xb0\x50\x7d\x8b\x92\x28\x0e\x44\xa8\x4c\x27\x79\x70\xed\x44" "\xd4\x42\xc6\x6e\x57\xfa\xe7\x0a\x2c\xf8\x23\x8b\x1d\x01\xcd" "\x24\x4e\x51\xb3\x81\xa7\x76\x49\x0f\x51\x23\x87\xab\x32\x14" "\xb3\xb3\x01\x37\x8f\x24\x5a\x21\x50\xbe\x0a\x6d\xfc\xb0\xd9" "\x8d\xf7\xe3\x56\xee\x24\x00\xaa\x76\x6c\xfd\x44\x44\xb4\xd1" "\x56\xe8\x45\xb9\xd8\x11\x40\x12\x62\x80\x15\xfe\xcf\x04\x2b" "\xe7\xbb\x34\x2c\xa1\x5e\x62\x6d\x1d\xa0\xd2\xd5\xcd\x1a\x4c" "\x66\x1e\x18\x1d\xf3\x9d\x29\x75\x13\xc9\x46\x2a\xe4\xf3\xfa" "\xbf\x3c\xce\x8b\xe1\xf1\xb5\x53\xe4\xfb\xed\x88\x14\xfe\xf6" "\xaf\x6d\xb0\xe1\xe4\x3f\x4a\x1b\x75\xa5\x76\x1e\xda\xf2\xe7" "\xff\x08\xed\xe9\xcd\xf2\x3b\x3e\x54\x06\x93\x23\x27\xfb\x64" "\x06\x92\x14\xee\x0a\x0b\xcd\x31\x43\x23\x0f\xad\x00\x8f\x4a" "\xe2\xa2\xaf\x97\xbd\xa4\xc7\x6d\x48\x64\xb4\x68\xea\x38\x2f" "\xf3\xd1\x3a\xc8\x71\x6b\x06\x98\x40\xd2\x5a\xb9\x8e\x49\x88" "\x65\xb5\xa5\x9f\xed\x16\x30\x3c\x9a\xe0\xf0\xbc\xce\xd1\x50" "\x3a\xee\x68\x08\x97\xea\x64\x66\x41\x05\x67\x1e\xc1\x03\xf7" "\x9c\x75\xff\x66\xb5\xf7\x8a\x55\x73\x49\x1e\x75\xde\xe5\x13" "\x77\x60\x2e\x7a\xc2\xd9\xf7\xbe\xe9\xc0\xd1\x97\xfc\x21\xe8" "\x2f\xf1\x67\xa2\xcf\x5c\x48\x7b\x28\x95\x81\x3c\xa7\x75\xd3" "\x17\x78\xf1\xde\xb6\x02\xd1\xce\x1f\x85\xc2\xba\x59\xf1\xad" "\x84\x35\x4b\x06\x68\xbd\x1d\x32\xe2\x87\xb1\x95\xee\xbf\x0d" "\xf0\xc9\x4a\x64\xc8\x93\x61\xa7\x8f\xe0\x5b\x78\xc9\xc2\x31" "\x5d\xc2\x9e\x39\x2c\x86\x8c\xe4\xd5\xb4\x89\x76\x67\x37\x31" "\x0e\xfa\x4f\xe5\x8c\x92\x31\xde\xe8\xf9\xbb\x46\x4a\xf2\xfc" "\xfc\x16\x87\xf0\x90\x6b\xce\x41\x66\x0a\x9b\x4e\xd0\x5d\xe2" "\xb9\x21\xd6\x47\x50\x28\xd1\xa4\xee\x89\x1d\xdb\x25\x85\xae" "\xd6\xef\x47\xea\x60\xc1\xdd\x0e\x93\x38\xac\xec\xfe\xcc\x8d" "\x81\x3e\x15\xd4\xf0\xbc\x56\xa6\xd2\xd3\xdc\xa7\x1a\x06\x96" "\x95\x6e\x60\x15\x2f\xf3\x72\xb5\x3a\x3f\x60\x69\x2f\x90\x1b" "\xd5\xf8\x3d\xc3\x28\x72\x80\x4c\x5d\x47\xc6\xc9\x63\x21\x88" "\xcb\x56\xf2\x44\xd2\x5a\xfd\xd8\x99\x9d\x8b\x39\xb2\x6f\xbc" "\xb9\x12\x92\x97\x20\x6a\xc6\x76\x89\xfb\xf6\xdc\x1d\xdd\xad" "\x55\xa2\xf9\x50\x88\xc1\xc5\x53\xa2\xc0\x3a\x48\x63\x34\x53" "\x48\xee\xbd\x5c\x0e\x2a\x22\x20\xb3\x7a\x2b\xbc\x0c\xa5\xb6" "\xd2\x75\xb8\x0c\xbb\x18\x54\xdf\x28\xb3\xaa\x4e\x7f\x02\xae" "\x18\x56\x74\x49\x23\xd5\x77\xcb\x1f\x02\x41\xdb\x08\x46\x19" "\xcb\x95\xd9\x3e\xa1\x78\x3b\x43\x29\xb8\xef\x62\x60\x89\x56" "\x8d\xfe\xf0\xee\x89\x01\xe4\x7f\x96\x63\xdc\xde\x3e\x98\x39" "\x71\x91\x64\xef\xea\x6f\x3e\xec\xcd\x01\xa3\xd9\xec\xe2\x14" "\xd1\xc0\x3f\x3d\x30\x65\xa8\x47\x74\xe0\xd9\x66\x13\xf9\x76" "\x41\x92\xb5\xc6\x14\xc7\x0a\xdc\xd7\x09\x70\x67\xdd\x98\xbb" "\x0f\x83\x59\x88\x6b\x3c\x2a\x61\xd5\xf8\x4c\x40\xf3\xa2\x50" "\x77\xeb\x20\x88\x33\x88\xbd\xb4\xb9\x1f\xf5\xe7\xb1\x11\x98" "\xdf\xae\x06\x40\xcc\x09\x5c\x03\xdc\xd3\xdc\x7d\xae\x78\xfd" "\x75\x44\xb9\x44\xeb\xf7\xc3\xed\xb8\xc1\x64\x81\x5c\xac\x96" "\x75\x39\x8b\xc6\x83\xc9\xa6\x46\xa5\x9b\x60\xab\xe5\x1d\xb9" "\x7c\x86\xab\x93\x3d\x64\x40\x17\xaf\xa7\xe1\xdb\x9e\xc2\xd6" "\x4c\x31\xed\xaa\xc5\x57\x0f\x8f\x90\x99\x69\x50\xe5\xef\x3e" "\x77\xea\xce\xf6\x3a\xe6\x3e\x92\x97\xcc\x63\x7a\x8e\x40\x8d" "\x96\x6a\xa9\x42\x27\x91\x8e\xcf\xd7\x76\x57\x6d\x3b\x40\xf7" "\x93\x83\x23\x74\x7c\xec\x37\x88\xca\xb2\x3d\x70\xb3\x76\x86" "\xb8\x3a\xe7\x6b\x16\xb8\xc0\x14\xbc\x37\x0e\xbd\x85\xf8\xed" "\x50\xc9\xc6\x80\x75\x48\x56\x9d\xba\x04\x77\xe6\x57\x72\xbc" "\xc8\x66\x63\x81\x41\xac\x79\x17\xa7\xb1\x93\x91\x6e\x48\x74" "\x49\x18\x73\x84\x24\x23\xc6\x07\x2e\xe0\xe2\x16\xce\x1f\x9f" "\xfb\x6a\x46\x49\xcc\xc1\x3f\xc4\xef\x4d\x88\x2d\x4e\x40\x45" "\x80\x9e\xa0\x90\x52\x68\xe7\x86\xe4\x3d\x53\x82\xf9\x2d\x2f" "\x5f\x2b\x32\x47\x9e\x25\x51\xa8\xc6\xd6\xc1\x37\xb9\xd1\x25" "\xfc\xba\x48\xd8\x8f\xd6\xae\x44\xb8\x72\x7f\xa7\x65\xb8\xe2" "\x05\x2d\x3d\x4b\x2b\xcf\x5b\x83\xb4\x1b\x3f\x8b\xfb\x1e\x0e" "\x13\x28\x13\x31\x45\x11\x35\xb8\xbe\x09\xbb\x21\xdc\x12\x1a" "\x94\x99\x4a\x74\x9c\xc6\x4e\xbd\xd2\xa6\x68\xa5\x67\x3e\x25" "\x3d\x58\x59\xee\x0e\x7c\x75\x48\xb9\x62\x27\xe5\x48\xf0\x66" "\x31\x61\x20\xec\xa0\xc3\xf7\x91\xc4\xf5\x2c\x32\x2e\x91\x89" "\xce\x16\x75\xc2\xd1\x9e\x90\x3a\x7b\xc8\x07\x3f\x12\xb0\x1d" "\x04\xcc\x72\x9b\x01\x4a\x8d\x7e\x78\xe6\xd6\xe0\xc1\x3b\xf5" "\xd4\x78\x5c\x53\x0f\x54\xa4\x11\xd5\x85\x7c\xf7\x8d\x41\x88" "\x22\x79\x39\x83\x68\x76\xd0\xa9\xd0\xa3\xa4\xc8\x33\xad\x13" "\x0e\x14\xd4\x3a\x9d\x2a\x0b\x12\x5b\x98\x9d\xf9\xa6\xb0\x25" "\xed\xb5\xe7\x21\x69\x77\x87\xec\xb1\xfe\xd7\xe5\xa9\x8f\x09" "\xe2\x40\xb3\x19\x2c\xe7\x08\x40\x9e\x49\xe1\x8d\x5e\x75\xbe" "\xf1\x0f\x47\x02\x18\xd2\x3d\xfa\xbf\x0c\xaf\xc7\x1c\x59\x07" "\xf8\x44\x6a\x26\x35\x51\x31\x7a\xc5\xbf\x57\xb7\xa1\xa8\x6a" "\x71\xe0\xd9\x43\xcd\x7a\x9d\x15\xb0\xfc\x21\xfe\x78\xab\x4d" "\x01\xba\x70\x3c\xaa\x46\x47\x25\xdd\xa0\x93\x9f\x56\xa7\x62" "\x21\xe1\xd9\xae\xab\x35\xf5\xb7\x7c\xc5\xf2\xea\xac\x39\x02" "\xd9\xd4\x66\xd8\xc2\x8e\xf1\x5a\x6c\x87\x82\x5a\xeb\xbb\xeb" "\x8f\x71\xd2\x68\x8e\xc7\xa2\xb8\xcd\x4b\x72\x3e\x1d\x24\x0b" "\x91\x82\xeb\xf1\x66\xac\x6b\xb6\xa2\x9a\xa7\xa8\x79\xf9\x0d" "\xaa\x14\xbd\x6d\x85\x2c\x89\x6d\x86\x8e\xfa\x03\x0c\x10\xec" "\xdb\x1e\xff\xa4\x6b\x52\x65\x4f\x0e\x2b\x0f\xce\x29\x32\xc2" "\x1f\xfa\xd7\x99\x3e\xb9\xa7\xb0\x47\x51\x1a\x2f\x32\x56\x93" "\x03\x89\xd6\x0e\x09\x18\x13\x48\x8a\xb0\xc2\xae\x50\xc5\xf3" "\xcb\xd0\x13\xec\x7e\x83\x34\xe1\xf9\x94\xbf\x45\xf0\x32\xe4" "\x9e\x0f\xd2\x52\x27\xd4\x51\x85\x99\x5e\x55\xc0\x7d\x40\xe5" "\x46\x02\xed\xa4\xd6\xe6\x1a\xde\xaf\x5b\x6f\x53\x6c\x4b\x0e" "\xd9\x49\x74\xb9\xf9\xf2\xf3\x19\xb1\xb7\xa6\x98\xfc\xde\x10" "\x55\x57\x07\xc9\x54\xa9\xf8\xb6\xa8\x75\x96\x76\x56\xe7\x74" "\x39\x28\x73\x33\x25\xa3\x57\xa4\xd2\xd7\x36\xd9\x2f\x20\x1f" "\xf5\x41\x21\x6b\x9e\x88\x8f\xaf\x3d\xe7\x3d\xe7\x9d\x3d\x97" "\xf4\xd0\x5e\x65\x7f\xaa\x1e\xc9\xd4\x55\xee\x42\xac\x8e\x3f" "\x6b\x5a\xa8\xe2\x93\x50\xca\x85\xb5\x84\x80\xc6\xb5\xe2\x12" "\x34\xe2\x5b\xbe\x40\x68\x2a\xfb\x0f\x0d\xa5\x53\xe8\xe9\x3c" "\x11\xab\xd9\x08\x38\x4c\x6b\x74\x9b\x58\x39\xbe\x72\x6b\x01" "\x53\xea\x95\x6a\x43\xaf\x4c\x0c\xa6\x65\xde\x90\xaa\x48\x61" "\x19\x9b\xce\xa6\x40\xf1\x07\x89\x31\xe8\x02\x9a\x0d\xb1\x02" "\x0c\x72\x93\xbe\xd0\x2b\x37\xe6\x4b\x0b\x47\xf4\x03\x8e\x2f" "\x5d\x37\x61\x2d\x0d\xeb\x9c\xe5\x58\xbc\xb4\x25\xb4\x4c\xab" "\xd3\xe7\xae\x13\xd8\xd0\xc9\x68\x0c\xad\x27\x9d\x01\xbd\x12" "\xe2\xa5\x42\xc7\x60\x90\x7c\x44\xe7\xe4\xfc\x72\x20\x75\xb2" "\xe7\x72\xd3\x8e\x84\xf4\x1d\x1c\x40\x27\x7a\xcf\xc1\xf8\x66" "\x0f\xcf\xaf\xec\xac\x26\x06\x12\x1d\x7e\x56\x96\x5a\x0e\x02" "\xc2\xd9\x4c\x43\x76\x10\x77\x65\x2d\xaa\x73\xa7\xda\xcb\x09" "\x36\xa2\x0d\x2c\x4a\xde\x0b\x08\x47\x3b\xca\x50\x1f\x67\xe4", 4095); struct csum_inet csum_67; csum_inet_init(&csum_67); csum_inet_update(&csum_67, (const uint8_t*)0x20df2fe8, 4); csum_inet_update(&csum_67, (const uint8_t*)0x20df2fec, 4); uint16_t csum_67_chunk_2 = 0x2100; csum_inet_update(&csum_67, (const uint8_t*)&csum_67_chunk_2, 2); uint16_t csum_67_chunk_3 = 0x1000; csum_inet_update(&csum_67, (const uint8_t*)&csum_67_chunk_3, 2); csum_inet_update(&csum_67, (const uint8_t*)0x20df2ff0, 16); *(uint16_t*)0x20df2ff6 = csum_inet_digest(&csum_67); struct csum_inet csum_68; csum_inet_init(&csum_68); csum_inet_update(&csum_68, (const uint8_t*)0x20df2fdc, 20); *(uint16_t*)0x20df2fe6 = csum_inet_digest(&csum_68); r[69] = syz_emit_ethernet(0x1031ul, 0x20df2fceul); break; case 5: *(uint8_t*)0x20df2fce = (uint8_t)0xbb; *(uint8_t*)0x20df2fcf = (uint8_t)0xbb; *(uint8_t*)0x20df2fd0 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd1 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd2 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd3 = (uint8_t)0x0; *(uint8_t*)0x20df2fd4 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd5 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd6 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd7 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd8 = (uint8_t)0xbb; *(uint8_t*)0x20df2fd9 = (uint8_t)0x0; *(uint16_t*)0x20df2fda = (uint16_t)0x8; STORE_BY_BITMASK(uint8_t, 0x20df2fdc, 0x5, 0, 4); STORE_BY_BITMASK(uint8_t, 0x20df2fdc, 0x4, 4, 4); STORE_BY_BITMASK(uint8_t, 0x20df2fdd, 0x0, 0, 2); STORE_BY_BITMASK(uint8_t, 0x20df2fdd, 0x0, 2, 6); *(uint16_t*)0x20df2fde = (uint16_t)0x1c00; *(uint16_t*)0x20df2fe0 = (uint16_t)0x6400; *(uint16_t*)0x20df2fe2 = (uint16_t)0x0; *(uint8_t*)0x20df2fe4 = (uint8_t)0x0; *(uint8_t*)0x20df2fe5 = (uint8_t)0x11; *(uint16_t*)0x20df2fe6 = (uint16_t)0x0; *(uint8_t*)0x20df2fe8 = (uint8_t)0xac; *(uint8_t*)0x20df2fe9 = (uint8_t)0x14; *(uint8_t*)0x20df2fea = (uint8_t)0x0; *(uint8_t*)0x20df2feb = (uint8_t)0xbb; *(uint32_t*)0x20df2fec = (uint32_t)0x10000e0; *(uint16_t*)0x20df2ff0 = (uint16_t)0x204e; *(uint16_t*)0x20df2ff2 = (uint16_t)0x224e; *(uint16_t*)0x20df2ff4 = (uint16_t)0x800; *(uint16_t*)0x20df2ff6 = (uint16_t)0x0; struct csum_inet csum_102; csum_inet_init(&csum_102); csum_inet_update(&csum_102, (const uint8_t*)0x20df2fe8, 4); csum_inet_update(&csum_102, (const uint8_t*)0x20df2fec, 4); uint16_t csum_102_chunk_2 = 0x1100; csum_inet_update(&csum_102, (const uint8_t*)&csum_102_chunk_2, 2); uint16_t csum_102_chunk_3 = 0x800; csum_inet_update(&csum_102, (const uint8_t*)&csum_102_chunk_3, 2); csum_inet_update(&csum_102, (const uint8_t*)0x20df2ff0, 8); *(uint16_t*)0x20df2ff6 = csum_inet_digest(&csum_102); struct csum_inet csum_103; csum_inet_init(&csum_103); csum_inet_update(&csum_103, (const uint8_t*)0x20df2fdc, 20); *(uint16_t*)0x20df2fe6 = csum_inet_digest(&csum_103); r[104] = syz_emit_ethernet(0x2aul, 0x20df2fceul); break; } return 0; } void test() { long i; pthread_t th[12]; memset(r, -1, sizeof(r)); srand(getpid()); for (i = 0; i < 6; i++) { pthread_create(&th[i], 0, thr, (void*)i); usleep(rand() % 10000); } for (i = 0; i < 6; i++) { pthread_create(&th[6 + i], 0, thr, (void*)i); if (rand() % 2) usleep(rand() % 10000); } usleep(rand() % 100000); } int main() { setup_tun(0, true); loop(); return 0; }
the_stack_data/125140109.c
/* * fake-rand48.c -- * Fake the *rand48 functions based on srand() and rand() * (for systems that don't have them) * * $Header: /home/srilm/CVS/srilm/misc/src/fake-rand48.c,v 1.2 2005/07/29 03:23:57 stolcke Exp $ */ #ifdef NEED_RAND48 #include <stdlib.h> void srand48(long seed) { srand((int)seed); } long lrand48() { return rand()*(RAND_MAX + 1) + rand(); } double drand48() { return (double)rand()/RAND_MAX; } #endif /* NEED_RAND48 */
the_stack_data/115766435.c
// Generated file. DO NOT EDIT! // aom_dsp_encoder_ssse3 needs a c file to force link language, // or to silence a harmless CMake warning: Ignore me. void aom_dsp_encoder_ssse3_dummy_function(void) {}
the_stack_data/211080743.c
/* c [rogram to split a file into equal parts */ #include <stdio.h> #include <string.h> #define MAX 256 int main() { int i = 0, line = 0; FILE *fp1, *fp2, *fp3; char file1[MAX], file2[MAX], file3[MAX], str[MAX]; /* get the name without file format(.txt) from user */ printf("Enter your input file name:"); scanf("%s", file1); /* form the output file names */ sprintf(file2, "%s_part_%d.txt", file1, 1); sprintf(file3, "%s_part_%d.txt", file1, 2); strcat(file1, ".txt"); /* open the input file in read mode */ fp1 = fopen(file1, "r"); /* error handling */ if (!fp1) { printf("Unable to open input file in read mode!!\n"); return 0; } /* open the output file in write mode */ fp2 = fopen(file2, "w"); /* error handling */ if (!fp2) { printf("Unable to open output file in write mode\n"); fclose(fp1); return 0; } /* open the output file in write mode */ fp3 = fopen(file3, "w"); /* error handling */ if (!fp3) { printf("Unable to open output file2 in write mode\n"); fclose(fp1); fclose(fp2); return 0; } /* calculate the number of lines in input file */ while (!feof(fp1)) { fgets(str, MAX, fp1); if (!feof(fp1)) line++; } /* moving the file pointer to the start of file */ rewind(fp1); /* writing first half of data to first output file */ while (i < line/2) { fgets(str, MAX, fp1); if (!feof(fp1)) { fputs(str, fp2); } i++; } /* writing second half to second output file */ while (!feof(fp1)) { fgets(str, MAX, fp1); if (!feof(fp1)) { fputs(str, fp3); } } /* close all opened files */ fclose(fp1); fclose(fp2); fclose(fp3); /* remove the input file */ remove(file1); return 0; }
the_stack_data/154830587.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2015 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Simple string test */ /* Windows 32 bit implementation */ # if (defined(_WIN32)) # if (!defined (_M_X64)) # define WIN_CODE(...) __VA_ARGS__ # define WIN32_CODE(...) __VA_ARGS__ # define WIN64_CODE(...) # define LINUX_CODE(...) # define LINUX32_CODE(...) # define LINUX64_CODE(...) # else /* Windows 64 bit implementation */ # define WIN_CODE(...) __VA_ARGS__ # define WIN32_CODE(...) # define WIN64_CODE(...) __VA_ARGS__ # define LINUX_CODE(...) # define LINUX32_CODE(...) # define LINUX64_CODE(...) # endif # else /* Not windows, presumably a GNU compiler and (likely) Linux */ # if (!defined (_M_X64)) # define WIN_CODE(...) # define WIN32_CODE(...) # define WIN64_CODE(...) # define LINUX_CODE(...) __VA_ARGS__ # define LINUX32_CODE(...) __VA_ARGS__ # define LINUX64_CODE(...) # else /* Linux 64 bit implementations */ # define WIN_CODE(...) # define WIN32_CODE(...) # define WIN64_CODE(...) # define LINUX_CODE(...) __VA_ARGS__ # define LINUX32_CODE(...) # define LINUX64_CODE(...) __VA_ARGS__ # endif # endif static void movsb (char * dest, const char * src, int len, int decrement) { if (decrement) { WIN_CODE ( __asm std ) LINUX_CODE (__asm__ volatile ("std");) } WIN32_CODE ( __asm mov esi, src __asm mov edi, dest __asm mov ecx, len __asm rep movsb ) WIN64_CODE ( __asm mov rsi, src __asm mov rdi, dest __asm mov rcx, len __asm rep movsb ) LINUX_CODE( __asm__ volatile ("rep movsb" :: "S"(src),"D"(dest),"c"(len) : "memory"); ) if (decrement) { WIN_CODE ( __asm cld ) LINUX_CODE (__asm__ volatile ("cld");) } } static void movsd (void * dest, const void * src, int len, int decrement) { if (decrement) { WIN_CODE ( __asm std ) LINUX_CODE (__asm__ volatile ("std");) } WIN32_CODE ( __asm mov esi, src __asm mov edi, dest __asm mov ecx, len __asm rep movsd ) WIN64_CODE ( __asm mov rsi, src __asm mov rdi, dest __asm mov rcx, len __asm rep movsd ) LINUX_CODE( __asm__ volatile ("rep movsd" :: "S"(src),"D"(dest),"c"(len) : "memory"); ) if (decrement) { WIN_CODE ( __asm cld ) LINUX_CODE (__asm__ volatile ("cld");) } } /* Use repne scasb to calculate length of a string. */ static int length(const char * src, int maxlen) { const char * s = src; WIN32_CODE ( __asm mov edi, src __asm mov al, 0 __asm mov ecx, maxlen __asm repne scasb __asm mov src, edi ) WIN64_CODE ( __asm mov rdi, src __asm mov al, 0 __asm mov rcx, maxlen __asm repne scasb __asm mov src, rdi ) LINUX_CODE( __asm__ volatile ("xor %%al,%%al; repne scasb" : "=D"(src) :"0"(src),"c"(maxlen): "%eax"); ) return src-s; } static int cmps (const char * s1, const char * s2, int maxlen, int decrement) { int res = 1; if (decrement) { WIN_CODE ( __asm std ) LINUX_CODE (__asm__ volatile ("std");) } LINUX_CODE( __asm__ volatile ("repz cmpsb\n" "cmovz %2,%0\n" "jge 1f\n" "neg %0\n" "1:" : "=r"(res) :"0"(res),"r"(0), "S"(s1),"D"(s2),"c"(maxlen) ); ) if (decrement) { WIN_CODE ( __asm cld ) LINUX_CODE (__asm__ volatile ("cld");) } return res; } /* Use rep stosb to fill a chunk of store. */ static void fill(char * target, char value, int count) { WIN32_CODE ( __asm mov edi, target __asm mov al, value __asm mov ecx, count __asm rep stosb ) WIN64_CODE ( __asm mov rdi, target __asm mov al, value __asm mov rcx, count __asm rep stosb ) LINUX_CODE( __asm__ volatile ("mov %1,%%al; rep stosb" : "=D"(target) :"m"(value),"c"(count),"0"(target): "%eax", "memory"); ) } int copyAndTest (int * dest, int * src, int len,int df) { int i; int failed = 0; memset(dest, 0xff, (len+2)*sizeof(int)); for (i=0;i<len;i++) src[i] = i; dest = dest + 1; if (df) movsd (dest+len-1, src+len-1, len, df); else movsd (dest, src, len, df); // Compare the results for (i=0;i<len;i++) { if (src[i] != dest[i]) { failed++; printf ("***Failed : copy %p to %p for %d %swards, at dest[%d] see %d not %d\n", src,dest,len,df ?"back":"for",i, dest[i], src[i]); } } if (dest[-1] != -1) { failed++; printf ("***Failed : %swards, overwrote below base (%d)\n", df ?"back":"for", dest[-1]); } if (dest[len] != -1) { failed++; printf ("***Failed : %swards, overwrote above top (%d)\n", df ?"back":"for", dest[len]); } return failed; } int testMovsd() { enum { length = 121 }; int * s1 = (int *)malloc (length * sizeof(int)); int * d1 = (int *)malloc ((length+2) * sizeof (int)); int df; int failures = 0; for (df=0; df<2; df++) { failures += copyAndTest(d1, s1, length, df); } printf ("%d failures in testMovsd\n", failures); return failures; } int doCmpsTests() { const char * s1 = "abcdefg"; const char * s2 = "abcdefh"; const char * s3 = &s2[1]; int df = 0; int results[4]; int failures = 0; printf ("s1 : '%s' @%p\n" "s2 : '%s' @%p\n", s1,s1,s2,s2); for (df = 0; df <2; df++) { int d1 = df ? 6 : 0; int d2 = df ? 5 : 0; printf ("DF = %d\n", df); results[0] = cmps (s1+d1,s1+d1,7,df); results[1] = cmps (s1+d1,s2+d1,7,df); results[2] = cmps (s2+d1,s1+d1,7,df); results[3] = cmps (s3+d2,s2+d2,6,df); printf ("cmps (%s,%s) = %d, should be 0\n",s1,s1,results[0]); printf ("cmps (%s,%s) = %d, should be -1\n",s1,s2,results[1]); printf ("cmps (%s,%s) = %d, should be 1\n",s2,s1,results[2]); printf ("cmps (%s,%s) = %d, should be 1\n",s3,s2,results[3]); failures += results[0] != 0; failures += results[1] != -1; failures += results[2] != 1; failures += results[3] != 1; } return failures; } int doTest() { const char * src = "Hello World"; char dest[50]; char d1[101]; int len = strlen(src)+1; int i; int failures = 0; movsb (&dest[0],src,len,0); printf ("Result after copy '%s'\n", dest); if (strcmp(dest,src) != 0) { printf ("*** Copy failed ***\n"); failures++; } memset (dest, 0, sizeof(dest)); movsb (&dest[len], &src[len], len+1, 1); printf ("Result after reversed copy '%s'\n", dest); if (strcmp(dest,src) != 0) { printf ("*** Copy failed ***\n"); failures++; } printf ("src = '%s'\n", src); i = length(src, 1024); printf ("Length gives %d\n", i); movsb (&dest[0],src,len,0); printf ("dest = '%s'\n", dest); movsb (&dest[0],&dest[6],len-6,0); printf ("Result after overlapping copy '%s'\n", dest); memset (d1, -1, 100); d1[100] = 99; fill (d1, (char)1, 100); printf ("Filled\n"); for (i=0;i<100; i++) if (d1[i] != 1) { printf ("Fill failed d1[%d] == 0x%02x\n",i, d1[i]); failures++; } if (d1[100] != 99) { printf ("Fill failed d1[101] == 0x%02x\n",d1[100]); failures++; } return failures; } int main (int argc, char ** argv) { int failures = 0; printf("Simple tests\n"); failures += doTest(); printf ("movsd tests\n"); failures += testMovsd(); printf("\n\ncmps tests\n"); failures += doCmpsTests(0); return failures; }
the_stack_data/122015017.c
int main(int argc, char *argv[]) { return 0; }
the_stack_data/509100.c
// WARNING: refcount bug in l2cap_global_chan_by_psm // https://syzkaller.appspot.com/bug?id=39ad9f042519082fcec9 // status:0 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } const int kInitNetNsFd = 239; #define MAX_FDS 30 static long syz_init_net_socket(volatile long domain, volatile long type, volatile long proto) { int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) return netns; if (setns(kInitNetNsFd, 0)) return -1; int sock = syscall(__NR_socket, domain, type, proto); int err = errno; if (setns(netns, 0)) exit(1); close(netns); errno = err; return sock; } #define BTPROTO_HCI 1 #define ACL_LINK 1 #define SCAN_PAGE 2 typedef struct { uint8_t b[6]; } __attribute__((packed)) bdaddr_t; #define HCI_COMMAND_PKT 1 #define HCI_EVENT_PKT 4 #define HCI_VENDOR_PKT 0xff struct hci_command_hdr { uint16_t opcode; uint8_t plen; } __attribute__((packed)); struct hci_event_hdr { uint8_t evt; uint8_t plen; } __attribute__((packed)); #define HCI_EV_CONN_COMPLETE 0x03 struct hci_ev_conn_complete { uint8_t status; uint16_t handle; bdaddr_t bdaddr; uint8_t link_type; uint8_t encr_mode; } __attribute__((packed)); #define HCI_EV_CONN_REQUEST 0x04 struct hci_ev_conn_request { bdaddr_t bdaddr; uint8_t dev_class[3]; uint8_t link_type; } __attribute__((packed)); #define HCI_EV_REMOTE_FEATURES 0x0b struct hci_ev_remote_features { uint8_t status; uint16_t handle; uint8_t features[8]; } __attribute__((packed)); #define HCI_EV_CMD_COMPLETE 0x0e struct hci_ev_cmd_complete { uint8_t ncmd; uint16_t opcode; } __attribute__((packed)); #define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a #define HCI_OP_READ_BUFFER_SIZE 0x1005 struct hci_rp_read_buffer_size { uint8_t status; uint16_t acl_mtu; uint8_t sco_mtu; uint16_t acl_max_pkt; uint16_t sco_max_pkt; } __attribute__((packed)); #define HCI_OP_READ_BD_ADDR 0x1009 struct hci_rp_read_bd_addr { uint8_t status; bdaddr_t bdaddr; } __attribute__((packed)); #define HCI_EV_LE_META 0x3e struct hci_ev_le_meta { uint8_t subevent; } __attribute__((packed)); #define HCI_EV_LE_CONN_COMPLETE 0x01 struct hci_ev_le_conn_complete { uint8_t status; uint16_t handle; uint8_t role; uint8_t bdaddr_type; bdaddr_t bdaddr; uint16_t interval; uint16_t latency; uint16_t supervision_timeout; uint8_t clk_accurancy; } __attribute__((packed)); struct hci_dev_req { uint16_t dev_id; uint32_t dev_opt; }; struct vhci_vendor_pkt { uint8_t type; uint8_t opcode; uint16_t id; }; #define HCIDEVUP _IOW('H', 201, int) #define HCISETSCAN _IOW('H', 221, int) static int vhci_fd = -1; static void hci_send_event_packet(int fd, uint8_t evt, void* data, size_t data_len) { struct iovec iv[3]; struct hci_event_hdr hdr; hdr.evt = evt; hdr.plen = data_len; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = data; iv[2].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data, size_t data_len) { struct iovec iv[4]; struct hci_event_hdr hdr; hdr.evt = HCI_EV_CMD_COMPLETE; hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len; struct hci_ev_cmd_complete evt_hdr; evt_hdr.ncmd = 1; evt_hdr.opcode = opcode; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = &evt_hdr; iv[2].iov_len = sizeof(evt_hdr); iv[3].iov_base = data; iv[3].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static bool process_command_pkt(int fd, char* buf, ssize_t buf_size) { struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf; if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) || hdr->plen != buf_size - sizeof(struct hci_command_hdr)) { exit(1); } switch (hdr->opcode) { case HCI_OP_WRITE_SCAN_ENABLE: { uint8_t status = 0; hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status)); return true; } case HCI_OP_READ_BD_ADDR: { struct hci_rp_read_bd_addr rp = {0}; rp.status = 0; memset(&rp.bdaddr, 0xaa, 6); hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } case HCI_OP_READ_BUFFER_SIZE: { struct hci_rp_read_buffer_size rp = {0}; rp.status = 0; rp.acl_mtu = 1021; rp.sco_mtu = 96; rp.acl_max_pkt = 4; rp.sco_max_pkt = 6; hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } } char dummy[0xf9] = {0}; hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy)); return false; } static void* event_thread(void* arg) { while (1) { char buf[1024] = {0}; ssize_t buf_size = read(vhci_fd, buf, sizeof(buf)); if (buf_size < 0) exit(1); if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) { if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1)) break; } } return NULL; } #define HCI_HANDLE_1 200 #define HCI_HANDLE_2 201 static void initialize_vhci() { int hci_sock = syz_init_net_socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); if (hci_sock < 0) exit(1); vhci_fd = open("/dev/vhci", O_RDWR); if (vhci_fd == -1) exit(1); const int kVhciFd = 241; if (dup2(vhci_fd, kVhciFd) < 0) exit(1); close(vhci_fd); vhci_fd = kVhciFd; struct vhci_vendor_pkt vendor_pkt; if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt)) exit(1); if (vendor_pkt.type != HCI_VENDOR_PKT) exit(1); pthread_t th; if (pthread_create(&th, NULL, event_thread, NULL)) exit(1); if (ioctl(hci_sock, HCIDEVUP, vendor_pkt.id) && errno != EALREADY) exit(1); struct hci_dev_req dr = {0}; dr.dev_id = vendor_pkt.id; dr.dev_opt = SCAN_PAGE; if (ioctl(hci_sock, HCISETSCAN, &dr)) exit(1); struct hci_ev_conn_request request; memset(&request, 0, sizeof(request)); memset(&request.bdaddr, 0xaa, 6); *(uint8_t*)&request.bdaddr.b[5] = 0x10; request.link_type = ACL_LINK; hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request, sizeof(request)); struct hci_ev_conn_complete complete; memset(&complete, 0, sizeof(complete)); complete.status = 0; complete.handle = HCI_HANDLE_1; memset(&complete.bdaddr, 0xaa, 6); *(uint8_t*)&complete.bdaddr.b[5] = 0x10; complete.link_type = ACL_LINK; complete.encr_mode = 0; hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete, sizeof(complete)); struct hci_ev_remote_features features; memset(&features, 0, sizeof(features)); features.status = 0; features.handle = HCI_HANDLE_1; hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features, sizeof(features)); struct { struct hci_ev_le_meta le_meta; struct hci_ev_le_conn_complete le_conn; } le_conn; memset(&le_conn, 0, sizeof(le_conn)); le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE; memset(&le_conn.le_conn.bdaddr, 0xaa, 6); *(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11; le_conn.le_conn.role = 1; le_conn.le_conn.handle = HCI_HANDLE_2; hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn)); pthread_join(th, NULL); close(hci_sock); } static long syz_emit_vhci(volatile long a0, volatile long a1) { if (vhci_fd < 0) return (uintptr_t)-1; char* data = (char*)a0; uint32_t length = a1; return write(vhci_fd, data, length); } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); if (dup2(netns, kInitNetNsFd) < 0) exit(1); close(netns); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } static int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); drop_caps(); if (unshare(CLONE_NEWNET)) { } initialize_vhci(); loop(); exit(1); } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void close_fds() { int fd; for (fd = 3; fd < MAX_FDS; fd++) close(fd); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter; for (iter = 0;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { setup_test(); execute_one(); close_fds(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } } } void execute_one(void) { syz_init_net_socket(0x1f, 1, 0); memcpy((void*)0x20000180, "\x02\xc8\x00\x04\x00\x00\x00\x02", 8); syz_emit_vhci(0x20000180, 9); } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); do_sandbox_none(); return 0; }
the_stack_data/148578931.c
#include<stdio.h> #include<signal.h> void a(){printf("A\n");} void p(){printf("B\n");} void g(){printf("C\n");} void u(){printf("D\n");} main() { int i=getpid(); printf("id=%d\n",i); signal(SIGINT,a); signal(SIGQUIT,p); signal(SIGUSR1,g); signal(SIGKILL,u); for(i=1;i>0;i++) { printf("%d\n",i); sleep(1); } }
the_stack_data/81015.c
/* Copyright (C) 2005 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <sys/time.h> #include <sys/stat.h> /* Change the access time of FILE relative to FD to TVP[0] and the modification time of FILE to TVP[1]. */ int futimesat (fd, file, tvp) int fd; const char *file; const struct timeval tvp[2]; { struct timespec tsp[2]; if (!tvp) return utimensat(fd, file, 0, 0); tsp[0].tv_sec = tvp[0].tv_sec; tsp[0].tv_nsec = 0; tsp[1].tv_sec = tvp[1].tv_sec; tsp[1].tv_nsec = 0; return utimensat(fd, file, tsp, 0); }
the_stack_data/126702578.c
#include <stdio.h> long long f(int); int main() { int m,n; long long a; scanf("%d%d",&m,&n); if(m!=0&&m>n&&n!=0) a=f(m)/(f(n)*f(m-n)); else a=1; printf("%lld",a); return 0; } long long f(int b) { long long k=1,i; for(i=b;i>0;i--) k=k*i; return k; }
the_stack_data/168894453.c
//Example program #1 from Chapter 24 of Absolute Beginner's Guide //to C, 3rd Edition //File Chapter21ex1.c /* This program demonstrates pointers by declaring and initialising both regular and pointer variables for int, float and char types and then display the value of each */ #include <stdio.h> main() { int kids; int * pKids; float price; float * pPrice; char code; char * pCode; price = 17.50; pPrice = &price; printf("\nHow many kids are you taking to the water park? "); scanf(" %d", &kids); pKids = &kids; printf("\nDo you have a discount ticket for the park?"); printf("\nEnter E for Employee Discount, S for Sav-More "); printf("Discount or N for No Discount: "); scanf(" %c", &code); pCode = &code; printf("\nFirst let's do it with the variables:\n"); printf("You've got %d kids...\n", kids); switch(code) { case('E'): printf("The employee discount saves you 25%% on the "); printf("$%.2f price", price); printf("\nTOtal ticket cost: $%.2f", (price*.75*kids)); break; case('S'): printf("The Sav-more discount saves you 15%% on the "); printf("$%.2f price", price); printf("\nTotal ticket cost: $%.2f", (price*.85*kids)); break; default: // Either entered N for no Discount or // an invalid letter printf("You will be paying full price of "); printf("$%.2f for your tickets", price); } //Now repeat the same code. but use dereferenced //pointers and get the same results printf("\n\n\nNow let's do it with the pointers:\n"); printf("You've got %d kids...\n", *pKids); switch(*pCode){ case('E'): printf("The employee discount saves you 25%% on the "); printf("$%.2f price", *pPrice); printf("Total ticket cost: $%.2f", (*pPrice * .75 * *pKids)); break; case('S'): printf("The Sav-more discount saves you 15%% on the "); printf("$%.2f for your tickets", *pPrice); } return(0); }
the_stack_data/46215.c
/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software 2010-07-03 Copyright 2010, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: http://github.com/signal11/hidapi . ********************************************************/ #if defined( __APPLE_CC__) /* See Apple Technical Note TN2187 for details on IOHidManager. */ #include <IOKit/hid/IOHIDManager.h> #include <IOKit/hid/IOHIDKeys.h> #include <CoreFoundation/CoreFoundation.h> #include <wchar.h> #include <locale.h> #include <pthread.h> #include <sys/time.h> #include <unistd.h> #include "hidapi.h" /* Barrier implementation because Mac OSX doesn't have pthread_barrier. It also doesn't have clock_gettime(). So much for POSIX and SUSv2. This implementation came from Brent Priddy and was posted on StackOverflow. It is used with his permission. */ typedef int pthread_barrierattr_t; typedef struct pthread_barrier { pthread_mutex_t mutex; pthread_cond_t cond; int count; int trip_count; } pthread_barrier_t; static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) { if(count == 0) { errno = EINVAL; return -1; } if(pthread_mutex_init(&barrier->mutex, 0) < 0) { return -1; } if(pthread_cond_init(&barrier->cond, 0) < 0) { pthread_mutex_destroy(&barrier->mutex); return -1; } barrier->trip_count = count; barrier->count = 0; return 0; } static int pthread_barrier_destroy(pthread_barrier_t *barrier) { pthread_cond_destroy(&barrier->cond); pthread_mutex_destroy(&barrier->mutex); return 0; } static int pthread_barrier_wait(pthread_barrier_t *barrier) { pthread_mutex_lock(&barrier->mutex); ++(barrier->count); if(barrier->count >= barrier->trip_count) { barrier->count = 0; pthread_cond_broadcast(&barrier->cond); pthread_mutex_unlock(&barrier->mutex); return 1; } else { pthread_cond_wait(&barrier->cond, &(barrier->mutex)); pthread_mutex_unlock(&barrier->mutex); return 0; } } static int return_data(hid_device *dev, unsigned char *data, size_t length); /* Linked List of input reports received from the device. */ struct input_report { uint8_t *data; size_t len; struct input_report *next; }; struct hid_device_ { IOHIDDeviceRef device_handle; int blocking; int uses_numbered_reports; int disconnected; CFStringRef run_loop_mode; CFRunLoopRef run_loop; CFRunLoopSourceRef source; uint8_t *input_report_buf; CFIndex max_input_report_len; struct input_report *input_reports; pthread_t thread; pthread_mutex_t mutex; /* Protects input_reports */ pthread_cond_t condition; pthread_barrier_t barrier; /* Ensures correct startup sequence */ pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */ int shutdown_thread; hid_device *next; }; /* Static list of all the devices open. This way when a device gets disconnected, its hid_device structure can be marked as disconnected from hid_device_removal_callback(). */ static hid_device *device_list = NULL; static pthread_mutex_t device_list_mutex = PTHREAD_MUTEX_INITIALIZER; static hid_device *new_hid_device(void) { hid_device *dev = calloc(1, sizeof(hid_device)); dev->device_handle = NULL; dev->blocking = 1; dev->uses_numbered_reports = 0; dev->disconnected = 0; dev->run_loop_mode = NULL; dev->run_loop = NULL; dev->source = NULL; dev->input_report_buf = NULL; dev->input_reports = NULL; dev->shutdown_thread = 0; dev->next = NULL; /* Thread objects */ pthread_mutex_init(&dev->mutex, NULL); pthread_cond_init(&dev->condition, NULL); pthread_barrier_init(&dev->barrier, NULL, 2); pthread_barrier_init(&dev->shutdown_barrier, NULL, 2); /* Add the new record to the device_list. */ pthread_mutex_lock(&device_list_mutex); if (!device_list) device_list = dev; else { hid_device *d = device_list; while (d) { if (!d->next) { d->next = dev; break; } d = d->next; } } pthread_mutex_unlock(&device_list_mutex); return dev; } static void free_hid_device(hid_device *dev) { if (!dev) return; /* Delete any input reports still left over. */ struct input_report *rpt = dev->input_reports; while (rpt) { struct input_report *next = rpt->next; free(rpt->data); free(rpt); rpt = next; } /* Free the string and the report buffer. The check for NULL is necessary here as CFRelease() doesn't handle NULL like free() and others do. */ if (dev->run_loop_mode) CFRelease(dev->run_loop_mode); if (dev->source) CFRelease(dev->source); free(dev->input_report_buf); /* Clean up the thread objects */ pthread_barrier_destroy(&dev->shutdown_barrier); pthread_barrier_destroy(&dev->barrier); pthread_cond_destroy(&dev->condition); pthread_mutex_destroy(&dev->mutex); /* Remove it from the device list. */ pthread_mutex_lock(&device_list_mutex); hid_device *d = device_list; if (d == dev) { device_list = d->next; } else { while (d) { if (d->next == dev) { d->next = d->next->next; break; } d = d->next; } } pthread_mutex_unlock(&device_list_mutex); /* Free the structure itself. */ free(dev); } static IOHIDManagerRef hid_mgr = 0x0; #if 0 static void register_error(hid_device *device, const char *op) { } #endif static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key) { CFTypeRef ref; int32_t value; ref = IOHIDDeviceGetProperty(device, key); if (ref) { if (CFGetTypeID(ref) == CFNumberGetTypeID()) { CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value); return value; } } return 0; } static unsigned short get_vendor_id(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDVendorIDKey)); } static unsigned short get_product_id(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDProductIDKey)); } static int32_t get_max_report_length(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey)); } static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len) { CFStringRef str; if (!len) return 0; str = IOHIDDeviceGetProperty(device, prop); buf[0] = 0; if (str) { len --; CFIndex str_len = CFStringGetLength(str); CFRange range; range.location = 0; range.length = (str_len > len)? len: str_len; CFIndex used_buf_len; CFIndex chars_copied; chars_copied = CFStringGetBytes(str, range, kCFStringEncodingUTF32LE, (char)'?', FALSE, (UInt8*)buf, len, &used_buf_len); buf[chars_copied] = 0; return 0; } else return -1; } static int get_string_property_utf8(IOHIDDeviceRef device, CFStringRef prop, char *buf, size_t len) { CFStringRef str; if (!len) return 0; str = IOHIDDeviceGetProperty(device, prop); buf[0] = 0; if (str) { len--; CFIndex str_len = CFStringGetLength(str); CFRange range; range.location = 0; range.length = (str_len > len)? len: str_len; CFIndex used_buf_len; CFIndex chars_copied; chars_copied = CFStringGetBytes(str, range, kCFStringEncodingUTF8, (char)'?', FALSE, (UInt8*)buf, len, &used_buf_len); buf[chars_copied] = 0; return used_buf_len; } else return 0; } static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len); } static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len); } static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len); } /* Implementation of wcsdup() for Mac. */ static wchar_t *dup_wcs(const wchar_t *s) { size_t len = wcslen(s); wchar_t *ret = malloc((len+1)*sizeof(wchar_t)); wcscpy(ret, s); return ret; } static int make_path(IOHIDDeviceRef device, char *buf, size_t len) { int res; unsigned short vid, pid; char transport[32]; buf[0] = '\0'; res = get_string_property_utf8( device, CFSTR(kIOHIDTransportKey), transport, sizeof(transport)); if (!res) return -1; vid = get_vendor_id(device); pid = get_product_id(device); res = snprintf(buf, len, "%s_%04hx_%04hx_%p", transport, vid, pid, device); buf[len-1] = '\0'; return res+1; } /* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */ static int init_hid_manager(void) { IOReturn res; /* Initialize all the HID Manager Objects */ hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (hid_mgr) { IOHIDManagerSetDeviceMatching(hid_mgr, NULL); IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); return 0; } return -1; } /* Initialize the IOHIDManager if necessary. This is the public function, and it is safe to call this function repeatedly. Return 0 for success and -1 for failure. */ int HID_API_EXPORT hid_init(void) { if (!hid_mgr) { return init_hid_manager(); } /* Already initialized. */ return 0; } int HID_API_EXPORT hid_exit(void) { if (hid_mgr) { /* Close the HID manager. */ IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone); CFRelease(hid_mgr); hid_mgr = NULL; } return 0; } static void process_pending_events() { SInt32 res; do { res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE); } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut); } struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) { struct hid_device_info *root = NULL; // return object struct hid_device_info *cur_dev = NULL; CFIndex num_devices; int i; /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) return NULL; /* give the IOHIDManager a chance to update itself */ process_pending_events(); /* Get a list of the Devices */ CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); /* Convert the list into a C array so we can iterate easily. */ num_devices = CFSetGetCount(device_set); IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); /* Iterate over each device, making an entry for it. */ for (i = 0; i < num_devices; i++) { unsigned short dev_vid; unsigned short dev_pid; #define BUF_LEN 256 wchar_t buf[BUF_LEN]; char cbuf[BUF_LEN]; IOHIDDeviceRef dev = device_array[i]; if (!dev) { continue; } dev_vid = get_vendor_id(dev); dev_pid = get_product_id(dev); /* Check the VID/PID against the arguments */ if ((vendor_id == 0x0 && product_id == 0x0) || (vendor_id == dev_vid && product_id == dev_pid)) { struct hid_device_info *tmp; size_t len; /* VID/PID match. Create the record. */ tmp = malloc(sizeof(struct hid_device_info)); if (cur_dev) { cur_dev->next = tmp; } else { root = tmp; } cur_dev = tmp; // Get the Usage Page and Usage for this device. cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey)); cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey)); /* Fill out the record */ cur_dev->next = NULL; len = make_path(dev, cbuf, sizeof(cbuf)); cur_dev->path = strdup(cbuf); /* Serial Number */ get_serial_number(dev, buf, BUF_LEN); cur_dev->serial_number = dup_wcs(buf); /* Manufacturer and Product strings */ get_manufacturer_string(dev, buf, BUF_LEN); cur_dev->manufacturer_string = dup_wcs(buf); get_product_string(dev, buf, BUF_LEN); cur_dev->product_string = dup_wcs(buf); /* VID/PID */ cur_dev->vendor_id = dev_vid; cur_dev->product_id = dev_pid; /* Release Number */ cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey)); /* Interface Number (Unsupported on Mac)*/ cur_dev->interface_number = -1; } } free(device_array); CFRelease(device_set); return root; } void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) { /* This function is identical to the Linux version. Platform independent. */ struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; free(d->path); free(d->serial_number); free(d->manufacturer_string); free(d->product_string); free(d); d = next; } } hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { /* This function is identical to the Linux version. Platform independent. */ struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device * handle = NULL; devs = hid_enumerate(vendor_id, product_id); cur_dev = devs; while (cur_dev) { if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { if (wcscmp(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } } else { path_to_open = cur_dev->path; break; } } cur_dev = cur_dev->next; } if (path_to_open) { /* Open the device */ handle = hid_open_path(path_to_open); } hid_free_enumeration(devs); return handle; } static void hid_device_removal_callback(void *context, IOReturn result, void *sender, IOHIDDeviceRef dev_ref) { /* Stop the Run Loop for this device. */ pthread_mutex_lock(&device_list_mutex); hid_device *d = device_list; while (d) { if (d->device_handle == dev_ref) { d->disconnected = 1; CFRunLoopStop(d->run_loop); } d = d->next; } pthread_mutex_unlock(&device_list_mutex); } /* The Run Loop calls this function for each input report received. This function puts the data into a linked list to be picked up by hid_read(). */ static void hid_report_callback(void *context, IOReturn result, void *sender, IOHIDReportType report_type, uint32_t report_id, uint8_t *report, CFIndex report_length) { struct input_report *rpt; hid_device *dev = context; /* Make a new Input Report object */ rpt = calloc(1, sizeof(struct input_report)); rpt->data = calloc(1, report_length); memcpy(rpt->data, report, report_length); rpt->len = report_length; rpt->next = NULL; /* Lock this section */ pthread_mutex_lock(&dev->mutex); /* Attach the new report object to the end of the list. */ if (dev->input_reports == NULL) { /* The list is empty. Put it at the root. */ dev->input_reports = rpt; } else { /* Find the end of the list and attach. */ struct input_report *cur = dev->input_reports; int num_queued = 0; while (cur->next != NULL) { cur = cur->next; num_queued++; } cur->next = rpt; /* Pop one off if we've reached 30 in the queue. This way we don't grow forever if the user never reads anything from the device. */ if (num_queued > 30) { return_data(dev, NULL, 0); } } /* Signal a waiting thread that there is data. */ pthread_cond_signal(&dev->condition); /* Unlock */ pthread_mutex_unlock(&dev->mutex); } /* This gets called when the read_thred's run loop gets signaled by hid_close(), and serves to stop the read_thread's run loop. */ static void perform_signal_callback(void *context) { hid_device *dev = context; CFRunLoopStop(dev->run_loop); //TODO: CFRunLoopGetCurrent() } static void *read_thread(void *param) { hid_device *dev = param; /* Move the device's run loop to this thread. */ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode); /* Create the RunLoopSource which is used to signal the event loop to stop when hid_close() is called. */ CFRunLoopSourceContext ctx; memset(&ctx, 0, sizeof(ctx)); ctx.version = 0; ctx.info = dev; ctx.perform = &perform_signal_callback; dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx); CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode); /* Store off the Run Loop so it can be stopped from hid_close() and on device disconnection. */ dev->run_loop = CFRunLoopGetCurrent(); /* Notify the main thread that the read thread is up and running. */ pthread_barrier_wait(&dev->barrier); /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input reports into the hid_report_callback(). */ SInt32 code; while (!dev->shutdown_thread && !dev->disconnected) { code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE); /* Return if the device has been disconnected */ if (code == kCFRunLoopRunFinished) { dev->disconnected = 1; break; } /* Break if The Run Loop returns Finished or Stopped. */ if (code != kCFRunLoopRunTimedOut && code != kCFRunLoopRunHandledSource) { /* There was some kind of error. Setting shutdown seems to make sense, but there may be something else more appropriate */ dev->shutdown_thread = 1; break; } } /* Now that the read thread is stopping, Wake any threads which are waiting on data (in hid_read_timeout()). Do this under a mutex to make sure that a thread which is about to go to sleep waiting on the condition acutally will go to sleep before the condition is signaled. */ pthread_mutex_lock(&dev->mutex); pthread_cond_broadcast(&dev->condition); pthread_mutex_unlock(&dev->mutex); /* Wait here until hid_close() is called and makes it past the call to CFRunLoopWakeUp(). This thread still needs to be valid when that function is called on the other thread. */ pthread_barrier_wait(&dev->shutdown_barrier); return NULL; } hid_device * HID_API_EXPORT hid_open_path(const char *path) { int i; hid_device *dev = NULL; CFIndex num_devices; dev = new_hid_device(); /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) return NULL; /* give the IOHIDManager a chance to update itself */ process_pending_events(); CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); num_devices = CFSetGetCount(device_set); IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); for (i = 0; i < num_devices; i++) { char cbuf[BUF_LEN]; size_t len; IOHIDDeviceRef os_dev = device_array[i]; len = make_path(os_dev, cbuf, sizeof(cbuf)); if (!strcmp(cbuf, path)) { // Matched Paths. Open this Device. IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeNone); if (ret == kIOReturnSuccess) { char str[32]; free(device_array); CFRetain(os_dev); CFRelease(device_set); dev->device_handle = os_dev; /* Create the buffers for receiving data */ dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev); dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t)); /* Create the Run Loop Mode for this device. printing the reference seems to work. */ sprintf(str, "HIDAPI_%p", os_dev); dev->run_loop_mode = CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); /* Attach the device to a Run Loop */ IOHIDDeviceRegisterInputReportCallback( os_dev, dev->input_report_buf, dev->max_input_report_len, &hid_report_callback, dev); IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, hid_device_removal_callback, NULL); /* Start the read thread */ pthread_create(&dev->thread, NULL, read_thread, dev); /* Wait here for the read thread to be initialized. */ pthread_barrier_wait(&dev->barrier); return dev; } else { goto return_error; } } } return_error: free(device_array); CFRelease(device_set); free_hid_device(dev); return NULL; } static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length) { const unsigned char *data_to_send; size_t length_to_send; IOReturn res; /* Return if the device has been disconnected. */ if (dev->disconnected) return -1; if (data[0] == 0x0) { /* Not using numbered Reports. Don't send the report number. */ data_to_send = data+1; length_to_send = length-1; } else { /* Using numbered Reports. Send the Report Number */ data_to_send = data; length_to_send = length; } if (!dev->disconnected) { res = IOHIDDeviceSetReport(dev->device_handle, type, data[0], /* Report ID*/ data_to_send, length_to_send); if (res == kIOReturnSuccess) { return length; } else return -1; } return -1; } int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) { return set_report(dev, kIOHIDReportTypeOutput, data, length); } /* Helper function, so that this isn't duplicated in hid_read(). */ static int return_data(hid_device *dev, unsigned char *data, size_t length) { /* Copy the data out of the linked list item (rpt) into the return buffer (data), and delete the liked list item. */ struct input_report *rpt = dev->input_reports; size_t len = (length < rpt->len)? length: rpt->len; memcpy(data, rpt->data, len); dev->input_reports = rpt->next; free(rpt->data); free(rpt); return len; } static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex) { while (!dev->input_reports) { int res = pthread_cond_wait(cond, mutex); if (res != 0) return res; /* A res of 0 means we may have been signaled or it may be a spurious wakeup. Check to see that there's acutally data in the queue before returning, and if not, go back to sleep. See the pthread_cond_timedwait() man page for details. */ if (dev->shutdown_thread || dev->disconnected) return -1; } return 0; } static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { while (!dev->input_reports) { int res = pthread_cond_timedwait(cond, mutex, abstime); if (res != 0) return res; /* A res of 0 means we may have been signaled or it may be a spurious wakeup. Check to see that there's acutally data in the queue before returning, and if not, go back to sleep. See the pthread_cond_timedwait() man page for details. */ if (dev->shutdown_thread || dev->disconnected) return -1; } return 0; } int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { int bytes_read = -1; /* Lock the access to the report list. */ pthread_mutex_lock(&dev->mutex); /* There's an input report queued up. Return it. */ if (dev->input_reports) { /* Return the first one */ bytes_read = return_data(dev, data, length); goto ret; } /* Return if the device has been disconnected. */ if (dev->disconnected) { bytes_read = -1; goto ret; } if (dev->shutdown_thread) { /* This means the device has been closed (or there has been an error. An error code of -1 should be returned. */ bytes_read = -1; goto ret; } /* There is no data. Go to sleep and wait for data. */ if (milliseconds == -1) { /* Blocking */ int res; res = cond_wait(dev, &dev->condition, &dev->mutex); if (res == 0) bytes_read = return_data(dev, data, length); else { /* There was an error, or a device disconnection. */ bytes_read = -1; } } else if (milliseconds > 0) { /* Non-blocking, but called with timeout. */ int res; struct timespec ts; struct timeval tv; gettimeofday(&tv, NULL); TIMEVAL_TO_TIMESPEC(&tv, &ts); ts.tv_sec += milliseconds / 1000; ts.tv_nsec += (milliseconds % 1000) * 1000000; if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; } res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts); if (res == 0) bytes_read = return_data(dev, data, length); else if (res == ETIMEDOUT) bytes_read = 0; else bytes_read = -1; } else { /* Purely non-blocking */ bytes_read = 0; } ret: /* Unlock */ pthread_mutex_unlock(&dev->mutex); return bytes_read; } int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) { return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); } int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) { /* All Nonblocking operation is handled by the library. */ dev->blocking = !nonblock; return 0; } int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { return set_report(dev, kIOHIDReportTypeFeature, data, length); } int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) { CFIndex len = length; IOReturn res; /* Return if the device has been unplugged. */ if (dev->disconnected) return -1; res = IOHIDDeviceGetReport(dev->device_handle, kIOHIDReportTypeFeature, data[0], /* Report ID */ data, &len); if (res == kIOReturnSuccess) return len; else return -1; } void HID_API_EXPORT hid_close(hid_device *dev) { if (!dev) return; /* Disconnect the report callback before close. */ if (!dev->disconnected) { IOHIDDeviceRegisterInputReportCallback( dev->device_handle, dev->input_report_buf, dev->max_input_report_len, NULL, dev); IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, NULL, dev); IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode); IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } /* Cause read_thread() to stop. */ dev->shutdown_thread = 1; /* Wake up the run thread's event loop so that the thread can exit. */ CFRunLoopSourceSignal(dev->source); CFRunLoopWakeUp(dev->run_loop); /* Notify the read thread that it can shut down now. */ pthread_barrier_wait(&dev->shutdown_barrier); /* Wait for read_thread() to end. */ pthread_join(dev->thread, NULL); /* Close the OS handle to the device, but only if it's not been unplugged. If it's been unplugged, then calling IOHIDDeviceClose() will crash. */ if (!dev->disconnected) { IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeNone); } /* Clear out the queue of received reports. */ pthread_mutex_lock(&dev->mutex); while (dev->input_reports) { return_data(dev, NULL, 0); } pthread_mutex_unlock(&dev->mutex); CFRelease(dev->device_handle); free_hid_device(dev); } int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { return get_manufacturer_string(dev->device_handle, string, maxlen); } int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { return get_product_string(dev->device_handle, string, maxlen); } int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { return get_serial_number(dev->device_handle, string, maxlen); } int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { // TODO: return 0; } HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) { // TODO: return NULL; } #if 0 static int32_t get_location_id(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDLocationIDKey)); } static int32_t get_usage(IOHIDDeviceRef device) { int32_t res; res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey)); if (!res) res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey)); return res; } static int32_t get_usage_page(IOHIDDeviceRef device) { int32_t res; res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey)); if (!res) res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey)); return res; } static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len); } int main(void) { IOHIDManagerRef mgr; int i; mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); IOHIDManagerSetDeviceMatching(mgr, NULL); IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone); CFSetRef device_set = IOHIDManagerCopyDevices(mgr); CFIndex num_devices = CFSetGetCount(device_set); IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); for (i = 0; i < num_devices; i++) { IOHIDDeviceRef dev = device_array[i]; printf("Device: %p\n", dev); printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev)); wchar_t serial[256], buf[256]; char cbuf[256]; get_serial_number(dev, serial, 256); printf(" Serial: %ls\n", serial); printf(" Loc: %ld\n", get_location_id(dev)); get_transport(dev, buf, 256); printf(" Trans: %ls\n", buf); make_path(dev, cbuf, 256); printf(" Path: %s\n", cbuf); } return 0; } #endif #endif // defined( __APPLE_CC__)
the_stack_data/187643732.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <string.h> typedef struct { char **ids; size_t length; } Input; typedef struct { int part1; char *part2; } Results; int part1(Input input) { int twiceCount = 0, thriceCount = 0, index = 0, cIndex; int counts[26]; char *id; char c; while (input.length--) { id = input.ids[index]; for (cIndex = 0; cIndex < 26; cIndex++) counts[cIndex] = 0; cIndex = 0; while (c = id[cIndex++]) counts[c - 'a']++; int hasTwos = 0, hasThrees = 0; for (cIndex = 0; cIndex < 26; cIndex++) { hasTwos |= counts[cIndex] == 2; hasThrees |= counts[cIndex] == 3; } twiceCount += hasTwos; thriceCount += hasThrees; index++; } return twiceCount * thriceCount; } char *part2(Input input) { int thisIndex, otherIndex, cIndex, differenceCount, differenceIndex; char *thisId, *otherId; for (thisIndex = 0; thisIndex < input.length; thisIndex++) { thisId = input.ids[thisIndex]; for (otherIndex = thisIndex + 1; otherIndex < input.length; otherIndex++) { differenceCount = 0; differenceIndex = 0; otherId = input.ids[otherIndex]; for (cIndex = 0; cIndex < strlen(thisId); cIndex++) if (thisId[cIndex] != otherId[cIndex]) { differenceCount++; differenceIndex = cIndex; } if (differenceCount == 1) { thisId[differenceIndex] = 0; otherId += differenceIndex + 1; strcat(thisId, otherId); return thisId; } } } return NULL; } Results solve(Input input) { return (Results){part1(input), part2(input)}; } Input getInput(char *filePath) { FILE *file; if ((file = fopen(filePath, "r")) == NULL) { perror("Error reading input file!\n"); exit(1); } char **ids = calloc(256, sizeof(char *)); char *line = NULL; size_t length = 0, count = 0; while (getline(&line, &length, file) != EOF) { ids[count] = malloc(strlen(line) + 1); strcpy(ids[count], line); ids[count][strlen(line) - 1] = 0; count++; } fclose(file); return (Input){ ids, count}; } void freeInput(Input input) { int index = 0; while (input.length--) free(input.ids[index++]); free(input.ids); } int main(int argc, char **argv) { if (argc != 2) { perror("Please, add input file path as parameter"); exit(1); } struct timeval starts, ends; gettimeofday(&starts, NULL); Input input = getInput(argv[1]); Results results = solve(input); gettimeofday(&ends, NULL); printf("P1: %d\n", results.part1); printf("P2: %s\n\n", results.part2); printf("Time: %.7f\n", (double)((ends.tv_sec - starts.tv_sec) * 1000000 + ends.tv_usec - starts.tv_usec) / 1000000); freeInput(input); return 0; }
the_stack_data/61553.c
double normalCFunction(int p1, char p2, float p3); static int staticCFunction(double p1); extern float externCFunction(int p1); inline void inlineCFunction(long p1); void varArgsCFunction(int p1, ...); const void constCFunction(); volatile void volatileCFunction(); void storageClassCFunction(register int p1, int p2); void noReturnCFunction() __attribute__((noreturn)); void voidCFunction(); int intCFunction(); double doubleCFunction(); char charCFunction(); float floatCFunction(); struct S { struct D { int a; }; };
the_stack_data/100928.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2018-2021 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ static int __attribute__ ((used)) foo (void) { return 2; } int main (void) { return 0; }
the_stack_data/582194.c
#include <pthread.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <stdio.h> #include <stdbool.h> #include <semaphore.h> pthread_t *CreateThread(void *(*f)(void *), void *a) { pthread_t *t = malloc(sizeof(pthread_t)); assert(t != NULL); int ret = pthread_create(t, NULL, f, a); assert(ret == 0); return t; } static const int N_ELVES = 10; static const int N_REINDEER = 9; static int elves; static int reindeer; static sem_t santaSem; static sem_t reindeerSem; static sem_t elfTex; static sem_t mutex; void *SantaClaus(void *arg) { printf("Santa Claus: Hoho, here I am\n"); while (true) { sem_wait(&santaSem); sem_wait(&mutex); if (reindeer == N_REINDEER) { printf("Santa Claus: preparing sleigh\n"); for (int r = 0; r < N_REINDEER; r++) sem_post(&reindeerSem); printf("Santa Claus: make all kids in the world happy\n"); reindeer = 0; } else if (elves == 3) { printf("Santa Claus: helping elves\n"); } sem_post(&mutex); } return arg; } void *Reindeer(void *arg) { int id = (int)arg; printf("This is reindeer %d\n", id); while (true) { sem_wait(&mutex); reindeer++; if (reindeer == N_REINDEER) sem_post(&santaSem); sem_post(&mutex); sem_wait(&reindeerSem); printf("Reindeer %d getting hitched\n", id); sleep(20); } return arg; } void *Elve(void *arg) { int id = (int)arg; printf("This is elve %d\n", id); while (true) { bool need_help = random() % 100 < 10; if (need_help) { sem_wait(&elfTex); sem_wait(&mutex); elves++; if (elves == 3) sem_post(&santaSem); else sem_post(&elfTex); sem_post(&mutex); printf("Elve %d will get help from Santa Claus\n", id); sleep(10); sem_wait(&mutex); elves--; if (elves == 0) sem_post(&elfTex); sem_post(&mutex); } // Do some work printf("Elve %d at work\n", id); sleep(2 + random() % 5); } return arg; } int main(int ac, char **av) { elves = 0; reindeer = 0; sem_init(&santaSem, 0, 0); sem_init(&reindeerSem, 0, 0); sem_init(&elfTex, 0, 1); sem_init(&mutex, 0, 1); pthread_t *santa_claus = CreateThread(SantaClaus, 0); pthread_t *reindeers[N_REINDEER]; for (int r = 0; r < N_REINDEER; r++) reindeers[r] = CreateThread(Reindeer, (void *)r + 1); pthread_t *elves[N_ELVES]; for (int e = 0; e < N_ELVES; e++) elves[e] = CreateThread(Elve, (void *)e + 1); int ret = pthread_join(*santa_claus, NULL); assert(ret == 0); }
the_stack_data/125276.c
/* * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <ctype.h> #include <stdio.h> #include <string.h> #include <openssl/asn1.h> #include <openssl/err.h> #include <openssl/objects.h> static STACK_OF(ASN1_STRING_TABLE) *stable = NULL; static void st_free(ASN1_STRING_TABLE *tbl); static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, const ASN1_STRING_TABLE *const *b); /* This is the global mask for the mbstring functions: this is use to * mask out certain types (such as BMPString and UTF8String) because * certain software (e.g. Netscape) has problems with them. */ static unsigned long global_mask = B_ASN1_UTF8STRING; void ASN1_STRING_set_default_mask(unsigned long mask) { global_mask = mask; } unsigned long ASN1_STRING_get_default_mask(void) { return global_mask; } /* This function sets the default to various "flavours" of configuration. * based on an ASCII string. Currently this is: * MASK:XXXX : a numerical mask value. * nobmp : Don't use BMPStrings (just Printable, T61). * pkix : PKIX recommendation in RFC2459. * utf8only : only use UTF8Strings (RFC2459 recommendation for 2004). * default: the default value, Printable, T61, BMP. */ int ASN1_STRING_set_default_mask_asc(const char *p) { unsigned long mask; char *end; if (strncmp(p, "MASK:", 5) == 0) { if (!p[5]) return 0; mask = strtoul(p + 5, &end, 0); if (*end) return 0; } else if (strcmp(p, "nombstr") == 0) mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING)); else if (strcmp(p, "pkix") == 0) mask = ~((unsigned long)B_ASN1_T61STRING); else if (strcmp(p, "utf8only") == 0) mask = B_ASN1_UTF8STRING; else if (strcmp(p, "default") == 0) mask = 0xFFFFFFFFL; else return 0; ASN1_STRING_set_default_mask(mask); return 1; } /* The following function generates an ASN1_STRING based on limits in a table. * Frequently the types and length of an ASN1_STRING are restricted by a * corresponding OID. For example certificates and certificate requests. */ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const uint8_t *in, int inlen, int inform, int nid) { ASN1_STRING_TABLE *tbl; ASN1_STRING *str = NULL; unsigned long mask; int ret; if (!out) out = &str; tbl = ASN1_STRING_TABLE_get(nid); if (tbl) { mask = tbl->mask; if (!(tbl->flags & STABLE_NO_MASK)) mask &= global_mask; ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask, tbl->minsize, tbl->maxsize); } else ret = ASN1_mbstring_copy(out, in, inlen, inform, DIRSTRING_TYPE & global_mask); if (ret <= 0) return NULL; return *out; } /* Now the tables and helper functions for the string table: */ /* size limits: this stuff is taken straight from RFC3280 */ #define ub_name 32768 #define ub_common_name 64 #define ub_locality_name 128 #define ub_state_name 128 #define ub_organization_name 64 #define ub_organization_unit_name 64 #define ub_title 64 #define ub_email_address 128 #define ub_serial_number 64 /* This table must be kept in NID order */ static const ASN1_STRING_TABLE tbl_standard[] = { { NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0 }, { NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK }, { NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0 }, { NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0 }, { NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0 }, { NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, 0 }, { NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, STABLE_NO_MASK }, { NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0 }, { NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0 }, { NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0 }, { NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0 }, { NID_surname, 1, ub_name, DIRSTRING_TYPE, 0 }, { NID_initials, 1, ub_name, DIRSTRING_TYPE, 0 }, { NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK }, { NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK }, { NID_name, 1, ub_name, DIRSTRING_TYPE, 0 }, { NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK }, { NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK }, { NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK } }; static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, const ASN1_STRING_TABLE *const *b) { return (*a)->nid - (*b)->nid; } DECLARE_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) { return a->nid - b->nid; } IMPLEMENT_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid) { int idx; ASN1_STRING_TABLE *ttmp; ASN1_STRING_TABLE fnd; fnd.nid = nid; ttmp = OBJ_bsearch_table(&fnd, tbl_standard, sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE)); if (ttmp) return ttmp; if (!stable) return NULL; idx = sk_ASN1_STRING_TABLE_find(stable, &fnd); if (idx < 0) return NULL; return sk_ASN1_STRING_TABLE_value(stable, idx); } int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize, unsigned long mask, unsigned long flags) { ASN1_STRING_TABLE *tmp; char new_nid = 0; flags &= ~STABLE_FLAGS_MALLOC; if (!stable) stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp); if (!stable) { ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE); return 0; } if (!(tmp = ASN1_STRING_TABLE_get(nid))) { tmp = malloc(sizeof(ASN1_STRING_TABLE)); if (!tmp) { ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE); return 0; } tmp->flags = flags | STABLE_FLAGS_MALLOC; tmp->nid = nid; tmp->minsize = tmp->maxsize = -1; new_nid = 1; } else tmp->flags = (tmp->flags & STABLE_FLAGS_MALLOC) | flags; if (minsize != -1) tmp->minsize = minsize; if (maxsize != -1) tmp->maxsize = maxsize; tmp->mask = mask; if (new_nid) sk_ASN1_STRING_TABLE_push(stable, tmp); return 1; } void ASN1_STRING_TABLE_cleanup(void) { STACK_OF(ASN1_STRING_TABLE) *tmp; tmp = stable; if (!tmp) return; stable = NULL; sk_ASN1_STRING_TABLE_pop_free(tmp, st_free); } static void st_free(ASN1_STRING_TABLE *tbl) { if (tbl->flags & STABLE_FLAGS_MALLOC) free(tbl); }
the_stack_data/37638716.c
/****************************************************** * Edgar A. Leon * Lawrence Livermore National Laboratory ******************************************************/ #include <stdio.h> #include <hwloc.h> #define SHORT_STR_SIZE 32 #define LONG_STR_SIZE 1024 #if 0 struct topo_level { char *name; int nobjs; int depth; int pus_per_obj; hwloc_bitmap_t cpuset; }; static void get_level_info(hwloc_topology_t topo, hwloc_cpuset_t cpuset, int depth, int pus_per_obj, struct topo_level *info) { int i, nobjs, pu, count, nc; hwloc_obj_t obj; char *str; info->cpuset = hwloc_bitmap_alloc(); info->name = malloc(SHORT_STR_SIZE); info->nobjs = 0; info->depth = depth; info->pus_per_obj = pus_per_obj; str = info->name; nobjs = hwloc_get_nbobjs_inside_cpuset_by_depth(topo, cpuset, depth); /* Get the pus for the given depth and cpuset */ for (i=0; i<nobjs; i++) { obj = hwloc_get_obj_inside_cpuset_by_depth(topo, cpuset, depth, i); count = 0; hwloc_bitmap_foreach_begin(pu, obj->cpuset) { hwloc_bitmap_set(info->cpuset, pu); info->nobjs++; if (++count == pus_per_obj) break; } hwloc_bitmap_foreach_end(); } /* Get the name of the matching level */ nc = hwloc_obj_type_snprintf(str, SHORT_STR_SIZE, obj, 1); if (depth == hwloc_get_type_depth(topo, HWLOC_OBJ_CORE)) snprintf(str+nc, SHORT_STR_SIZE-nc, "SMT%d", pus_per_obj); } static void free_topo_levels(struct topo_level *levels, int size) { int i; for (i=0; i<size; i++) { free(levels[i].name); hwloc_bitmap_free(levels[i].cpuset); } free(levels); } /* * While I can walk down the tree to find out what level * is to be used for given ntasks/nthreads, I would have * special cases since the topology does not have SMT-2, * SMT-3, etc. levels. * Thus, this function creates my own level structure that * I can use to manage any request uniformly. */ static struct topo_level* build_mapping_levels(hwloc_topology_t topo, hwloc_obj_t root, int *size) { int idx, topo_depth, depth, hw_smt, smt, core_depth, nlevels; struct topo_level *topo_levels; hw_smt = get_smt_level(topo); topo_depth = hwloc_topology_get_depth(topo); core_depth = hwloc_get_type_depth(topo, HWLOC_OBJ_CORE); nlevels = topo_depth - root->depth; if (hw_smt > 2) nlevels += hw_smt - 2; topo_levels = calloc(nlevels, sizeof(struct topo_level)); /* Walk the tree starting from the root */ idx = 0; for (depth=root->depth; depth<topo_depth; depth++) { get_level_info(topo, root->cpuset, depth, 1, topo_levels+idx); idx++; /* Build SMT levels starting at the Core+1 level */ if (depth == core_depth) for (smt=2; smt<hw_smt; smt++) { get_level_info(topo, root->cpuset, depth, smt, topo_levels+idx); idx++; } } *size = idx; return topo_levels; } #endif /* * Get the PCI Bus ID of an I/O device object, e.g., * 0000:04:00.0 * Make sure PCI devices are not filtered out * when loading an hwloc topology. */ int pci_busid_snprintf(char *buf, size_t size, hwloc_obj_t io) { hwloc_obj_t obj; if (io->type == HWLOC_OBJ_PCI_DEVICE) obj = io; else if (io->parent->type == HWLOC_OBJ_PCI_DEVICE) obj = io->parent; else return 0; return snprintf(buf, size, "%04x:%02x:%02x.%01x", obj->attr->pcidev.domain, obj->attr->pcidev.bus, obj->attr->pcidev.dev, obj->attr->pcidev.func); } /* * Get the Universally Unique ID (UUID) of a GPU device. * * The GPU UUID is located in the info attributes of the * associated OSDEV_GPU device (rather than OSDEV_COPROC). * The backend for NVIDIA is NVML and for AMD is RSMI. * NVML GPU OS devices * NVIDIAUUID, NVIDIASerial * NVML is the NVIDIA Management Library and is included in CUDA. * RSMI GPU OS devices * AMDUUID, AMDSerial * RSMI is the AMD ROCm SMI library */ int gpu_uuid_snprintf(char *buf, size_t size, hwloc_obj_t dev) { int nc=0; hwloc_obj_t obj=NULL; if (dev->type == HWLOC_OBJ_OS_DEVICE && dev->attr->osdev.type == HWLOC_OBJ_OSDEV_GPU) obj = dev; else if (dev->parent->io_arity > 0) { hwloc_obj_t io = dev->parent->io_first_child; do { if (io->type == HWLOC_OBJ_OS_DEVICE && io->attr->osdev.type == HWLOC_OBJ_OSDEV_GPU) obj = io; } while ((io = io->next_sibling) != NULL); } if (obj) { nc = snprintf(buf, size, "%s", hwloc_obj_get_info_by_name(obj, "AMDUUID")); if (nc <= 0) nc = snprintf(buf, size, "%s", hwloc_obj_get_info_by_name(obj, "NVIDIAUUID")); } return nc; } /* * Get the 'name=value' pairs of the infos structure * of an object. * struct hwloc_info_s ∗ infos * char*name * char*value * unsigned infos_count */ static int obj_infos_snprintf(char *str, size_t size, hwloc_obj_t obj) { int i, nc=0; for (i=0; i<obj->infos_count; i++) nc += snprintf(str+nc, size-nc, "%s=%s ", obj->infos[i].name, obj->infos[i].value); return nc; } /* * Get the attributes of a normal or I/O object. * Verbosity can be zero or greater than zero. * Todo: Add memory objects (HWLOC_OBJ_NUMA_NODE) */ static int obj_attr_snprintf(char *str, size_t size, hwloc_obj_t obj, int verbose) { int nc=0; /* Other object attributes: obj->depth, obj->gp_index, obj->logical_index, obj->attr->pcidev.vendor_id, obj->attr->pcidev.device_id hwloc_pci_class_string(obj->attr->pcidev.class_id) */ if (hwloc_obj_type_is_normal(obj->type)) { nc += hwloc_obj_type_snprintf(str+nc, size-nc, obj, 1); nc += snprintf(str+nc, size-nc, "[%d]: os=%d ", obj->logical_index, obj->os_index); nc += snprintf(str+nc, size-nc, "cpuset="); nc += hwloc_bitmap_list_snprintf(str+nc, size-nc, obj->cpuset); nc += snprintf(str+nc, size-nc, " nodeset="); nc += hwloc_bitmap_list_snprintf(str+nc, size-nc, obj->nodeset); nc += snprintf(str+nc, size-nc, " arity=%d mema=%d ioa=%d ", obj->arity, obj->memory_arity, obj->io_arity); } if (obj->type == HWLOC_OBJ_OS_DEVICE) switch (obj->attr->osdev.type) { case HWLOC_OBJ_OSDEV_COPROC : nc += hwloc_obj_type_snprintf(str+nc, size-nc, obj, 1); nc += snprintf(str+nc, size-nc, ": name=%s ", obj->name); nc += snprintf(str+nc, size-nc, "subtype=%s ", obj->subtype); nc += snprintf(str+nc, size-nc, "GPUModel=%s ", hwloc_obj_get_info_by_name(obj, "GPUModel")); nc += snprintf(str+nc, size-nc, " "); /* Get obj->infos in one shot */ nc += hwloc_obj_attr_snprintf(str+nc, size-nc, obj, " ", verbose); break; case HWLOC_OBJ_OSDEV_GPU : nc += hwloc_obj_type_snprintf(str+nc, size-nc, obj, 1); nc += snprintf(str+nc, size-nc, ": name=%s ", obj->name); nc += snprintf(str+nc, size-nc, "UUID=%s ", (hwloc_obj_get_info_by_name(obj, "AMDUUID")) ? hwloc_obj_get_info_by_name(obj, "AMDUUID") : hwloc_obj_get_info_by_name(obj, "NVIDIAUUID")); nc += snprintf(str+nc, size-nc, " "); nc += hwloc_obj_attr_snprintf(str+nc, size-nc, obj, " ", verbose); break; case HWLOC_OBJ_OSDEV_OPENFABRICS : nc += hwloc_obj_type_snprintf(str+nc, size-nc, obj, 1); nc += snprintf(str+nc, size-nc, ": name=%s ", obj->name); nc += snprintf(str+nc, size-nc, "NodeGUID=%s ", hwloc_obj_get_info_by_name(obj, "NodeGUID")); nc += snprintf(str+nc, size-nc, " "); nc += hwloc_obj_attr_snprintf(str+nc, size-nc, obj, " ", verbose); break; default: break; } if (obj->type == HWLOC_OBJ_PCI_DEVICE) { /* Filter out less interesting devices: 0x106: SATA 0x200: Ethernet 0x300: VGA More interesting devices: 0x108: NVMe memory 0x207: InfiniBand NICs 0x302: NVIDIA GPUs 0x380: AMD GPUs */ unsigned cid = obj->attr->pcidev.class_id; if (cid != 0x300 && cid != 0x200 && cid != 0x106) { nc += hwloc_obj_type_snprintf(str+nc, size-nc, obj, 1); nc += snprintf(str+nc, size-nc, ": busid="); nc += pci_busid_snprintf(str+nc, size-nc, obj); nc += snprintf(str+nc, size-nc, " link=%.2fGB/s ", obj->attr->pcidev.linkspeed); nc += snprintf(str+nc, size-nc, "class=0x%x ", obj->attr->pcidev.class_id); nc += snprintf(str+nc, size-nc, "PCIDevice=%s ", hwloc_obj_get_info_by_name(obj, "PCIDevice")); nc += snprintf(str+nc, size-nc, " "); nc += hwloc_obj_attr_snprintf(str+nc, size-nc, obj, " ", verbose); } } return nc; } /* * Walk the I/O objects stemming from 'root' * and apply function 'apply' to each object. * * Applying this function to the topology root * object (Machine) may not show all the I/O devices, * because most of them are hanging off of a Package, * not Machine. To see all the I/O objects use * 'print_topo_io' */ static void tree_walk_io_simple(void (*apply)(hwloc_obj_t, int), hwloc_obj_t root, int depth) { hwloc_obj_t obj; (*apply)(root, depth); if (root->io_arity > 0) { obj = root->io_first_child; do { tree_walk_io_simple(apply, obj, depth+1); } while ((obj = obj->next_sibling) != NULL); } } /* * A generalization of tree_walk_io() that allows * a function with arguments to be applied to * each object */ void tree_walk_io(void (*apply)(hwloc_obj_t, void*, int), hwloc_obj_t root, void *args, int depth) { hwloc_obj_t obj; (*apply)(root, args, depth); if (root->io_arity > 0) { obj = root->io_first_child; do { tree_walk_io(apply, obj, args, depth+1); } while ((obj = obj->next_sibling) != NULL); } } /* * Print the 'name=value' pairs of the infos structure * of an object. */ void print_obj_info(hwloc_obj_t obj) { char str[LONG_STR_SIZE]; if ( obj_infos_snprintf(str, sizeof(str), obj) ) printf("%s\n", str); } /* * Print the object and its attributes. * Use 'indent' (non-negative) to indent the output. */ void print_obj(hwloc_obj_t obj, int indent) { int verb = 0; char str[LONG_STR_SIZE]; if (obj_attr_snprintf(str, sizeof(str), obj, verb) > 0) printf("%*s%s\n", 2*indent, "", str); } /* * Print devices of a specific type as a flat list. * Types: * HWLOC_OBJ_PCI_DEVICE * HWLOC_OBJ_OS_DEVICE * HWLOC_OBJ_DIE * HWLOC_OBJ_NUMA_NODE * HWLOC_OBJ_GROUP * HWLOC_OBJ_CORE, ... */ void print_devices(hwloc_topology_t topo, hwloc_obj_type_t type) { hwloc_obj_t obj = NULL; while ( (obj=hwloc_get_next_obj_by_type(topo, type, obj)) != NULL ) print_obj(obj, 0); } /* * A quick view of the topology of the normal * components, i.e., no I/O devices. */ void print_topo_brief(hwloc_topology_t topo) { int depth; int topo_depth = hwloc_topology_get_depth(topo); for (depth = 0; depth < topo_depth; depth++) printf("Depth %d: %s[%d]\n", depth, hwloc_obj_type_string(hwloc_get_depth_type(topo, depth)), hwloc_get_nbobjs_by_depth(topo, depth)); } /* * Print the hierarchy of I/O objects of interest, * including non-I/O ancestors, of a given topology. * Objects of interest include Coprocessors, * PCI devices, GPUs, and OpenFabrics NICs. */ void print_topo_io(hwloc_topology_t topo) { hwloc_uint64_t nonio_gp[128]; int i, nonio_cnt=0; hwloc_obj_t obj=NULL, parent; while ( (obj = hwloc_get_next_osdev(topo, obj)) != NULL ) if (obj->attr->osdev.type == HWLOC_OBJ_OSDEV_COPROC || obj->attr->osdev.type == HWLOC_OBJ_OSDEV_GPU || obj->attr->osdev.type == HWLOC_OBJ_OSDEV_OPENFABRICS) { /* Find the non-io ancestor first */ parent = hwloc_get_non_io_ancestor_obj(topo, obj); /* Check if we've seen this normal object before */ for (i=0; i<nonio_cnt; i++) if (nonio_gp[i] == parent->gp_index) break; /* If not, print it out with its I/O children */ if (i == nonio_cnt) { nonio_gp[nonio_cnt++] = parent->gp_index; tree_walk_io_simple(print_obj, parent, 0); } } }
the_stack_data/232955598.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sched.h> #include <unistd.h> #include <time.h> /** NUM_COLLECTORS specifies,how much tax collectors are in the game. */ #define NUM_COLLECTORS 5 #define START_AMOUNT_OF_MONEY 300 int num_collectors = NUM_COLLECTORS; pthread_t *threads; long *moneys; long *ins; long *outs; int stop = 0; #ifdef BIGLOCK pthread_mutex_t biglock; #endif #ifdef MULTILOCK pthread_mutex_t *multilock; #endif void *tax_collector(void *field){ /* target is a random number between 0 and NUM_COLLECTORS */ int target; int my_tid; int get_money = 0; my_tid = (long) field; target = my_tid; int i = 0; while(stop){ } while(!stop){ while (my_tid == target){ target = rand() % num_collectors; } /* not a perfect randomness, but it should be sufficient for our * needs. */ #ifdef BIGLOCK pthread_mutex_lock(&biglock); #endif if (moneys[target] < 100 ){ get_money = 100; for(i=0; i<10; i++){ if(moneys[target] < 100){ #ifdef BIGLOCK pthread_mutex_unlock(&biglock); #endif sched_yield(); #ifdef BIGLOCK pthread_mutex_lock(&biglock); #endif } else{ #ifdef MULTILOCK if(target < my_tid){ pthread_mutex_lock(&multilock[target]); pthread_mutex_lock(&multilock[my_tid]); // printf("Thread %d locked and target %d locked\n",my_tid,target); }else{ pthread_mutex_lock(&multilock[my_tid]); pthread_mutex_lock(&multilock[target]); // printf("Thread %d locked and target %d locked\n",my_tid,target); } #endif moneys[my_tid] += get_money; moneys[target] -= get_money; ins[my_tid]++; outs[target]++; #ifdef MULTILOCK pthread_mutex_unlock(&multilock[target]); pthread_mutex_unlock(&multilock[my_tid]); // printf("Thread %d and %d unlocked\n",my_tid,target); #endif } } } else { #ifdef MULTILOCK if(target < my_tid){ pthread_mutex_lock(&multilock[target]); pthread_mutex_lock(&multilock[my_tid]); // printf("Thread %d locked and target %d locked\n",my_tid,target); }else{ pthread_mutex_lock(&multilock[my_tid]); pthread_mutex_lock(&multilock[target]); // printf("Thread %d locked and target %d locked\n",my_tid,target); } #endif get_money = moneys[target]; get_money = get_money / 100; if (get_money % 2) {get_money++;} get_money = get_money * 50; moneys[my_tid] += get_money; moneys[target] -= get_money; #ifdef MULTILOCK pthread_mutex_unlock(&multilock[target]); pthread_mutex_unlock(&multilock[my_tid]); // printf("Thread %d and %d unlocked\n",my_tid,target); #endif ins[my_tid]++; outs[target]++; } #ifdef BIGLOCK pthread_mutex_unlock(&biglock); #endif target = my_tid; } pthread_exit(0); return 0; } int main(int argc, char **argv) { int start_money = START_AMOUNT_OF_MONEY; long amount_money; long total_in=0; long total_out=0; long i; int test; int a; (void)a; if ( argc > 1 ) { num_collectors = atoi(argv[1]); if ( argc > 2 ) start_money = atoi(argv[2]); } printf("Tax Collectors: %d\nAmount of money: %d\n",num_collectors,start_money); #ifdef MULTILOCK printf("MULTILOCK \t activated \n"); #endif #ifdef BIGLOCK printf("BIGLOCK \t activated \n"); #endif srand(time(NULL)); amount_money = start_money; /* malloc the arrays */ threads = malloc(sizeof(pthread_t) * num_collectors); moneys = malloc(sizeof(long) * num_collectors); ins = malloc(sizeof(long) * num_collectors); outs = malloc(sizeof(long) * num_collectors); #ifdef MULTILOCK multilock = malloc(sizeof(pthread_mutex_t) * num_collectors); #endif /* initialize the moneys array */ i = 0; while(amount_money > 0){ if(amount_money < 100){ moneys[i] += amount_money; amount_money -= amount_money; } else{ moneys[i] += 100; amount_money -= 100; } i = (i+1) % num_collectors; } stop = 1; /* initialize the threads array */ for(i = 0; i < num_collectors; i++){ test = pthread_create(&threads[i], NULL, tax_collector, (void*) i); if(test){ printf("ERROR: could not initialize arrays on index %li\n",i); exit(-1); } #ifdef MULTILOCK pthread_mutex_init(&multilock[i],NULL); #endif } stop = 0; sleep(20); stop = 1; sleep(3); /* collect all threads */ for(i=0; i < num_collectors; i++){ pthread_join(threads[i], NULL); } /* sum up ressources */ for(i=0; i < num_collectors; i++){ amount_money += moneys[i]; total_in += ins[i]; total_out += outs[i]; printf("Collector %li has:\t money=%li,\t in=%li,\t out=%li\n",i,moneys[i],ins[i],outs[i]); } printf("ended with: amount money = %li,\t total_ins=%li,\t total_outs=%li\n",amount_money,total_in,total_out); return 0; }
the_stack_data/90762768.c
#include <stdio.h> // puts #include <stdlib.h> // malloc #include <signal.h> // kill #include <stdint.h> // uint*_t types #include <errno.h> // errno #include <string.h> // strerror #include <sys/ipc.h> // shmget #include <sys/shm.h> // shmget #include <sys/types.h> // fork, getppid #include <unistd.h> // fork, getppid, sleep #include <sys/types.h> // kill, shmat, shmdt #include <sys/shm.h> // shmat, shmdt #include <sys/wait.h> // wait #define LOG //printf("%s/%s/%d\n", __FILE__, __FUNCTION__, __LINE__) #define PRINTPID //printf("%d\n", getpid()) // Parent may request for any of the below typedef enum _req_type { NONE, MALLOC, FREE, DEREF8, DEREF16, DEREF32, DEREF64, STORE8, STORE16, STORE32, STORE64, QUIT } req_type_t; // Parent requests with this format // if allocation, size is filled // if free, p must be set by parent // if deref*/store*, p must be set by parent // request must initially be NONE and be set // in the end while making a new request typedef struct _req { size_t size; void *p; uint64_t data; req_type_t request; } req_t; // used to let each other know that both are ready volatile unsigned char ch_shmat; // man signal.7 and see what SIGRTMIN does void sigrtmin_handler(int signo) { ch_shmat = 1; } // SEGFAULT handler is not practical // SEGFAULT handler will be called again and again // for a single SEGFAULT // setjmp.h may not be helpful too /* // re-route SEGFAULTs to parent */ /* void ch_sigsegv_handler(int signo) { */ /* kill(getppid(), SIGSEGV); */ /* } */ int main() { int shmid; pid_t pid; void *shmp; // Create a shared memory in parent // only memory is created and will be ready to be // shared across processes shmid = shmget(IPC_PRIVATE, sizeof(req_t), 0666 | IPC_CREAT); if (shmid == -1) { puts("Unable to get shared memory id"); goto shm_failed; } // child will raise the below signal once it's ready // we register now here even before forking // What if the child is ready, even before parent is // scheduled? // Ready here refers indicates that the child has attached // to created shared memory segment. signal(SIGRTMIN, sigrtmin_handler); // Not an essential stuff (probably) // used it to help with debug stuff // fflush is not required as the recieved // value is straight forwarded to stdout setvbuf(stdout, NULL, _IONBF, 0); pid = fork(); if (pid < 0) { puts("Unable to fork"); goto fork_failed; } else if (pid > 0) { // Parent // mark the volatile here // this will point to shared memory // and so, modifications to data pointed by this pointer // are asynchronous to parent volatile req_t *parents_req; // signal(SIGSEGV, parent_sigsegv_handler); // attach to shared memory so that we can IPC with child shmp = shmat(shmid, NULL, 0); if (shmp == (void *) -1) { puts("Parent: failed to attach to shared memory segment"); goto shmat_failed; } // shmp is voidp; cumbersome to typecast everytime // to the actual req_t concrete type // better use a pointer which can point to req_t parents_req = shmp; *parents_req = (req_t) {0, 0, 0, 0}; parents_req->request = NONE; // wait till child attaches // child will signal parent // parent's signal handler will // change the value of the variable while (ch_shmat != 1); // and then signal child that we got to know that it's ready // recieve requests // on success, pid in parent will have child's pid kill(pid, SIGRTMIN); // **********************Goal********************* // actual address extension starts now { uint32_t *p; LOG; // ***First request*** // request child for 10 blocks of ui32's // request shall be updated at the last parents_req->size = 10 * sizeof(uint32_t); // changing this member must be done in the end // since, any changes to this member will act as // a notification to child parents_req->request = MALLOC; // wait till request is processed // once request is processed, child will set request // member to NONE back and that is our (parent's) // notification while(parents_req->request != NONE); // will take out the address shared by child // may be NULL checking is required (ignoring it for now) p = parents_req->p; // lets store 10 values in it (it = 10 contiguous ui32s for (uint32_t i = 0; i < 10; ++i) { // will store value of i parents_req->data = i; // make sure of the pointer that gets into request container // p + 10 is invalid (=>SEGFAULT in child) // p + 0 to p + 9 are valid parents_req->p = p + i; parents_req->request = STORE32; while(parents_req->request != NONE); } // lets access them and print them for (uint32_t i = 0; i < 10; ++i) { parents_req->p = p + i; parents_req->request = DEREF32; while(parents_req->request != NONE); printf("%i\t", (uint32_t)parents_req->data); } // lets free it parents_req->p = p; parents_req->request = FREE; while(parents_req->request != NONE); // we ask child to stop all // and quit // If this isn't done, it keeps waiting // and make us (parent) wait forever (at wait(NULL) statement) parents_req->request = QUIT; while(parents_req->request != NONE); } // ******************************************************** // detach parent from accessing shared memory // this may remove VA-PA mappings but not the actual sh-mem shmdt(shmp); shmat_failed: ; } else { // Child volatile req_t *parents_req; // may not be required // we'll sleep so that parent gets first chance sleep(1); // parent will signal us that, it got to know // we're (child) ready - handler for us to know // about it signal(SIGRTMIN, sigrtmin_handler); // signal(SIGSEGV, ch_sigsegv_handler); shmp = shmat(shmid, NULL, 0); if (shmp == (void *) -1) { puts("Child: failed to attach to shared memory segment"); goto ch_shmat_failed; } // signal parent that, child is ready to receive instructions kill(getppid(), SIGRTMIN); // and wait till parent ACKs // mark that, this variable is not shared across processes // each process gets different copies of this global-volatile byte while (ch_shmat != 1); parents_req = shmp; // ************************Core job handling****** while (1) { // process the request if there's a request in the container // else wait // It's my wish to have an else clause to while if (parents_req->request != NONE) { LOG; switch (parents_req->request) { case MALLOC: parents_req->p = malloc(parents_req->size); break; case FREE: free(parents_req->p); break; case DEREF8: parents_req->data = *(uint8_t*)(parents_req->p); break; case DEREF16: parents_req->data = *(uint16_t*)(parents_req->p); break; case DEREF32: parents_req->data = *(uint32_t*)(parents_req->p); break; case DEREF64: parents_req->data = *(uint64_t*)(parents_req->p); break; case STORE8: *(uint8_t*)(parents_req->p) = (uint8_t)(parents_req->data); break; case STORE16: *(uint16_t*)(parents_req->p) = (uint16_t)(parents_req->data); break; case STORE32: *(uint32_t*)(parents_req->p) = (uint32_t)(parents_req->data); break; case STORE64: *(uint64_t*)(parents_req->p) = (uint64_t)parents_req->data; break; case QUIT: parents_req->request = NONE; goto ch_quit; } // once the request is processed // reset the request member inorder to // notify parent that request is processed // else it'd wait forever parents_req->request = NONE; } } ch_quit: shmdt(shmp); ch_shmat_failed: ; } // Child end wait(NULL); fork_failed: if (shmctl(shmid, IPC_RMID, 0) == -1) { printf("Error while removing shared memory:"); puts(strerror(errno)); // puts("Parent: failed to destroy the created memory segment"); } shm_failed: return 0; }
the_stack_data/162643276.c
/** ****************************************************************************** * @file usbd_cdc.c * @author MCD Application Team * @brief This file provides the high layer firmware functions to manage the * following functionalities of the USB CDC Class: * - Initialization and Configuration of high and low layer * - Enumeration as CDC Device (and enumeration for each implemented memory interface) * - OUT/IN data transfer * - Command IN transfer (class requests management) * - Error management * * @verbatim * * =================================================================== * CDC Class Driver Description * =================================================================== * This driver manages the "Universal Serial Bus Class Definitions for Communications Devices * Revision 1.2 November 16, 2007" and the sub-protocol specification of "Universal Serial Bus * Communications Class Subclass Specification for PSTN Devices Revision 1.2 February 9, 2007" * This driver implements the following aspects of the specification: * - Device descriptor management * - Configuration descriptor management * - Enumeration as CDC device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN) * - Requests management (as described in section 6.2 in specification) * - Abstract Control Model compliant * - Union Functional collection (using 1 IN endpoint for control) * - Data interface class * * These aspects may be enriched or modified for a specific user application. * * This driver doesn't implement the following aspects of the specification * (but it is possible to manage these features with some modifications on this driver): * - Any class-specific aspect relative to communication classes should be managed by user application. * - All communication classes other than PSTN are not managed * * @endverbatim * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2015 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifdef USBCON #ifdef USBD_USE_CDC /* Includes ------------------------------------------------------------------*/ #include "usbd_webusb.h" #include "usbd_ctlreq.h" #include "usbd_def.h" /** @addtogroup STM32_USB_DEVICE_LIBRARY * @{ */ /** @defgroup USBD_CDC * @brief usbd core module * @{ */ /** @defgroup USBD_WebUSB_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup USBD_WebUSB_Private_Defines * @{ */ /** * @} */ /** @defgroup USBD_WebUSB_Private_Macros * @{ */ /** * @} */ /** @defgroup USBD_WebUSB_Private_FunctionPrototypes * @{ */ static uint8_t USBD_WebUSB_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx); static uint8_t USBD_WebUSB_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx); static uint8_t USBD_WebUSB_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); static uint8_t USBD_WebUSB_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum); static uint8_t USBD_WebUSB_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum); static uint8_t USBD_WebUSB_EP0_RxReady(USBD_HandleTypeDef *pdev); static uint8_t *USBD_WebUSB_GetFSCfgDesc(uint16_t *length); static uint8_t *USBD_WebUSB_GetHSCfgDesc(uint16_t *length); static uint8_t *USBD_WebUSB_GetOtherSpeedCfgDesc(uint16_t *length); static uint8_t *USBD_WebUSB_GetOtherSpeedCfgDesc(uint16_t *length); uint8_t *USBD_WebUSB_GetDeviceQualifierDescriptor(uint16_t *length); /* USB Standard Device Descriptor */ __ALIGN_BEGIN static uint8_t USBD_WebUSB_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END = { USB_LEN_DEV_QUALIFIER_DESC, USB_DESC_TYPE_DEVICE_QUALIFIER, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, }; /** * @} */ /** @defgroup USBD_WebUSB_Private_Variables * @{ */ /* CDC interface class callbacks structure */ USBD_ClassTypeDef USBD_WEBUSB_ClassDriver = { USBD_WebUSB_Init, USBD_WebUSB_DeInit, USBD_WebUSB_Setup, NULL, /* EP0_TxSent, */ USBD_WebUSB_EP0_RxReady, USBD_WebUSB_DataIn, USBD_WebUSB_DataOut, NULL, NULL, NULL, USBD_WebUSB_GetHSCfgDesc, USBD_WebUSB_GetFSCfgDesc, USBD_WebUSB_GetOtherSpeedCfgDesc, USBD_WebUSB_GetDeviceQualifierDescriptor, }; /* USB CDC device Configuration Descriptor */ __ALIGN_BEGIN static uint8_t USBD_WebUSB_CfgHSDesc[USB_WebUSB_CONFIG_DESC_SIZ] __ALIGN_END = { /* Configuration Descriptor */ 0x09, /* bLength: Configuration Descriptor size */ USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ USB_WebUSB_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */ 0x00, 0x03, /* bNumInterfaces: 3 interface */ 0x01, /* bConfigurationValue: Configuration value */ 0x00, /* iConfiguration: Index of string descriptor describing the configuration */ 0xC0, /* bmAttributes: self powered */ 0x32, /* MaxPower 0 mA */ /*---------------------------------------------------------------------------*/ /* --- CDC -- */ /* Interface Descriptor */ 0x09, /* bLength: Interface Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ /* Interface descriptor type */ 0x00, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x01, /* bNumEndpoints: One endpoints used */ 0x02, /* bInterfaceClass: Communication Interface Class */ 0x02, /* bInterfaceSubClass: Abstract Control Model */ 0x00, /* bInterfaceProtocol: No specific protocol */ 0x00, /* iInterface: */ /* Header Functional Descriptor */ 0x05, /* bLength: Endpoint Descriptor size */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x00, /* bDescriptorSubtype: Header Func Desc */ 0x10, /* bcdCDC: spec release number */ 0x01, /* Call Management Functional Descriptor */ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x01, /* bDescriptorSubtype: Call Management Func Desc */ 0x00, /* bmCapabilities: D0+D1 */ 0x01, /* bDataInterface: 1 */ /* ACM Functional Descriptor */ 0x04, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x02, /* bDescriptorSubtype: Abstract Control Management desc */ 0x02, /* bmCapabilities */ /* Union Functional Descriptor */ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x06, /* bDescriptorSubtype: Union func desc */ 0x00, /* bMasterInterface: Communication class interface */ 0x01, /* bSlaveInterface0: Data Class Interface */ /* Endpoint 2 Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_CMD_EP, /* bEndpointAddress */ 0x03, /* bmAttributes: Interrupt */ LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_CMD_PACKET_SIZE), WebUSB_HS_BINTERVAL, /* bInterval: */ /*---------------------------------------------------------------------------*/ /* Data class interface descriptor */ 0x09, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */ 0x01, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x02, /* bNumEndpoints: Two endpoints used */ 0x0A, /* bInterfaceClass: CDC */ 0x00, /* bInterfaceSubClass: */ 0x00, /* bInterfaceProtocol: */ 0x00, /* iInterface: */ /* Endpoint OUT Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_OUT_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), 0x00, /* bInterval: ignore for Bulk transfer */ /* Endpoint IN Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_IN_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ LOBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_DATA_HS_MAX_PACKET_SIZE), 0x00, /* bInterval: ignore for Bulk transfer */ /* --- WEB USB --- */ /* Interface Descriptor */ 0x09, // bLength USB_DESC_TYPE_INTERFACE, // bDescriptorType : Interface 0x03, // bInterfaceNumber 0x00, // bAlternateSetting 0x00, // bNumEndpoints 0xFF, // bInterfaceClass 0x03, // bInterfaceSubClass 0x00, // bInterfaceProtocol 0x0A, // bInterface }; /* USB CDC device Configuration Descriptor */ __ALIGN_BEGIN static uint8_t USBD_WebUSB_CfgFSDesc[USB_WebUSB_CONFIG_DESC_SIZ] __ALIGN_END = { /* Configuration Descriptor */ 0x09, /* bLength: Configuration Descriptor size */ USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ USB_WebUSB_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */ 0x00, 0x03, /* bNumInterfaces: 3 interface */ 0x01, /* bConfigurationValue: Configuration value */ 0x00, /* iConfiguration: Index of string descriptor describing the configuration */ 0xC0, /* bmAttributes: self powered */ 0x32, /* MaxPower 0 mA */ /*---------------------------------------------------------------------------*/ /* --- CDC -- */ /* Interface Descriptor */ 0x09, /* bLength: Interface Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ /* Interface descriptor type */ 0x00, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x01, /* bNumEndpoints: One endpoints used */ 0x02, /* bInterfaceClass: Communication Interface Class */ 0x02, /* bInterfaceSubClass: Abstract Control Model */ 0x00, /* bInterfaceProtocol: No specific protocol */ 0x00, /* iInterface: */ /* Header Functional Descriptor */ 0x05, /* bLength: Endpoint Descriptor size */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x00, /* bDescriptorSubtype: Header Func Desc */ 0x10, /* bcdCDC: spec release number */ 0x01, /* Call Management Functional Descriptor */ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x01, /* bDescriptorSubtype: Call Management Func Desc */ 0x00, /* bmCapabilities: D0+D1 */ 0x01, /* bDataInterface: 1 */ /* ACM Functional Descriptor */ 0x04, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x02, /* bDescriptorSubtype: Abstract Control Management desc */ 0x02, /* bmCapabilities */ /* Union Functional Descriptor */ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x06, /* bDescriptorSubtype: Union func desc */ 0x00, /* bMasterInterface: Communication class interface */ 0x01, /* bSlaveInterface0: Data Class Interface */ /* Endpoint 2 Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_CMD_EP, /* bEndpointAddress */ 0x03, /* bmAttributes: Interrupt */ LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_CMD_PACKET_SIZE), WebUSB_FS_BINTERVAL, /* bInterval: */ /*---------------------------------------------------------------------------*/ /* Data class interface descriptor */ 0x09, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */ 0x01, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x02, /* bNumEndpoints: Two endpoints used */ 0x0A, /* bInterfaceClass: CDC */ 0x00, /* bInterfaceSubClass: */ 0x00, /* bInterfaceProtocol: */ 0x00, /* iInterface: */ /* Endpoint OUT Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_OUT_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), 0x00, /* bInterval: ignore for Bulk transfer */ /* Endpoint IN Descriptor */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_IN_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), 0x00, /* bInterval: ignore for Bulk transfer */ /* --- WEB USB --- */ /* Interface Descriptor */ 0x09, // bLength USB_DESC_TYPE_INTERFACE, // bDescriptorType : Interface 0x03, // bInterfaceNumber 0x00, // bAlternateSetting 0x00, // bNumEndpoints 0xFF, // bInterfaceClass 0x03, // bInterfaceSubClass 0x00, // bInterfaceProtocol 0x0A, // bInterface }; __ALIGN_BEGIN static uint8_t USBD_WebUSB_OtherSpeedCfgDesc[USB_WebUSB_CONFIG_DESC_SIZ] __ALIGN_END = { 0x09, /* bLength: Configuation Descriptor size */ USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION, USB_WebUSB_CONFIG_DESC_SIZ, 0x00, 0x03, /* bNumInterfaces: 3 interfaces */ 0x01, /* bConfigurationValue: */ 0x04, /* iConfiguration: */ 0xC0, /* bmAttributes: */ 0x32, /* MaxPower 100 mA */ /* --- CDC -- */ /*Interface Descriptor */ 0x09, /* bLength: Interface Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */ /* Interface descriptor type */ 0x00, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x01, /* bNumEndpoints: One endpoints used */ 0x02, /* bInterfaceClass: Communication Interface Class */ 0x02, /* bInterfaceSubClass: Abstract Control Model */ 0x00, /* bInterfaceProtocol: No specific protocol */ 0x00, /* iInterface: */ /* Header Functional Descriptor */ 0x05, /* bLength: Endpoint Descriptor size */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x00, /* bDescriptorSubtype: Header Func Desc */ 0x10, /* bcdCDC: spec release number */ 0x01, /*Call Management Functional Descriptor*/ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x01, /* bDescriptorSubtype: Call Management Func Desc */ 0x00, /* bmCapabilities: D0+D1 */ 0x01, /* bDataInterface: 1 */ /*ACM Functional Descriptor*/ 0x04, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x02, /* bDescriptorSubtype: Abstract Control Management desc */ 0x02, /* bmCapabilities */ /*Union Functional Descriptor*/ 0x05, /* bFunctionLength */ 0x24, /* bDescriptorType: CS_INTERFACE */ 0x06, /* bDescriptorSubtype: Union func desc */ 0x00, /* bMasterInterface: Communication class interface */ 0x01, /* bSlaveInterface0: Data Class Interface */ /*Endpoint 2 Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_CMD_EP, /* bEndpointAddress */ 0x03, /* bmAttributes: Interrupt */ LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize: */ HIBYTE(CDC_CMD_PACKET_SIZE), WebUSB_FS_BINTERVAL, /* bInterval: */ /*---------------------------------------------------------------------------*/ /*Data class interface descriptor*/ 0x09, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */ 0x01, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x02, /* bNumEndpoints: Two endpoints used */ 0x0A, /* bInterfaceClass: CDC */ 0x00, /* bInterfaceSubClass: */ 0x00, /* bInterfaceProtocol: */ 0x00, /* iInterface: */ /*Endpoint OUT Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_OUT_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ 0x40, /* wMaxPacketSize: */ 0x00, 0x00, /* bInterval: ignore for Bulk transfer */ /*Endpoint IN Descriptor*/ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */ CDC_IN_EP, /* bEndpointAddress */ 0x02, /* bmAttributes: Bulk */ 0x40, /* wMaxPacketSize: */ 0x00, 0x00, /* bInterval */ /* --- WEB USB --- */ /* Interface Descriptor */ 0x09, // bLength USB_DESC_TYPE_INTERFACE, // bDescriptorType : Interface 0x03, // bInterfaceNumber 0x00, // bAlternateSetting 0x00, // bNumEndpoints 0xFF, // bInterfaceClass 0x03, // bInterfaceSubClass 0x00, // bInterfaceProtocol 0x0A, // bInterface }; /** * @} */ /** @defgroup USBD_WebUSB_Private_Functions * @{ */ /** * @brief USBD_WebUSB_Init * Initialize the CDC interface * @param pdev: device instance * @param cfgidx: Configuration index * @retval status */ static uint8_t USBD_WebUSB_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx) { UNUSED(cfgidx); USBD_WebUSB_HandleTypeDef *hcdc; hcdc = USBD_malloc(sizeof(USBD_WebUSB_HandleTypeDef)); if (hcdc == NULL) { pdev->pClassData = NULL; return (uint8_t)USBD_EMEM; } pdev->pClassData = (void *)hcdc; if (pdev->dev_speed == USBD_SPEED_HIGH) { /* Open EP IN */ (void)USBD_LL_OpenEP(pdev, CDC_IN_EP, USBD_EP_TYPE_BULK, WebUSB_DATA_HS_IN_PACKET_SIZE); pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 1U; /* Open EP OUT */ (void)USBD_LL_OpenEP(pdev, CDC_OUT_EP, USBD_EP_TYPE_BULK, WebUSB_DATA_HS_OUT_PACKET_SIZE); pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 1U; /* Set bInterval for CDC CMD Endpoint */ pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = WebUSB_HS_BINTERVAL; } else { /* Open EP IN */ (void)USBD_LL_OpenEP(pdev, CDC_IN_EP, USBD_EP_TYPE_BULK, WebUSB_DATA_FS_IN_PACKET_SIZE); pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 1U; /* Open EP OUT */ (void)USBD_LL_OpenEP(pdev, CDC_OUT_EP, USBD_EP_TYPE_BULK, WebUSB_DATA_FS_OUT_PACKET_SIZE); pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 1U; /* Set bInterval for CMD Endpoint */ pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = WebUSB_FS_BINTERVAL; } /* Open Command IN EP */ (void)USBD_LL_OpenEP(pdev, CDC_CMD_EP, USBD_EP_TYPE_INTR, CDC_CMD_PACKET_SIZE); pdev->ep_in[CDC_CMD_EP & 0xFU].is_used = 1U; /* Init physical Interface components */ ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->Init(); /* Init Xfer states */ hcdc->TxState = 0U; hcdc->RxState = 0U; if (pdev->dev_speed == USBD_SPEED_HIGH) { /* Prepare Out endpoint to receive next packet */ (void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer, WebUSB_DATA_HS_OUT_PACKET_SIZE); } else { /* Prepare Out endpoint to receive next packet */ (void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer, WebUSB_DATA_FS_OUT_PACKET_SIZE); } return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_Init * DeInitialize the CDC layer * @param pdev: device instance * @param cfgidx: Configuration index * @retval status */ static uint8_t USBD_WebUSB_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx) { UNUSED(cfgidx); uint8_t ret = 0U; /* Close EP IN */ (void)USBD_LL_CloseEP(pdev, CDC_IN_EP); pdev->ep_in[CDC_IN_EP & 0xFU].is_used = 0U; /* Close EP OUT */ (void)USBD_LL_CloseEP(pdev, CDC_OUT_EP); pdev->ep_out[CDC_OUT_EP & 0xFU].is_used = 0U; /* Close Command IN EP */ (void)USBD_LL_CloseEP(pdev, CDC_CMD_EP); pdev->ep_in[CDC_CMD_EP & 0xFU].is_used = 0U; pdev->ep_in[CDC_CMD_EP & 0xFU].bInterval = 0U; /* DeInit physical Interface components */ if (pdev->pClassData != NULL) { ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->DeInit(); (void)USBD_free(pdev->pClassData); pdev->pClassData = NULL; } return ret; } /** * @brief USBD_WebUSB_Setup * Handle the CDC specific requests * @param pdev: instance * @param req: usb requests * @retval status */ static uint8_t USBD_WebUSB_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *) pdev->pClassData; uint8_t ifalt = 0U; uint16_t status_info = 0U; USBD_StatusTypeDef ret = USBD_OK; switch (req->bmRequest & USB_REQ_TYPE_MASK) { case USB_REQ_TYPE_CLASS: if (req->wLength != 0U) { if ((req->bmRequest & 0x80U) != 0U) { ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->Control(req->bRequest, (uint8_t *)hcdc->data, req->wLength); (void)USBD_CtlSendData(pdev, (uint8_t *)hcdc->data, req->wLength); } else { hcdc->CmdOpCode = req->bRequest; hcdc->CmdLength = (uint8_t)req->wLength; (void)USBD_CtlPrepareRx(pdev, (uint8_t *)hcdc->data, req->wLength); } } else { ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->Control(req->bRequest, (uint8_t *)req, 0U); } break; case USB_REQ_TYPE_STANDARD: switch (req->bRequest) { case USB_REQ_GET_STATUS: if (pdev->dev_state == USBD_STATE_CONFIGURED) { (void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U); } else { USBD_CtlError(pdev, req); ret = USBD_FAIL; } break; case USB_REQ_GET_INTERFACE: if (pdev->dev_state == USBD_STATE_CONFIGURED) { (void)USBD_CtlSendData(pdev, &ifalt, 1U); } else { USBD_CtlError(pdev, req); ret = USBD_FAIL; } break; case USB_REQ_SET_INTERFACE: if (pdev->dev_state != USBD_STATE_CONFIGURED) { USBD_CtlError(pdev, req); ret = USBD_FAIL; } break; case USB_REQ_CLEAR_FEATURE: break; default: USBD_CtlError(pdev, req); ret = USBD_FAIL; break; } break; default: USBD_CtlError(pdev, req); ret = USBD_FAIL; break; } return (uint8_t)ret; } /** * @brief USBD_WebUSB_DataIn * Data sent on non-control IN endpoint * @param pdev: device instance * @param epnum: endpoint number * @retval status */ static uint8_t USBD_WebUSB_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum) { USBD_WebUSB_HandleTypeDef *hcdc; PCD_HandleTypeDef *hpcd = pdev->pData; if (pdev->pClassData == NULL) { return (uint8_t)USBD_FAIL; } hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; if ((pdev->ep_in[epnum].total_length > 0U) && ((pdev->ep_in[epnum].total_length % hpcd->IN_ep[epnum].maxpacket) == 0U)) { /* Update the packet total length */ pdev->ep_in[epnum].total_length = 0U; /* Send ZLP */ (void)USBD_LL_Transmit(pdev, epnum, NULL, 0U); } else { hcdc->TxState = 0U; ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->TransmitCplt(hcdc->TxBuffer, &hcdc->TxLength, epnum); } return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_DataOut * Data received on non-control Out endpoint * @param pdev: device instance * @param epnum: endpoint number * @retval status */ static uint8_t USBD_WebUSB_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; if (pdev->pClassData == NULL) { return (uint8_t)USBD_FAIL; } /* Get the received data length */ hcdc->RxLength = USBD_LL_GetRxDataSize(pdev, epnum); /* USB data will be immediately processed, this allow next USB traffic being NAKed till the end of the application Xfer */ ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->Receive(hcdc->RxBuffer, &hcdc->RxLength); return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_EP0_RxReady * Handle EP0 Rx Ready event * @param pdev: device instance * @retval status */ static uint8_t USBD_WebUSB_EP0_RxReady(USBD_HandleTypeDef *pdev) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; if ((pdev->pUserData != NULL) && (hcdc->CmdOpCode != 0xFFU)) { ((USBD_WebUSB_ItfTypeDef *)pdev->pUserData)->Control(hcdc->CmdOpCode, (uint8_t *)hcdc->data, (uint16_t)hcdc->CmdLength); hcdc->CmdOpCode = 0xFFU; } return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_GetFSCfgDesc * Return configuration descriptor * @param speed : current device speed * @param length : pointer data length * @retval pointer to descriptor buffer */ static uint8_t *USBD_WebUSB_GetFSCfgDesc(uint16_t *length) { *length = (uint16_t)sizeof(USBD_WebUSB_CfgFSDesc); return USBD_WebUSB_CfgFSDesc; } /** * @brief USBD_WebUSB_GetHSCfgDesc * Return configuration descriptor * @param speed : current device speed * @param length : pointer data length * @retval pointer to descriptor buffer */ static uint8_t *USBD_WebUSB_GetHSCfgDesc(uint16_t *length) { *length = (uint16_t)sizeof(USBD_WebUSB_CfgHSDesc); return USBD_WebUSB_CfgHSDesc; } /** * @brief USBD_WebUSB_GetCfgDesc * Return configuration descriptor * @param speed : current device speed * @param length : pointer data length * @retval pointer to descriptor buffer */ static uint8_t *USBD_WebUSB_GetOtherSpeedCfgDesc(uint16_t *length) { *length = (uint16_t)sizeof(USBD_WebUSB_OtherSpeedCfgDesc); return USBD_WebUSB_OtherSpeedCfgDesc; } /** * @brief DeviceQualifierDescriptor * return Device Qualifier descriptor * @param length : pointer data length * @retval pointer to descriptor buffer */ uint8_t *USBD_WebUSB_GetDeviceQualifierDescriptor(uint16_t *length) { *length = (uint16_t)sizeof(USBD_WebUSB_DeviceQualifierDesc); return USBD_WebUSB_DeviceQualifierDesc; } /** * @brief USBD_WebUSB_RegisterInterface * @param pdev: device instance * @param fops: CD Interface callback * @retval status */ uint8_t USBD_WebUSB_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_WebUSB_ItfTypeDef *fops) { if (fops == NULL) { return (uint8_t)USBD_FAIL; } pdev->pUserData = fops; return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_SetTxBuffer * @param pdev: device instance * @param pbuff: Tx Buffer * @retval status */ uint8_t USBD_WebUSB_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff, uint32_t length) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; hcdc->TxBuffer = pbuff; hcdc->TxLength = length; return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_SetRxBuffer * @param pdev: device instance * @param pbuff: Rx Buffer * @retval status */ uint8_t USBD_WebUSB_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; hcdc->RxBuffer = pbuff; return (uint8_t)USBD_OK; } /** * @brief USBD_WebUSB_TransmitPacket * Transmit packet on IN endpoint * @param pdev: device instance * @retval status */ uint8_t USBD_WebUSB_TransmitPacket(USBD_HandleTypeDef *pdev) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; USBD_StatusTypeDef ret = USBD_BUSY; if (pdev->pClassData == NULL) { return (uint8_t)USBD_FAIL; } if (hcdc->TxState == 0U) { /* Tx Transfer in progress */ hcdc->TxState = 1U; /* Update the packet total length */ pdev->ep_in[CDC_IN_EP & 0xFU].total_length = hcdc->TxLength; /* Transmit next packet */ (void)USBD_LL_Transmit(pdev, CDC_IN_EP, hcdc->TxBuffer, hcdc->TxLength); ret = USBD_OK; } return (uint8_t)ret; } /** * @brief USBD_WebUSB_ReceivePacket * prepare OUT Endpoint for reception * @param pdev: device instance * @retval status */ uint8_t USBD_WebUSB_ReceivePacket(USBD_HandleTypeDef *pdev) { USBD_WebUSB_HandleTypeDef *hcdc = (USBD_WebUSB_HandleTypeDef *)pdev->pClassData; if (pdev->pClassData == NULL) { return (uint8_t)USBD_FAIL; } if (pdev->dev_speed == USBD_SPEED_HIGH) { /* Prepare Out endpoint to receive next packet */ (void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer, WebUSB_DATA_HS_OUT_PACKET_SIZE); } else { /* Prepare Out endpoint to receive next packet */ (void)USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, hcdc->RxBuffer, WebUSB_DATA_FS_OUT_PACKET_SIZE); } return (uint8_t)USBD_OK; } uint8_t USBD_WebUSB_ClearBuffer(USBD_HandleTypeDef *pdev) { /* Suspend or Resume USB Out process */ if (pdev->pClassData != NULL) { /* Prepare Out endpoint to receive next packet */ USBD_LL_PrepareReceive(pdev, CDC_OUT_EP, 0, 0); return (uint8_t)USBD_OK; } else { return (uint8_t)USBD_FAIL; } } #endif /* USBD_USE_CDC */ #endif /* USBCON */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/102530.c
/* Copyright 1990-2008, Jsoftware Inc. All rights reserved. */ /* Licensed use only. Any other use is in violation of copyright. */ /* */ /* Conjunctions: Differentiation and Integration */ #if 0 #include "j.h" // returns TRUE if w is a constant verb m"r static B jtiscons(J jt,A w){A x;V*v; if(!w)R 0; v=VAV(w); x=v->fgh[0]; R CQQ==v->id&&NOUN&AT(x)&&!AR(x); } static const C ispoly1[]={CLEFT,CRIGHT,CLE,CGE,CNOT,CMINUS,CPLUSCO,CHALVE,CCIRCLE,CJDOT,0}; static I jtispoly(J jt,A w){A e,f,g,h,x,y;B nf,ng,vf,vg;C c,id;I k,m,n,t;V*v; if(!w)R 0; v=VAV(w); id=v->id; if(id==CFCONS||iscons(w))R 1; if(strchr(ispoly1,id))R 2; if(id==CSTARCO)R 3; f=v->fgh[0]; nf=f&&NOUN&AT(f); vf=!nf; g=v->fgh[1]; ng=g&&NOUN&AT(g); vg=!ng; x=nf?f:g; t=x?AT(x):0; h=nf?g:f; c=h?ID(h):0; if(id==CFORK){ if(!(vf&&vg))R 0; m=ispoly(f); n=ispoly(v->fgh[2]); switch(m&&n?ID(g):0){ case CPLUS: R MAX(m,n); case CSTAR: R m+n-1; }} if(vf&&vg&&(id==CAT||id==CATCO||id==CAMP||id==CAMPCO)){m=ispoly(f); n=ispoly(g); if(m&&n)R 1+(m-1)*(n-1);} if(!(id==CAMP&&(t&NUMERIC||c==CPOLY)))R 0; if(nf&&1>=AR(x)&&c==CPOLY){ if(!(t&BOX+NUMERIC))R 0; SETIC(x,k); if(t&NUMERIC)R k; y=*(AAV(x)+k-1); if(!(2>=AR(y)))R 0; if(1>=AR(y))R 1+IC(y); if(!(2==AS(y)[1]))R 0; RZ(e=irs1(y,0L,1L,jttail)); RZ(equ(e,floor1(e))&&all1(le(zeroionei(0),e))); RZ(y=aslash(CMAX,cvt(INT,e))); R 1+*AV(y); } if(nf==ng||AR(x))R 0; if(c==CPLUS||c==CMINUS||c==CSTAR||c==CDIV&&ng)R 2; RZ(x=pcvt(INT,x)); if(!(INT&AT(x)))R 0; k=*AV(x); R 0<=k&&(c==CBANG&&nf||c==CEXP&&ng)?1+k:0; } /* 1 + degree of polynomial (0 if not poly) */ static F1(jtfpolyc){A b;B*bv;I m,n; RZ(b=ne(w,zeroionei(0))); bv=BAV(b); m=n=AN(w); DQ(n, if(bv[--m])break;); ++m; if(m<n)RZ(w=take(sc(m),w)); n=m; switch(n){ case 1: R qq(head(w),zeroionei(0)); case 3: if(equ(w,over(v2(0L,0L),zeroionei(1))))R ds(CSTARCO); break; case 2: if(equ(w,v2( 0L,-1L))) R ds(CMINUS); if(equ(w,v2( 1L,-1L))) R ds(CNOT); if(equ(w,v2(-1L, 1L))) R ds(CLE); if(equ(w,v2( 0L, 1L))) R ds(CLEFT); if(equ(w,v2( 1L, 1L))) R ds(CGE); if(equ(w,v2( 0L, 2L))) R ds(CPLUSCO); if(equ(w,over(num(0),onehalf)))R ds(CHALVE); if(equ(w,over(num(0),pie)))R ds(CCIRCLE); if(equ(w,over(num(0),a0j1 )))R ds(CJDOT); } R amp(w,ds(CPOLY)); } static A jtfpoly(J jt,I n,A f){I m=0>n?1:1+n; RZ(f); R fpolyc(df1(IX(m),tdot(f)));} static F1(jtfnegate){V*v; ARGCHK1(w); v=VAV(w); R CAT==v->id&&CMINUS==ID(v->fgh[0])?v->fgh[1]:atop(ds(CMINUS),w);} static F2(jtfplus){ ARGCHK2(a,w); if(iscons(a)&&equ(VAV(a)->fgh[0],zeroionei(0)))R w; if(iscons(w)&&equ(VAV(w)->fgh[0],zeroionei(0)))R a; R folk(a,ds(CPLUS),w); } static F2(jtfminus){ ARGCHK2(a,w); if(iscons(a)&&equ(VAV(a)->fgh[0],zeroionei(0)))R fnegate(w); if(iscons(w)&&equ(VAV(w)->fgh[0],zeroionei(0)))R a; R folk(a,ds(CMINUS),w); } static F2(jtftymes){A x,y;B b,c;I k; ARGCHK2(a,w); b=iscons(a); x=VAV(a)->fgh[0]; c=iscons(w); y=VAV(w)->fgh[0]; if(CFORK==ID(w)&&NOUN&AT(y))R ftymes(a,folk(qq(y,ainf),VAV(w)->fgh[1],VAV(w)->fgh[2])); if(b&&AT(x)&B01+INT){k=i0(x); if(-1<=k&&k<=1)R !k?a:0<k?w:fnegate(w);} if(c&&AT(y)&B01+INT){k=i0(y); if(-1<=k&&k<=1)R !k?w:0<k?a:fnegate(a);} if(b&&CFORK==ID(w)&&iscons(y))R ftymes(qq(tymes(x,VAV(y)->fgh[0]),zeroionei(0)),VAV(w)->fgh[2]); R c?folk(w,ds(CSTAR),a):folk(a,ds(CSTAR),w); } static F1(jtdpoly){A c,e,x;I n,t; ARGCHK1(w); n=AN(w); t=AT(w); ASSERT(!n||t&NUMERIC+BOX,EVDOMAIN); if(!n||t&NUMERIC)R 2>=n?qq(2==n?tail(w):cvt(n?t:B01,num(0)),zeroionei(0)):fpolyc(behead(tymes(w,IX(n)))); x=AAV(w)[0]; if(1<n||1>=AR(x))R dpoly(poly1(w)); ASSERT(2==AR(x)&&2==AS(x)[1],EVDOMAIN); c=irs1(x,0L,1L,jthead); e=irs1(x,0L,1L,jttail); R amp(box(stitch(tymes(c,e),minus(e,zeroionei(1)))),ds(CPOLY)); } static F1(jtipoly){A b,c,e,p=0,q=0,x;I n,t; ARGCHK1(w); n=AN(w); t=AT(w); ASSERT(!n||t&NUMERIC+BOX,EVDOMAIN); if(!n||t&NUMERIC)R fpolyc(over(num(0),divide(w,apv(n,1L,1L)))); x=AAV(w)[0]; if(1<n||1>=AR(x))R ipoly(poly1(w)); ASSERT(2==AR(x)&&2==AS(x)[1],EVDOMAIN); RZ(c=irs1(x,0L,1L,jthead)); RZ(e=plus(zeroionei(1),irs1(x,0L,1L,jttail))); RZ(b=ne(e,zeroionei(0))); if(!all0(b))RZ(p=amp(box(repeat(b,stitch(divide(c,e),e))),ds(CPOLY))); if(!all1(b))RZ(q=evc(not(b),c,"(+/x#y)&*@^.")); R p&&q?folk(p,ds(CPLUS),q):p?p:q; } static F1(jticube){R atco(eval("* =/~@(i.@$)"),w);} static F1(jtdiffamp0){A f,g,h,x,y;B nf,ng;C id;V*v; ARGCHK1(w); v=VAV(w); f=v->fgh[0]; nf=1&&NOUN&AT(f); g=v->fgh[1]; ng=1&&NOUN&AT(g); h=nf?g:f; id=ID(h); x=nf?f:g; // h is the verb, id is its id; x is the noun if(!(!AR(x)||id==CPOLY))R 0; switch(id){ case CPLUS: R qq(num(1),zeroionei(0)); case CSTAR: R qq(x,zeroionei(0)); case CMINUS: R qq(num(nf?-1:1),zeroionei(0)); case CDIV: R nf?eva(x,"(-x)&%@*:"):qq(recip(x),zeroionei(0)); case CPOLY: if(nf)R dpoly(x); break; case CBANG: if(nf&&!AR(x))R dpoly(df1(iota(increm(x)),tdot(w))); break; case CROOT: if(nf&&!AR(x))R atop(amp(recip(x),ds(CSTAR)),amp(ds(CEXP),decrem(recip(x)))); break; case CLOG: R eva(logar1(x),nf?"(%x)&%":"(-x)&%@(* *:@^.)"); case CEXP: if(nf)R evc(x,w,"(^.x)&*@y"); RZ(y=pcvt(INT,x)); if(INT&AT(y))switch(*AV(y)){ case 0: R qq(num(0),zeroionei(0)); case 1: R qq(num(1),zeroionei(0)); case 2: R ds(CPLUSCO); } R eva(x,"x&*@(^&(x-1))"); case CCIRCLE: if(nf){ RZ(x=vi(x)); switch(*AV(x)){ case 0: R folk(ds(CMINUS),ds(CDIV),w); case 1: R amp(num(2),h); case 2: R atop(ds(CMINUS),amp(num(1),h)); case 3: R atop(atop(ds(CDIV),ds(CSTARCO)),amp(num(2),h)); case 5: R amp(num[6],h); case 6: R amp(num(5),h); case 7: R atop(atop(ds(CDIV),ds(CSTARCO)),amp(num[6],h)); }}} R A0; } static F1(jtdiff0){A df,dg,dh,f,g,h,x,y,z;B b,nf,ng,vf,vg;C id;I m,p,q;V*v; ARGCHK1(w); v=VAV(w); id=v->id; f=v->fgh[0]; nf=f&&NOUN&AT(f); vf=f&&!nf; // nf=f is a noun vf=f is a verb same for ng, vg g=v->fgh[1]; ng=g&&NOUN&AT(g); vg=g&&!ng; if(id==CAMP&&nf!=ng)R diffamp0(w); switch(id){ case CLE: case CGE: case CLEFT: case CRIGHT: R qq(num(1),zeroionei(0)); case CPLUSCO: R qq(num(2),zeroionei(0)); case CNOT: case CMINUS: R qq(num(-1),zeroionei(0)); case CFCONS: R qq(num(0),zeroionei(0)); case CSTARCO: R ds(CPLUSCO); case CHALVE: R qq(connum(3L,"1r2"),zeroionei(0)); case CCIRCLE: R qq(pie,zeroionei(0)); case CDIV: R eval("- @%@*:"); case CSQRT: R eval("-:@%@%:"); case CEXP: R w; case CLOG: R ds(CDIV); case CJDOT: R qq(a0j1,zeroionei(0)); case CRDOT: R atop(ds(CJDOT),w); case CDDOT: if(vf&&ng)R ddot(f,increm(g)); break; case CPOWOP: if(vf&&ng&&!AR(g))switch(p=i0(g)){ case -1: R diff0(inv(f)); case 0: RE(0); R qq(num(1),zeroionei(0)); case 1: R diff0(f); default: if(0>p){RZ(f=inv(f)); p=-p;} if(q=ispoly(f)){RE(m=i0(vib(expn2(sc(q-1),g)))); R dpoly(df1(IX(1+m),tdot(w)));} R diff0(atop(powop(f,sc(p-1),0),f)); } break; case CQQ: if(!AR(f)&&NUMERIC&AT(f)&&ng&&equ(g,zeroionei(0)))R qq(num(0),zeroionei(0)); if(vf&&ng)R qq(diff0(f),g); break; case CAT: case CATCO: case CAMP: case CAMPCO: if(vf&&vg){ p=ispoly(f); q=ispoly(g); if(p&&q)R dpoly(df1(IX(1+(p-1)*(q-1)),tdot(w))); if(!(dg=diff0(g)))R A0; if(!(df=diff0(f)))R A0; v=VAV(df); x=v->fgh[0]; if(CQQ!=v->id)R ftymes(dg,atop(df,g)); switch(CQQ==v->id&&AT(x)&B01+INT?i0(x):9){ case 0: R df; case 1: R dg; case 2: R atop(ds(CPLUSCO),dg); case -1: R fnegate(dg); default: R ftymes(df,dg); }} break; case CTILDE: if(vf)switch(ID(f)){ case CPLUS: R qq(num(2),zeroionei(0)); case CSTAR: R ds(CPLUSCO); case CMINUS: case CLOG: case CDIV: R qq(num(0),zeroionei(0)); case CEXP: R eva(w,"x * >:@^."); } break; case CFORK: h=v->fgh[2]; if(NOUN&AT(f))R diff0(folk(qq(f,zeroionei(0)),g,h)); if(CCAP==ID(f))R diff0(atco(g,h)); p=ispoly(f); if(!(df=diff0(f)))R A0; q=ispoly(h); if(!(dh=diff0(h)))R A0; b=p&&q; switch(ID(g)){ case CPLUS: z=fplus (df,dh); R b?fpoly(MAX(p,q)-1,z):z; case CMINUS: z=fminus(df,dh); R b?fpoly(MAX(p,q)-1,z):z; case CSTAR: z=fplus(ftymes(df,h),ftymes(f,dh)); R b?fpoly(p+q,z):z; case CCOMMA: R folk(df,g,dh); case CDIV: x=fminus(ftymes(df,h),ftymes(f,dh)); y=atop(ds(CSTARCO),h); R folk(b?fpoly(p+q-1-(I )(p==q),x):x,ds(CDIV),q?fpoly(q+q,y):y); case CEXP: if(1==q){A k; RZ(k=df1(num(0),h)); if(equ(k,zeroionei(0)))R qq(num(0),zeroionei(0)); if(equ(k,zeroionei(1)))R df; if(equ(k,num(2)))R ftymes(df,ftymes(h,f)); R ftymes(df,ftymes(h,folk(f,g,qq(decrem(k),zeroionei(0))))); } }} R A0; } // integrals of f&g, where exactly one of f,g is a noun static F1(jtintgamp0){A f,g,h,x,y;B nf,ng;C id;V*v; ARGCHK1(w); v=VAV(w); f=v->fgh[0]; nf=1&&NOUN&AT(f); // nf means f is a noun, ng means g is a noun g=v->fgh[1]; ng=1&&NOUN&AT(g); h=nf?g:f; id=ID(h); x=nf?f:g; // h is the verb operand, x is the noun if(!(!AR(x)||id==CPOLY))R A0; // give up if noun is not an atom, except for p. switch(id){ case CPLUS: R ipoly(over(x,zeroionei(1))); case CSTAR: R ipoly(over(zeroionei(0),x)); case CMINUS: R nf?ipoly(over(x,num(-1))):ipoly(over(negate(x),zeroionei(1))); case CDIV: R nf?eva(x,"x&*@^."):ipoly(over(num(0),recip(x))); case CPOLY: if(nf)R ipoly(x); break; case CBANG: if(nf&&AT(x))R ipoly(df1(iota(increm(x)),tdot(w))); break; case CEXP: if(ng){ // ^&x x must be an atom here if(equ(x,num(-1)))R ds(CLOG); // ^_1 => log RZ(y=pcvt(INT,x)); // if y is an INT and value > 0, integrate as polynomial (ipoly), else do y^(a+1) / (a+1). // For non-positive integer case, J representation is %&(a+1)@(^&(a+1)) // We could just use y^(a+1) / (a+1) for all cases, but the ipoly form is better to feed into further symbolic processing R ((INT&AT(y))&&i0(y)>0)? ipoly(take(sc(-1-i0(y)),num(1))) : atop(amp(ds(CDIV),increm(y)),amp(ds(CEXP),increm(y))); } else { // x&^ /* e.g. a^y for some y (i.e. an exponential without base e). Integrate as exp(log(a) * y). If a is negative the result will be complex. J example: (2&^) d. _1 %&(^.2)@(2&^) For the case where a=0, this will cause an error.*/ if(equ(x,zeroionei(0)))R A0; // 0^h gives domain error R atop(amp(ds(CDIV),logar1(x)), amp(x,ds(CEXP))); // J: %&(^. a)@(a&^) } case CCIRCLE: if(nf){ RZ(x=vi(x)); switch(*AV(x)){ case 1: R atop(ds(CMINUS),amp(num(2),h)); case 2: R amp(num(1),h); case 3: R eval("-@^.@(2&o.)"); case 5: R amp(num[6],h); case 6: R amp(num(5),h); case 7: R atop(ds(CLOG),amp(num[6],h)); }}} R A0; } static F1(jtintg0); static F2(jtintgatop){A df,f=a,g=w,q,x,y;I m,n;V*v; ARGCHK2(a,w); m=ispoly(f); n=ispoly(g); if(m&&n)R ipoly(df1(IX(1+(m-1)*(n-1)),tdot(atop(a,w)))); if(2==m){ RZ(q=v2(0L,1L)); RZ(x=df1(q,tdot(f))); RZ(y=equ(zeroionei(1), tail(x))?intg0(g):atop(fpolyc(tymes(q,x)),intg0(g))); R equ(zeroionei(0),head(x))?y :folk(y,ds(CPLUS),amp(head(x),ds(CSTAR))); } if(1==n||2==n){ df=atop(intg0(f),g); if(1==n)R df; RZ(x=df1(num(1),tdot(g))); R equ(x,zeroionei(1))?df:atop(amp(ds(CDIV),x),df); } v=VAV(g); if(m&&equ(take(sc(-m),num(1)),df1(IX(m),tdot(f)))){ /* ^&m @ g */ if(CLOG==v->id)R 1==m?ds(CRIGHT):2==m?intg0(g):eva(sc(m-1),"(] * ^&x@^.) - x&* @(^&(x-1)@^. d. _1)"); if(CAMP==v->id&&CCIRCLE==ID(v->fgh[1])&&(y=v->fgh[0],!AR(y)&&equ(y,floor1(y)))){ if(2>=m)R 1==m?ds(CRIGHT):intgamp0(g); switch(i0(y)){ case 1: R eva(sc(m-1),"%&(-x )@(^&(x-1)@(1&o.) * 2&o.) + ((x-1)%x)&*@(^&(x-2)@(1&o.) d. _1)"); case 2: R eva(sc(m-1),"%&x @(^&(x-1)@(2&o.) * 1&o.) + ((x-1)%x)&*@(^&(x-2)@(2&o.) d. _1)"); case 3: R eva(sc(m-1),"%&(x-1)@(^&(x-1)@(3&o.) ) - ^&(x-2)@(3&o.) d. _1 "); case 7: R eva(sc(m-1),"%&(1-x)@(^&(x-1)@(7&o.) ) + ^&(x-2)@(7&o.) d. _1 "); }}} R 0; } /* integral of a @ w */ static F2(jtintgtymes){A f=a,g=w; ARGCHK2(a,w); R A0; } /* integral of a * w */ static F1(jtintg0){A df,dh,f,g,h;B nf,ng,vf,vg;C id;I m,n,p,q;V*fv,*gv,*v; ARGCHK1(w); id=ID(w); v=VAV(w); f=v->fgh[0]; nf=f&&NOUN&AT(f); if(vf=f&&!nf)fv=VAV(f); g=v->fgh[1]; ng=g&&NOUN&AT(g); if(vg=g&&!ng)gv=VAV(g); if(id==CAMP&&nf!=ng)R intgamp0(w); switch(id){ case CLE: R ipoly(v2(-1L, 1L)); case CGE: R ipoly(v2( 1L, 1L)); case CLEFT: case CRIGHT: R ipoly(v2( 0L, 1L)); case CNOT: R ipoly(v2( 1L,-1L)); case CMINUS: R ipoly(v2( 0L,-1L)); case CPLUSCO: R ds(CSTARCO); case CFCONS: R amp(v->fgh[2],ds(CSTAR)); case CSTARCO: R ipoly(over(v2(0L,0L),zeroionei(1))); case CHALVE: R ipoly(over(num(0),scf((D)0.5))); case CCIRCLE: R ipoly(over(num(0),scf(PI ))); case CDIV: R ds(CLOG); case CSQRT: R eval("%: * (0 2%3)&p."); case CEXP: R w; case CLOG: R eval("(]*^.) - ]"); case CJDOT: R ipoly(over(num(0),a0j1)); case CRDOT: R eval("-@j.@r."); case CDDOT: if(vf&&ng)R ddot(f,decrem(g)); break; case CPOWOP: if(vf&&ng&&!AR(g))switch(p=i0(g)){ case -1: R intg0(inv(f)); case 0: RE(0); R ipoly(v2(0L,1L)); case 1: R intg0(f); default: if(0>p){RZ(f=inv(f)); p=-p;} if(q=ispoly(f)){RE(m=i0(vib(expn2(sc(q-1),g)))); R ipoly(df1(IX(1+m),tdot(w)));} R intg0(atop(powop(f,sc(p-1),0),f)); } break; case CQQ: if(!AR(f)&&NUMERIC&AT(f)&&ng&&equ(g,zeroionei(0)))R amp(f,ds(CSTAR)); if(vf&&ng)R qq(intg0(f),g); break; case CAT: case CATCO: case CAMP: case CAMPCO: if(vf&&vg)R intgatop(f,g); break; case CTILDE: if(vf)switch(ID(f)){ case CPLUS: R ipoly(v2(0L,2L)); case CSTAR: R ipoly(over(v2(0L,0L),zeroionei(1))); case CMINUS: R FCONS(num(0)); case CLOG: case CDIV: R ds(CRIGHT); } break; case CFORK: h=v->fgh[2]; if(NOUN&AT(f))R intg0(folk(qq(f,zeroionei(0)),g,h)); dh=intg0(h); n=ispoly(h); df=intg0(f); m=ispoly(f); switch(ID(g)){ case CPLUS: R m&&n ? (p=MAX(m,n),ipoly(df1(IX(p),tdot(w)))) : fplus(df,dh); case CMINUS: R m&&n ? (p=MAX(m,n),ipoly(df1(IX(p),tdot(w)))) : fminus(df,dh); case CSTAR: if(m&&n){p=2+(m-1)*(n-1); R ipoly(df1(IX(p),tdot(w)));} R intgtymes(f,h); }} R 0; } static DF1(jtddot1){V*v=VAV(self); R df1(w,ddot(fix(v->fgh[0],zeroionei(0)),v->fgh[1]));} F2(jtddot){A x,*xv,y,z;AF f;I j,n,p,q,r,*wv; ARGCHK2(a,w); ASSERT(NOUN&AT(w),EVDOMAIN); RZ(w=vi(w)); r=AR(w); n=AN(w); wv=AV(w); if(NOUN&AT(a)){ASSERT(0,EVNONCE);} if(!nameless(a)||1<r)R CDERIV(CDDOT, jtddot1,0L, 0L, 0L,0L,0L); CR rng = condrange(wv,n,IMAX,IMIN,IMAX-1); p=rng.min; q=rng.range; if(!r){ if(!p){V*v=VAV(a); R v->mr||v->lrr?qq(a,zeroionei(0)):a;} f=0<=p?jtdiff0:jtintg0; y=a; DQ(ABS(p), ASSERT(y=CALL1(f,y,0L),EVDOMAIN);); R y; } q+=p-1; p=0>p?p:0; q=0<q?q:0; GATV0(x,BOX,1+q-p,1); xv=AAV(x); xv[-p]=incorp(a); if(0>p){y=a; j=-p; DQ(-p, ASSERT(y=intg0(y),EVDOMAIN); xv[--j]=incorp(y););} if(0<q){y=a; j=-p; DQ( q, ASSERT(y=diff0(y),EVDOMAIN); xv[++j]=incorp(y););} j=n; z=xv[wv[--j]-p]; DQ(n-1, RZ(z=folk(xv[wv[--j]-p],ds(CCOMMA),z));); R qq(z,zeroionei(0)); } static F1(jtdiffamp){A f,g,h,x,y;B nf,ng;V*v; ARGCHK1(w); v=VAV(w); f=v->fgh[0]; nf=1&&NOUN&AT(f); g=v->fgh[1]; ng=1&&NOUN&AT(g); h=nf?g:f; x=nf?f:g; switch(ID(h)){ case CROT: case CCANT: case CLBRACE: case CATOMIC: case CCYCLE: if(nf)R atop(hook(eval("=/"),w),eval("i.@$")); break; case CPOLY: if(nf&&1>=AR(x))R dpoly(NUMERIC&AT(x)?x:poly1(x)); break; case CBANG: if(!AR(x)&&(x=pcvt(INT,x),INT&AT(x)))R dpoly(df1(IX(1+*AV(x)),tdot(w))); break; case CFIT: if(nf&&1>=AR(x)&&(y=VAV(h)->fgh[0],CPOLY==ID(y)))R dpoly(df1(IX(IC(x)),tdot(w))); } R A0; } static F1(jtdiff){A df,dh,f,g,h,z;B nf,ng,vf,vg;C id;I r;V*v; ARGCHK1(w); ASSERT(VERB&AT(w),EVDOMAIN); v=VAV(w); id=v->id; r=v->mr; f=v->fgh[0]; nf=f&&NOUN&AT(f); vf=f&&!nf; g=v->fgh[1]; ng=g&&NOUN&AT(g); vg=g&&!ng; if(nf&&id==CFORK)R diff(folk(qq(f,ainf),g,v->fgh[2])); if(z=diff0(w))R id==CQQ&&ng&&equ(g,zeroionei(0))?z:icube(z); if(id==CAMP&&nf!=ng)R diffamp(w); switch(id){ case CREV: R eval("(|.=/])@(i.@$)"); case CCANT: R eval("(|:=/])@(i.@$)"); case CHGEOM: R hgdiff(w); case CSLASH: switch(ID(f)){ case CPLUS: R eval("({. =/ */@}.@$ | ])@(i.@$)"); } break; /* ----- commented out because it is incorrect case CBSLASH: case CBSDOT: if(CSLASH==ID(f)&&(ff=VAV(f)->fgh[0],ff&&VERB&AT(ff))){ b=id==CBSDOT; switch(ID(ff)){ case CPLUS: R eval(b ? "<:/~@(i.@$)" : ">:/~@(i.@$)"); }} break; ----- */ case CFCONS: R atop(amp(ds(CDOLLAR),num(0)),ds(CDOLLAR)); case CQQ: if(NUMERIC&AT(f)&&ng){ z=atop(amp(ds(CDOLLAR),num(0)),ds(CDOLLAR)); R RMAX<mr(w)?z:qq(z,g); } if(vf&&ng)R qq(diff(f),g); break; case CAT: case CAMP: if(vf&&ng)R qq(df1(g,f),ainf); if(vf&&vg)R folk(diff(g),eval("+/ .*"),atop(diff(f),g)); break; case CFORK: df=diff(f); h=v->fgh[2]; dh=diff(h); switch(ID(g)){ case CPLUS: R fplus(df,dh); case CMINUS: R fminus(df,dh); case CSTAR: R fplus(ftymes(df,h),ftymes(f,dh)); case CDIV: R folk(fminus(ftymes(df,h),ftymes(f,dh)), ds(CDIV), atop(ds(CSTARCO),h)); }} R A0; } static F1(jtintg){ASSERT(0,EVNONCE);} static A jtdtab(J jt,A a,I d){A h;V*v; if(!a)R A0; // return 0 if not found in table if(CDCAP==ID(a)&&(v=VAV(a),NOUN&AT(v->fgh[0])&&d==i0(v->fgh[1]))){h=VAV(a)->fgh[2]; R*(1+AAV(h));} switch(SGN(d)){ default: ASSERTSYS(0,"dtab"); case -1: R dtab(intg(a),d+1); case 0: R a; case 1: R dtab(diff(a),d-1); }} static DF2(jtsslope){A fs,f0,p,y,z,*zv;I m,n,r,t;V*sv=VAV(self); PREF2(jtsslope); fs=sv->fgh[0]; m=*AV(sv->fgh[1]); RZ(fs=1<m?dcapco(fs,sc(m-1)):atop(fs,ds(CRIGHT))); r=AR(a); n=AN(w); ASSERT(!r||r==AR(w)&&!memcmp(AS(a),AS(w),r*SZI),EVNONCE); RZ(f0=df2(a,w,fs)); GATV(z,BOX,n,AR(w),AS(w)); zv=AAV(z); t=CMPX&AT(a)||CMPX&AT(w)?CMPX:FL; RZ(a=cvt(t,a)); RZ(y=cvt(t,w)); GA(p,t,1,0,0); if(t&CMPX){Z*av=ZAV(a),e,*pv=ZAV(p),*v=ZAV(y),x; e.re=1e-7; e.im=0.0; *pv=ZNZ(*av)?*av:e; DO(n, if(r)*pv=ZNZ(av[i])?av[i]:e; x=v[i]; v[i]=zplus(v[i],*pv); RZ(zv[i]=incorp(divide(minus(df2(p,y,fs),f0),p))); v[i]=x;); }else {D*av=DAV(a),e,*pv=DAV(p),*v=DAV(y),x; e=1e-7; *pv= *av ?*av:e; DO(n, if(r)*pv= av[i] ?av[i]:e; x=v[i]; v[i]+=*pv; RZ(zv[i]=incorp(divide(minus(df2(p,y,fs),f0),p))); v[i]=x;); } R ope(z); /* cant2(IX(AR(w)),ope(z)); */ } static DF1(jtderiv1){A e,ff,fs,gs,s,t,z,*zv;I*gv,d,n,*tv;V*v; PREF1(jtderiv1); v=VAV(self); RZ(fs=fix(v->fgh[0],zeroionei(0))); gs=v->fgh[1]; n=AN(gs); gv=AV(gs); if(!(AT(w)&FL+CMPX))RZ(w=cvt(FL,w)); RZ(e=scf((D)1e-7)); GAT0(t,INT,1,0); tv=AV(t); // no need to INCORP t, since no one cares and it's not virtual RZ(s=ca(self)); v=VAV(s); v->fgh[1]=t; v->lrr=(v->lrr&RMAX)+(v->mr<<RANKTX); GATV(z,BOX,n,AR(gs),AS(gs)); zv=AAV(z); DO(n, *tv=d=gv[i]; zv[i]=incorp((ff=dtab(fs,d))?df1(w,ff):sslope(tymes(e,w),w,s));); RE(0); R ope(z); } F2(jtdcap){A z;I r,*v; ARGCHK2(a,w); ASSERT(NOUN&AT(w),EVDOMAIN); RZ(w=vi(w)); v=AV(w); DO(AN(w), ASSERT(0<=v[i],EVNONCE);); if(NOUN&AT(a))R vger2(CDCAP,a,w); r=mr(a); R !AR(w)&&nameless(a)&&(z=dtab(a,*v))?z:CDERIV(CDCAP,jtderiv1,0L,VFLAGNONE,r,0L,r); } F2(jtdcapco){I r,*v; ASSERTVN(a,w); RZ(w=vi(w)); v=AV(w); DO(AN(w), ASSERT(0<=v[i],EVNONCE);); r=mr(a); R CDERIV(CDCAPCO,0L,jtsslope,VFLAGNONE,0L,r,r); } #endif
the_stack_data/73574356.c
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <math.h> /* * Print the relative entropy of the input stream. * This is a fraction in the range 0-1 which we express as a percent. * It means that random data having this probability distribution can * be compressed by that amount. Data with this distribution may also * compress a lot better in some cases e.g. if local structure exists. * * examples: * * ./rel /usr/share/dict/words * * dd if=/dev/random bs=1 count=100 | ./rel * */ void usage(char *prog) { fprintf(stderr, "usage: %s [-v] [file]\n", prog); exit(-1); } unsigned counts[256]; unsigned total; int main(int argc, char * argv[]) { int opt,verbose=0,i; FILE *ifilef=stdin; char *ifile=NULL,line[100]; double p, lp, sum=0, rel; while ( (opt = getopt(argc, argv, "v+")) != -1) { switch (opt) { case 'v': verbose++; break; default: usage(argv[0]); break; } } if (optind < argc) ifile=argv[optind++]; if (ifile) { if ( (ifilef = fopen(ifile,"r")) == NULL) { fprintf(stderr,"can't open %s: %s\n", ifile, strerror(errno)); exit(-1); } } /* accumulate counts of each byte value */ while ( (i=fgetc(ifilef)) != EOF) { counts[i]++; total++; } /* compute the final entropy. this is -SUM[0,255](p*l(p)) * where p is the probability of byte value [0..255] * and l(p) is the base-2 log of p. Unit is bits per byte. */ for(i=0; i < 256; i++) { if (counts[i] == 0) continue; p = 1.0*counts[i]/total; lp = log(p)/log(2); sum -= p*lp; } rel = sum/8; printf("E: Source entropy: %.2f bits per byte\n", sum); printf("M: Max entropy: 8.00 bits per byte\n"); printf("R: Relative entropy (E/M): %.2f%%\n", rel*100); printf("\n"); printf("Original: %5d bytes\n", total); printf("Compression to E: %5d bytes\n", (int)(total*rel)); printf("Compression ratio: %.1f to 1\n", (8/sum)); printf("\n"); printf("Random data having symbol probabilities that match\n" "this stream can be compressed approximately as shown.\n" "Random data is a worst-case. Data with local structure\n" "but having the same first-order probabilities may be\n" "compressed further by suitable compression schemes.\n"); printf("\n"); }
the_stack_data/64199783.c
#include <stdlib.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include <stdbool.h> #define LEFT_TURN 0 #define STRAIGHT 1 #define RIGHT_TURN 2 typedef struct cart { int x; int y; char direction; int last_turn; bool crashed; } cart_t; typedef struct tile { char track; cart_t* cart; } tile_t; char map_track(char c) { switch (c) { case '>': case '<': return '-'; case 'v': case '^': return '|'; default: return c; } } cart_t* create_cart(int x, int y, char direction) { cart_t* cart = malloc(sizeof(cart_t)); cart->x = x; cart->y = y; cart->direction = direction; cart->last_turn = RIGHT_TURN; cart->crashed = false; return cart; } cart_t* map_cart(int x, int y, char c) { switch (c) { case '>': case '<': case 'v': case '^': return create_cart(x, y, c); default: return NULL; } } void populate_map(char* fileName, tile_t* map[150][150]) { FILE* input = fopen(fileName, "r"); int character; int x=0; int y=0; while ((character = fgetc(input)) != EOF) { if (character == '\n') { y++; x = 0; } else { map[x][y] = malloc(sizeof(tile_t)); map[x][y]->track = map_track((char)character); map[x][y]->cart = map_cart(x, y, (char)character); x++; } } fclose(input); } int count_carts(char* fileName) { FILE* input = fopen(fileName, "r"); int carts = 0; int ch; while ((ch = fgetc(input)) != EOF) { if (ch == '>' || ch == '<' || ch == 'v' || ch == '^') { carts++; } } fclose(input); return carts; } void print(tile_t* map[150][150]) { int y; int x; for (y = 0; y < 150; y++) { for (x = 0; x < 150; x++) { if (map[x][y]->cart == NULL) { printf("%c", map[x][y]->track); } else { printf("%c", map[x][y]->cart->direction); } } printf("\n"); } } void intersection_turn(cart_t* cart) { switch (cart->direction) { case '>': if (cart->last_turn == LEFT_TURN) { cart->last_turn = STRAIGHT; } else if (cart->last_turn == STRAIGHT) { cart->last_turn = RIGHT_TURN; cart->direction = 'v'; } else { cart->last_turn = LEFT_TURN; cart->direction = '^'; } break; case 'v': if (cart->last_turn == LEFT_TURN) { cart->last_turn = STRAIGHT; } else if (cart->last_turn == STRAIGHT) { cart->last_turn = RIGHT_TURN; cart->direction = '<'; } else { cart->last_turn = LEFT_TURN; cart->direction = '>'; } break; case '<': if (cart->last_turn == LEFT_TURN) { cart->last_turn = STRAIGHT; } else if (cart->last_turn == STRAIGHT) { cart->last_turn = RIGHT_TURN; cart->direction = '^'; } else { cart->last_turn = LEFT_TURN; cart->direction = 'v'; } break; case '^': if (cart->last_turn == LEFT_TURN) { cart->last_turn = STRAIGHT; } else if (cart->last_turn == STRAIGHT) { cart->last_turn = RIGHT_TURN; cart->direction = '>'; } else { cart->last_turn = LEFT_TURN; cart->direction = '<'; } break; } } int first_collision = true; // return true on crash bool move(tile_t* map[150][150], cart_t* cart) { if (cart == NULL) { return false; } int x = cart->x; int y = cart->y; map[x][y]->cart = NULL; switch (cart->direction) { case '>': x++; break; case '<': x--; break; case '^': y--; break; case 'v': y++; break; } if (map[x][y]->cart != NULL) { if (first_collision) { printf("13.1: %d,%d\n", x, y); first_collision = false; } map[x][y]->cart->crashed = true; cart->crashed = true; map[x][y]->cart = NULL; return true; } cart->x = x; cart->y = y; map[x][y]->cart = cart; switch (map[x][y]->track) { case '/': if (cart->direction == '>') { cart->direction = '^'; } else if (cart->direction == 'v') { cart->direction = '<'; } else if (cart->direction == '<') { cart->direction = 'v'; } else if (cart->direction == '^') { cart->direction = '>'; } break; case '\\': if (cart->direction == '>') { cart->direction = 'v'; } else if (cart->direction == 'v') { cart->direction = '>'; } else if (cart->direction == '<') { cart->direction = '^'; } else if (cart->direction == '^') { cart->direction = '<'; } break; case '+': intersection_turn(cart); break; } return false; } void populate_cart_order(tile_t* map[150][150], cart_t** carts) { int i = 0; for (int y = 0; y < 150; y++) { for (int x = 0; x < 150; x++) { if (map[x][y]->cart != NULL) { carts[i] = map[x][y]->cart; i++; } } } } int main(int argc, char** argv) { tile_t* map[150][150]; populate_map(argv[1], map); int cart_count = count_carts(argv[1]); cart_t* carts[cart_count]; int new_cart_count = cart_count; populate_cart_order(map, carts); while (cart_count > 1) { for (int c = 0 ; c < cart_count ; c++) { if (!carts[c]->crashed) { if (move(map, carts[c])) { new_cart_count-=2; } } } cart_count = new_cart_count; populate_cart_order(map, carts); } printf("13.2: %d,%d\n", carts[0]->x, carts[0]->y); }
the_stack_data/104827904.c
#include <stdio.h> #define MAX_STMT_SIZE 1024 #define MAX_EXPR_SIZE 1024 #define MAX_DATA_SIZE 4 #define MAX_EXPR_NODE 32 #define MAX_EXPR_STACK 32 typedef struct { int level; char * exprs[ MAX_EXPR_NODE ]; } EXPR_NODE; typedef EXPR_NODE *PEXPR_NODE; char * increase_indent( const char * , int ); char * increase_indent1( char *, const int, const char *, int ); int get_level( const char * ); char * merge_expr( PEXPR_NODE, int, int ); int main( int argc, char * argv[] ) { char buf[ MAX_STMT_SIZE ]; char * data[ MAX_DATA_SIZE ] = { "\n", "a", "1\n2\n3", "1\n" }; int i; for ( i = 0; i < MAX_DATA_SIZE; i ++ ){ printf( "Test Data:\n%s\n", data[ i ] ); printf( "Result:\n'%s'\n", increase_indent( data[ i ], 2 ) ); printf( "Result1:\n'%s'\n", increase_indent1 ( buf, MAX_STMT_SIZE, data[ i ], 2 ) ); } return 0; } char * increase_indent( const char * expr, int indent ) { char * buf = (char *) malloc( MAX_STMT_SIZE ); if ( !buf ){ fprintf( stderr, "Error: memory fault\n" ); return NULL; } char *s = (char *)expr; char *p = strchr( s, '\n' ); int len = 0; int offset = 0; while ( p ){ len = p - s + 1; if ( len + offset + indent >= MAX_STMT_SIZE ){ fprintf( stderr, "Error: buffer override\n" ); free( buf ); return NULL; } strncpy( buf + offset, s, len ); offset += len; /* 增加一个缩进单位 */ memset( buf + offset, ' ', indent ); offset += indent; /* 查找下一个换行符号 */ s = p + 1; p = strchr( s, '\n' ); } if ( s ){ if ( snprintf( buf + offset, MAX_STMT_SIZE - offset, "%s", s ) < 0 ){ fprintf( stderr, "Error: buffer override\n" ); free( buf ); return NULL; } } else { if ( offset < MAX_STMT_SIZE ) buf[ offset ] = 0; else { fprintf( stderr, "Error: buffer override\n" ); free( buf ); return NULL; } } return buf; } /* expr 中的每一个换行符号被替换成为换行加上缩进宽度个空格,返回到 buf 中。 buf 是一个预先分配好的缓冲区。 */ char * increase_indent1( char * buf, const int buf_size, const char * expr, int indent ) { char *s = (char *)expr; char *p = strchr( s, '\n' ); int len = 0; int offset = 0; while ( p ){ len = p - s + 1; if ( offset + len + indent >= buf_size ){ fprintf( stderr, "Error: buffer override\n" ); return NULL; } strncpy( buf + offset, s, len ); offset += len; /* 增加一个缩进单位 */ memset( buf + offset, ' ', indent ); offset += indent; /* 查找下一个换行符号 */ s = p + 1; p = strchr( s, '\n' ); } if ( s ){ if ( snprintf( buf + offset, buf_size - offset, "%s", s ) < 0 ){ fprintf( stderr, "Error: buffer override\n" ); return NULL; } } else { if ( offset < buf_size ) buf[ offset ] = 0; else { fprintf( stderr, "Error: buffer override\n" ); return NULL; } } return buf; } /* 合并表达式,将其中的换行符号替换成为空格 */ char * merge_expr1( char * expr ) { char * p = strchr( expr, '\n' ); while ( p ){ *p = ' '; p = strchr( p + 1, '\n' ); } return expr; } /* 对齐策略 1. 第一操作数顶格对齐,操作数全部折行。 例如 1 + 2 + 3 => 1 + 2 + 3 2. 第一操作数与第二操作数缩进对齐,操作数全部折行。 例如 1 + 2 + 3 => 1 + 2 + 3 3. 第一操作数顶格对齐,操作数仅在必要的时候折行。 4. 第一操作数与第二操作数缩进对齐,操作数仅在必要的时候折行。 前两种方式实现简单,直接在规则中增加缩进空格即可。后两种方 式需要对表达式进行二次处理,重新判断是否换行。对于不需要换 行的运算符要放在一行。 */ /* * 将一个缩进折行表达式重新格式化成为没有必要则不折行的表达式。 * * 例如,将下面的缩进折行表达式 * 1 * + 2 * * 3 * * 4 * + 5 * * 转换成为 * * 1 * + 2 * 3 * 4 * + 5 */ char * format_stmt( const char * expr, int indent, int width ) { int x1, x2; char * s = (char *)expr; char * p; EXPR_NODE stack[ MAX_EXPR_STACK ]; PEXPR_NODE pexpr = stack; int i; char *pp; char buffer [ MAX_EXPR_SIZE ]; /* 得到第一行的缩进 */ x1 = get_level ( p ); x2 = x1; /* 初始化堆栈 */ memset( stack, 0, sizeof( EXPR_NODE ) * MAX_EXPR_STACK ); pexpr -> level = x1; p = strchr( s, '\n' ); while ( p ){ if ( x1 < x2 ){ /* 出栈操作 */ /* 计算当前栈的表达式的全部长度是否一行可以放的下 */ /* 如果可以,那么合并成为一行,放到上一层堆栈的最后一个表达式 */ /* 如果不可以,那么使用缩进方式,合并到上一层堆栈的最后一个表达式 */ pp = merge_expr( pexpr, indent, width ); /* 将当前栈顶清零,出栈 */ memset( pexpr, 0, sizeof( EXPR_NODE ) ); pexpr --; x1 = pexpr -> level; if ( pexpr -> exprs[ 0 ] ){ for ( i = MAX_EXPR_NODE - 1; i >= 0; i -- ) if ( pexpr -> exprs[ i ] ) break; if ( snprintf( buffer, MAX_EXPR_SIZE, "%s %s", pexpr -> exprs[ i ], pp ) < 0 ) return NULL; free( pexpr -> exprs[ i ] ); free( pp ); pexpr -> exprs[ i ] = strdup( buffer ); } else { pexpr -> exprs[ 0 ] = pp; } continue ; } if ( x1 > x2 ){ /* 入栈 */ pexpr ++; pexpr -> level = x2; } /* 表达式拷贝到栈顶 */ if ( pexpr -> exprs[ MAX_EXPR_NODE - 1 ] ){ return NULL; } for ( i = 0; i < MAX_EXPR_NODE; i ++ ) if ( !( pexpr -> exprs [ i ] ) ){ pexpr -> exprs[ i ] = strndup( s, p - s ); break; } /* 读下一行 */ s = p + 1; p = strchr( s, '\n' ); x1 = x2; x2 = get_level( s ); } /* 最后一个表达式入栈 */ if ( pexpr -> exprs[ MAX_EXPR_NODE - 1 ] ){ return NULL; } for ( i = 0; i < MAX_EXPR_NODE; i ++ ) if ( !pexpr -> exprs [ i ] ){ pexpr -> exprs[ i ] = strdup( s ); break; } /* 全部格式化输出堆栈之中的内容 */ while ( pexpr > stack){ /* 出栈操作 */ pp = merge_expr( pexpr, indent, width ); pexpr --; if ( pexpr -> exprs[ 0 ] ){ for ( i = MAX_EXPR_NODE - 1; i >= 0; i -- ) if ( pexpr -> exprs[ i ] ) break; if ( snprintf( buffer, MAX_EXPR_SIZE, "%s %s", pexpr -> exprs[ i ], pp ) < 0 ) return NULL; free( pexpr -> exprs[ i ] ); free( pp ); pexpr -> exprs[ i ] = strdup( buffer ); } else { pexpr -> exprs[ 0 ] = pp; } } return buffer; } int get_level( const char * expr ) { int x = 0; char * p = ( char *)expr; while ( p ){ if ( ( char )*p != ' ' ) return x; p ++, x ++; } return x; } char * merge_expr( PEXPR_NODE pexpr, int indent, int width ) { /* 合并多个表达式到一行 */ char * s = pexpr -> exprs; int len = 0; int counter = 0; int level = pexpr -> level; while ( s ){ len += strlen( s ) - level; counter ++; s ++; } /* 判断是否一行放得下,根据公式 len + indent + level < 列宽 确定 */ char * buf; int offset = 0; if ( len + level + indent > width ){ buf = malloc ( len + 1 ); s = pexpr -> exprs; while ( s ){ if ( strncpy( buf + offset, s + level, strlen( s ) - level ) <= 0 ) return NULL; offset += strlen( s ) - level; *( buf + offset ) = ' '; s ++; } *( buf + offset ) = 0; } else { buf = malloc( len + counter * level + counter * indent ); s = pexpr -> exprs; while ( s ){ strcpy( buf + offset, s ); offset += strlen( s ); s ++; if ( s ){ memset( buf + offset, ' ', indent ); offset += indent; } } } return buf; }
the_stack_data/232954610.c
struct ListNode { int val; struct ListNode *next; }; #include <stdlib.h> struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) { struct ListNode *res, *tail, *tmp; int c; if (!l1 && !l2) { res = calloc(1, sizeof(struct ListNode)); return(res); } res = 0; c = 0; while (l1 && l2) { tmp = malloc(sizeof(struct ListNode)); tmp->next = 0; tmp->val = l1->val + l2->val + c; if (tmp->val >= 10) { tmp->val -= 10; c = 1; } else { c = 0; } if (!res) { res = tail = tmp; } else { tail->next = tmp; tail = tmp; } l1 = l1->next; l2 = l2->next; } while (l1) { tmp = malloc(sizeof(struct ListNode)); tmp->next = 0; tmp->val = l1->val + c; if (tmp->val >= 10) { tmp->val -= 10; c = 1; } else { c = 0; } if (!res) { res = tail = tmp; } else { tail->next = tmp; tail = tmp; } l1 = l1->next; } while (l2) { tmp = malloc(sizeof(struct ListNode)); tmp->next = 0; tmp->val = l2->val + c; if (tmp->val >= 10) { tmp->val -= 10; c = 1; } else { c = 0; } if (!res) { res = tail = tmp; } else { tail->next = tmp; tail = tmp; } l2 = l2->next; } if (c) { tmp = malloc(sizeof(struct ListNode)); tmp->next = 0; tmp->val = c; tail->next = tmp; } return(res); } int main(void) {}
the_stack_data/92327214.c
#include <stdio.h> #include <math.h> double Vfunc(double x, double nu){ return 1./nu * x*(1.-x); } double Mfunc1D(double x, double gamma, double h){ return gamma * 2*(h + (1.-2*h)*x) * x*(1.-x); } double Mfunc2D(double x, double y, double m, double gamma, double h){ return m * (y-x) + gamma * 2*(h + (1.-2*h)*x) * x*(1.-x); } double Mfunc3D(double x, double y, double z, double mxy, double mxz, double gamma, double h){ return mxy * (y-x) + mxz * (z-x) + gamma * 2*(h + (1.-2*h)*x) * x*(1.-x); } void compute_dx(double *xx, int N, double *dx){ int ii; for(ii = 0; ii < N-1; ii++) dx[ii] = xx[ii+1]-xx[ii]; } void compute_dfactor(double *dx, int N, double *dfactor){ int ii; for(ii=1; ii < N-1; ii++) dfactor[ii] = 2./(dx[ii] + dx[ii-1]); dfactor[0] = 2./dx[0]; dfactor[N-1] = 2./dx[N-2]; } void compute_xInt(double *xx, int N, double *xInt){ int ii; for(ii = 0; ii < N-1; ii++) xInt[ii] = 0.5*(xx[ii+1]+xx[ii]); } void compute_delj(double *dx, double *MInt, double *VInt, int N, double *delj, int use_delj_trick){ int ii; double wj, epsj; if(!use_delj_trick){ for(ii=0; ii < N-1; ii++) delj[ii] = 0.5; return; } for(ii=0; ii < N-1; ii++){ wj = 2 * MInt[ii] * dx[ii]; epsj = exp(wj/VInt[ii]); if((epsj != 1.0) && (wj != 0)) delj[ii] = (-epsj*wj + epsj*VInt[ii] - VInt[ii])/(wj - epsj*wj); else delj[ii] = 0.5; } } void compute_abc_nobc(double *dx, double *dfactor, double *delj, double *MInt, double *V, double dt, int N, double *a, double *b, double *c){ int ii; double atemp, ctemp; a[0] = 0; c[N-1] = 0; for(ii = 0; ii < N; ii++) b[ii] = 1./dt; /* Using atemp and ctemp yields an ~10% speed-up. */ for(ii = 0; ii < N-1; ii++){ atemp = MInt[ii] * delj[ii] + V[ii]/(2*dx[ii]); a[ii+1] = -dfactor[ii+1]*atemp; b[ii] += dfactor[ii]*atemp; ctemp = -MInt[ii] * (1 - delj[ii]) + V[ii+1]/(2*dx[ii]); b[ii+1] += dfactor[ii+1]*ctemp; c[ii] = -dfactor[ii]*ctemp; } }
the_stack_data/54825991.c
#include <stdio.h> int main() { int arr[] = {2, 94, 8, 65, 21}; int len = sizeof(arr) / sizeof(arr[0]); int i; int(*p)[5] = &arr; for (i = 0; i < len; i++) { printf("%d, ", (*p)[i]); } return 0; }
the_stack_data/635431.c
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define FILENAME "Test.txt" int main() { FILE *fp = NULL; FILE *fp1 = NULL; char ch = ' '; fp = fopen(FILENAME, "r"); if (fp == NULL) return -1; // create a temp file fp1 = fopen("temp.txt", "w"); if (fp1 == NULL) return -1; while ((ch = fgetc(fp)) != EOF) { if (islower(ch)) { ch = ch-32; } fputc(ch, fp1); } fclose(fp); fclose(fp1); remove(FILENAME); // rename temp file to Test.txt file rename("temp.txt", FILENAME); // remove the temp file remove("temp.txt"); fp = fopen(FILENAME, "r"); if (fp == NULL) return -1; while ((ch =fgetc(fp)) != EOF) printf("%c", ch); fclose(fp); fp = NULL; fp1 = NULL; return 0; }
the_stack_data/89200386.c
/* * ===================================================================================== * * Filename: main.c * * Description: rejects from main.c. * * Version: 1.0 * Created: 13/06/09 15:09:32 * Revision: none * Compiler: gcc * * ===================================================================================== */ #ifdef MYDEBUG { fcs_card_t card; int ret; char card_str[10]; ret = fcs_check_state_validity( ptr_state_with_locations, context->freecells_num, context->stacks_num, context->decks_num, &card ); if (ret != 0) { fcs_card_perl2user(card, card_str, context->display_10_as_t); if (ret == 3) { fprintf(stdout, "%s\n", "There's an empty slot in one of the stacks." ); } else { fprintf(stdout, "%s%s.\n", ((ret == 2)? "There's an extra card: " : "There's a missing card: "), card_str ); } exit(-1); } } #endif
the_stack_data/475663.c
/* ヘッダファイルのインクルード */ #include <stdio.h> /* C標準入出力 */ #include <string.h> /* C文字列処理 */ #include <unistd.h> /* UNIX標準 */ #include <X11/Xlib.h> /* Xlib */ #include <X11/Xutil.h> /* Xユーティリティ */ #include <X11/Xatom.h> /* アトム */ /* main関数 */ int main(int argc, char **argv){ /* 変数の宣言と初期化. */ Display *d; /* Display構造体へのポインタd. */ Window wr; /* ウィンドウ生成の結果を表す値wr.(Window == XID == unsigned long) */ int result; /* マップの結果result. */ unsigned long white; /* 白のRGB値white. */ XEvent event; /* XEvent構造体(共用体)のevent. */ int i; /* ループ用変数i. */ XTextProperty text_property; /* テキストプロパティtext_property. */ char title[] = "ABCDE"; /* タイトルtitleを"ABCDE"で初期化. */ Atom atom_wm_delete_window; /* WM_DELETE_WINDOWのアトムatom_wm_delete_window. */ Atom atom_wm_protocols; /* WM_PROTOCOLSのアトムatom_wm_protocols. */ int default_screen; /* デフォルトスクリーン番号default_screen. */ Colormap default_colormap; /* デフォルトカラーマップdefault_colormap. */ XColor screen; /* 近似値screen. */ XColor exact; /* 正確値exact. */ /* Xサーバとの接続. */ d = XOpenDisplay(NULL); /* XOpenDisplayでXサーバに接続し, 戻り値のアドレスをdに格納. */ /* dを出力. */ printf("d = %08x\n", d); /* dの値を16進数で出力. */ /* デフォルトスクリーン番号の取得. */ default_screen = DefaultScreen(d); /* DefaultScreenでデフォルトスクリーン番号を取得し, default_screenに格納. */ printf("default_screen = %d\n", default_screen); /* default_screenを出力. */ /* デフォルトカラーマップの取得. */ default_colormap = DefaultColormap(d, default_screen); /* DefaultColormapでdefault_screenのdefault_colormapを取得. */ printf("default_colormap = %08x\n", default_colormap); /* default_colormapを出力. */ /* 赤のピクセル値を取得. */ XAllocNamedColor(d, default_colormap, "red", &screen, &exact); /* XAllocNamedColorで"red"のピクセル値を取得.(screenは近似色情報, exactは正確色情報.) */ /* 白のピクセル値を取得. */ white = XWhitePixel(d, 0); /* XWhitePixelでスクリーン0における白のピクセル値を取得し, whiteに格納. */ /* ウィンドウの生成. */ wr = XCreateSimpleWindow(d, DefaultRootWindow(d), 100, 100, 640, 480, 1, white, screen.pixel); /* XCreateSimpleWindowでウィンドウ生成し, 結果はwrに格納.(screen.pixelにピクセル値が格納されている.) */ /* ウィンドウ生成の結果を出力. */ printf("wr = %08x\n", wr); /* wrを出力. */ /* ウィンドウのマッピング(表示要求) */ result = XMapWindow(d, wr); /* XMapWindowでマッピング. */ /* マッピング結果を出力. */ printf("result = %d\n", result); /* resultの値を出力. */ /* テキストプロパティのセット. */ text_property.value = (unsigned char *)title; /* タイトル文字列を指定. */ text_property.encoding = XA_STRING; /* XA_STRINGを指定. */ text_property.format = 8; /* 半角英数の場合8ビットなので8を指定. */ text_property.nitems = strlen(title); /* titleの文字数を指定. */ XSetWMProperties(d, wr, &text_property, NULL, argv, argc, NULL, NULL, NULL); /* XSetWMPropertiesでウィンドウマネージャにtext_propertyをセット. */ /* WM_PROTOCOLSにWM_DELETE_WINDOWをセット. */ atom_wm_delete_window = XInternAtom(d, "WM_DELETE_WINDOW", False); /* XInternAtomで"WM_DELETE_WINDOW"のアトムを取得. */ XSetWMProtocols(d, wr, &atom_wm_delete_window, 1); /* XSetWMProtocolsでatom_wm_delete_windowをセット. */ /* WM_PROTOCOLSのアトムを取得. */ atom_wm_protocols = XInternAtom(d, "WM_PROTOCOLS", False); /* XInternAtomでWM_PROTOCOLSのアトムを取得. */ /* イベントマスクのセット. */ XSelectInput(d, wr, ButtonPressMask | ButtonReleaseMask | StructureNotifyMask); /* XSelectInputでButtonPressMask, ButtonReleaseMask(マウスボタンを離された時のマスク.), StructureNotifyMask(通知マスク)をセット. */ /* 表示要求イベントをフラッシュ. */ XFlush(d); /* XFlushでフラッシュ. */ /* iの初期化. */ i = 0; /* iを0にしておく. */ /* イベントループ. */ while (1){ /* イベントの取得. */ XNextEvent(d, &event); /* XNextEventでeventを取得. */ /* イベントタイプごとに処理. */ switch (event.type){ /* event.typeの値で分岐. */ /* ButtonPress */ case ButtonPress: /* マウスボタンが押された時. */ /* ButtonPressブロック. */ { /* マウス位置の出力. */ printf("(%d, %d)\n", event.xbutton.x, event.xbutton.y); /* event.xbutton.xとevent.xbutton.yを出力. */ i++; /* iをインクリメント. */ if (i == 10){ /* iが10の時. */ /* Xサーバとの接続を終了する. */ XCloseDisplay(d); /* XCloseDisplayで切断する. */ /* プログラムの終了 */ return 0; /* 0を返して正常終了. */ } } /* break. */ break; /* breakで終わる. */ /* ButtonRelease */ case ButtonRelease: /* マウスボタンが離された時. */ /* ButtonReleaseブロック. */ { /* "ButtonRelease!!". */ printf("ButtonRelease!!\n"); /* "ButtonRelease!!"と出力. */ } /* break. */ break; /* breakで終わる. */ /* ClientMessage */ case ClientMessage: /* クライアントメッセージ */ /* ClientMessageブロック. */ { /* WM_PROTOCOLSの場合. */ if (event.xclient.message_type == atom_wm_protocols){ /* atom_wm_protocolsなら. */ /* "WM_PROTOCOLS!" */ printf("WM_PROTOCOLS!\n"); /* "WM_PROTOCOLS!"と出力. */ /* WM_DELETE_WINDOWなら終了. */ if (event.xclient.data.l[0] == atom_wm_delete_window){ /* atom_wm_delete_windowなら. */ /* "WM_DELETE_WINDOW!!" */ printf("WM_DELETE_WINDOW!!\n"); /* "WM_DELETE_WINDOW!!"と出力. */ /* ウィンドウを破棄. */ XDestroyWindow(d, wr); /* XDestroyWindowでウィンドウを破棄. */ } } } /* break. */ break; /* breakで終わる. */ /* DestroyNotify */ case DestroyNotify: /* ウィンドウ破棄通知. */ /* DestroyNotifyブロック. */ { /* "DestroyNotify!" */ printf("DestroyNotify!\n"); /* "DestroyNotify!"と出力. */ /* 切断したら全てのリソースを破棄. */ XSetCloseDownMode(d, DestroyAll); /* XSetCloseDownModeでDestroyAllをセット. */ /* Xサーバとの接続を終了する. */ XCloseDisplay(d); /* XCloseDisplayで切断する. */ /* プログラムの終了 */ return 0; /* 0を返して正常終了. */ } /* break. */ break; /* breakで終わる. */ /* default */ default: /* それ以外. */ /* break. */ break; /* breakで終わる. */ } } }
the_stack_data/75136502.c
#include <stdio.h> int main(void) { int i_age = 23; signed int score = 100; unsigned int u_score = -3; long long int big = -10010110L; float income = 12340.66; printf("Age: %d\n", i_age); printf("Score: %d\n", score); printf("Score (unsigned): %u\n", u_score); printf("Big: %lld\n", big); printf("Income: %f\n", income); return 0; }
the_stack_data/152978.c
#include <stdio.h> int main() { int n,k=1,l; scanf("%d",&n); for(int i=1;i<=n;i++) { k=i; l=2*n-i+1; for(int j=1;j<=n;j++) { if(j%2!=0) { printf("%d ",k); k=k+2*n; } else { printf("%d ",l); l=l+2*n; } } printf("\n"); } return 0; }
the_stack_data/34512178.c
// // Created by demonkit on 3/7/19. // #include <stdio.h> #define MAX_NODES 1024 #define INFINITY 1000000000 int n, dist[MAX_NODES][MAX_NODES]; void shortest_path(int s, int t, int path[]) { struct state { int predecessor; int length; enum { permanent, tentative } label; } node[MAX_NODES]; int i, k, min; struct state *p; for (p = &node[0]; p < &node[n]; p++) { p->predecessor = -1; p->length = INFINITY; p->label = tentative; } node[t].length = 0; node[t].label = permanent; k = t; do { for (i = 0; i < n; i++) { if (dist[k][i] != 0 && node[i].label == tentative) { if (node[k].length + dist[k][i] < node[i].length) { node[i].predecessor = k; node[i].length = node[k].length + dist[k][i]; } } } k = 0; min = INFINITY; for (i = 0; i < n; i++) { if (node[i].label == tentative && node[i].length < min) { min = node[i].length; k = i; } } node[k].label = permanent; } while (k != s); i = 0; k = s; do { path[i++] = k; k = node[k].predecessor; } while (k >= 0); } int main() { n = 8; // dist[][8] = { // {0, 2, INFINITY, INFINITY, INFINITY, INFINITY, 6, INFINITY}, // {2, 0, 7, INFINITY, 3, INFINITY, INFINITY, INFINITY}, // {INFINITY, 7, 0, 3, INFINITY, 3, INFINITY, INFINITY}, // {INFINITY, INFINITY, 3, 0, INFINITY, INFINITY, INFINITY, 2}, // {INFINITY, 3, INFINITY, INFINITY, 0, 2, 1, INFINITY}, // {INFINITY, INFINITY, 3, INFINITY, 2, 0, INFINITY, 2}, // {INFINITY, 6, INFINITY, INFINITY, 1, INFINITY, 0, 4}, // {INFINITY, INFINITY, INFINITY, 2, INFINITY, 2, 4, 0} // }; dist[0][1] = 2; dist[1][0] = 2; dist[0][6] = 6; dist[6][0] = 6; dist[1][2] = 7; dist[2][1] = 7; dist[1][4] = 3; dist[4][1] = 3; dist[2][3] = 3; dist[3][2] = 3; dist[2][5] = 3; dist[5][2] = 3; dist[3][7] = 2; dist[7][3] = 2; dist[4][5] = 2; dist[5][4] = 2; dist[4][6] = 1; dist[6][4] = 1; dist[5][7] = 2; dist[7][5] = 2; dist[6][7] = 4; dist[7][6] = 4; int *path; shortest_path(0, 3, path); for (int i = 0; i < n; ++i) { printf("%d\n", path[i]); } return 0; }
the_stack_data/33503.c
/* Functional tests for the function hotpatching feature. */ /* { dg-do compile } */ /* { dg-options "-O3 -mzarch" } */ typedef int (*fn_t)(void); fn_t hp1(void) { __attribute__((hotpatch(0,0))) int nested1(void) { return 1; } return nested1; } fn_t hp2(void) { __attribute__ ((hotpatch(1,2))) int nested2(void) { return 2; } return nested2; }
the_stack_data/192331192.c
#include <stdio.h> #include <unistd.h> int main() { pid_t cpid = fork(); if(cpid) while(1) printf("1"); else while(1) printf("2"); return 0; }
the_stack_data/14245.c
#include <stdio.h> #include <omp.h> int main( ) { printf("%d\n", omp_get_num_procs( )); #pragma omp parallel #pragma omp master { printf("%d\n", omp_get_num_procs( )); } }
the_stack_data/59212.c
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* 파일 타입을 검사한다. */ int main(int argc, char *argv[]) { int i; struct stat buf; for (i = 1; i < argc; i++) { printf("%s: ", argv[i]); if (lstat(argv[i], &buf) < 0) { perror("lstat()"); continue; } if (S_ISREG(buf.st_mode)) printf("%s \n", "일반 파일"); if (S_ISDIR(buf.st_mode)) printf("%s \n", "디렉토리"); if (S_ISCHR(buf.st_mode)) printf("%s \n", "문자 장치 파일"); if (S_ISBLK(buf.st_mode)) printf("%s \n", "블록 장치 파일"); if (S_ISFIFO(buf.st_mode)) printf("%s \n", "FIFO 파일"); if (S_ISLNK(buf.st_mode)) printf("%s \n", "심볼릭 링크"); if (S_ISSOCK(buf.st_mode)) printf("%s \n", "소켓"); } exit(0); }
the_stack_data/125140042.c
/* * ===================================================================================== * Filename: lock3.c * Description: * Version: 1.0 * Created: 2017年01月21日 22时40分27秒 * Revision: none * Compiler: gcc * Author: YOUR NAME (), * Organization: * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> const char *file="/tmp/test_loc"; int main ( int argc, char *argv[] ) { int fd; char buf[100]; struct flock reg_1; struct flock reg_2; memset(buf,'A',100); printf ( "%s\n",buf ); fd=open(file,O_RDWR|O_CREAT,0666); if(fd==-1){ perror("open error"); } write(fd,buf,100); //1 reg_1.l_type=F_WRLCK; reg_1.l_whence=SEEK_SET; reg_1.l_start=10; reg_1.l_len=20; printf ( "RDLCK file 10-30\n" ); if((fcntl(fd,F_SETLK,&reg_1)) == -1){ perror("LCK file error"); } reg_2.l_type=F_WRLCK; reg_2.l_whence=SEEK_SET; reg_2.l_start=10; reg_2.l_len=30; if((fcntl(fd,F_SETLK,&reg_2)) == -1){ perror("LCK2 file error"); } // fcntl(fd,F_GETLK,&reg_2); sleep(5); lseek(fd,10,SEEK_SET); write(fd,"123456",6); getchar(); return 0; }
the_stack_data/1315.c
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <errno.h> #include <pthread.h> #include <semaphore.h> #define N 5 pthread_barrier_t thread_barrier; sem_t mutex; int number_of_threads = N; int count; #define CHECK_ERR(a,msg) {if ((a) == -1) { perror((msg)); exit(EXIT_FAILURE); } } void * thread_function(void * arg) { int s; printf("rendezvous\n"); if (sem_wait(&mutex) == -1) { perror("sem_wait"); exit(EXIT_FAILURE); } count++; if (sem_post(&mutex) == -1) { perror("sem_post"); exit(EXIT_FAILURE); } s = pthread_barrier_wait(&thread_barrier); printf("critical point\n"); return NULL; } int main() { int s; pthread_t threads[N]; s = sem_init(&mutex, 0, 1); s = pthread_barrier_init(&thread_barrier, NULL, N); CHECK_ERR(s,"pthread_barrier_init") for (int i=0; i < number_of_threads; i++) { s = pthread_create(&threads[i], NULL, thread_function, NULL); if (s != 0) { perror("pthread_create"); exit(EXIT_FAILURE); } } for (int i=0; i < number_of_threads; i++) { s = pthread_join(threads[i], NULL); if (s != 0) { perror("pthread_join"); exit(EXIT_FAILURE); } } s = pthread_barrier_destroy(&thread_barrier); CHECK_ERR(s,"pthread_barrier_destroy") printf("\ncount: %d", count); return 0; }
the_stack_data/29826640.c
#include<stdio.h> int main() { int a1, a2, b1, b2, c1, c2, x, y; printf("a1 = "); scanf("%d", &a1); printf("a2 = "); scanf("%d", &a2); printf("b1 = "); scanf("%d", &b1); printf("b2 = "); scanf("%d", &b2); printf("c1 = "); scanf("%d", &c1); printf("c2 = "); scanf("%d", &c2); x = (b2*c1 - b1*c2) / (a1*b2 - a2*b1) ; y = (a1*c2 - a2*c1) / (a1*b2 - a2*b1) ; printf("x = %d , y = %d \n", x , y); return 0; }
the_stack_data/31850.c
#include <curses.h> int main(void) { initscr(); waddstr(curscr, "test thingy"); // refresh(); getch(); endwin(); return 0; }
the_stack_data/247018967.c
// Lemmes nécessaires pour l'arithmétique non linéaire //@ lemma distr_right: forall x, y, z. x*(y+z) == (x*y)+(x*z) ; //@ lemma distr_left: forall x, y, z. (x+y)*z == (x*z)+(y*z) ; // Définition du carré (fonction sqr) //@ function int sqr(int x) = x * x ; int isqrt(int x) { // Le résultat doit être la partie entière de la racine carrée de x //@ requires x >= 0 ; //@ ensures sqr(result) <= x && x < sqr(result + 1) ; int count = 0; int sum = 1; while (sum <= x) { //@ invariant x >= sqr(count) && sum == sqr(count + 1) ; //@ variant x - count ; count++; sum = sum + 2*count+1; } // On a: sqr(count) <= x && sum == sqr(count + 1) && sum > x // On veut: sqr(count) <= x && x < sqr(count + 1) return count; }
the_stack_data/32950812.c
#include <stdio.h> #include <string.h> int hex2dec(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else { return -1; } } char dec2hex(short int c) { if (0 <= c && c <= 9) { return c + '0'; } else if (10 <= c && c <= 15) { return c + 'A' - 10; } else { return -1; } } void urlencode(char in[], char out[]) { int i = 0; int len = strlen(in); int res_len = 0; for (i = 0; i < len; ++i) { char c = in[i]; if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '.' || c == '/' || c == '?' || c == '&' || c == '=' || c == '-' || c == '_') { out[res_len++] = c; } else if (c == ' ') { out[res_len++] = '+'; } else { int j = (short int)c; if (j < 0) j += 256; int i1, i0; i1 = j / 16; i0 = j - i1 * 16; out[res_len++] = '%'; out[res_len++] = dec2hex(i1); out[res_len++] = dec2hex(i0); } } out[res_len] = '\0'; } void urldecode(char in[], char out[]) { int i = 0; int len = strlen(in); int res_len = 0; for (i = 0; i < len; ++i) { char c = in[i]; if (c != '%') { if (c == '+') out[res_len++] = ' '; else out[res_len++] = c; } else { char c1 = in[++i]; char c0 = in[++i]; int num = 0; num = hex2dec(c1) * 16 + hex2dec(c0); out[res_len++] = num; } } out[res_len] = '\0'; } void testUrlEncode() { char in[100] = "http://www.example.com/vad?date=Thu, 31 Thu 1999 15:04:39 GMT"; char out[100]; urlencode(in, out); printf("%s\n", out); urldecode(out, in); printf("%s\n", in); }
the_stack_data/1241113.c
#include <stdio.h> //【证明算法的美 !】计算1——>100的和 //普通思维算法,运算次数COUNT=100 /* int main() { int i, sum, count; for (i = 1; i <= 100; i++) { count++; sum += i; } printf("SUM = %d\n", sum); printf("COUNT = %d\n", count); getchar(); return 0; } */ //简洁思维算法,运算次数为COUNT=1 int main() { int sum; int count=0; int n=100; sum = (1 + n) * n / 2; printf("SUM = %d\n", sum); printf("COUNT = %d\n", ++count); getchar(); return 0; }