file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/178264751.c
#include <term.h> #define key_f27 tigetstr("kf27") /** f27 key **/ /* TERMINFO_NAME(kf27) TERMCAP_NAME(kr) XOPEN(400) */
the_stack_data/45450322.c
a[111], s, s2, b[111], t; main(n, i) { scanf("%d%d", &n, a + 1); b[++t] = 1, s = s2 = a[1]; for (i = 2; i <= n; i++) { scanf("%d", a + i); if (a[i] * 2 <= a[1]) b[++t] = i, s += a[i]; s2 += a[i]; } if (s * 2 <= s2) return puts("0"), 0; printf("%d\n", t); for (i = 1; i <= t; i++) printf("%d ", b[i]); }
the_stack_data/25574.c
#include <stdio.h> int main() { int percentual; double salario, aumento; scanf("%lf", &salario); if(salario > 0) { if(salario <= 400.00) { percentual = 15; } else { if(salario <= 800.00) { percentual = 12; } else { if(salario <= 1200.00) { percentual = 10; } else { if(salario <= 2000.00) { percentual = 7; } else { percentual = 4; } } } } aumento = (salario/100) * percentual; salario += aumento; printf("Novo salario: %.2lf\n", salario); printf("Reajuste ganho: %.2lf\n", aumento); printf("Em percentual: %d %%\n", percentual); } } /* 0 - 400.00 15% Novo salario: 460.00 400.01 - 800.00 12% Reajuste ganho: 60.00 800.01 - 1200.00 10% Em percentual: 15 % 1200.01 - 2000.00 7% Acima de 2000.00 4% */
the_stack_data/181394278.c
#ifdef CONFIG_USE_LOCAL_STRING_H #include "_string.h" #else #include <string.h> #endif //----------------------------------------------------------------- // memchr: //----------------------------------------------------------------- #ifdef MEMCHAR_LEGACY void * memchr(const void *s, unsigned char c, int n) #else void * memchr(const void *s, int c, size_t n) #endif { if (n != 0) { const unsigned char *p = (const unsigned char*)s; do { if (*p++ == c) return ((void *)(p - 1)); } while (--n != 0); } return 0; }
the_stack_data/133201.c
// Write your code here #include <stdio.h> #include <stdlib.h> int main() { int n; int count; scanf("%d%d",&n,&count); int i,j,temp,minimum; int arr[i]; for(i = 0;i < n;i++) { scanf("%d",&arr[i]); } for(i = 0;i < count;i++) { minimum = i; for(j = i+1;j < n;j++) { if(arr[minimum] > arr[j]) { minimum = j; } } if(minimum != i) { temp = arr[minimum]; arr[minimum] = arr[j]; arr[j] = temp; } } for(i = 0;i < n;i++) { printf("%d ",arr[i]); } return 0; }
the_stack_data/114547.c
#include<stdio.h> #include<stdlib.h> void InsertionSort(int A[],int n) { int i, j, x; for (i = 1; i < n; i++) { j=i-1; x=A[i]; while (j>-1 && A[j]>x) { A[j+1]=A[j]; j--; } A[j+1]=x; } } int main() { int *p, num ,i; printf("Enter the number of elements to sort: "); scanf("%d",&num); p=(int*) malloc(num * sizeof(int)); printf("\nPut the numbers: "); for(i=0;i<num;i++) { scanf("%d",(p+i)); } InsertionSort(p,num); printf("\n"); for(i=0;i<num;i++) { printf("%d\t",*(p+i)); } free(p); return 0; }
the_stack_data/179831879.c
#include <stdio.h> #include <math.h> #define PI 3.1415926536 int main(){ double x,y,z; double r,h,t; while(scanf("%lf %lf %lf",&r,&h,&t) != EOF){ x = r * sin(h*PI/180) * cos(t*PI/180); y = r * sin(h*PI/180) * sin(t*PI/180); z = r * cos(h*PI/180); printf("x = %.10f y = %.10f z = %.10f\n",x,y,z); } return 0; }
the_stack_data/43887953.c
#include <stdio.h> int main() { int rad; printf("please enter a raduis: "); scanf("%i", &rad); double area = 3.14159 * (rad * rad); printf("The area of a circle with %i radius is %f\n", rad,area); return 0; }
the_stack_data/132953538.c
/* * Copyright (c) 2007 - 2015 Joseph Gaeddert * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // // autotest fft data for 20-point transform // #include <complex.h> float complex fft_test_x20[] = { -0.138174469322 + -0.274748504122*_Complex_I, -1.227476709426 + 0.905279873773*_Complex_I, -0.940584818722 + -0.463678927507*_Complex_I, -0.327372793730 + 0.441537277752*_Complex_I, 0.086812488375 + 1.122322318862*_Complex_I, -0.100645730164 + -0.142102548176*_Complex_I, -0.339607323410 + -0.632982556339*_Complex_I, -1.122342071583 + -0.361529677196*_Complex_I, -0.394764118785 + 1.317868322379*_Complex_I, 0.885025645922 + 0.277662260330*_Complex_I, -0.937809434341 + -0.464711897028*_Complex_I, -0.316998490158 + 0.688777215432*_Complex_I, 0.649526607014 + 0.181558179235*_Complex_I, 0.780299241568 + -0.070192359053*_Complex_I, 1.932600474030 + -0.136400805574*_Complex_I, -0.216121187682 + -0.461249755715*_Complex_I, 0.926223942818 + -0.028529590209*_Complex_I, 1.602135289481 + 1.434596371731*_Complex_I, 1.623836928491 + -1.265873017618*_Complex_I, 1.568843067308 + -0.364404259258*_Complex_I}; float complex fft_test_y20[] = { 3.993406537683 + 1.703197921701*_Complex_I, 3.008874212687 + 7.663142996950*_Complex_I, -1.159042365700 + 3.282695683450*_Complex_I, 0.903124379379 + 1.428002755716*_Complex_I, -1.572075523393 + 4.283883169775*_Complex_I, 2.253301421641 + 2.928788716985*_Complex_I, 3.534976344610 + 2.383761115026*_Complex_I, 1.326813143543 + 3.111834244207*_Complex_I, -3.988701280111 + -0.677308408606*_Complex_I, -1.984004176890 + -4.401380983625*_Complex_I, 0.942714014611 + -2.993550877540*_Complex_I, 2.448617718798 + -1.195359461640*_Complex_I, -3.328697057289 + -4.221639306000*_Complex_I, 4.287827550431 + 1.139111429335*_Complex_I, -4.013398939947 + -0.677595378939*_Complex_I, -2.670924173537 + 7.635447143438*_Complex_I, -2.067686784436 + -7.802196902076*_Complex_I, -1.972088145081 + -6.957222482710*_Complex_I, -3.101333982661 + -2.675851028288*_Complex_I, 0.394807719219 + -9.452730429599*_Complex_I};
the_stack_data/150141112.c
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { float x,y; float total,avg; printf("Enter marks of your first subject: "); scanf("%2f", &x); printf("Enter marks of your second subject: "); scanf("%2f", &y); total=x+y; avg=total/2; printf("The average is %2f", avg); return 0; }
the_stack_data/40761778.c
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) Id */ #define ZLIB_INTERNAL #include "zlib.h" #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* use NO_DIVIDE if your processor does not do division in hardware */ #ifdef NO_DIVIDE # define MOD(a) \ do { \ if (a >= (BASE << 16)) a -= (BASE << 16); \ if (a >= (BASE << 15)) a -= (BASE << 15); \ if (a >= (BASE << 14)) a -= (BASE << 14); \ if (a >= (BASE << 13)) a -= (BASE << 13); \ if (a >= (BASE << 12)) a -= (BASE << 12); \ if (a >= (BASE << 11)) a -= (BASE << 11); \ if (a >= (BASE << 10)) a -= (BASE << 10); \ if (a >= (BASE << 9)) a -= (BASE << 9); \ if (a >= (BASE << 8)) a -= (BASE << 8); \ if (a >= (BASE << 7)) a -= (BASE << 7); \ if (a >= (BASE << 6)) a -= (BASE << 6); \ if (a >= (BASE << 5)) a -= (BASE << 5); \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) # define MOD4(a) \ do { \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE # define MOD4(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long sum2; unsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD4(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32_combine(adler1, adler2, len2) uLong adler1; uLong adler2; z_off_t len2; { unsigned long sum1; unsigned long sum2; unsigned rem; /* the derivation of this formula is left as an exercise for the reader */ rem = (unsigned)(len2 % BASE); sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); sum1 += (adler2 & 0xffff) + BASE - 1; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; if (sum1 > BASE) sum1 -= BASE; if (sum1 > BASE) sum1 -= BASE; if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); if (sum2 > BASE) sum2 -= BASE; return sum1 | (sum2 << 16); }
the_stack_data/161080838.c
#include <stdio.h> #include <unistd.h> void main() { fork(); printf("Novo processo criado!\n"); }
the_stack_data/132189.c
extern int __VERIFIER_nondet_int(); extern void __VERIFIER_assume(int); int nondet_signed_int() { int r = __VERIFIER_nondet_int(); __VERIFIER_assume ((-0x7fffffff - 1) <= r && r <= 0x7fffffff); return r; } void foo(void); signed int x; void foo(void) { while(!(!(x - 1 < (-0x7fffffff - 1) || 0x7fffffff < x - 1))); x = x - 1; } signed int main() { x = nondet_signed_int(); while(x >= 1) { signed int return_value___VERIFIER_nondet_int=nondet_signed_int(); if(!(return_value___VERIFIER_nondet_int == 0)) foo(); else foo(); } return 0; }
the_stack_data/59512659.c
#include<stdio.h> #include<stdlib.h> struct lista{ int info; struct lista *ant; struct lista *prox; }; typedef struct lista Lista; Lista* iniciarLista(void){ return NULL; } Lista* inserirElemento(Lista* l, int v){ Lista* novo = (Lista*)malloc(sizeof(Lista)); novo->info = v; novo->prox = l; novo->ant = NULL; if(l != NULL) l->ant = novo; return novo; } Lista* busca(Lista* l, int v){ Lista* p; for(p = l; p != NULL; p = p->prox) if(p->info == v) return p; return NULL; } Lista* removerElemento(Lista* l, int v){ Lista* p = busca(l, v); if(p == NULL) return l; if(l == p) l = p->prox; else p->ant->prox = p->prox; if(p->prox != NULL) p->prox->ant = p->ant; free(p); return l; } void imprimeElementos(Lista* l){ Lista* p; //Variável auxiliar para percorrer a lista for(p = l; p != NULL; p = p->prox) printf("info = %d\n", p->info); } void liberarLista(Lista* l){ //Remove elemento por elemento Lista* p = l; while(p != NULL){ Lista* t = p->prox; //Guarda referência para o próximo elemento a ser removido free(p); //Librea p p = t; //Faz p apontar para o próximo elemento } } int main(){ Lista* l; l = iniciarLista(); l = inserirElemento(l, 23); l = inserirElemento(l, 56); l = inserirElemento(l, 7); imprimeElementos(l); printf("\n"); l = removerElemento(l, 23); imprimeElementos(l); printf("\n"); liberarLista(l); return 0; }
the_stack_data/888917.c
// Exercise 5 from chapter 3 // This program executes a sum, a subtraction and shows the result at the terminal. #include<stdio.h> int main( void ) { int sum; // COMPUTE RESULT sum = 25 + 37 - 19; // DISPLAY RESULTS printf( "The answer is %i\n", sum ); return 0; }
the_stack_data/23576032.c
#include <stdio.h> int main() { int n, num1 = 0, num2 = 1, temp; printf("How many Fibonacci numbers do you want?\n"); scanf("%d", &n); for (int i = 0; i <= n; i++) { printf("%d\n", num1); temp = num1 + num2; num1 = num2; num2 = temp; } return 0; }
the_stack_data/198579539.c
main(p,c){for(p=0;c=~getchar();printf(" %02x"+(p++%16!=8),~c))p%16||printf("\n%08x:"+!p,p);puts("");}
the_stack_data/15547.c
/* Exercício 07 - Faça 3 funções: • ler: - uma função que receba dois número inteiro positivo n; • multiplicar: - que multiplique os números recebidos na função ler; • imprimir: - que imprima o resultado da função multiplicar. */ # include <stdio.h> int n1, n2; int main(void) { int ler(void); int multiplicar(int n1, int n2); int imprimir(int num); ler(); imprimir(multiplicar(n1, n2)); return 0; } int ler(void) { printf("1° valor: "); scanf("%d", &n1); printf("2° valor: "); scanf("%d", &n2); return n1, n2; } int multiplicar(int n1, int n2) { return n1 * n2; } int imprimir(int num) { printf("Resultado = %d\n", num); return 0; }
the_stack_data/192330690.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern int __VERIFIER_nondet_int(void); extern int printf (__const char *__restrict __format, ...); /* Generated by CIL v. 1.3.7 */ /* print_CIL_Input is true */ struct JoinPoint { void **(*fp)(struct JoinPoint * ) ; void **args ; int argsCount ; char const **argsType ; void *(*arg)(int , struct JoinPoint * ) ; char const *(*argType)(int , struct JoinPoint * ) ; void **retValue ; char const *retType ; char const *funcName ; char const *targetName ; char const *fileName ; char const *kind ; void *excep_return ; }; struct __UTAC__CFLOW_FUNC { int (*func)(int , int ) ; int val ; struct __UTAC__CFLOW_FUNC *next ; }; struct __UTAC__EXCEPTION { void *jumpbuf ; unsigned long long prtValue ; int pops ; struct __UTAC__CFLOW_FUNC *cflowfuncs ; }; typedef unsigned int size_t; struct __ACC__ERR { void *v ; struct __ACC__ERR *next ; }; #pragma merger(0,"Specification4_spec.i","") void __automaton_fail(void) ; int isPumpRunning(void) ; int getWaterLevel(void) ; inline static void __utac_acc__Specification4_spec__1(void) { int tmp ; int tmp___0 ; { { tmp = getWaterLevel(); } if (tmp == 0) { { tmp___0 = isPumpRunning(); } if (tmp___0) { { __automaton_fail(); } } else { } } else { } return; } } #pragma merger(0,"libacc.i","") extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion , char const *__file , unsigned int __line , char const *__function ) ; extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ; extern __attribute__((__nothrow__)) void free(void *__ptr ) ; void __utac__exception__cf_handler_set(void *exception , int (*cflow_func)(int , int ) , int val ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; void *tmp ; unsigned long __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; unsigned long __cil_tmp13 ; unsigned long __cil_tmp14 ; int (**mem_15)(int , int ) ; int *mem_16 ; struct __UTAC__CFLOW_FUNC **mem_17 ; struct __UTAC__CFLOW_FUNC **mem_18 ; struct __UTAC__CFLOW_FUNC **mem_19 ; { { excep = (struct __UTAC__EXCEPTION *)exception; tmp = malloc(24UL); cf = (struct __UTAC__CFLOW_FUNC *)tmp; mem_15 = (int (**)(int , int ))cf; *mem_15 = cflow_func; __cil_tmp7 = (unsigned long )cf; __cil_tmp8 = __cil_tmp7 + 8; mem_16 = (int *)__cil_tmp8; *mem_16 = val; __cil_tmp9 = (unsigned long )cf; __cil_tmp10 = __cil_tmp9 + 16; __cil_tmp11 = (unsigned long )excep; __cil_tmp12 = __cil_tmp11 + 24; mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp10; mem_18 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp12; *mem_17 = *mem_18; __cil_tmp13 = (unsigned long )excep; __cil_tmp14 = __cil_tmp13 + 24; mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14; *mem_19 = cf; } return; } } void __utac__exception__cf_handler_free(void *exception ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; struct __UTAC__CFLOW_FUNC *tmp ; unsigned long __cil_tmp5 ; unsigned long __cil_tmp6 ; struct __UTAC__CFLOW_FUNC *__cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; void *__cil_tmp12 ; unsigned long __cil_tmp13 ; unsigned long __cil_tmp14 ; struct __UTAC__CFLOW_FUNC **mem_15 ; struct __UTAC__CFLOW_FUNC **mem_16 ; struct __UTAC__CFLOW_FUNC **mem_17 ; { excep = (struct __UTAC__EXCEPTION *)exception; __cil_tmp5 = (unsigned long )excep; __cil_tmp6 = __cil_tmp5 + 24; mem_15 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6; cf = *mem_15; { while (1) { while_0_continue: /* CIL Label */ ; { __cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0; __cil_tmp8 = (unsigned long )__cil_tmp7; __cil_tmp9 = (unsigned long )cf; if (__cil_tmp9 != __cil_tmp8) { } else { goto while_0_break; } } { tmp = cf; __cil_tmp10 = (unsigned long )cf; __cil_tmp11 = __cil_tmp10 + 16; mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp11; cf = *mem_16; __cil_tmp12 = (void *)tmp; free(__cil_tmp12); } } while_0_break: /* CIL Label */ ; } __cil_tmp13 = (unsigned long )excep; __cil_tmp14 = __cil_tmp13 + 24; mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14; *mem_17 = (struct __UTAC__CFLOW_FUNC *)0; return; } } void __utac__exception__cf_handler_reset(void *exception ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; unsigned long __cil_tmp5 ; unsigned long __cil_tmp6 ; struct __UTAC__CFLOW_FUNC *__cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; int (*__cil_tmp10)(int , int ) ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; int __cil_tmp13 ; unsigned long __cil_tmp14 ; unsigned long __cil_tmp15 ; struct __UTAC__CFLOW_FUNC **mem_16 ; int (**mem_17)(int , int ) ; int *mem_18 ; struct __UTAC__CFLOW_FUNC **mem_19 ; { excep = (struct __UTAC__EXCEPTION *)exception; __cil_tmp5 = (unsigned long )excep; __cil_tmp6 = __cil_tmp5 + 24; mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6; cf = *mem_16; { while (1) { while_1_continue: /* CIL Label */ ; { __cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0; __cil_tmp8 = (unsigned long )__cil_tmp7; __cil_tmp9 = (unsigned long )cf; if (__cil_tmp9 != __cil_tmp8) { } else { goto while_1_break; } } { mem_17 = (int (**)(int , int ))cf; __cil_tmp10 = *mem_17; __cil_tmp11 = (unsigned long )cf; __cil_tmp12 = __cil_tmp11 + 8; mem_18 = (int *)__cil_tmp12; __cil_tmp13 = *mem_18; (*__cil_tmp10)(4, __cil_tmp13); __cil_tmp14 = (unsigned long )cf; __cil_tmp15 = __cil_tmp14 + 16; mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp15; cf = *mem_19; } } while_1_break: /* CIL Label */ ; } { __utac__exception__cf_handler_free(exception); } return; } } void *__utac__error_stack_mgt(void *env , int mode , int count ) ; static struct __ACC__ERR *head = (struct __ACC__ERR *)0; void *__utac__error_stack_mgt(void *env , int mode , int count ) { void *retValue_acc ; struct __ACC__ERR *new ; void *tmp ; struct __ACC__ERR *temp ; struct __ACC__ERR *next ; void *excep ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; unsigned long __cil_tmp13 ; void *__cil_tmp14 ; unsigned long __cil_tmp15 ; unsigned long __cil_tmp16 ; void *__cil_tmp17 ; void **mem_18 ; struct __ACC__ERR **mem_19 ; struct __ACC__ERR **mem_20 ; void **mem_21 ; struct __ACC__ERR **mem_22 ; void **mem_23 ; void **mem_24 ; { if (count == 0) { return (retValue_acc); } else { } if (mode == 0) { { tmp = malloc(16UL); new = (struct __ACC__ERR *)tmp; mem_18 = (void **)new; *mem_18 = env; __cil_tmp10 = (unsigned long )new; __cil_tmp11 = __cil_tmp10 + 8; mem_19 = (struct __ACC__ERR **)__cil_tmp11; *mem_19 = head; head = new; retValue_acc = (void *)new; } return (retValue_acc); } else { } if (mode == 1) { temp = head; { while (1) { while_2_continue: /* CIL Label */ ; if (count > 1) { } else { goto while_2_break; } { __cil_tmp12 = (unsigned long )temp; __cil_tmp13 = __cil_tmp12 + 8; mem_20 = (struct __ACC__ERR **)__cil_tmp13; next = *mem_20; mem_21 = (void **)temp; excep = *mem_21; __cil_tmp14 = (void *)temp; free(__cil_tmp14); __utac__exception__cf_handler_reset(excep); temp = next; count = count - 1; } } while_2_break: /* CIL Label */ ; } { __cil_tmp15 = (unsigned long )temp; __cil_tmp16 = __cil_tmp15 + 8; mem_22 = (struct __ACC__ERR **)__cil_tmp16; head = *mem_22; mem_23 = (void **)temp; excep = *mem_23; __cil_tmp17 = (void *)temp; free(__cil_tmp17); __utac__exception__cf_handler_reset(excep); retValue_acc = excep; } return (retValue_acc); } else { } if (mode == 2) { if (head) { mem_24 = (void **)head; retValue_acc = *mem_24; return (retValue_acc); } else { retValue_acc = (void *)0; return (retValue_acc); } } else { } return (retValue_acc); } } void *__utac__get_this_arg(int i , struct JoinPoint *this ) { void *retValue_acc ; unsigned long __cil_tmp4 ; unsigned long __cil_tmp5 ; int __cil_tmp6 ; int __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; void **__cil_tmp10 ; void **__cil_tmp11 ; int *mem_12 ; void ***mem_13 ; { if (i > 0) { { __cil_tmp4 = (unsigned long )this; __cil_tmp5 = __cil_tmp4 + 16; mem_12 = (int *)__cil_tmp5; __cil_tmp6 = *mem_12; if (i <= __cil_tmp6) { } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 123U, "__utac__get_this_arg"); } } } } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 123U, "__utac__get_this_arg"); } } __cil_tmp7 = i - 1; __cil_tmp8 = (unsigned long )this; __cil_tmp9 = __cil_tmp8 + 8; mem_13 = (void ***)__cil_tmp9; __cil_tmp10 = *mem_13; __cil_tmp11 = __cil_tmp10 + __cil_tmp7; retValue_acc = *__cil_tmp11; return (retValue_acc); return (retValue_acc); } } char const *__utac__get_this_argtype(int i , struct JoinPoint *this ) { char const *retValue_acc ; unsigned long __cil_tmp4 ; unsigned long __cil_tmp5 ; int __cil_tmp6 ; int __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; char const **__cil_tmp10 ; char const **__cil_tmp11 ; int *mem_12 ; char const ***mem_13 ; { if (i > 0) { { __cil_tmp4 = (unsigned long )this; __cil_tmp5 = __cil_tmp4 + 16; mem_12 = (int *)__cil_tmp5; __cil_tmp6 = *mem_12; if (i <= __cil_tmp6) { } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 131U, "__utac__get_this_argtype"); } } } } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 131U, "__utac__get_this_argtype"); } } __cil_tmp7 = i - 1; __cil_tmp8 = (unsigned long )this; __cil_tmp9 = __cil_tmp8 + 24; mem_13 = (char const ***)__cil_tmp9; __cil_tmp10 = *mem_13; __cil_tmp11 = __cil_tmp10 + __cil_tmp7; retValue_acc = *__cil_tmp11; return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"wsllib_check.i","") void __automaton_fail(void) { { ERROR: __VERIFIER_error(); return; } } #pragma merger(0,"Test.i","") int cleanupTimeShifts = 4; void timeShift(void) ; void cleanup(void) { int i ; int __cil_tmp2 ; { { timeShift(); i = 0; } { while (1) { while_3_continue: /* CIL Label */ ; { __cil_tmp2 = cleanupTimeShifts - 1; if (i < __cil_tmp2) { } else { goto while_3_break; } } { timeShift(); i = i + 1; } } while_3_break: /* CIL Label */ ; } return; } } void printPump(void) ; void waterRise(void) ; void changeMethaneLevel(void) ; void Specification2(void) { { { timeShift(); printPump(); timeShift(); printPump(); timeShift(); printPump(); waterRise(); printPump(); timeShift(); printPump(); changeMethaneLevel(); printPump(); timeShift(); printPump(); cleanup(); } return; } } void setup(void) { { return; } } void test(void) ; void runTest(void) { { { test(); } return; } } void select_helpers(void) ; void select_features(void) ; int valid_product(void) ; int main(void) { int retValue_acc ; int tmp ; { { select_helpers(); select_features(); tmp = valid_product(); } if (tmp) { { setup(); runTest(); } } else { } retValue_acc = 0; return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"MinePump.i","") void lowerWaterLevel(void) ; int isMethaneLevelCritical(void) ; void printEnvironment(void) ; void activatePump(void) ; void deactivatePump(void) ; void startSystem(void) ; int pumpRunning = 0; int systemActive = 1; void processEnvironment(void) ; void timeShift(void) { { if (pumpRunning) { { lowerWaterLevel(); } } else { } if (systemActive) { { processEnvironment(); } } else { } { __utac_acc__Specification4_spec__1(); } return; } } void processEnvironment(void) { { return; } } void activatePump__wrappee__base(void) { { pumpRunning = 1; return; } } int isMethaneAlarm(void) ; void activatePump(void) { int tmp ; { { tmp = isMethaneAlarm(); } if (tmp) { } else { { activatePump__wrappee__base(); } } return; } } void deactivatePump(void) { { pumpRunning = 0; return; } } int isMethaneAlarm(void) { int retValue_acc ; { { retValue_acc = isMethaneLevelCritical(); } return (retValue_acc); return (retValue_acc); } } int isPumpRunning(void) { int retValue_acc ; { retValue_acc = pumpRunning; return (retValue_acc); return (retValue_acc); } } void printPump(void) { { { printf("Pump(System:"); } if (systemActive) { { printf("On"); } } else { { printf("Off"); } } { printf(",Pump:"); } if (pumpRunning) { { printf("On"); } } else { { printf("Off"); } } { printf(") "); printEnvironment(); printf("\n"); } return; } } void startSystem(void) { { systemActive = 1; return; } } #pragma merger(0,"scenario.i","") void test(void) { int splverifierCounter ; int tmp ; int tmp___0 ; int tmp___1 ; int tmp___2 ; { splverifierCounter = 0; { while (1) { while_4_continue: /* CIL Label */ ; if (splverifierCounter < 4) { } else { goto while_4_break; } { tmp = __VERIFIER_nondet_int(); } if (tmp) { { waterRise(); } } else { } { tmp___0 = __VERIFIER_nondet_int(); } if (tmp___0) { { changeMethaneLevel(); } } else { } { tmp___2 = __VERIFIER_nondet_int(); } if (tmp___2) { { startSystem(); } } else { { tmp___1 = __VERIFIER_nondet_int(); } if (tmp___1) { } else { } } { timeShift(); } } while_4_break: /* CIL Label */ ; } { cleanup(); } return; } } #pragma merger(0,"Environment.i","") int waterLevel = 1; int methaneLevelCritical = 0; void lowerWaterLevel(void) { { if (waterLevel > 0) { waterLevel = waterLevel - 1; } else { } return; } } void waterRise(void) { { if (waterLevel < 2) { waterLevel = waterLevel + 1; } else { } return; } } void changeMethaneLevel(void) { { if (methaneLevelCritical) { methaneLevelCritical = 0; } else { methaneLevelCritical = 1; } return; } } int isMethaneLevelCritical(void) { int retValue_acc ; { retValue_acc = methaneLevelCritical; return (retValue_acc); return (retValue_acc); } } void printEnvironment(void) { { { printf("Env(Water:%i", waterLevel); printf(",Meth:"); } if (methaneLevelCritical) { { printf("CRIT"); } } else { { printf("OK"); } } { printf(")"); } return; } } int getWaterLevel(void) { int retValue_acc ; { retValue_acc = waterLevel; return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"featureselect.i","") int select_one(void) ; int select_one(void) { int retValue_acc ; int choice = __VERIFIER_nondet_int(); { retValue_acc = choice; return (retValue_acc); return (retValue_acc); } } void select_features(void) { { return; } } void select_helpers(void) { { return; } } int valid_product(void) { int retValue_acc ; { retValue_acc = 1; return (retValue_acc); return (retValue_acc); } }
the_stack_data/926719.c
#include <stdio.h> int main(void) { int num_a = 20; int num_b = 14; printf("%d or %d = %d\n", num_a, num_b, num_a | num_b); return 0; }
the_stack_data/32201.c
// Program Question 1 Week 3 Arthur Coll// #include <stdio.h> int main() { float Answer = 100 % 33; printf ("%f Remains", Answer); getchar(); return 0; }
the_stack_data/75137200.c
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #define NOFLAGS 0 #define BLOCK_LENGTH 16 extern int macfd, vrfyfd; int Oracle_Connect() { struct sockaddr_in mac_servaddr, mac_cliaddr, vrfy_servaddr, vrfy_cliaddr; macfd = socket(AF_INET, SOCK_STREAM, 0); vrfyfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&mac_servaddr, sizeof(mac_servaddr)); bzero(&vrfy_servaddr, sizeof(vrfy_servaddr)); mac_servaddr.sin_family = AF_INET; vrfy_servaddr.sin_family = AF_INET; mac_servaddr.sin_addr.s_addr=inet_addr("54.165.60.84"); vrfy_servaddr.sin_addr.s_addr=inet_addr("54.165.60.84"); mac_servaddr.sin_port=htons(81); vrfy_servaddr.sin_port=htons(82); if( !connect(macfd, (struct sockaddr *)&mac_servaddr, sizeof(mac_servaddr)) && !connect(vrfyfd, (struct sockaddr *)&vrfy_servaddr, sizeof(vrfy_servaddr)) ) { printf("Connected to server successfully.\n"); return 0; } else { perror("Failed to connect to oracle"); return -1; } } int Oracle_Disconnect() { if(!close(macfd) && !close(vrfyfd)) { printf("Connection closed successfully.\n"); return 0; } else { perror("[WARNING]: You haven't connected to the server yet"); return -1; } } // < mlength (1) || message (mlength) || 0 > int Mac(unsigned char *message, int mlength, unsigned char *tag) { unsigned char out[mlength+2]; unsigned char in[16]; int i; out[0] = mlength; memcpy((out+1), message, mlength); out[1+mlength] = '\0'; if(!send(macfd, out, (mlength + 2), NOFLAGS)) { perror("[WARNING]: You haven't connected to the server yet"); return -1; } if(!recv(macfd, in, 16, NOFLAGS)) { perror("[ERROR]: Recv failed"); return -1; } for (i=0; i<16; i++) { tag[i] = in[i]; } return 0; } int Vrfy(unsigned char *message, int mlength, unsigned char *tag) { unsigned char out[mlength+2+16]; char in[2]; int i; out[0] = mlength; memcpy((out+1), message, mlength); memcpy((out+1+mlength), tag, 16); out[1+mlength+16] = '\0'; if(!send(vrfyfd, out, (mlength + 2 + 16), NOFLAGS)) { perror("[WARNING]: You haven't connected to the server yet"); return -1; } if(!recv(vrfyfd, in, 2, NOFLAGS)) { perror("[ERROR]: Recv failed"); return -1; } return atoi(in); }
the_stack_data/192331518.c
#include <stdio.h> #include <assert.h> int linear_search(int arr[], int size, int element); int linear_search(int arr[], int size, int element) { for(int i=0;i<size;i++){ if(arr[i] == element) { return i; } } return -1; } void linear_search_test(){ // testing for an empty array int empty[] = {}; int empty_size = sizeof(empty)/sizeof(int); //testing for a specific element int a[] = {1, 3, 4, 8, 6}; int a_size = sizeof(a)/sizeof(int); assert(linear_search(empty, empty_size, 3) == -1); assert(linear_search(a, a_size, 3) == 1); printf("Should return -1 = %d\n", linear_search(empty, empty_size, 3)); printf("Should return 1 = %d\n", linear_search(a, a_size, 3)); } int main() { linear_search_test(); return 0; }
the_stack_data/33189.c
/****************************************************************************** * * Copyright (C) 2019 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; typedef unsigned long UINTPTR; // Standard constants #define XSDFEC_STANDARD_OTHER 0 #define XSDFEC_STANDARD_5G 1 // Type Definitions /** Device configuration * * Contains configuration information for the device. */ typedef struct { u16 DeviceId; UINTPTR BaseAddress; u32 Standard; u32 Initialization[4]; } XSdFec_Config; /** SD-FEC driver instance * * Contains state information for each device. */ typedef struct { UINTPTR BaseAddress; u32 IsReady; u32 Standard; u32 SCOffset[128]; /**< Lookup to SC table offsets for each code ID */ u32 LAOffset[128]; /**< Lookup to LA table offsets for each code ID */ u32 QCOffset[128]; /**< Lookup to QC table offsets for each code ID */ } XSdFec; /** Struct defining LDPC code parameters * * Member values are defined in device specific header * x<ipinst_name >_<code_id>_params.h. as per IP GUI configuration */ typedef struct { u32 N; u32 K; u32 PSize; u32 NLayers; u32 NQC; u32 NMQC; u32 NM; u32 NormType; u32 NoPacking; u32 SpecialQC; u32 NoFinalParity; u32 MaxSchedule; u32* SCTable; u32* LATable; u32* QCTable; } XSdFecLdpcParameters; /** Struct defining Turbo Decode parameters * * Member values defined in device specific header * x<ipinst_name>_turbo_params.h as per IP GUI configuration */ typedef struct { u8 Alg; u16 Scale; } XSdFecTurboParameters; // Default MaxScale Turbo configuration // #define XSDFEC_TD_PARAM_MAX_DEFAULT { 0 , 12 } // Default MaxScale Turbo configuration // #define XSDFEC_TD_PARAM_MAXSTAR_DEFAULT { 1 , 0 } /** Interrupt class * * Members define interrupt class and action required */ typedef struct { u8 Intf; /**< Triggered due to interface or control error (ISR) */ u8 ECCSBit; /**< Triggered due to single-bit ECC error (ECC_ISR) */ u8 ECCMBit; /**< Triggered due to multi-bit ECC error (ECC_ISR) */ u8 RstReq; /**< Device requires reset */ u8 ReprogReq; /**< Device requires reprogrammed */ u8 ReCfgReq; /**< FPGA requires reprogrammed */ } XSdFecInterruptClass; // API Function Prototypes /** Device initialization * * The driver looks up its own configuration structure created by the * tool-chain based on an ID provided by the tool-chain. */ int XSdFecInitialize(XSdFec *InstancePtr, u16 DeviceId); /** Configuration lookup * * Returns the configuration struct for a given device ID */ XSdFec_Config* XSdFecLookupConfig(u16 DeviceId); /**Device initialization * * Uses a configuration structure provided by the caller */ int XSdFecCfgInitialize(XSdFec *InstancePtr, XSdFec_Config *ConfigPtr); /** Add LDPC parameters to a device * * Updates LDPC code parameter registers and share tables using the * specified CodeId and offsets with the specified parameters. * The offsets arrays in the given XSdFec instance structure are updated * with the supplied offsets for specified CodeId. * * NOTE: When the device/IP has been configured to support the 5G NR standard * the IP directly supports the 5G NR codes * and it is not necessary to add the codes at run-time. This function will * generate an assertion if used on a instance * configured to support the 5G NR standard. * * @param InstancePtr Pointer to device instance struct * @param CodeId Code number to be used for the specified LDPC code * @param SCOffset Scale table offset to use for specified LDPC code * @param LAOffset LA table offset to use for specified LDPC code * @param QSCOffset QC table offset to use for specified LDPC code * @param ParamsPtr Pointer to parameters struct for the LDPC code to be * added to the device * */ void XSdFecAddLdpcParams(XSdFec *InstancePtr, u32 CodeId, u32 SCOffset, u32 LAOffset, u32 QCOffset, const XSdFecLdpcParameters* ParamsPtr); /** Set Turbo parameters on a device * * Updates Turbo code parameter registers * * @param InstancePtr Pointer to device instance struct * @param ParamsPtr Pointer to Turbo parameters struct to be set on device */ void XSdFecSetTurboParams(XSdFec *InstancePtr, const XSdFecTurboParameters* ParamsPtr); /**Calculate share table size for a LDPC code * * Populates SCSizePtr, LASizePtr and QCSizePtr variables with the effective * table size occupied by the specified * LDPC code. These values can be used to increment the table offsets. * * @param ParamsPtr Pointer to parameters struct for the LDPC code being * queried * @param SCSizePtr Pointer to variable to populate with the effective * scale table size for the specified LDPC code * @param LASizePtr Pointer to variable to populate with the effective * LA table size for the specified LDPC code * @param QCSizePtr Pointer to variable to populate with the effective QC * table size for the specified LDPC code * */ void XSdFecShareTableSize(const XSdFecLdpcParameters* ParamsPtr, u32* SCSizePtr, u32* LASizePtr, u32* QCSizePtr); /**Classify interrupts * * Queries interrupt status registers and classifies interrupt and reports recovery action * * @param InstancePtr Pointer to device instance struct * * @returns Interrupt Class Struct defining interrupt class and * recover action */ XSdFecInterruptClass XSdFecInterruptClassifier(XSdFec *InstancePtr); // Base API Function Prototypes /** * CORE_AXI_WR_PROTECT access functions */ void XSdFecSet_CORE_AXI_WR_PROTECT(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXI_WR_PROTECT(UINTPTR BaseAddress); /** * CORE_CODE_WR_PROTECT access functions */ void XSdFecSet_CORE_CODE_WR_PROTECT(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_CODE_WR_PROTECT(UINTPTR BaseAddress); /** * CORE_ACTIVE access functions */ u32 XSdFecGet_CORE_ACTIVE(UINTPTR BaseAddress); /** * CORE_AXIS_WIDTH access functions */ void XSdFecSet_CORE_AXIS_WIDTH_DIN(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_WIDTH_DIN(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_WIDTH_DIN_WORDS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_WIDTH_DIN_WORDS(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_WIDTH_DOUT(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_WIDTH_DOUT(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_WIDTH_DOUT_WORDS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_WIDTH_DOUT_WORDS(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_WIDTH(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_WIDTH(UINTPTR BaseAddress); /** * CORE_AXIS_ENABLE access functions */ void XSdFecSet_CORE_AXIS_ENABLE_CTRL(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_CTRL(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE_DIN(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_DIN(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE_DIN_WORDS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_DIN_WORDS(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE_STATUS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_STATUS(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE_DOUT(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_DOUT(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE_DOUT_WORDS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE_DOUT_WORDS(UINTPTR BaseAddress); void XSdFecSet_CORE_AXIS_ENABLE(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_AXIS_ENABLE(UINTPTR BaseAddress); /** * CORE_ORDER access functions */ void XSdFecSet_CORE_ORDER(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_ORDER(UINTPTR BaseAddress); /** * CORE_ISR access functions */ void XSdFecSet_CORE_ISR(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_ISR(UINTPTR BaseAddress); /** * CORE_IER access functions */ void XSdFecSet_CORE_IER(UINTPTR BaseAddress, u32 Data); /** * CORE_IDR access functions */ void XSdFecSet_CORE_IDR(UINTPTR BaseAddress, u32 Data); /** * CORE_IMR access functions */ u32 XSdFecGet_CORE_IMR(UINTPTR BaseAddress); /** * CORE_ECC_ISR access functions */ void XSdFecSet_CORE_ECC_ISR(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_ECC_ISR(UINTPTR BaseAddress); /** * CORE_ECC_IER access functions */ void XSdFecSet_CORE_ECC_IER(UINTPTR BaseAddress, u32 Data); /** * CORE_ECC_IDR access functions */ void XSdFecSet_CORE_ECC_IDR(UINTPTR BaseAddress, u32 Data); /** * CORE_ECC_IMR access functions */ u32 XSdFecGet_CORE_ECC_IMR(UINTPTR BaseAddress); /** * CORE_BYPASS access functions */ void XSdFecSet_CORE_BYPASS(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_CORE_BYPASS(UINTPTR BaseAddress); /** * CORE_VERSION access functions */ u32 XSdFecGet_CORE_VERSION(UINTPTR BaseAddress); /** * TURBO access functions */ void XSdFecSet_TURBO_ALG(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_TURBO_ALG(UINTPTR BaseAddress); void XSdFecSet_TURBO_SCALE_FACTOR(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_TURBO_SCALE_FACTOR(UINTPTR BaseAddress); void XSdFecSet_TURBO(UINTPTR BaseAddress, u32 Data); u32 XSdFecGet_TURBO(UINTPTR BaseAddress); /** * LDPC_CODE_REG0 access functions */ u32 XSdFecWrite_LDPC_CODE_REG0_N_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG0_N_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG0_K_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG0_K_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG0_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG0_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_CODE_REG1 access functions */ u32 XSdFecWrite_LDPC_CODE_REG1_PSIZE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG1_PSIZE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG1_NO_PACKING_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG1_NO_PACKING_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG1_NM_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG1_NM_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG1_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG1_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_CODE_REG2 access functions */ u32 XSdFecWrite_LDPC_CODE_REG2_NLAYERS_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_NLAYERS_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_NMQC_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_NMQC_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_NORM_TYPE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_NORM_TYPE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_SPECIAL_QC_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_SPECIAL_QC_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_NO_FINAL_PARITY_CHECK_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_NO_FINAL_PARITY_CHECK_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_MAX_SCHEDULE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_MAX_SCHEDULE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG2_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG2_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_CODE_REG3 access functions */ u32 XSdFecWrite_LDPC_CODE_REG3_SC_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG3_SC_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG3_LA_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG3_LA_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG3_QC_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG3_QC_OFF_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); u32 XSdFecWrite_LDPC_CODE_REG3_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_CODE_REG3_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_SC_TABLE access functions */ u32 XSdFecWrite_LDPC_SC_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_SC_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_LA_TABLE access functions */ u32 XSdFecWrite_LDPC_LA_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_LA_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData); /** * LDPC_QC_TABLE access functions */ u32 XSdFecWrite_LDPC_QC_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, const u32 *DataArrayPtr, u32 NumData); u32 XSdFecRead_LDPC_QC_TABLE_Words(UINTPTR BaseAddress, u32 WordOffset, u32 *DataArrayPtr, u32 NumData);
the_stack_data/2944.c
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #define STRINGS_MAX_NUM 100 int create_search_table(int fd, off_t *indents, off_t *strings_length, off_t *string_max_length); int main(int argc, char *argv[]) { if(argc != 2) { fprintf(stderr, "should be only one argument!\n"); return -1; } int file = open(argv[1], O_RDONLY); if(file == -1) { perror("open"); return -1; } off_t indents[STRINGS_MAX_NUM]; off_t strings_length[STRINGS_MAX_NUM]; off_t string_max_length; int strings_num; if((strings_num = create_search_table(file, indents, strings_length, &string_max_length)) == -1) { exit(-1); } int num, len; char *string = (char*)malloc(sizeof(char) * string_max_length); while (1) { printf("Input string number: "); if(scanf("%d", &num) != 1 || num == 0) { break; } if(num > strings_num || num < 0) { fprintf(stderr, "Unexpected string number!\n"); continue; } if(lseek(file, indents[num - 1] - strings_length[num - 1], SEEK_SET) == -1) { perror("lseek"); break; } len = read(file, string, strings_length[num - 1]); if(len <= 0 || write(STDOUT_FILENO, string, sizeof(char) * len) <= 0) { break; } } free(string); exit(0); } int create_search_table(int fd, off_t *indents, off_t *strings_length, off_t *string_max_length) { char symbol; off_t string_length = 0, file_length = 0; int i = 0; *string_max_length = 0; while (read(fd, &symbol, sizeof(char)) && i < STRINGS_MAX_NUM) { file_length++; string_length++; if(symbol == '\n') { indents[i] = file_length; strings_length[i] = string_length; if(string_length > *string_max_length) { *string_max_length = string_length; } string_length = 0; i++; } } if(i < STRINGS_MAX_NUM) { indents[i] = file_length; strings_length[i] = string_length; if (string_length > *string_max_length) { *string_max_length = string_length; } } if(lseek(fd, 0, SEEK_SET) == -1) { perror("lseek"); return -1; } return i; }
the_stack_data/89201484.c
/* * Copyright (c) 1983, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.redist.c% */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)getservent.c 8.1 (Berkeley) 06/04/93"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXALIASES 35 static FILE *servf = NULL; static char line[BUFSIZ+1]; static struct servent serv; static char *serv_aliases[MAXALIASES]; int _serv_stayopen; void setservent(f) int f; { if (servf == NULL) servf = fopen(_PATH_SERVICES, "r" ); else rewind(servf); _serv_stayopen |= f; } void endservent() { if (servf) { fclose(servf); servf = NULL; } _serv_stayopen = 0; } struct servent * getservent() { char *p; register char *cp, **q; if (servf == NULL && (servf = fopen(_PATH_SERVICES, "r" )) == NULL) return (NULL); again: if ((p = fgets(line, BUFSIZ, servf)) == NULL) return (NULL); if (*p == '#') goto again; cp = strpbrk(p, "#\n"); if (cp == NULL) goto again; *cp = '\0'; serv.s_name = p; p = strpbrk(p, " \t"); if (p == NULL) goto again; *p++ = '\0'; while (*p == ' ' || *p == '\t') p++; cp = strpbrk(p, ",/"); if (cp == NULL) goto again; *cp++ = '\0'; serv.s_port = htons((u_short)atoi(p)); serv.s_proto = cp; q = serv.s_aliases = serv_aliases; cp = strpbrk(cp, " \t"); if (cp != NULL) *cp++ = '\0'; while (cp && *cp) { if (*cp == ' ' || *cp == '\t') { cp++; continue; } if (q < &serv_aliases[MAXALIASES - 1]) *q++ = cp; cp = strpbrk(cp, " \t"); if (cp != NULL) *cp++ = '\0'; } *q = NULL; return (&serv); }
the_stack_data/92326516.c
/*********************************************************** distsort.c -- 分布数えソート ***********************************************************/ #define MAX 100 #define MIN 0 void distsort(int n, const int a[], int b[]) { int i, x; static int count[MAX - MIN + 1]; for (i = 0; i <= MAX - MIN; i++) count[i] = 0; for (i = 0; i < n; i++) count[a[i] - MIN]++; for (i = 1; i <= MAX - MIN; i++) count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { x = a[i] - MIN; b[--count[x]] = a[i]; } } #include <stdio.h> #include <stdlib.h> #define N 20 int main(void) { int i; static int a[N], b[N]; printf("Before:"); for (i = 0; i < N; i++) { a[i] = (MAX - MIN + 1.0) / (RAND_MAX + 1.0) * rand() + MIN; printf(" %d", a[i]); } printf("\n"); distsort(N, a, b); printf("After: "); for (i = 0; i < N; i++) printf(" %d", b[i]); printf("\n"); return 0; }
the_stack_data/51700248.c
#include <stdio.h> #include <string.h> struct s_type { char str[80]; } var; void f(struct s_type i); int main(void) { strcpy(var.str, "this is original string"); f(var); printf("%s", var.str); } void f(struct s_type i) { strcpy(i.str, "new string"); printf("%s\n", i.str); }
the_stack_data/232955112.c
/** ****************************************************************************** * @file stm32f1xx_ll_tim.c * @author MCD Application Team * @brief TIM LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_ll_tim.h" #include "stm32f1xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /* USE_FULL_ASSERT */ /** @addtogroup STM32F1xx_LL_Driver * @{ */ #if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM8) || defined (TIM9) || defined (TIM10) || defined (TIM11) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) /** @addtogroup TIM_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup TIM_LL_Private_Macros * @{ */ #define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN)) #define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \ || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \ || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4)) #define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \ || ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \ || ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_PWM1) \ || ((__VALUE__) == LL_TIM_OCMODE_PWM2)) #define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) #define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \ || ((__VALUE__) == LL_TIM_OCPOLARITY_LOW)) #define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \ || ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH)) #define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \ || ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \ || ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC)) #define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV2) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV4) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV8)) #define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8)) #define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) #define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \ || ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \ || ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12)) #define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) #define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \ || ((__VALUE__) == LL_TIM_OSSR_ENABLE)) #define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \ || ((__VALUE__) == LL_TIM_OSSI_ENABLE)) #define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_3)) #define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \ || ((__VALUE__) == LL_TIM_BREAK_ENABLE)) #define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \ || ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH)) #define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \ || ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /** @defgroup TIM_LL_Private_Functions TIM Private Functions * @{ */ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_LL_Exported_Functions * @{ */ /** @addtogroup TIM_LL_EF_Init * @{ */ /** * @brief Set TIMx registers to their reset values. * @param TIMx Timer instance * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: invalid TIMx instance */ ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx) { ErrorStatus result = SUCCESS; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(TIMx)); if (TIMx == TIM2) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2); } #if defined(TIM1) else if (TIMx == TIM1) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1); } #endif #if defined(TIM3) else if (TIMx == TIM3) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3); } #endif #if defined(TIM4) else if (TIMx == TIM4) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4); } #endif #if defined(TIM5) else if (TIMx == TIM5) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5); } #endif #if defined(TIM6) else if (TIMx == TIM6) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6); } #endif #if defined (TIM7) else if (TIMx == TIM7) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7); } #endif #if defined(TIM8) else if (TIMx == TIM8) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM8); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM8); } #endif #if defined(TIM9) else if (TIMx == TIM9) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM9); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM9); } #endif #if defined(TIM10) else if (TIMx == TIM10) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM10); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM10); } #endif #if defined(TIM11) else if (TIMx == TIM11) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM11); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM11); } #endif #if defined(TIM12) else if (TIMx == TIM12) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM12); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM12); } #endif #if defined(TIM13) else if (TIMx == TIM13) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM13); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM13); } #endif #if defined(TIM14) else if (TIMx == TIM14) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM14); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM14); } #endif #if defined(TIM15) else if (TIMx == TIM15) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15); } #endif #if defined(TIM16) else if (TIMx == TIM16) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16); } #endif #if defined(TIM17) else if (TIMx == TIM17) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17); } #endif else { result = ERROR; } return result; } /** * @brief Set the fields of the time base unit configuration data structure * to their default values. * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure) * @retval None */ void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct) { /* Set the default configuration */ TIM_InitStruct->Prescaler = (uint16_t)0x0000; TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP; TIM_InitStruct->Autoreload = 0xFFFFFFFFU; TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; TIM_InitStruct->RepetitionCounter = (uint8_t)0x00; } /** * @brief Configure the TIMx time base unit. * @param TIMx Timer Instance * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (TIMx time base unit configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct) { uint32_t tmpcr1; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(TIMx)); assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode)); assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision)); tmpcr1 = LL_TIM_ReadReg(TIMx, CR1); if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) { /* Select the Counter Mode */ MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode); } if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) { /* Set the clock division */ MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision); } /* Write to TIMx CR1 */ LL_TIM_WriteReg(TIMx, CR1, tmpcr1); /* Set the Autoreload value */ LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload); /* Set the Prescaler value */ LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler); if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) { /* Set the Repetition Counter value */ LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter); } /* Generate an update event to reload the Prescaler and the repetition counter value (if applicable) immediately */ LL_TIM_GenerateEvent_UPDATE(TIMx); return SUCCESS; } /** * @brief Set the fields of the TIMx output channel configuration data * structure to their default values. * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (the output channel configuration data structure) * @retval None */ void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) { /* Set the default configuration */ TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN; TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct->CompareValue = 0x00000000U; TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH; TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH; TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW; TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW; } /** * @brief Configure the TIMx output channel. * @param TIMx Timer Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_TIM_CHANNEL_CH1 * @arg @ref LL_TIM_CHANNEL_CH2 * @arg @ref LL_TIM_CHANNEL_CH3 * @arg @ref LL_TIM_CHANNEL_CH4 * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx output channel is initialized * - ERROR: TIMx output channel is not initialized */ ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) { ErrorStatus result = ERROR; switch (Channel) { case LL_TIM_CHANNEL_CH1: result = OC1Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH2: result = OC2Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH3: result = OC3Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH4: result = OC4Config(TIMx, TIM_OC_InitStruct); break; default: break; } return result; } /** * @brief Set the fields of the TIMx input channel configuration data * structure to their default values. * @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration data structure) * @retval None */ void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Set the default configuration */ TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING; TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1; TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1; } /** * @brief Configure the TIMx input channel. * @param TIMx Timer Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_TIM_CHANNEL_CH1 * @arg @ref LL_TIM_CHANNEL_CH2 * @arg @ref LL_TIM_CHANNEL_CH3 * @arg @ref LL_TIM_CHANNEL_CH4 * @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx output channel is initialized * - ERROR: TIMx output channel is not initialized */ ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct) { ErrorStatus result = ERROR; switch (Channel) { case LL_TIM_CHANNEL_CH1: result = IC1Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH2: result = IC2Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH3: result = IC3Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH4: result = IC4Config(TIMx, TIM_IC_InitStruct); break; default: break; } return result; } /** * @brief Fills each TIM_EncoderInitStruct field with its default value * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface configuration data structure) * @retval None */ void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) { /* Set the default configuration */ TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1; TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING; TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1; TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1; } /** * @brief Configure the encoder interface of the timer instance. * @param TIMx Timer Instance * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) { uint32_t tmpccmr1; uint32_t tmpccer; /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx)); assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter)); /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Configure TI1 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U); /* Configure TI2 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U); /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity); tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U); tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Set encoder mode */ LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Set the fields of the TIMx Hall sensor interface configuration data * structure to their default values. * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface configuration data structure) * @retval None */ void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) { /* Set the default configuration */ TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; TIM_HallSensorInitStruct->CommutationDelay = 0U; } /** * @brief Configure the Hall sensor interface of the timer instance. * @note TIMx CH1, CH2 and CH3 inputs connected through a XOR * to the TI1 input channel * @note TIMx slave mode controller is configured in reset mode. Selected internal trigger is TI1F_ED. * @note Channel 1 is configured as input, IC1 is mapped on TRC. * @note Captured value stored in TIMx_CCR1 correspond to the time elapsed * between 2 changes on the inputs. It gives information about motor speed. * @note Channel 2 is configured in output PWM 2 mode. * @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay. * @note OC2REF is selected as trigger output on TRGO. * @param TIMx Timer Instance * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor interface configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) { uint32_t tmpcr2; uint32_t tmpccmr1; uint32_t tmpccer; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity)); assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter)); /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx SMCR register value */ tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR); /* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */ tmpcr2 |= TIM_CR2_TI1S; /* OC2REF signal is used as trigger output (TRGO) */ tmpcr2 |= LL_TIM_TRGO_OC2REF; /* Configure the slave mode controller */ tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS); tmpsmcr |= LL_TIM_TS_TI1F_ED; tmpsmcr |= LL_TIM_SLAVEMODE_RESET; /* Configure input channel 1 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U); tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U); tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U); /* Configure input channel 2 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE); tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U); /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity); tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx SMCR */ LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); /* Write to TIMx CCR2 */ LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay); return SUCCESS; } /** * @brief Set the fields of the Break and Dead Time configuration data structure * to their default values. * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure) * @retval None */ void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) { /* Set the default configuration */ TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE; TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE; TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF; TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00; TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE; TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW; TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE; } /** * @brief Configure the Break and Dead Time feature of the timer instance. * @note As the bits AOE, BKP, BKE, OSSR, OSSI and DTG[7:0] can be write-locked * depending on the LOCK configuration, it can be necessary to configure all of * them during the first write access to the TIMx_BDTR register. * @note Macro IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not * a timer instance provides a break input. * @param TIMx Timer Instance * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: Break and Dead Time is initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) { uint32_t tmpbdtr = 0; /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState)); assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState)); assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel)); assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, the OSSI State, the dead time value and the Automatic Output Enable Bit */ /* Set the BDTR bits */ MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime); MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); MODIFY_REG(tmpbdtr, TIM_BDTR_MOE, TIM_BDTRInitStruct->AutomaticOutput); /* Set TIMx_BDTR */ LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr); return SUCCESS; } /** * @} */ /** * @} */ /** @addtogroup TIM_LL_Private_Functions TIM Private Functions * @brief Private functions * @{ */ /** * @brief Configure the TIMx output channel 1. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr1; uint32_t tmpccer; uint32_t tmpcr2; /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 1: Reset the CC1E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S); /* Set the Output Compare Mode */ MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 2. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr1; uint32_t tmpccer; uint32_t tmpcr2; /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 2: Reset the CC2E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 3. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr2; uint32_t tmpccer; uint32_t tmpcr2; /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 3: Reset the CC3E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR2 register value */ tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR2 */ LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 4. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr2; uint32_t tmpccer; uint32_t tmpcr2; /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); /* Disable the Channel 4: Reset the CC4E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR2 register value */ tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR2 */ LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx input channel 1. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR1, (TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); /* Select the Polarity and set the CC1E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P | TIM_CCER_CC1NP), (TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 2. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR1, (TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); /* Select the Polarity and set the CC2E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC2P | TIM_CCER_CC2NP), ((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 3. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 3: Reset the CC3E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR2, (TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); /* Select the Polarity and set the CC3E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC3P | TIM_CCER_CC3NP), ((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 4. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR2, (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); /* Select the Polarity and set the CC4E Bit */ MODIFY_REG(TIMx->CCER, TIM_CCER_CC4P, ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); return SUCCESS; } /** * @} */ /** * @} */ #endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM8 || TIM9 || TIM10 || TIM11 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/64199309.c
float ycbcrCoeffs[3] = { .299, .587, .114 }; /* default coding range is CCIR Rec 601-1 with no headroom/footroom */ unsigned long refBlackWhite[6] = { 0, 255, 128, 255, 128, 255 }; #define LumaRed ycbcrCoeffs[0] #define LumaGreen ycbcrCoeffs[1] #define LumaBlue ycbcrCoeffs[2] long eRtotal = 0; long eGtotal = 0; long eBtotal = 0; long preveRtotal = 0; long preveGtotal = 0; long preveBtotal = 0; unsigned long AbseRtotal = 0; unsigned long AbseGtotal = 0; unsigned long AbseBtotal = 0; unsigned long eCodes = 0; unsigned long preveCodes = 0; unsigned long eBits = 0; unsigned long preveBits = 0; static void setupLumaTables(); static int abs(int v) { return (v < 0 ? -v : v); } static double pct(int v,double range) { return (v*100. / range); } static void check(int R, int G, int B); float D1, D2; float D3, D4; float D5, D6; int main(int argc, char* argv) { int R, G, B; if (argc > 1) { refBlackWhite[0] = 16; refBlackWhite[1] = 235; refBlackWhite[2] = 128; refBlackWhite[3] = 240; refBlackWhite[4] = 128; refBlackWhite[5] = 240; } D3 = 2 - 2*LumaRed; D4 = 2 - 2*LumaBlue; D1 = 1. / D3; D2 = 1. / D4; D5 = D3*LumaRed / LumaGreen; D6 = D4*LumaBlue / LumaGreen; setupLumaTables(); for (R = 0; R < 256; R++) { for (G = 0; G < 256; G++) for (B = 0; B < 256; B++) check(R, G, B); printf("[%3u] c %u/%u b %u/%u (R %u/%d/%u G %u/%d/%u B %u/%d/%u)\n" , R , eCodes - preveCodes, eCodes , eBits - preveBits, eBits , abs(AbseRtotal - preveRtotal), eRtotal , AbseRtotal , abs(AbseGtotal - preveGtotal), eGtotal , AbseGtotal , abs(AbseBtotal - preveBtotal), eBtotal , AbseBtotal ); preveRtotal = AbseRtotal; preveGtotal = AbseGtotal; preveBtotal = AbseBtotal; preveCodes = eCodes; preveBits = eBits; } printf("%u total codes\n", 256*256*256); printf("total error: %u codes %u bits (R %d/%u G %d/%u B %d/%u)\n" , eCodes , eBits , eRtotal , AbseRtotal , eGtotal , AbseGtotal , eBtotal , AbseBtotal ); return (0); } float *lumaRed; float *lumaGreen; float *lumaBlue; static float* setupLuma(float c) { float *v = (float *)_TIFFmalloc(256 * sizeof (float)); int i; for (i = 0; i < 256; i++) v[i] = c * i; return (v); } static void setupLumaTables(void) { lumaRed = setupLuma(LumaRed); lumaGreen = setupLuma(LumaGreen); lumaBlue = setupLuma(LumaBlue); } static unsigned V2Code(float f, unsigned long RB, unsigned long RW, int CR) { unsigned int c = (unsigned int)((((f)*(RW-RB)/CR)+RB)+.5); return (c > 255 ? 255 : c); } #define Code2V(c, RB, RW, CR) ((((c)-(int)RB)*(float)CR)/(float)(RW-RB)) #define CLAMP(f,min,max) \ (int)((f)+.5 < (min) ? (min) : (f)+.5 > (max) ? (max) : (f)+.5) static void check(int R, int G, int B) { float Y, Cb, Cr; int iY, iCb, iCr; float rY, rCb, rCr; float rR, rG, rB; int eR, eG, eB; Y = lumaRed[R] + lumaGreen[G] + lumaBlue[B]; Cb = (B - Y)*D2; Cr = (R - Y)*D1; iY = V2Code(Y, refBlackWhite[0], refBlackWhite[1], 255); iCb = V2Code(Cb, refBlackWhite[2], refBlackWhite[3], 127); iCr = V2Code(Cr, refBlackWhite[4], refBlackWhite[5], 127); rCb = Code2V(iCb, refBlackWhite[2], refBlackWhite[3], 127); rCr = Code2V(iCr, refBlackWhite[4], refBlackWhite[5], 127); rY = Code2V(iY, refBlackWhite[0], refBlackWhite[1], 255); rR = rY + rCr*D3; rB = rY + rCb*D4; rG = rY - rCb*D6 - rCr*D5; eR = R - CLAMP(rR,0,255); eG = G - CLAMP(rG,0,255); eB = B - CLAMP(rB,0,255); if (abs(eR) > 1 || abs(eG) > 1 || abs(eB) > 1) { printf("R %u G %u B %u", R, G, B); printf(" Y %g Cb %g Cr %g", Y, Cb, Cr); printf(" iY %u iCb %u iCr %u", iY, iCb, iCr); printf("\n -> Y %g Cb %g Cr %g", rY, rCb, rCr); printf(" R %g (%u) G %g (%u) B %g (%u) E=[%d %d %d])\n" , rR, CLAMP(rR,0,255) , rG, CLAMP(rG,0,255) , rB, CLAMP(rB,0,255) , eR, eG, eB ); } eRtotal += eR; eGtotal += eG; eBtotal += eB; AbseRtotal += abs(eR); AbseGtotal += abs(eG); AbseBtotal += abs(eB); if (eR | eG | eB) eCodes++; eBits += abs(eR) + abs(eG) + abs(eB); }
the_stack_data/73575454.c
#include <stdio.h> /** * Matrix A, row * column, element (i,j) */ void print(const int *matrix, const int row, const int col) { int i,j; int offset; for (i = 0; i < row; i++) { offset = i * col; for (j = 0; j < col; j++) { printf("%d ", matrix[offset+j]); } printf("\n"); } } /** * Matrix A, row * column, element (i,j) * A(i,j)m*s B(i,j)s*n * C = A*B = C(i,j)m*n c(i,j) = sum(a(i,k)*b(k,j)) * * m1,m2 is input matrix, m1 is x*y, m2 is y*z * r is the result matrx, is x*z * * refer: https://zhuanlan.zhihu.com/p/108085571 */ void matrix_multiply (int *m1, int *m2, int *r, int x, int y, int z ) { int *m1p; int *m2p; int offsetR=0; int k; int row; int column; for ( row = 0; row < x; row ++ ) { for ( column = 0; column < z; column ++ ) { m1p = m1 + row * y; m2p = m2 + column; r[offsetR] = 0; for ( k = 0; k < y; k ++) { r[offsetR] += *m1p * *m2p; m1p += 1; m2p += z; } offsetR++; // printf("---- M1*M2: %d, %d %d \n", row, column, offsetR); // print(r, x,z); } } printf("M1: \n"); print(m1,x,y); printf("M2: \n"); print(m2,y, z); printf("M1*M2: \n"); print(r, x,z); } int main ( int argc, char const *argv[]) { // int x = 3, y = 2, z = 4; // int m1[4] = {3,4,5,6}; // int m2[4] = {5,4,3,2}; // int x = 2, y = 2, z = 2; // int r[4]; // int m1[3*2] = {2, -6, 3, 5, 1, -1}; // int m2[2*4] = {4, -2, -4, -5, -7, -3, 6, 7}; // int r[3*4] = {0}; // int x = 3, y = 2, z = 3; // int m1[6] = {2,3,4,5,3,5}; // int m2[6] = { 1,2,3,4,5,6 }; // int r[9]={0}; int m1[4] = {3,4,5,6}; int m2[4] = {5,4,3,2}; int r[4] = {0}; int x = 2, y = 2, z = 2; matrix_multiply (m1,m2,r,x,y,z); return 0; }
the_stack_data/83887.c
/* "$Id: create_table.c,v 1.1 2011/12/10 04:55:22 rbsheth Exp $" * * Author: Jean-Marc Lienher ( http://oksid.ch ) * Copyright 2000-2003 by O'ksi'D. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * Please report all bugs and problems on the following page: * * http://www.fltk.org/str.php */ #include <wchar.h> #include <stdio.h> char buffer[1000000]; /*** you can try to modifie this value to have better performences **/ #define MAX_DELTA 0x80 int main(int argc, char **argv) { char buf[80]; int len; unsigned int i = 0; unsigned char *ptr; size_t nb; int nbb = 0; len = fread(buffer, 1, 1000000, stdin); buffer[len] = '\0'; ptr = (unsigned char *)buffer; while (*ptr != '\n') ptr++; ptr++; while (*ptr != '\n') { if (*ptr == ',') nbb++; ptr++; } ptr = (unsigned char *)buffer; printf("/* %s */\n", argv[1]); while (len > 0) { unsigned int ucs = 0; char *p = ptr; char pp[20]; nb = 0; pp[0] = '\0'; while (*p != 'U') p++; strncat(pp, p, 6); *pp = '0'; *(pp+1) = 'x'; ucs = (unsigned int)strtoul(pp, NULL, 16);; if (ucs < 1) { printf("ERROR %d %d\n", len, ucs); abort(); } if (i != ucs - 1 || !i) { if ((ucs - i) > MAX_DELTA || !i) { if (i) { printf("};\n"); fprintf(stderr, "\t/* end: U+%04X */\n", i); } if (strcmp(argv[1], "spacing")) { printf("\nstatic const char unicode_to_%s_%db_%04X[] = {\n", argv[1], nbb, ucs); fprintf(stderr, "unicode_to_%s_%db_%04X[]; ", argv[1], nbb, ucs); } else { printf("\nstatic const unsigned short" " ucs_table_%04X[]" " = {\n", ucs); fprintf(stderr, "ucs_table_%04X[]; ", ucs); } } else { while (i < ucs - 1) { i++; if (nbb == 1) { printf("0x00,\n"); } else { printf("0x00, 0x00,\n"); } }; } } i = ucs; while (*ptr != '\n') { printf("%c", *ptr); ptr++; len--; } printf("\n"); ptr++; len--; } printf("};\n"); fprintf(stderr, "\t/* end: U+%04X */\n", i); return 0; } /* * End of "$Id: create_table.c,v 1.1 2011/12/10 04:55:22 rbsheth Exp $". */
the_stack_data/162642574.c
// Arup Guha // 3/7/2017 // Written in COP 3502 class - Linked List implementation of a stack. #include <stdio.h> #include <stdlib.h> // A linked list node. typedef struct node { int data; struct node* next; } node; // A struct for the stack. typedef struct stack { struct node* top; int size; } stack; void init(stack* myStack); int push(stack* myStack, int item); node* pop(stack* myStack); int top(stack* myStack); int size(stack* myStack); int main() { // Test to fail... stack myStack; init(&myStack); int i = 0; // Push lots of stuff until the push fails. while (1) { int tmp = push(&myStack, i); if (tmp == 0) break; i++; } // See how much memory we had! printf("We failed after %d pushes.\n", i); // Pop everything off. while (size(&myStack) > 0) { node* ret = pop(&myStack); free(ret); } // Smaller test cases. // Get 10 things onto the stack. for (i=0; i<10; i++) push(&myStack, i); // Pop 5 of them. for (i=0; i<5; i++) { node* ret = pop(&myStack); printf("Just popped %d\n", ret->data); free(ret); printf("Top of the stack is now %d\n", top(&myStack)); } // Get rid of everything else. while (size(&myStack) > 0) { printf("There are %d items in the stack.\n", size(&myStack)); node* ret = pop(&myStack); printf("Just popped %d\n", ret->data); free(ret); } return 0; } // Initializes the stack pointed to by myStack to be empty. void init(stack* myStack) { myStack->top = NULL; myStack->size = 0; } // Pushes item onto the stack pointed to by myStack. Returns 1 if the push // succeeded, 0 if it failed. int push(stack* myStack, int item) { node* tmp = malloc(sizeof(node)); // malloc failed. if (tmp == NULL) { return 0; } // Create node link to old front. tmp->data = item; tmp->next = myStack->top; // Reset front and size. myStack->top = tmp; myStack->size++; return 1; } // Pops the top node off the stack pointed to by myStack and returns a pointer // to the node. node* pop(stack* myStack) { // Take care of empty case. if (myStack->size == 0) return NULL; // Store return node. node* retval = myStack->top; // Update new top. myStack->top = myStack->top->next; // To be safe, NULL this out. retval->next = NULL; // Update this. myStack->size--; return retval; } // Returns the integer at the top of the stack pointed to by myStack without // popping it. Returns -1 if the stack is empty. int top(stack* myStack) { if (myStack->size == 0) return -1; return myStack->top->data; } // Returns the size of the stack. int size(stack* myStack) { return myStack->size; }
the_stack_data/103232.c
#include <stdio.h> #include <stdlib.h> int pathfind_aux(int* cache, int* tab, int len, int pos) { if (pos >= len - 1) return 0; else if (cache[pos] != -1) return cache[pos]; else { cache[pos] = len * 2; int posval = pathfind_aux(cache, tab, len, tab[pos]); int oneval = pathfind_aux(cache, tab, len, pos + 1); int out0 = 0; if (posval < oneval) out0 = 1 + posval; else out0 = 1 + oneval; cache[pos] = out0; return out0; } } int pathfind(int* tab, int len) { int i; int *cache = calloc(len, sizeof(int)); for (i = 0; i < len; i++) cache[i] = -1; return pathfind_aux(cache, tab, len, 0); } int main(void) { int i; int len = 0; scanf("%d ", &len); int *tab = calloc(len, sizeof(int)); for (i = 0; i < len; i++) { int tmp = 0; scanf("%d ", &tmp); tab[i] = tmp; } int result = pathfind(tab, len); printf("%d", result); return 0; }
the_stack_data/37639014.c
#include <stdio.h> #include <stdlib.h> int add(int x,int y) { return x+y; } int main(int argc, char **argv) { int x = 0x100; int y = 0x200; int z = add(x,y); printf("%d\n",z); return 0; } //gcc -O0 -o test1 add.c //gcc 的开关 把优化都关掉 //gcc -O2 -o test2 add.c // O1 O2 O3 各种优化级别
the_stack_data/124574.c
/* dummy file compiled to extract head path information from clang */ int main() { return 0; }
the_stack_data/583696.c
/** ****************************************************************************** * @file stm32f4xx_ll_rtc.c * @author MCD Application Team * @brief RTC LL module driver. ****************************************************************************** * @attention * * Copyright (c) 2017 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_rtc.h" #include "stm32f4xx_ll_cortex.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F4xx_LL_Driver * @{ */ #if defined(RTC) /** @addtogroup RTC_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Constants * @{ */ /* Default values used for prescaler */ #define RTC_ASYNCH_PRESC_DEFAULT 0x0000007FU #define RTC_SYNCH_PRESC_DEFAULT 0x000000FFU /* Values used for timeout */ #define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */ #define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Macros * @{ */ #define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \ || ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM)) #define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU) #define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU) #define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ || ((__VALUE__) == LL_RTC_FORMAT_BCD)) #define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \ || ((__VALUE__) == LL_RTC_TIME_FORMAT_PM)) #define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U)) #define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) #define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) #define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) #define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY)) #define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= 1U) && ((__DAY__) <= 31U)) #define IS_LL_RTC_MONTH(__MONTH__) (((__MONTH__) >= 1U) && ((__MONTH__) <= 12U)) #define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U) #define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_ALL)) #define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_ALL)) #define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \ ((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY)) #define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \ ((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_LL_Exported_Functions * @{ */ /** @addtogroup RTC_LL_EF_Init * @{ */ /** * @brief De-Initializes the RTC registers to their default reset values. * @note This function does not reset the RTC Clock source and RTC Backup Data * registers. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are de-initialized * - ERROR: RTC registers are not de-initialized */ ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) { ErrorStatus status = ERROR; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Reset TR, DR and CR registers */ LL_RTC_WriteReg(RTCx, TR, 0x00000000U); LL_RTC_WriteReg(RTCx, WUTR, RTC_WUTR_WUT); LL_RTC_WriteReg(RTCx, DR, (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); /* Reset All CR bits except CR[2:0] */ LL_RTC_WriteReg(RTCx, CR, (LL_RTC_ReadReg(RTCx, CR) & RTC_CR_WUCKSEL)); LL_RTC_WriteReg(RTCx, PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT)); LL_RTC_WriteReg(RTCx, ALRMAR, 0x00000000U); LL_RTC_WriteReg(RTCx, ALRMBR, 0x00000000U); LL_RTC_WriteReg(RTCx, CALR, 0x00000000U); LL_RTC_WriteReg(RTCx, SHIFTR, 0x00000000U); LL_RTC_WriteReg(RTCx, ALRMASSR, 0x00000000U); LL_RTC_WriteReg(RTCx, ALRMBSSR, 0x00000000U); /* Reset ISR register and exit initialization mode */ LL_RTC_WriteReg(RTCx, ISR, 0x00000000U); /* Reset Tamper and alternate functions configuration register */ LL_RTC_WriteReg(RTCx, TAFCR, 0x00000000U); /* Wait till the RTC RSF flag is set */ status = LL_RTC_WaitForSynchro(RTCx); } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Initializes the RTC registers according to the specified parameters * in RTC_InitStruct. * @param RTCx RTC Instance * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains * the configuration information for the RTC peripheral. * @note The RTC Prescaler register is write protected and can be written in * initialization mode only. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are initialized * - ERROR: RTC registers are not initialized */ ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat)); assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Set Hour Format */ LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat); /* Configure Synchronous and Asynchronous prescaler factor */ LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler); LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTCx); status = SUCCESS; } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_InitTypeDef field to default value. * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. * @retval None */ void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) { /* Set RTC_InitStruct fields to default values */ RTC_InitStruct->HourFormat = LL_RTC_HOURFORMAT_24HOUR; RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT; } /** * @brief Set the RTC current time. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains * the time configuration information for the RTC. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Time register is configured * - ERROR: RTC Time register is not configured */ ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); } else { RTC_TimeStruct->TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); } else { RTC_TimeStruct->TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours, RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds); } else { LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds)); } /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTCx); /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) { status = LL_RTC_WaitForSynchro(RTCx); } else { status = SUCCESS; } } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. * @retval None */ void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) { /* Time = 00h:00min:00sec */ RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24; RTC_TimeStruct->Hours = 0U; RTC_TimeStruct->Minutes = 0U; RTC_TimeStruct->Seconds = 0U; } /** * @brief Set the RTC current date. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_DateStruct pointer to a RTC_DateTypeDef structure that contains * the date configuration information for the RTC. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Day register is configured * - ERROR: RTC Day register is not configured */ ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U)) { RTC_DateStruct->Month = (uint8_t)(RTC_DateStruct->Month & (uint8_t)~(0x10U)) + 0x0AU; } if (RTC_Format == LL_RTC_FORMAT_BIN) { assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year)); assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month)); assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day)); } else { assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year))); assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month))); assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day))); } assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year); } else { LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); } /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTCx); /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) { status = LL_RTC_WaitForSynchro(RTCx); } else { status = SUCCESS; } } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00) * @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized. * @retval None */ void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct) { /* Monday, January 01 xx00 */ RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY; RTC_DateStruct->Day = 1U; RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY; RTC_DateStruct->Year = 0U; } /** * @brief Set the RTC Alarm A. * @note The Alarm register can only be written when the corresponding Alarm * is disabled (Use @ref LL_RTC_ALMA_Disable function). * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that * contains the alarm configuration parameters. * @retval An ErrorStatus enumeration value: * - SUCCESS: ALARMA registers are configured * - ERROR: ALARMA registers are not configured */ ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask)); assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); } else { assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } else { assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Select weekday selection */ if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { /* Set the date for ALARM */ LL_RTC_ALMA_DisableWeekday(RTCx); if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } else { LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { /* Set the week day for ALARM */ LL_RTC_ALMA_EnableWeekday(RTCx); LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } /* Configure the Alarm register */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); } else { LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); } /* Set ALARM mask */ LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return SUCCESS; } /** * @brief Set the RTC Alarm B. * @note The Alarm register can only be written when the corresponding Alarm * is disabled (@ref LL_RTC_ALMB_Disable function). * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that * contains the alarm configuration parameters. * @retval An ErrorStatus enumeration value: * - SUCCESS: ALARMB registers are configured * - ERROR: ALARMB registers are not configured */ ErrorStatus LL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); assert_param(IS_LL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask)); assert_param(IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); } else { assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } else { assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Select weekday selection */ if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { /* Set the date for ALARM */ LL_RTC_ALMB_DisableWeekday(RTCx); if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } else { LL_RTC_ALMB_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { /* Set the week day for ALARM */ LL_RTC_ALMB_EnableWeekday(RTCx); LL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } /* Configure the Alarm register */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); } else { LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); } /* Set ALARM mask */ LL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return SUCCESS; } /** * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / * Day = 1st day of the month/Mask = all fields are masked). * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. * @retval None */ void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Alarm Time Settings : Time = 00h:00mn:00sec */ RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM; RTC_AlarmStruct->AlarmTime.Hours = 0U; RTC_AlarmStruct->AlarmTime.Minutes = 0U; RTC_AlarmStruct->AlarmTime.Seconds = 0U; /* Alarm Day Settings : Day = 1st day of the month */ RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE; RTC_AlarmStruct->AlarmDateWeekDay = 1U; /* Alarm Masks Settings : Mask = all fields are not masked */ RTC_AlarmStruct->AlarmMask = LL_RTC_ALMA_MASK_NONE; } /** * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / * Day = 1st day of the month/Mask = all fields are masked). * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. * @retval None */ void LL_RTC_ALMB_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Alarm Time Settings : Time = 00h:00mn:00sec */ RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMB_TIME_FORMAT_AM; RTC_AlarmStruct->AlarmTime.Hours = 0U; RTC_AlarmStruct->AlarmTime.Minutes = 0U; RTC_AlarmStruct->AlarmTime.Seconds = 0U; /* Alarm Day Settings : Day = 1st day of the month */ RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMB_DATEWEEKDAYSEL_DATE; RTC_AlarmStruct->AlarmDateWeekDay = 1U; /* Alarm Masks Settings : Mask = all fields are not masked */ RTC_AlarmStruct->AlarmMask = LL_RTC_ALMB_MASK_NONE; } /** * @brief Enters the RTC Initialization mode. * @note The RTC Initialization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC is in Init mode * - ERROR: RTC is not in Init mode */ ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Check if the Initialization mode is set */ if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U) { /* Set the Initialization mode */ LL_RTC_EnableInitMode(RTCx); /* Wait till RTC is in INIT state and if Time out is reached exit */ tmp = LL_RTC_IsActiveFlag_INIT(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout --; } tmp = LL_RTC_IsActiveFlag_INIT(RTCx); if (timeout == 0U) { status = ERROR; } } } return status; } /** * @brief Exit the RTC Initialization mode. * @note When the initialization sequence is complete, the calendar restarts * counting after 4 RTCCLK cycles. * @note The RTC Initialization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC exited from in Init mode * - ERROR: Not applicable */ ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) { /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable initialization mode */ LL_RTC_DisableInitMode(RTCx); return SUCCESS; } /** * @brief Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are * synchronized with RTC APB clock. * @note The RTC Resynchronization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @note To read the calendar through the shadow registers after calendar * initialization, calendar update or after wakeup from low power modes * the software must first clear the RSF flag. * The software must then wait until it is set again before reading * the calendar, which means that the calendar registers have been * correctly copied into the RTC_TR and RTC_DR shadow registers. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are synchronised * - ERROR: RTC registers are not synchronised */ ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Clear RSF flag */ LL_RTC_ClearFlag_RS(RTCx); /* Wait the registers to be synchronised */ tmp = LL_RTC_IsActiveFlag_RS(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout--; } tmp = LL_RTC_IsActiveFlag_RS(RTCx); if (timeout == 0U) { status = ERROR; } } return (status); } /** * @} */ /** * @} */ /** * @} */ #endif /* defined(RTC) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */
the_stack_data/562058.c
/* * A média harmônica, Hn, de um conjunto de valores é dada por: * * 1/Hn = S[i=0, n-1] 1/Vi * * Escreva uma função para calcular e retornar a média harmônica de um conjunto * de valores. Essa função deve obedecer ao protótipo a seguir. Escreva um programa * para testar sua função. * * float harmonica (int n, float *v); */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 10 float harmonica(int n, float *v) { float s = .0f; for (int i = 0; i < n; i++) { s += 1 / v[i]; } return 1 / s; } int main(void) { float hn, v[N]; srand(time(NULL)); for (int i = 0; i < N; i++) { v[i] = rand() % 100 + 1; printf("%.2f ", v[i]); } puts(""); hn = harmonica(N, v); printf("Hn = %f\n", hn); return 0; }
the_stack_data/231394022.c
/* *Recurrnce Relation Algorithm */ #include<stdio.h> #include<math.h> void integral_recur(int nmin, int nmax, double vals[]); void integral_recur(int nmin, int nmax, double vals[]) { vals[100] = 0.00367843028136748866811; // Initial Condidtion evaluated using an integrator // int i; for (i = nmax - 1; i >= nmin; i--) { vals[i] = vals[i + 1] / (i + 1) + 1 / (M_E * (i + 1)); // New recursion formula // } }
the_stack_data/1052558.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #define XSTR(x) #x #define STR(x) XSTR(x) #define streqls(s1, s2) (!strcmp(s1, s2)) #define check(condition) \ if (!(condition)) { \ fprintf(stderr, "error: %s: %d: " STR(condition) "\n", __FILE__, \ __LINE__); \ exit(1); \ } #define BUFFER_SIZE 1024 char buf[BUFFER_SIZE]; #pragma omp threadprivate(buf) char* get_string(size_t check_needed) { size_t needed = omp_capture_affinity(buf, BUFFER_SIZE, NULL); //printf("buf = %s\n", buf); check(needed < BUFFER_SIZE); if (check_needed != 0) { check(needed == check_needed); } return buf; } void check_thread_num_padded_rjustified() { int i; const char* formats[2] = {"%0.8{thread_num}", "%0.8n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(8); for (j = 0; j < 7; ++j) { check(s[j] == '0'); } check(s[j] == ctid); } } } void check_thread_num_rjustified() { int i; const char* formats[2] = {"%.12{thread_num}", "%.12n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(12); for (j = 0; j < 11; ++j) { check(s[j] == ' '); } check(s[j] == ctid); } } } void check_thread_num_ljustified() { int i; const char* formats[2] = {"%5{thread_num}", "%5n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(5); check(s[0] == ctid); for (j = 1; j < 5; ++j) { check(s[j] == ' '); } } } } void check_thread_num_padded_ljustified() { int i; const char* formats[2] = {"%018{thread_num}", "%018n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(18); check(s[0] == ctid); for (j = 1; j < 18; ++j) { check(s[j] == ' '); } } } } int main(int argc, char** argv) { check_thread_num_ljustified(); check_thread_num_rjustified(); check_thread_num_padded_ljustified(); check_thread_num_padded_rjustified(); return 0; }
the_stack_data/168894192.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-2020 Free Software Foundation, Inc. Contributed by Intel Corp. <[email protected]> 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/>. */ int inc (int i) { return i+1; } int fib (int n) { if (n <= 1) return n; return fib(n-2) + fib(n-1); } int main (void) { int i, j; for (i = 0; i < 10; i++) j += inc(i); j += fib(3); /* bp.1 */ return j; /* bp.2 */ }
the_stack_data/508749.c
#include"stdio.h" #include"unistd.h" int main() { int pid,pid2; pid = fork(); if(pid) { pid2 = fork(); printf("ITER\n"); } else { printf("ITER\n"); pid2 = fork(); } } //No. of times "ITER" is displayesd is 3
the_stack_data/234517878.c
#include <stdio.h> int main() { short a; long b; long long c; long double d; printf("size of short = %d bytes\n", sizeof(a)); printf("size of long = %d bytes\n", sizeof(b)); printf("size of long long = %d bytes\n", sizeof(c)); printf("size of long double = %d bytes\n", sizeof(d)); return 0; }
the_stack_data/61092.c
/* Capstone Disassembly Engine */ /* By Nguyen Anh Quynh <[email protected]>, 2013-2014 */ #ifdef CAPSTONE_HAS_POWERPC #include <stdio.h> // debug #include <string.h> #include "../../utils.h" #include "PPCMapping.h" #define GET_INSTRINFO_ENUM #include "PPCGenInstrInfo.inc" #ifndef CAPSTONE_DIET static name_map reg_name_maps[] = { { PPC_REG_INVALID, NULL }, { PPC_REG_CARRY, "ca" }, { PPC_REG_CR0, "cr0" }, { PPC_REG_CR1, "cr1" }, { PPC_REG_CR2, "cr2" }, { PPC_REG_CR3, "cr3" }, { PPC_REG_CR4, "cr4" }, { PPC_REG_CR5, "cr5" }, { PPC_REG_CR6, "cr6" }, { PPC_REG_CR7, "cr7" }, { PPC_REG_CR8, "cr8" }, { PPC_REG_CR9, "cr9" }, { PPC_REG_CR10, "cr10" }, { PPC_REG_CR11, "cr11" }, { PPC_REG_CR12, "cr12" }, { PPC_REG_CR13, "cr13" }, { PPC_REG_CR14, "cr14" }, { PPC_REG_CR15, "cr15" }, { PPC_REG_CR16, "cr16" }, { PPC_REG_CR17, "cr17" }, { PPC_REG_CR18, "cr18" }, { PPC_REG_CR19, "cr19" }, { PPC_REG_CR20, "cr20" }, { PPC_REG_CR21, "cr21" }, { PPC_REG_CR22, "cr22" }, { PPC_REG_CR23, "cr23" }, { PPC_REG_CR24, "cr24" }, { PPC_REG_CR25, "cr25" }, { PPC_REG_CR26, "cr26" }, { PPC_REG_CR27, "cr27" }, { PPC_REG_CR28, "cr28" }, { PPC_REG_CR29, "cr29" }, { PPC_REG_CR30, "cr30" }, { PPC_REG_CR31, "cr31" }, { PPC_REG_CTR, "ctr" }, { PPC_REG_F0, "f0" }, { PPC_REG_F1, "f1" }, { PPC_REG_F2, "f2" }, { PPC_REG_F3, "f3" }, { PPC_REG_F4, "f4" }, { PPC_REG_F5, "f5" }, { PPC_REG_F6, "f6" }, { PPC_REG_F7, "f7" }, { PPC_REG_F8, "f8" }, { PPC_REG_F9, "f9" }, { PPC_REG_F10, "f10" }, { PPC_REG_F11, "f11" }, { PPC_REG_F12, "f12" }, { PPC_REG_F13, "f13" }, { PPC_REG_F14, "f14" }, { PPC_REG_F15, "f15" }, { PPC_REG_F16, "f16" }, { PPC_REG_F17, "f17" }, { PPC_REG_F18, "f18" }, { PPC_REG_F19, "f19" }, { PPC_REG_F20, "f20" }, { PPC_REG_F21, "f21" }, { PPC_REG_F22, "f22" }, { PPC_REG_F23, "f23" }, { PPC_REG_F24, "f24" }, { PPC_REG_F25, "f25" }, { PPC_REG_F26, "f26" }, { PPC_REG_F27, "f27" }, { PPC_REG_F28, "f28" }, { PPC_REG_F29, "f29" }, { PPC_REG_F30, "f30" }, { PPC_REG_F31, "f31" }, { PPC_REG_LR, "lr" }, { PPC_REG_R0, "r0" }, { PPC_REG_R1, "r1" }, { PPC_REG_R2, "r2" }, { PPC_REG_R3, "r3" }, { PPC_REG_R4, "r4" }, { PPC_REG_R5, "r5" }, { PPC_REG_R6, "r6" }, { PPC_REG_R7, "r7" }, { PPC_REG_R8, "r8" }, { PPC_REG_R9, "r9" }, { PPC_REG_R10, "r10" }, { PPC_REG_R11, "r11" }, { PPC_REG_R12, "r12" }, { PPC_REG_R13, "r13" }, { PPC_REG_R14, "r14" }, { PPC_REG_R15, "r15" }, { PPC_REG_R16, "r16" }, { PPC_REG_R17, "r17" }, { PPC_REG_R18, "r18" }, { PPC_REG_R19, "r19" }, { PPC_REG_R20, "r20" }, { PPC_REG_R21, "r21" }, { PPC_REG_R22, "r22" }, { PPC_REG_R23, "r23" }, { PPC_REG_R24, "r24" }, { PPC_REG_R25, "r25" }, { PPC_REG_R26, "r26" }, { PPC_REG_R27, "r27" }, { PPC_REG_R28, "r28" }, { PPC_REG_R29, "r29" }, { PPC_REG_R30, "r30" }, { PPC_REG_R31, "r31" }, { PPC_REG_V0, "v0" }, { PPC_REG_V1, "v1" }, { PPC_REG_V2, "v2" }, { PPC_REG_V3, "v3" }, { PPC_REG_V4, "v4" }, { PPC_REG_V5, "v5" }, { PPC_REG_V6, "v6" }, { PPC_REG_V7, "v7" }, { PPC_REG_V8, "v8" }, { PPC_REG_V9, "v9" }, { PPC_REG_V10, "v10" }, { PPC_REG_V11, "v11" }, { PPC_REG_V12, "v12" }, { PPC_REG_V13, "v13" }, { PPC_REG_V14, "v14" }, { PPC_REG_V15, "v15" }, { PPC_REG_V16, "v16" }, { PPC_REG_V17, "v17" }, { PPC_REG_V18, "v18" }, { PPC_REG_V19, "v19" }, { PPC_REG_V20, "v20" }, { PPC_REG_V21, "v21" }, { PPC_REG_V22, "v22" }, { PPC_REG_V23, "v23" }, { PPC_REG_V24, "v24" }, { PPC_REG_V25, "v25" }, { PPC_REG_V26, "v26" }, { PPC_REG_V27, "v27" }, { PPC_REG_V28, "v28" }, { PPC_REG_V29, "v29" }, { PPC_REG_V30, "v30" }, { PPC_REG_V31, "v31" }, { PPC_REG_VRSAVE, "vrsave" }, // extras { PPC_REG_RM, "rm" }, { PPC_REG_CTR8, "ctr8" }, { PPC_REG_LR8, "lr8" }, { PPC_REG_CR1EQ, "cr1eq" }, }; #endif const char *PPC_reg_name(csh handle, unsigned int reg) { #ifndef CAPSTONE_DIET if (reg >= PPC_REG_MAX) return NULL; return reg_name_maps[reg].name; #else return NULL; #endif } static insn_map insns[] = { // dummy item { 0, 0, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD4, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD4TLS, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD4o, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD8, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD8TLS, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD8TLS_, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADD8o, PPC_INS_ADD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDC, PPC_INS_ADDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDC8, PPC_INS_ADDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDC8o, PPC_INS_ADDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDCo, PPC_INS_ADDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDE, PPC_INS_ADDE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDE8, PPC_INS_ADDE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDE8o, PPC_INS_ADDE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDEo, PPC_INS_ADDE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDI, PPC_INS_ADDI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDI8, PPC_INS_ADDI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDIC, PPC_INS_ADDIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDIC8, PPC_INS_ADDIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDICo, PPC_INS_ADDIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDIS, PPC_INS_ADDIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDIS8, PPC_INS_ADDIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDME, PPC_INS_ADDME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDME8, PPC_INS_ADDME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDME8o, PPC_INS_ADDME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDMEo, PPC_INS_ADDME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDZE, PPC_INS_ADDZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDZE8, PPC_INS_ADDZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDZE8o, PPC_INS_ADDZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ADDZEo, PPC_INS_ADDZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_AND, PPC_INS_AND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_AND8, PPC_INS_AND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_AND8o, PPC_INS_AND, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDC, PPC_INS_ANDC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDC8, PPC_INS_ANDC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDC8o, PPC_INS_ANDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDCo, PPC_INS_ANDC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDISo, PPC_INS_ANDIS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDISo8, PPC_INS_ANDIS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDIo, PPC_INS_ANDI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDIo8, PPC_INS_ANDI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ANDo, PPC_INS_AND, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_B, PPC_INS_B, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_BA, PPC_INS_BA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_BCC, PPC_INS_B, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_BCCA, PPC_INS_B, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_BCCL, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BCCLA, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BCCTR, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { 0 }, { 0 }, 1, 1 #endif }, { PPC_BCCTR8, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, 0 }, { 0 }, { PPC_GRP_MODE64, 0 }, 1, 1 #endif }, { PPC_BCCTRL, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BCCTRL8, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { PPC_GRP_MODE64, 0 }, 0, 0 #endif }, { PPC_BCLR, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_LR, PPC_REG_RM, 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_BCLRL, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BCLalways, PPC_INS_BCL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BCTR, PPC_INS_BCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { 0 }, { 0 }, 1, 1 #endif }, { PPC_BCTR8, PPC_INS_BCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, 0 }, { 0 }, { PPC_GRP_MODE64, 0 }, 1, 1 #endif }, { PPC_BCTRL, PPC_INS_BCTRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { PPC_GRP_MODE32, 0 }, 0, 0 #endif }, { PPC_BCTRL8, PPC_INS_BCTRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { PPC_GRP_MODE64, 0 }, 0, 0 #endif }, { PPC_BDNZ, PPC_INS_BDNZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZ8, PPC_INS_BDNZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZA, PPC_INS_BDNZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZAm, PPC_INS_BDNZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZAp, PPC_INS_BDNZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZL, PPC_INS_BDNZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLA, PPC_INS_BDNZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLAm, PPC_INS_BDNZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLAp, PPC_INS_BDNZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLR, PPC_INS_BDNZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZLR8, PPC_INS_BDNZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, PPC_REG_LR8, PPC_REG_RM, 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZLRL, PPC_INS_BDNZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLRLm, PPC_INS_BDNZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLRLp, PPC_INS_BDNZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLRm, PPC_INS_BDNZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZLRp, PPC_INS_BDNZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZLm, PPC_INS_BDNZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZLp, PPC_INS_BDNZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDNZm, PPC_INS_BDNZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDNZp, PPC_INS_BDNZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZ, PPC_INS_BDZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZ8, PPC_INS_BDZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZA, PPC_INS_BDZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZAm, PPC_INS_BDZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZAp, PPC_INS_BDZA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZL, PPC_INS_BDZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLA, PPC_INS_BDZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLAm, PPC_INS_BDZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLAp, PPC_INS_BDZLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLR, PPC_INS_BDZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZLR8, PPC_INS_BDZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, PPC_REG_LR8, PPC_REG_RM, 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZLRL, PPC_INS_BDZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLRLm, PPC_INS_BDZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLRLp, PPC_INS_BDZLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLRm, PPC_INS_BDZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZLRp, PPC_INS_BDZLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZLm, PPC_INS_BDZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZLp, PPC_INS_BDZL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BDZm, PPC_INS_BDZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BDZp, PPC_INS_BDZ, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 1, 0 #endif }, { PPC_BL, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BL8, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BL8_NOP, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BL8_NOP_TLS, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BL8_TLS, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BL8_TLS_, PPC_INS_BL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BLA, PPC_INS_BLA, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_BLA8, PPC_INS_BLA, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BLA8_NOP, PPC_INS_BLA, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_BLR, PPC_INS_BLR, #ifndef CAPSTONE_DIET { PPC_REG_LR, PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_BLRL, PPC_INS_BLRL, #ifndef CAPSTONE_DIET { PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPD, PPC_INS_CMPD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPDI, PPC_INS_CMPDI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPLD, PPC_INS_CMPLD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPLDI, PPC_INS_CMPLDI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPLW, PPC_INS_CMPLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPLWI, PPC_INS_CMPLWI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPW, PPC_INS_CMPW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CMPWI, PPC_INS_CMPWI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CNTLZD, PPC_INS_CNTLZD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CNTLZDo, PPC_INS_CNTLZD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_CNTLZW, PPC_INS_CNTLZW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CNTLZWo, PPC_INS_CNTLZW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_CR6SET, PPC_INS_CREQV, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1EQ, 0 }, { 0 }, 0, 0 #endif }, { PPC_CR6UNSET, PPC_INS_CRXOR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1EQ, 0 }, { 0 }, 0, 0 #endif }, { PPC_CRAND, PPC_INS_CRAND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRANDC, PPC_INS_CRANDC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CREQV, PPC_INS_CREQV, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRNAND, PPC_INS_CRNAND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRNOR, PPC_INS_CRNOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CROR, PPC_INS_CROR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRORC, PPC_INS_CRORC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRSET, PPC_INS_CREQV, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRUNSET, PPC_INS_CRXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_CRXOR, PPC_INS_CRXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBA, PPC_INS_DCBA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBF, PPC_INS_DCBF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBI, PPC_INS_DCBI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBST, PPC_INS_DCBST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBT, PPC_INS_DCBT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBTST, PPC_INS_DCBTST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBZ, PPC_INS_DCBZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DCBZL, PPC_INS_DCBZL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVD, PPC_INS_DIVD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVDU, PPC_INS_DIVDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVDUo, PPC_INS_DIVDU, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVDo, PPC_INS_DIVD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVW, PPC_INS_DIVW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVWU, PPC_INS_DIVWU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVWUo, PPC_INS_DIVWU, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_DIVWo, PPC_INS_DIVW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_DSS, PPC_INS_DSS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSSALL, PPC_INS_DSSALL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DST, PPC_INS_DST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DST64, PPC_INS_DST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTST, PPC_INS_DSTST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTST64, PPC_INS_DSTST, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTSTT, PPC_INS_DSTSTT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTSTT64, PPC_INS_DSTSTT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTT, PPC_INS_DSTT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_DSTT64, PPC_INS_DSTT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_EIEIO, PPC_INS_EIEIO, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EQV, PPC_INS_EQV, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EQV8, PPC_INS_EQV, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EQV8o, PPC_INS_EQV, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EQVo, PPC_INS_EQV, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSB, PPC_INS_EXTSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSB8, PPC_INS_EXTSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSB8_32_64, PPC_INS_EXTSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSB8o, PPC_INS_EXTSB, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSBo, PPC_INS_EXTSB, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSH, PPC_INS_EXTSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSH8, PPC_INS_EXTSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSH8_32_64, PPC_INS_EXTSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSH8o, PPC_INS_EXTSH, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSHo, PPC_INS_EXTSH, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSW, PPC_INS_EXTSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSW_32_64, PPC_INS_EXTSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSW_32_64o, PPC_INS_EXTSW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_EXTSWo, PPC_INS_EXTSW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_FABSD, PPC_INS_FABS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FABSDo, PPC_INS_FABS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FABSS, PPC_INS_FABS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FABSSo, PPC_INS_FABS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FADD, PPC_INS_FADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FADDS, PPC_INS_FADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FADDSo, PPC_INS_FADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FADDo, PPC_INS_FADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFID, PPC_INS_FCFID, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDS, PPC_INS_FCFIDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDSo, PPC_INS_FCFIDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDU, PPC_INS_FCFIDU, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDUS, PPC_INS_FCFIDUS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDUSo, PPC_INS_FCFIDUS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDUo, PPC_INS_FCFIDU, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCFIDo, PPC_INS_FCFID, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCMPUD, PPC_INS_FCMPU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCMPUS, PPC_INS_FCMPU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCPSGND, PPC_INS_FCPSGN, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCPSGNDo, PPC_INS_FCPSGN, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCPSGNS, PPC_INS_FCPSGN, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCPSGNSo, PPC_INS_FCPSGN, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTID, PPC_INS_FCTID, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIDUZ, PPC_INS_FCTIDUZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIDUZo, PPC_INS_FCTIDUZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIDZ, PPC_INS_FCTIDZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIDZo, PPC_INS_FCTIDZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIDo, PPC_INS_FCTID, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIW, PPC_INS_FCTIW, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIWUZ, PPC_INS_FCTIWUZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIWUZo, PPC_INS_FCTIWUZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIWZ, PPC_INS_FCTIWZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIWZo, PPC_INS_FCTIWZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FCTIWo, PPC_INS_FCTIW, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FDIV, PPC_INS_FDIV, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FDIVS, PPC_INS_FDIVS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FDIVSo, PPC_INS_FDIVS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FDIVo, PPC_INS_FDIV, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMADD, PPC_INS_FMADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMADDS, PPC_INS_FMADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMADDSo, PPC_INS_FMADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMADDo, PPC_INS_FMADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMR, PPC_INS_FMR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMRo, PPC_INS_FMR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMSUB, PPC_INS_FMSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMSUBS, PPC_INS_FMSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMSUBSo, PPC_INS_FMSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMSUBo, PPC_INS_FMSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMUL, PPC_INS_FMUL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMULS, PPC_INS_FMULS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FMULSo, PPC_INS_FMULS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FMULo, PPC_INS_FMUL, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNABSD, PPC_INS_FNABS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNABSDo, PPC_INS_FNABS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNABSS, PPC_INS_FNABS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNABSSo, PPC_INS_FNABS, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNEGD, PPC_INS_FNEG, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNEGDo, PPC_INS_FNEG, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNEGS, PPC_INS_FNEG, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNEGSo, PPC_INS_FNEG, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMADD, PPC_INS_FNMADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMADDS, PPC_INS_FNMADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMADDSo, PPC_INS_FNMADDS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMADDo, PPC_INS_FNMADD, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMSUB, PPC_INS_FNMSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMSUBS, PPC_INS_FNMSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMSUBSo, PPC_INS_FNMSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FNMSUBo, PPC_INS_FNMSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRE, PPC_INS_FRE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRES, PPC_INS_FRES, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRESo, PPC_INS_FRES, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FREo, PPC_INS_FRE, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIMD, PPC_INS_FRIM, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIMDo, PPC_INS_FRIM, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIMS, PPC_INS_FRIM, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIMSo, PPC_INS_FRIM, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIND, PPC_INS_FRIN, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRINDo, PPC_INS_FRIN, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRINS, PPC_INS_FRIN, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRINSo, PPC_INS_FRIN, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIPD, PPC_INS_FRIP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIPDo, PPC_INS_FRIP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIPS, PPC_INS_FRIP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIPSo, PPC_INS_FRIP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIZD, PPC_INS_FRIZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIZDo, PPC_INS_FRIZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIZS, PPC_INS_FRIZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRIZSo, PPC_INS_FRIZ, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSP, PPC_INS_FRSP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSPo, PPC_INS_FRSP, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSQRTE, PPC_INS_FRSQRTE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSQRTES, PPC_INS_FRSQRTES, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSQRTESo, PPC_INS_FRSQRTES, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FRSQRTEo, PPC_INS_FRSQRTE, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSELD, PPC_INS_FSEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSELDo, PPC_INS_FSEL, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSELS, PPC_INS_FSEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSELSo, PPC_INS_FSEL, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSQRT, PPC_INS_FSQRT, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSQRTS, PPC_INS_FSQRTS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSQRTSo, PPC_INS_FSQRTS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSQRTo, PPC_INS_FSQRT, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSUB, PPC_INS_FSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSUBS, PPC_INS_FSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_FSUBSo, PPC_INS_FSUBS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_FSUBo, PPC_INS_FSUB, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_CR1, 0 }, { 0 }, 0, 0 #endif }, { PPC_ICBI, PPC_INS_ICBI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ISEL, PPC_INS_ISEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ISEL8, PPC_INS_ISEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ISYNC, PPC_INS_ISYNC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LA, PPC_INS_LA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZ, PPC_INS_LBZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZ8, PPC_INS_LBZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZU, PPC_INS_LBZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZU8, PPC_INS_LBZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZUX, PPC_INS_LBZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZUX8, PPC_INS_LBZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZX, PPC_INS_LBZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LBZX8, PPC_INS_LBZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LD, PPC_INS_LD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDARX, PPC_INS_LDARX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDBRX, PPC_INS_LDBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDU, PPC_INS_LDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDUX, PPC_INS_LDUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDX, PPC_INS_LDX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDinto_toc, PPC_INS_LD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LDtoc_restore, PPC_INS_LD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFD, PPC_INS_LFD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFDU, PPC_INS_LFDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFDUX, PPC_INS_LFDUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFDX, PPC_INS_LFDX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFIWAX, PPC_INS_LFIWAX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFIWZX, PPC_INS_LFIWZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFS, PPC_INS_LFS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFSU, PPC_INS_LFSU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFSUX, PPC_INS_LFSUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LFSX, PPC_INS_LFSX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHA, PPC_INS_LHA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHA8, PPC_INS_LHA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAU, PPC_INS_LHAU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAU8, PPC_INS_LHAU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAUX, PPC_INS_LHAUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAUX8, PPC_INS_LHAUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAX, PPC_INS_LHAX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHAX8, PPC_INS_LHAX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHBRX, PPC_INS_LHBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZ, PPC_INS_LHZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZ8, PPC_INS_LHZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZU, PPC_INS_LHZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZU8, PPC_INS_LHZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZUX, PPC_INS_LHZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZUX8, PPC_INS_LHZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZX, PPC_INS_LHZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LHZX8, PPC_INS_LHZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LI, PPC_INS_LI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LI8, PPC_INS_LI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LIS, PPC_INS_LIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LIS8, PPC_INS_LIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LMW, PPC_INS_LMW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LVEBX, PPC_INS_LVEBX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVEHX, PPC_INS_LVEHX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVEWX, PPC_INS_LVEWX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVSL, PPC_INS_LVSL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVSR, PPC_INS_LVSR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVX, PPC_INS_LVX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LVXL, PPC_INS_LVXL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_LWA, PPC_INS_LWA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWARX, PPC_INS_LWARX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWAUX, PPC_INS_LWAUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWAX, PPC_INS_LWAX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWAX_32, PPC_INS_LWAX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWA_32, PPC_INS_LWA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWBRX, PPC_INS_LWBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZ, PPC_INS_LWZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZ8, PPC_INS_LWZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZU, PPC_INS_LWZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZU8, PPC_INS_LWZU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZUX, PPC_INS_LWZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZUX8, PPC_INS_LWZUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZX, PPC_INS_LWZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_LWZX8, PPC_INS_LWZX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MCRF, PPC_INS_MCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFCR, PPC_INS_MFCR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFCR8, PPC_INS_MFCR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFCTR, PPC_INS_MFCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFCTR8, PPC_INS_MFCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFFS, PPC_INS_MFFS, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFLR, PPC_INS_MFLR, #ifndef CAPSTONE_DIET { PPC_REG_LR, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFLR8, PPC_INS_MFLR, #ifndef CAPSTONE_DIET { PPC_REG_LR8, 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFMSR, PPC_INS_MFMSR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFOCRF, PPC_INS_MFOCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFOCRF8, PPC_INS_MFOCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFSPR, PPC_INS_MFSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFTB, PPC_INS_MFTB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFTB8, PPC_INS_MFSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFVRSAVE, PPC_INS_MFSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFVRSAVEv, PPC_INS_MFSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MFVSCR, PPC_INS_MFVSCR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_MSYNC, PPC_INS_MSYNC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_BOOKE, 0 }, 0, 0 #endif }, { PPC_MTCRF, PPC_INS_MTCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTCRF8, PPC_INS_MTCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTCTR, PPC_INS_MTCTR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTCTR8, PPC_INS_MTCTR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTCTR8loop, PPC_INS_MTCTR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CTR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTCTRloop, PPC_INS_MTCTR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTFSB0, PPC_INS_MTFSB0, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_RM, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTFSB1, PPC_INS_MTFSB1, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_RM, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTFSF, PPC_INS_MTFSF, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { PPC_REG_RM, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTLR, PPC_INS_MTLR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_LR, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTLR8, PPC_INS_MTLR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_LR8, 0 }, { 0 }, 0, 0 #endif }, { PPC_MTMSR, PPC_INS_MTMSR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTMSRD, PPC_INS_MTMSRD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTOCRF, PPC_INS_MTOCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTOCRF8, PPC_INS_MTOCRF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTSPR, PPC_INS_MTSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTVRSAVE, PPC_INS_MTSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTVRSAVEv, PPC_INS_MTSPR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MTVSCR, PPC_INS_MTVSCR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_MULHD, PPC_INS_MULHD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHDU, PPC_INS_MULHDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHDUo, PPC_INS_MULHDU, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHDo, PPC_INS_MULHD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHW, PPC_INS_MULHW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHWU, PPC_INS_MULHWU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHWUo, PPC_INS_MULHWU, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_MULHWo, PPC_INS_MULHW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLD, PPC_INS_MULLD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLDo, PPC_INS_MULLD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLI, PPC_INS_MULLI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLI8, PPC_INS_MULLI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLW, PPC_INS_MULLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_MULLWo, PPC_INS_MULLW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NAND, PPC_INS_NAND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NAND8, PPC_INS_NAND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NAND8o, PPC_INS_NAND, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NANDo, PPC_INS_NAND, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NEG, PPC_INS_NEG, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NEG8, PPC_INS_NEG, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NEG8o, PPC_INS_NEG, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NEGo, PPC_INS_NEG, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NOP, PPC_INS_NOP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NOP_GT_PWR6, PPC_INS_ORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NOP_GT_PWR7, PPC_INS_ORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NOR, PPC_INS_NOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NOR8, PPC_INS_NOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_NOR8o, PPC_INS_NOR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_NORo, PPC_INS_NOR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_OR, PPC_INS_OR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_OR8, PPC_INS_OR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_OR8o, PPC_INS_OR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ORC, PPC_INS_ORC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORC8, PPC_INS_ORC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORC8o, PPC_INS_ORC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ORCo, PPC_INS_ORC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_ORI, PPC_INS_ORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORI8, PPC_INS_ORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORIS, PPC_INS_ORIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORIS8, PPC_INS_ORIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_ORo, PPC_INS_OR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_POPCNTD, PPC_INS_POPCNTD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_POPCNTW, PPC_INS_POPCNTW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDCL, PPC_INS_RLDCL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDCLo, PPC_INS_RLDCL, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDCR, PPC_INS_RLDCR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDCRo, PPC_INS_RLDCR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDIC, PPC_INS_RLDIC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICL, PPC_INS_RLDICL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICL_32_64, PPC_INS_RLDICL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICLo, PPC_INS_RLDICL, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICR, PPC_INS_RLDICR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICRo, PPC_INS_RLDICR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDICo, PPC_INS_RLDIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDIMI, PPC_INS_RLDIMI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLDIMIo, PPC_INS_RLDIMI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWIMI, PPC_INS_RLWIMI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWIMIo, PPC_INS_RLWIMI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWINM, PPC_INS_RLWINM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWINM8, PPC_INS_RLWINM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWINM8o, PPC_INS_RLWINM, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWINMo, PPC_INS_RLWINM, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWNM, PPC_INS_RLWNM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_RLWNMo, PPC_INS_RLWNM, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SC, PPC_INS_SC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLBIA, PPC_INS_SLBIA, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLBIE, PPC_INS_SLBIE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLBMFEE, PPC_INS_SLBMFEE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLBMTE, PPC_INS_SLBMTE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLD, PPC_INS_SLD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLDo, PPC_INS_SLD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SLW, PPC_INS_SLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SLWo, PPC_INS_SLW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRAD, PPC_INS_SRAD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRADI, PPC_INS_SRADI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRADIo, PPC_INS_SRADI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRADo, PPC_INS_SRAD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRAW, PPC_INS_SRAW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRAWI, PPC_INS_SRAWI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRAWIo, PPC_INS_SRAWI, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRAWo, PPC_INS_SRAW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRD, PPC_INS_SRD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SRDo, PPC_INS_SRD, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SRW, PPC_INS_SRW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SRWo, PPC_INS_SRW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_STB, PPC_INS_STB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STB8, PPC_INS_STB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBU, PPC_INS_STBU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBU8, PPC_INS_STBU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBUX, PPC_INS_STBUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBUX8, PPC_INS_STBUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBX, PPC_INS_STBX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STBX8, PPC_INS_STBX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STD, PPC_INS_STD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STDBRX, PPC_INS_STDBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STDCX, PPC_INS_STDCX, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_STDU, PPC_INS_STDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STDUX, PPC_INS_STDUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STDX, PPC_INS_STDX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFD, PPC_INS_STFD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFDU, PPC_INS_STFDU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFDUX, PPC_INS_STFDUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFDX, PPC_INS_STFDX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFIWX, PPC_INS_STFIWX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFS, PPC_INS_STFS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFSU, PPC_INS_STFSU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFSUX, PPC_INS_STFSUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STFSX, PPC_INS_STFSX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STH, PPC_INS_STH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STH8, PPC_INS_STH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHBRX, PPC_INS_STHBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHU, PPC_INS_STHU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHU8, PPC_INS_STHU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHUX, PPC_INS_STHUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHUX8, PPC_INS_STHUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHX, PPC_INS_STHX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STHX8, PPC_INS_STHX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STMW, PPC_INS_STMW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STVEBX, PPC_INS_STVEBX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_STVEHX, PPC_INS_STVEHX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_STVEWX, PPC_INS_STVEWX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_STVX, PPC_INS_STVX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_STVXL, PPC_INS_STVXL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_STW, PPC_INS_STW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STW8, PPC_INS_STW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWBRX, PPC_INS_STWBRX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWCX, PPC_INS_STWCX, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_STWU, PPC_INS_STWU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWU8, PPC_INS_STWU, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWUX, PPC_INS_STWUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWUX8, PPC_INS_STWUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWX, PPC_INS_STWX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_STWX8, PPC_INS_STWX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBF, PPC_INS_SUBF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBF8, PPC_INS_SUBF, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBF8o, PPC_INS_SUBF, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFC, PPC_INS_SUBFC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFC8, PPC_INS_SUBFC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFC8o, PPC_INS_SUBFC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFCo, PPC_INS_SUBFC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFE, PPC_INS_SUBFE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFE8, PPC_INS_SUBFE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFE8o, PPC_INS_SUBFE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFEo, PPC_INS_SUBFE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFIC, PPC_INS_SUBFIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFIC8, PPC_INS_SUBFIC, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFME, PPC_INS_SUBFME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFME8, PPC_INS_SUBFME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFME8o, PPC_INS_SUBFME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFMEo, PPC_INS_SUBFME, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFZE, PPC_INS_SUBFZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFZE8, PPC_INS_SUBFZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFZE8o, PPC_INS_SUBFZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFZEo, PPC_INS_SUBFZE, #ifndef CAPSTONE_DIET { PPC_REG_CARRY, 0 }, { PPC_REG_CARRY, PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SUBFo, PPC_INS_SUBF, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_SYNC, PPC_INS_SYNC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_NOTBOOKE, 0 }, 0, 0 #endif }, { PPC_TAILB, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_TAILB8, PPC_INS_B, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_TAILBA, PPC_INS_BA, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_TAILBA8, PPC_INS_BA, #ifndef CAPSTONE_DIET { PPC_REG_RM, 0 }, { 0 }, { 0 }, 1, 0 #endif }, { PPC_TAILBCTR, PPC_INS_BCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { 0 }, { PPC_GRP_MODE32, 0 }, 1, 1 #endif }, { PPC_TAILBCTR8, PPC_INS_BCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR8, PPC_REG_RM, 0 }, { 0 }, { PPC_GRP_MODE64, 0 }, 1, 1 #endif }, { PPC_TD, PPC_INS_TD, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TDI, PPC_INS_TDI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TLBIE, PPC_INS_TLBIE, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TLBIEL, PPC_INS_TLBIEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TLBSYNC, PPC_INS_TLBSYNC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TRAP, PPC_INS_TRAP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TW, PPC_INS_TW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_TWI, PPC_INS_TWI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_VADDCUW, PPC_INS_VADDCUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDFP, PPC_INS_VADDFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDSBS, PPC_INS_VADDSBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDSHS, PPC_INS_VADDSHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDSWS, PPC_INS_VADDSWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUBM, PPC_INS_VADDUBM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUBS, PPC_INS_VADDUBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUHM, PPC_INS_VADDUHM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUHS, PPC_INS_VADDUHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUWM, PPC_INS_VADDUWM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VADDUWS, PPC_INS_VADDUWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAND, PPC_INS_VAND, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VANDC, PPC_INS_VANDC, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGSB, PPC_INS_VAVGSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGSH, PPC_INS_VAVGSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGSW, PPC_INS_VAVGSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGUB, PPC_INS_VAVGUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGUH, PPC_INS_VAVGUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VAVGUW, PPC_INS_VAVGUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCFSX, PPC_INS_VCFSX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCFSX_0, PPC_INS_VCFSX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCFUX, PPC_INS_VCFUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCFUX_0, PPC_INS_VCFUX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPBFP, PPC_INS_VCMPBFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPBFPo, PPC_INS_VCMPBFP, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQFP, PPC_INS_VCMPEQFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQFPo, PPC_INS_VCMPEQFP, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUB, PPC_INS_VCMPEQUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUBo, PPC_INS_VCMPEQUB, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUH, PPC_INS_VCMPEQUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUHo, PPC_INS_VCMPEQUH, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUW, PPC_INS_VCMPEQUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPEQUWo, PPC_INS_VCMPEQUW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGEFP, PPC_INS_VCMPGEFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGEFPo, PPC_INS_VCMPGEFP, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTFP, PPC_INS_VCMPGTFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTFPo, PPC_INS_VCMPGTFP, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSB, PPC_INS_VCMPGTSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSBo, PPC_INS_VCMPGTSB, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSH, PPC_INS_VCMPGTSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSHo, PPC_INS_VCMPGTSH, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSW, PPC_INS_VCMPGTSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTSWo, PPC_INS_VCMPGTSW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUB, PPC_INS_VCMPGTUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUBo, PPC_INS_VCMPGTUB, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUH, PPC_INS_VCMPGTUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUHo, PPC_INS_VCMPGTUH, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUW, PPC_INS_VCMPGTUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCMPGTUWo, PPC_INS_VCMPGTUW, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR6, 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCTSXS, PPC_INS_VCTSXS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCTSXS_0, PPC_INS_VCTSXS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCTUXS, PPC_INS_VCTUXS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VCTUXS_0, PPC_INS_VCTUXS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VEXPTEFP, PPC_INS_VEXPTEFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VLOGEFP, PPC_INS_VLOGEFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMADDFP, PPC_INS_VMADDFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXFP, PPC_INS_VMAXFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXSB, PPC_INS_VMAXSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXSH, PPC_INS_VMAXSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXSW, PPC_INS_VMAXSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXUB, PPC_INS_VMAXUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXUH, PPC_INS_VMAXUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMAXUW, PPC_INS_VMAXUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMHADDSHS, PPC_INS_VMHADDSHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMHRADDSHS, PPC_INS_VMHRADDSHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINFP, PPC_INS_VMINFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINSB, PPC_INS_VMINSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINSH, PPC_INS_VMINSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINSW, PPC_INS_VMINSW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINUB, PPC_INS_VMINUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINUH, PPC_INS_VMINUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMINUW, PPC_INS_VMINUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMLADDUHM, PPC_INS_VMLADDUHM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGHB, PPC_INS_VMRGHB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGHH, PPC_INS_VMRGHH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGHW, PPC_INS_VMRGHW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGLB, PPC_INS_VMRGLB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGLH, PPC_INS_VMRGLH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMRGLW, PPC_INS_VMRGLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMMBM, PPC_INS_VMSUMMBM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMSHM, PPC_INS_VMSUMSHM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMSHS, PPC_INS_VMSUMSHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMUBM, PPC_INS_VMSUMUBM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMUHM, PPC_INS_VMSUMUHM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMSUMUHS, PPC_INS_VMSUMUHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULESB, PPC_INS_VMULESB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULESH, PPC_INS_VMULESH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULEUB, PPC_INS_VMULEUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULEUH, PPC_INS_VMULEUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULOSB, PPC_INS_VMULOSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULOSH, PPC_INS_VMULOSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULOUB, PPC_INS_VMULOUB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VMULOUH, PPC_INS_VMULOUH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VNMSUBFP, PPC_INS_VNMSUBFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VNOR, PPC_INS_VNOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VOR, PPC_INS_VOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPERM, PPC_INS_VPERM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKPX, PPC_INS_VPKPX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKSHSS, PPC_INS_VPKSHSS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKSHUS, PPC_INS_VPKSHUS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKSWSS, PPC_INS_VPKSWSS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKSWUS, PPC_INS_VPKSWUS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKUHUM, PPC_INS_VPKUHUM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKUHUS, PPC_INS_VPKUHUS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKUWUM, PPC_INS_VPKUWUM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VPKUWUS, PPC_INS_VPKUWUS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VREFP, PPC_INS_VREFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRFIM, PPC_INS_VRFIM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRFIN, PPC_INS_VRFIN, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRFIP, PPC_INS_VRFIP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRFIZ, PPC_INS_VRFIZ, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRLB, PPC_INS_VRLB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRLH, PPC_INS_VRLH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRLW, PPC_INS_VRLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VRSQRTEFP, PPC_INS_VRSQRTEFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSEL, PPC_INS_VSEL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSL, PPC_INS_VSL, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSLB, PPC_INS_VSLB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSLDOI, PPC_INS_VSLDOI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSLH, PPC_INS_VSLH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSLO, PPC_INS_VSLO, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSLW, PPC_INS_VSLW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTB, PPC_INS_VSPLTB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTH, PPC_INS_VSPLTH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTISB, PPC_INS_VSPLTISB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTISH, PPC_INS_VSPLTISH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTISW, PPC_INS_VSPLTISW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSPLTW, PPC_INS_VSPLTW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSR, PPC_INS_VSR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRAB, PPC_INS_VSRAB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRAH, PPC_INS_VSRAH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRAW, PPC_INS_VSRAW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRB, PPC_INS_VSRB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRH, PPC_INS_VSRH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRO, PPC_INS_VSRO, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSRW, PPC_INS_VSRW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBCUW, PPC_INS_VSUBCUW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBFP, PPC_INS_VSUBFP, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBSBS, PPC_INS_VSUBSBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBSHS, PPC_INS_VSUBSHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBSWS, PPC_INS_VSUBSWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUBM, PPC_INS_VSUBUBM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUBS, PPC_INS_VSUBUBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUHM, PPC_INS_VSUBUHM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUHS, PPC_INS_VSUBUHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUWM, PPC_INS_VSUBUWM, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUBUWS, PPC_INS_VSUBUWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUM2SWS, PPC_INS_VSUM2SWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUM4SBS, PPC_INS_VSUM4SBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUM4SHS, PPC_INS_VSUM4SHS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUM4UBS, PPC_INS_VSUM4UBS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VSUMSWS, PPC_INS_VSUMSWS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKHPX, PPC_INS_VUPKHPX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKHSB, PPC_INS_VUPKHSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKHSH, PPC_INS_VUPKHSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKLPX, PPC_INS_VUPKLPX, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKLSB, PPC_INS_VUPKLSB, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VUPKLSH, PPC_INS_VUPKLSH, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_VXOR, PPC_INS_VXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SET0, PPC_INS_VXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SET0B, PPC_INS_VXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SET0H, PPC_INS_VXOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SETALLONES, PPC_INS_VSPLTISW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SETALLONESB, PPC_INS_VSPLTISW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_V_SETALLONESH, PPC_INS_VSPLTISW, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { PPC_GRP_ALTIVEC, 0 }, 0, 0 #endif }, { PPC_WAIT, PPC_INS_WAIT, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XOR, PPC_INS_XOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XOR8, PPC_INS_XOR, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XOR8o, PPC_INS_XOR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_XORI, PPC_INS_XORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XORI8, PPC_INS_XORI, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XORIS, PPC_INS_XORIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XORIS8, PPC_INS_XORIS, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, { PPC_XORo, PPC_INS_XOR, #ifndef CAPSTONE_DIET { 0 }, { PPC_REG_CR0, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBC, PPC_INS_BC, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCA, PPC_INS_BCA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCCTR, PPC_INS_BCCTR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCCTRL, PPC_INS_BCCTRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_LR, PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCL, PPC_INS_BCL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_LR, PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCLA, PPC_INS_BCLA, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_RM, 0 }, { PPC_REG_LR, PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCLR, PPC_INS_BCLR, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, { PPC_gBCLRL, PPC_INS_BCLRL, #ifndef CAPSTONE_DIET { PPC_REG_CTR, PPC_REG_LR, PPC_REG_RM, 0 }, { PPC_REG_LR, PPC_REG_CTR, 0 }, { 0 }, 0, 0 #endif }, }; // given internal insn id, return public instruction info void PPC_get_insn_id(cs_struct *h, cs_insn *insn, unsigned int id) { int i; i = insn_find(insns, ARR_SIZE(insns), id, &h->insn_cache); if (i != 0) { insn->id = insns[i].mapid; if (h->detail) { #ifndef CAPSTONE_DIET cs_struct handle; handle.detail = h->detail; memcpy(insn->detail->regs_read, insns[i].regs_use, sizeof(insns[i].regs_use)); insn->detail->regs_read_count = (uint8_t)count_positive(insns[i].regs_use); memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod)); insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod); memcpy(insn->detail->groups, insns[i].groups, sizeof(insns[i].groups)); insn->detail->groups_count = (uint8_t)count_positive(insns[i].groups); if (insns[i].branch || insns[i].indirect_branch) { // this insn also belongs to JUMP group. add JUMP group insn->detail->groups[insn->detail->groups_count] = PPC_GRP_JUMP; insn->detail->groups_count++; } insn->detail->ppc.update_cr0 = cs_reg_write((csh)&handle, insn, PPC_REG_CR0); #endif } } } #ifndef CAPSTONE_DIET static name_map insn_name_maps[] = { { PPC_INS_INVALID, NULL }, { PPC_INS_ADD, "add" }, { PPC_INS_ADDC, "addc" }, { PPC_INS_ADDE, "adde" }, { PPC_INS_ADDI, "addi" }, { PPC_INS_ADDIC, "addic" }, { PPC_INS_ADDIS, "addis" }, { PPC_INS_ADDME, "addme" }, { PPC_INS_ADDZE, "addze" }, { PPC_INS_AND, "and" }, { PPC_INS_ANDC, "andc" }, { PPC_INS_ANDIS, "andis" }, { PPC_INS_ANDI, "andi" }, { PPC_INS_B, "b" }, { PPC_INS_BA, "ba" }, { PPC_INS_BCL, "bcl" }, { PPC_INS_BCTR, "bctr" }, { PPC_INS_BCTRL, "bctrl" }, { PPC_INS_BDNZ, "bdnz" }, { PPC_INS_BDNZA, "bdnza" }, { PPC_INS_BDNZL, "bdnzl" }, { PPC_INS_BDNZLA, "bdnzla" }, { PPC_INS_BDNZLR, "bdnzlr" }, { PPC_INS_BDNZLRL, "bdnzlrl" }, { PPC_INS_BDZ, "bdz" }, { PPC_INS_BDZA, "bdza" }, { PPC_INS_BDZL, "bdzl" }, { PPC_INS_BDZLA, "bdzla" }, { PPC_INS_BDZLR, "bdzlr" }, { PPC_INS_BDZLRL, "bdzlrl" }, { PPC_INS_BL, "bl" }, { PPC_INS_BLA, "bla" }, { PPC_INS_BLR, "blr" }, { PPC_INS_BLRL, "blrl" }, { PPC_INS_CMPD, "cmpd" }, { PPC_INS_CMPDI, "cmpdi" }, { PPC_INS_CMPLD, "cmpld" }, { PPC_INS_CMPLDI, "cmpldi" }, { PPC_INS_CMPLW, "cmplw" }, { PPC_INS_CMPLWI, "cmplwi" }, { PPC_INS_CMPW, "cmpw" }, { PPC_INS_CMPWI, "cmpwi" }, { PPC_INS_CNTLZD, "cntlzd" }, { PPC_INS_CNTLZW, "cntlzw" }, { PPC_INS_CREQV, "creqv" }, { PPC_INS_CRXOR, "crxor" }, { PPC_INS_CRAND, "crand" }, { PPC_INS_CRANDC, "crandc" }, { PPC_INS_CRNAND, "crnand" }, { PPC_INS_CRNOR, "crnor" }, { PPC_INS_CROR, "cror" }, { PPC_INS_CRORC, "crorc" }, { PPC_INS_DCBA, "dcba" }, { PPC_INS_DCBF, "dcbf" }, { PPC_INS_DCBI, "dcbi" }, { PPC_INS_DCBST, "dcbst" }, { PPC_INS_DCBT, "dcbt" }, { PPC_INS_DCBTST, "dcbtst" }, { PPC_INS_DCBZ, "dcbz" }, { PPC_INS_DCBZL, "dcbzl" }, { PPC_INS_DIVD, "divd" }, { PPC_INS_DIVDU, "divdu" }, { PPC_INS_DIVW, "divw" }, { PPC_INS_DIVWU, "divwu" }, { PPC_INS_DSS, "dss" }, { PPC_INS_DSSALL, "dssall" }, { PPC_INS_DST, "dst" }, { PPC_INS_DSTST, "dstst" }, { PPC_INS_DSTSTT, "dststt" }, { PPC_INS_DSTT, "dstt" }, { PPC_INS_EIEIO, "eieio" }, { PPC_INS_EQV, "eqv" }, { PPC_INS_EXTSB, "extsb" }, { PPC_INS_EXTSH, "extsh" }, { PPC_INS_EXTSW, "extsw" }, { PPC_INS_FABS, "fabs" }, { PPC_INS_FADD, "fadd" }, { PPC_INS_FADDS, "fadds" }, { PPC_INS_FCFID, "fcfid" }, { PPC_INS_FCFIDS, "fcfids" }, { PPC_INS_FCFIDU, "fcfidu" }, { PPC_INS_FCFIDUS, "fcfidus" }, { PPC_INS_FCMPU, "fcmpu" }, { PPC_INS_FCPSGN, "fcpsgn" }, { PPC_INS_FCTID, "fctid" }, { PPC_INS_FCTIDUZ, "fctiduz" }, { PPC_INS_FCTIDZ, "fctidz" }, { PPC_INS_FCTIW, "fctiw" }, { PPC_INS_FCTIWUZ, "fctiwuz" }, { PPC_INS_FCTIWZ, "fctiwz" }, { PPC_INS_FDIV, "fdiv" }, { PPC_INS_FDIVS, "fdivs" }, { PPC_INS_FMADD, "fmadd" }, { PPC_INS_FMADDS, "fmadds" }, { PPC_INS_FMR, "fmr" }, { PPC_INS_FMSUB, "fmsub" }, { PPC_INS_FMSUBS, "fmsubs" }, { PPC_INS_FMUL, "fmul" }, { PPC_INS_FMULS, "fmuls" }, { PPC_INS_FNABS, "fnabs" }, { PPC_INS_FNEG, "fneg" }, { PPC_INS_FNMADD, "fnmadd" }, { PPC_INS_FNMADDS, "fnmadds" }, { PPC_INS_FNMSUB, "fnmsub" }, { PPC_INS_FNMSUBS, "fnmsubs" }, { PPC_INS_FRE, "fre" }, { PPC_INS_FRES, "fres" }, { PPC_INS_FRIM, "frim" }, { PPC_INS_FRIN, "frin" }, { PPC_INS_FRIP, "frip" }, { PPC_INS_FRIZ, "friz" }, { PPC_INS_FRSP, "frsp" }, { PPC_INS_FRSQRTE, "frsqrte" }, { PPC_INS_FRSQRTES, "frsqrtes" }, { PPC_INS_FSEL, "fsel" }, { PPC_INS_FSQRT, "fsqrt" }, { PPC_INS_FSQRTS, "fsqrts" }, { PPC_INS_FSUB, "fsub" }, { PPC_INS_FSUBS, "fsubs" }, { PPC_INS_ICBI, "icbi" }, { PPC_INS_ISEL, "isel" }, { PPC_INS_ISYNC, "isync" }, { PPC_INS_LA, "la" }, { PPC_INS_LBZ, "lbz" }, { PPC_INS_LBZU, "lbzu" }, { PPC_INS_LBZUX, "lbzux" }, { PPC_INS_LBZX, "lbzx" }, { PPC_INS_LD, "ld" }, { PPC_INS_LDARX, "ldarx" }, { PPC_INS_LDBRX, "ldbrx" }, { PPC_INS_LDU, "ldu" }, { PPC_INS_LDUX, "ldux" }, { PPC_INS_LDX, "ldx" }, { PPC_INS_LFD, "lfd" }, { PPC_INS_LFDU, "lfdu" }, { PPC_INS_LFDUX, "lfdux" }, { PPC_INS_LFDX, "lfdx" }, { PPC_INS_LFIWAX, "lfiwax" }, { PPC_INS_LFIWZX, "lfiwzx" }, { PPC_INS_LFS, "lfs" }, { PPC_INS_LFSU, "lfsu" }, { PPC_INS_LFSUX, "lfsux" }, { PPC_INS_LFSX, "lfsx" }, { PPC_INS_LHA, "lha" }, { PPC_INS_LHAU, "lhau" }, { PPC_INS_LHAUX, "lhaux" }, { PPC_INS_LHAX, "lhax" }, { PPC_INS_LHBRX, "lhbrx" }, { PPC_INS_LHZ, "lhz" }, { PPC_INS_LHZU, "lhzu" }, { PPC_INS_LHZUX, "lhzux" }, { PPC_INS_LHZX, "lhzx" }, { PPC_INS_LI, "li" }, { PPC_INS_LIS, "lis" }, { PPC_INS_LMW, "lmw" }, { PPC_INS_LVEBX, "lvebx" }, { PPC_INS_LVEHX, "lvehx" }, { PPC_INS_LVEWX, "lvewx" }, { PPC_INS_LVSL, "lvsl" }, { PPC_INS_LVSR, "lvsr" }, { PPC_INS_LVX, "lvx" }, { PPC_INS_LVXL, "lvxl" }, { PPC_INS_LWA, "lwa" }, { PPC_INS_LWARX, "lwarx" }, { PPC_INS_LWAUX, "lwaux" }, { PPC_INS_LWAX, "lwax" }, { PPC_INS_LWBRX, "lwbrx" }, { PPC_INS_LWZ, "lwz" }, { PPC_INS_LWZU, "lwzu" }, { PPC_INS_LWZUX, "lwzux" }, { PPC_INS_LWZX, "lwzx" }, { PPC_INS_MCRF, "mcrf" }, { PPC_INS_MFCR, "mfcr" }, { PPC_INS_MFCTR, "mfctr" }, { PPC_INS_MFFS, "mffs" }, { PPC_INS_MFLR, "mflr" }, { PPC_INS_MFMSR, "mfmsr" }, { PPC_INS_MFOCRF, "mfocrf" }, { PPC_INS_MFSPR, "mfspr" }, { PPC_INS_MFTB, "mftb" }, { PPC_INS_MFVSCR, "mfvscr" }, { PPC_INS_MSYNC, "msync" }, { PPC_INS_MTCRF, "mtcrf" }, { PPC_INS_MTCTR, "mtctr" }, { PPC_INS_MTFSB0, "mtfsb0" }, { PPC_INS_MTFSB1, "mtfsb1" }, { PPC_INS_MTFSF, "mtfsf" }, { PPC_INS_MTLR, "mtlr" }, { PPC_INS_MTMSR, "mtmsr" }, { PPC_INS_MTMSRD, "mtmsrd" }, { PPC_INS_MTOCRF, "mtocrf" }, { PPC_INS_MTSPR, "mtspr" }, { PPC_INS_MTVSCR, "mtvscr" }, { PPC_INS_MULHD, "mulhd" }, { PPC_INS_MULHDU, "mulhdu" }, { PPC_INS_MULHW, "mulhw" }, { PPC_INS_MULHWU, "mulhwu" }, { PPC_INS_MULLD, "mulld" }, { PPC_INS_MULLI, "mulli" }, { PPC_INS_MULLW, "mullw" }, { PPC_INS_NAND, "nand" }, { PPC_INS_NEG, "neg" }, { PPC_INS_NOP, "nop" }, { PPC_INS_ORI, "ori" }, { PPC_INS_NOR, "nor" }, { PPC_INS_OR, "or" }, { PPC_INS_ORC, "orc" }, { PPC_INS_ORIS, "oris" }, { PPC_INS_POPCNTD, "popcntd" }, { PPC_INS_POPCNTW, "popcntw" }, { PPC_INS_RLDCL, "rldcl" }, { PPC_INS_RLDCR, "rldcr" }, { PPC_INS_RLDIC, "rldic" }, { PPC_INS_RLDICL, "rldicl" }, { PPC_INS_RLDICR, "rldicr" }, { PPC_INS_RLDIMI, "rldimi" }, { PPC_INS_RLWIMI, "rlwimi" }, { PPC_INS_RLWINM, "rlwinm" }, { PPC_INS_RLWNM, "rlwnm" }, { PPC_INS_SC, "sc" }, { PPC_INS_SLBIA, "slbia" }, { PPC_INS_SLBIE, "slbie" }, { PPC_INS_SLBMFEE, "slbmfee" }, { PPC_INS_SLBMTE, "slbmte" }, { PPC_INS_SLD, "sld" }, { PPC_INS_SLW, "slw" }, { PPC_INS_SRAD, "srad" }, { PPC_INS_SRADI, "sradi" }, { PPC_INS_SRAW, "sraw" }, { PPC_INS_SRAWI, "srawi" }, { PPC_INS_SRD, "srd" }, { PPC_INS_SRW, "srw" }, { PPC_INS_STB, "stb" }, { PPC_INS_STBU, "stbu" }, { PPC_INS_STBUX, "stbux" }, { PPC_INS_STBX, "stbx" }, { PPC_INS_STD, "std" }, { PPC_INS_STDBRX, "stdbrx" }, { PPC_INS_STDCX, "stdcx" }, { PPC_INS_STDU, "stdu" }, { PPC_INS_STDUX, "stdux" }, { PPC_INS_STDX, "stdx" }, { PPC_INS_STFD, "stfd" }, { PPC_INS_STFDU, "stfdu" }, { PPC_INS_STFDUX, "stfdux" }, { PPC_INS_STFDX, "stfdx" }, { PPC_INS_STFIWX, "stfiwx" }, { PPC_INS_STFS, "stfs" }, { PPC_INS_STFSU, "stfsu" }, { PPC_INS_STFSUX, "stfsux" }, { PPC_INS_STFSX, "stfsx" }, { PPC_INS_STH, "sth" }, { PPC_INS_STHBRX, "sthbrx" }, { PPC_INS_STHU, "sthu" }, { PPC_INS_STHUX, "sthux" }, { PPC_INS_STHX, "sthx" }, { PPC_INS_STMW, "stmw" }, { PPC_INS_STVEBX, "stvebx" }, { PPC_INS_STVEHX, "stvehx" }, { PPC_INS_STVEWX, "stvewx" }, { PPC_INS_STVX, "stvx" }, { PPC_INS_STVXL, "stvxl" }, { PPC_INS_STW, "stw" }, { PPC_INS_STWBRX, "stwbrx" }, { PPC_INS_STWCX, "stwcx" }, { PPC_INS_STWU, "stwu" }, { PPC_INS_STWUX, "stwux" }, { PPC_INS_STWX, "stwx" }, { PPC_INS_SUBF, "subf" }, { PPC_INS_SUBFC, "subfc" }, { PPC_INS_SUBFE, "subfe" }, { PPC_INS_SUBFIC, "subfic" }, { PPC_INS_SUBFME, "subfme" }, { PPC_INS_SUBFZE, "subfze" }, { PPC_INS_SYNC, "sync" }, { PPC_INS_TD, "td" }, { PPC_INS_TDI, "tdi" }, { PPC_INS_TLBIE, "tlbie" }, { PPC_INS_TLBIEL, "tlbiel" }, { PPC_INS_TLBSYNC, "tlbsync" }, { PPC_INS_TRAP, "trap" }, { PPC_INS_TW, "tw" }, { PPC_INS_TWI, "twi" }, { PPC_INS_VADDCUW, "vaddcuw" }, { PPC_INS_VADDFP, "vaddfp" }, { PPC_INS_VADDSBS, "vaddsbs" }, { PPC_INS_VADDSHS, "vaddshs" }, { PPC_INS_VADDSWS, "vaddsws" }, { PPC_INS_VADDUBM, "vaddubm" }, { PPC_INS_VADDUBS, "vaddubs" }, { PPC_INS_VADDUHM, "vadduhm" }, { PPC_INS_VADDUHS, "vadduhs" }, { PPC_INS_VADDUWM, "vadduwm" }, { PPC_INS_VADDUWS, "vadduws" }, { PPC_INS_VAND, "vand" }, { PPC_INS_VANDC, "vandc" }, { PPC_INS_VAVGSB, "vavgsb" }, { PPC_INS_VAVGSH, "vavgsh" }, { PPC_INS_VAVGSW, "vavgsw" }, { PPC_INS_VAVGUB, "vavgub" }, { PPC_INS_VAVGUH, "vavguh" }, { PPC_INS_VAVGUW, "vavguw" }, { PPC_INS_VCFSX, "vcfsx" }, { PPC_INS_VCFUX, "vcfux" }, { PPC_INS_VCMPBFP, "vcmpbfp" }, { PPC_INS_VCMPEQFP, "vcmpeqfp" }, { PPC_INS_VCMPEQUB, "vcmpequb" }, { PPC_INS_VCMPEQUH, "vcmpequh" }, { PPC_INS_VCMPEQUW, "vcmpequw" }, { PPC_INS_VCMPGEFP, "vcmpgefp" }, { PPC_INS_VCMPGTFP, "vcmpgtfp" }, { PPC_INS_VCMPGTSB, "vcmpgtsb" }, { PPC_INS_VCMPGTSH, "vcmpgtsh" }, { PPC_INS_VCMPGTSW, "vcmpgtsw" }, { PPC_INS_VCMPGTUB, "vcmpgtub" }, { PPC_INS_VCMPGTUH, "vcmpgtuh" }, { PPC_INS_VCMPGTUW, "vcmpgtuw" }, { PPC_INS_VCTSXS, "vctsxs" }, { PPC_INS_VCTUXS, "vctuxs" }, { PPC_INS_VEXPTEFP, "vexptefp" }, { PPC_INS_VLOGEFP, "vlogefp" }, { PPC_INS_VMADDFP, "vmaddfp" }, { PPC_INS_VMAXFP, "vmaxfp" }, { PPC_INS_VMAXSB, "vmaxsb" }, { PPC_INS_VMAXSH, "vmaxsh" }, { PPC_INS_VMAXSW, "vmaxsw" }, { PPC_INS_VMAXUB, "vmaxub" }, { PPC_INS_VMAXUH, "vmaxuh" }, { PPC_INS_VMAXUW, "vmaxuw" }, { PPC_INS_VMHADDSHS, "vmhaddshs" }, { PPC_INS_VMHRADDSHS, "vmhraddshs" }, { PPC_INS_VMINFP, "vminfp" }, { PPC_INS_VMINSB, "vminsb" }, { PPC_INS_VMINSH, "vminsh" }, { PPC_INS_VMINSW, "vminsw" }, { PPC_INS_VMINUB, "vminub" }, { PPC_INS_VMINUH, "vminuh" }, { PPC_INS_VMINUW, "vminuw" }, { PPC_INS_VMLADDUHM, "vmladduhm" }, { PPC_INS_VMRGHB, "vmrghb" }, { PPC_INS_VMRGHH, "vmrghh" }, { PPC_INS_VMRGHW, "vmrghw" }, { PPC_INS_VMRGLB, "vmrglb" }, { PPC_INS_VMRGLH, "vmrglh" }, { PPC_INS_VMRGLW, "vmrglw" }, { PPC_INS_VMSUMMBM, "vmsummbm" }, { PPC_INS_VMSUMSHM, "vmsumshm" }, { PPC_INS_VMSUMSHS, "vmsumshs" }, { PPC_INS_VMSUMUBM, "vmsumubm" }, { PPC_INS_VMSUMUHM, "vmsumuhm" }, { PPC_INS_VMSUMUHS, "vmsumuhs" }, { PPC_INS_VMULESB, "vmulesb" }, { PPC_INS_VMULESH, "vmulesh" }, { PPC_INS_VMULEUB, "vmuleub" }, { PPC_INS_VMULEUH, "vmuleuh" }, { PPC_INS_VMULOSB, "vmulosb" }, { PPC_INS_VMULOSH, "vmulosh" }, { PPC_INS_VMULOUB, "vmuloub" }, { PPC_INS_VMULOUH, "vmulouh" }, { PPC_INS_VNMSUBFP, "vnmsubfp" }, { PPC_INS_VNOR, "vnor" }, { PPC_INS_VOR, "vor" }, { PPC_INS_VPERM, "vperm" }, { PPC_INS_VPKPX, "vpkpx" }, { PPC_INS_VPKSHSS, "vpkshss" }, { PPC_INS_VPKSHUS, "vpkshus" }, { PPC_INS_VPKSWSS, "vpkswss" }, { PPC_INS_VPKSWUS, "vpkswus" }, { PPC_INS_VPKUHUM, "vpkuhum" }, { PPC_INS_VPKUHUS, "vpkuhus" }, { PPC_INS_VPKUWUM, "vpkuwum" }, { PPC_INS_VPKUWUS, "vpkuwus" }, { PPC_INS_VREFP, "vrefp" }, { PPC_INS_VRFIM, "vrfim" }, { PPC_INS_VRFIN, "vrfin" }, { PPC_INS_VRFIP, "vrfip" }, { PPC_INS_VRFIZ, "vrfiz" }, { PPC_INS_VRLB, "vrlb" }, { PPC_INS_VRLH, "vrlh" }, { PPC_INS_VRLW, "vrlw" }, { PPC_INS_VRSQRTEFP, "vrsqrtefp" }, { PPC_INS_VSEL, "vsel" }, { PPC_INS_VSL, "vsl" }, { PPC_INS_VSLB, "vslb" }, { PPC_INS_VSLDOI, "vsldoi" }, { PPC_INS_VSLH, "vslh" }, { PPC_INS_VSLO, "vslo" }, { PPC_INS_VSLW, "vslw" }, { PPC_INS_VSPLTB, "vspltb" }, { PPC_INS_VSPLTH, "vsplth" }, { PPC_INS_VSPLTISB, "vspltisb" }, { PPC_INS_VSPLTISH, "vspltish" }, { PPC_INS_VSPLTISW, "vspltisw" }, { PPC_INS_VSPLTW, "vspltw" }, { PPC_INS_VSR, "vsr" }, { PPC_INS_VSRAB, "vsrab" }, { PPC_INS_VSRAH, "vsrah" }, { PPC_INS_VSRAW, "vsraw" }, { PPC_INS_VSRB, "vsrb" }, { PPC_INS_VSRH, "vsrh" }, { PPC_INS_VSRO, "vsro" }, { PPC_INS_VSRW, "vsrw" }, { PPC_INS_VSUBCUW, "vsubcuw" }, { PPC_INS_VSUBFP, "vsubfp" }, { PPC_INS_VSUBSBS, "vsubsbs" }, { PPC_INS_VSUBSHS, "vsubshs" }, { PPC_INS_VSUBSWS, "vsubsws" }, { PPC_INS_VSUBUBM, "vsububm" }, { PPC_INS_VSUBUBS, "vsububs" }, { PPC_INS_VSUBUHM, "vsubuhm" }, { PPC_INS_VSUBUHS, "vsubuhs" }, { PPC_INS_VSUBUWM, "vsubuwm" }, { PPC_INS_VSUBUWS, "vsubuws" }, { PPC_INS_VSUM2SWS, "vsum2sws" }, { PPC_INS_VSUM4SBS, "vsum4sbs" }, { PPC_INS_VSUM4SHS, "vsum4shs" }, { PPC_INS_VSUM4UBS, "vsum4ubs" }, { PPC_INS_VSUMSWS, "vsumsws" }, { PPC_INS_VUPKHPX, "vupkhpx" }, { PPC_INS_VUPKHSB, "vupkhsb" }, { PPC_INS_VUPKHSH, "vupkhsh" }, { PPC_INS_VUPKLPX, "vupklpx" }, { PPC_INS_VUPKLSB, "vupklsb" }, { PPC_INS_VUPKLSH, "vupklsh" }, { PPC_INS_VXOR, "vxor" }, { PPC_INS_WAIT, "wait" }, { PPC_INS_XOR, "xor" }, { PPC_INS_XORI, "xori" }, { PPC_INS_XORIS, "xoris" }, { PPC_INS_BC, "bc" }, { PPC_INS_BCA, "bca" }, { PPC_INS_BCCTR, "bcctr" }, { PPC_INS_BCCTRL, "bcctrl" }, { PPC_INS_BCLA, "bcla" }, { PPC_INS_BCLR, "bclr" }, { PPC_INS_BCLRL, "bclrl" }, }; // special alias insn static name_map alias_insn_names[] = { { 0, NULL } }; #endif const char *PPC_insn_name(csh handle, unsigned int id) { #ifndef CAPSTONE_DIET unsigned int i; if (id >= PPC_INS_MAX) return NULL; // handle special alias first for (i = 0; i < ARR_SIZE(alias_insn_names); i++) { if (alias_insn_names[i].id == id) return alias_insn_names[i].name; } return insn_name_maps[id].name; #else return NULL; #endif } // map internal raw register to 'public' register ppc_reg PPC_map_register(unsigned int r) { static unsigned int map[] = { 0, 0, PPC_REG_CARRY, PPC_REG_CTR, 0, PPC_REG_LR, 0, PPC_REG_VRSAVE, PPC_REG_CR0, 0, PPC_REG_CR0, PPC_REG_CR1, PPC_REG_CR2, PPC_REG_CR3, PPC_REG_CR4, PPC_REG_CR5, PPC_REG_CR6, PPC_REG_CR7, PPC_REG_CTR, PPC_REG_F0, PPC_REG_F1, PPC_REG_F2, PPC_REG_F3, PPC_REG_F4, PPC_REG_F5, PPC_REG_F6, PPC_REG_F7, PPC_REG_F8, PPC_REG_F9, PPC_REG_F10, PPC_REG_F11, PPC_REG_F12, PPC_REG_F13, PPC_REG_F14, PPC_REG_F15, PPC_REG_F16, PPC_REG_F17, PPC_REG_F18, PPC_REG_F19, PPC_REG_F20, PPC_REG_F21, PPC_REG_F22, PPC_REG_F23, PPC_REG_F24, PPC_REG_F25, PPC_REG_F26, PPC_REG_F27, PPC_REG_F28, PPC_REG_F29, PPC_REG_F30, PPC_REG_F31, 0, PPC_REG_LR, PPC_REG_R0, PPC_REG_R1, PPC_REG_R2, PPC_REG_R3, PPC_REG_R4, PPC_REG_R5, PPC_REG_R6, PPC_REG_R7, PPC_REG_R8, PPC_REG_R9, PPC_REG_R10, PPC_REG_R11, PPC_REG_R12, PPC_REG_R13, PPC_REG_R14, PPC_REG_R15, PPC_REG_R16, PPC_REG_R17, PPC_REG_R18, PPC_REG_R19, PPC_REG_R20, PPC_REG_R21, PPC_REG_R22, PPC_REG_R23, PPC_REG_R24, PPC_REG_R25, PPC_REG_R26, PPC_REG_R27, PPC_REG_R28, PPC_REG_R29, PPC_REG_R30, PPC_REG_R31, PPC_REG_V0, PPC_REG_V1, PPC_REG_V2, PPC_REG_V3, PPC_REG_V4, PPC_REG_V5, PPC_REG_V6, PPC_REG_V7, PPC_REG_V8, PPC_REG_V9, PPC_REG_V10, PPC_REG_V11, PPC_REG_V12, PPC_REG_V13, PPC_REG_V14, PPC_REG_V15, PPC_REG_V16, PPC_REG_V17, PPC_REG_V18, PPC_REG_V19, PPC_REG_V20, PPC_REG_V21, PPC_REG_V22, PPC_REG_V23, PPC_REG_V24, PPC_REG_V25, PPC_REG_V26, PPC_REG_V27, PPC_REG_V28, PPC_REG_V29, PPC_REG_V30, PPC_REG_V31, PPC_REG_R0, PPC_REG_R1, PPC_REG_R2, PPC_REG_R3, PPC_REG_R4, PPC_REG_R5, PPC_REG_R6, PPC_REG_R7, PPC_REG_R8, PPC_REG_R9, PPC_REG_R10, PPC_REG_R11, PPC_REG_R12, PPC_REG_R13, PPC_REG_R14, PPC_REG_R15, PPC_REG_R16, PPC_REG_R17, PPC_REG_R18, PPC_REG_R19, PPC_REG_R20, PPC_REG_R21, PPC_REG_R22, PPC_REG_R23, PPC_REG_R24, PPC_REG_R25, PPC_REG_R26, PPC_REG_R27, PPC_REG_R28, PPC_REG_R29, PPC_REG_R30, PPC_REG_R31, PPC_REG_CR0, PPC_REG_CR2, PPC_REG_CR6, PPC_REG_CR10, PPC_REG_CR14, PPC_REG_CR18, PPC_REG_CR22, PPC_REG_CR26, PPC_REG_CR30, PPC_REG_CR1, PPC_REG_CR5, PPC_REG_CR9, PPC_REG_CR13, PPC_REG_CR17, PPC_REG_CR21, PPC_REG_CR25, PPC_REG_CR29, PPC_REG_CR0, PPC_REG_CR4, PPC_REG_CR8, PPC_REG_CR12, PPC_REG_CR16, PPC_REG_CR20, PPC_REG_CR24, PPC_REG_CR28, PPC_REG_CR3, PPC_REG_CR7, PPC_REG_CR11, PPC_REG_CR15, PPC_REG_CR19, PPC_REG_CR23, PPC_REG_CR27, PPC_REG_CR31, }; if (r < ARR_SIZE(map)) return map[r]; // cannot find this register return 0; } #endif
the_stack_data/126703331.c
/* 16-bit Windows Selection processing for emacs on MS-Windows Copyright (C) 1996, 1997 Free Software Foundation. This file is part of GNU Emacs. GNU Emacs is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* These functions work by using WinOldAp interface. WinOldAp (WINOLDAP.MOD) is a Microsoft Windows extension supporting "old" (character-mode) application access to Dynamic Data Exchange, menus, and the Windows clipboard. */ /* Written by Dale P. Smith <[email protected]> */ /* Adapted to DJGPP v1 by Eli Zaretskii <[email protected]> */ #ifdef MSDOS #include <config.h> #include <string.h> #include <dpmi.h> #include <go32.h> #include <sys/farptr.h> #include "lisp.h" #include "dispextern.h" /* frame.h seems to want this */ #include "frame.h" /* Need this to get the X window of selected_frame */ #include "blockinput.h" #include "buffer.h" #include "charset.h" #include "coding.h" /* If ever some function outside this file will need to call any clipboard-related function, the following prototypes and constants should be put on a header file. Right now, nobody else uses them. */ #define CF_TEXT 0x01 #define CF_BITMAP 0x02 #define CF_METAFILE 0x03 #define CF_SYLK 0x04 #define CF_DIF 0x05 #define CF_TIFF 0x06 #define CF_OEMTEXT 0x07 #define CF_DIBBITMAP 0x08 #define CF_WINWRITE 0x80 #define CF_DSPTEXT 0x81 #define CF_DSPBITMAP 0x82 unsigned identify_winoldap_version (void); unsigned open_clipboard (void); unsigned empty_clipboard (void); unsigned set_clipboard_data (unsigned, void *, unsigned, int); unsigned get_clipboard_data_size (unsigned); unsigned get_clipboard_data (unsigned, void *, unsigned, int); unsigned close_clipboard (void); unsigned clipboard_compact (unsigned); Lisp_Object QCLIPBOARD, QPRIMARY; /* Coding system for communicating with other Windows programs via the clipboard. */ static Lisp_Object Vselection_coding_system; /* Coding system for the next communicating with other Windows programs. */ static Lisp_Object Vnext_selection_coding_system; /* The segment address and the size of the buffer in low memory used to move data between us and WinOldAp module. */ static struct { unsigned long size; unsigned short rm_segment; } clipboard_xfer_buf_info; /* The last text we put into the clipboard. This is used to prevent passing back our own text from the clipboard, instead of using the kill ring. The former is undesirable because the clipboard data could be MULEtilated by inappropriately chosen (next-)selection-coding-system. For this reason, we must store the text *after* it was encoded/Unix-to-DOS-converted. */ static unsigned char *last_clipboard_text; /* The size of allocated storage for storing the clipboard data. */ static size_t clipboard_storage_size; /* Emulation of `__dpmi_int' and friends for DJGPP v1.x */ #if __DJGPP__ < 2 typedef _go32_dpmi_registers __dpmi_regs; #define __tb _go32_info_block.linear_address_of_transfer_buffer #define _dos_ds _go32_info_block.selector_for_linear_memory static int __dpmi_int (intno, regs) int intno; __dpmi_regs *regs; { regs->x.ss = regs->x.sp = regs->x.flags = 0; return _go32_dpmi_simulate_int (intno, regs); } #endif /* __DJGPP__ < 2 */ /* C functions to access the Windows 3.1x clipboard from DOS apps. The information was obtained from the Microsoft Knowledge Base, article Q67675 and can be found at: http://www.microsoft.com/kb/developr/win_dk/q67675.htm */ /* See also Ralf Brown's Interrupt List. I also seem to remember reading about this in Dr. Dobbs Journal a while ago, but if you knew my memory... :-) Dale P. Smith <[email protected]> */ /* Return the WinOldAp support version, or 0x1700 if not supported. */ unsigned identify_winoldap_version () { __dpmi_regs regs; /* Calls Int 2Fh/AX=1700h Return Values AX == 1700H: Clipboard functions not available <> 1700H: AL = Major version number AH = Minor version number */ regs.x.ax = 0x1700; __dpmi_int(0x2f, &regs); return regs.x.ax; } /* Open the clipboard, return non-zero if successfull. */ unsigned open_clipboard () { __dpmi_regs regs; /* Is WINOLDAP supported? */ /* Kludge alert!! If WinOldAp is not supported, we return a 0, which is the same as ``Clipboard already open''. Currently, this is taken as an error by all the functions that use `open_clipboard', but if somebody someday will use that ``open'' clipboard, they will have interesting time debugging it... */ if (identify_winoldap_version () == 0x1700) return 0; /* Calls Int 2Fh/AX=1701h Return Values AX == 0: Clipboard already open <> 0: Clipboard opened */ regs.x.ax = 0x1701; __dpmi_int(0x2f, &regs); return regs.x.ax; } /* Empty clipboard, return non-zero if successfull. */ unsigned empty_clipboard () { __dpmi_regs regs; /* Calls Int 2Fh/AX=1702h Return Values AX == 0: Error occurred <> 0: OK, Clipboard emptied */ regs.x.ax = 0x1702; __dpmi_int(0x2f, &regs); return regs.x.ax; } /* Ensure we have a buffer in low memory with enough memory for data of size WANT_SIZE. Return the linear address of the buffer. */ static unsigned long alloc_xfer_buf (want_size) unsigned want_size; { __dpmi_regs regs; /* If the usual DJGPP transfer buffer is large enough, use that. */ if (want_size <= _go32_info_block.size_of_transfer_buffer) return __tb & 0xfffff; /* Don't even try to allocate more than 1MB of memory: DOS cannot possibly handle that (it will overflow the BX register below). */ if (want_size > 0xfffff) return 0; /* Need size rounded up to the nearest paragraph, and in paragraph units (1 paragraph = 16 bytes). */ clipboard_xfer_buf_info.size = (want_size + 15) >> 4; /* The NT DPMI host crashes us if we free DOS memory via the DPMI service. Work around by calling DOS allocate/free block. */ regs.h.ah = 0x48; regs.x.bx = clipboard_xfer_buf_info.size; __dpmi_int (0x21, &regs); if (regs.x.flags & 1) { clipboard_xfer_buf_info.size = 0; return 0; } clipboard_xfer_buf_info.rm_segment = regs.x.ax; return (((int)clipboard_xfer_buf_info.rm_segment) << 4) & 0xfffff; } /* Free our clipboard buffer. We always free it after use, because keeping it leaves less free conventional memory for subprocesses. The clipboard buffer tends to be large in size, because for small clipboard data sizes we use the DJGPP transfer buffer. */ static void free_xfer_buf () { /* If the size is 0, we used DJGPP transfer buffer, so don't free. */ if (clipboard_xfer_buf_info.size) { __dpmi_regs regs; /* The NT DPMI host crashes us if we free DOS memory via the DPMI service. Work around by calling DOS free block. */ regs.h.ah = 0x49; regs.x.es = clipboard_xfer_buf_info.rm_segment; __dpmi_int (0x21, &regs); clipboard_xfer_buf_info.size = 0; } } /* Copy data into the clipboard, return zero if successfull. */ unsigned set_clipboard_data (Format, Data, Size, Raw) unsigned Format; void *Data; unsigned Size; int Raw; { __dpmi_regs regs; unsigned truelen; unsigned long xbuf_addr, buf_offset; unsigned char *dp = Data, *dstart = dp; if (Format != CF_OEMTEXT) return 0; /* need to know final size after '\r' chars are inserted (the standard CF_OEMTEXT clipboard format uses CRLF line endings, while Emacs uses just LF internally). */ truelen = Size + 1; /* +1 for the terminating null */ if (!Raw) { /* avoid using strchr because it recomputes the length everytime */ while ((dp = memchr (dp, '\n', Size - (dp - dstart))) != 0) { truelen++; dp++; } } if (clipboard_compact (truelen) < truelen) return 0; if ((xbuf_addr = alloc_xfer_buf (truelen)) == 0) return 0; /* Move the buffer into the low memory, convert LF into CR-LF if needed. */ if (Raw) { dosmemput (Data, Size, xbuf_addr); /* Terminate with a null, otherwise Windows does strange things when the text size is an integral multiple of 32 bytes. */ _farpokeb (_dos_ds, xbuf_addr + Size, '\0'); } else { dp = Data; buf_offset = xbuf_addr; _farsetsel (_dos_ds); while (Size--) { /* Don't allow them to put binary data into the clipboard, since it will cause yanked data to be truncated at the first null. */ if (*dp == '\0') return 2; if (*dp == '\n') _farnspokeb (buf_offset++, '\r'); _farnspokeb (buf_offset++, *dp++); } /* Terminate with a null, otherwise Windows does strange things when the text size is an integral multiple of 32 bytes. */ _farnspokeb (buf_offset, '\0'); } /* Stash away the data we are about to put into the clipboard, so we could later check inside get_clipboard_data whether the clipboard still holds our data. */ if (clipboard_storage_size < truelen) { clipboard_storage_size = truelen + 100; last_clipboard_text = (char *) xrealloc (last_clipboard_text, clipboard_storage_size); } if (last_clipboard_text) dosmemget (xbuf_addr, truelen, last_clipboard_text); /* Calls Int 2Fh/AX=1703h with: DX = WinOldAp-Supported Clipboard format ES:BX = Pointer to data SI:CX = Size of data in bytes Return Values AX == 0: Error occurred <> 0: OK. Data copied into the Clipboard. */ regs.x.ax = 0x1703; regs.x.dx = Format; regs.x.si = truelen >> 16; regs.x.cx = truelen & 0xffff; regs.x.es = xbuf_addr >> 4; regs.x.bx = xbuf_addr & 15; __dpmi_int(0x2f, &regs); free_xfer_buf (); /* If the above failed, invalidate the local copy of the clipboard. */ if (regs.x.ax == 0) *last_clipboard_text = '\0'; /* Zero means success, otherwise (1 or 2) it's an error. */ return regs.x.ax > 0 ? 0 : 1; } /* Return the size of the clipboard data of format FORMAT. */ unsigned get_clipboard_data_size (Format) unsigned Format; { __dpmi_regs regs; /* Calls Int 2Fh/AX=1704h with: DX = WinOldAp-Supported Clipboard format Return Values DX:AX == Size of the data in bytes, including any headers. == 0 If data in this format is not in the clipboard. */ regs.x.ax = 0x1704; regs.x.dx = Format; __dpmi_int(0x2f, &regs); return ( (((unsigned)regs.x.dx) << 16) | regs.x.ax); } /* Get clipboard data, return its length. Warning: this doesn't check whether DATA has enough space to hold SIZE bytes. */ unsigned get_clipboard_data (Format, Data, Size, Raw) unsigned Format; void *Data; unsigned Size; int Raw; { __dpmi_regs regs; unsigned long xbuf_addr; unsigned char *dp = Data; if (Format != CF_OEMTEXT) return 0; if (Size == 0) return 0; if ((xbuf_addr = alloc_xfer_buf (Size)) == 0) return 0; /* Calls Int 2Fh/AX=1705h with: DX = WinOldAp-Supported Clipboard format ES:BX = Pointer to data buffer to hold data Return Values AX == 0: Error occurred (or data in this format is not in the clipboard) <> 0: OK */ regs.x.ax = 0x1705; regs.x.dx = Format; regs.x.es = xbuf_addr >> 4; regs.x.bx = xbuf_addr & 15; __dpmi_int(0x2f, &regs); if (regs.x.ax != 0) { unsigned char null_char = '\0'; unsigned long xbuf_beg = xbuf_addr; /* If last_clipboard_text is NULL, we don't want to slow down the next loop by an additional test. */ register unsigned char *lcdp = last_clipboard_text == NULL ? &null_char : last_clipboard_text; /* Copy data from low memory, remove CR characters before LF if needed. */ _farsetsel (_dos_ds); while (Size--) { register unsigned char c = _farnspeekb (xbuf_addr++); if (*lcdp == c) lcdp++; if ((*dp++ = c) == '\r' && !Raw && _farnspeekb (xbuf_addr) == '\n') { dp--; *dp++ = '\n'; xbuf_addr++; if (*lcdp == '\n') lcdp++; } /* Windows reportedly rounds up the size of clipboard data (passed in SIZE) to a multiple of 32, and removes trailing spaces from each line without updating SIZE. We therefore bail out when we see the first null character. */ else if (c == '\0') break; } /* If the text in clipboard is identical to what we put there last time set_clipboard_data was called, pretend there's no data in the clipboard. This is so we don't pass our own text from the clipboard (which might be troublesome if the killed text includes null characters). */ if (last_clipboard_text && xbuf_addr - xbuf_beg == (long)(lcdp - last_clipboard_text)) dp = (unsigned char *)Data + 1; } free_xfer_buf (); return (unsigned) (dp - (unsigned char *)Data - 1); } /* Close clipboard, return non-zero if successfull. */ unsigned close_clipboard () { __dpmi_regs regs; /* Calls Int 2Fh/AX=1708h Return Values AX == 0: Error occurred <> 0: OK */ regs.x.ax = 0x1708; __dpmi_int(0x2f, &regs); return regs.x.ax; } /* Compact clipboard data so that at least SIZE bytes is available. */ unsigned clipboard_compact (Size) unsigned Size; { __dpmi_regs regs; /* Calls Int 2Fh/AX=1709H with: SI:CX = Desired memory size in bytes. Return Values DX:AX == Number of bytes of largest block of free memory. == 0 if error or no memory */ regs.x.ax = 0x1709; regs.x.si = Size >> 16; regs.x.cx = Size & 0xffff; __dpmi_int(0x2f, &regs); return ((unsigned)regs.x.dx << 16) | regs.x.ax; } static char no_mem_msg[] = "(Not enough DOS memory to put saved text into clipboard.)"; static char binary_msg[] = "(Binary characters in saved text; clipboard data not set.)"; DEFUN ("w16-set-clipboard-data", Fw16_set_clipboard_data, Sw16_set_clipboard_data, 1, 2, 0, "This sets the clipboard data to the given text.") (string, frame) Lisp_Object string, frame; { unsigned ok = 1, put_status = 0; int nbytes; unsigned char *src, *dst = NULL; int charsets[MAX_CHARSET + 1]; int num; int no_crlf_conversion; CHECK_STRING (string, 0); if (NILP (frame)) frame = Fselected_frame (); CHECK_LIVE_FRAME (frame, 0); if ( !FRAME_MSDOS_P (XFRAME (frame))) goto done; BLOCK_INPUT; nbytes = STRING_BYTES (XSTRING (string)); src = XSTRING (string)->data; /* Since we are now handling multilingual text, we must consider encoding text for the clipboard. */ bzero (charsets, (MAX_CHARSET + 1) * sizeof (int)); num = ((nbytes <= 1 /* Check the possibility of short cut. */ || !STRING_MULTIBYTE (string) || nbytes == XSTRING (string)->size) ? 0 : find_charset_in_str (src, nbytes, charsets, Qnil, 0, 1)); if (!num || (num == 1 && charsets[CHARSET_ASCII])) { /* No multibyte character in OBJ. We need not encode it, but we will have to convert it to DOS CR-LF style. */ no_crlf_conversion = 0; } else { /* We must encode contents of STRING according to what clipboard-coding-system specifies. */ int bufsize; struct coding_system coding; unsigned char *htext2; if (NILP (Vnext_selection_coding_system)) Vnext_selection_coding_system = Vselection_coding_system; setup_coding_system (Fcheck_coding_system (Vnext_selection_coding_system), &coding); Vnext_selection_coding_system = Qnil; coding.mode |= CODING_MODE_LAST_BLOCK; Vlast_coding_system_used = coding.symbol; bufsize = encoding_buffer_size (&coding, nbytes); dst = (unsigned char *) xmalloc (bufsize); encode_coding (&coding, src, dst, nbytes, bufsize); no_crlf_conversion = 1; nbytes = coding.produced; src = dst; } if (!open_clipboard ()) goto error; ok = empty_clipboard () && ((put_status = set_clipboard_data (CF_OEMTEXT, src, nbytes, no_crlf_conversion)) == 0); if (!no_crlf_conversion) Vlast_coding_system_used = Qraw_text; close_clipboard (); if (ok) goto unblock; error: ok = 0; unblock: if (dst) xfree (dst); UNBLOCK_INPUT; /* Notify user if the text is too large to fit into DOS memory. (This will happen somewhere after 600K bytes (470K in DJGPP v1.x), depending on user system configuration.) If we just silently fail the function, people might wonder why their text sometimes doesn't make it to the clipboard. */ if (put_status) { switch (put_status) { case 1: message2 (no_mem_msg, sizeof (no_mem_msg) - 1, 0); break; case 2: message2 (binary_msg, sizeof (binary_msg) - 1, 0); break; } sit_for (2, 0, 0, 1, 1); } done: return (ok && put_status == 0 ? string : Qnil); } DEFUN ("w16-get-clipboard-data", Fw16_get_clipboard_data, Sw16_get_clipboard_data, 0, 1, 0, "This gets the clipboard data in text format.") (frame) Lisp_Object frame; { unsigned data_size, truelen; unsigned char *htext; Lisp_Object ret = Qnil; int no_crlf_conversion; int require_encoding = 0; if (NILP (frame)) frame = Fselected_frame (); CHECK_LIVE_FRAME (frame, 0); if ( !FRAME_MSDOS_P (XFRAME (frame))) goto done; BLOCK_INPUT; if (!open_clipboard ()) goto unblock; if ((data_size = get_clipboard_data_size (CF_OEMTEXT)) == 0 || (htext = (unsigned char *)xmalloc (data_size)) == 0) goto closeclip; /* need to know final size after '\r' chars are removed because we can't change the string size manually, and doing an extra copy is silly */ if ((truelen = get_clipboard_data (CF_OEMTEXT, htext, data_size, 0)) == 0) goto closeclip; /* Do we need to decode it? */ if ( #if 1 1 #else ! NILP (buffer_defaults.enable_multibyte_characters) #endif ) { /* If the clipboard data contains any 8-bit Latin-1 code, we need to decode it. */ int i; for (i = 0; i < truelen; i++) { if (htext[i] >= 0x80) { require_encoding = 1; break; } } } if (require_encoding) { int bufsize; unsigned char *buf; struct coding_system coding; if (NILP (Vnext_selection_coding_system)) Vnext_selection_coding_system = Vselection_coding_system; setup_coding_system (Fcheck_coding_system (Vnext_selection_coding_system), &coding); Vnext_selection_coding_system = Qnil; coding.mode |= CODING_MODE_LAST_BLOCK; truelen = get_clipboard_data (CF_OEMTEXT, htext, data_size, 1); bufsize = decoding_buffer_size (&coding, truelen); buf = (unsigned char *) xmalloc (bufsize); decode_coding (&coding, htext, buf, truelen, bufsize); truelen = (coding.fake_multibyte ? multibyte_chars_in_text (buf, coding.produced) : coding.produced_char); ret = make_string_from_bytes ((char *) buf, truelen, coding.produced); xfree (buf); Vlast_coding_system_used = coding.symbol; } else { ret = make_unibyte_string ((char *) htext, truelen); Vlast_coding_system_used = Qraw_text; } xfree (htext); closeclip: close_clipboard (); unblock: UNBLOCK_INPUT; done: return (ret); } /* Support checking for a clipboard selection. */ DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p, 0, 1, 0, "Whether there is an owner for the given X Selection.\n\ The arg should be the name of the selection in question, typically one of\n\ the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'.\n\ \(Those are literal upper-case symbol names, since that's what X expects.)\n\ For convenience, the symbol nil is the same as `PRIMARY',\n\ and t is the same as `SECONDARY'.") (selection) Lisp_Object selection; { CHECK_SYMBOL (selection, 0); /* Return nil for SECONDARY selection. For PRIMARY (or nil) selection, check if there is some text on the kill-ring; for CLIPBOARD, check if the clipboard currently has valid text format contents. The test for killed text on the kill-ring emulates the Emacs behavior on X, where killed text is also put into X selection by the X interface code. (On MSDOS, killed text is only put into the clipboard if we run under Windows, so we cannot check the clipboard alone.) */ if ((EQ (selection, Qnil) || EQ (selection, QPRIMARY)) && ! NILP (XSYMBOL (Fintern_soft (build_string ("kill-ring"), Qnil))->value)) return Qt; if (EQ (selection, QCLIPBOARD)) { Lisp_Object val = Qnil; if (open_clipboard ()) { if (get_clipboard_data_size (CF_OEMTEXT)) val = Qt; close_clipboard (); } return val; } return Qnil; } void syms_of_win16select () { defsubr (&Sw16_set_clipboard_data); defsubr (&Sw16_get_clipboard_data); defsubr (&Sx_selection_exists_p); DEFVAR_LISP ("selection-coding-system", &Vselection_coding_system, "Coding system for communicating with other X clients.\n\ When sending or receiving text via cut_buffer, selection, and clipboard,\n\ the text is encoded or decoded by this coding system.\n\ A default value is `iso-latin-1-dos'"); Vselection_coding_system=intern ("iso-latin-1-dos"); DEFVAR_LISP ("next-selection-coding-system", &Vnext_selection_coding_system, "Coding system for the next communication with other X clients.\n\ Usually, `selection-coding-system' is used for communicating with\n\ other X clients. But, if this variable is set, it is used for the\n\ next communication only. After the communication, this variable is\n\ set to nil."); Vnext_selection_coding_system = Qnil; QPRIMARY = intern ("PRIMARY"); staticpro (&QPRIMARY); QCLIPBOARD = intern ("CLIPBOARD"); staticpro (&QCLIPBOARD); } #endif /* MSDOS */
the_stack_data/100140827.c
#include <pthread.h> #include <unistd.h> #include <stdio.h> volatile long work_counter; int req_count; pthread_mutex_t q_lock; void grab_lock() { pthread_mutex_lock(&q_lock); } void ungrab_lock() { pthread_mutex_unlock(&q_lock); } void do_work() { for (int i = 0; i < 50000; ++i) ++work_counter; // Burn CPU } void * request_processor(void *dummy) { printf("[*] Request processor initialized.\n"); while (1) { grab_lock(); do_work(); ungrab_lock(); } return NULL; } void flush_work() { usleep(10000); // 10ms } void * backend_handler(void *dummy) { printf("[*] Backend handler initialized.\n"); while (1) { grab_lock(); ++req_count; if (req_count % 1000 == 0) { printf("[-] Handled %d requests.\n", req_count); } if (req_count % 37 == 0) { flush_work(); } ungrab_lock(); } return NULL; } #define NTHREADS 2 int main() { pthread_t req_processors[NTHREADS]; pthread_t backend; pthread_mutex_init(&q_lock, NULL); for (int i = 0; i < NTHREADS; ++i) { pthread_create(&req_processors[i], NULL, request_processor, NULL); } pthread_create(&backend, NULL, backend_handler, NULL); printf("[*] Ready to process requests.\n"); pthread_join(backend, NULL); printf("[*] Exiting.\n"); return 0; }
the_stack_data/92324845.c
/* $OpenBSD: pwrite.c,v 1.3 2003/09/02 23:52:17 david Exp $ */ /* * Written by Artur Grabowski <[email protected]> 2002 Public Domain. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <err.h> #include <fcntl.h> int main(int argc, char *argv[]) { char temp[] = "/tmp/pwriteXXXXXXXXX"; const char magic[10] = "0123456789"; const char zeroes[10] = "0000000000"; char buf[10]; char c; int fd; if ((fd = mkstemp(temp)) < 0) err(1, "mkstemp"); remove(temp); if (write(fd, zeroes, sizeof(zeroes)) != sizeof(zeroes)) err(1, "write"); if (lseek(fd, 5, SEEK_SET) != 5) err(1, "lseek"); if (pwrite(fd, &magic[1], 4, 4) != 4) err(1, "pwrite"); if (read(fd, &c, 1) != 1) err(1, "read"); if (c != '2') errx(1, "read %c != %c", c, '2'); c = '5'; if (write(fd, &c, 1) != 1) err(1, "write"); if (pread(fd, buf, 10, 0) != 10) err(1, "pread"); if (memcmp(buf, "0000125400", 10) != 0) errx(1, "data mismatch: %s != %s", buf, "0000125400"); return 0; }
the_stack_data/93887312.c
/* $NetBSD: refclock_ptbacts.c,v 1.2 1998/01/09 06:07:10 perry Exp $ */ /* * crude hack to avoid hard links in distribution * and keep only one ACTS type source for different * ACTS refclocks */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #if defined(REFCLOCK) && defined(PTBACTS) # define KEEPPTBACTS # include "refclock_acts.c" #else /* not (REFCLOCK && PTBACTS) */ int refclock_ptbacts_bs; #endif /* not (REFCLOCK && PTBACTS) */
the_stack_data/154830046.c
#include <stdio.h> #include <string.h> int main() { char str[10001], *p; int j = 0, i = 0; gets(str); for (p = strstr(str, "JOI"); p; j++) p = strstr(p + 3, "JOI"); for (p = strstr(str, "IOI"); p; i++) p = strstr(p + 2, "IOI"); printf("%d\n%d", j, i); }
the_stack_data/211080282.c
#include<stdio.h> int main() { printf("%x", -1<<1); getchar(); return 0; }
the_stack_data/189065.c
#include <pthread.h> #include <semaphore.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define N 10 #define MAX_STRING 100 int in = 0, out = 0; char buffer[MAX_STRING][N]; pthread_t producer[3]; pthread_t consumer[4]; pthread_mutex_t mutex; sem_t empty, full; void produce(int i) { FILE *fp; while (1) { sem_wait(&empty); pthread_mutex_lock(&mutex); fp = fopen("source.txt", "r"); fgets(buffer[in], MAX_STRING, fp); fclose(fp); printf("[Producer %d] Wrote %d\n", i, in + 1); in = (in + 1) % N; pthread_mutex_unlock(&mutex); sem_post(&full); } } void consume(int i) { while (1) { sem_wait(&full); pthread_mutex_lock(&mutex); printf("[Consumer %d] Get %d: %s\n", i, out + 1, buffer[out]); out = (out + 1) % N; pthread_mutex_unlock(&mutex); sem_post(&empty); } } int main() { int i; sem_init(&empty, 0, N); sem_init(&full, 0, 0); pthread_mutex_init(&mutex, NULL); for (i = 0; i < 3; i++) { pthread_create(&producer[i], NULL, (void *)produce, (void *)i); } for (i = 0; i < 4; i++) { pthread_create(&consumer[i], NULL, (void *)consume, (void *)i); } for (i = 0; i < 3; i++) { pthread_join(producer[i], NULL); } for (i = 0; i < 4; i++) { pthread_join(consumer[i], NULL); } pthread_mutex_destroy(&mutex); sem_destroy(&empty); sem_destroy(&full); return 0; }
the_stack_data/126827.c
//matvec.c //Multiplies a matrix by a vector // This is the linear, no AVX/OpenMP version #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 1000 #define N 1200 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(float *matrix, float *vector) { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) { matrix[i*N+j] = (float)rand()/(float)(RAND_MAX/10.0); } vector[i] = (float)rand()/(float)(RAND_MAX/10.0); } } extern void mulvec(float *matrix, float *vector, float *buf, int size); extern float add(float *vector, int size); int main(int argc, char **argv) { //Set everything up float *matrix = malloc(sizeof(float)*N*N); float *vector = malloc(sizeof(float)*N); float *buf = malloc(sizeof(float)*N); float *answer = malloc(sizeof(float)*N); srand(time(NULL)); init(matrix, vector); double start = read_timer(); for (int i = 0; i<N_RUNS; i++) { mulvec(matrix, vector, answer, N); } double t = (read_timer() - start); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); printf("==================================================================\n"); printf("Performance:\t\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("Matrix-vector (AVX- Assembly):\t\t%4f\t%4f\n", t, gflops); //Clean up free(matrix); free(vector); free(buf); free(answer); return 0; }
the_stack_data/974602.c
#include <stdio.h> #include <ctype.h> #include <string.h> int main(void) { int n; scanf("%d", &n); char str1[101], str2[101]; int index = 0; while((str1[index++] = tolower(getchar())) != '\n') ; str1[index] = '\0'; index = 0; while((str2[index++] = tolower(getchar())) != '\n') ; str2[index] = '\0'; int comp = strcmp(str1, str2); if(comp < 0) { printf("-1\n"); } else if(comp > 0) { printf("1\n"); } else { printf("0\n"); } return 0; }
the_stack_data/1027305.c
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { float distance; int Amount; printf("Input the distance the van has travelled:"); scanf("%f",&distance); if(distance<=30) { Amount=distance*50; printf("The Amount is %d",Amount); } else { Amount= 30*50+(distance-30)*40; printf("The Amount is %d",Amount); } return 0; }
the_stack_data/151329.c
/* * Copyright (C) 2002 Stichting NLnet, Netherlands, [email protected]. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND STICHTING NLNET * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * STICHTING NLNET 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. * * The development of Dynamically Loadable Zones (DLZ) for Bind 9 was * conceived and contributed by Rob Butler. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ROB BUTLER * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * ROB BUTLER 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. */ /* * Copyright (C) 1999-2001 Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef DLZ_MYSQL #include <config.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dns/log.h> #include <dns/sdlz.h> #include <dns/result.h> #include <isc/mem.h> #include <isc/platform.h> #include <isc/print.h> #include <isc/result.h> #include <isc/string.h> #include <isc/util.h> #include <named/globals.h> #include <dlz/sdlz_helper.h> #include <dlz/dlz_mysql_driver.h> #include <mysql.h> static dns_sdlzimplementation_t *dlz_mysql = NULL; #define dbc_search_limit 30 #define ALLNODES 1 #define ALLOWXFR 2 #define AUTHORITY 3 #define FINDZONE 4 #define COUNTZONE 5 #define LOOKUP 6 #define safeGet(in) in == NULL ? "" : in /* * Private methods */ /*% * Allocates memory for a new string, and then constructs the new * string by "escaping" the input string. The new string is * safe to be used in queries. This is necessary because we cannot * be sure of what types of strings are passed to us, and we don't * want special characters in the string causing problems. */ static char * mysqldrv_escape_string(MYSQL *mysql, const char *instr) { char *outstr; unsigned int len; if (instr == NULL) return NULL; len = strlen(instr); outstr = isc_mem_allocate(ns_g_mctx ,(2 * len * sizeof(char)) + 1); if (outstr == NULL) return NULL; mysql_real_escape_string(mysql, outstr, instr, len); return outstr; } /*% * This function is the real core of the driver. Zone, record * and client strings are passed in (or NULL is passed if the * string is not available). The type of query we want to run * is indicated by the query flag, and the dbdata object is passed * passed in to. dbdata really holds a single database instance. * The function will construct and run the query, hopefully getting * a result set. */ static isc_result_t mysql_get_resultset(const char *zone, const char *record, const char *client, unsigned int query, void *dbdata, MYSQL_RES **rs) { isc_result_t result; dbinstance_t *dbi = NULL; char *querystring = NULL; unsigned int i = 0; unsigned int j = 0; int qres = 0; if (query != COUNTZONE) REQUIRE(*rs == NULL); else REQUIRE(rs == NULL); /* get db instance / connection */ dbi = (dbinstance_t *) dbdata; /* if DBI is null, can't do anything else */ if (dbi == NULL) { result = ISC_R_FAILURE; goto cleanup; } /* what type of query are we going to run? */ switch(query) { case ALLNODES: /* * if the query was not passed in from the config file * then we can't run it. return not_implemented, so * it's like the code for that operation was never * built into the driver.... AHHH flexibility!!! */ if (dbi->allnodes_q == NULL) { result = ISC_R_NOTIMPLEMENTED; goto cleanup; } break; case ALLOWXFR: /* same as comments as ALLNODES */ if (dbi->allowxfr_q == NULL) { result = ISC_R_NOTIMPLEMENTED; goto cleanup; } break; case AUTHORITY: /* same as comments as ALLNODES */ if (dbi->authority_q == NULL) { result = ISC_R_NOTIMPLEMENTED; goto cleanup; } break; case FINDZONE: /* this is required. It's the whole point of DLZ! */ if (dbi->findzone_q == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2), "No query specified for findzone. " "Findzone requires a query"); result = ISC_R_FAILURE; goto cleanup; } break; case COUNTZONE: /* same as comments as ALLNODES */ if (dbi->countzone_q == NULL) { result = ISC_R_NOTIMPLEMENTED; goto cleanup; } break; case LOOKUP: /* this is required. It's also a major point of DLZ! */ if (dbi->lookup_q == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2), "No query specified for lookup. " "Lookup requires a query"); result = ISC_R_FAILURE; goto cleanup; } break; default: /* * this should never happen. If it does, the code is * screwed up! */ UNEXPECTED_ERROR(__FILE__, __LINE__, "Incorrect query flag passed to " "mysql_get_resultset"); result = ISC_R_UNEXPECTED; goto cleanup; } /* * was a zone string passed? If so, make it safe for use in * queries. */ if (zone != NULL) { dbi->zone = mysqldrv_escape_string((MYSQL *) dbi->dbconn, zone); if (dbi->zone == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } } else { /* no string passed, set the string pointer to NULL */ dbi->zone = NULL; } /* * was a record string passed? If so, make it safe for use in * queries. */ if (record != NULL) { dbi->record = mysqldrv_escape_string((MYSQL *) dbi->dbconn, record); if (dbi->record == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } } else { /* no string passed, set the string pointer to NULL */ dbi->record = NULL; } /* * was a client string passed? If so, make it safe for use in * queries. */ if (client != NULL) { dbi->client = mysqldrv_escape_string((MYSQL *) dbi->dbconn, client); if (dbi->client == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } } else { /* no string passed, set the string pointer to NULL */ dbi->client = NULL; } /* * what type of query are we going to run? this time we build * the actual query to run. */ switch(query) { case ALLNODES: querystring = build_querystring(ns_g_mctx, dbi->allnodes_q); break; case ALLOWXFR: querystring = build_querystring(ns_g_mctx, dbi->allowxfr_q); break; case AUTHORITY: querystring = build_querystring(ns_g_mctx, dbi->authority_q); break; case FINDZONE: querystring = build_querystring(ns_g_mctx, dbi->findzone_q); break; case COUNTZONE: querystring = build_querystring(ns_g_mctx, dbi->countzone_q); break; case LOOKUP: querystring = build_querystring(ns_g_mctx, dbi->lookup_q); break; default: /* * this should never happen. If it does, the code is * screwed up! */ UNEXPECTED_ERROR(__FILE__, __LINE__, "Incorrect query flag passed to " "mysql_get_resultset"); result = ISC_R_UNEXPECTED; goto cleanup; } /* if the querystring is null, Bummer, outta RAM. UPGRADE TIME!!! */ if (querystring == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } /* * output the full query string during debug so we can see * what lame error the query has. */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1), "\nQuery String: %s\n", querystring); /* attempt query up to 3 times. */ for (i=0; i < 3; i++) { qres = mysql_query((MYSQL *) dbi->dbconn, querystring); if (qres == 0) break; for (j=0; mysql_ping((MYSQL *) dbi->dbconn) != 0 && j < 4; j++) ; } if (qres == 0) { result = ISC_R_SUCCESS; if (query != COUNTZONE) { *rs = mysql_store_result((MYSQL *) dbi->dbconn); if (*rs == NULL) result = ISC_R_FAILURE; } } else { result = ISC_R_FAILURE; } cleanup: /* it's always good to cleanup after yourself */ /* if we couldn't even get DBI, just return NULL */ if (dbi == NULL) return ISC_R_FAILURE; /* free dbi->zone string */ if (dbi->zone != NULL) isc_mem_free(ns_g_mctx, dbi->zone); /* free dbi->record string */ if (dbi->record != NULL) isc_mem_free(ns_g_mctx, dbi->record); /* free dbi->client string */ if (dbi->client != NULL) isc_mem_free(ns_g_mctx, dbi->client); /* release query string */ if (querystring != NULL) isc_mem_free(ns_g_mctx, querystring); /* return result */ return result; } /*% * The processing of result sets for lookup and authority are * exactly the same. So that functionality has been moved * into this function to minimize code. */ static isc_result_t mysql_process_rs(dns_sdlzlookup_t *lookup, MYSQL_RES *rs) { isc_result_t result = ISC_R_NOTFOUND; MYSQL_ROW row; unsigned int fields; unsigned int j; unsigned int len; char *tmpString; char *endp; int ttl; row = mysql_fetch_row(rs); /* get a row from the result set */ fields = mysql_num_fields(rs); /* how many columns in result set */ while (row != NULL) { switch(fields) { case 1: /* * one column in rs, it's the data field. use * default type of A record, and default TTL * of 86400 */ result = dns_sdlz_putrr(lookup, "a", 86400, safeGet(row[0])); break; case 2: /* * two columns, data field, and data type. * use default TTL of 86400. */ result = dns_sdlz_putrr(lookup, safeGet(row[0]), 86400, safeGet(row[1])); break; case 3: /* * three columns, all data no defaults. * convert text to int, make sure it worked * right. */ ttl = strtol(safeGet(row[0]), &endp, 10); if (*endp != '\0' || ttl < 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver ttl must be " "a postive number"); } result = dns_sdlz_putrr(lookup, safeGet(row[1]), ttl, safeGet(row[2])); break; default: /* * more than 3 fields, concatenate the last * ones together. figure out how long to make * string. */ for (j=2, len=0; j < fields; j++) { len += strlen(safeGet(row[j])) + 1; } /* * allocate string memory, allow for NULL to * term string */ tmpString = isc_mem_allocate(ns_g_mctx, len + 1); if (tmpString == NULL) { /* major bummer, need more ram */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable " "to allocate memory for " "temporary string"); mysql_free_result(rs); return (ISC_R_FAILURE); /* Yeah, I'd say! */ } /* copy field to tmpString */ strcpy(tmpString, safeGet(row[2])); /* * concat the rest of fields together, space * between each one. */ for (j=3; j < fields; j++) { strcat(tmpString, " "); strcat(tmpString, safeGet(row[j])); } /* convert text to int, make sure it worked right */ ttl = strtol(safeGet(row[0]), &endp, 10); if (*endp != '\0' || ttl < 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver ttl must be " "a postive number"); } /* ok, now tell Bind about it. */ result = dns_sdlz_putrr(lookup, safeGet(row[1]), ttl, tmpString); /* done, get rid of this thing. */ isc_mem_free(ns_g_mctx, tmpString); } /* I sure hope we were successful */ if (result != ISC_R_SUCCESS) { /* nope, get rid of the Result set, and log a msg */ mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "dns_sdlz_putrr returned error. " "Error code was: %s", isc_result_totext(result)); return (ISC_R_FAILURE); } row = mysql_fetch_row(rs); /* get next row */ } /* free result set memory */ mysql_free_result(rs); /* return result code */ return result; } /* * SDLZ interface methods */ /*% determine if the zone is supported by (in) the database */ static isc_result_t mysql_findzone(void *driverarg, void *dbdata, const char *name) { isc_result_t result; MYSQL_RES *rs = NULL; my_ulonglong rows; UNUSED(driverarg); /* run the query and get the result set from the database. */ result = mysql_get_resultset(name, NULL, NULL, FINDZONE, dbdata, &rs); /* if we didn't get a result set, log an err msg. */ if (result != ISC_R_SUCCESS || rs == NULL) { if (rs != NULL) mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable to return " "result set for findzone query"); return (ISC_R_FAILURE); } /* count how many rows in result set */ rows = mysql_num_rows(rs); /* get rid of result set, we are done with it. */ mysql_free_result(rs); /* if we returned any rows, zone is supported. */ if (rows > 0) { mysql_get_resultset(name, NULL, NULL, COUNTZONE, dbdata, NULL); return (ISC_R_SUCCESS); } /* no rows returned, zone is not supported. */ return (ISC_R_NOTFOUND); } /*% Determine if the client is allowed to perform a zone transfer */ static isc_result_t mysql_allowzonexfr(void *driverarg, void *dbdata, const char *name, const char *client) { isc_result_t result; MYSQL_RES *rs = NULL; my_ulonglong rows; UNUSED(driverarg); /* first check if the zone is supported by the database. */ result = mysql_findzone(driverarg, dbdata, name); if (result != ISC_R_SUCCESS) return (ISC_R_NOTFOUND); /* * if we get to this point we know the zone is supported by * the database the only questions now are is the zone * transfer is allowed for this client and did the config file * have an allow zone xfr query. * * Run our query, and get a result set from the database. */ result = mysql_get_resultset(name, NULL, client, ALLOWXFR, dbdata, &rs); /* if we get "not implemented", send it along. */ if (result == ISC_R_NOTIMPLEMENTED) return result; /* if we didn't get a result set, log an err msg. */ if (result != ISC_R_SUCCESS || rs == NULL) { if (rs != NULL) mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable to return " "result set for allow xfr query"); return (ISC_R_FAILURE); } /* count how many rows in result set */ rows = mysql_num_rows(rs); /* get rid of result set, we are done with it. */ mysql_free_result(rs); /* if we returned any rows, zone xfr is allowed. */ if (rows > 0) return (ISC_R_SUCCESS); /* no rows returned, zone xfr not allowed */ return (ISC_R_NOPERM); } /*% * If the client is allowed to perform a zone transfer, the next order of * business is to get all the nodes in the zone, so bind can respond to the * query. */ static isc_result_t mysql_allnodes(const char *zone, void *driverarg, void *dbdata, dns_sdlzallnodes_t *allnodes) { isc_result_t result; MYSQL_RES *rs = NULL; MYSQL_ROW row; unsigned int fields; unsigned int j; unsigned int len; char *tmpString; char *endp; int ttl; UNUSED(driverarg); /* run the query and get the result set from the database. */ result = mysql_get_resultset(zone, NULL, NULL, ALLNODES, dbdata, &rs); /* if we get "not implemented", send it along */ if (result == ISC_R_NOTIMPLEMENTED) return result; /* if we didn't get a result set, log an err msg. */ if (result != ISC_R_SUCCESS) { if (rs != NULL) mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable to return " "result set for all nodes query"); return (ISC_R_FAILURE); } result = ISC_R_NOTFOUND; row = mysql_fetch_row(rs); /* get a row from the result set */ fields = mysql_num_fields(rs); /* how many columns in result set */ while (row != NULL) { if (fields < 4) { /* gotta have at least 4 columns */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver too few fields returned " "by all nodes query"); } /* convert text to int, make sure it worked right */ ttl = strtol(safeGet(row[0]), &endp, 10); if (*endp != '\0' || ttl < 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver ttl must be " "a postive number"); } if (fields == 4) { /* tell Bind about it. */ result = dns_sdlz_putnamedrr(allnodes, safeGet(row[2]), safeGet(row[1]), ttl, safeGet(row[3])); } else { /* * more than 4 fields, concatenate the last * ones together. figure out how long to make * string. */ for (j=3, len=0; j < fields; j++) { len += strlen(safeGet(row[j])) + 1; } /* allocate memory, allow for NULL to term string */ tmpString = isc_mem_allocate(ns_g_mctx, len + 1); if (tmpString == NULL) { /* we need more ram. */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable " "to allocate memory for " "temporary string"); mysql_free_result(rs); return (ISC_R_FAILURE); } /* copy this field to tmpString */ strcpy(tmpString, safeGet(row[3])); /* concatonate the rest, with spaces between */ for (j=4; j < fields; j++) { strcat(tmpString, " "); strcat(tmpString, safeGet(row[j])); } /* tell Bind about it. */ result = dns_sdlz_putnamedrr(allnodes, safeGet(row[2]), safeGet(row[1]), ttl, tmpString); isc_mem_free(ns_g_mctx, tmpString); } /* if we weren't successful, log err msg */ if (result != ISC_R_SUCCESS) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "dns_sdlz_putnamedrr returned error. " "Error code was: %s", isc_result_totext(result)); result = ISC_R_FAILURE; break; } /* get next row from the result set */ row = mysql_fetch_row(rs); } /* free result set memory */ mysql_free_result(rs); return result; } /*% if the lookup function does not return SOA or NS records for the zone, * use this function to get that information for Bind. */ static isc_result_t mysql_authority(const char *zone, void *driverarg, void *dbdata, dns_sdlzlookup_t *lookup) { isc_result_t result; MYSQL_RES *rs = NULL; UNUSED(driverarg); /* run the query and get the result set from the database. */ result = mysql_get_resultset(zone, NULL, NULL, AUTHORITY, dbdata, &rs); /* if we get "not implemented", send it along */ if (result == ISC_R_NOTIMPLEMENTED) return result; /* if we didn't get a result set, log an err msg. */ if (result != ISC_R_SUCCESS) { if (rs != NULL) mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable to return " "result set for authority query"); return (ISC_R_FAILURE); } /* * lookup and authority result sets are processed in the same * manner mysql_process_rs does the job for both functions. */ return mysql_process_rs(lookup, rs); } /*% if zone is supported, lookup up a (or multiple) record(s) in it */ static isc_result_t mysql_lookup(const char *zone, const char *name, void *driverarg, void *dbdata, dns_sdlzlookup_t *lookup) { isc_result_t result; MYSQL_RES *rs = NULL; UNUSED(driverarg); /* run the query and get the result set from the database. */ result = mysql_get_resultset(zone, name, NULL, LOOKUP, dbdata, &rs); /* if we didn't get a result set, log an err msg. */ if (result != ISC_R_SUCCESS) { if (rs != NULL) mysql_free_result(rs); isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver unable to return " "result set for lookup query"); return (ISC_R_FAILURE); } /* * lookup and authority result sets are processed in the same manner * mysql_process_rs does the job for both functions. */ return mysql_process_rs(lookup, rs); } /*% * create an instance of the driver. Remember, only 1 copy of the driver's * code is ever loaded, the driver has to remember which context it's * operating in. This is done via use of the dbdata argument which is * passed into all query functions. */ static isc_result_t mysql_create(const char *dlzname, unsigned int argc, char *argv[], void *driverarg, void **dbdata) { isc_result_t result; dbinstance_t *dbi = NULL; char *tmp = NULL; char *dbname = NULL; char *host = NULL; char *user = NULL; char *pass = NULL; char *socket = NULL; int port; MYSQL *dbc; char *endp; int j; unsigned int flags = 0; #if MYSQL_VERSION_ID >= 50000 my_bool auto_reconnect = 1; #endif UNUSED(driverarg); UNUSED(dlzname); /* verify we have at least 4 arg's passed to the driver */ if (argc < 4) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver requires " "at least 4 command line args."); return (ISC_R_FAILURE); } /* no more than 8 arg's should be passed to the driver */ if (argc > 8) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver cannot accept " "more than 7 command line args."); return (ISC_R_FAILURE); } /* parse connection string and get paramters. */ /* get db name - required */ dbname = getParameterValue(argv[1], "dbname="); if (dbname == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver requires a dbname parameter."); result = ISC_R_FAILURE; goto full_cleanup; } /* get db port. Not required, but must be > 0 if specified */ tmp = getParameterValue(argv[1], "port="); if (tmp == NULL) { port = 0; } else { port = strtol(tmp, &endp, 10); if (*endp != '\0' || port < 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Mysql driver port " "must be a positive number."); isc_mem_free(ns_g_mctx, tmp); result = ISC_R_FAILURE; goto full_cleanup; } isc_mem_free(ns_g_mctx, tmp); } /* how many queries were passed in from config file? */ switch(argc) { case 4: result = build_sqldbinstance(ns_g_mctx, NULL, NULL, NULL, argv[2], argv[3], NULL, &dbi); break; case 5: result = build_sqldbinstance(ns_g_mctx, NULL, NULL, argv[4], argv[2], argv[3], NULL, &dbi); break; case 6: result = build_sqldbinstance(ns_g_mctx, argv[5], NULL, argv[4], argv[2], argv[3], NULL, &dbi); break; case 7: result = build_sqldbinstance(ns_g_mctx, argv[5], argv[6], argv[4], argv[2], argv[3], NULL, &dbi); break; case 8: result = build_sqldbinstance(ns_g_mctx, argv[5], argv[6], argv[4], argv[2], argv[3], argv[7], &dbi); break; default: /* not really needed, should shut up compiler. */ result = ISC_R_FAILURE; } /* unsuccessful?, log err msg and cleanup. */ if (result != ISC_R_SUCCESS) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver could not create " "database instance object."); result = ISC_R_FAILURE; goto cleanup; } /* create and set db connection */ dbi->dbconn = mysql_init(NULL); /* if db connection cannot be created, log err msg and cleanup. */ if (dbi->dbconn == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver could not allocate " "memory for database connection"); result = ISC_R_FAILURE; goto full_cleanup; } tmp = getParameterValue(argv[1], "compress="); if (tmp != NULL) { if (strcasecmp(tmp, "true") == 0) flags = CLIENT_COMPRESS; isc_mem_free(ns_g_mctx, tmp); } tmp = getParameterValue(argv[1], "ssl="); if (tmp != NULL) { if (strcasecmp(tmp, "true") == 0) flags = flags | CLIENT_SSL; isc_mem_free(ns_g_mctx, tmp); } tmp = getParameterValue(argv[1], "space="); if (tmp != NULL) { if (strcasecmp(tmp, "ignore") == 0) flags = flags | CLIENT_IGNORE_SPACE; isc_mem_free(ns_g_mctx, tmp); } dbc = NULL; host = getParameterValue(argv[1], "host="); user = getParameterValue(argv[1], "user="); pass = getParameterValue(argv[1], "pass="); socket = getParameterValue(argv[1], "socket="); #if MYSQL_VERSION_ID >= 50000 /* enable automatic reconnection. */ if (mysql_options((MYSQL *) dbi->dbconn, MYSQL_OPT_RECONNECT, &auto_reconnect) != 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_WARNING, "mysql driver failed to set " "MYSQL_OPT_RECONNECT option, continuing"); } #endif for (j=0; dbc == NULL && j < 4; j++) dbc = mysql_real_connect((MYSQL *) dbi->dbconn, host, user, pass, dbname, port, socket, flags); /* let user know if we couldn't connect. */ if (dbc == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "mysql driver failed to create " "database connection after 4 attempts"); result = ISC_R_FAILURE; goto full_cleanup; } /* return db connection via dbdata */ *dbdata = dbi; result = ISC_R_SUCCESS; goto cleanup; full_cleanup: destroy_sqldbinstance(dbi); cleanup: if (dbname != NULL) isc_mem_free(ns_g_mctx, dbname); if (host != NULL) isc_mem_free(ns_g_mctx, host); if (user != NULL) isc_mem_free(ns_g_mctx, user); if (pass != NULL) isc_mem_free(ns_g_mctx, pass); if (socket != NULL) isc_mem_free(ns_g_mctx, socket); return result; } /*% * destroy the driver. Remember, only 1 copy of the driver's * code is ever loaded, the driver has to remember which context it's * operating in. This is done via use of the dbdata argument. * so we really only need to clean it up since we are not using driverarg. */ static void mysql_destroy(void *driverarg, void *dbdata) { dbinstance_t *dbi; UNUSED(driverarg); dbi = (dbinstance_t *) dbdata; /* release DB connection */ if (dbi->dbconn != NULL) mysql_close((MYSQL *) dbi->dbconn); /* destroy DB instance */ destroy_sqldbinstance(dbi); } /* pointers to all our runtime methods. */ /* this is used during driver registration */ /* i.e. in dlz_mysql_init below. */ static dns_sdlzmethods_t dlz_mysql_methods = { mysql_create, mysql_destroy, mysql_findzone, mysql_lookup, mysql_authority, mysql_allnodes, mysql_allowzonexfr, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; /*% * Wrapper around dns_sdlzregister(). */ isc_result_t dlz_mysql_init(void) { isc_result_t result; /* * Write debugging message to log */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2), "Registering DLZ mysql driver."); /* Driver is always threadsafe. Because of the way MySQL handles * threads the MySQL driver can only be used when bind is run single * threaded. Using MySQL with Bind running multi-threaded is not * allowed. When using the MySQL driver "-n1" should always be * passed to Bind to guarantee single threaded operation. */ result = dns_sdlzregister("mysql", &dlz_mysql_methods, NULL, DNS_SDLZFLAG_RELATIVEOWNER | DNS_SDLZFLAG_RELATIVERDATA | DNS_SDLZFLAG_THREADSAFE, ns_g_mctx, &dlz_mysql); /* if we can't register the driver, there are big problems. */ if (result != ISC_R_SUCCESS) { UNEXPECTED_ERROR(__FILE__, __LINE__, "dns_sdlzregister() failed: %s", isc_result_totext(result)); result = ISC_R_UNEXPECTED; } return result; } /*% * Wrapper around dns_sdlzunregister(). */ void dlz_mysql_clear(void) { /* * Write debugging message to log */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2), "Unregistering DLZ mysql driver."); /* unregister the driver. */ if (dlz_mysql != NULL) dns_sdlzunregister(&dlz_mysql); } #endif
the_stack_data/59698.c
//Contributors //G. Poppe //Meredith Quail //Benjamin Lozano //Room 19: Jonathan Chua #include <stdlib.h> #include <ctype.h> #include <string.h> #include <time.h> #include <stdio.h> #include <stdbool.h> #include <unistd.h> /* Room 19 additional includes */ int RollArray(int arr[]);//LA void Prt(int arr[]);//LA void nV(char a[]);//LA void BBGprnt();//LA void BagTossed(int *arr);//lA void TossBag(int *arr);//lA void patrickInitialPrompt(void); void demondoor(void); void angeldoor(char name[]); void broomcloset(void); /* Start of Room 19 Function Prototypes */ int doorDecision(void); void room19_readFile(FILE*); /* End of Room 19 Function Prototyping */ char *randomString(char *p); void mQhelpPrompt(void); //mquail void mQhelpMenu(void); //mquail void mQcontinue(void); //mquail int mQuserInput(void); //mquail int mQparser(void); //mquail char uInput[100]; //mquail void printIntroduction(void); // Manuel Castaneda void printRules(int rollsPerTurn, int pointsToLoose); // Manuel Castaneda double averageM(int rolls[], int numberOfRolls); // Manuel Castaneda double sumM(double sums[], int maxSums); // Manuel Castaneda void printRollResults(int rolls[], int numberOfRolls, int isUser); // Manuel Castaneda void play(void);//josue void story(void);//josue void elf(void);//josue // Talise void printMessage(int msg[]); void decodeMessage(char alphabet[], int codedMessage[], int *totalGuesses, int *wrong); void userFate(int x); //Monika void monikawelcome(char name[]); void monikacase1(char yellowdecision[]); void monikacase2(char reddecision[]); void monikacase3(char greenchoice[]); //Monika // Tien Tran Functions Start void room_37_read_instructions_from_file(); int room_37_guess_number(int); int room_37_prompt_guess(int, int); int room_37_average(); void room_37_fill_array(int *, int); // Tien Tran Functions End //Carlos Gonzalez int dpsCalc(int x, int y, int a); void printResults(int z, int a); //Benjamin Lozano void greenUSB26(int arrInt26[], int size); void blueUSB26(); void redUSB26(); void lockedDoor26(); //Benjamin Lozano int urGuess(void);//AndyV int Anumber(int a[], int urGuess);//AndyV void noteFromRick(void);//Berenis Castruita void stars(void);//Berenis Castruita void flurbos(void);//Berenis Castruita void planets(void);//Berenis Castruita void goodBye(void);//Berenis Castruita int main(int argc, char *argv[]) { int a,x,y,z,i,h,g,k,choice=0; char name[256]; int boxNum=0; int sum = 0; int number; float average; srand(time(NULL)); printf("Please enter your name: "); //Input any number of array inputs scanf("%s",name); printf("Hello %s welcome to the rpgGame!\n",name); while(choice != 99) { puts("You find yourself in a dark room and you are not sure how you got here."); puts("As you look around you see the room has 40 doors, each labeled with a number. You are not sure how such a small room can have 40 doors, sooo magic..."); puts("The room starts filling with water and you must choose a door to open or you will likely drown. you may quit anytime by selecting option 99"); puts("What door do you choose?"); scanf("%d",&choice); switch(choice) { case 1: { int counter = 0; while(choice != 99) { puts("You open the door and found a lot of people jumping around"); puts("You are almost certain that you have found a hidden civilization"); puts("At this point it seems like you have three options"); puts("Every option you choose has a hidden value related to it.."); puts("Choose wisely to earn enough points to win this game!!"); puts("1. Talk to the poeple and figure out why is everyone jumping!!"); puts("2. Walk further down and explore the place"); puts("3. Go back into the door you came from and drown"); scanf("%d",&choice); if (choice == 1) { puts("You talk to one of the elders and find out that a monster has threatened the city and everyone is panicking"); counter++; counter++; puts("The monster is a big red dragon that came upon the city to burn its lands"); printf("Once again.. You have 3 options.\n1. You can fight with them\n2. You can run away\n3. You can have a random option be chosen for you.\n"); scanf("%d",&choice); //switch statement switch(choice) { case 1: { puts("GREAT!! You chose to fight!"); counter++; counter++; counter++; break; } case 2: { puts("WOAH! You chose to be a coward! You do not deserve to play anymore.. GG"); counter--; break; } case 3: { //random choice = rand()%2 + 1; if (choice == 1) { puts("GREAT!! You chose to fight!"); counter++; counter++; counter++; break; } if (choice == 2) { puts("WOAH! You chose to be a coward! You do not deserve to play anymore.. GG"); counter--; break; } break; } } break; } else if (choice == 2) { puts("You walk further down the street and you get amazed by how beautiful the city is"); puts("To be continued..."); counter++; break; } else if (choice == 3) { puts("You opened the door and the water killed you"); counter++; break; } else { puts("Wrong choice!!!"); } } printf("Counter = %d. \n \n", counter); break; } case 2: { while(choice != 99) { puts("you open the door and find ........ \n"); puts("Watch out, look behind you, A Meeseeks is coming towarsds you.\n"); puts("Hi I'm Mr.Meeseeks look at me, waving hands around.\n"); puts("Ask him for a request and he will complete it and disapear.\n"); puts("What type of request would you want to make?\n"); puts("1st choice is Meeseeks can take you to Blips\n"); puts("2nd choice is you can join Morty and go on an Adventure\n"); puts("3rd choice is go back through the door you came from\n"); scanf("%d",&choice); if(choice == 1) { puts("Hi I'm Mr Meeseeks look at me.\n"); printf("Okay %s are you ready to go to Blips?\n", name); puts("First you need Flurbos.\n"); flurbos(); return 0; } if(choice == 2) { printf("Hey %s its Morty, hurry get in, Rick isn't watching, let go on a adventure\n",name); stars(); puts("I will let you choose what plannet we go to \n"); planets(); } if(choice == 3) { puts("You selected to exit.\n"); goodBye(); return 0; } else { puts("Incorrect input, please selecte from the following choices, 1, 2, or 3.\n"); } } break; } case 3: { while(choice != 99) { puts("You open the door and find a mysterious man saying: \n'Wendy, darling, Light of my Life! I'm not gonna hurt ya \n"); puts("He looks at you menancingly and starts to run to you with a knife, there are multiple doors behind you and the door you came from.\n "); puts("QUICK! which door do you pick?"); puts("you may quit anytime by selecting option:99"); scanf("%d",&choice); if(choice==1) { int DieArr[1]={0}; int q,f=0,c=0; double l=0.00; printf("your average is %f \n", l); puts("You stumble into a room, and a skeleton behind a counter and holds a 6 sided die"); puts("He asks you with a hollow voice, Hi would you like to roll the dice? you cannot leave the room without rolling 6 times."); puts("Depending on ur average you will get a prize or punishment"); puts("[1] for Yes or [2] for No"); scanf("%d",&x); if(x == 1) { for (i=0;i<6;i++) { q=RollArray(DieArr); f=f+q; Prt(DieArr); } l=f/(float)6; //average printf("your average is %lf \n", l); if (l<3) { puts("you will fall into the abyss once you exit this room"); choice=99; } else if (l<4) { puts("I have looked at your name"); nV(name); } else if (l<5) { puts("Good job"); } else if (l<6) { puts("you will now exit the room"); break; } } else { puts("Alright good bye"); } puts("You turn around and go back outside"); puts("ONCE AGAIN"); } if(choice==2) { char pic[42]; FILE *wptr; wptr = fopen("squirrel.txt","w"); FILE *rptr; rptr = fopen("pic.txt","r"); puts("Enjoy a picture of a Camel"); while(!feof(rptr)) { if(rptr) { fscanf(rptr,"%s",pic); printf("%s \n",pic); fprintf(wptr,"%s \n",pic); } } fclose(wptr); fclose(rptr); puts("You turn around and go back outside"); puts("ONCE AGAIN"); } if (choice==3) { int holes[3]; for (i=0;i<3;i++) { holes[i]=0; } puts("you are suddenly teleported outside and there you see an angled plank with 3 holes and 3 bags beside it\n"); puts("a voice above asked if you want to play bean bag toss"); puts("[1] for Yes or [2] for No"); scanf("%d",&x); if (x==1) { puts("The voice above says: 'for you to win, you must put at least 2 bags into 2 of the 3 holes'"); BBGprnt(); TossBag(holes); BagTossed(holes); puts("now wasnt that fun?"); puts("you can come back here whenever you want\n"); } else { puts("Alright good bye"); } puts("You turn around and go back outside"); puts("ONCE AGAIN"); } } break; } case 4: { while(choice != 99) { puts("My room no 4. you open the door and find ........"); scanf("%d",&choice); } break; } case 5: { while(choice != 99) { puts("you open the door slowly, you hear a click in the distance:"); puts("Do you close the door or open it fast? Type 1 for open and 2 for close."); scanf("%d",&choice); switch(choice) { case 1: { puts("you get hit with an arrow in the knee!"); break; } case 2: { puts("you hear an arrow hit the door"); break; } } } break; } case 6: { while(choice != 99) { FILE *wptrTalise; wptrTalise = fopen(argv[2], "w"); int totalGuesses = 0; int wrongGuesses = 0; int *totalPtr = &totalGuesses; int *wrongPtr = &wrongGuesses; char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'z', 'y', 'z', '\0'}; int codedMessage[10] = {8, 5, 12, 12, 15, 23, 15, 18, 12, 4}; char message[] = "Hello World"; puts("You open the door and walk inside the room."); puts("The door locks, and the only way out is to decode a message."); printMessage(codedMessage); decodeMessage(alphabet, codedMessage, totalPtr, wrongPtr); fprintf(wptrTalise, "Total Guesses: %d \nWrong Guesses: %d \nDecoded Message: %s \n", totalGuesses, wrongGuesses, message); x = (rand() % (3 + 1 - 1) + 1); userFate(x); for(i = 0; name[i] != '\0'; i++) { name[i] = toupper(name[i]); } printf("That's all, %s \n", name); fclose(wptrTalise); printf("Enter 1-40 to go to another room or 99 to quit. \n"); scanf("%d", &choice); } break; } case 7: { while(choice != 99) { char ladder; int rollDie, door1; float numbers[50], average, sum = 0.0; FILE *rptr; rollDie = rand()%9; puts("\nYou open the door and all the water drains"); puts("In front of you are five doors"); puts(" ----- ----- ----- ----- ----- "); puts("| | | | | | | | | | "); puts("| 1 | | 2 | | 3 | | 4 | | 5 | "); puts("| | | | | | | | | | "); puts(" ----- ----- ----- ----- ----- "); puts("Which door will you choose? (99 will exit the program)"); scanf("%d", &choice); switch(choice) { case 1: { puts("\nYou picked the first door"); puts("You look and see a small figure in the distance"); puts("As you walk closer you see that it's a skeleton running straight towards you!"); puts("There is another door to your right and written on the door says: "); puts("In order to move escape the skeleton you need to add up 5 numbers averaging at least 10"); printf("\nEnter 5 numbers\n"); for(i = 0; i < 5; i++) { printf("Number %d : ",i+1); scanf("%f", &numbers[i]); sum += numbers[i]; } average = sum / 5; printf("Your average is = %.2f \n", average); if(average < 10) { printf("\n\nPlease try again \n"); printf("Retutning to the main menu\n\n"); break; } else if (average > 10) { printf("\n\nCongrats! You escaped the skeleton!\n"); printf("Returning to the main menu\n\n"); break; } case 2: { puts("You enter door number 2 and find a man rolling dice"); puts("You approach the man"); puts("The man says to you, if you roll the correct number I will give you this gold ingot but if you lose then you'll be stuck down here forever"); printf("\nWould you like to roll? [1] = yes, [2] = no\n"); scanf("%d", &choice); if(choice == 1) { puts("The man says to pick a number 1 - 10"); printf("Enter a number: "); printf("%d", rollDie);//Random number appears to test the correct guess scanf("%d", &choice); if(choice == rollDie) { puts("Congrats you won the gold ingot!"); break; } else { puts("You lose"); puts("Returning back to the main menu"); break; } } else if(choice == 2) { printf("\nYou choose 2\n"); } } case 3: { rptr = fopen("mSkullPic.txt", "r"); if(rptr == NULL) { printf("Cannot open"); } else { if(choice != 3) { puts("You found a computer in the door what"); scanf("%d", &choice); } } } } } } break; } case 8: { // Declare Variables char *userEntry[256]; char uYes[5] = "yes"; char uNo[4] = "no"; int gameLevel = 1; bool kitchen1Clear = false; bool lightsOn = false; while(choice != 99) { // Opening Narration puts("-------------------------------------------------------------------------------------------------------"); puts("\nTwisting the knob and bracing your shoulder, you push against the heavy door with a strained grunt.\n"); puts("It slams shut just as you weave your way through. The door is now sealed tightly behind you.\n"); puts("A familiar grumble roils from deep within your gut."); puts("Before you conquer that hefty door again, you'll have to vanquish the hunger beast.\n"); puts("Do you want to take a look around? (Type 'yes' or 'no') : \n"); scanf("%s", *userEntry); // Type yes (replace later with a better method) if (strstr(*userEntry, uYes) != NULL) { puts("\nPatting your stomach in agreement, you decide that going on incredible adventures through other mysterious doors can wait.\n"); puts("For now, you have to look around for some food. Eat first, think later.\n"); mQcontinue(); } // Type no else if (strstr(*userEntry, uNo) != NULL) { puts("\n...no?"); puts("\nNO?????"); printf("\noOOOooo OOO oo lookit me, I'm a silly little adventurer named %s! I dOnT nEeD To eAt!! i'M sO StROnG aN d ClEvEr AnD I'm nEvEr HuNgRYyyyYYH haAHAa heeHEEhoO\n\n", name); puts("You're about as dumb as a bowl of oats. Do you think you can open a heavily sealed door like this?\n"); puts("When you're so hungry, you couldn't open a door twice?!\n"); puts("Well, too bad - that door isn't budging, and you're looking around for some sustenance, whether you like it or not! Your stomach isn't giving you any other options here!\n"); mQcontinue(); } // Level 1 : Kitchen if (gameLevel == 1) { mQhelpPrompt(); mQhelpMenu(); mQcontinue(); if (kitchen1Clear == false) { // Lights Off if (lightsOn == false) { puts("----------------------------------------------------------------------------------------------------------------"); puts("\nYou were so preoccupied with the door and your appetite that you hadn't noticed the room is completely dark.\n"); puts("Fishing your phone out of your pocket, you swipe a few times to activate its flashlight. Suppose that will have to do, until you can get the lights working.\n"); puts("You tentatively stretch a hand to the wall next to the door to check for a light switch - no dice.\n"); puts("Sweeping the room with your cellphone light, you notice the stainless steel glint of a FRIDGE and FREEZER wedged into the right corner.\n"); puts("You make out the red glow of a STOVE clock, blinking 00:00 steadily against the darkness.\n"); //Parser Loop begins while (mQuserInput() && mQparser()); } // Lights On else if (lightsOn == true) { puts("The stainless steel glint of a REFRIDGERATOR and FREEZER glints from the right corner.\n"); puts("To the left of the freezer is an old combination STOVE and OVEN.\n"); puts("A dirty SINK full of dishes connects to the counter space left of it, with a MICROWAVE on the counter space nearby."); puts("Some CABINETS lay half-open on rusted hinges above the sink space.\n"); break; } //break? } } } break; } //case 8 ends case 9: { while(choice != 99) { long balance = 100.00; long betAmount = 0.0; char bjRules = 'x'; char bjPlay = 'y'; puts("cl"); puts("You open the door and find yourself in an eery, dark room."); puts("You shut the door behind you and inspect the room. You spot a stool with a note placed on top of it and walk towards it."); puts("You then pick up the note, but before you can begin reading it, you are startled by the sound of a footstep."); puts("Before you can even process what you just heard, you are hit in the head with a shovel by a myseroius man, knocking you unconscious."); puts("You wake up in the back of the man's car, scared for your life. He notices that you're awake."); puts("'You've been out for a while', he says. 'Listen here and listen good because your life depends on it. I'm in need of some serious money, and you're gonna help me."); puts("'Huh? Why me? I only have 100 dollars on me.' you explain to him."); puts("'You were the only person dumb enough to walk into that room I was hiding in. Seriously, you wouldn't believe how long I waited in there for somebody.' he says."); puts("'Any how, there's no getting out of this for you. Unless you pay with your life, but you don't want that to happen do you? So here's the plan...'"); puts("'I hope you're a good gambler, because I'm going to drop you off at the local casino. There you can play any game you want, but I'd suggest sticking with what you're good at'"); puts("'You're going to win me lots of money and I'll set you free. Easy enough, right?'"); puts("'But what happens if I lose my $100?' you ask him."); puts("'Well kid, you better pray you don't lose that money. Because the only way you're getting out of this in one piece is if you come back to me with a bag full of cash!'"); puts("'And don't think you can contact the police while you're in there. If any of this gets back to me I will make sure your entire family is killed. I know people...'"); puts("As he finishes explaining what you are to do, you arrive at the casino."); puts("'Good luck, I know you'll make me happy.', he says to you as you exit his car."); puts("You enter the casino and exchange your $100 for chips."); puts("You spot a blackjack table and decide to try your luck"); puts("'Welcome to the blackjack table! Would you like me to explain the rules? (Enter Y or N)"); scanf(" %c",&bjRules); switch(bjRules) { case 'y': case 'Y': { puts("Each participant attempts to beat the dealer by getting a count as close to 21 as possible, without going over 21."); puts("It is up to each individual player if an Ace is worth 1 or 11. Face cards are 10 and any other card is its pip value."); puts("Before the deal begins, each player places a bet, in chips, in front of them in the designated area."); puts("When all the players have placed their bets, the dealer gives each player in the rotation a single card, including one to the dealer. This is repeated once more until everyone has 2 cards."); puts("Each player must then decide whether to 'stand' (not ask for another card) or 'hit' (ask for another card in an attempt to get closer to a count of 21."); puts("Player(s) may 'hit' as many times as they'd like during their turn."); puts("If the player goes over 21, their round is over and they lose their bet. If, instead, the player decides to stand (therefore under 21), it is the dealer's turn."); puts("The dealer then reveals his/her cards to the table. If the total of the dealer's cards is 17 or more, the dealer must stand. If the total is 16 or under, they must take a card."); puts("The dealer must continue to take cards until the total is 17 or more, at which point the dealer must stand."); puts("If the dealer goes over 21, any remaining player(s) automatically win. If the dealer does not go over 21, player(s) compare their cards to the dealers. Closes to 21 wins."); puts("If there is a tie between dealer and player(s), both dealer and player(s) then draw a single card from the top of the deck. Whoever has the higher value card wins!"); break; } case 'n': case 'N': { break; } default: { puts("Invalid input."); break; } } scanf("%d",&choice); } break; } case 10: { while(choice != 99) { int x, y, z, i, j, k, priceActual, priceGuess; char guess; char upperName[28]; srand(time(NULL)); for(i = 0; i<28; i++) { upperName[i] = toupper(name[i]); } printf("\n$$$$$$ %s COME ON DOWN!! YOU'RE ON THE PRICE IS RIGHT!! $$$$$$\n", upperName); puts(" : : doo dooo dooooOoOoOo, doo dooooo DoooOooooooo : :\n"); puts("\nBob Barker: Welcome contestants, let me show you the first item up for bid on the Price Is Right...\n"); puts("\nJohnny Olsen: It's a new stove! A gas stove designed for your pleasure by LG Electronics. It is 6.3 cu. ft., has a Smart Wi-Fi enabled fan, and a convection electric oven range with AirFry and EasyClean in Stainless Steel.\n"); printf("\nBob Barker: Contestants please bid on it in dollars because we round off our retail prices to the nearest dollar.. %s what do you bid? ", name); scanf("%d", &priceGuess); priceActual = (rand() %400) + 600; if(priceActual - priceGuess <= 200) { printf("\nBob Barker; The actual retail price is $%d, that means %s, you are the winner!\n", priceActual, name); } else { printf("\nBob Barker: The actual retail price is $%d, that means %s, you are not the winner, let's try again...\n", priceActual, name); } } break; } case 11: { int doorChoice; while(choice != 99) { puts("you open the door and find ........\n"); puts("3 closed doors\n"); printf("The first door is made of rock with cracks that seem to have orange lava flowing from them and fire comming out from the edges\n"); printf("The second door seems to be an ornage rock door with vines covering it and light bleeding from the edges with mist flowing from underneath\n"); printf("The final door seems to be an ordinary old wooden door of a broom closet\n"); printf("Which door will you choose?\n"); printf("1 for the fire door\n"); printf("2 for the mysterious glowing door\n"); printf("3 for the broom closet\n"); scanf("%d",&doorChoice); switch(doorChoice) { case 1: demondoor(); break; case 2: angeldoor(name); break; case 3: broomcloset(); break; default: printf("That isn't a valid door\n"); } } break; } case 12: { while(choice != 99) { } break; } case 13: { // Norville Amao while(choice != 99) { char name[20]; int race = 5; puts("\nCHARACTER CREATION"); puts("Enter your name:"); scanf("%s",name); while(race == 5){ puts("\nChoose your race"); puts("1 - human"); puts("2 - elf"); puts("3 - ilvyr"); puts("4 - ferren"); puts("5 - race information"); scanf("%d",&race); if(race == 5){ puts("\nTHE RACES OF HABREN"); puts("HUMANS"); puts("Known as Goddess's favorite. The most prosperous of all the races."); puts("ELVES"); puts("The racial offpsring of ilvyrs and humans. They often live underground, opposite of their ilvyr ancestors."); puts("ILVYRS"); puts("A race of fallen angels who have succumbed to the sin of pride. Identified by their pointed ears and white bird-like wings."); puts("FERRENS"); puts("Often mistaken as humans. They are identified by their towering heights, especially those of their women."); } } puts("\nType 99 to quit"); scanf("%d",&choice); } break; } case 14: { while(choice != 99) { puts("hello world! welcome to room 14. spoooky.."); puts("then a giant spider fell on your face"); puts("RUNNN!"); break; } break; } case 15: {//Monika while(choice != 99) { char yellowdecision[2]; char reddecision[2]; char greenchoice[2]; srand(time(NULL)); monikawelcome(name); puts("You enter door 15 but you end up outside and see three colored paths\n"); puts("Choose a path:\n 1 (yellow)\n 2 (red)\n 3 (green)\n"); scanf("%d", &choice); switch(choice) { case 1: { monikacase1(yellowdecision); break; } case 2: { monikacase2(reddecision); break; } case 3: { monikacase3(greenchoice); break; } } } } case 16: { while(choice != 99) { puts("The room is dark and cold"); puts("You look at the empty room with empty Shelves.."); puts("You think to yourself, there's nothing of value in here.."); puts("What should you do?"); puts("1. Move and advance to the next room"); puts("2. Examine the room a little more carefully"); puts("3. Go back to the last room"); scanf("%d", &choice); if(choice == 1) { puts("You go towards the door, but the handle is locked.."); puts("*Maybe you should examine the room.."); break; } else if(choice == 2) { puts("You look at the very top of the shelf and find a old brass key"); break; } else if(choice == 3) { puts("You back out slowly towards the previous room... but it's locked!"); } else { puts("Try again"); } } break; } case 17: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 18: { while(choice != 99) { puts("Welcome to Door 18\n"); puts("'Have a seat...if you dare', beckons an old Wizened Man siting in the center of the cavern at a small card table.\n"); printf("\n You can either (sit) down, (look) around, or (leave) back to where you came..like a coward. "); scanf("%d",&choice); } break; } case 19: /* Room 19 */ { while(choice != 99) { FILE *readPtr0, *readPtr1, *readPtr2; readPtr0 = fopen("./room19/room19_D.txt", "r"); readPtr1 = fopen("./room19/room19_O.txt", "r"); readPtr2 = fopen("./room19/room19_M.txt", "r"); while(choice != 99) { printf("\n\n"); room19_readFile(readPtr0); printf("\n\nOur brave hero %s approaches the door\n\n", name); choice = doorDecision(); switch(choice) /* Criteria : Case Statement */ { case 1: { room19_readFile(readPtr1); puts("\nyou open the door and find ........\n"); sleep(4); room19_readFile(readPtr2); scanf("%d",&choice); break; } default: { printf("\nOur not-so brave hero %s slowly backs away from door 19 and decides to pick another door\n\n", name); break; } } } fclose(readPtr0); fclose(readPtr1); fclose(readPtr2); } break; } case 20: { while(choice != 99) { puts("There is a noise in the distance but you can't quite make out what it is"); patrickInitialPrompt(); scanf("%d",&choice); if(choice == 1) { puts("You open the door and actually find out the noise is just Naked in the Rain by the Red Hot Chili Peppers playing on a radio"); puts("You actually see a guitar next to the radio. Do you pick it up? 1 for yes, 2 for no"); scanf("%d",&choice); switch(choice) { case 1: { puts("You pick up the guitar and suddenly feel a change in your body. Maybe its the 5G everyone jokes about"); break; } case 2: { puts("Someone comes out of the shadows and hits you over the head with it. You died."); } } } else if (choice == 2) { puts("The floor fails and you through it into the void"); } else if (choice == 3) { int i, n; float num[10], sum = 0.0, avg; puts("The gentleman welcomes you into the corner with the light and he asks you to give him some numbers"); puts("However you find out that the old man cannot keep track of more than 10 values"); printf("Enter the amount of numbers you want to make an average out of \n"); scanf("%d",&n); while(n>10 || n<1) { printf("Error! Keep it between 1 and 10 values. \n"); printf("Enter the amoount of numbers you want to average: "); scanf("%d",&n); } for(i=0;i<n;++i) { printf("%d. Enter number: ",i+1); scanf("%f",&num[i]); sum += num[i]; } avg = sum /n; printf("Average = %.2f \n", avg); } } break; } case 21: { while(choice != 99) { int x=0; int y; int z=0; srand(time(NULL)); puts("You have entered a chamber resembling the ruins of an Ancient Egyptian Temple "); puts("The door to your left shows signs of innocence"); puts("while the door to your right emits a dark and powerful energy"); puts("You see a dark figure in the distance"); puts("He tosses a coin"); for (i=0;i<1;i++) { y = rand()%2; if(y==1) { x++; puts("The coin lands on heads"); puts("Fate has decided for you to choose the door to your left"); } else { z++; puts("the coin lands on tails"); puts("???: Fate has decide for you to walk through the door to your right "); } printf("???: %s would you ignore fate \n",name); puts("???: Pick a door?!"); puts("1. Innocent door"); puts("2.Door towards a powerful Energy"); } scanf("%d",&choice); switch(choice) { case 1: { if(x==1) { printf("reveal code HEADS\n"); //use file heads } puts("Intersting choice"); scanf("%d",&choice); break; } case 2: { if(z==1) { printf("reveal code TAILS \n"); // use file tails puts("Intersting choice"); scanf("%d",&choice); } break; } } } break; } case 22: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 23: { while(choice != 99) { puts("\nYou open the door and find ........"); puts("Yourself inside of JoJos Bizarre Dungeon. \n"); puts("Select your stand"); puts("1. Star Platinum"); puts("2. Golden Experience."); puts("3. Mr. President "); scanf(" %d", &choice); switch(choice) { case 1: { puts("\nDIO, the arch nemesis of the Joestar family bloodline, has successfully killed your grandpa and drank his blood achieving an incredible power buff."); puts("You must defeat DIO to revive your uncle and save humanity."); x = 100; y = 100; a = 1; z = dpsCalc(x, y, a); printResults(z, a); break; } case 2: { puts("\nDiavolo, the head of an italian mafia that sells drugs to kids, is about to acquire a requiem arrow that will allow him to upgrade his stand and become the strongest stand user in existance."); puts("You must get to the arrow before him in order to upgrade your stand and become head of the mafia and stop the flow of drugs to the kids."); x = 100; y = 100; a = 2; z = dpsCalc(x, y, a); printResults(z, a); break; } case 3: { puts("Not finished \n"); break; } } puts("Thank you for playing."); exit(0); } break; } case 24: { while(choice != 99) { puts("you open the door and find ........"); puts("press 1 to start"); scanf("%d",&choice); int arr[1] = {0}; int y, z; y =urGuess(); z = Anumber(arr, y); if(z != 0 && z != -1) { puts("yes"); } else if(z == -1) { puts("sorry"); } else if(z >= 11 && z <= 98) { puts("not valid"); } else if (z == 99) { break; return 0; } } break; } case 25: { while(choice != 99) { puts("you open the door and find ........"); puts("You are in a small dark room"); puts("You turn the lights on and see 3 doors"); puts("You have to choose what door to go through"); puts("1.Go through the red door"); puts("2.Go through the blue door"); puts("3.Go through the green door"); printf("Please enter a number 1-3 or press 99 to exit the program:"); scanf("%d",&choice); if (choice == 1) { puts("\nWoah! Wow! You really chose the red door"); puts("Very brave of you, but what a stupid choice to make"); puts("Really?! Who choses a red door over a green and blue door"); puts("Anyways! Prepare to meet your doom! HAHA!"); puts("You died!\n"); } if (choice == 2) { puts("\nYou enter the room and close the door"); puts("You realize you have seen this room before"); puts("You are confused"); puts("You see a mirror and go to it"); puts("You see yourself in the mirro and see a 10 year old kid"); puts("THAT'S YOU!"); puts("You are confused and scared"); puts("You realize this room is your room"); puts("You see your bed and decide to take a nap\n"); } if (choice == 3) { puts("\nYou go through the green door and the door slams behind you!"); puts("You cannot see what is happening"); puts("You start walking foward, but fall off a cliff!"); puts("SPLAT!"); puts("You fell to your death\n"); } } break; } case 26: { while(choice != 99) { int choice26 = 0; int arrInt26[9] = {7,3,5,6,9,1,3,2,6}; int randomGame26; printf("\nYou open the door and find a small room with a door on the other side and a desk with a laptop and three USB drives equally spread apart, one gree, one blue, one red.\n"); printf("The door behind you slams shut. You open the door again to see a bottomless pit.\n"); printf("You are now realizing there is no immediate way out, so you decide to find your own way out...\n"); printf("You walk over to the desk and see a message above each USB...\n\n"); do{ printf("1) Inspect the Green USB.\n"); printf("2) Inspect the Blue USB.\n"); printf("3) Inspect the Red USB.\n"); printf("4) Walk up to the door on the other side of the room.\n"); printf("5) Leave the room and fall into the bottomless pit.\n"); printf("Enter choice 1-5: "); scanf("%d", &choice26); switch(choice26) { case 1: greenUSB26(arrInt26, 9); break; case 2: blueUSB26(); break; case 3: redUSB26(); break; case 4: lockedDoor26(); break; } }while(choice26 != 5); printf("\nChoose another room 1-40 or type 99 to exit the program.\n"); scanf("%d",&choice); } break; } case 27: { while(choice != 99) { puts("you open the door and find ........"); puts("Fantasy world with flying dragons, mystery mythic, magic and rescuing princess... Your dream adventure world! Oh look! The little fairy flew and welcomes you."); puts("Would you like to talk to it (yes=1 no=0)?"); scanf("%d",&choice); if(choice == 1) { puts("You: Hey! How are you? This world seems pretty nic..."); puts("Fairy: Shut up and give me ALL you've got!!"); puts("You: Wait wha..?"); scanf("%c", &name[0]); puts("Fairy: I need a MONEY!(pulls out of a knife)."); puts("\nLooks like that wasn't clever choice."); puts("\t\t...YOU DIED...."); break; } puts("Are you really going to ignore this cute fairy? Come on~ at least saying hi wouldn't hurt anybody."); puts("Talk to the fairy(yes=1 no=0)."); scanf("%d",&choice); if(choice == 1) { puts("You: Hi,I was wonder what were you doing he..."); puts("Fairy: Were you trying to ignore me huh? (stabs with a knife)"); puts("Well... seems like that fairy would hurt anybody here haha. You Die..."); break; } puts("You have safely ranway from that cold blood fairy. Please select your derection to go"); puts("1.Mining Mountain 2.Shop 3.Gamble"); scanf("%d",&choice); switch(choice) { case 1: { puts("Entering Mining Mountain"); puts("Miner: Welcome to Pitcoin mining! You can mine your Pitcoin as many as you want. But the amount will be random. So GL!"); puts("Mine Pitcoin? (yes=1 no=0)"); scanf("%d",&choice); if(choice == 0) { puts("Exiting Mining Mountain"); break; } else if(choice == 1) { while(choice != -1) { puts("Let's mining!"); scanf("%d",&choice); } break; } else { puts("Please select again."); } } puts("reselect case"); scanf("%d",&choice); } } break; } case 28: { while(choice != 99) { puts("you open the door and find ........"); printf("Hello World"); printf("Turn back"); scanf("%d",&choice); } break; } case 29: { while(choice != 99) { int portalChoice = 5; puts("you open the door and find ........"); puts("Four portals right next to each other. A voice tells you to enter one."); puts("The first portal is blue, second is red, third is yellow, fourth is black."); puts("1 = First Portal | 2nd = Second Portal | 3rd = Third Portal | 4th = Fourth Portal"); scanf("%d",&portalChoice); if(portalChoice == 0) { puts("Seriously?! That wasn't any of the options!"); puts("Since you cannot follow the directions, you have died."); puts("GAME OVER."); } if(portalChoice == 1) { int guideChoice = 0; puts("You have entered portal number 1. A man walks up to you and says: "); puts("Greetings! I see you are a new arrival to this land. My job is to welcome all new visitors."); puts("You think to yourself. You've read that before somewhere. A long time ago but you're not 100% sure where you have."); puts("As the man continues talking you look around your surroundings and realize you're in Gielinor, from the MMORPG RuneScape."); puts("You interrupt the man, yelling you don't belong here and that you belong on Earth! The man continues without skipping a beat."); puts("You're not sure whether or not to just run away or hit the guy. You choose to: "); puts("1 to run away | 2 to hit the guide"); scanf("%d", &guideChoice); if(guideChoice == 1) { puts("You run out of the building and see a woman training people how to cut logs off trees and fish for shrimp."); } if(guideChoice == 2) { puts("You hit the guide. He replies with: You can't do that here. And now, you have to pay."); puts("Suddednly an explosion rocks your world and you die instantly."); puts("Seriously though, why did you hit him?"); puts("Game Over."); } } if(portalChoice == 2) { puts("You wake up on a cart."); } if(portalChoice == 3) { puts("You wake up in your bed."); } if(portalChoice == 4) { puts("You have entered portal number 4. You're suddendly teleported onto a stage with a microphone. There is no audience."); puts("You walk up to the microphone in curiosity and say: "); } return EXIT_SUCCESS; } break; } case 30://Markease's room of "why did you do this?" { while(choice != 99) { //int nextChoice = 0; puts("you open the door and find ........"); puts("Some guy screaming that he is the coolest in the universe!"); puts("You stand in shock as it is said in your precense."); puts("You contemplate your current options"); printf("Which do you choose? 1: Acknowledge that You are truly the coolest \n"); printf("2:Acknowledge he is the coolest \n"); scanf(" %d",&choice); // while(choice != 1 || choice != 2) // { if(choice == 1) { printf("Your claim has been ignored.\n"); printf("You challenge him to a cool contest. \n"); // break; } else if(choice == 2) { printf("Your claim has been taken as sarcasim. \n"); printf("He challenges you to a cool contest. \n"); // break; } // } /*switch(choice) { case 1: { printf("Your claim has been ignored.\n"); printf("You challenge him to a cool contest. \n"); break; } case 2: { printf("Your acknowledgement has been taken as sarcasim. \n"); printf("You are challenged to a cool contest. \n"); break; } default: { puts("You can't think that fast"); break; } } }*/ printf("Play again? Enter 99 to quit\n"); scanf(" %d",&choice); } break; } case 31: { while (choice != 99) { // constants int MAX_SUMS = 30, ROLLS_PER_TURN = 3, POINTS_TO_LOOSE = 30, AI_STOPING_POINT = 10; FILE *writer = fopen("Casino.txt", "a"); // the "a" will append to the file printIntroduction(); int showRules = 2; printf("Would you like to read the rules? (1: yes | 2: no) "); scanf(" %d", &showRules); // format switch switch (showRules) { case 1: printRules(ROLLS_PER_TURN, POINTS_TO_LOOSE); break; } srand(time(NULL)); // arrays of all the averages that each player rolls double userSums[30] = {0}; double player2Sums[30] = {0}; double player3Sums[30] = {0}; // pointers for the sums arrays double *userSumPtr = userSums; double *player2SumPtr = player2Sums; double *player3SumPtr = player3Sums; // decides when the game should stop (if no one is able to play anymore) int userStillPlaying = 1, player2StillPlaying = 1, player3StillPlaying = 1; int iteration = 0; // increases in each loop, determines how large the dice will get double currentScore[3]; // keeps track of the score for each player int i; // for loops while (userStillPlaying == 1 || player2StillPlaying == 1 || player3StillPlaying == 1) { int userInput; int lowDiceSize, highDiceSize; // the lowest and highest value a dice can get you int rolls[3]; // holds the values of all the rolls int chooseToRoll; // stores the decision of the other players to roll or not iteration++; highDiceSize = iteration * 10; puts("\n- - - - - - -\n"); // just a divider since there is a lot going on in the console. printf("\nRound %d, Dice size is %d to %d", iteration, 1, highDiceSize); if (userStillPlaying) { puts("\n\nYour Turn:"); printf("Would you like to roll your three dice? (1: yes | 2: no) "); scanf(" %d", &userInput); if (userInput == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *userSumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 1); // prints out the outcome of all your rolls printf("Average of your rolls: %.1lf\n", *userSumPtr); userSumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[0] = sumM(userSums, MAX_SUMS); // takes the sum of all your averages so far printf("Your current score: %.1lf", currentScore[0]); if (currentScore[0] > POINTS_TO_LOOSE) { userStillPlaying = 0; printf("\nYou lost. %.1lf is larger than %d...", currentScore[0], POINTS_TO_LOOSE); } } else if (userInput == 2) { userStillPlaying = 0; } } if (player2StillPlaying) { puts("\n\nPlayer 2 Turn:"); chooseToRoll = 1; // decides to keep rolling if ((POINTS_TO_LOOSE - sumM(player2Sums, MAX_SUMS)) < AI_STOPING_POINT) // if the ai is (stoping point) away from the score limit, they will stop rolling { chooseToRoll = 0; player2StillPlaying = 0; puts("Player 2 chose not to roll anymore."); } if (chooseToRoll == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *player2SumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 0); // prints out the outcome of all your rolls printf("Player 2 rolls average: %.1lf\n", *player2SumPtr); player2SumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[1] = sumM(player2Sums, MAX_SUMS); // takes the sum of all your averages so far printf("Player 2 score: %.1lf", currentScore[1]); if (currentScore[1] > POINTS_TO_LOOSE) { player2StillPlaying = 0; printf("\nPlayer 2 is out. %.1lf is larger than %d...", currentScore[1], POINTS_TO_LOOSE); } } } if (player3StillPlaying) { puts("\n\nPlayer 3 Turn:"); chooseToRoll = 1; // decides to keep rolling if ((POINTS_TO_LOOSE - sumM(player3Sums, MAX_SUMS)) < AI_STOPING_POINT) // if the ai is (stoping point) away from the score limit, they will stop rolling { chooseToRoll = 0; player3StillPlaying = 0; puts("Player 3 is choosing not to roll anymore."); } if (chooseToRoll == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *player3SumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 0); // prints out the outcome of all your rolls printf("Player 3 average rolls is %.1lf\n", *player3SumPtr); player3SumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[2] = sumM(player3Sums, MAX_SUMS); // takes the sum of all your averages so far printf("Player 3 score: %.1lf", currentScore[2]); if (currentScore[2] > POINTS_TO_LOOSE) { player3StillPlaying = 0; printf("\nPlayer 3 is out. %.1lf is larger than %d...", currentScore[2], POINTS_TO_LOOSE); } } } } printf("\n\nUser score: %.1lf\n", currentScore[0]); printf("Player 2 score: %.1lf\n", currentScore[1]); printf("Player 3 score: %.1lf\n", currentScore[2]); if (currentScore[0] > POINTS_TO_LOOSE) { currentScore[0] = -1; } if (currentScore[1] > POINTS_TO_LOOSE) { currentScore[1] = -1; } if (currentScore[2] > POINTS_TO_LOOSE) { currentScore[2] = -1; } // change name to all capital letters for (i = 0; i < strlen(name); i++) // doing char function { if(i % 2 == 0) { name[i] = toupper(name[i]); } else { name[i] = tolower(name[i]); } } char nameToReplace[256] = "CTO OF HOT POCKETS"; char myNameWhichIsManny[256] = "MaNnY"; if(strcmp(myNameWhichIsManny, name) == 0) // compares strings // string function { strcpy(name, nameToReplace); // copies string } if ((currentScore[0] == -1) && (currentScore[1] == -1) && (currentScore[2] == -1)) { puts("\nEveryone lost..."); fprintf(writer, "%s lost with everyone\n", name); } else if ((currentScore[0] > currentScore[1]) && (currentScore[0] > currentScore[2])) { printf("\nYou won!"); fprintf(writer, "%s beat player 1 and 2\n", name); } else if ((currentScore[1] > currentScore[2]) && (currentScore[1] > currentScore[0])) { printf("\nPlayer 2 won!"); fprintf(writer, "%s lost to player 2\n", name); } else { printf("\nPlayer 3 won!"); fprintf(writer, "%s lost to player 3\n", name); } fclose(writer); // close the output file so i can start writing in it again. int showRecords = 2; printf("\nGood game. Would you like to see the records of previous games? (1: yes | 2: no) "); scanf(" %d", &showRecords); if (showRecords == 1) { FILE *reader = fopen("Casino.txt", "r"); char line[50]; char c; c = fgetc(reader); while (c != EOF) { printf("%c", c); c = fgetc(reader); } fclose(reader); } puts("\nRemember to enter 99 to exit!"); scanf("%d", &choice); } break; } case 32: { while(choice != 99) { puts("You are safe from the water, but strange random strings start to attack. What do you do?"); while(choice != 99) { char *ptr; char randStr[11] = ""; puts("1. Smack the string in the leftmost bit"); puts("2. Kick the string in the rightmost bit"); puts("99. Exit Room"); scanf("%d", &choice); switch(choice) { case 1: ptr = randomString(randStr); printf("String %s approaches you and you smack it!\n", ptr); printf("The string is confused and altered to %s \n", ptr); break; case 2: break; case 99: break; default: puts("You can't do that."); break; } } } break; } case 33: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 34: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 35: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 36: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 37: { while(choice != 99) { char monster[20] = ""; char action[1000]; room_37_read_instructions_from_file(); scanf("%d",&choice); while(!(choice>=1 && choice <=3)) { puts("You have selected an incorrect choice Please choose again.\n"); scanf("%d",&choice); } switch(choice) { case 1: puts("You have selected to fight Godzilla.\n"); puts("Godzilla's signature weapon is his distinctive atomic breath. Godzilla's dorsal spines glow ominously, and then he lets loose with a concentrated blast of radiation from his mouth\n"); puts("In addition to his deadly atomic breath, Godzilla can also emit atomic energy in all directions from every inch of his body in a short-range pulse called the nuclear pulse\n"); puts("Godzilla displays an uncanny ability to resist injury. Not even the pressure and cold of deep sea trenches can kill him.\n"); puts("Godzilla is vulnerable to electricity\n"); strcpy(monster, "Godzilla"); break; case 2: puts("You have selected to fight King Ghidorah\n"); puts("When Ghidorah becomes the alpha, he lets out an extremely loud and powerful call that could be heard by the other Titans all around the world\n"); puts("Ghidorah has an electro-receptor molecular biology, and his skin is covered with traces of gold that acts as a conductor that carries bioelectrical currents throughout his body.\n"); puts("Ghidorah can drain energy and electricity directly into himself by biting down on power sources.\n"); strcpy(monster, "King Ghidorah"); break; case 3: puts("You have selected to fight King Kong\n"); puts("Kong is also remarkably intelligent. He makes use of environmental objects like trees or rocks when fighting, and even when overwhelmed by more powerful or more numerous opponents he can think on his feet and find a way to win.\n"); puts("Kong also demonstrates durability when he is able to continue fighting against airplanes and even destroy some of them after being riddled with bullets.\n"); strcpy(monster, "King Kong"); break; default: break; } puts("Good Luck Hero. The fate of earth depends on you.\n"); puts("For hitting the target you have to guess a number between 1 and 30 inclusive\n"); puts("You will have 10 chances to guess it\n"); number = (rand() % 30) + 1; int firstRound = room_37_guess_number(number); if(firstRound == 0) { puts("Sorry :( You guess is incorrect. But don't worry as you have a second round too.\n"); } else { puts("Congrats :) You guess is correct, now you need to win the second round as well.\n"); puts("Now the plasma beam is fully charged up. Type fire\n"); scanf("%s", action); for(i=0;i<strlen(action);i++) { action[i] = tolower(action[i]); } while(strcmp(action, "fire") != 0) { puts("Type fire to fire the plasma beam\n"); scanf("%s", action); for(i=0;i<strlen(action);i++) { action[i] = tolower(action[i]); } } printf("%s has suffered a fatal blow from plasma beam\n", monster); } puts("A list of numbers would be displayed on the screen and you have to write the average of all numbers.\n"); int secondRound = room_37_average(); if(secondRound == 1) { puts("Now the plasma beam is fully charged up. Type fire\n"); scanf("%s", action); for(i=0;i<strlen(action);i++) { action[i] = tolower(action[i]); } while(strcmp(action, "fire") != 0) { puts("Type fire to fire the plasma beam\n"); scanf("%s", action); for(i=0;i<strlen(action);i++) { action[i] = tolower(action[i]); } } printf("%s has suffered a fatal blow from plasma beam\n", monster); } if(firstRound + secondRound == 2) { printf("Congrats you were able to fire two plasma beams on %s\n", monster); printf("%s is now down and you have earned the respect of rest of two monsters\n", monster); } else if(firstRound + secondRound == 1) { printf("You were able to fire only one plasma beams on %s\n", monster); printf("Its a draw and you haven't earned any respect from the monsters\n"); } else { printf("You weren't able to fire any plasma beams on %s\n", monster); printf("You have run away and monsters have emerged victorious\n"); } puts("Enter 99 to exit this room or enter any other number to repeat this room\n"); scanf("%d",&choice); } break; } case 38: { while(choice != 99) { int grade; int aCount = 0; int bCount = 0; int cCount = 0; while((grade = getchar()) != 'q') { switch(grade) { case 'a': case 'A': ++aCount; break; case 'b': case 'B': ++bCount; case 'c': case 'C': ++cCount; break; case '\n': case '\t': case ' ': default: printf("%s","Incorrect letter grade entered."); puts("Enter a new grade."); break; } printf("Enter a letter grade (press q to quit): "); scanf("%d",&grade); } printf("\nThere are "); printf("%u", aCount); printf(" A's, %u", bCount); printf(" B's, %u", cCount); printf(" C's"); printf("\nThe class average is %.1f\n",(aCount+bCount+cCount)/3.0); //puts("you open the door 38 to and found a deadly cake........"); scanf("%d",&choice); } break; } case 39: { while(choice != 99) { story(); elf(); // play();; scanf("%d",&choice); } break; } case 40: { while(choice != 99) { puts("You open the door and close it behind you."); puts("After you overcome the panic from almost drowning, you look around and You find yourself in a cave, the air is damp and you smell mold."); puts("You notice a skeleton at your feet with it's right hand clenched around something. The cave ahead leads to a tunnel and you see a door to your right."); puts("At this point you have 3 choices:"); puts("1. Examine the skeleton."); puts("2. Proceed further ahead in the cave."); puts("3. Enter the door to your right."); scanf("%d",&choice); if(choice == 1) { puts("You reach down and pry open the skeleton's hand, a finger breaks loose and you place it in your pocket. Once you pry the opject free you look at it closely in the light and see it is a live grenade and the pin springs free. You drop the grenade and dash through the cave. You can hear the grenade explode, collapsing the tunnel behind you."); puts("To be continued..."); break; } else if(choice == 2) { puts("You find yourself further ahead in the cave."); puts("To be continued...."); break; } else if(choice == 3) { puts("You enter the and close the door behind you."); printf("You hear an loud voice \" %s why do you disturb me? \" \n",name); puts("To be continued...."); break; } else { puts("wrong choice"); } } break; } } } return EXIT_SUCCESS; } void play(void) // Josue Carrillo { int i; int total = 0; int numbers[4] = {0}; int avg; for(i = 0; i < 4; i++) { numbers[i] = rand() % 100; total = total + numbers[i]; } avg = total / 5; if(avg % 2 == 0) { printf("The number is even you win!!"); } else { printf("You lose"); } } void story(void)//Josue { puts("You find yourself on the outskirts of an unknown city."); puts("You look back and there is a barrier that prevents anyone from leaving or entering this place"); puts("Having no other choice, you begin to enter the city, and from a distance, you see a huge tower at the center of this city."); puts("As you walk towards this tower, the city seems to be getting brighter with lights. You begin to see the residents of this city playing games against each other."); puts("Seeing people around, you begin to ask people, 'Where is this place?'"); puts("You ask many people, yet no one knows"); puts("Everyone seems to have the same experience, they opened a door, and you found yourself at the outskirts of this city, no way out."); puts("Yet everyone explains that playing games is the most important thing in this city."); puts("Not knowing what to do, you begin to wander around, and then find yourself in front of something familiar, a SunBucks."); puts("You enter and notice a person with pointy ears sitting near the corner of the store."); puts("You give in into your curiosity and decide to sit next to this person."); } void elf(void)//Josue { puts("As you are sit next to this person, she says: 'What do you want?'"); puts("You say, 'I was just curious, never seen a person with pointy ears'"); puts("She says, 'Are you new here'"); puts("You say, 'yes, just got here couple of hours ago'"); puts("She says, 'Ah ok, I am an elf that has lived in this city for many years. My name is Lia.'"); } int RollArray(int arr[])//lA { int y; y= rand()%6+1; arr[1]=y; return y; } void Prt(int arr[])//LA { printf("roll = %d\n", arr[1]); } void nV(char a[]) { int i,counter=0; for(i=0;i<21;i++) { switch(a[i]) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': case 'Y': case 'y': { counter++; break; } default: { break; } } } printf("\nNumber of Vowels in your name: %d \n",counter); } void BBGprnt() { puts(" [you] / 1 / 2 / 3 /"); } void TossBag(int *arr)//LA { int i; int y; int *ptr; ptr = arr; for (i=0;i<3;i++) { y= rand()%3; *(arr+y) = *(arr+y)+1; arr=ptr; } } void BagTossed(int *arr)//lA { int i; for (i=0;i<3;i++) { printf("hole #%d, has %d bag(s) in it\n", i+1 , *arr); arr++; } } //Monika void monikawelcome(char name[]) { int monikai = 0; char monikaname[256] = {0}; strcpy(monikaname, name); for(monikai = 0; monikai < 256; monikai++) { if(islower(monikaname[monikai])) { monikaname[monikai] = toupper(monikaname[monikai]); } if(isupper(monikaname[monikai])) { //printf("%c", monikaname[monikai]); } } printf("\n~Welcome %s to this minigame~\n\n", monikaname); puts("MAKE SURE THE TERMINAL IS IN FULL SCREEN WHEN RUNNING CASE 15\n"); } void monikacase1(char yellowdecision[]) { puts("You chose the yellow path, as you walk you see a hop scotch drawn on the floor\n"); puts(" ______ "); puts(" | 1 | "); puts(" _____|______|_____ "); puts("| 2 | 3 | 4 |"); puts("|_____|______|_____|"); puts(" | 5 | "); puts(" _____|______|_____ "); puts("| 6 | 7 | 8 |"); puts("|_____|______|_____|"); puts(" | 9 | "); puts(" |______| "); puts(" | 10 | "); puts(" |______| \n"); puts("do you want to play with it?\ny or n\n"); scanf(" %s", yellowdecision); //prints hopscotch if(strcmp(yellowdecision, "y") == 0) //if its equal to each other //0 = true, !0 == false { int jumps = 0; int i = 0; char anotherRoll[2]; int yellowTries = 0; while(jumps != 6) { yellowTries++; i = 0; for(i = 0; i < 2; i++) { puts("You stand infront of the first box, and you find a 6 sided die,\nnext to the die theres a note that says to roll the die in order to jump.\nDo you want to roll? (y or n)\n"); scanf(" %s", anotherRoll); //while the choices are wrong, do the below //but if its right it will exit and move forward if(strcmp(anotherRoll, "y") == 0) { jumps = (rand() % 6) + 1; //above prints one int if(jumps != 6) { printf("You got %d from the die, it wasnt enough to go to the other side, re-roll.\n", jumps); } else { printf("You got %d, you can pass\n", jumps); break; } } else { puts("ok, bye\n"); exit(1); } } if(jumps == 6) { break; } else { puts("\nYou ran out of attempts, good bye\n"); break; } } } else if (strcmp(yellowdecision, "n") == 0) { FILE *monikasponge; char filesponge[200] = "sponge.txt", spongePrint; // Open file monikasponge = fopen(filesponge, "r"); if (monikasponge == NULL) { printf("Wrong file name, retry \n"); exit(0); } // Read contents from file spongePrint = fgetc(monikasponge); while (spongePrint != EOF) { printf("%c", spongePrint); spongePrint = fgetc(monikasponge); } puts("I dOnT wAnT tO pResS yEs\n"); puts("\nbye\n"); fclose(monikasponge); exit(1); //return 0; //exits u from the program } } void monikacase2(char reddecision[]) { char key[20]; char monikausertry[20], pressF[2]; FILE *monikaoutput, *Deciphered; monikaoutput = fopen("monikaoutput.txt", "w"); Deciphered = fopen("Deciphered.txt", "r"); puts("Youve chosen the red road, and you see a blue tunnel. You enter and you\nsee a wall with a code pad on it, its asking if you\nwant to see the prompt to move forward. Do you say yes or no? (y or n)\n"); scanf(" %s", reddecision); //create a text thing where we show the user the file and we make them //deciper the code and if its right they will move forward int keepLooping = 1; while(strcmp(reddecision, "y") == 0 && keepLooping == 1) { printf("\nDecipher the following text: \nOnce you have an answer, input it below\n"); puts("\n71 97 114 114 101 116 116 66 108 117 80 111 112 112 101\n"); //text file to decipher puts("Need a hint? Ask the key\n"); scanf(" %s", monikausertry); //if yes then we will prompt the text and ask to deciper fscanf(Deciphered, " %s", key); if(strcmp(monikausertry, key) == 0) //check if the same then continue { puts("\nPIN UNLOCKED\n"); puts("You can see your previous attempts in the monikaoutput.txt file"); if(strcmp(monikausertry, key) == 0) { puts("\nYour sight is filled with darkness and the glistening of the water as it shines from the light behind you."); puts("You begin to move forward and get into the water but it feels weird. You think maybe its because its cold so you just dismiss it."); puts("You continue but you begin to feel a burning sensation on your body and you begin panicking,\n'what's in this water'"); puts("As you look for something to grab to get out of the water\nyour eyes lock on to a warning label on the side of the river, reading: 'WARNING: SULFURIC ACID REMAINS IN THE WATER\nIF IN CONTACT, PERISHABLE'\n"); puts("YOU DIED\n"); exit(1); } keepLooping = 0; } else { fprintf(monikaoutput, "Failed Attempt: %s\n", monikausertry); } fprintf(monikaoutput, "\n"); } rewind(monikaoutput); fclose(monikaoutput); if(strcmp(reddecision, "n") == 0) { puts("You said no\n"); puts("You tried going back to the entrance and fell through a dirt hole and died, press f to pay respects\n"); scanf(" %c", pressF); if(strcmp(pressF, "f") == 0) { exit(1); } else { puts("fine then, dont pay respects\n"); exit(1); } } } void monikacase3(char greenchoice[]) { puts("Do you want to continue green path? (y or n)\n"); scanf(" %s", greenchoice); if(strcmp(greenchoice, "y") == 0) { FILE *monikanothing; char filenothing[200] = "nothing.txt", nothingPrint; // Open file monikanothing = fopen(filenothing, "r"); if(monikanothing == NULL) { printf("Wrong file name, retry \n"); exit(0); } // Read contents from file nothingPrint = fgetc(monikanothing); while(nothingPrint != EOF) { printf("%c", nothingPrint); nothingPrint = fgetc(monikanothing); } puts("\nyoure welcome\n"); fclose(monikanothing); exit(1); } else if(strcmp(greenchoice, "n") == 0) { int monikai = 0, monikasize = 5, monikasum = 0, monikaArray[monikasize]; int *monikaPointer; monikaPointer = monikaArray; printf("Fine since you dont want to go the path you can play this boring calculator game\nInsert five numbers you want to add and find the sum of\n"); for(monikai = 0; monikai < monikasize; monikai++) { scanf(" %d", &monikaArray[monikai]); } printf("Things inputted are: \n"); monikasize = 5; for(monikai = 0; monikai < (monikasize - 1); monikai++) { printf(" %d\n", *monikaPointer); monikaPointer++; } monikasize = sizeof(*monikaPointer) / sizeof(int); printf(" + %d \n---------\n", monikaPointer[monikasize - 1]); monikasum = 0; monikasize = 5; for(monikai = 0; monikai < monikasize; monikai++) { monikasum += monikaArray[monikai]; } printf("sum : %d\n", monikasum); int monikaaverage = 0; monikaaverage = (double)monikasum / (double)monikasize; printf("Average: %.1lf\n", (double)monikaaverage); exit(1); } } //Monika char *randomString(char *p) { int randLine = rand() % 100; int i = 0; FILE *rfPtr; if((rfPtr = fopen("randomStrings.txt", "r")) == NULL) { puts("File could not be opened."); } else { while(fgets(p, 11, rfPtr) != NULL) { if(i == randLine) { fclose(rfPtr); return p; } else { i++; } } fclose(rfPtr); } return p; } void mQhelpPrompt(void) { puts("-----------------------------------------------------------------------------------------"); puts("Type 'help' at any time to see the Help menu, which has a list of commands you can use.\n"); puts("-----------------------------------------------------------------------------------------"); } void mQhelpMenu(void) { puts("--------------------------------------------------------------------------------------------------"); puts("Usable Commands: inv, go, look, use, and exit\n"); puts("Type 'inv' to see your inventory"); puts("Type 'go' followed by a location to move towards it"); puts("Type 'look' followed by an object OR location to inspect it."); puts("Type 'use' to use an object from your inventory, OR obtain it and put it in your inventory."); puts("\nType 'exit' to leave the parser."); puts("'Any noun in capital letters - like THIS - can be used with commands (example: use KEY, look TABLE"); puts("--------------------------------------------------------------------------------------------------"); } void mQcontinue(void) { printf("(Press 0 and Enter to continue)"); fflush(stdout); //do I need this? while(getchar() != '0'){}; } int mQuserInput(void) { //fflush(stdout); printf(" "); printf("\n------> "); return fgets (uInput, sizeof(uInput), stdin ) != NULL; } int mQparser(void) { char *word1 = strtok(uInput, " \n"); char *word2 = strtok(NULL, " \n"); if (word1 != NULL) { // command "exit" if (strcmp(word1, "exit") == 0) { puts("Insert clever start-over text here. Maybe a little 'are you sure you want to quit?' or whatever"); return 0; } // command "help" else if (strcmp(word1, "help") == 0) { mQhelpMenu(); } // command "inv" else if (strcmp(word1, "inv") == 0) { puts("The user only has 'updog' in their inventory.\n"); } // command "look" else if (strcmp(word1, "look") == 0) { // look stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user looks at the stove. The user loves a good stove. This one has electric burners though, so it's not a good stove. The user frowns and wishes they picked another student's door."); } // look fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nThe fridge's stainless steel surface is littered with post it notes. You pick one up and angle your cell phone to read it."); puts("\n\n'If one more person eats my leftovers without permission, I will COMMMIT A FELONY. I MEAN IT!!!!!'"); puts("\nFrowning, you turn it over to discover there's more written on the back."); puts("\n'Actually, you know what? YOU KNOW WHAT?! Eat them. Go on. I dare you. Eat all of it. I hope you choke on a piece and die in agony right here on my KITCHEN FLOOR. YOU SHOULD HAVE NEVER BEEN BORN. - J'"); puts("\nYou find yourself wondering who the hell this 'J' is, and what made them upset enough to cover their refridgerator with passive aggressive post-its."); } // look freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nThe freezer's stainless steel surface is littered with post it notes. You pick one up and angle your cell phone to read it."); puts("\n'Jim, I swear to God, if you move the eggs again to put more post-it notes inside, I will buy the dollar store brand of BBQ sauce from now on. Do not try me, young man. - H'"); puts("\nAnother post-it note is attached to the end of this one. It reads: "); puts("\n'I DO NOT FEAR DEATH OR DRY CHICKEN NUGGETS! I WILL NOT BE MANIPULATED BY THE SAUCE! \nI have an emergency stash of Sweet Baby Rays for just this occasion, anyway. -J'"); puts("\nYou are baffled by just how much writing can fit on a post-it note. Your eyes are starting to hurt from squinting at all the tiny writing.\n"); } } // command "go" - CONSIDER REMOVAL else if (strcmp(word1, "go") == 0) { // go stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user goes to the stove. Good job. You're at the stove. You did it. Wonderful."); } // go fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nThe user approaches the fridge. The distance...it's still too much. You must get closer..."); puts("\nThe user presses their cheek against the fridge, wrapping their arms around as far as they can reach."); puts("\nThe fridge does not hug you back, but you somehow feel a brief reprieve from your loneliness, nonetheless."); } // go freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nYou approach the freezer."); puts("\nYou think of a few cold-related puns, but you quickly banish them from your mind. Puns are the lowest form of comedy, of course, and you'd be a shameless wreck before you'd ever entertain one, even in your head."); puts("\nIf thought to yourself just now, 'Now, that's just cold...', you, in fact, did not. You didn't think anything at all. You don't think. Your head is empty. Go shove your stupid head full of puns in the freezer."); } } // command "use" else if (strcmp(word1, "use") == 0) { // use stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user uses the stove. The stove says 'get the hell out of my kitchen.' The user does not, in fact, get the hell out of the kitchen."); } // use fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nYou pull gently on the fridge handle, and are greeted with its soft inner glow and a faint whiff of eggs and...old onions? Ugh."); puts("\nYou see a small bowl of LEFTOVERS, a bottle of Sweet Baby Ray's bbq SAUCE, and a can of Natural Light BEER. There are post-it notes on each."); } // use freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nThe user pulls swiftly against the hermetic seal of the freezer, and is met with a small puff of chilled air."); puts("\n...followed closely by a much stronger, more decidedly *pungent* whiff of egg."); puts("\nBlinking rapidly to ensure they aren't seeing things, the user realizes the entire fridge is full of decorated frozen easter eggs. A small post-it note on eye-level with the user reads: 'Little Jimmy's Easter Eggs, 1987. DO ***NOT*** THROW AWAY!!!'"); puts("\nHorrified, the user sincerely wishes they had found a dead body instead."); puts("\nThere is an additional NOTE wedged in between the freezer wall and the awful, awful Egg Pile."); } // funny joke else if (strcmp(word2, "updog") == 0) { puts("\nNothin, what's up with you, man?\n"); puts(" ( ͡° ͜ʖ ͡°) "); puts("..."); puts("\nThis joke would have been better if I had figured out how to open a webpage to www.updog.com like I had originally planned."); } } // dumb parser else { printf("\nI have no idea how to %s, but knock yourself out.", word1); } } return 1; } // Talise void printMessage(int msg[]) { int i = 0; printf("Message: "); while(i < 10) { printf("%d ", msg[i]); i++; } printf("\n"); } void decodeMessage(char alphabet[], int codedMessage[], int *totalGuesses, int *wrong) { int i, x; char guess; char c; puts("Decode the message: "); for(i = 0; i < 10; i++) { printf("Enter lowercase guess for %d: ", codedMessage[i]); scanf(" %c", &guess); x = (codedMessage[i] - 1); c = alphabet[x]; if(guess == c) { (*totalGuesses)++; } while(guess != c) { printf("Try again. Enter lowercase guess for %d: ", codedMessage[i]); scanf(" %c", &guess); (*totalGuesses)++; (*wrong)++; } } } void userFate(int x) { int i, score; double avg = 0.0; double sum = 0.0; switch(x) { case 1: { puts("You are free."); break; } case 2: { puts("You decoded the message, but now you must enter 3 test scores: "); break; } } if(x == 2) { for(i = 0; i < 3; i++) { printf("Enter score: "); scanf("%d", &score); sum += score; } avg = sum / 3; printf("Your test score average is: %.2lf \n", avg); } } void printRollResults(int rolls[], int numberOfRolls, int isUser) // Manuel Castaneda { if (isUser) { printf("You rolled: "); } else { printf("they rolled: "); } int i; for (i = 0; i < numberOfRolls; i++) { printf("%d ", rolls[i]); } printf("\n"); } double averageM(int rolls[], int numberOfRolls) // Manuel Castaneda { int i, sum = 0; for (i = 0; i < numberOfRolls; i++) { sum = sum + rolls[i]; } return sum / (double)numberOfRolls; } double sumM(double sums[], int maxSums) // Manuel Castaneda { int i = 0; double sum = 0; for (i = 0; i < maxSums; i++) { if (sums[i] == 0) { break; } sum = sum + sums[i]; } return sum; } void printIntroduction(void) // Manuel Castaneda { puts("\n\nYou walked into a secret casino."); puts("The door closes behind you."); puts("The only way to leave is to play a game Dice Average."); } void printRules(int rollsPerTurn, int pointsToLoose) { puts("\nRules:"); printf("- Each turn, you and two other players will choose if you wish to roll %d dice.\n", rollsPerTurn); printf("- The average number of the %d dice are added to your score.\n", rollsPerTurn); printf("- Who ever can get their score closest to %d wins. If your score goes above %d then you loose.\n", pointsToLoose, pointsToLoose); puts("- Before each turn, the dice values increase."); puts("- After each turn, you will get an opportunity to roll again or stop rolling."); puts("- If you choose to stop rolling, you can no longer roll for the rest of the game."); } // Manuel Castaneda // Tien Tran Function void room_37_read_instructions_from_file() { int bufferLength = 255; char buffer[bufferLength]; FILE *rptr; rptr=fopen("instructions_room_37","r"); if (rptr == NULL) { puts("You open a door and you find 3 monsters standing right in front of you.\n\n"); puts("You must take on one monster to prove your authority over them.\n"); puts("You can\n"); puts("-> Press 1 to tackle Godzilla\n"); puts("-> Press 2 to tackle King Ghidorah\n"); puts("-> Press 3 to tackle King Kong\n\n"); puts("Unlike the movies just defeating one of them will show your courage to others and they will back out.\n\n"); puts("What is your choice Hero?\n"); } else { while(fgets(buffer, bufferLength, rptr)) { printf("%s", buffer); } } } // Tien Tran Function int room_37_guess_number(int number) { int guess; int guesses_remaining = 10; while(guesses_remaining != 0) { guess = room_37_prompt_guess(1, 30); if(guess == number) { puts("You guessed right. Congrats\n"); break; } else if(guess > number) { puts("Your guess is greater than the number"); } else { puts("Your guess is less than the number"); } guesses_remaining--; } if(guesses_remaining != 0) { return 1; } return 0; } // Tien Tran Function int room_37_prompt_guess(int minimum, int maximum) { printf("Enter your guess between %d and %d inclusive\n", minimum, maximum); int guess; scanf("%d", &guess); while(!(guess >=minimum && guess <= maximum)) { printf("Enter your guess between %d and %d inclusive\n", minimum, maximum); scanf("%d", &guess); } return guess; } void printResults(int z, int a) { //Carlos Gonzalez int i; FILE *wpointer; wpointer = fopen("output.txt", "a"); if(a == 1) { if(z == 1) { puts("\nYou reverse the time stop on DIO for 9 seconds."); puts("You find a road roller, crush him with it, and throw a flurry of punches at it."); puts("After the 9 seconds pass the road roller explodes killing DIO, you win."); printf("Check your ouput file for your win screen\n"); for(i = 0; i <= 99; i++) { fprintf(wpointer, "ORA ORA ORA\n"); } } if(z == 0) { printf("\nYour health drops below zero and DIO crushes you with a road roller, you are dead\n"); printf("Check your ouput file for your lose screen\n"); for(i = 0; i <= 99; i++) { fprintf(wpointer, "GAME OVER GAME OVER GAME OVER\n"); } } } if(a == 2) { if(z == 1) { puts("\nYou acquire the requiem arrow and undergo a transformation making you the strongest on earth."); puts("Diavolo attempts to use epitaph to attack, but has his attack is automatically deflected by Golden Experience Requiem."); puts("You place him in an infinite death loop and become the ultimate gang star."); printf("Check your ouput file for your win screen\n"); for(i = 0; i <= 99; i++) { fprintf(wpointer, "MUDA MUDA MUDA\n"); } } if(z == 0) { printf("\nYour health drops below zero and King Crimson punches you straight through the chest, you are dead\n"); printf("Check your ouput file for your lose screen\n"); for(i = 0; i <= 99; i++) { fprintf(wpointer, "GAME OVER GAME OVER GAME OVER\n"); } } } fclose(wpointer); } int dpsCalc(int x, int y, int a) { //Carlos Gonzalez double avg = 0; int i = 0, select = 0, dmg = 0, enemyDmg = 0; if(a == 1) { while(y > 0 && x > 0) { puts("\nAttacks: "); puts("1. ORA Rush"); puts("2. Star Finger"); puts("3. Block"); puts("Choose a move"); scanf("%d", &select); switch(select) { case 1: { dmg = (rand() % 20) + 15; enemyDmg = (rand() % 20) + 9; y = y - dmg; x = x - enemyDmg; avg += dmg; i++; puts("You and DIO trade close range consecutive blows\n"); printf("You deal %d points of damage\n", dmg); printf("You take %d points of damage\n", enemyDmg); printf("Your health %d, DIO health %d\n", x, y); break; } case 2: { dmg = (rand() % 20) + 10; enemyDmg = (rand() % 20) + 5; y = y - dmg; x = x - enemyDmg; avg += dmg; i++; puts("You extend your forefinger to attack DIO, and he counters with a knife throw\n"); printf("You deal %d points of damage\n", dmg); printf("You take %d points of damage\n", enemyDmg); printf("Your health %d, DIO health %d\n", x, y); break; } case 3: { enemyDmg = (rand() % 20) + 80; printf("DIO stops time for 3 seconds and throws enough knives to surround you from all sides, this is equivalent to %d points of damage. \n", enemyDmg); puts("Luckily you and DIO have the same type of stand and you are able to deflect all the knives at the last second"); puts("You take no points of damage"); break; } default: { puts("invalid input, try again."); break; } } } } if(a == 2) { while(y > 0 && x > 0) { puts("\nAttacks:"); puts("1. MUDA Rush"); puts("2. Create life"); puts("3. Life shot"); scanf("%d", &select); switch(select) { case 1: { dmg = (rand() % 20) + 15; enemyDmg = (rand() % 20) + 9; y = y - dmg; x = x - enemyDmg; avg += dmg; i++; puts("You and Diavola trade close range consecutive blows\n"); printf("You deal %d points of damage\n", dmg); printf("You take %d points of damage\n", enemyDmg); printf("Your health %d, DIO health %d\n", x, y); break; } case 2: { dmg = (rand() % 20) + 10; enemyDmg = (rand() % 20) + 5; y = y - dmg; x = x - enemyDmg; avg += dmg; i++; puts("You create a piranha out of some rocks next to you and they seek out Diavolo, he counters with a time erase followed by a devastating punch\n"); printf("You deal %d points of damage\n", dmg); printf("You take %d points of damage\n", enemyDmg); printf("Your health %d, DIO health %d\n", x, y); break; } case 3: { dmg = (rand() % 20) + 20; enemyDmg = (rand() % 20) + 11; y = y - dmg; x = x - enemyDmg; avg += dmg; i++; puts("You punch Diavolo and imbue him with life energy, this puts him into an out of body mindstate making him vulnerable to taking more damage. \n"); printf("The attack lands and deals %d points of damage\n", dmg); puts("Upon exiting this state, Diavolo responds with Epitaph allowing him to move into the future and land a devasting blow of his own. "); printf("You take %d points of damage\n", enemyDmg); printf("Your health %d, DIO health %d\n", x, y); break; } default: { puts("invalid input, try again."); break; } } } } avg = avg / (double)i; printf("\nYour average damage was %.2f\n", avg); if(x > 0 && y <= 0 ) { return 1; } if(x <= 0 && y > 0) { return 0; } if(x <= 0 && y <=0) { printf("You both kill eachother"); return 0; } } // Tien Tran Function int room_37_average() { int arr[10]; int i,size=10; double average = 0.0; double num; room_37_fill_array(arr, size); for(i=0;i<size;i++) { printf("%d ", arr[i]); average+=arr[i]; } average /= size; puts("\n"); puts("What is the average of above numbers?\n"); scanf("%le", &num); if(num == average) { puts("Congrats you guessed the average correctly\n"); return 1; } else { printf("Sorry the average is %lf\n", average); return 0; } } // Tien Tran Function void room_37_fill_array(int *pntr, int size) { int i; for(i=0;i<size;i++) { *pntr=(rand() % 20) + 1; pntr++; } } //Richard Vela, demondoor, angelicdoor, broomcloset are for door 11 void demondoor(void) { int choice; char chararray[10]; printf("You chose the demonic looking door\n"); printf("The stone door budges open slowly to reveal a sinsiter cave with what looks like lava cracks lining the walls dimly lighing up the cave"); printf("The cave is very sketchy so you decide that if you feel threatened you will simply run back out the door and you can start over.\n"); printf("If you wish to leave now press 777, otherwise enter any other number\n"); scanf("%d",&choice); while (choice != 777) { printf("After walking for a while you stumble upon a weird reflective crystal wall. Every time you touch it, the area that was touched glowed like a weird finger painting wall.\n"); printf("You start drawing and after writing words realize it inverses the capitalization of letters.\n"); printf("You decide to write a lowercase word and see what happens\n"); printf("Insert text:\n"); scanf("%s", chararray); printf("The wall repeats back: "); for(int i=0;i<10;i++) { chararray[i] = toupper(chararray[i]); } printf("%s",chararray); printf("\n"); printf("You then decide to try writing an uppercase word\n"); printf("Insert text:\n"); scanf("%s", chararray); printf("The wall repeats back: "); for(int i=0;i<10;i++) { chararray[i] = tolower(chararray[i]); } printf("%s",chararray); printf("\n"); printf("It's a neat novelty but it gets old quickly so you continue on.\n"); printf("You keep going into a cave when suddently around a corner you see a deep gorge with a lava river at the bottom.\n"); printf("You find a bridge and decide to cross it despite how unstable it is, like the one they cross over the lava moat in shrek\n"); printf("You cross it and immidetly it colaspes into the lava, and you find that foreward is only a dead end, oh no.\n"); printf("You look around and realize up ahead is just a dead end without a way out. You turn back to see theres no way to get off of this small cave in front of the"); printf("Just as panic begins to set in, you suddently wake up and find yourself at home in bed. You realize everything was just a dream. Or was it really?\n"); exit(0); break; } } //Richard Vela, demondoor, angelicdoor, broomcloset are for door 11 void angeldoor(char name[]) { int choice=0; int i,x,y; int sum = 0; char idolnote; float average; FILE *rptr; rptr = fopen("idolnote.txt", "r"); srand(time(NULL)); printf("You chose the ancient angelic door\n"); printf("You walk in and all of a sudden find yourself in a peaceful rainforest next to a waterfall.\n"); printf("You walk forward into the forest and find a temple, in the middle of which is an altar with a pair of golden die on the altar.\n"); printf("A loud and deep disembodied voice begins to speak and says:\n"); printf("Welcome, %s, to the temple of Shangri-La.\n",name); printf("I noticed your name is %ld letters long, very well.\n", strlen(name)); printf("This temple contains a pair of ancient die used to decide the fates of people each year in the ancient civilization that used to be here, but since the civilization died out centuries ago, the die have sat here waiting for another person to use them.\n"); printf("Roll the die, if you get an even tally, you get good fortune, however, roll an odd tally, you will die instantly.\n"); printf("press 1 to roll die\n"); scanf("%d",&choice); if (choice == 1) { printf("*rolls die*\n"); for(i=0;i<2;i++) { y = rand()%6+1; x = rand()%6+1; } sum = x + y; printf("First dice was %d and the second one was %d\n",x,y); printf("Your total number is %d\n", sum); average = (float)(x + y)/2; printf("The average of that roll was %.2f\n",average); switch (sum) { case 3: case 5: case 9: case 11: printf("%s, unfortunately you have recieved an odd total.\n",name); printf("You Died\n"); exit(0); break; case 7: printf("%s, you got a 7, but unfortunately in this case it is not a lucky number\n",name); printf("You Died\n"); exit(0); break; case 2: case 4: case 6: case 8: case 10: case 12: printf("Congratulation, %s, you have been chosen by the ancient gods to recieve a gift from the heavens.\n",name); printf("That gift is being able to go home alive. You probably don't want to stay here for the rest of your life despite it's beauty, and you would have a hard time making it home seeing that the door disapeared right as you stepped through it.\n"); printf("Even if you expected to get some great super power or riches, the true blessing is being able to go home after taking such a risk as rolling those dice, so i shall send you back home. Goodbye.\n"); printf("\n"); printf("\n"); printf("You suddently collapse on the ground unconscious. After an unknown amount of time, you awake in your bed at home and find a golden idol similar to the one from Indiana Jones on your nightstand next to you. There is a note that reads:\n"); idolnote = fgetc(rptr); while(!feof(rptr)) { printf("%c", idolnote); idolnote = fgetc(rptr); } fclose(rptr); break; } } else { printf("You did not choose 1\n"); } exit(0); } //Richard Vela, demondoor, angelicdoor, broomcloset are for door 11 void broomcloset(void) { char usertext[100]; FILE *fptr = fopen("leatherjournal.txt", "w"); printf("You chose the broom closet. Great.\n"); printf("You walk in and see it is a dim and dank medium sized room full of old wooden barrels and cleaning supplies\n"); printf("On one of the barrels you find an old leather journal\n"); printf("'It's blank' you think to yourself\n"); printf("Inside the cover is a pen, you decide to write in it to see if the pen still works\n"); printf("Enter a word:\n"); scanf("%s", usertext); fprintf(fptr, "%s", usertext); puts("Check leatherjournal.txt to see what you've written"); fclose(fptr); printf("Theres literally nothing but boring barrels and old janitorial supplies in here. I should go see what the other doors do.\n"); printf("You decide to go back to the closet door and prepare to reopen it,\n"); } //Benjamin Lozano Functions start void greenUSB26(int arrInt26[], int size) { int greenChoice = 0; int targetCoulumn; int targetRow; int i,j; printf("\nAs you walk closer to the green USB, you read the message above, it states...\n"); printf("\t#2\n"); printf("There are two options you consider\n"); printf("1) plug the green USB into the laptop.\n"); printf("2) Step back and view the room again.\n"); printf("Enter choice 1-2: "); scanf("%d", &greenChoice); if(greenChoice == 1) { printf("You plug the green USB into the laptop and a window pops up\n"); targetCoulumn = rand()%3 + 1; targetRow = rand()%3 + 1; for(i = 0; i < 3; i++) { for(j = 0; j < 3; j++) { printf("%d ", arrInt26[j]); } printf("\n"); } } else { printf("You step back and view the room again.\n"); } } void blueUSB26() { int blueChoice; printf("\nAs you walk closer to the blue USB, you read the message above, it states...\n"); printf("\t#3\n"); printf("There are two options you consider\n"); printf("1) Plug the blue USB into the laptop.\n"); printf("2) Step back and view the room again.\n"); printf("Enter choice 1-2: "); scanf("%d", &blueChoice); if(blueChoice == 1) { printf("blue USB game\n"); } else { printf("You step back and view the room again"); } } void redUSB26() { int redChoice; printf("\nAs you walk closer to the red USB, you read the message above, it states...\n"); printf("\t#1"); printf("There are two options you consider\n"); printf("1) Plug the red USB into the laptop.\n"); printf("2) Step back and look at the room again.\n"); printf("Enter choice 1-2: "); scanf("%d", &redChoice); if(redChoice == 1) { printf("Red USB game\n"); } else { printf("You step back and view the room again.\n"); } } void lockedDoor26() { printf("As you walk closer to the door on the other side you see a keypad lock...\n"); printf("The numbers range from 0-9...\n"); } //Benjamin Lozano end functions /* Start of Room 19 (Jonathan Chua) Function Definitions */ void room19_readFile(FILE *readPtr) { /* Criteria : Pointers and While Loop */ system("clear"); char string[256]; while(fgets(string,sizeof(string),readPtr) != NULL) { printf("%s",string); } } int doorDecision(void) { /* Criteria : Character Function */ char choice; printf("Do you open the door? [Y]es [N]o : "); scanf(" %c", &choice); if(tolower(choice) == 'n') { return 99; } else { return 1; } } /* End of Room 19 Function Definitions */ void patrickInitialPrompt(void) { puts("1. Do you open the door that is 50 feet in fron of you?"); puts("2. Do you simplay stand there and wait for the noise to get clearer on it's own?"); puts("3. There is an old, oriental gentleman in the corner which is lit up by a torch. Do you approach him?"); } int coolGuysInteract(void)//Markease Harris { } //AndyV int urGuess(void) { int y; puts("Pick a number between 1 and 10"); scanf("%d", &y); return y; } //AndyV int Anumber(int a[], int urGuess) { int i, x; for(i = 0; i < 2; i++) { x = (rand() %10 + 1); a[i] = x; } if(urGuess < 1 || urGuess > 10) { return 0; } if(a[i] == urGuess) { return i; } return -1; } void stars(void) { int n,m,i,k,j; //printf("how old are you by the way?\n"); //scanf("%d",&n); int z = (rand()%50)+1; m = z; for(i = 1; i <= z; i++) { for(j = 1; j <= m-1; j++) { printf(" "); } for(k = 1; k <= 2 * i - 1; k++) { printf("*"); } m--; printf("\n"); } puts("Woooaaahhh get ready for Hyper Drive \n"); } void flurbos(void) { int sum = 0; int number; int test; float average; int x,y; puts("Please enter how many games you want to play.\n"); scanf("%d", &x); puts("Enter the amount of Flurbos that you will need for that game, one by one\n"); for(y = 0; y < x; ++y) { scanf("%d", &number); sum = sum + number; } average = sum / y; printf("You will need an average of %.2f Flurbos, for your first time at Blips\n",average); } void planets(void) { int planet = 0; char keyword[] = "Red"; char input[3]; puts("your choices are 1.Alphabetrum, 2.Bird World, or 3.Unity's Planet"); scanf("%d", &planet); puts("\n"); switch (planet) { case 1: { puts("Morty Narrating.... \n"); puts("Cool, we are heading to Alphabetrum \n"); puts("This planet is inhabited by an ancient race who resemble giant letters of various alphabets. It's ruled by a council, which consists of Helium-Q, Magnesium-J, and Hydrogen-F"); puts("\n"); puts("It's the homeworld of Ice-T, an exiled native of Alphabetrium who became a well known rapper on Earth. After Ice-T saved Earth from being destroyed by the Cromulons, the elders of Alphabetrium received word from across the galaxy of Ice-T's heroism and relieved him of his exile, granting him of his true form Water-T.\n"); puts("\n"); puts("Wait what is that noise? Oh wait I think there is something wrong with the space cruiser \n"); puts("Quick we need to fix these warnings, please type Red to cancel all the warining buttons that are going off \n"); while(strcmp(input,"Red")) { scanf("%s", input); if(strcmp(input, "Red") == 0) { printf("\n"); printf("Great you fix all the warnings !! \n"); printf("We can continue our jouney \n"); printf("Lets hope Rick does not find out about this\n"); break; } else { printf("Hurry, please type Red to cancel all the warining buttons that are going off \n"); } } break; } case 2: { puts("Morty Narrating.... \n"); puts("Cool, we are heading to Bird World \n"); puts("Bird World is the planet where Birdperson lives. TV-signals from Earth take 20 years to reach this planet, meaning it's 20 light-years away from Earth, although in the season 2 finale The wedding squanchers, Rick claims that Bird world is over 6,000 light years away. \n"); puts("\n"); puts("Bird People live in wooden structures often incorporated into trees, but do possess technology like TV. They primarily eats worms and have worm ranches around on the planet. When sending messages they may tend to use robotic eggs with hologram messages, or it is technology by Tammy. In Bird culture, mate-melding is the equivalent of marriage on Earth."); puts("\n"); puts("Seems like we are having some engine problems we are going to have to stay here untill we can get it fix. \n"); puts("Whats this, looks like rick left us a note lets sees what it says\n"); noteFromRick(); break; } case 3: { puts("Morty Narrating.... \n"); puts("Cool, we are heading to Unity's Planet \n"); puts("\n"); puts("The planet Unity was entirely assimilated, and plans to use to assimilate the Galactic Federation. However, Unity left the planet with its people following certain events with Rick. \n"); puts("\n"); puts("The inhabitants are blue-skinned humanoids with three yellow-tipped protrusions on their heads. There are differences in nipple structure as some have flat concentric nipple rings, and others have cone nipples. In the absence of Unity's control, the inhabitants instantly devolve into starting a race war based on their nipple differences. The unassimilated crew of the S.S. Independence do not exhibit this, but they may have all been of a similar nipple-type. The entire planet's population disappeared after Unity decided to leave Rick, and went to stay with Beta-Seven."); puts("\n"); break; } } } void goodBye(void) { int i; char message[] = {"Good Bye"}; char *m = message; for(i = 0; i<sizeof(message);i++) { printf("%c",*m); m++; } } void noteFromRick(void)//Berenis Castruita { FILE *wptr; char read; char rs[100]; wptr = fopen("note.txt", "r"); if(wptr == NULL) { printf("Oh never mind, it wasn't a note\n"); exit(1); } while((read = fgetc(wptr)) != EOF) printf("%c", read); fclose(wptr); }
the_stack_data/17814.c
/* Autor (usuario): mynorjrv Fecha: Sun 21 Mar 2021 09:52:47 PM CST compilador: gcc (Debian 8.3.0-6) 8.3.0 Para Compilar: gcc -o PrimosenRango PrimosenRango.c Version: 1.0 librerias: stdio (u otras) Resumen: Muestra los primos en un rango de números. Entradas: Salidas: */ //Librerias //Recuerde añadirlas al header #include <stdio.h> int N1, N2; int i, j; int primo; int main(void){ printf("Primos en un intervalo \n"); printf("Ingrese el límite inferior del intervalo: "); scanf("%i", &N1); printf("Ingrese el límite superior del intervalo: "); scanf("%i", &N2); printf("Primos en este intervalo: "); i = N1; //Lo único diferente es meter lo de primo a un while while( i <= N2){ //Empieza subproceso, esliteralmente Primo cambiando variables j = 2; primo = 1; while ( j<(i-1) && (primo==1) ){ if (i%j==0) primo = 0; j++; } //Termina subproceso //Imprime sólo si es primo if (primo==1) printf("%i ", i); i++; } //una línea extra por estética printf("\n"); return 0; }
the_stack_data/1241599.c
#include <stdio.h> int main(void) { int w,h,b,sum; long long int to; double re; scanf("%d", &w); sum=1; for(h=0; h<=w; h++){ if(0==h%3)continue; printf("%d ",h); } return 0; }
the_stack_data/243894024.c
#include <stdio.h> #include <stdlib.h> int main() { system("color 5f"); //1,1,1,1,2,2,3,4,4, 1,2,3,4 int i,a[]={1,1,2,2,2,3,4,5,5,5,6,7,8,8,9}; int n=sizeof(a)/sizeof(int); printf("%d,",a[0]); for(i=1;i<=n-1;i++) //Shivank Algorithm { if(a[i]!=a[i-1]) printf("%d,",a[i]); } }
the_stack_data/95450963.c
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n; int *arr; /* Enter your code here. Read input from STDIN. Print output to STDOUT */ scanf("%d", &n); arr = (int*) calloc(n, sizeof(int)); int i; for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } int sum = 0; for (i = 0; i < n; i++) { sum += arr[i]; } printf("%d\n", sum); free(arr); return 0; }
the_stack_data/3264107.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> char * binsh = "/bin/sh"; int main() { setvbuf(stdout, 0, 2, 0); setvbuf(stderr, 0, 2, 0); system(NULL); char * shellcode[0]; printf("Unfortunately, no one can be told what the Matrix is. You have to see it for yourself.\n"); read(0, shellcode, 64); }
the_stack_data/125141740.c
/* */ #include <memory.h> int main(void){return 0;}
the_stack_data/58510.c
// RUN: %clang -target i386-unknown-unknown -march=core2 -msse4 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE4 %s // SSE4: #define __SSE2_MATH__ 1 // SSE4: #define __SSE2__ 1 // SSE4: #define __SSE3__ 1 // SSE4: #define __SSE4_1__ 1 // SSE4: #define __SSE4_2__ 1 // SSE4: #define __SSE_MATH__ 1 // SSE4: #define __SSE__ 1 // SSE4: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=core2 -msse4.1 -mno-sse4 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NOSSE4 %s // NOSSE4-NOT: #define __SSE4_1__ 1 // RUN: %clang -target i386-unknown-unknown -march=core2 -msse4 -mno-sse2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE %s // SSE-NOT: #define __SSE2_MATH__ 1 // SSE-NOT: #define __SSE2__ 1 // SSE-NOT: #define __SSE3__ 1 // SSE-NOT: #define __SSE4_1__ 1 // SSE-NOT: #define __SSE4_2__ 1 // SSE: #define __SSE_MATH__ 1 // SSE: #define __SSE__ 1 // SSE-NOT: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentium-m -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE2 %s // SSE2: #define __SSE2_MATH__ 1 // SSE2: #define __SSE2__ 1 // SSE2-NOT: #define __SSE3__ 1 // SSE2-NOT: #define __SSE4_1__ 1 // SSE2-NOT: #define __SSE4_2__ 1 // SSE2: #define __SSE_MATH__ 1 // SSE2: #define __SSE__ 1 // SSE2-NOT: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentium-m -mno-sse -mavx -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX %s // AVX: #define __AVX__ 1 // AVX: #define __SSE2_MATH__ 1 // AVX: #define __SSE2__ 1 // AVX: #define __SSE3__ 1 // AVX: #define __SSE4_1__ 1 // AVX: #define __SSE4_2__ 1 // AVX: #define __SSE_MATH__ 1 // AVX: #define __SSE__ 1 // AVX: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentium-m -mxop -mno-avx -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE4A %s // SSE4A: #define __SSE2_MATH__ 1 // SSE4A: #define __SSE2__ 1 // SSE4A: #define __SSE3__ 1 // SSE4A: #define __SSE4A__ 1 // SSE4A: #define __SSE4_1__ 1 // SSE4A: #define __SSE4_2__ 1 // SSE4A: #define __SSE_MATH__ 1 // SSE4A: #define __SSE__ 1 // SSE4A: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512f -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512F %s // AVX512F: #define __AVX2__ 1 // AVX512F: #define __AVX512F__ 1 // AVX512F: #define __AVX__ 1 // AVX512F: #define __SSE2_MATH__ 1 // AVX512F: #define __SSE2__ 1 // AVX512F: #define __SSE3__ 1 // AVX512F: #define __SSE4_1__ 1 // AVX512F: #define __SSE4_2__ 1 // AVX512F: #define __SSE_MATH__ 1 // AVX512F: #define __SSE__ 1 // AVX512F: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512cd -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512CD %s // AVX512CD: #define __AVX2__ 1 // AVX512CD: #define __AVX512CD__ 1 // AVX512CD: #define __AVX512F__ 1 // AVX512CD: #define __AVX__ 1 // AVX512CD: #define __SSE2_MATH__ 1 // AVX512CD: #define __SSE2__ 1 // AVX512CD: #define __SSE3__ 1 // AVX512CD: #define __SSE4_1__ 1 // AVX512CD: #define __SSE4_2__ 1 // AVX512CD: #define __SSE_MATH__ 1 // AVX512CD: #define __SSE__ 1 // AVX512CD: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512er -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512ER %s // AVX512ER: #define __AVX2__ 1 // AVX512ER: #define __AVX512ER__ 1 // AVX512ER: #define __AVX512F__ 1 // AVX512ER: #define __AVX__ 1 // AVX512ER: #define __SSE2_MATH__ 1 // AVX512ER: #define __SSE2__ 1 // AVX512ER: #define __SSE3__ 1 // AVX512ER: #define __SSE4_1__ 1 // AVX512ER: #define __SSE4_2__ 1 // AVX512ER: #define __SSE_MATH__ 1 // AVX512ER: #define __SSE__ 1 // AVX512ER: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512pf -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512PF %s // AVX512PF: #define __AVX2__ 1 // AVX512PF: #define __AVX512F__ 1 // AVX512PF: #define __AVX512PF__ 1 // AVX512PF: #define __AVX__ 1 // AVX512PF: #define __SSE2_MATH__ 1 // AVX512PF: #define __SSE2__ 1 // AVX512PF: #define __SSE3__ 1 // AVX512PF: #define __SSE4_1__ 1 // AVX512PF: #define __SSE4_2__ 1 // AVX512PF: #define __SSE_MATH__ 1 // AVX512PF: #define __SSE__ 1 // AVX512PF: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512dq -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512DQ %s // AVX512DQ: #define __AVX2__ 1 // AVX512DQ: #define __AVX512DQ__ 1 // AVX512DQ: #define __AVX512F__ 1 // AVX512DQ: #define __AVX__ 1 // AVX512DQ: #define __SSE2_MATH__ 1 // AVX512DQ: #define __SSE2__ 1 // AVX512DQ: #define __SSE3__ 1 // AVX512DQ: #define __SSE4_1__ 1 // AVX512DQ: #define __SSE4_2__ 1 // AVX512DQ: #define __SSE_MATH__ 1 // AVX512DQ: #define __SSE__ 1 // AVX512DQ: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512bw -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512BW %s // AVX512BW: #define __AVX2__ 1 // AVX512BW: #define __AVX512BW__ 1 // AVX512BW: #define __AVX512F__ 1 // AVX512BW: #define __AVX__ 1 // AVX512BW: #define __SSE2_MATH__ 1 // AVX512BW: #define __SSE2__ 1 // AVX512BW: #define __SSE3__ 1 // AVX512BW: #define __SSE4_1__ 1 // AVX512BW: #define __SSE4_2__ 1 // AVX512BW: #define __SSE_MATH__ 1 // AVX512BW: #define __SSE__ 1 // AVX512BW: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512vl -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512VL %s // AVX512VL: #define __AVX2__ 1 // AVX512VL: #define __AVX512F__ 1 // AVX512VL: #define __AVX512VL__ 1 // AVX512VL: #define __AVX__ 1 // AVX512VL: #define __SSE2_MATH__ 1 // AVX512VL: #define __SSE2__ 1 // AVX512VL: #define __SSE3__ 1 // AVX512VL: #define __SSE4_1__ 1 // AVX512VL: #define __SSE4_2__ 1 // AVX512VL: #define __SSE_MATH__ 1 // AVX512VL: #define __SSE__ 1 // AVX512VL: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512pf -mno-avx512f -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512F2 %s // AVX512F2: #define __AVX2__ 1 // AVX512F2-NOT: #define __AVX512F__ 1 // AVX512F2-NOT: #define __AVX512PF__ 1 // AVX512F2: #define __AVX__ 1 // AVX512F2: #define __SSE2_MATH__ 1 // AVX512F2: #define __SSE2__ 1 // AVX512F2: #define __SSE3__ 1 // AVX512F2: #define __SSE4_1__ 1 // AVX512F2: #define __SSE4_2__ 1 // AVX512F2: #define __SSE_MATH__ 1 // AVX512F2: #define __SSE__ 1 // AVX512F2: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512ifma -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512IFMA %s // AVX512IFMA: #define __AVX2__ 1 // AVX512IFMA: #define __AVX512F__ 1 // AVX512IFMA: #define __AVX512IFMA__ 1 // AVX512IFMA: #define __AVX__ 1 // AVX512IFMA: #define __SSE2_MATH__ 1 // AVX512IFMA: #define __SSE2__ 1 // AVX512IFMA: #define __SSE3__ 1 // AVX512IFMA: #define __SSE4_1__ 1 // AVX512IFMA: #define __SSE4_2__ 1 // AVX512IFMA: #define __SSE_MATH__ 1 // AVX512IFMA: #define __SSE__ 1 // AVX512IFMA: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512vbmi -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512VBMI %s // AVX512VBMI: #define __AVX2__ 1 // AVX512VBMI: #define __AVX512BW__ 1 // AVX512VBMI: #define __AVX512F__ 1 // AVX512VBMI: #define __AVX512VBMI__ 1 // AVX512VBMI: #define __AVX__ 1 // AVX512VBMI: #define __SSE2_MATH__ 1 // AVX512VBMI: #define __SSE2__ 1 // AVX512VBMI: #define __SSE3__ 1 // AVX512VBMI: #define __SSE4_1__ 1 // AVX512VBMI: #define __SSE4_2__ 1 // AVX512VBMI: #define __SSE_MATH__ 1 // AVX512VBMI: #define __SSE__ 1 // AVX512VBMI: #define __SSSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mavx512vbmi -mno-avx512bw -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AVX512VBMINOAVX512BW %s // AVX512VBMINOAVX512BW-NOT: #define __AVX512BW__ 1 // AVX512VBMINOAVX512BW-NOT: #define __AVX512VBMI__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -msse4.2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE42POPCNT %s // SSE42POPCNT: #define __POPCNT__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mno-popcnt -msse4.2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSE42NOPOPCNT %s // SSE42NOPOPCNT-NOT: #define __POPCNT__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mpopcnt -mno-sse4.2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NOSSE42POPCNT %s // NOSSE42POPCNT: #define __POPCNT__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -msse -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSEMMX %s // SSEMMX: #define __MMX__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -msse -mno-sse -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSENOSSEMMX %s // SSENOSSEMMX-NOT: #define __MMX__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -msse -mno-mmx -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SSENOMMX %s // SSENOMMX-NOT: #define __MMX__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mf16c -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=F16C %s // F16C: #define __AVX__ 1 // F16C: #define __F16C__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mf16c -mno-avx -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=F16CNOAVX %s // F16CNOAVX-NOT: #define __AVX__ 1 // F16CNOAVX-NOT: #define __F16C__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -mpclmul -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=PCLMUL %s // PCLMUL: #define __PCLMUL__ 1 // PCLMUL: #define __SSE2__ 1 // PCLMUL-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -mpclmul -mno-sse2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=PCLMULNOSSE2 %s // PCLMULNOSSE2-NOT: #define __PCLMUL__ 1 // PCLMULNOSSE2-NOT: #define __SSE2__ 1 // PCLMULNOSSE2-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -maes -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AES %s // AES: #define __AES__ 1 // AES: #define __SSE2__ 1 // AES-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -maes -mno-sse2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=AESNOSSE2 %s // AESNOSSE2-NOT: #define __AES__ 1 // AESNOSSE2-NOT: #define __SSE2__ 1 // AESNOSSE2-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -msha -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SHA %s // SHA: #define __SHA__ 1 // SHA: #define __SSE2__ 1 // SHA-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -msha -mno-sha -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SHANOSHA %s // SHANOSHA-NOT: #define __SHA__ 1 // SHANOSHA-NOT: #define __SSE2__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -msha -mno-sse2 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=SHANOSSE2 %s // SHANOSSE2-NOT: #define __SHA__ 1 // SHANOSSE2-NOT: #define __SSE2__ 1 // SHANOSSE2-NOT: #define __SSE3__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mtbm -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=TBM %s // TBM: #define __TBM__ 1 // RUN: %clang -target i386-unknown-unknown -march=bdver2 -mno-tbm -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NOTBM %s // NOTBM-NOT: #define __TBM__ 1 // RUN: %clang -target i386-unknown-unknown -march=pentiumpro -mcx16 -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=MCX16 %s // MCX16: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mprfchw -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=PRFCHW %s // PRFCHW: #define __PRFCHW__ 1 // RUN: %clang -target i386-unknown-unknown -march=btver2 -mno-prfchw -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NOPRFCHW %s // NOPRFCHW-NOT: #define __PRFCHW__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -m3dnow -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=3DNOWPRFCHW %s // 3DNOWPRFCHW: #define __PRFCHW__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mno-prfchw -m3dnow -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=3DNOWNOPRFCHW %s // 3DNOWNOPRFCHW-NOT: #define __PRFCHW__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mprfchw -mno-3dnow -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NO3DNOWPRFCHW %s // NO3DNOWPRFCHW: #define __PRFCHW__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -madx -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=ADX %s // ADX: #define __ADX__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mrdseed -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=RDSEED %s // RDSEED: #define __RDSEED__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mxsave -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=XSAVE %s // XSAVE: #define __XSAVE__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mxsaveopt -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=XSAVEOPT %s // XSAVEOPT: #define __XSAVEOPT__ 1 // XSAVEOPT: #define __XSAVE__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mxsavec -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=XSAVEC %s // XSAVEC: #define __XSAVEC__ 1 // XSAVEC: #define __XSAVE__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mxsaves -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=XSAVES %s // XSAVES: #define __XSAVES__ 1 // XSAVES: #define __XSAVE__ 1 // RUN: %clang -target i386-unknown-unknown -march=atom -mxsaveopt -mno-xsave -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=NOXSAVE %s // NOXSAVE-NOT: #define __XSAVEOPT__ 1 // NOXSAVE-NOT: #define __XSAVE__ 1
the_stack_data/18888249.c
/* 1) Fazer um algoritmo para ler o salário de uma pessoa, o percentual de aumento e o percentual de descontos. Os descontos incidem sobre o salário com aumento. Calcular o novo salário e mostrá-lo na forma: salário de 1234 reais e 65 centavos. Observações: a) Orientar o usuário na forma como deve ser informado o percentual (por exemplo, 10 para 10% ou 0.1 para 10%), ou seja, como o programa espera que o valor seja informado. Isso é importante para definir a fórmula. b) Cálculos de percentual podem ser realizados por meio de regras de três. */ #include <stdio.h> int main(void) { float salario; float porcentual_aumento; float porcentual_desconto; float novo_salario; float novo_salario_desconto; int reais; int centavos; printf("Informe seu salario atual: "); scanf("%f", &salario); printf("Informe o porcentual de aumento ex (10 para 10%%): "); scanf("%f", &porcentual_aumento); printf("Informe o porcentual de descontos ex (10 para 10%%): "); scanf("%f", &porcentual_desconto); novo_salario = (porcentual_aumento * salario / 100) + salario; novo_salario_desconto = novo_salario - ((porcentual_desconto * novo_salario) / 100); reais = novo_salario_desconto; centavos = (novo_salario_desconto - reais) * 100; printf("Seu novo salario será de %d reais e %d centavos\n", reais, centavos); system("pause"); return (0); /* Salario ---------> 100% Salario Novo ----> x % Salario Novo = (%aumento * salario / 100) + salario. Novo_salario --------> 100% x (salario desconto) -> % desconto Salario com desconto = Salario Novo com aumento - (%desconto * Novo Salario / 100); */ }
the_stack_data/36075970.c
#include <stdio.h> void print_int(int a) { printf("%d\n", a); } int main() { int a; int b; b = a = 5; print_int(a); print_int(b); }
the_stack_data/70240.c
/* some helpers, so our code also works with LibreSSL */ #include <openssl/opensslv.h> #include <openssl/evp.h> #if defined(LIBRESSL_VERSION_NUMBER) const EVP_CIPHER *EVP_aes_256_ocb(void){ /* dummy, so that code compiles */ return NULL; } const EVP_CIPHER *EVP_chacha20_poly1305(void){ /* dummy, so that code compiles */ return NULL; } #endif
the_stack_data/964758.c
#include <stdio.h> #define Q_SIZE 5 typedef struct{ int data[Q_SIZE + 1]; int head, tail; } Queue; //data type void enqueue(Queue *q, int item) { if ((q->tail + 1)% (Q_SIZE + 1) == q->head){ printf("Queue is full\n"); return; } q->data[q->tail] = item; q->tail = (q->tail + 1) % (Q_SIZE + 1); } int dequeue(Queue *q) { int item; if(q->tail == q->head) { printf("Queue is empty/n"); return -1; } item = q->data[q->head]; q->head = (q->head + 1) % (Q_SIZE + 1); return item; } int main() { Queue my_q; int item; my_q.head = 0; my_q.tail = 0; enqueue(&my_q, 1); printf("tail = %d\n", my_q.tail); enqueue(&my_q, 2); printf("tail = %d\n", my_q.tail); printf("begining head = %d\n", my_q.head); item = dequeue(&my_q); printf("item = %d, head = %d\n",item,my_q.head); item = dequeue(&my_q); printf("item = %d, head = %d\n",item,my_q.head); item = dequeue(&my_q); printf("item = %d, head = %d\n",item,my_q.head); }
the_stack_data/57506.c
/* testinggit.c * * Copyright 2018 KiIIaWatt * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name(s) of the above copyright * holders shall not be used in advertising or otherwise to promote the sale, * use or other dealings in this Software without prior written * authorization. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf ("Hello, World!\n"); return EXIT_SUCCESS; }
the_stack_data/336.c
#include <stddef.h> #include <sys/types.h> #include <sys/socket.h> int main() { (void)getsockopt (1, 1, 1, NULL, (size_t *)NULL); }
the_stack_data/206392540.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <error.h> #include <fcntl.h> #include <sys/types.h> #include <string.h> const char *str1 = "test"; const char *str2 = "test2\n"; int main(int argc, char **argv) { int fd; int nwritten; if (argc != 2) { printf("Usage: %s filename\n", argv[0]); exit(EXIT_SUCCESS); } fd = open(argv[1], O_CREAT | O_RDWR, 0666); if (fd < 0) { perror("open: "); exit(EXIT_FAILURE); } nwritten = write(fd, str1, strlen(str1)); if (nwritten != strlen(str1)) { perror("write (str1) "); exit(EXIT_FAILURE); } nwritten = write(fd, str2, strlen(str2)); if (nwritten != strlen(str2)) { perror("write (str2) "); exit(EXIT_FAILURE); } close(fd); return EXIT_SUCCESS; }
the_stack_data/590917.c
#include <stdio.h> #include <stdlib.h> #include <string.h> // Usage: // // /path/to/program arg1 [arg2 [...]] // // Return EXIT_SUCCESS if 'generated_exe_emulator_expected' // string was found in <arg1>. // Return EXIT_FAILURE if 'generated_exe_emulator_unexpected' // string was found in <arg1>. int main(int argc, const char* argv[]) { const char* substring_failure = "generated_exe_emulator_unexpected"; const char* substring_success = "generated_exe_emulator_expected"; const char* str = argv[1]; if (argc < 2) { return EXIT_FAILURE; } if (strstr(str, substring_success) != 0) { return EXIT_SUCCESS; } if (strstr(str, substring_failure) != 0) { return EXIT_FAILURE; } fprintf(stderr, "Failed to find string '%s' in '%s'\n", substring_success, str); return EXIT_FAILURE; }
the_stack_data/1028313.c
#include <stdio.h> #include <string.h> int main () { char str[1000],str1[1000],str2[1000],str3[1000],str4[1000]; int i,j,k,l,m,n,T,a,s,t,p,q,o,w; scanf("%d",&T); getchar(); while(T--) { gets(str); i = strlen(str); m = i/2; for(j=0;j<m;j++) str1[j] = str[j]; str1[j] = '\0'; for(k = m,n=0;k<i;k++,n++) str2[n] = str[k]; str2[n] = '\0'; s = strlen(str1); t = strlen(str2); o=0; for(p=s-1;p>=0;p--) { str3[o] = str1[p]; o++; } str3[o] = '\0'; w=0; for(q=t-1;q>=0;q--) { str4[w] = str2[q]; w++; } str4[w] = '\0'; strcat(str3,str4); printf("%s\n",str3); } }
the_stack_data/90706.c
/* # # author : Prashant Kuntala # date : 17th Feb, 2017 # # last modified : 6th April, 2017 # */ #include<stdio.h> #include<stdlib.h> #include<string.h> #define NHASH 263167 //Use a prime number! #define MULT 31 #define MAX_WORD_LENGTH 15 #define MAX_NUMBER_OF_SEQUENCES 10 #define MAX_FILENAME_LENGTH 255 #define MAX_FILE_LENGTH 500000 #define ALPHA_NUM 26 #define max(a,b) (((a) > (b)) ? (a) : (b)) struct node { // add length of the word // add probability of the word or have a function that calculates it before printing. char *word; int total_count; int sequence_count; int last_matching_sequence_id; struct node * next; } node; typedef enum { ASCENDING_TOTAL, ASCENDING_SEQUENCE, DESCENDING_TOTAL, DESCENDING_SEQUENCE, ASCENDING_WORDLENGTH, DESCENDING_WORDLENGTH } sort_order_t; typedef struct node Node; unsigned long total_number_words = 0; Node *bin[NHASH]; Node** bin_array; char input_sequences[MAX_NUMBER_OF_SEQUENCES][MAX_FILE_LENGTH]; unsigned long sequence_lengths[MAX_NUMBER_OF_SEQUENCES]; //record the p(a), p(b)... double prob_letter[50]; int MARKOV_ORDER = 1; unsigned int hash(char *p) { unsigned int h = 0; for(; *p; p++) h = MULT * h + *p; return h % NHASH; } // calculates word frequencies. void incword(char *s, int sequence_id) { Node * p; int h = hash(s); for(p = bin[h]; p!= NULL; p = p->next) { if(strcmp(s, p->word) == 0) { p->total_count++; if(sequence_id != p->last_matching_sequence_id) { p->sequence_count++; p->last_matching_sequence_id = sequence_id; } return; } } p = (Node *)malloc(sizeof(node)); if(!p) return; p->total_count = 1; p->sequence_count = 1; p->last_matching_sequence_id = sequence_id; p->word = (char *)malloc(strlen(s)+1); total_number_words++; strcpy(p->word, s); p->next = bin[h]; bin[h] = p; //printf("mycount %s\t%d\n",p->word,p->total_count); } int compare( const void* ptr1, const void* ptr2, const void* ptr3) { Node** np1, *(*np2); sort_order_t sort_order = (sort_order_t)ptr3; np1 = (Node**) ptr1; np2 = (Node**) ptr2; switch(sort_order) { case ASCENDING_TOTAL: if( (*np1)->total_count < (*np2)->total_count ) return -1; if( (*np1)->total_count == (*np2)->total_count ) sort_order = ASCENDING_WORDLENGTH; if( (*np1)->total_count > (*np2)->total_count ) return 1; break; case ASCENDING_SEQUENCE: if( (*np1)->sequence_count < (*np2)->sequence_count ) return -1; if( (*np1)->sequence_count == (*np2)->sequence_count ) return 0; if( (*np1)->sequence_count > (*np2)->sequence_count ) return 1; break; case DESCENDING_TOTAL: if( (*np1)->total_count > (*np2)->total_count ) return -1; if( (*np1)->total_count == (*np2)->total_count ) return 0; if( (*np1)->total_count < (*np2)->total_count ) return 1; break; case DESCENDING_SEQUENCE: if( (*np1)->sequence_count > (*np2)->sequence_count ) return -1; if( (*np1)->sequence_count == (*np2)->sequence_count ) return 0; if( (*np1)->sequence_count < (*np2)->sequence_count ) return 1; break; case ASCENDING_WORDLENGTH: if( strlen( (*np1)->word ) < strlen( (*np2)->word )) return -1; if( strlen( (*np1)->word ) == strlen( (*np2)->word )) return 0; if( strlen( (*np1)->word ) > strlen( (*np2)->word )) return 1; break; case DESCENDING_WORDLENGTH: if( strlen( (*np1)->word ) > strlen( (*np2)->word )) return -1; if( strlen( (*np1)->word ) == strlen( (*np2)->word )) return 0; if( strlen( (*np1)->word ) < strlen( (*np2)->word )) return 1; break; default: return 0; break; } } void sort_hash(sort_order_t order) { Node* p; int i; unsigned long nwords = 0; bin_array = (Node**)malloc(total_number_words * (sizeof(Node*))); for(i = 0; i < NHASH; i++) { for(p = bin[i]; p!= NULL; p = p->next) { bin_array[nwords++] = p; } } qsort_r(&bin_array[0], total_number_words, sizeof(Node*), compare, (void*)order); } void print_cmdline_error() { fprintf(stderr, "Error: improper command line arguments\n"); fprintf(stderr, "Usage: word_count -min X -max Y [-descseq|-ascseq|-desctot|-asctot|-desclength|-asclength] filename [other filenames]\n"); fprintf(stderr, "-min minimum word length\n"); fprintf(stderr, "-max maximum word length\n"); fprintf(stderr, "-descseq causes the output to be sorted in descending order of sequence counts\n"); fprintf(stderr, "-ascseq causes the output to be sorted in ascending order of sequence counts\n"); fprintf(stderr, "-desctot causes the output to be sorted in descending order of total counts\n"); fprintf(stderr, "-asctot causes the output to be sorted in ascending order of total counts\n"); fprintf(stderr, "-desclength causes the output to be sorted in descending order of word length\n"); fprintf(stderr, "-order pick the markov order 1, 2 or 3\n"); fprintf(stderr, "Example: word_count -min 3 -max 10 -asctot -order 2 filename1 filename2 filname3\n"); exit(1); } // Function that read the filecontents into the buffer passed and returns the length of the file. unsigned long open_copy(char* filename, char* cbuf) { FILE *fp; fp = fopen(filename, "r"); unsigned long sequence_length = 0; if( fp == NULL) { fprintf(stderr, "Error: unable to open file %s\n", filename); exit(1); } while( fgets(cbuf, MAX_FILE_LENGTH, fp) == NULL ); return strlen(cbuf); } //########################################################## functions // calculates the frequency of the letter in the sequence int calcfr(char* seq,char str, int len){ char dest[12]; memset(dest,'\0',sizeof(dest)); char src[2]; src[0] = str; src[1] = '\0'; int count = 0; int i =0; for(i=0;i<strlen(seq);i++){ strncpy(dest, seq+i,len); if(strcmp(src,dest) == 0) { count = count+1; } } //printf("word count: %d\t word: %s\n",count,src); return count; } // calculates the frequency of the word in the sequence(book in this case) int calcWordFrequency(char* seq,char* str, int len){ char dest[12]; memset(dest,'\0',sizeof(dest)); int count = 0; int i =0; for( i=0;i<strlen(seq);i++){ strncpy(dest, seq+i,len); if(strcmp(str,dest) == 0) { count = count+1; } } //printf("word count: %d\t word: %s\n",count,src); return count; } //calculates letter Probabilities void calcLetterProb(int number_of_sequences,unsigned long *sequence_lengths) { char ch[10]; double val; char letter; int counts[40]; // to store frequency. memset(&counts[0], 0, sizeof(counts)); int denom =-1; int i = 0 ; //calculates the letter frequencies in all the books for (letter= 65 ; letter <= 90; ++letter) { counts[letter-65] = 0; for(i =0;i<number_of_sequences;i++){ counts[letter-65] = counts[letter-65]+ calcfr(&input_sequences[i][0],letter,1); denom += sequence_lengths[i]; } val = counts[letter-65]; prob_letter[letter-65] = val/denom; denom = -1; } } // function to calculate the word probabilities. double calcWordProb(char* word) { double val =1.0; char ch; int i =0; //printf("word : %s\n",word); for(i = 0; word[i] != '\0'; i++) { ch = word[i]; val = val * prob_letter[ch-65]; } return val; } double phicount(char* word,int model,int number_of_sequences){ int i,j =0; int cn,cd = 0; // numerator count and denominator count char ch[model] ; // to retrieve the probability of the first letter. char num[model+2]; // stores the substrings for the numerator. char den[model]; // stores the substrings for the denominator. Node * p; int n=0; if(model == 1){ ch[0] = word[0]; ch[1] = '\0'; } else{ strncpy(ch,word,model); // copying the first "m" characters, m represents the MARCOV_ORDER } double wprob = calcWordProb(ch); // to store the final probability value. memset(num,'\0',sizeof(num)); memset(den,'\0',sizeof(den)); // generate all substrings based on the model passed. for(i=0;i<strlen(word);i=i+1){ strncpy(num, word+i,model+1); strncpy(den, word+i,model); if(strlen(num)>model){ cn = 0; cd = 0; n = hash(num); for(p = bin[n]; p!= NULL; p = p->next) { if(strcmp(num, p->word) == 0) { cn = p->total_count; } } n = hash(den); for(p = bin[n]; p!= NULL; p = p->next) { if(strcmp(den, p->word) == 0) { cd = p->total_count; } } wprob = wprob * (double)((double)cn/(double)cd); // printf("numerator : %s\t cn : %d\t denominator: %s\t cd: %d\t final wprob : %.15lf\n\n\n",num,cn,den,cd,wprob); } } // printf("final wprob : %.15lf\n",wprob); return wprob; } int main(int argc, char *argv[]) { int number_of_sequences = 0; int min_wordlength = 0; int max_wordlength = 0; sort_order_t sort_order = DESCENDING_TOTAL; int i,k; int j; double wordprob = 1; // to store the value of word probability returned by calcWordProb double oescore ; // to store the O/E score for each word. double expectedvalue =0; // to store the denominatore (n-k+1)*P(w) double totalSeqLength = 0; // to store the total sequence length ( since we have more than one sequence) if (argc == 1) { print_cmdline_error(); } for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-min") == 0) { // input file ++i; min_wordlength = atoi(argv[i]); } else if (strcmp(argv[i], "-asctot") == 0) { sort_order = ASCENDING_TOTAL; } else if (strcmp(argv[i], "-ascseq") == 0) { sort_order = ASCENDING_SEQUENCE; } else if (strcmp(argv[i], "-desctot") == 0) { sort_order = DESCENDING_TOTAL; } else if (strcmp(argv[i], "-descseq") == 0) { sort_order = DESCENDING_SEQUENCE; } else if (strcmp(argv[i], "-asclength") == 0) { sort_order = ASCENDING_WORDLENGTH; } else if (strcmp(argv[i], "-desclength") == 0) { sort_order = DESCENDING_WORDLENGTH; } else if (strcmp(argv[i], "-max") == 0) { ++i; max_wordlength = atoi(argv[i]); } else if (strcmp(argv[i], "-order") == 0) { ++i; MARKOV_ORDER = atoi(argv[i]); } else { sequence_lengths[number_of_sequences] = open_copy(argv[i], &input_sequences[number_of_sequences][0]); ++number_of_sequences; } } if (MARKOV_ORDER != 1 && MARKOV_ORDER != 2 && MARKOV_ORDER != 3 && MARKOV_ORDER != 4) { printf("%d\n", MARKOV_ORDER); fprintf(stderr, "Error: -order can take only 1, 2, 3 or 4\n"); exit(1); } if( min_wordlength == 0 || max_wordlength == 0 || min_wordlength > max_wordlength ) { fprintf(stderr, "Error: incorrect or missing minimum or maximum word length\n"); exit(1); } if( number_of_sequences == 0) { fprintf(stderr, "Error: no input file names specified\n"); exit(1); } fprintf(stderr,"min wordlength = %d\n", min_wordlength); fprintf(stderr,"max wordlength = %d\n", max_wordlength); fprintf(stderr,"number of input files = %d\n", number_of_sequences); fprintf(stderr,"Markov order chosen = %d\n", MARKOV_ORDER); char buf[MAX_WORD_LENGTH+1]; int wl; // Enumeration for( i=0; i < number_of_sequences; i++) { for( wl = 1; wl < max_wordlength+1; wl++) { // read words of length wl from the sequence. for( j=0; j < max( 0, (signed int)(sequence_lengths[i]-wl+1)); j++) { strncpy(buf, &input_sequences[i][j], wl); buf[wl] = '\0'; incword(buf, i); // calculates each word frequency and also populates the hash. } } } // Sort the output sort_hash(sort_order); calcLetterProb(number_of_sequences,sequence_lengths); for(j =0;j<number_of_sequences;j++){ totalSeqLength = totalSeqLength + sequence_lengths[j] ; } printf("total number of words =\t %ld\n", total_number_words); printf("Word\tWordCount\t SeqCount\t Word Probbility\tExpected value\tO/E score \n"); for(i = 0; i < total_number_words; i++) { if( bin_array[i] == NULL ) { exit(1); } if(strlen(bin_array[i]->word) >= min_wordlength){ wordprob = phicount(bin_array[i]->word,MARKOV_ORDER,number_of_sequences); expectedvalue = (wordprob * (totalSeqLength-strlen(bin_array[i]->word)+1)); oescore = (double)bin_array[i]->total_count/(double)expectedvalue; printf("%-*s \t%d \t%d\t %.15lf\t %.15lf\t %.15lf\n", max_wordlength, bin_array[i]->word, bin_array[i]->total_count, bin_array[i]->sequence_count,wordprob,expectedvalue,oescore); } } }
the_stack_data/18802.c
/* $NetBSD: err_syntax1.tab.c,v 1.1.1.1 2015/01/03 22:58:25 christos Exp $ */ /* original parser id follows */ /* yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93" */ /* (use YYMAJOR/YYMINOR for ifdefs dependent of parser version) */ #define YYBYACC 1 #define YYMAJOR 1 #define YYMINOR 9 #define YYCHECK "yyyymmdd" #define YYEMPTY (-1) #define yyclearin (yychar = YYEMPTY) #define yyerrok (yyerrflag = 0) #define YYRECOVERING() (yyerrflag != 0) #define YYENOMEM (-2) #define YYEOF 0
the_stack_data/942396.c
/* Resembles include/linux/compiler_types.h */ #define __kernel __attribute__((address_space(0))) #define __user __attribute__((address_space(1))) #define __iomem __attribute__((address_space(2))) #define __percpu __attribute__((address_space(3))) #define __rcu __attribute__((address_space(4))) typedef unsigned long ulong; typedef struct s obj_t; static void expl(obj_t __kernel *k, obj_t __iomem *o, obj_t __user *p, obj_t __percpu *pc, obj_t __rcu *r) { (ulong)(k); (__UINTPTR_TYPE__)(k); (void *)(k); (obj_t*)(k); (obj_t __kernel*)(k); (ulong)(o); (__UINTPTR_TYPE__)(o); (void *)(o); (obj_t*)(o); (obj_t __iomem*)(o); (ulong)(p); (__UINTPTR_TYPE__)(p); (void *)(p); (obj_t*)(p); (obj_t __user*)(p); (ulong)(pc); (__UINTPTR_TYPE__)(pc); (void *)(pc); (obj_t*)(pc); (obj_t __percpu*)(pc); (ulong)(r); (__UINTPTR_TYPE__)(r); (void *)(r); (obj_t*)(r); (obj_t __rcu*)(r); } /* * check-name: Waddress-space-all-attr * check-command: sparse -Wcast-from-as -Wcast-to-as $file * * check-error-start Waddress-space-all-attr.c:21:10: warning: cast removes address space '<asn:2>' of expression Waddress-space-all-attr.c:21:22: warning: cast removes address space '<asn:2>' of expression Waddress-space-all-attr.c:22:10: warning: cast removes address space '<asn:2>' of expression Waddress-space-all-attr.c:23:10: warning: cast removes address space '<asn:2>' of expression Waddress-space-all-attr.c:26:10: warning: cast removes address space '<asn:1>' of expression Waddress-space-all-attr.c:26:22: warning: cast removes address space '<asn:1>' of expression Waddress-space-all-attr.c:27:10: warning: cast removes address space '<asn:1>' of expression Waddress-space-all-attr.c:28:10: warning: cast removes address space '<asn:1>' of expression Waddress-space-all-attr.c:31:10: warning: cast removes address space '<asn:3>' of expression Waddress-space-all-attr.c:31:23: warning: cast removes address space '<asn:3>' of expression Waddress-space-all-attr.c:32:10: warning: cast removes address space '<asn:3>' of expression Waddress-space-all-attr.c:33:10: warning: cast removes address space '<asn:3>' of expression Waddress-space-all-attr.c:36:10: warning: cast removes address space '<asn:4>' of expression Waddress-space-all-attr.c:36:22: warning: cast removes address space '<asn:4>' of expression Waddress-space-all-attr.c:37:10: warning: cast removes address space '<asn:4>' of expression Waddress-space-all-attr.c:38:10: warning: cast removes address space '<asn:4>' of expression * check-error-end */
the_stack_data/93888304.c
#include <stdio.h> int get_retval(void); int main(int argc, char **argv) { printf("C seems to be working.\n"); return get_retval(); }
the_stack_data/129831.c
/* 132. Pattern @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ */ #include<stdio.h> int main() { int n,x,y; scanf("%d",&n); if(n%2==0) n=n+1; for(y=3*n/2; y>=-3*(n/2); y--) { for(x=-3*(n/2); x<=3*(n/2); x++) { if((x>=-1*n/2 && x<=n/2) || (y>=-1*n/2 && y<=n/2)) { if(x==y || x==-y) printf("@ "); else if((y<=0 || y>=n/2) && (x+y==n-1)) printf("@ "); else if((y>=0 || y<=-n/2) && (x+y==1-n)) printf("@ "); else if((x<=0 || x>=n/2) && (x-y==n-1)) printf("@ "); else if((x>=0 || x<=-n/2) && (x-y==1-n)) printf("@ "); else printf(" "); } else { if(x+y==(n-1)*2) printf("@ "); else if(x+y==(1-n)*2) printf("@ "); else if(x-y==(n-1)*2) printf("@ "); else if(x-y==(1-n)*2) printf("@ "); else printf(" "); } } printf("\n"); } }
the_stack_data/208054.c
#include <stdio.h> #include <stdlib.h> int main( int argc, char * argv[] ) { char * name; char input[25]; printf("Enter your name: " ); name = gets(input); printf("\n\n Hello, %s \n\n", name); exit(0); }
the_stack_data/22012482.c
/* Write a program to evaluate the addition of diagonal elements of two square matrixes. Assumptions : Matrix are square and equal size Code by Abhishek */ #include <stdio.h> int main() { int matrix1[4][4]= { {2,-3,44,5}, {1,23,8,1}, {-3,2,78,12}, {5,0,-23,24} }; int matrix2[4][4]= { {1,3,44,17}, {6,3,8,41}, {-39,20,-25,2}, {28,0,-43,24} }; int n = sizeof(matrix2[0])/4; int Dsum[n]; for(int a=0;a<n;a++) Dsum[a]=matrix1[a][a]+matrix2[a][a]; for(int a=0;a<n;a++) printf("%i\n",Dsum[a]); return 1; }
the_stack_data/781485.c
extern int sprintf(char*, const char*, ...); extern void console_log(char*); extern void quit(); extern void read_in(void* dest, void* extern_src, unsigned int size); extern void write_out(void* extern_dest, void* src, unsigned int size); #define EXPORT __attribute__((used)) #define SIZE(ty, siz) \ typedef ty i##siz; \ typedef unsigned ty u##siz; SIZE(char, 8); SIZE(short, 16); SIZE(int, 32); SIZE(long long, 64); #undef SIZE typedef u32 size_t; typedef u64 rights_t; typedef u8 filetype_t; typedef u16 fdflags_t; typedef u32 fd_t; typedef struct fdstat_t {} fdstat; typedef struct ciovec_t { void* buf; size_t len; } ciovec; const fd_t STDIN_FILENO = 0; const fd_t STDOUT_FILENO = 1; const fd_t STDERR_FILENO = 2; typedef i32 wasi_errno; EXPORT wasi_errno fd_fdstat_get(i32 fd, i32 fdstat_ptr) { console_log("Calling stub: fd_fdstat_get"); // const fdstat = load_wasi_fdstat_t(fdstat_ptr); // console_log("fdstat: ", fdstat); return 0; } EXPORT wasi_errno fd_close(i32 fd) { console_log("Calling stub: fd_close"); return 0; } EXPORT wasi_errno fd_seek(i32 a, i64 b, i32 c, i32 d) { console_log("Calling stub: fd_seek"); return 0; } EXPORT wasi_errno fd_write(fd_t fd, ciovec* io, size_t iovs_len, size_t* nwritten) { console_log("Calling stub: fd_write"); char str[1024]; size_t written = 0; char buffer[1024]; char* bufPtr = buffer; for (int i = 0; i < iovs_len; ++i) { ciovec my_io; read_in(&my_io, &io[i], sizeof(ciovec)); sprintf(str, "fd: %d, io: {%p , %d}, len: %d", fd, my_io.buf, my_io.len, iovs_len); console_log(str); read_in(bufPtr, my_io.buf, my_io.len); bufPtr += my_io.len; written += my_io.len; } *bufPtr = 0; console_log(buffer); write_out(nwritten, &written, sizeof(written)); return 0; }
the_stack_data/181391904.c
#include "string.h" int strncmp(const char *s, const char *t, size_t n) { for (size_t i = 0; i < n; ++i) { const char schar = s[i]; const char tchar = t[i]; if (schar == 0 && tchar == 0) { return 0; } if (schar == 0 && tchar != 0) { return 1; } if (schar != 0 && tchar == 0) { return -1; } if (schar < tchar) { return -1; } if (schar > tchar) { return 1; } } return 0; }
the_stack_data/141273.c
int findNumberOfLIS(int *nums, int numsSize) { if (numsSize == 0) return 0; int dp[numsSize][2]; //{LIS,count} for (int i = 0; i < numsSize; ++i) { dp[i][0] = dp[i][1] = 1; for (int j = 0; j < i; ++j) { if (nums[i] > nums[j]) { if (dp[i][0] < dp[j][0] + 1) { dp[i][0] = dp[j][0] + 1; dp[i][1] = dp[j][1]; } else if (dp[i][0] == dp[j][0] + 1) dp[i][1] += dp[j][1]; } } } int res = 0, maxlen = 0; for (int i = 0; i < numsSize; ++i) { if (dp[i][0] > maxlen) { maxlen = dp[i][0]; res = dp[i][1]; } else if (dp[i][0] == maxlen) res += dp[i][1]; } return res; }
the_stack_data/92328688.c
//https://www.tutorialspoint.com/inter_process_communication/inter_process_communication_shared_memory.htm #include<stdio.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> #include<sys/types.h> #include<string.h> #include<errno.h> #include<stdlib.h> #define BUF_SIZE 1024 #define SHM_KEY 0x1234 struct shmseg { int cnt; int complete; char buf[BUF_SIZE]; }; int main(int argc, char *argv[]) { int shmid; struct shmseg *shmp; shmid = shmget(SHM_KEY, sizeof(struct shmseg), 0644|IPC_CREAT); if (shmid == -1) { perror("Shared memory"); return 1; } // Attach to the segment to get a pointer to it. shmp = shmat(shmid, NULL, 0); if (shmp == (void *) -1) { perror("Shared memory attach"); return 1; } /* Transfer blocks of data from shared memory to stdout*/ while (shmp->complete != 1) { printf("segment contains : \n\"%s\"\n", shmp->buf); if (shmp->cnt == -1) { perror("read"); return 1; } printf("Reading Process: Shared Memory: Read %d bytes\n", shmp->cnt); sleep(3); } printf("Reading Process: Reading Done, Detaching Shared Memory\n"); if (shmdt(shmp) == -1) { perror("shmdt"); return 1; } printf("Reading Process: Complete\n"); return 0; }
the_stack_data/262745.c
/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string.h> /* for NULL, size_t, strncat() */ /** * @date 2014-11-23 * @author Vlad Gluhovsky * @see http://libc11.org/string/strncat.html */ char* strncat(char* restrict s1, const char* restrict s2, size_t n) { size_t i = 0, j = 0; while (s1[i++]) ; while (j < n && s2[j]) s1[i++] = s2[j++]; s1[i] = 0; return s1; }
the_stack_data/182952567.c
#include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<pthread.h> #include<sys/ipc.h> #include<semaphore.h> #include<string.h> #define Quantidade_passageiro 6 #define Quantidade_veiculos 3 sem_t sem_passageiros; //representa os passageiros sem_t sem_passageiro[Quantidade_passageiro]; //representa a fila de passageiros sem_t sem_uber[Quantidade_veiculos]; // representa os uber sem_t sem_uber_check[Quantidade_veiculos]; // represta se uber atendou cliente até o destino ou nao sem_t sem_passageiros_Fila[Quantidade_veiculos]; //representa o num de passageiros na fila sem_t sem_escreve, sem_ler; int visor, amb=0, viat=0; void* Uber(void * v){ int id = *(int*)v; while(1) { sem_wait(&sem_escreve); // esperando por passageiro visor = id; //mostra que está livre sem_post(&sem_ler); //avisa que esta livre sem_wait(&sem_passageiros_Fila[id]); //levando passageiro até o destino sleep(random()%3); sem_post(&sem_uber_check[id]); //avisa que deixou passageiro destino final sleep(random()%3); } } void * Passageiro(void* v) { //veiculos while(1){ int id = *(int*) v; int minha_Fila; char tp[15]; int i,acum=0; //sleep(random()%3); usleep(random()%700+4); if (id == 0){ strcpy(tp,"Passageiro Barra"); } else if (id == 1){ strcpy(tp,"Passageiro Imbui"); } else if (id == 2){ strcpy(tp,"passageiro Boca Do Rio"); } else if (id == 3){ strcpy(tp,"Passageiro Campo Grande"); } else if (id == 4){ strcpy(tp,"Passageiro Nazaré"); } else if (id == 5){ strcpy(tp,"Passageiro Paralela"); } //printf("%s chegou na fila\n",tp); for(i=0;i<Quantidade_passageiro;i++){ //if (sem_trywait(&sem_passageiro[i]) != 0) { if(id<=1){ // se passageiro for da barra ou imbui seleciona, #### PRECISA MODIFICAR ESSA CONDIÇÃO #### sem_wait(&sem_passageiro[i]); //printf("%s chegou na fila\n",tp); sem_wait(&sem_ler); //espera indicar que existe ubers livres na região minha_Fila = visor; //mostra quais ubers estão livres na região sem_post(&sem_escreve); //solicita o uber sem_wait(&sem_uber[minha_Fila]); //espera um uber ser selecionado printf("%s está no uber %d \n",tp,minha_Fila ); sem_post(&sem_passageiros_Fila[minha_Fila]); //avisa que passageiro esta na fila de pedidos sem_post(&sem_passageiro[i]); //uber chega e passageiro deixa a fila de pedidos //usleep(1000*id); sem_wait(&sem_uber_check[minha_Fila]); //espera uber levar até destino final sem_post(&sem_uber[minha_Fila]); //chega ao destino final printf("%s chegou ao Destino Final.\n",tp ); }else{ sem_wait(&sem_passageiro[i]); //printf("%s chegou na fila\n",tp); sem_wait(&sem_ler); //espera indicar que existe ubers livres na região minha_Fila = visor; //mostra quais ubers estão livres na região sem_post(&sem_escreve); //solicita o uber sem_wait(&sem_uber[minha_Fila]); //espera um uber ser selecionado printf("%s está no uber %d \n",tp,minha_Fila ); sem_post(&sem_passageiros_Fila[minha_Fila]); //avisa que passageiro esta na fila de pedidos sem_post(&sem_passageiro[i]); //uber chega e passageiro deixa a fila de pedidos //usleep(1000*id); sem_wait(&sem_uber_check[minha_Fila]); //espera uber levar até destino final sem_post(&sem_uber[minha_Fila]); //chega ao destino final printf("%s chegou ao Destino Final.\n",tp ); } //} } } } int main() { pthread_t thr_passageiro[Quantidade_passageiro], thr_uber[Quantidade_veiculos]; int i, id_passageiro[Quantidade_passageiro], id_uber[Quantidade_veiculos]; for(i=0; i<Quantidade_passageiro;i++){ sem_init(&sem_passageiro[i],0,1); //fila } sem_init(&sem_escreve,0,1); sem_init(&sem_ler,0,0); for (i = 0;i < Quantidade_veiculos;i++){ //inicia semaforo sem_init(&sem_uber[i],0,1); sem_init(&sem_passageiros_Fila[i],0,0); sem_init(&sem_uber_check[i],0,0); } for (i=0;i< Quantidade_passageiro;i++) { //cria passageiros id_passageiro[i] = i; pthread_create(&thr_passageiro[i], NULL, Passageiro, (void*) &id_passageiro[i]); } for (i=0;i< Quantidade_veiculos;i++) { //cria veiculos do uber id_uber[i] = i; pthread_create(&thr_uber[i], NULL, Uber, (void*) &id_uber[i]); } for (i=0; i <Quantidade_passageiro; i++) pthread_join(thr_passageiro[i],NULL); }
the_stack_data/151706094.c
#include <stdio.h> #include <stdlib.h> #define MAX 6 #define SENTINEL 0 int enter_numbers(int tab[], int capacity); void print_table(int tab[], int n); void insert_number_in_table(int a_number, int tab[], int place, int capacity); int main(void) { int n; int *tab = (int*)malloc(MAX * sizeof(int)); if (tab == NULL){ printf("Out of memory..."); exit(EXIT_FAILURE); } n = enter_numbers(tab, MAX); print_table(tab, n); free(tab); return 0; } int enter_numbers(int tab[], int capacity){ int a_number, done = 0, count = 0; while(!done && count < capacity){ /* Prompt for input number */ printf("Enter a number: "); scanf(" %d", &a_number); done = a_number == SENTINEL; if(!done){ insert_number_in_table(a_number, tab, count, capacity); ++count; } } return count; } void insert_number_in_table(int a_number, int tab[], int place, int capacity){ int i = 0, j = 0; /* Progress i as long as small numbers */ while(tab[i] < a_number) ++i; /*for(j = place-1; j > i; --j){ tab[j+1] = tab[j]; }*/ tab[i+1] = tab[i]; tab[i] = a_number; } void print_table(int tab[], int number_of_elements_in_table){ int i; for(i = 0; i < number_of_elements_in_table; ++i){ printf("%3d", tab[i]); } }
the_stack_data/181393457.c
#include <stdio.h> typedef struct expr_tag { char v; struct expr_tag *lhs, *rhs; } expr; static expr store[300]; expr *freelist; expr *var(char c) { expr *e = freelist++; e->v = c; e->lhs = e->rhs = NULL; return e; } expr *binop(char op, expr *l, expr *r) { expr *e = freelist++; e->v = op; e->lhs = l; e->rhs = r; return e; } void ppr(expr *e, int level) { if (!e->lhs) { putchar(e->v); } else { int llv, rlv; switch (e->v) { case '*': llv = rlv = 4; break; case '/': llv = 4; rlv = 5; break; case '+': llv = rlv = 1; break; case '-': llv = 1; rlv = 2; break; } if (level > llv) { putchar('('); } ppr(e->lhs, llv); putchar(e->v); ppr(e->rhs, rlv); if (level > llv) { putchar(')'); } } } expr *parse_expr(); expr *parse_factor() { const char c = getchar(); if (c == '(') { expr *e = parse_expr(); (void)getchar(); return e; } else { expr *e = var(c); return e; } } expr *parse_term() { expr *l = parse_factor(); char c = getchar(); while (c != '\n' && (c == '*' || c == '/')) { expr *r = parse_factor(); l = binop(c, l, r); c = getchar(); } ungetc(c, stdin); return l; } expr *parse_expr() { expr *l = parse_term(); char c = getchar(); while (c != '\n' && (c == '+' || c == '-')) { expr *r = parse_term(); l = binop(c, l, r); c = getchar(); } ungetc(c, stdin); return l; } int main() { int N; scanf("%d", &N); (void)getchar(); while (N-- > 0) { freelist = store; expr *e = parse_expr(); ppr(e, 0); (void)getchar(); putchar('\n'); } return 0; }
the_stack_data/161079995.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #define PORT 8080 #define MAXLINE 1024 // Driver code int main() { int sockfd; char buffer[MAXLINE]; int a,b, result; scanf("%d %d", &a, &b); struct sockaddr_in servaddr; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; sendto(sockfd, &a, sizeof(a), 0, (const struct sockaddr *) &servaddr, sizeof(servaddr)); sendto(sockfd, &b, sizeof(b), 0, (const struct sockaddr *) &servaddr, sizeof(servaddr)); printf("Numbers sent.\n"); n = recvfrom(sockfd, &result, sizeof(int), 0, (struct sockaddr *) &servaddr, &len); printf("Server : %d\n", result); close(sockfd); return 0; }
the_stack_data/225142816.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-2021 POK team */ /* @(#)e_scalb.c 5.1 93/09/24 */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* * __ieee754_scalb(x, fn) is provide for * passing various standard test suite. One * should use scalbn() instead. */ #ifdef POK_NEEDS_LIBMATH #include "math_private.h" #include <libm.h> #ifdef _SCALB_INT double __ieee754_scalb(double x, int fn) #else double __ieee754_scalb(double x, double fn) #endif { #ifdef _SCALB_INT return scalbn(x, fn); #else if (isnan(x) || isnan(fn)) return x * fn; if (!finite(fn)) { if (fn > 0.0) return x * fn; else return x / (-fn); } if (rint(fn) != fn) return (fn - fn) / (fn - fn); if (fn > 65000.0) return scalbn(x, 65000); if (-fn > 65000.0) return scalbn(x, -65000); return scalbn(x, (int)fn); #endif } #endif
the_stack_data/198580494.c
#include <stdio.h> #include <stdlib.h> int hookme(void) { return 1; } int main(void) { fprintf(stderr, "a start\n"); // fgetc(stdin); system("./b"); fprintf(stderr, "a hookme(): %d\n", hookme()); fprintf(stderr, "a finish\n"); return 0; }
the_stack_data/113368.c
#include <stdio.h> int main(void) { printf("eof: 0x%x, dec %d\n", EOF, EOF); return 0; }
the_stack_data/55855.c
// // Sample Code: // #include <stdio.h> #include <stdlib.h> #include <string.h> void pre_Initializing_Input_Tensors(); void post_Correctness(); int main(int argc, char** argv) { // for sd2 double *host_t3, *host_t3_chk; double *host_t2_1, *host_t2_2, *host_t2_3, *host_t2_4, *host_t2_5, *host_t2_6, *host_t2_7, *host_t2_8, *host_t2_9; double *host_v2_1, *host_v2_2, *host_v2_3, *host_v2_4, *host_v2_5, *host_v2_6, *host_v2_7, *host_v2_8, *host_v2_9; int size_h3, size_h2, size_h1, size_p6, size_p5, size_p4, size_h7; int opt_register_transpose; // Problem Size size_h3 = 16; size_h2 = 16; size_h1 = 16; size_p6 = 16; size_p5 = 16; size_p4 = 16; size_h7 = 16; opt_register_transpose = 1; // if (argc == 9) { size_h3 = atoi(argv[1]); size_h2 = atoi(argv[2]); size_h1 = atoi(argv[3]); size_p6 = atoi(argv[4]); size_p5 = atoi(argv[5]); size_p4 = atoi(argv[6]); size_h7 = atoi(argv[7]); opt_register_transpose = atoi(argv[8]); } printf (">>> Problem Size (h3,h2,h1,p6,p5,p4) and (h7): (%2d,%2d,%2d,%2d,%2d,%2d) and (%2d)\n", size_h3, size_h2, size_h1, size_p6, size_p5, size_p4, size_h7); printf (">>> Option for Register Transpose: %2d\n", opt_register_transpose); int size_T3; int size_T2_1, size_T2_2, size_T2_3, size_T2_4, size_T2_5, size_T2_6, size_T2_7, size_T2_8, size_T2_9; int size_V2_1, size_V2_2, size_V2_3, size_V2_4, size_V2_5, size_V2_6, size_V2_7, size_V2_8, size_V2_9; int size_internal; // size_internal = size_h7; size_T3 = size_h3 * size_h2 * size_h1 * size_p6 * size_p5 * size_p4; /* >> sd1 << 1: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_1 [h7,p4,p5,h1] * v2_1 [h3,h2,p6,h7]; 2: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_2 [h7,p4,p5,h2] * v2_2 [h3,h1,p6,h7]; 3: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_3 [h7,p4,p5,h3] * v2_3 [h2,h1,p6,h7]; 4: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_4 [h7,p5,p6,h1] * v2_4 [h3,h2,p4,h7]; 5: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_5 [h7,p5,p6,h2] * v2_5 [h3,h1,p4,h7]; 6: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_6 [h7,p5,p6,h3] * v2_6 [h2,h1,p4,h7]; 7: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_7 [h7,p4,p6,h1] * v2_7 [h3,h2,p5,h7]; 8: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_8 [h7,p4,p6,h2] * v2_8 [h3,h1,p5,h7]; 9: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_8 [h7,p4,p6,h3] * v2_9 [h2,h1,p5,h7]; */ // size_T2_1 = size_h7 * size_p4 * size_p5 * size_h1; size_V2_1 = size_h3 * size_h2 * size_p6 * size_h7; size_T2_2 = size_h7 * size_p4 * size_p5 * size_h2; size_V2_2 = size_h3 * size_h1 * size_p6 * size_h7; size_T2_3 = size_h7 * size_p4 * size_p5 * size_h3; size_V2_3 = size_h2 * size_h1 * size_p6 * size_h7; size_T2_4 = size_h7 * size_p5 * size_p6 * size_h1; size_V2_4 = size_h3 * size_h2 * size_p4 * size_h7; size_T2_5 = size_h7 * size_p5 * size_p6 * size_h2; size_V2_5 = size_h3 * size_h1 * size_p4 * size_h7; size_T2_6 = size_h7 * size_p5 * size_p6 * size_h3; size_V2_6 = size_h2 * size_h1 * size_p4 * size_h7; size_T2_7 = size_h7 * size_p4 * size_p6 * size_h1; size_V2_7 = size_h3 * size_h2 * size_p5 * size_h7; size_T2_8 = size_h7 * size_p4 * size_p6 * size_h2; size_V2_8 = size_h3 * size_h1 * size_p5 * size_h7; size_T2_9 = size_h7 * size_p4 * size_p6 * size_h3; size_V2_9 = size_h2 * size_h1 * size_p5 * size_h7; host_t3 = (double*)malloc(sizeof(double) * size_T3); host_t3_chk = (double*)malloc(sizeof(double) * size_T3); host_t2_1 = (double*)malloc(sizeof(double) * size_T2_1); host_t2_2 = (double*)malloc(sizeof(double) * size_T2_2); host_t2_3 = (double*)malloc(sizeof(double) * size_T2_3); host_t2_4 = (double*)malloc(sizeof(double) * size_T2_4); host_t2_5 = (double*)malloc(sizeof(double) * size_T2_5); host_t2_6 = (double*)malloc(sizeof(double) * size_T2_6); host_t2_7 = (double*)malloc(sizeof(double) * size_T2_7); host_t2_8 = (double*)malloc(sizeof(double) * size_T2_8); host_t2_9 = (double*)malloc(sizeof(double) * size_T2_9); host_v2_1 = (double*)malloc(sizeof(double) * size_V2_1); host_v2_2 = (double*)malloc(sizeof(double) * size_V2_2); host_v2_3 = (double*)malloc(sizeof(double) * size_V2_3); host_v2_4 = (double*)malloc(sizeof(double) * size_V2_4); host_v2_5 = (double*)malloc(sizeof(double) * size_V2_5); host_v2_6 = (double*)malloc(sizeof(double) * size_V2_6); host_v2_7 = (double*)malloc(sizeof(double) * size_V2_7); host_v2_8 = (double*)malloc(sizeof(double) * size_V2_8); host_v2_9 = (double*)malloc(sizeof(double) * size_V2_9); printf ("==========================================================================================================\n"); printf (" >>> %s <<<\n", __func__); printf (" T3: %'12d\n", size_T3); printf (" T2_1: %'12d, V2_1: %'12d\n", size_T2_1, size_V2_1); printf (" T2_2: %'12d, V2_2: %'12d\n", size_T2_2, size_V2_2); printf (" T2_3: %'12d, V2_3: %'12d\n", size_T2_3, size_V2_3); printf (" T2_4: %'12d, V2_4: %'12d\n", size_T2_4, size_V2_4); printf (" T2_5: %'12d, V2_5: %'12d\n", size_T2_5, size_V2_5); printf (" T2_6: %'12d, V2_6: %'12d\n", size_T2_6, size_V2_6); printf (" T2_7: %'12d, V2_7: %'12d\n", size_T2_7, size_V2_7); printf (" T2_8: %'12d, V2_8: %'12d\n", size_T2_8, size_V2_8); printf (" T2_9: %'12d, V2_9: %'12d\n", size_T2_9, size_V2_9); printf ("==========================================================================================================\n"); // // Initialze "1" Output and "2 x 9" Inputs pre_Initializing_Input_Tensors(host_t3, host_t3_chk, host_t2_1, host_v2_1, host_t2_2, host_v2_2, host_t2_3, host_v2_3, host_t2_4, host_v2_4, host_t2_5, host_v2_5, host_t2_6, host_v2_6, host_t2_7, host_v2_7, host_t2_8, host_v2_8, host_t2_9, host_v2_9, size_h3, size_h2, size_h1, size_p6, size_p5, size_p4, size_h7); // Run the Kernels sd_t_d2_fusion_(size_h3, size_h2, size_h1, size_p6, size_p5, size_p4, size_h7, host_t3, host_t2_2, host_v2_2, 1, opt_register_transpose); // Correctness-Check post_Correctness(host_t3, host_t3_chk, host_t2_1, host_v2_1, host_t2_2, host_v2_2, host_t2_3, host_v2_3, host_t2_4, host_v2_4, host_t2_5, host_v2_5, host_t2_6, host_v2_6, host_t2_7, host_v2_7, host_t2_8, host_v2_8, host_t2_9, host_v2_9, 1, 1, 1, 1, 1, 1, 1, 1, 1, size_h3, size_h2, size_h1, size_p6, size_p5, size_p4, size_h7); // Free free(host_t3); free(host_t3_chk); free(host_t2_1); free(host_t2_2); free(host_t2_3); free(host_t2_4); free(host_t2_5); free(host_t2_6); free(host_t2_7); free(host_t2_8); free(host_t2_9); free(host_v2_1); free(host_v2_2); free(host_v2_3); free(host_v2_4); free(host_v2_5); free(host_v2_6); free(host_v2_7); free(host_v2_8); free(host_v2_9); return 0; } // Initialize t3 (t3_temp), 9 t2 and 9 v2. void pre_Initializing_Input_Tensors(double* h_t3, double* h_t3_chk, double* h_t2_1, double* h_v2_1, double* h_t2_2, double* h_v2_2, double* h_t2_3, double* h_v2_3, double* h_t2_4, double* h_v2_4, double* h_t2_5, double* h_v2_5, double* h_t2_6, double* h_v2_6, double* h_t2_7, double* h_v2_7, double* h_t2_8, double* h_v2_8, double* h_t2_9, double* h_v2_9, int size_idx_h3, int size_idx_h2, int size_idx_h1, int size_idx_p6, int size_idx_p5, int size_idx_p4, int size_idx_h7) { int size_T3; int size_T2_1, size_T2_2, size_T2_3, size_T2_4, size_T2_5, size_T2_6, size_T2_7, size_T2_8, size_T2_9; int size_V2_1, size_V2_2, size_V2_3, size_V2_4, size_V2_5, size_V2_6, size_V2_7, size_V2_8, size_V2_9; int size_internal; // size_internal = size_idx_h7; size_T3 = size_idx_h3 * size_idx_h2 * size_idx_h1 * size_idx_p6 * size_idx_p5 * size_idx_p4; /* >> sd1 << 1: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_1 [h7,p4,p5,h1] * v2_1 [h3,h2,p6,h7]; 2: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_2 [h7,p4,p5,h2] * v2_2 [h3,h1,p6,h7]; 3: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_3 [h7,p4,p5,h3] * v2_3 [h2,h1,p6,h7]; 4: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_4 [h7,p5,p6,h1] * v2_4 [h3,h2,p4,h7]; 5: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_5 [h7,p5,p6,h2] * v2_5 [h3,h1,p4,h7]; 6: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_6 [h7,p5,p6,h3] * v2_6 [h2,h1,p4,h7]; 7: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_7 [h7,p4,p6,h1] * v2_7 [h3,h2,p5,h7]; 8: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_8 [h7,p4,p6,h2] * v2_8 [h3,h1,p5,h7]; 9: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_8 [h7,p4,p6,h3] * v2_9 [h2,h1,p5,h7]; */ // size_T2_1 = size_idx_h7 * size_idx_p4 * size_idx_p5 * size_idx_h1; size_V2_1 = size_idx_h3 * size_idx_h2 * size_idx_p6 * size_idx_h7; size_T2_2 = size_idx_h7 * size_idx_p4 * size_idx_p5 * size_idx_h2; size_V2_2 = size_idx_h3 * size_idx_h1 * size_idx_p6 * size_idx_h7; size_T2_3 = size_idx_h7 * size_idx_p4 * size_idx_p5 * size_idx_h3; size_V2_3 = size_idx_h2 * size_idx_h1 * size_idx_p6 * size_idx_h7; size_T2_4 = size_idx_h7 * size_idx_p5 * size_idx_p6 * size_idx_h1; size_V2_4 = size_idx_h3 * size_idx_h2 * size_idx_p4 * size_idx_h7; size_T2_5 = size_idx_h7 * size_idx_p5 * size_idx_p6 * size_idx_h2; size_V2_5 = size_idx_h3 * size_idx_h1 * size_idx_p4 * size_idx_h7; size_T2_6 = size_idx_h7 * size_idx_p5 * size_idx_p6 * size_idx_h3; size_V2_6 = size_idx_h2 * size_idx_h1 * size_idx_p4 * size_idx_h7; size_T2_7 = size_idx_h7 * size_idx_p4 * size_idx_p6 * size_idx_h1; size_V2_7 = size_idx_h3 * size_idx_h2 * size_idx_p5 * size_idx_h7; size_T2_8 = size_idx_h7 * size_idx_p4 * size_idx_p6 * size_idx_h2; size_V2_8 = size_idx_h3 * size_idx_h1 * size_idx_p5 * size_idx_h7; size_T2_9 = size_idx_h7 * size_idx_p4 * size_idx_p6 * size_idx_h3; size_V2_9 = size_idx_h2 * size_idx_h1 * size_idx_p5 * size_idx_h7; // t3 int i, j; for (i = 0; i < size_T3; i++) { h_t3[i] = 0.0; h_t3_chk[i] = 0.0; } for (j = 0; j < size_T2_1; j++) { h_t2_1[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_1; j++) { h_v2_1[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_2; j++) { h_t2_2[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_2; j++) { h_v2_2[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_3; j++) { h_t2_3[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_3; j++) { h_v2_3[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_4; j++) { h_t2_4[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_4; j++) { h_v2_4[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_5; j++) { h_t2_5[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_5; j++) { h_v2_5[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_6; j++) { h_t2_6[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_6; j++) { h_v2_6[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_7; j++) { h_t2_7[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_7; j++) { h_v2_7[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_8; j++) { h_t2_8[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_8; j++) { h_v2_8[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_T2_9; j++) { h_t2_9[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_V2_9; j++) { h_v2_9[j] = ((double)rand() / RAND_MAX); } printf ("==========================================================================================================\n"); printf (" >>> %s <<<\n", __func__); printf (" T3: %'12d\n", size_T3); printf (" T2_1: %'12d, V2_1: %'12d\n", size_T2_1, size_V2_1); printf (" T2_2: %'12d, V2_2: %'12d\n", size_T2_2, size_V2_2); printf (" T2_3: %'12d, V2_3: %'12d\n", size_T2_3, size_V2_3); printf (" T2_4: %'12d, V2_4: %'12d\n", size_T2_4, size_V2_4); printf (" T2_5: %'12d, V2_5: %'12d\n", size_T2_5, size_V2_5); printf (" T2_6: %'12d, V2_6: %'12d\n", size_T2_6, size_V2_6); printf (" T2_7: %'12d, V2_7: %'12d\n", size_T2_7, size_V2_7); printf (" T2_8: %'12d, V2_8: %'12d\n", size_T2_8, size_V2_8); printf (" T2_9: %'12d, V2_9: %'12d\n", size_T2_9, size_V2_9); printf ("==========================================================================================================\n"); } // void post_Correctness(double* h_t3, double* h_t3_chk, double* h_t2_1, double* h_v2_1, double* h_t2_2, double* h_v2_2, double* h_t2_3, double* h_v2_3, double* h_t2_4, double* h_v2_4, double* h_t2_5, double* h_v2_5, double* h_t2_6, double* h_v2_6, double* h_t2_7, double* h_v2_7, double* h_t2_8, double* h_v2_8, double* h_t2_9, double* h_v2_9, int kernel_1, int kernel_2, int kernel_3, int kernel_4, int kernel_5, int kernel_6, int kernel_7, int kernel_8, int kernel_9, int size_idx_h3, int size_idx_h2, int size_idx_h1, int size_idx_p6, int size_idx_p5, int size_idx_p4, int size_idx_h7) { int SIZE_IDX_H3; int SIZE_IDX_H2; int SIZE_IDX_H1; int SIZE_IDX_P6; int SIZE_IDX_P5; int SIZE_IDX_P4; int SIZE_IDX_H7; int STR_SD2_T3_H3; int STR_SD2_T3_H2;// STR_SD2_T3_H3 * SIZE_IDX_H3 int STR_SD2_T3_H1;// STR_SD2_T3_H2 * SIZE_IDX_H2 int STR_SD2_T3_P6;// STR_SD2_T3_H1 * SIZE_IDX_H1 int STR_SD2_T3_P5;// STR_SD2_T3_P6 * SIZE_IDX_P6 int STR_SD2_T3_P4;// STR_SD2_T3_P5 * SIZE_IDX_P5 // t2 for inputs int STR_SD2_T2_4_H7;// 1 int STR_SD2_T2_4_P5;// STR_SD2_T2_4_H7 * SIZE_IDX_H7 int STR_SD2_T2_4_P6;// STR_SD2_T2_4_P5 * SIZE_IDX_P5 int STR_SD2_T2_4_H1;// STR_SD2_T2_4_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_4_H3;// 1 int STR_SD2_V2_4_H2;// STR_SD2_V2_4_H3 * SIZE_IDX_H3 int STR_SD2_V2_4_P4;// STR_SD2_V2_4_H2 * SIZE_IDX_H2 int STR_SD2_V2_4_H7;// STR_SD2_V2_4_P4 * SIZE_IDX_P4 // t2 for inputs int STR_SD2_T2_5_H7;// 1 int STR_SD2_T2_5_P5;// STR_SD2_T2_5_H7 * SIZE_IDX_H7 int STR_SD2_T2_5_P6;// STR_SD2_T2_5_P5 * SIZE_IDX_P5 int STR_SD2_T2_5_H2;// STR_SD2_T2_5_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_5_H3;// 1 int STR_SD2_V2_5_H1;// STR_SD2_V2_5_H3 * SIZE_IDX_H3 int STR_SD2_V2_5_P4;// STR_SD2_V2_5_H1 * SIZE_IDX_H1 int STR_SD2_V2_5_H7;// STR_SD2_V2_5_P4 * SIZE_IDX_P4 // t2 for inputs int STR_SD2_T2_6_H7;// 1 int STR_SD2_T2_6_P5;// STR_SD2_T2_6_H7 * SIZE_IDX_H7 int STR_SD2_T2_6_P6;// STR_SD2_T2_6_P5 * SIZE_IDX_P5 int STR_SD2_T2_6_H3;// STR_SD2_T2_6_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_6_H2;// 1 int STR_SD2_V2_6_H1;// STR_SD2_V2_6_H2 * SIZE_IDX_H2 int STR_SD2_V2_6_P4;// STR_SD2_V2_6_H1 * SIZE_IDX_H1 int STR_SD2_V2_6_H7;// STR_SD2_V2_6_P4 * SIZE_IDX_P4 // t2 for inputs int STR_SD2_T2_7_H7;// 1 int STR_SD2_T2_7_P4;// STR_SD2_T2_7_H7 * SIZE_IDX_H7 int STR_SD2_T2_7_P6;// STR_SD2_T2_7_P4 * SIZE_IDX_P4 int STR_SD2_T2_7_H1;// STR_SD2_T2_7_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_7_H3;// 1 int STR_SD2_V2_7_H2;// STR_SD2_V2_7_H3 * SIZE_IDX_H3 int STR_SD2_V2_7_P5;// STR_SD2_V2_7_H2 * SIZE_IDX_H2 int STR_SD2_V2_7_H7;// STR_SD2_V2_7_P5 * SIZE_IDX_P5 // t2 for inputs int STR_SD2_T2_8_H7;// 1 int STR_SD2_T2_8_P4;// STR_SD2_T2_8_H7 * SIZE_IDX_H7 int STR_SD2_T2_8_P6;// STR_SD2_T2_8_P4 * SIZE_IDX_P4 int STR_SD2_T2_8_H2;// STR_SD2_T2_8_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_8_H3;// 1 int STR_SD2_V2_8_H1;// STR_SD2_V2_8_H3 * SIZE_IDX_H3 int STR_SD2_V2_8_P5;// STR_SD2_V2_8_H1 * SIZE_IDX_H1 int STR_SD2_V2_8_H7;// STR_SD2_V2_8_P5 * SIZE_IDX_P5 // t2 for inputs int STR_SD2_T2_9_H7;// 1 int STR_SD2_T2_9_P4;// STR_SD2_T2_9_H7 * SIZE_IDX_H7 int STR_SD2_T2_9_P6;// STR_SD2_T2_9_P4 * SIZE_IDX_P4 int STR_SD2_T2_9_H3;// STR_SD2_T2_9_P6 * SIZE_IDX_P6 // v2 for inputs int STR_SD2_V2_9_H2;// 1 int STR_SD2_V2_9_H1;// STR_SD2_V2_9_H2 * SIZE_IDX_H2 int STR_SD2_V2_9_P5;// STR_SD2_V2_9_H1 * SIZE_IDX_H1 int STR_SD2_V2_9_H7;// STR_SD2_V2_9_P5 * SIZE_IDX_P5 // t2 for inputs int STR_SD2_T2_1_H7;// 1 int STR_SD2_T2_1_P4;// STR_SD2_T2_1_H7 * SIZE_IDX_H7 int STR_SD2_T2_1_P5;// STR_SD2_T2_1_P4 * SIZE_IDX_P4 int STR_SD2_T2_1_H1;// STR_SD2_T2_1_P5 * SIZE_IDX_P5 // v2 for inputs int STR_SD2_V2_1_H3;// 1 int STR_SD2_V2_1_H2;// STR_SD2_V2_1_H3 * SIZE_IDX_H3 int STR_SD2_V2_1_P6;// STR_SD2_V2_1_H2 * SIZE_IDX_H2 int STR_SD2_V2_1_H7;// STR_SD2_V2_1_P6 * SIZE_IDX_P6 // t2 for inputs int STR_SD2_T2_2_H7;// 1 int STR_SD2_T2_2_P4;// STR_SD2_T2_2_H7 * SIZE_IDX_H7 int STR_SD2_T2_2_P5;// STR_SD2_T2_2_P4 * SIZE_IDX_P4 int STR_SD2_T2_2_H2;// STR_SD2_T2_2_P5 * SIZE_IDX_P5 // v2 for inputs int STR_SD2_V2_2_H3;// 1 int STR_SD2_V2_2_H1;// STR_SD2_V2_2_H3 * SIZE_IDX_H3 int STR_SD2_V2_2_P6;// STR_SD2_V2_2_H1 * SIZE_IDX_H1 int STR_SD2_V2_2_H7;// STR_SD2_V2_2_P6 * SIZE_IDX_P6 // t2 for inputs int STR_SD2_T2_3_H7;// 1 int STR_SD2_T2_3_P4;// STR_SD2_T2_3_H7 * SIZE_IDX_H7 int STR_SD2_T2_3_P5;// STR_SD2_T2_3_P4 * SIZE_IDX_P4 int STR_SD2_T2_3_H3;// STR_SD2_T2_3_P5 * SIZE_IDX_P5 // v2 for inputs int STR_SD2_V2_3_H2;// 1 int STR_SD2_V2_3_H1;// STR_SD2_V2_3_H2 * SIZE_IDX_H2 int STR_SD2_V2_3_P6;// STR_SD2_V2_3_H1 * SIZE_IDX_H1 int STR_SD2_V2_3_H7;// STR_SD2_V2_3_P6 * SIZE_IDX_P6 // Indices SIZE_IDX_H3 = size_idx_h3; SIZE_IDX_H2 = size_idx_h2; SIZE_IDX_H1 = size_idx_h1; SIZE_IDX_P6 = size_idx_p6; SIZE_IDX_P5 = size_idx_p5; SIZE_IDX_P4 = size_idx_p4; SIZE_IDX_H7 = size_idx_h7; // t3 STR_SD2_T3_H3 = 1; STR_SD2_T3_H2 = STR_SD2_T3_H3 * SIZE_IDX_H3; STR_SD2_T3_H1 = STR_SD2_T3_H2 * SIZE_IDX_H2; STR_SD2_T3_P6 = STR_SD2_T3_H1 * SIZE_IDX_H1; STR_SD2_T3_P5 = STR_SD2_T3_P6 * SIZE_IDX_P6; STR_SD2_T3_P4 = STR_SD2_T3_P5 * SIZE_IDX_P5; /* >> sd1 << 1: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_1 [h7,p4,p5,h1] * v2_1 [h3,h2,p6,h7]; 2: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_2 [h7,p4,p5,h2] * v2_2 [h3,h1,p6,h7]; 3: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_3 [h7,p4,p5,h3] * v2_3 [h2,h1,p6,h7]; 4: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_4 [h7,p5,p6,h1] * v2_4 [h3,h2,p4,h7]; 5: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_5 [h7,p5,p6,h2] * v2_5 [h3,h1,p4,h7]; 6: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_6 [h7,p5,p6,h3] * v2_6 [h2,h1,p4,h7]; 7: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_7 [h7,p4,p6,h1] * v2_7 [h3,h2,p5,h7]; 8: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] -= sum(h7,16) * t2_8 [h7,p4,p6,h2] * v2_8 [h3,h1,p5,h7]; 9: t3 [h3,16,h2,16,h1,16,p6,16,p5,16,p4,16] += sum(h7,16) * t2_8 [h7,p4,p6,h3] * v2_9 [h2,h1,p5,h7]; */ // t2 for inputs STR_SD2_T2_4_H7 = 1; STR_SD2_T2_4_P5 = STR_SD2_T2_4_H7 * SIZE_IDX_H7; STR_SD2_T2_4_P6 = STR_SD2_T2_4_P5 * SIZE_IDX_P5; STR_SD2_T2_4_H1 = STR_SD2_T2_4_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_4_H3 = 1; STR_SD2_V2_4_H2 = STR_SD2_V2_4_H3 * SIZE_IDX_H3; STR_SD2_V2_4_P4 = STR_SD2_V2_4_H2 * SIZE_IDX_H2; STR_SD2_V2_4_H7 = STR_SD2_V2_4_P4 * SIZE_IDX_P4; // t2 for inputs STR_SD2_T2_5_H7 = 1; STR_SD2_T2_5_P5 = STR_SD2_T2_5_H7 * SIZE_IDX_H7; STR_SD2_T2_5_P6 = STR_SD2_T2_5_P5 * SIZE_IDX_P5; STR_SD2_T2_5_H2 = STR_SD2_T2_5_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_5_H3 = 1; STR_SD2_V2_5_H1 = STR_SD2_V2_5_H3 * SIZE_IDX_H3; STR_SD2_V2_5_P4 = STR_SD2_V2_5_H1 * SIZE_IDX_H1; STR_SD2_V2_5_H7 = STR_SD2_V2_5_P4 * SIZE_IDX_P4; // t2 for inputs STR_SD2_T2_6_H7 = 1; STR_SD2_T2_6_P5 = STR_SD2_T2_6_H7 * SIZE_IDX_H7; STR_SD2_T2_6_P6 = STR_SD2_T2_6_P5 * SIZE_IDX_P5; STR_SD2_T2_6_H3 = STR_SD2_T2_6_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_6_H2 = 1; STR_SD2_V2_6_H1 = STR_SD2_V2_6_H2 * SIZE_IDX_H2; STR_SD2_V2_6_P4 = STR_SD2_V2_6_H1 * SIZE_IDX_H1; STR_SD2_V2_6_H7 = STR_SD2_V2_6_P4 * SIZE_IDX_P4; // t2 for inputs STR_SD2_T2_7_H7 = 1; STR_SD2_T2_7_P4 = STR_SD2_T2_7_H7 * SIZE_IDX_H7; STR_SD2_T2_7_P6 = STR_SD2_T2_7_P4 * SIZE_IDX_P4; STR_SD2_T2_7_H1 = STR_SD2_T2_7_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_7_H3 = 1; STR_SD2_V2_7_H2 = STR_SD2_V2_7_H3 * SIZE_IDX_H3; STR_SD2_V2_7_P5 = STR_SD2_V2_7_H2 * SIZE_IDX_H2; STR_SD2_V2_7_H7 = STR_SD2_V2_7_P5 * SIZE_IDX_P5; // t2 for inputs STR_SD2_T2_8_H7 = 1; STR_SD2_T2_8_P4 = STR_SD2_T2_8_H7 * SIZE_IDX_H7; STR_SD2_T2_8_P6 = STR_SD2_T2_8_P4 * SIZE_IDX_P4; STR_SD2_T2_8_H2 = STR_SD2_T2_8_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_8_H3 = 1; STR_SD2_V2_8_H1 = STR_SD2_V2_8_H3 * SIZE_IDX_H3; STR_SD2_V2_8_P5 = STR_SD2_V2_8_H1 * SIZE_IDX_H1; STR_SD2_V2_8_H7 = STR_SD2_V2_8_P5 * SIZE_IDX_P5; // t2 for inputs STR_SD2_T2_9_H7 = 1; STR_SD2_T2_9_P4 = STR_SD2_T2_9_H7 * SIZE_IDX_H7; STR_SD2_T2_9_P6 = STR_SD2_T2_9_P4 * SIZE_IDX_P4; STR_SD2_T2_9_H3 = STR_SD2_T2_9_P6 * SIZE_IDX_P6; // v2 for inputs STR_SD2_V2_9_H2 = 1; STR_SD2_V2_9_H1 = STR_SD2_V2_9_H2 * SIZE_IDX_H2; STR_SD2_V2_9_P5 = STR_SD2_V2_9_H1 * SIZE_IDX_H1; STR_SD2_V2_9_H7 = STR_SD2_V2_9_P5 * SIZE_IDX_P5; // t2 for inputs STR_SD2_T2_1_H7 = 1; STR_SD2_T2_1_P4 = STR_SD2_T2_1_H7 * SIZE_IDX_H7; STR_SD2_T2_1_P5 = STR_SD2_T2_1_P4 * SIZE_IDX_P4; STR_SD2_T2_1_H1 = STR_SD2_T2_1_P5 * SIZE_IDX_P5;; // v2 for inputs STR_SD2_V2_1_H3 = 1; STR_SD2_V2_1_H2 = STR_SD2_V2_1_H3 * SIZE_IDX_H3; STR_SD2_V2_1_P6 = STR_SD2_V2_1_H2 * SIZE_IDX_H2; STR_SD2_V2_1_H7 = STR_SD2_V2_1_P6 * SIZE_IDX_P6; // t2 for inputs STR_SD2_T2_2_H7 = 1; STR_SD2_T2_2_P4 = STR_SD2_T2_2_H7 * SIZE_IDX_H7; STR_SD2_T2_2_P5 = STR_SD2_T2_2_P4 * SIZE_IDX_P4; STR_SD2_T2_2_H2 = STR_SD2_T2_2_P5 * SIZE_IDX_P5; // v2 for inputs STR_SD2_V2_2_H3 = 1; STR_SD2_V2_2_H1 = STR_SD2_V2_2_H3 * SIZE_IDX_H3; STR_SD2_V2_2_P6 = STR_SD2_V2_2_H1 * SIZE_IDX_H1; STR_SD2_V2_2_H7 = STR_SD2_V2_2_P6 * SIZE_IDX_P6; // t2 for inputs STR_SD2_T2_3_H7 = 1; STR_SD2_T2_3_P4 = STR_SD2_T2_3_H7 * SIZE_IDX_H7; STR_SD2_T2_3_P5 = STR_SD2_T2_3_P4 * SIZE_IDX_P4; STR_SD2_T2_3_H3 = STR_SD2_T2_3_P5 * SIZE_IDX_P5; // v2 for inputs STR_SD2_V2_3_H2 = 1; STR_SD2_V2_3_H1 = STR_SD2_V2_3_H2 * SIZE_IDX_H2; STR_SD2_V2_3_P6 = STR_SD2_V2_3_H1 * SIZE_IDX_H1; STR_SD2_V2_3_H7 = STR_SD2_V2_3_P6 * SIZE_IDX_P6; long long int tmp_ops = 0; int ops = 0; int t3_h3, t3_h2, t3_h1, t3_p6, t3_p5, t3_p4, t3_h7; for (t3_h3 = 0; t3_h3 < SIZE_IDX_H3; t3_h3++) for (t3_h2 = 0; t3_h2 < SIZE_IDX_H2; t3_h2++) for (t3_h1 = 0; t3_h1 < SIZE_IDX_H1; t3_h1++) for (t3_p6 = 0; t3_p6 < SIZE_IDX_P6; t3_p6++) for (t3_p5 = 0; t3_p5 < SIZE_IDX_P5; t3_p5++) for (t3_p4 = 0; t3_p4 < SIZE_IDX_P4; t3_p4++) { int tmp_r_idx = t3_h3 * STR_SD2_T3_H3 + t3_h2 * STR_SD2_T3_H2 + t3_h1 * STR_SD2_T3_H1 + t3_p6 * STR_SD2_T3_P6 + t3_p5 * STR_SD2_T3_P5 + t3_p4 * STR_SD2_T3_P4; for (t3_h7 = 0; t3_h7 < SIZE_IDX_H7; t3_h7++, ops = 0) { /* if (kernel_4 == 1) { h_t3_chk[tmp_r_idx] -= h_t2_4[t3_h7 * STR_SD2_T2_4_H7 + t3_p5 * STR_SD2_T2_4_P5 + t3_p6 * STR_SD2_T2_4_P6 + t3_h1 * STR_SD2_T2_4_H1] * h_v2_4[t3_h3 * STR_SD2_V2_4_H3 + t3_h2 * STR_SD2_V2_4_H2 + t3_p4 * STR_SD2_V2_4_P4 + t3_h7 * STR_SD2_V2_4_H7]; ops++; } */ /* if (kernel_5 == 1) { h_t3_chk[tmp_r_idx] += h_t2_5[t3_h7 * STR_SD2_T2_5_H7 + t3_p5 * STR_SD2_T2_5_P5 + t3_p6 * STR_SD2_T2_5_P6 + t3_h2 * STR_SD2_T2_5_H2] * h_v2_5[t3_h3 * STR_SD2_V2_5_H3 + t3_h1 * STR_SD2_V2_5_H1 + t3_p4 * STR_SD2_V2_5_P4 + t3_h7 * STR_SD2_V2_5_H7]; ops++; } if (kernel_6 == 1) { h_t3_chk[tmp_r_idx] -= h_t2_6[t3_h7 * STR_SD2_T2_6_H7 + t3_p5 * STR_SD2_T2_6_P5 + t3_p6 * STR_SD2_T2_6_P6 + t3_h3 * STR_SD2_T2_6_H3] * h_v2_6[t3_h2 * STR_SD2_V2_6_H2 + t3_h1 * STR_SD2_V2_6_H1 + t3_p4 * STR_SD2_V2_6_P4 + t3_h7 * STR_SD2_V2_6_H7]; ops++; } if (kernel_7 == 1) { h_t3_chk[tmp_r_idx] += h_t2_7[t3_h7 * STR_SD2_T2_7_H7 + t3_p4 * STR_SD2_T2_7_P4 + t3_p6 * STR_SD2_T2_7_P6 + t3_h1 * STR_SD2_T2_7_H1] * h_v2_7[t3_h3 * STR_SD2_V2_7_H3 + t3_h2 * STR_SD2_V2_7_H2 + t3_p5 * STR_SD2_V2_7_P5 + t3_h7 * STR_SD2_V2_7_H7]; ops++; } if (kernel_8 == 1) { h_t3_chk[tmp_r_idx] -= h_t2_8[t3_h7 * STR_SD2_T2_8_H7 + t3_p4 * STR_SD2_T2_8_P4 + t3_p6 * STR_SD2_T2_8_P6 + t3_h2 * STR_SD2_T2_8_H2] * h_v2_8[t3_h3 * STR_SD2_V2_8_H3 + t3_h1 * STR_SD2_V2_8_H1 + t3_p5 * STR_SD2_V2_8_P5 + t3_h7 * STR_SD2_V2_8_H7]; ops++; } if (kernel_9 == 1) { h_t3_chk[tmp_r_idx] += h_t2_9[t3_h7 * STR_SD2_T2_9_H7 + t3_p4 * STR_SD2_T2_9_P4 + t3_p6 * STR_SD2_T2_9_P6 + t3_h3 * STR_SD2_T2_9_H3] * h_v2_9[t3_h2 * STR_SD2_V2_9_H2 + t3_h1 * STR_SD2_V2_9_H1 + t3_p5 * STR_SD2_V2_9_P5 + t3_h7 * STR_SD2_V2_9_H7]; ops++; } if (kernel_1 == 1) { h_t3_chk[tmp_r_idx] -= h_t2_1[t3_h7 * STR_SD2_T2_1_H7 + t3_p4 * STR_SD2_T2_1_P4 + t3_p5 * STR_SD2_T2_1_P5 + t3_h1 * STR_SD2_T2_1_H1] * h_v2_1[t3_h3 * STR_SD2_V2_1_H3 + t3_h2 * STR_SD2_V2_1_H2 + t3_p6 * STR_SD2_V2_1_P6 + t3_h7 * STR_SD2_V2_1_H7]; ops++; } */ h_t3_chk[tmp_r_idx] -= h_t2_2[t3_h7 * STR_SD2_T2_2_H7 + t3_p4 * STR_SD2_T2_2_P4 + t3_p5 * STR_SD2_T2_2_P5 + t3_h2 * STR_SD2_T2_2_H2] * h_v2_2[t3_h3 * STR_SD2_V2_2_H3 + t3_h1 * STR_SD2_V2_2_H1 + t3_p6 * STR_SD2_V2_2_P6 + t3_h7 * STR_SD2_V2_2_H7]; ops++; /* if (tmp_r_idx == 0) { printf ("[%d][%2d] t2_2: %f (%d), v2_2: %f (%d)\n", tmp_r_idx, t3_h7, h_t2_2[t3_h7 * STR_SD2_T2_2_H7 + t3_p4 * STR_SD2_T2_2_P4 + t3_p5 * STR_SD2_T2_2_P5 + t3_h2 * STR_SD2_T2_2_H2], t3_h7 * STR_SD2_T2_2_H7 + t3_p4 * STR_SD2_T2_2_P4 + t3_p5 * STR_SD2_T2_2_P5 + t3_h2 * STR_SD2_T2_2_H2, h_v2_2[t3_h3 * STR_SD2_V2_2_H3 + t3_h1 * STR_SD2_V2_2_H1 + t3_p6 * STR_SD2_V2_2_P6 + t3_h7 * STR_SD2_V2_2_H7], t3_h3 * STR_SD2_V2_2_H3 + t3_h1 * STR_SD2_V2_2_H1 + t3_p6 * STR_SD2_V2_2_P6 + t3_h7 * STR_SD2_V2_2_H7); } */ /* if (kernel_3 == 1) { h_t3_chk[tmp_r_idx] -= h_t2_3[t3_h7 * STR_SD2_T2_3_H7 + t3_p4 * STR_SD2_T2_3_P4 + t3_p5 * STR_SD2_T2_3_P5 + t3_h3 * STR_SD2_T2_3_H3] * h_v2_3[t3_h2 * STR_SD2_V2_3_H2 + t3_h1 * STR_SD2_V2_3_H1 + t3_p6 * STR_SD2_V2_3_P6 + t3_h7 * STR_SD2_V2_3_H7]; ops++; } */ tmp_ops = tmp_ops + ops; } } printf ("======================================= Correctness Check ==========================================\n"); double epsilon = 0.00000001; int diff = 0; int same = 0; int i; for (i = 0; i < size_idx_h3 * size_idx_h2 * size_idx_h1 * size_idx_p6 * size_idx_p5 * size_idx_p4; i++) { double check = h_t3_chk[i] - h_t3[i]; if (check < 0) check *= -1; if (check > epsilon) { diff++; if (diff < 8) printf ("Index: %5d, (Host) %8.4f, (Dev.) %8.4f >> (Diff.) %8.4f\n", i, h_t3_chk[i], h_t3[i], check); } else { same++; } } printf (" >>> PASSED: %'10d among %'10d in t3\n", same, size_idx_h3 * size_idx_h2 * size_idx_h1 * size_idx_p6 * size_idx_p5 * size_idx_p4); printf (" >>> ERROR : %'10d among %'10d in t3\n", diff, size_idx_h3 * size_idx_h2 * size_idx_h1 * size_idx_p6 * size_idx_p5 * size_idx_p4); printf (" >>> Total Operations: %'lld\n", tmp_ops * 2); printf ("====================================================================================================\n"); }
the_stack_data/132954317.c
// BHAX BogoMIPS // Copyright (C) 2019 // Norbert Batfai, [email protected] // // 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 <https://www.gnu.org/licenses/>. // // Version history // // This program is based on // // - Linus Torvalds's original code (https://mirrors.edge.kernel.org/pub/linux/kernel/v1.0/linux-1.0.tar.gz init/main.c) // - and Jeff Tranter's standalone version (archive.debian.org/debian/pool/main/s/sysutils/sysutils_1.3.8.5.1.tar.gz). // // See also UDPROG // #include <time.h> #include <stdio.h> void delay (unsigned long long loops) { for (unsigned long long i = 0; i < loops; i++); } int main (void) { unsigned long long loops_per_sec = 1; unsigned long long ticks; printf ("Calibrating delay loop.."); fflush (stdout); while ((loops_per_sec <<= 1)) { ticks = clock (); delay (loops_per_sec); ticks = clock () - ticks; if (ticks >= CLOCKS_PER_SEC) { loops_per_sec = (loops_per_sec / ticks) * CLOCKS_PER_SEC; printf ("ok - %llu.%02llu BogoMIPS\n", loops_per_sec / 500000, (loops_per_sec / 5000) % 100); return 0; } } printf ("failed\n"); return -1; }
the_stack_data/572102.c
void main() { unsigned long u; u = 1; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; if (!u) _exit(0); _exit(1); }
the_stack_data/98576254.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_str_is_uppercase.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkalnins <[email protected]. +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/17 21:37:56 by kkalnins #+# #+# */ /* Updated: 2021/02/17 23:19:43 by kkalnins ### ########.fr */ /* */ /* ************************************************************************** */ int ft_str_is_uppercase(char *str) { int i; i = 0; while (str[i]) { if (str[i] > 'Z' || str[i] < 'A') return (0); i++; } return (1); }
the_stack_data/200143771.c
/* Extended regular expression matching and search library. Copyright (C) 2002, 2003, 2005 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Isamu Hasegawa <[email protected]>. 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. */ /* this is for removing a compiler warning */ void gkfooo() { return; } #ifdef USE_GKREGEX #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef _LIBC /* We have to keep the namespace clean. */ # define regfree(preg) __regfree (preg) # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef) # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags) # define regerror(errcode, preg, errbuf, errbuf_size) \ __regerror(errcode, preg, errbuf, errbuf_size) # define re_set_registers(bu, re, nu, st, en) \ __re_set_registers (bu, re, nu, st, en) # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \ __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop) # define re_match(bufp, string, size, pos, regs) \ __re_match (bufp, string, size, pos, regs) # define re_search(bufp, string, size, startpos, range, regs) \ __re_search (bufp, string, size, startpos, range, regs) # define re_compile_pattern(pattern, length, bufp) \ __re_compile_pattern (pattern, length, bufp) # define re_set_syntax(syntax) __re_set_syntax (syntax) # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \ __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop) # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp) # include "../locale/localeinfo.h" #endif #include "GKlib.h" /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* GKINCLUDE #include "regex_internal.h" */ /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* Extended regular expression matching and search library. Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Isamu Hasegawa <[email protected]>. 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. */ #ifndef _REGEX_INTERNAL_H #define _REGEX_INTERNAL_H 1 #include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(__MINGW32_VERSION) || defined(_MSC_VER) #define strcasecmp stricmp #endif #if defined HAVE_LANGINFO_H || defined HAVE_LANGINFO_CODESET || defined _LIBC # include <langinfo.h> #endif #if defined HAVE_LOCALE_H || defined _LIBC # include <locale.h> #endif #if defined HAVE_WCHAR_H || defined _LIBC # include <wchar.h> #endif /* HAVE_WCHAR_H || _LIBC */ #if defined HAVE_WCTYPE_H || defined _LIBC # include <wctype.h> #endif /* HAVE_WCTYPE_H || _LIBC */ #if defined HAVE_STDBOOL_H || defined _LIBC # include <stdbool.h> #else typedef enum { false, true } bool; #endif /* HAVE_STDBOOL_H || _LIBC */ #if defined HAVE_STDINT_H || defined _LIBC # include <stdint.h> #endif /* HAVE_STDINT_H || _LIBC */ #if defined _LIBC # include <bits/libc-lock.h> #else # define __libc_lock_define(CLASS,NAME) # define __libc_lock_init(NAME) do { } while (0) # define __libc_lock_lock(NAME) do { } while (0) # define __libc_lock_unlock(NAME) do { } while (0) #endif /* In case that the system doesn't have isblank(). */ #if !defined _LIBC && !defined HAVE_ISBLANK && !defined isblank # define isblank(ch) ((ch) == ' ' || (ch) == '\t') #endif #ifdef _LIBC # ifndef _RE_DEFINE_LOCALE_FUNCTIONS # define _RE_DEFINE_LOCALE_FUNCTIONS 1 # include <locale/localeinfo.h> # include <locale/elem-hash.h> # include <locale/coll-lookup.h> # endif #endif /* This is for other GNU distributions with internationalized messages. */ #if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC # include <libintl.h> # ifdef _LIBC # undef gettext # define gettext(msgid) \ INTUSE(__dcgettext) (_libc_intl_domainname, msgid, LC_MESSAGES) # endif #else # define gettext(msgid) (msgid) #endif #ifndef gettext_noop /* This define is so xgettext can find the internationalizable strings. */ # define gettext_noop(String) String #endif /* For loser systems without the definition. */ #ifndef SIZE_MAX # define SIZE_MAX ((size_t) -1) #endif #if (defined MB_CUR_MAX && HAVE_LOCALE_H && HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_WCRTOMB && HAVE_MBRTOWC && HAVE_WCSCOLL) || _LIBC # define RE_ENABLE_I18N #endif #if __GNUC__ >= 3 # define BE(expr, val) __builtin_expect (expr, val) #else # define BE(expr, val) (expr) # define inline #endif /* Number of single byte character. */ #define SBC_MAX 256 #define COLL_ELEM_LEN_MAX 8 /* The character which represents newline. */ #define NEWLINE_CHAR '\n' #define WIDE_NEWLINE_CHAR L'\n' /* Rename to standard API for using out of glibc. */ #ifndef _LIBC # define __wctype wctype # define __iswctype iswctype # define __btowc btowc # define __mempcpy mempcpy # define __wcrtomb wcrtomb # define __regfree regfree # define attribute_hidden #endif /* not _LIBC */ #ifdef __GNUC__ # define __attribute(arg) __attribute__ (arg) #else # define __attribute(arg) #endif extern const char __re_error_msgid[] attribute_hidden; extern const size_t __re_error_msgid_idx[] attribute_hidden; /* An integer used to represent a set of bits. It must be unsigned, and must be at least as wide as unsigned int. */ typedef unsigned long int bitset_word_t; /* All bits set in a bitset_word_t. */ #define BITSET_WORD_MAX ULONG_MAX /* Number of bits in a bitset_word_t. */ #define BITSET_WORD_BITS (sizeof (bitset_word_t) * CHAR_BIT) /* Number of bitset_word_t in a bit_set. */ #define BITSET_WORDS (SBC_MAX / BITSET_WORD_BITS) typedef bitset_word_t bitset_t[BITSET_WORDS]; typedef bitset_word_t *re_bitset_ptr_t; typedef const bitset_word_t *re_const_bitset_ptr_t; #define bitset_set(set,i) \ (set[i / BITSET_WORD_BITS] |= (bitset_word_t) 1 << i % BITSET_WORD_BITS) #define bitset_clear(set,i) \ (set[i / BITSET_WORD_BITS] &= ~((bitset_word_t) 1 << i % BITSET_WORD_BITS)) #define bitset_contain(set,i) \ (set[i / BITSET_WORD_BITS] & ((bitset_word_t) 1 << i % BITSET_WORD_BITS)) #define bitset_empty(set) memset (set, '\0', sizeof (bitset_t)) #define bitset_set_all(set) memset (set, '\xff', sizeof (bitset_t)) #define bitset_copy(dest,src) memcpy (dest, src, sizeof (bitset_t)) #define PREV_WORD_CONSTRAINT 0x0001 #define PREV_NOTWORD_CONSTRAINT 0x0002 #define NEXT_WORD_CONSTRAINT 0x0004 #define NEXT_NOTWORD_CONSTRAINT 0x0008 #define PREV_NEWLINE_CONSTRAINT 0x0010 #define NEXT_NEWLINE_CONSTRAINT 0x0020 #define PREV_BEGBUF_CONSTRAINT 0x0040 #define NEXT_ENDBUF_CONSTRAINT 0x0080 #define WORD_DELIM_CONSTRAINT 0x0100 #define NOT_WORD_DELIM_CONSTRAINT 0x0200 typedef enum { INSIDE_WORD = PREV_WORD_CONSTRAINT | NEXT_WORD_CONSTRAINT, WORD_FIRST = PREV_NOTWORD_CONSTRAINT | NEXT_WORD_CONSTRAINT, WORD_LAST = PREV_WORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT, INSIDE_NOTWORD = PREV_NOTWORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT, LINE_FIRST = PREV_NEWLINE_CONSTRAINT, LINE_LAST = NEXT_NEWLINE_CONSTRAINT, BUF_FIRST = PREV_BEGBUF_CONSTRAINT, BUF_LAST = NEXT_ENDBUF_CONSTRAINT, WORD_DELIM = WORD_DELIM_CONSTRAINT, NOT_WORD_DELIM = NOT_WORD_DELIM_CONSTRAINT } re_context_type; typedef struct { int alloc; int nelem; int *elems; } re_node_set; typedef enum { NON_TYPE = 0, /* Node type, These are used by token, node, tree. */ CHARACTER = 1, END_OF_RE = 2, SIMPLE_BRACKET = 3, OP_BACK_REF = 4, OP_PERIOD = 5, #ifdef RE_ENABLE_I18N COMPLEX_BRACKET = 6, OP_UTF8_PERIOD = 7, #endif /* RE_ENABLE_I18N */ /* We define EPSILON_BIT as a macro so that OP_OPEN_SUBEXP is used when the debugger shows values of this enum type. */ #define EPSILON_BIT 8 OP_OPEN_SUBEXP = EPSILON_BIT | 0, OP_CLOSE_SUBEXP = EPSILON_BIT | 1, OP_ALT = EPSILON_BIT | 2, OP_DUP_ASTERISK = EPSILON_BIT | 3, ANCHOR = EPSILON_BIT | 4, /* Tree type, these are used only by tree. */ CONCAT = 16, SUBEXP = 17, /* Token type, these are used only by token. */ OP_DUP_PLUS = 18, OP_DUP_QUESTION, OP_OPEN_BRACKET, OP_CLOSE_BRACKET, OP_CHARSET_RANGE, OP_OPEN_DUP_NUM, OP_CLOSE_DUP_NUM, OP_NON_MATCH_LIST, OP_OPEN_COLL_ELEM, OP_CLOSE_COLL_ELEM, OP_OPEN_EQUIV_CLASS, OP_CLOSE_EQUIV_CLASS, OP_OPEN_CHAR_CLASS, OP_CLOSE_CHAR_CLASS, OP_WORD, OP_NOTWORD, OP_SPACE, OP_NOTSPACE, BACK_SLASH } re_token_type_t; #ifdef RE_ENABLE_I18N typedef struct { /* Multibyte characters. */ wchar_t *mbchars; /* Collating symbols. */ # ifdef _LIBC int32_t *coll_syms; # endif /* Equivalence classes. */ # ifdef _LIBC int32_t *equiv_classes; # endif /* Range expressions. */ # ifdef _LIBC uint32_t *range_starts; uint32_t *range_ends; # else /* not _LIBC */ wchar_t *range_starts; wchar_t *range_ends; # endif /* not _LIBC */ /* Character classes. */ wctype_t *char_classes; /* If this character set is the non-matching list. */ unsigned int non_match : 1; /* # of multibyte characters. */ int nmbchars; /* # of collating symbols. */ int ncoll_syms; /* # of equivalence classes. */ int nequiv_classes; /* # of range expressions. */ int nranges; /* # of character classes. */ int nchar_classes; } re_charset_t; #endif /* RE_ENABLE_I18N */ typedef struct { union { unsigned char c; /* for CHARACTER */ re_bitset_ptr_t sbcset; /* for SIMPLE_BRACKET */ #ifdef RE_ENABLE_I18N re_charset_t *mbcset; /* for COMPLEX_BRACKET */ #endif /* RE_ENABLE_I18N */ int idx; /* for BACK_REF */ re_context_type ctx_type; /* for ANCHOR */ } opr; #if __GNUC__ >= 2 re_token_type_t type : 8; #else re_token_type_t type; #endif unsigned int constraint : 10; /* context constraint */ unsigned int duplicated : 1; unsigned int opt_subexp : 1; #ifdef RE_ENABLE_I18N unsigned int accept_mb : 1; /* These 2 bits can be moved into the union if needed (e.g. if running out of bits; move opr.c to opr.c.c and move the flags to opr.c.flags). */ unsigned int mb_partial : 1; #endif unsigned int word_char : 1; } re_token_t; #define IS_EPSILON_NODE(type) ((type) & EPSILON_BIT) struct re_string_t { /* Indicate the raw buffer which is the original string passed as an argument of regexec(), re_search(), etc.. */ const unsigned char *raw_mbs; /* Store the multibyte string. In case of "case insensitive mode" like REG_ICASE, upper cases of the string are stored, otherwise MBS points the same address that RAW_MBS points. */ unsigned char *mbs; #ifdef RE_ENABLE_I18N /* Store the wide character string which is corresponding to MBS. */ wint_t *wcs; int *offsets; mbstate_t cur_state; #endif /* Index in RAW_MBS. Each character mbs[i] corresponds to raw_mbs[raw_mbs_idx + i]. */ int raw_mbs_idx; /* The length of the valid characters in the buffers. */ int valid_len; /* The corresponding number of bytes in raw_mbs array. */ int valid_raw_len; /* The length of the buffers MBS and WCS. */ int bufs_len; /* The index in MBS, which is updated by re_string_fetch_byte. */ int cur_idx; /* length of RAW_MBS array. */ int raw_len; /* This is RAW_LEN - RAW_MBS_IDX + VALID_LEN - VALID_RAW_LEN. */ int len; /* End of the buffer may be shorter than its length in the cases such as re_match_2, re_search_2. Then, we use STOP for end of the buffer instead of LEN. */ int raw_stop; /* This is RAW_STOP - RAW_MBS_IDX adjusted through OFFSETS. */ int stop; /* The context of mbs[0]. We store the context independently, since the context of mbs[0] may be different from raw_mbs[0], which is the beginning of the input string. */ unsigned int tip_context; /* The translation passed as a part of an argument of re_compile_pattern. */ RE_TRANSLATE_TYPE trans; /* Copy of re_dfa_t's word_char. */ re_const_bitset_ptr_t word_char; /* 1 if REG_ICASE. */ unsigned char icase; unsigned char is_utf8; unsigned char map_notascii; unsigned char mbs_allocated; unsigned char offsets_needed; unsigned char newline_anchor; unsigned char word_ops_used; int mb_cur_max; }; typedef struct re_string_t re_string_t; struct re_dfa_t; typedef struct re_dfa_t re_dfa_t; #ifndef _LIBC # ifdef __i386__ # define internal_function __attribute ((regparm (3), stdcall)) # else # define internal_function # endif #endif static reg_errcode_t re_string_realloc_buffers (re_string_t *pstr, int new_buf_len) internal_function; #ifdef RE_ENABLE_I18N static void build_wcs_buffer (re_string_t *pstr) internal_function; static int build_wcs_upper_buffer (re_string_t *pstr) internal_function; #endif /* RE_ENABLE_I18N */ static void build_upper_buffer (re_string_t *pstr) internal_function; static void re_string_translate_buffer (re_string_t *pstr) internal_function; static unsigned int re_string_context_at (const re_string_t *input, int idx, int eflags) internal_function __attribute ((pure)); #define re_string_peek_byte(pstr, offset) \ ((pstr)->mbs[(pstr)->cur_idx + offset]) #define re_string_fetch_byte(pstr) \ ((pstr)->mbs[(pstr)->cur_idx++]) #define re_string_first_byte(pstr, idx) \ ((idx) == (pstr)->valid_len || (pstr)->wcs[idx] != WEOF) #define re_string_is_single_byte_char(pstr, idx) \ ((pstr)->wcs[idx] != WEOF && ((pstr)->valid_len == (idx) + 1 \ || (pstr)->wcs[(idx) + 1] != WEOF)) #define re_string_eoi(pstr) ((pstr)->stop <= (pstr)->cur_idx) #define re_string_cur_idx(pstr) ((pstr)->cur_idx) #define re_string_get_buffer(pstr) ((pstr)->mbs) #define re_string_length(pstr) ((pstr)->len) #define re_string_byte_at(pstr,idx) ((pstr)->mbs[idx]) #define re_string_skip_bytes(pstr,idx) ((pstr)->cur_idx += (idx)) #define re_string_set_index(pstr,idx) ((pstr)->cur_idx = (idx)) #ifdef __GNUC__ # define nb_allocate_on_stack(size) __builtin_alloca (size) # define HAVE_ALLOCA 1 #elif defined(_MSC_VER) # include <malloc.h> # define alloca _alloca # define HAVE_ALLOCA 1 #else # error No nb_allocate_on_stack() #endif #ifndef _LIBC # if HAVE_ALLOCA /* The OS usually guarantees only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely allocate anything larger than 4096 bytes. Also care for the possibility of a few compiler-allocated temporary stack slots. */ # define __libc_use_nb_allocate_on_stack(n) ((n) < 4032) # else /* alloca is implemented with malloc, so just use malloc. */ # define __libc_use_nb_allocate_on_stack(n) 0 # endif #endif #define re_malloc(t,n) ((t *) malloc ((n) * sizeof (t))) #define re_realloc(p,t,n) ((t *) realloc (p, (n) * sizeof (t))) #define re_free(p) free (p) struct bin_tree_t { struct bin_tree_t *parent; struct bin_tree_t *left; struct bin_tree_t *right; struct bin_tree_t *first; struct bin_tree_t *next; re_token_t token; /* `node_idx' is the index in dfa->nodes, if `type' == 0. Otherwise `type' indicate the type of this node. */ int node_idx; }; typedef struct bin_tree_t bin_tree_t; #define BIN_TREE_STORAGE_SIZE \ ((1024 - sizeof (void *)) / sizeof (bin_tree_t)) struct bin_tree_storage_t { struct bin_tree_storage_t *next; bin_tree_t data[BIN_TREE_STORAGE_SIZE]; }; typedef struct bin_tree_storage_t bin_tree_storage_t; #define CONTEXT_WORD 1 #define CONTEXT_NEWLINE (CONTEXT_WORD << 1) #define CONTEXT_BEGBUF (CONTEXT_NEWLINE << 1) #define CONTEXT_ENDBUF (CONTEXT_BEGBUF << 1) #define IS_WORD_CONTEXT(c) ((c) & CONTEXT_WORD) #define IS_NEWLINE_CONTEXT(c) ((c) & CONTEXT_NEWLINE) #define IS_BEGBUF_CONTEXT(c) ((c) & CONTEXT_BEGBUF) #define IS_ENDBUF_CONTEXT(c) ((c) & CONTEXT_ENDBUF) #define IS_ORDINARY_CONTEXT(c) ((c) == 0) #define IS_WORD_CHAR(ch) (isalnum (ch) || (ch) == '_') #define IS_NEWLINE(ch) ((ch) == NEWLINE_CHAR) #define IS_WIDE_WORD_CHAR(ch) (iswalnum (ch) || (ch) == L'_') #define IS_WIDE_NEWLINE(ch) ((ch) == WIDE_NEWLINE_CHAR) #define NOT_SATISFY_PREV_CONSTRAINT(constraint,context) \ ((((constraint) & PREV_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \ || ((constraint & PREV_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \ || ((constraint & PREV_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context))\ || ((constraint & PREV_BEGBUF_CONSTRAINT) && !IS_BEGBUF_CONTEXT (context))) #define NOT_SATISFY_NEXT_CONSTRAINT(constraint,context) \ ((((constraint) & NEXT_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \ || (((constraint) & NEXT_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \ || (((constraint) & NEXT_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context)) \ || (((constraint) & NEXT_ENDBUF_CONSTRAINT) && !IS_ENDBUF_CONTEXT (context))) struct re_dfastate_t { unsigned int hash; re_node_set nodes; re_node_set non_eps_nodes; re_node_set inveclosure; re_node_set *entrance_nodes; struct re_dfastate_t **trtable, **word_trtable; unsigned int context : 4; unsigned int halt : 1; /* If this state can accept `multi byte'. Note that we refer to multibyte characters, and multi character collating elements as `multi byte'. */ unsigned int accept_mb : 1; /* If this state has backreference node(s). */ unsigned int has_backref : 1; unsigned int has_constraint : 1; }; typedef struct re_dfastate_t re_dfastate_t; struct re_state_table_entry { int num; int alloc; re_dfastate_t **array; }; /* Array type used in re_sub_match_last_t and re_sub_match_top_t. */ typedef struct { int next_idx; int alloc; re_dfastate_t **array; } state_array_t; /* Store information about the node NODE whose type is OP_CLOSE_SUBEXP. */ typedef struct { int node; int str_idx; /* The position NODE match at. */ state_array_t path; } re_sub_match_last_t; /* Store information about the node NODE whose type is OP_OPEN_SUBEXP. And information about the node, whose type is OP_CLOSE_SUBEXP, corresponding to NODE is stored in LASTS. */ typedef struct { int str_idx; int node; state_array_t *path; int alasts; /* Allocation size of LASTS. */ int nlasts; /* The number of LASTS. */ re_sub_match_last_t **lasts; } re_sub_match_top_t; struct re_backref_cache_entry { int node; int str_idx; int subexp_from; int subexp_to; char more; char unused; unsigned short int eps_reachable_subexps_map; }; typedef struct { /* The string object corresponding to the input string. */ re_string_t input; #if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) const re_dfa_t *const dfa; #else const re_dfa_t *dfa; #endif /* EFLAGS of the argument of regexec. */ int eflags; /* Where the matching ends. */ int match_last; int last_node; /* The state log used by the matcher. */ re_dfastate_t **state_log; int state_log_top; /* Back reference cache. */ int nbkref_ents; int abkref_ents; struct re_backref_cache_entry *bkref_ents; int max_mb_elem_len; int nsub_tops; int asub_tops; re_sub_match_top_t **sub_tops; } re_match_context_t; typedef struct { re_dfastate_t **sifted_states; re_dfastate_t **limited_states; int last_node; int last_str_idx; re_node_set limits; } re_sift_context_t; struct re_fail_stack_ent_t { int idx; int node; regmatch_t *regs; re_node_set eps_via_nodes; }; struct re_fail_stack_t { int num; int alloc; struct re_fail_stack_ent_t *stack; }; struct re_dfa_t { re_token_t *nodes; size_t nodes_alloc; size_t nodes_len; int *nexts; int *org_indices; re_node_set *edests; re_node_set *eclosures; re_node_set *inveclosures; struct re_state_table_entry *state_table; re_dfastate_t *init_state; re_dfastate_t *init_state_word; re_dfastate_t *init_state_nl; re_dfastate_t *init_state_begbuf; bin_tree_t *str_tree; bin_tree_storage_t *str_tree_storage; re_bitset_ptr_t sb_char; int str_tree_storage_idx; /* number of subexpressions `re_nsub' is in regex_t. */ unsigned int state_hash_mask; int init_node; int nbackref; /* The number of backreference in this dfa. */ /* Bitmap expressing which backreference is used. */ bitset_word_t used_bkref_map; bitset_word_t completed_bkref_map; unsigned int has_plural_match : 1; /* If this dfa has "multibyte node", which is a backreference or a node which can accept multibyte character or multi character collating element. */ unsigned int has_mb_node : 1; unsigned int is_utf8 : 1; unsigned int map_notascii : 1; unsigned int word_ops_used : 1; int mb_cur_max; bitset_t word_char; reg_syntax_t syntax; int *subexp_map; #ifdef DEBUG char* re_str; #endif __libc_lock_define (, lock) }; #define re_node_set_init_empty(set) memset (set, '\0', sizeof (re_node_set)) #define re_node_set_remove(set,id) \ (re_node_set_remove_at (set, re_node_set_contains (set, id) - 1)) #define re_node_set_empty(p) ((p)->nelem = 0) #define re_node_set_free(set) re_free ((set)->elems) typedef enum { SB_CHAR, MB_CHAR, EQUIV_CLASS, COLL_SYM, CHAR_CLASS } bracket_elem_type; typedef struct { bracket_elem_type type; union { unsigned char ch; unsigned char *name; wchar_t wch; } opr; } bracket_elem_t; /* Inline functions for bitset operation. */ static inline void bitset_not (bitset_t set) { int bitset_i; for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i) set[bitset_i] = ~set[bitset_i]; } static inline void bitset_merge (bitset_t dest, const bitset_t src) { int bitset_i; for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i) dest[bitset_i] |= src[bitset_i]; } static inline void bitset_mask (bitset_t dest, const bitset_t src) { int bitset_i; for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i) dest[bitset_i] &= src[bitset_i]; } #ifdef RE_ENABLE_I18N /* Inline functions for re_string. */ static inline int internal_function __attribute ((pure)) re_string_char_size_at (const re_string_t *pstr, int idx) { int byte_idx; if (pstr->mb_cur_max == 1) return 1; for (byte_idx = 1; idx + byte_idx < pstr->valid_len; ++byte_idx) if (pstr->wcs[idx + byte_idx] != WEOF) break; return byte_idx; } static inline wint_t internal_function __attribute ((pure)) re_string_wchar_at (const re_string_t *pstr, int idx) { if (pstr->mb_cur_max == 1) return (wint_t) pstr->mbs[idx]; return (wint_t) pstr->wcs[idx]; } static int internal_function __attribute ((pure)) re_string_elem_size_at (const re_string_t *pstr, int idx) { # ifdef _LIBC const unsigned char *p, *extra; const int32_t *table, *indirect; int32_t tmp; # include <locale/weight.h> uint_fast32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); if (nrules != 0) { table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB); p = pstr->mbs + idx; tmp = findidx (&p); return p - pstr->mbs - idx; } else # endif /* _LIBC */ return 1; } #endif /* RE_ENABLE_I18N */ #endif /* _REGEX_INTERNAL_H */ /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* GKINCLUDE #include "regex_internal.c" */ /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* Extended regular expression matching and search library. Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Isamu Hasegawa <[email protected]>. 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. */ static void re_string_construct_common (const char *str, int len, re_string_t *pstr, RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa) internal_function; static re_dfastate_t *create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes, unsigned int hash) internal_function; static re_dfastate_t *create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes, unsigned int context, unsigned int hash) internal_function; /* Functions for string operation. */ /* This function allocate the buffers. It is necessary to call re_string_reconstruct before using the object. */ static reg_errcode_t internal_function re_string_allocate (re_string_t *pstr, const char *str, int len, int init_len, RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa) { reg_errcode_t ret; int init_buf_len; /* Ensure at least one character fits into the buffers. */ if (init_len < dfa->mb_cur_max) init_len = dfa->mb_cur_max; init_buf_len = (len + 1 < init_len) ? len + 1: init_len; re_string_construct_common (str, len, pstr, trans, icase, dfa); ret = re_string_realloc_buffers (pstr, init_buf_len); if (BE (ret != REG_NOERROR, 0)) return ret; pstr->word_char = dfa->word_char; pstr->word_ops_used = dfa->word_ops_used; pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str; pstr->valid_len = (pstr->mbs_allocated || dfa->mb_cur_max > 1) ? 0 : len; pstr->valid_raw_len = pstr->valid_len; return REG_NOERROR; } /* This function allocate the buffers, and initialize them. */ static reg_errcode_t internal_function re_string_construct (re_string_t *pstr, const char *str, int len, RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa) { reg_errcode_t ret; memset (pstr, '\0', sizeof (re_string_t)); re_string_construct_common (str, len, pstr, trans, icase, dfa); if (len > 0) { ret = re_string_realloc_buffers (pstr, len + 1); if (BE (ret != REG_NOERROR, 0)) return ret; } pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str; if (icase) { #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) { while (1) { ret = build_wcs_upper_buffer (pstr); if (BE (ret != REG_NOERROR, 0)) return ret; if (pstr->valid_raw_len >= len) break; if (pstr->bufs_len > pstr->valid_len + dfa->mb_cur_max) break; ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2); if (BE (ret != REG_NOERROR, 0)) return ret; } } else #endif /* RE_ENABLE_I18N */ build_upper_buffer (pstr); } else { #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) build_wcs_buffer (pstr); else #endif /* RE_ENABLE_I18N */ { if (trans != NULL) re_string_translate_buffer (pstr); else { pstr->valid_len = pstr->bufs_len; pstr->valid_raw_len = pstr->bufs_len; } } } return REG_NOERROR; } /* Helper functions for re_string_allocate, and re_string_construct. */ static reg_errcode_t internal_function re_string_realloc_buffers (re_string_t *pstr, int new_buf_len) { #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) { wint_t *new_wcs = re_realloc (pstr->wcs, wint_t, new_buf_len); if (BE (new_wcs == NULL, 0)) return REG_ESPACE; pstr->wcs = new_wcs; if (pstr->offsets != NULL) { int *new_offsets = re_realloc (pstr->offsets, int, new_buf_len); if (BE (new_offsets == NULL, 0)) return REG_ESPACE; pstr->offsets = new_offsets; } } #endif /* RE_ENABLE_I18N */ if (pstr->mbs_allocated) { unsigned char *new_mbs = re_realloc (pstr->mbs, unsigned char, new_buf_len); if (BE (new_mbs == NULL, 0)) return REG_ESPACE; pstr->mbs = new_mbs; } pstr->bufs_len = new_buf_len; return REG_NOERROR; } static void internal_function re_string_construct_common (const char *str, int len, re_string_t *pstr, RE_TRANSLATE_TYPE trans, int icase, const re_dfa_t *dfa) { pstr->raw_mbs = (const unsigned char *) str; pstr->len = len; pstr->raw_len = len; pstr->trans = trans; pstr->icase = icase ? 1 : 0; pstr->mbs_allocated = (trans != NULL || icase); pstr->mb_cur_max = dfa->mb_cur_max; pstr->is_utf8 = dfa->is_utf8; pstr->map_notascii = dfa->map_notascii; pstr->stop = pstr->len; pstr->raw_stop = pstr->stop; } #ifdef RE_ENABLE_I18N /* Build wide character buffer PSTR->WCS. If the byte sequence of the string are: <mb1>(0), <mb1>(1), <mb2>(0), <mb2>(1), <sb3> Then wide character buffer will be: <wc1> , WEOF , <wc2> , WEOF , <wc3> We use WEOF for padding, they indicate that the position isn't a first byte of a multibyte character. Note that this function assumes PSTR->VALID_LEN elements are already built and starts from PSTR->VALID_LEN. */ static void internal_function build_wcs_buffer (re_string_t *pstr) { #ifdef _LIBC unsigned char buf[MB_LEN_MAX]; assert (MB_LEN_MAX >= pstr->mb_cur_max); #else unsigned char buf[64]; #endif mbstate_t prev_st; int byte_idx, end_idx, remain_len; size_t mbclen; /* Build the buffers from pstr->valid_len to either pstr->len or pstr->bufs_len. */ end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; for (byte_idx = pstr->valid_len; byte_idx < end_idx;) { wchar_t wc; const char *p; remain_len = end_idx - byte_idx; prev_st = pstr->cur_state; /* Apply the translation if we need. */ if (BE (pstr->trans != NULL, 0)) { int i, ch; for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i) { ch = pstr->raw_mbs [pstr->raw_mbs_idx + byte_idx + i]; buf[i] = pstr->mbs[byte_idx + i] = pstr->trans[ch]; } p = (const char *) buf; } else p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx; mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state); if (BE (mbclen == (size_t) -2, 0)) { /* The buffer doesn't have enough space, finish to build. */ pstr->cur_state = prev_st; break; } else if (BE (mbclen == (size_t) -1 || mbclen == 0, 0)) { /* We treat these cases as a singlebyte character. */ mbclen = 1; wc = (wchar_t) pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]; if (BE (pstr->trans != NULL, 0)) wc = pstr->trans[wc]; pstr->cur_state = prev_st; } /* Write wide character and padding. */ pstr->wcs[byte_idx++] = wc; /* Write paddings. */ for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) pstr->wcs[byte_idx++] = WEOF; } pstr->valid_len = byte_idx; pstr->valid_raw_len = byte_idx; } /* Build wide character buffer PSTR->WCS like build_wcs_buffer, but for REG_ICASE. */ static reg_errcode_t internal_function build_wcs_upper_buffer (re_string_t *pstr) { mbstate_t prev_st; int src_idx, byte_idx, end_idx, remain_len; size_t mbclen; #ifdef _LIBC char buf[MB_LEN_MAX]; assert (MB_LEN_MAX >= pstr->mb_cur_max); #else char buf[64]; #endif byte_idx = pstr->valid_len; end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; /* The following optimization assumes that ASCII characters can be mapped to wide characters with a simple cast. */ if (! pstr->map_notascii && pstr->trans == NULL && !pstr->offsets_needed) { while (byte_idx < end_idx) { wchar_t wc; if (isascii (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]) && mbsinit (&pstr->cur_state)) { /* In case of a singlebyte character. */ pstr->mbs[byte_idx] = toupper (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]); /* The next step uses the assumption that wchar_t is encoded ASCII-safe: all ASCII values can be converted like this. */ pstr->wcs[byte_idx] = (wchar_t) pstr->mbs[byte_idx]; ++byte_idx; continue; } remain_len = end_idx - byte_idx; prev_st = pstr->cur_state; mbclen = mbrtowc (&wc, ((const char *) pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx), remain_len, &pstr->cur_state); if (BE (mbclen + 2 > 2, 1)) { wchar_t wcu = wc; if (iswlower (wc)) { size_t mbcdlen; wcu = towupper (wc); mbcdlen = wcrtomb (buf, wcu, &prev_st); if (BE (mbclen == mbcdlen, 1)) memcpy (pstr->mbs + byte_idx, buf, mbclen); else { src_idx = byte_idx; goto offsets_needed; } } else memcpy (pstr->mbs + byte_idx, pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx, mbclen); pstr->wcs[byte_idx++] = wcu; /* Write paddings. */ for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) pstr->wcs[byte_idx++] = WEOF; } else if (mbclen == (size_t) -1 || mbclen == 0) { /* It is an invalid character or '\0'. Just use the byte. */ int ch = pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]; pstr->mbs[byte_idx] = ch; /* And also cast it to wide char. */ pstr->wcs[byte_idx++] = (wchar_t) ch; if (BE (mbclen == (size_t) -1, 0)) pstr->cur_state = prev_st; } else { /* The buffer doesn't have enough space, finish to build. */ pstr->cur_state = prev_st; break; } } pstr->valid_len = byte_idx; pstr->valid_raw_len = byte_idx; return REG_NOERROR; } else for (src_idx = pstr->valid_raw_len; byte_idx < end_idx;) { wchar_t wc; const char *p; offsets_needed: remain_len = end_idx - byte_idx; prev_st = pstr->cur_state; if (BE (pstr->trans != NULL, 0)) { int i, ch; for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i) { ch = pstr->raw_mbs [pstr->raw_mbs_idx + src_idx + i]; buf[i] = pstr->trans[ch]; } p = (const char *) buf; } else p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + src_idx; mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state); if (BE (mbclen + 2 > 2, 1)) { wchar_t wcu = wc; if (iswlower (wc)) { size_t mbcdlen; wcu = towupper (wc); mbcdlen = wcrtomb ((char *) buf, wcu, &prev_st); if (BE (mbclen == mbcdlen, 1)) memcpy (pstr->mbs + byte_idx, buf, mbclen); else if (mbcdlen != (size_t) -1) { size_t i; if (byte_idx + mbcdlen > pstr->bufs_len) { pstr->cur_state = prev_st; break; } if (pstr->offsets == NULL) { pstr->offsets = re_malloc (int, pstr->bufs_len); if (pstr->offsets == NULL) return REG_ESPACE; } if (!pstr->offsets_needed) { for (i = 0; i < (size_t) byte_idx; ++i) pstr->offsets[i] = i; pstr->offsets_needed = 1; } memcpy (pstr->mbs + byte_idx, buf, mbcdlen); pstr->wcs[byte_idx] = wcu; pstr->offsets[byte_idx] = src_idx; for (i = 1; i < mbcdlen; ++i) { pstr->offsets[byte_idx + i] = src_idx + (i < mbclen ? i : mbclen - 1); pstr->wcs[byte_idx + i] = WEOF; } pstr->len += mbcdlen - mbclen; if (pstr->raw_stop > src_idx) pstr->stop += mbcdlen - mbclen; end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; byte_idx += mbcdlen; src_idx += mbclen; continue; } else memcpy (pstr->mbs + byte_idx, p, mbclen); } else memcpy (pstr->mbs + byte_idx, p, mbclen); if (BE (pstr->offsets_needed != 0, 0)) { size_t i; for (i = 0; i < mbclen; ++i) pstr->offsets[byte_idx + i] = src_idx + i; } src_idx += mbclen; pstr->wcs[byte_idx++] = wcu; /* Write paddings. */ for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) pstr->wcs[byte_idx++] = WEOF; } else if (mbclen == (size_t) -1 || mbclen == 0) { /* It is an invalid character or '\0'. Just use the byte. */ int ch = pstr->raw_mbs[pstr->raw_mbs_idx + src_idx]; if (BE (pstr->trans != NULL, 0)) ch = pstr->trans [ch]; pstr->mbs[byte_idx] = ch; if (BE (pstr->offsets_needed != 0, 0)) pstr->offsets[byte_idx] = src_idx; ++src_idx; /* And also cast it to wide char. */ pstr->wcs[byte_idx++] = (wchar_t) ch; if (BE (mbclen == (size_t) -1, 0)) pstr->cur_state = prev_st; } else { /* The buffer doesn't have enough space, finish to build. */ pstr->cur_state = prev_st; break; } } pstr->valid_len = byte_idx; pstr->valid_raw_len = src_idx; return REG_NOERROR; } /* Skip characters until the index becomes greater than NEW_RAW_IDX. Return the index. */ static int internal_function re_string_skip_chars (re_string_t *pstr, int new_raw_idx, wint_t *last_wc) { mbstate_t prev_st; int rawbuf_idx; size_t mbclen; wchar_t wc = WEOF; /* Skip the characters which are not necessary to check. */ for (rawbuf_idx = pstr->raw_mbs_idx + pstr->valid_raw_len; rawbuf_idx < new_raw_idx;) { int remain_len; remain_len = pstr->len - rawbuf_idx; prev_st = pstr->cur_state; mbclen = mbrtowc (&wc, (const char *) pstr->raw_mbs + rawbuf_idx, remain_len, &pstr->cur_state); if (BE (mbclen == (size_t) -2 || mbclen == (size_t) -1 || mbclen == 0, 0)) { /* We treat these cases as a single byte character. */ if (mbclen == 0 || remain_len == 0) wc = L'\0'; else wc = *(unsigned char *) (pstr->raw_mbs + rawbuf_idx); mbclen = 1; pstr->cur_state = prev_st; } /* Then proceed the next character. */ rawbuf_idx += mbclen; } *last_wc = (wint_t) wc; return rawbuf_idx; } #endif /* RE_ENABLE_I18N */ /* Build the buffer PSTR->MBS, and apply the translation if we need. This function is used in case of REG_ICASE. */ static void internal_function build_upper_buffer (re_string_t *pstr) { int char_idx, end_idx; end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; for (char_idx = pstr->valid_len; char_idx < end_idx; ++char_idx) { int ch = pstr->raw_mbs[pstr->raw_mbs_idx + char_idx]; if (BE (pstr->trans != NULL, 0)) ch = pstr->trans[ch]; if (islower (ch)) pstr->mbs[char_idx] = toupper (ch); else pstr->mbs[char_idx] = ch; } pstr->valid_len = char_idx; pstr->valid_raw_len = char_idx; } /* Apply TRANS to the buffer in PSTR. */ static void internal_function re_string_translate_buffer (re_string_t *pstr) { int buf_idx, end_idx; end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; for (buf_idx = pstr->valid_len; buf_idx < end_idx; ++buf_idx) { int ch = pstr->raw_mbs[pstr->raw_mbs_idx + buf_idx]; pstr->mbs[buf_idx] = pstr->trans[ch]; } pstr->valid_len = buf_idx; pstr->valid_raw_len = buf_idx; } /* This function re-construct the buffers. Concretely, convert to wide character in case of pstr->mb_cur_max > 1, convert to upper case in case of REG_ICASE, apply translation. */ static reg_errcode_t internal_function re_string_reconstruct (re_string_t *pstr, int idx, int eflags) { int offset = idx - pstr->raw_mbs_idx; if (BE (offset < 0, 0)) { /* Reset buffer. */ #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) memset (&pstr->cur_state, '\0', sizeof (mbstate_t)); #endif /* RE_ENABLE_I18N */ pstr->len = pstr->raw_len; pstr->stop = pstr->raw_stop; pstr->valid_len = 0; pstr->raw_mbs_idx = 0; pstr->valid_raw_len = 0; pstr->offsets_needed = 0; pstr->tip_context = ((eflags & REG_NOTBOL) ? CONTEXT_BEGBUF : CONTEXT_NEWLINE | CONTEXT_BEGBUF); if (!pstr->mbs_allocated) pstr->mbs = (unsigned char *) pstr->raw_mbs; offset = idx; } if (BE (offset != 0, 1)) { /* Should the already checked characters be kept? */ if (BE (offset < pstr->valid_raw_len, 1)) { /* Yes, move them to the front of the buffer. */ #ifdef RE_ENABLE_I18N if (BE (pstr->offsets_needed, 0)) { int low = 0, high = pstr->valid_len, mid; do { mid = (high + low) / 2; if (pstr->offsets[mid] > offset) high = mid; else if (pstr->offsets[mid] < offset) low = mid + 1; else break; } while (low < high); if (pstr->offsets[mid] < offset) ++mid; pstr->tip_context = re_string_context_at (pstr, mid - 1, eflags); /* This can be quite complicated, so handle specially only the common and easy case where the character with different length representation of lower and upper case is present at or after offset. */ if (pstr->valid_len > offset && mid == offset && pstr->offsets[mid] == offset) { memmove (pstr->wcs, pstr->wcs + offset, (pstr->valid_len - offset) * sizeof (wint_t)); memmove (pstr->mbs, pstr->mbs + offset, pstr->valid_len - offset); pstr->valid_len -= offset; pstr->valid_raw_len -= offset; for (low = 0; low < pstr->valid_len; low++) pstr->offsets[low] = pstr->offsets[low + offset] - offset; } else { /* Otherwise, just find out how long the partial multibyte character at offset is and fill it with WEOF/255. */ pstr->len = pstr->raw_len - idx + offset; pstr->stop = pstr->raw_stop - idx + offset; pstr->offsets_needed = 0; while (mid > 0 && pstr->offsets[mid - 1] == offset) --mid; while (mid < pstr->valid_len) if (pstr->wcs[mid] != WEOF) break; else ++mid; if (mid == pstr->valid_len) pstr->valid_len = 0; else { pstr->valid_len = pstr->offsets[mid] - offset; if (pstr->valid_len) { for (low = 0; low < pstr->valid_len; ++low) pstr->wcs[low] = WEOF; memset (pstr->mbs, 255, pstr->valid_len); } } pstr->valid_raw_len = pstr->valid_len; } } else #endif { pstr->tip_context = re_string_context_at (pstr, offset - 1, eflags); #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) memmove (pstr->wcs, pstr->wcs + offset, (pstr->valid_len - offset) * sizeof (wint_t)); #endif /* RE_ENABLE_I18N */ if (BE (pstr->mbs_allocated, 0)) memmove (pstr->mbs, pstr->mbs + offset, pstr->valid_len - offset); pstr->valid_len -= offset; pstr->valid_raw_len -= offset; #if DEBUG assert (pstr->valid_len > 0); #endif } } else { /* No, skip all characters until IDX. */ int prev_valid_len = pstr->valid_len; #ifdef RE_ENABLE_I18N if (BE (pstr->offsets_needed, 0)) { pstr->len = pstr->raw_len - idx + offset; pstr->stop = pstr->raw_stop - idx + offset; pstr->offsets_needed = 0; } #endif pstr->valid_len = 0; #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) { int wcs_idx; wint_t wc = WEOF; if (pstr->is_utf8) { const unsigned char *raw, *p, *q, *end; /* Special case UTF-8. Multi-byte chars start with any byte other than 0x80 - 0xbf. */ raw = pstr->raw_mbs + pstr->raw_mbs_idx; end = raw + (offset - pstr->mb_cur_max); if (end < pstr->raw_mbs) end = pstr->raw_mbs; p = raw + offset - 1; #ifdef _LIBC /* We know the wchar_t encoding is UCS4, so for the simple case, ASCII characters, skip the conversion step. */ if (isascii (*p) && BE (pstr->trans == NULL, 1)) { memset (&pstr->cur_state, '\0', sizeof (mbstate_t)); /* pstr->valid_len = 0; */ wc = (wchar_t) *p; } else #endif for (; p >= end; --p) if ((*p & 0xc0) != 0x80) { mbstate_t cur_state; wchar_t wc2; int mlen = raw + pstr->len - p; unsigned char buf[6]; size_t mbclen; q = p; if (BE (pstr->trans != NULL, 0)) { int i = mlen < 6 ? mlen : 6; while (--i >= 0) buf[i] = pstr->trans[p[i]]; q = buf; } /* XXX Don't use mbrtowc, we know which conversion to use (UTF-8 -> UCS4). */ memset (&cur_state, 0, sizeof (cur_state)); mbclen = mbrtowc (&wc2, (const char *) p, mlen, &cur_state); if (raw + offset - p <= mbclen && mbclen < (size_t) -2) { memset (&pstr->cur_state, '\0', sizeof (mbstate_t)); pstr->valid_len = mbclen - (raw + offset - p); wc = wc2; } break; } } if (wc == WEOF) pstr->valid_len = re_string_skip_chars (pstr, idx, &wc) - idx; if (wc == WEOF) pstr->tip_context = re_string_context_at (pstr, prev_valid_len - 1, eflags); else pstr->tip_context = ((BE (pstr->word_ops_used != 0, 0) && IS_WIDE_WORD_CHAR (wc)) ? CONTEXT_WORD : ((IS_WIDE_NEWLINE (wc) && pstr->newline_anchor) ? CONTEXT_NEWLINE : 0)); if (BE (pstr->valid_len, 0)) { for (wcs_idx = 0; wcs_idx < pstr->valid_len; ++wcs_idx) pstr->wcs[wcs_idx] = WEOF; if (pstr->mbs_allocated) memset (pstr->mbs, 255, pstr->valid_len); } pstr->valid_raw_len = pstr->valid_len; } else #endif /* RE_ENABLE_I18N */ { int c = pstr->raw_mbs[pstr->raw_mbs_idx + offset - 1]; pstr->valid_raw_len = 0; if (pstr->trans) c = pstr->trans[c]; pstr->tip_context = (bitset_contain (pstr->word_char, c) ? CONTEXT_WORD : ((IS_NEWLINE (c) && pstr->newline_anchor) ? CONTEXT_NEWLINE : 0)); } } if (!BE (pstr->mbs_allocated, 0)) pstr->mbs += offset; } pstr->raw_mbs_idx = idx; pstr->len -= offset; pstr->stop -= offset; /* Then build the buffers. */ #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) { if (pstr->icase) { reg_errcode_t ret = build_wcs_upper_buffer (pstr); if (BE (ret != REG_NOERROR, 0)) return ret; } else build_wcs_buffer (pstr); } else #endif /* RE_ENABLE_I18N */ if (BE (pstr->mbs_allocated, 0)) { if (pstr->icase) build_upper_buffer (pstr); else if (pstr->trans != NULL) re_string_translate_buffer (pstr); } else pstr->valid_len = pstr->len; pstr->cur_idx = 0; return REG_NOERROR; } static unsigned char internal_function __attribute ((pure)) re_string_peek_byte_case (const re_string_t *pstr, int idx) { int ch, off; /* Handle the common (easiest) cases first. */ if (BE (!pstr->mbs_allocated, 1)) return re_string_peek_byte (pstr, idx); #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1 && ! re_string_is_single_byte_char (pstr, pstr->cur_idx + idx)) return re_string_peek_byte (pstr, idx); #endif off = pstr->cur_idx + idx; #ifdef RE_ENABLE_I18N if (pstr->offsets_needed) off = pstr->offsets[off]; #endif ch = pstr->raw_mbs[pstr->raw_mbs_idx + off]; #ifdef RE_ENABLE_I18N /* Ensure that e.g. for tr_TR.UTF-8 BACKSLASH DOTLESS SMALL LETTER I this function returns CAPITAL LETTER I instead of first byte of DOTLESS SMALL LETTER I. The latter would confuse the parser, since peek_byte_case doesn't advance cur_idx in any way. */ if (pstr->offsets_needed && !isascii (ch)) return re_string_peek_byte (pstr, idx); #endif return ch; } static unsigned char internal_function __attribute ((pure)) re_string_fetch_byte_case (re_string_t *pstr) { if (BE (!pstr->mbs_allocated, 1)) return re_string_fetch_byte (pstr); #ifdef RE_ENABLE_I18N if (pstr->offsets_needed) { int off, ch; /* For tr_TR.UTF-8 [[:islower:]] there is [[: CAPITAL LETTER I WITH DOT lower:]] in mbs. Skip in that case the whole multi-byte character and return the original letter. On the other side, with [[: DOTLESS SMALL LETTER I return [[:I, as doing anything else would complicate things too much. */ if (!re_string_first_byte (pstr, pstr->cur_idx)) return re_string_fetch_byte (pstr); off = pstr->offsets[pstr->cur_idx]; ch = pstr->raw_mbs[pstr->raw_mbs_idx + off]; if (! isascii (ch)) return re_string_fetch_byte (pstr); re_string_skip_bytes (pstr, re_string_char_size_at (pstr, pstr->cur_idx)); return ch; } #endif return pstr->raw_mbs[pstr->raw_mbs_idx + pstr->cur_idx++]; } static void internal_function re_string_destruct (re_string_t *pstr) { #ifdef RE_ENABLE_I18N re_free (pstr->wcs); re_free (pstr->offsets); #endif /* RE_ENABLE_I18N */ if (pstr->mbs_allocated) re_free (pstr->mbs); } /* Return the context at IDX in INPUT. */ static unsigned int internal_function re_string_context_at (const re_string_t *input, int idx, int eflags) { int c; if (BE (idx < 0, 0)) /* In this case, we use the value stored in input->tip_context, since we can't know the character in input->mbs[-1] here. */ return input->tip_context; if (BE (idx == input->len, 0)) return ((eflags & REG_NOTEOL) ? CONTEXT_ENDBUF : CONTEXT_NEWLINE | CONTEXT_ENDBUF); #ifdef RE_ENABLE_I18N if (input->mb_cur_max > 1) { wint_t wc; int wc_idx = idx; while(input->wcs[wc_idx] == WEOF) { #ifdef DEBUG /* It must not happen. */ assert (wc_idx >= 0); #endif --wc_idx; if (wc_idx < 0) return input->tip_context; } wc = input->wcs[wc_idx]; if (BE (input->word_ops_used != 0, 0) && IS_WIDE_WORD_CHAR (wc)) return CONTEXT_WORD; return (IS_WIDE_NEWLINE (wc) && input->newline_anchor ? CONTEXT_NEWLINE : 0); } else #endif { c = re_string_byte_at (input, idx); if (bitset_contain (input->word_char, c)) return CONTEXT_WORD; return IS_NEWLINE (c) && input->newline_anchor ? CONTEXT_NEWLINE : 0; } } /* Functions for set operation. */ static reg_errcode_t internal_function re_node_set_alloc (re_node_set *set, int size) { set->alloc = size; set->nelem = 0; set->elems = re_malloc (int, size); if (BE (set->elems == NULL, 0)) return REG_ESPACE; return REG_NOERROR; } static reg_errcode_t internal_function re_node_set_init_1 (re_node_set *set, int elem) { set->alloc = 1; set->nelem = 1; set->elems = re_malloc (int, 1); if (BE (set->elems == NULL, 0)) { set->alloc = set->nelem = 0; return REG_ESPACE; } set->elems[0] = elem; return REG_NOERROR; } static reg_errcode_t internal_function re_node_set_init_2 (re_node_set *set, int elem1, int elem2) { set->alloc = 2; set->elems = re_malloc (int, 2); if (BE (set->elems == NULL, 0)) return REG_ESPACE; if (elem1 == elem2) { set->nelem = 1; set->elems[0] = elem1; } else { set->nelem = 2; if (elem1 < elem2) { set->elems[0] = elem1; set->elems[1] = elem2; } else { set->elems[0] = elem2; set->elems[1] = elem1; } } return REG_NOERROR; } static reg_errcode_t internal_function re_node_set_init_copy (re_node_set *dest, const re_node_set *src) { dest->nelem = src->nelem; if (src->nelem > 0) { dest->alloc = dest->nelem; dest->elems = re_malloc (int, dest->alloc); if (BE (dest->elems == NULL, 0)) { dest->alloc = dest->nelem = 0; return REG_ESPACE; } memcpy (dest->elems, src->elems, src->nelem * sizeof (int)); } else re_node_set_init_empty (dest); return REG_NOERROR; } /* Calculate the intersection of the sets SRC1 and SRC2. And merge it to DEST. Return value indicate the error code or REG_NOERROR if succeeded. Note: We assume dest->elems is NULL, when dest->alloc is 0. */ static reg_errcode_t internal_function re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1, const re_node_set *src2) { int i1, i2, is, id, delta, sbase; if (src1->nelem == 0 || src2->nelem == 0) return REG_NOERROR; /* We need dest->nelem + 2 * elems_in_intersection; this is a conservative estimate. */ if (src1->nelem + src2->nelem + dest->nelem > dest->alloc) { int new_alloc = src1->nelem + src2->nelem + dest->alloc; int *new_elems = re_realloc (dest->elems, int, new_alloc); if (BE (new_elems == NULL, 0)) return REG_ESPACE; dest->elems = new_elems; dest->alloc = new_alloc; } /* Find the items in the intersection of SRC1 and SRC2, and copy into the top of DEST those that are not already in DEST itself. */ sbase = dest->nelem + src1->nelem + src2->nelem; i1 = src1->nelem - 1; i2 = src2->nelem - 1; id = dest->nelem - 1; for (;;) { if (src1->elems[i1] == src2->elems[i2]) { /* Try to find the item in DEST. Maybe we could binary search? */ while (id >= 0 && dest->elems[id] > src1->elems[i1]) --id; if (id < 0 || dest->elems[id] != src1->elems[i1]) dest->elems[--sbase] = src1->elems[i1]; if (--i1 < 0 || --i2 < 0) break; } /* Lower the highest of the two items. */ else if (src1->elems[i1] < src2->elems[i2]) { if (--i2 < 0) break; } else { if (--i1 < 0) break; } } id = dest->nelem - 1; is = dest->nelem + src1->nelem + src2->nelem - 1; delta = is - sbase + 1; /* Now copy. When DELTA becomes zero, the remaining DEST elements are already in place; this is more or less the same loop that is in re_node_set_merge. */ dest->nelem += delta; if (delta > 0 && id >= 0) for (;;) { if (dest->elems[is] > dest->elems[id]) { /* Copy from the top. */ dest->elems[id + delta--] = dest->elems[is--]; if (delta == 0) break; } else { /* Slide from the bottom. */ dest->elems[id + delta] = dest->elems[id]; if (--id < 0) break; } } /* Copy remaining SRC elements. */ memcpy (dest->elems, dest->elems + sbase, delta * sizeof (int)); return REG_NOERROR; } /* Calculate the union set of the sets SRC1 and SRC2. And store it to DEST. Return value indicate the error code or REG_NOERROR if succeeded. */ static reg_errcode_t internal_function re_node_set_init_union (re_node_set *dest, const re_node_set *src1, const re_node_set *src2) { int i1, i2, id; if (src1 != NULL && src1->nelem > 0 && src2 != NULL && src2->nelem > 0) { dest->alloc = src1->nelem + src2->nelem; dest->elems = re_malloc (int, dest->alloc); if (BE (dest->elems == NULL, 0)) return REG_ESPACE; } else { if (src1 != NULL && src1->nelem > 0) return re_node_set_init_copy (dest, src1); else if (src2 != NULL && src2->nelem > 0) return re_node_set_init_copy (dest, src2); else re_node_set_init_empty (dest); return REG_NOERROR; } for (i1 = i2 = id = 0 ; i1 < src1->nelem && i2 < src2->nelem ;) { if (src1->elems[i1] > src2->elems[i2]) { dest->elems[id++] = src2->elems[i2++]; continue; } if (src1->elems[i1] == src2->elems[i2]) ++i2; dest->elems[id++] = src1->elems[i1++]; } if (i1 < src1->nelem) { memcpy (dest->elems + id, src1->elems + i1, (src1->nelem - i1) * sizeof (int)); id += src1->nelem - i1; } else if (i2 < src2->nelem) { memcpy (dest->elems + id, src2->elems + i2, (src2->nelem - i2) * sizeof (int)); id += src2->nelem - i2; } dest->nelem = id; return REG_NOERROR; } /* Calculate the union set of the sets DEST and SRC. And store it to DEST. Return value indicate the error code or REG_NOERROR if succeeded. */ static reg_errcode_t internal_function re_node_set_merge (re_node_set *dest, const re_node_set *src) { int is, id, sbase, delta; if (src == NULL || src->nelem == 0) return REG_NOERROR; if (dest->alloc < 2 * src->nelem + dest->nelem) { int new_alloc = 2 * (src->nelem + dest->alloc); int *new_buffer = re_realloc (dest->elems, int, new_alloc); if (BE (new_buffer == NULL, 0)) return REG_ESPACE; dest->elems = new_buffer; dest->alloc = new_alloc; } if (BE (dest->nelem == 0, 0)) { dest->nelem = src->nelem; memcpy (dest->elems, src->elems, src->nelem * sizeof (int)); return REG_NOERROR; } /* Copy into the top of DEST the items of SRC that are not found in DEST. Maybe we could binary search in DEST? */ for (sbase = dest->nelem + 2 * src->nelem, is = src->nelem - 1, id = dest->nelem - 1; is >= 0 && id >= 0; ) { if (dest->elems[id] == src->elems[is]) is--, id--; else if (dest->elems[id] < src->elems[is]) dest->elems[--sbase] = src->elems[is--]; else /* if (dest->elems[id] > src->elems[is]) */ --id; } if (is >= 0) { /* If DEST is exhausted, the remaining items of SRC must be unique. */ sbase -= is + 1; memcpy (dest->elems + sbase, src->elems, (is + 1) * sizeof (int)); } id = dest->nelem - 1; is = dest->nelem + 2 * src->nelem - 1; delta = is - sbase + 1; if (delta == 0) return REG_NOERROR; /* Now copy. When DELTA becomes zero, the remaining DEST elements are already in place. */ dest->nelem += delta; for (;;) { if (dest->elems[is] > dest->elems[id]) { /* Copy from the top. */ dest->elems[id + delta--] = dest->elems[is--]; if (delta == 0) break; } else { /* Slide from the bottom. */ dest->elems[id + delta] = dest->elems[id]; if (--id < 0) { /* Copy remaining SRC elements. */ memcpy (dest->elems, dest->elems + sbase, delta * sizeof (int)); break; } } } return REG_NOERROR; } /* Insert the new element ELEM to the re_node_set* SET. SET should not already have ELEM. return -1 if an error is occured, return 1 otherwise. */ static int internal_function re_node_set_insert (re_node_set *set, int elem) { int idx; /* In case the set is empty. */ if (set->alloc == 0) { if (BE (re_node_set_init_1 (set, elem) == REG_NOERROR, 1)) return 1; else return -1; } if (BE (set->nelem, 0) == 0) { /* We already guaranteed above that set->alloc != 0. */ set->elems[0] = elem; ++set->nelem; return 1; } /* Realloc if we need. */ if (set->alloc == set->nelem) { int *new_elems; set->alloc = set->alloc * 2; new_elems = re_realloc (set->elems, int, set->alloc); if (BE (new_elems == NULL, 0)) return -1; set->elems = new_elems; } /* Move the elements which follows the new element. Test the first element separately to skip a check in the inner loop. */ if (elem < set->elems[0]) { idx = 0; for (idx = set->nelem; idx > 0; idx--) set->elems[idx] = set->elems[idx - 1]; } else { for (idx = set->nelem; set->elems[idx - 1] > elem; idx--) set->elems[idx] = set->elems[idx - 1]; } /* Insert the new element. */ set->elems[idx] = elem; ++set->nelem; return 1; } /* Insert the new element ELEM to the re_node_set* SET. SET should not already have any element greater than or equal to ELEM. Return -1 if an error is occured, return 1 otherwise. */ static int internal_function re_node_set_insert_last (re_node_set *set, int elem) { /* Realloc if we need. */ if (set->alloc == set->nelem) { int *new_elems; set->alloc = (set->alloc + 1) * 2; new_elems = re_realloc (set->elems, int, set->alloc); if (BE (new_elems == NULL, 0)) return -1; set->elems = new_elems; } /* Insert the new element. */ set->elems[set->nelem++] = elem; return 1; } /* Compare two node sets SET1 and SET2. return 1 if SET1 and SET2 are equivalent, return 0 otherwise. */ static int internal_function __attribute ((pure)) re_node_set_compare (const re_node_set *set1, const re_node_set *set2) { int i; if (set1 == NULL || set2 == NULL || set1->nelem != set2->nelem) return 0; for (i = set1->nelem ; --i >= 0 ; ) if (set1->elems[i] != set2->elems[i]) return 0; return 1; } /* Return (idx + 1) if SET contains the element ELEM, return 0 otherwise. */ static int internal_function __attribute ((pure)) re_node_set_contains (const re_node_set *set, int elem) { unsigned int idx, right, mid; if (set->nelem <= 0) return 0; /* Binary search the element. */ idx = 0; right = set->nelem - 1; while (idx < right) { mid = (idx + right) / 2; if (set->elems[mid] < elem) idx = mid + 1; else right = mid; } return set->elems[idx] == elem ? idx + 1 : 0; } static void internal_function re_node_set_remove_at (re_node_set *set, int idx) { if (idx < 0 || idx >= set->nelem) return; --set->nelem; for (; idx < set->nelem; idx++) set->elems[idx] = set->elems[idx + 1]; } /* Add the token TOKEN to dfa->nodes, and return the index of the token. Or return -1, if an error will be occured. */ static int internal_function re_dfa_add_node (re_dfa_t *dfa, re_token_t token) { int type = token.type; if (BE (dfa->nodes_len >= dfa->nodes_alloc, 0)) { size_t new_nodes_alloc = dfa->nodes_alloc * 2; int *new_nexts, *new_indices; re_node_set *new_edests, *new_eclosures; re_token_t *new_nodes; /* Avoid overflows. */ if (BE (new_nodes_alloc < dfa->nodes_alloc, 0)) return -1; new_nodes = re_realloc (dfa->nodes, re_token_t, new_nodes_alloc); if (BE (new_nodes == NULL, 0)) return -1; dfa->nodes = new_nodes; new_nexts = re_realloc (dfa->nexts, int, new_nodes_alloc); new_indices = re_realloc (dfa->org_indices, int, new_nodes_alloc); new_edests = re_realloc (dfa->edests, re_node_set, new_nodes_alloc); new_eclosures = re_realloc (dfa->eclosures, re_node_set, new_nodes_alloc); if (BE (new_nexts == NULL || new_indices == NULL || new_edests == NULL || new_eclosures == NULL, 0)) return -1; dfa->nexts = new_nexts; dfa->org_indices = new_indices; dfa->edests = new_edests; dfa->eclosures = new_eclosures; dfa->nodes_alloc = new_nodes_alloc; } dfa->nodes[dfa->nodes_len] = token; dfa->nodes[dfa->nodes_len].constraint = 0; #ifdef RE_ENABLE_I18N dfa->nodes[dfa->nodes_len].accept_mb = (type == OP_PERIOD && dfa->mb_cur_max > 1) || type == COMPLEX_BRACKET; #endif dfa->nexts[dfa->nodes_len] = -1; re_node_set_init_empty (dfa->edests + dfa->nodes_len); re_node_set_init_empty (dfa->eclosures + dfa->nodes_len); return dfa->nodes_len++; } static inline unsigned int internal_function calc_state_hash (const re_node_set *nodes, unsigned int context) { unsigned int hash = nodes->nelem + context; int i; for (i = 0 ; i < nodes->nelem ; i++) hash += nodes->elems[i]; return hash; } /* Search for the state whose node_set is equivalent to NODES. Return the pointer to the state, if we found it in the DFA. Otherwise create the new one and return it. In case of an error return NULL and set the error code in ERR. Note: - We assume NULL as the invalid state, then it is possible that return value is NULL and ERR is REG_NOERROR. - We never return non-NULL value in case of any errors, it is for optimization. */ static re_dfastate_t * internal_function re_acquire_state (reg_errcode_t *err, const re_dfa_t *dfa, const re_node_set *nodes) { unsigned int hash; re_dfastate_t *new_state; struct re_state_table_entry *spot; int i; if (BE (nodes->nelem == 0, 0)) { *err = REG_NOERROR; return NULL; } hash = calc_state_hash (nodes, 0); spot = dfa->state_table + (hash & dfa->state_hash_mask); for (i = 0 ; i < spot->num ; i++) { re_dfastate_t *state = spot->array[i]; if (hash != state->hash) continue; if (re_node_set_compare (&state->nodes, nodes)) return state; } /* There are no appropriate state in the dfa, create the new one. */ new_state = create_ci_newstate (dfa, nodes, hash); if (BE (new_state == NULL, 0)) *err = REG_ESPACE; return new_state; } /* Search for the state whose node_set is equivalent to NODES and whose context is equivalent to CONTEXT. Return the pointer to the state, if we found it in the DFA. Otherwise create the new one and return it. In case of an error return NULL and set the error code in ERR. Note: - We assume NULL as the invalid state, then it is possible that return value is NULL and ERR is REG_NOERROR. - We never return non-NULL value in case of any errors, it is for optimization. */ static re_dfastate_t * internal_function re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa, const re_node_set *nodes, unsigned int context) { unsigned int hash; re_dfastate_t *new_state; struct re_state_table_entry *spot; int i; if (nodes->nelem == 0) { *err = REG_NOERROR; return NULL; } hash = calc_state_hash (nodes, context); spot = dfa->state_table + (hash & dfa->state_hash_mask); for (i = 0 ; i < spot->num ; i++) { re_dfastate_t *state = spot->array[i]; if (state->hash == hash && state->context == context && re_node_set_compare (state->entrance_nodes, nodes)) return state; } /* There are no appropriate state in `dfa', create the new one. */ new_state = create_cd_newstate (dfa, nodes, context, hash); if (BE (new_state == NULL, 0)) *err = REG_ESPACE; return new_state; } /* Finish initialization of the new state NEWSTATE, and using its hash value HASH put in the appropriate bucket of DFA's state table. Return value indicates the error code if failed. */ static reg_errcode_t register_state (const re_dfa_t *dfa, re_dfastate_t *newstate, unsigned int hash) { struct re_state_table_entry *spot; reg_errcode_t err; int i; newstate->hash = hash; err = re_node_set_alloc (&newstate->non_eps_nodes, newstate->nodes.nelem); if (BE (err != REG_NOERROR, 0)) return REG_ESPACE; for (i = 0; i < newstate->nodes.nelem; i++) { int elem = newstate->nodes.elems[i]; if (!IS_EPSILON_NODE (dfa->nodes[elem].type)) re_node_set_insert_last (&newstate->non_eps_nodes, elem); } spot = dfa->state_table + (hash & dfa->state_hash_mask); if (BE (spot->alloc <= spot->num, 0)) { int new_alloc = 2 * spot->num + 2; re_dfastate_t **new_array = re_realloc (spot->array, re_dfastate_t *, new_alloc); if (BE (new_array == NULL, 0)) return REG_ESPACE; spot->array = new_array; spot->alloc = new_alloc; } spot->array[spot->num++] = newstate; return REG_NOERROR; } static void free_state (re_dfastate_t *state) { re_node_set_free (&state->non_eps_nodes); re_node_set_free (&state->inveclosure); if (state->entrance_nodes != &state->nodes) { re_node_set_free (state->entrance_nodes); re_free (state->entrance_nodes); } re_node_set_free (&state->nodes); re_free (state->word_trtable); re_free (state->trtable); re_free (state); } /* Create the new state which is independ of contexts. Return the new state if succeeded, otherwise return NULL. */ static re_dfastate_t * internal_function create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes, unsigned int hash) { int i; reg_errcode_t err; re_dfastate_t *newstate; newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1); if (BE (newstate == NULL, 0)) return NULL; err = re_node_set_init_copy (&newstate->nodes, nodes); if (BE (err != REG_NOERROR, 0)) { re_free (newstate); return NULL; } newstate->entrance_nodes = &newstate->nodes; for (i = 0 ; i < nodes->nelem ; i++) { re_token_t *node = dfa->nodes + nodes->elems[i]; re_token_type_t type = node->type; if (type == CHARACTER && !node->constraint) continue; #ifdef RE_ENABLE_I18N newstate->accept_mb |= node->accept_mb; #endif /* RE_ENABLE_I18N */ /* If the state has the halt node, the state is a halt state. */ if (type == END_OF_RE) newstate->halt = 1; else if (type == OP_BACK_REF) newstate->has_backref = 1; else if (type == ANCHOR || node->constraint) newstate->has_constraint = 1; } err = register_state (dfa, newstate, hash); if (BE (err != REG_NOERROR, 0)) { free_state (newstate); newstate = NULL; } return newstate; } /* Create the new state which is depend on the context CONTEXT. Return the new state if succeeded, otherwise return NULL. */ static re_dfastate_t * internal_function create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes, unsigned int context, unsigned int hash) { int i, nctx_nodes = 0; reg_errcode_t err; re_dfastate_t *newstate; newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1); if (BE (newstate == NULL, 0)) return NULL; err = re_node_set_init_copy (&newstate->nodes, nodes); if (BE (err != REG_NOERROR, 0)) { re_free (newstate); return NULL; } newstate->context = context; newstate->entrance_nodes = &newstate->nodes; for (i = 0 ; i < nodes->nelem ; i++) { unsigned int constraint = 0; re_token_t *node = dfa->nodes + nodes->elems[i]; re_token_type_t type = node->type; if (node->constraint) constraint = node->constraint; if (type == CHARACTER && !constraint) continue; #ifdef RE_ENABLE_I18N newstate->accept_mb |= node->accept_mb; #endif /* RE_ENABLE_I18N */ /* If the state has the halt node, the state is a halt state. */ if (type == END_OF_RE) newstate->halt = 1; else if (type == OP_BACK_REF) newstate->has_backref = 1; else if (type == ANCHOR) constraint = node->opr.ctx_type; if (constraint) { if (newstate->entrance_nodes == &newstate->nodes) { newstate->entrance_nodes = re_malloc (re_node_set, 1); if (BE (newstate->entrance_nodes == NULL, 0)) { free_state (newstate); return NULL; } re_node_set_init_copy (newstate->entrance_nodes, nodes); nctx_nodes = 0; newstate->has_constraint = 1; } if (NOT_SATISFY_PREV_CONSTRAINT (constraint,context)) { re_node_set_remove_at (&newstate->nodes, i - nctx_nodes); ++nctx_nodes; } } } err = register_state (dfa, newstate, hash); if (BE (err != REG_NOERROR, 0)) { free_state (newstate); newstate = NULL; } return newstate; } /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* GKINCLUDE #include "regcomp.c" */ /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* Extended regular expression matching and search library. Copyright (C) 2002,2003,2004,2005,2006 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Isamu Hasegawa <[email protected]>. 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. */ static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern, size_t length, reg_syntax_t syntax); static void re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state, char *fastmap); static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len); #ifdef RE_ENABLE_I18N static void free_charset (re_charset_t *cset); #endif /* RE_ENABLE_I18N */ static void free_workarea_compile (regex_t *preg); static reg_errcode_t create_initial_state (re_dfa_t *dfa); #ifdef RE_ENABLE_I18N static void optimize_utf8 (re_dfa_t *dfa); #endif static reg_errcode_t analyze (regex_t *preg); static reg_errcode_t preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), void *extra); static reg_errcode_t postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), void *extra); static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node); static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node); static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node); static reg_errcode_t calc_first (void *extra, bin_tree_t *node); static reg_errcode_t calc_next (void *extra, bin_tree_t *node); static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node); static int duplicate_node (re_dfa_t *dfa, int org_idx, unsigned int constraint); static int search_duplicated_node (const re_dfa_t *dfa, int org_node, unsigned int constraint); static reg_errcode_t calc_eclosure (re_dfa_t *dfa); static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, int node, int root); static reg_errcode_t calc_inveclosure (re_dfa_t *dfa); static int fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax); static int peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax) internal_function; static bin_tree_t *parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax, reg_errcode_t *err); static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err); static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err); static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err); static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err); static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp, re_dfa_t *dfa, re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err); static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err); static reg_errcode_t parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp, re_token_t *token, int token_len, re_dfa_t *dfa, reg_syntax_t syntax, int accept_hyphen); static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp, re_token_t *token); #ifdef RE_ENABLE_I18N static reg_errcode_t build_equiv_class (bitset_t sbcset, re_charset_t *mbcset, int *equiv_class_alloc, const unsigned char *name); static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, re_charset_t *mbcset, int *char_class_alloc, const unsigned char *class_name, reg_syntax_t syntax); #else /* not RE_ENABLE_I18N */ static reg_errcode_t build_equiv_class (bitset_t sbcset, const unsigned char *name); static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, const unsigned char *class_name, reg_syntax_t syntax); #endif /* not RE_ENABLE_I18N */ static bin_tree_t *build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans, const unsigned char *class_name, const unsigned char *extra, int non_match, reg_errcode_t *err); static bin_tree_t *create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, re_token_type_t type); static bin_tree_t *create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, const re_token_t *token); static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa); static void free_token (re_token_t *node); static reg_errcode_t free_tree (void *extra, bin_tree_t *node); static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node); /* This table gives an error message for each of the error codes listed in regex.h. Obviously the order here has to be same as there. POSIX doesn't require that we do anything for REG_NOERROR, but why not be nice? */ const char __re_error_msgid[] attribute_hidden = { #define REG_NOERROR_IDX 0 gettext_noop ("Success") /* REG_NOERROR */ "\0" #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success") gettext_noop ("No match") /* REG_NOMATCH */ "\0" #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match") gettext_noop ("Invalid regular expression") /* REG_BADPAT */ "\0" #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression") gettext_noop ("Invalid collation character") /* REG_ECOLLATE */ "\0" #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character") gettext_noop ("Invalid character class name") /* REG_ECTYPE */ "\0" #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name") gettext_noop ("Trailing backslash") /* REG_EESCAPE */ "\0" #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash") gettext_noop ("Invalid back reference") /* REG_ESUBREG */ "\0" #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference") gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */ "\0" #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^") gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */ "\0" #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(") gettext_noop ("Unmatched \\{") /* REG_EBRACE */ "\0" #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{") gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */ "\0" #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}") gettext_noop ("Invalid range end") /* REG_ERANGE */ "\0" #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end") gettext_noop ("Memory exhausted") /* REG_ESPACE */ "\0" #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted") gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */ "\0" #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression") gettext_noop ("Premature end of regular expression") /* REG_EEND */ "\0" #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression") gettext_noop ("Regular expression too big") /* REG_ESIZE */ "\0" #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big") gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */ }; const size_t __re_error_msgid_idx[] attribute_hidden = { REG_NOERROR_IDX, REG_NOMATCH_IDX, REG_BADPAT_IDX, REG_ECOLLATE_IDX, REG_ECTYPE_IDX, REG_EESCAPE_IDX, REG_ESUBREG_IDX, REG_EBRACK_IDX, REG_EPAREN_IDX, REG_EBRACE_IDX, REG_BADBR_IDX, REG_ERANGE_IDX, REG_ESPACE_IDX, REG_BADRPT_IDX, REG_EEND_IDX, REG_ESIZE_IDX, REG_ERPAREN_IDX }; /* Entry points for GNU code. */ /* re_compile_pattern is the GNU regular expression compiler: it compiles PATTERN (of length LENGTH) and puts the result in BUFP. Returns 0 if the pattern was valid, otherwise an error string. Assumes the `allocated' (and perhaps `buffer') and `translate' fields are set in BUFP on entry. */ const char * re_compile_pattern (pattern, length, bufp) const char *pattern; size_t length; struct re_pattern_buffer *bufp; { reg_errcode_t ret; /* And GNU code determines whether or not to get register information by passing null for the REGS argument to re_match, etc., not by setting no_sub, unless RE_NO_SUB is set. */ bufp->no_sub = !!(re_syntax_options & RE_NO_SUB); /* Match anchors at newline. */ bufp->newline_anchor = 1; ret = re_compile_internal (bufp, pattern, length, re_syntax_options); if (!ret) return NULL; return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]); } #ifdef _LIBC weak_alias (__re_compile_pattern, re_compile_pattern) #endif /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can also be assigned to arbitrarily: each pattern buffer stores its own syntax, so it can be changed between regex compilations. */ /* This has no initializer because initialized variables in Emacs become read-only after dumping. */ reg_syntax_t re_syntax_options; /* Specify the precise syntax of regexps for compilation. This provides for compatibility for various utilities which historically have different, incompatible syntaxes. The argument SYNTAX is a bit mask comprised of the various bits defined in regex.h. We return the old syntax. */ reg_syntax_t re_set_syntax (syntax) reg_syntax_t syntax; { reg_syntax_t ret = re_syntax_options; re_syntax_options = syntax; return ret; } #ifdef _LIBC weak_alias (__re_set_syntax, re_set_syntax) #endif int re_compile_fastmap (bufp) struct re_pattern_buffer *bufp; { re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; char *fastmap = bufp->fastmap; memset (fastmap, '\0', sizeof (char) * SBC_MAX); re_compile_fastmap_iter (bufp, dfa->init_state, fastmap); if (dfa->init_state != dfa->init_state_word) re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap); if (dfa->init_state != dfa->init_state_nl) re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap); if (dfa->init_state != dfa->init_state_begbuf) re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap); bufp->fastmap_accurate = 1; return 0; } #ifdef _LIBC weak_alias (__re_compile_fastmap, re_compile_fastmap) #endif static inline void __attribute ((always_inline)) re_set_fastmap (char *fastmap, int icase, int ch) { fastmap[ch] = 1; if (icase) fastmap[tolower (ch)] = 1; } /* Helper function for re_compile_fastmap. Compile fastmap for the initial_state INIT_STATE. */ static void re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state, char *fastmap) { re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; int node_cnt; int icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE)); for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt) { int node = init_state->nodes.elems[node_cnt]; re_token_type_t type = dfa->nodes[node].type; if (type == CHARACTER) { re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c); #ifdef RE_ENABLE_I18N if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1) { unsigned char *buf = alloca (dfa->mb_cur_max), *p; wchar_t wc; mbstate_t state; p = buf; *p++ = dfa->nodes[node].opr.c; while (++node < dfa->nodes_len && dfa->nodes[node].type == CHARACTER && dfa->nodes[node].mb_partial) *p++ = dfa->nodes[node].opr.c; memset (&state, '\0', sizeof (state)); if (mbrtowc (&wc, (const char *) buf, p - buf, &state) == p - buf && (__wcrtomb ((char *) buf, towlower (wc), &state) != (size_t) -1)) re_set_fastmap (fastmap, 0, buf[0]); } #endif } else if (type == SIMPLE_BRACKET) { int i, ch; for (i = 0, ch = 0; i < BITSET_WORDS; ++i) { int j; bitset_word_t w = dfa->nodes[node].opr.sbcset[i]; for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) if (w & ((bitset_word_t) 1 << j)) re_set_fastmap (fastmap, icase, ch); } } #ifdef RE_ENABLE_I18N else if (type == COMPLEX_BRACKET) { int i; re_charset_t *cset = dfa->nodes[node].opr.mbcset; if (cset->non_match || cset->ncoll_syms || cset->nequiv_classes || cset->nranges || cset->nchar_classes) { # ifdef _LIBC if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0) { /* In this case we want to catch the bytes which are the first byte of any collation elements. e.g. In da_DK, we want to catch 'a' since "aa" is a valid collation element, and don't catch 'b' since 'b' is the only collation element which starts from 'b'. */ const int32_t *table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); for (i = 0; i < SBC_MAX; ++i) if (table[i] < 0) re_set_fastmap (fastmap, icase, i); } # else if (dfa->mb_cur_max > 1) for (i = 0; i < SBC_MAX; ++i) if (__btowc (i) == WEOF) re_set_fastmap (fastmap, icase, i); # endif /* not _LIBC */ } for (i = 0; i < cset->nmbchars; ++i) { char buf[256]; mbstate_t state; memset (&state, '\0', sizeof (state)); if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1) re_set_fastmap (fastmap, icase, *(unsigned char *) buf); if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1) { if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state) != (size_t) -1) re_set_fastmap (fastmap, 0, *(unsigned char *) buf); } } } #endif /* RE_ENABLE_I18N */ else if (type == OP_PERIOD #ifdef RE_ENABLE_I18N || type == OP_UTF8_PERIOD #endif /* RE_ENABLE_I18N */ || type == END_OF_RE) { memset (fastmap, '\1', sizeof (char) * SBC_MAX); if (type == END_OF_RE) bufp->can_be_null = 1; return; } } } /* Entry point for POSIX code. */ /* regcomp takes a regular expression as a string and compiles it. PREG is a regex_t *. We do not expect any fields to be initialized, since POSIX says we shouldn't. Thus, we set `buffer' to the compiled pattern; `used' to the length of the compiled pattern; `syntax' to RE_SYNTAX_POSIX_EXTENDED if the REG_EXTENDED bit in CFLAGS is set; otherwise, to RE_SYNTAX_POSIX_BASIC; `newline_anchor' to REG_NEWLINE being set in CFLAGS; `fastmap' to an allocated space for the fastmap; `fastmap_accurate' to zero; `re_nsub' to the number of subexpressions in PATTERN. PATTERN is the address of the pattern string. CFLAGS is a series of bits which affect compilation. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we use POSIX basic syntax. If REG_NEWLINE is set, then . and [^...] don't match newline. Also, regexec will try a match beginning after every newline. If REG_ICASE is set, then we considers upper- and lowercase versions of letters to be equivalent when matching. If REG_NOSUB is set, then when PREG is passed to regexec, that routine will report only success or failure, and nothing about the registers. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for the return codes and their meanings.) */ int regcomp (preg, pattern, cflags) regex_t *__restrict preg; const char *__restrict pattern; int cflags; { reg_errcode_t ret; reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC); preg->buffer = NULL; preg->allocated = 0; preg->used = 0; /* Try to allocate space for the fastmap. */ preg->fastmap = re_malloc (char, SBC_MAX); if (BE (preg->fastmap == NULL, 0)) return REG_ESPACE; syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0; /* If REG_NEWLINE is set, newlines are treated differently. */ if (cflags & REG_NEWLINE) { /* REG_NEWLINE implies neither . nor [^...] match newline. */ syntax &= ~RE_DOT_NEWLINE; syntax |= RE_HAT_LISTS_NOT_NEWLINE; /* It also changes the matching behavior. */ preg->newline_anchor = 1; } else preg->newline_anchor = 0; preg->no_sub = !!(cflags & REG_NOSUB); preg->translate = NULL; ret = re_compile_internal (preg, pattern, strlen (pattern), syntax); /* POSIX doesn't distinguish between an unmatched open-group and an unmatched close-group: both are REG_EPAREN. */ if (ret == REG_ERPAREN) ret = REG_EPAREN; /* We have already checked preg->fastmap != NULL. */ if (BE (ret == REG_NOERROR, 1)) /* Compute the fastmap now, since regexec cannot modify the pattern buffer. This function never fails in this implementation. */ (void) re_compile_fastmap (preg); else { /* Some error occurred while compiling the expression. */ re_free (preg->fastmap); preg->fastmap = NULL; } return (int) ret; } #ifdef _LIBC weak_alias (__regcomp, regcomp) #endif /* Returns a message corresponding to an error code, ERRCODE, returned from either regcomp or regexec. We don't use PREG here. */ /* regerror ( int errcode, preg, errbuf, errbuf_size) */ size_t regerror ( int errcode, const regex_t *__restrict preg, char *__restrict errbuf, size_t errbuf_size) { const char *msg; size_t msg_size; if (BE (errcode < 0 || errcode >= (int) (sizeof (__re_error_msgid_idx) / sizeof (__re_error_msgid_idx[0])), 0)) /* Only error codes returned by the rest of the code should be passed to this routine. If we are given anything else, or if other regex code generates an invalid error code, then the program has a bug. Dump core so we can fix it. */ abort (); msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]); msg_size = strlen (msg) + 1; /* Includes the null. */ if (BE (errbuf_size != 0, 1)) { if (BE (msg_size > errbuf_size, 0)) { #if defined HAVE_MEMPCPY || defined _LIBC *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0'; #else memcpy (errbuf, msg, errbuf_size - 1); errbuf[errbuf_size - 1] = 0; #endif } else memcpy (errbuf, msg, msg_size); } return msg_size; } #ifdef _LIBC weak_alias (__regerror, regerror) #endif #ifdef RE_ENABLE_I18N /* This static array is used for the map to single-byte characters when UTF-8 is used. Otherwise we would allocate memory just to initialize it the same all the time. UTF-8 is the preferred encoding so this is a worthwhile optimization. */ static const bitset_t utf8_sb_map = { /* Set the first 128 bits. */ [0 ... 0x80 / BITSET_WORD_BITS - 1] = BITSET_WORD_MAX }; #endif static void free_dfa_content (re_dfa_t *dfa) { int i, j; if (dfa->nodes) for (i = 0; i < dfa->nodes_len; ++i) free_token (dfa->nodes + i); re_free (dfa->nexts); for (i = 0; i < dfa->nodes_len; ++i) { if (dfa->eclosures != NULL) re_node_set_free (dfa->eclosures + i); if (dfa->inveclosures != NULL) re_node_set_free (dfa->inveclosures + i); if (dfa->edests != NULL) re_node_set_free (dfa->edests + i); } re_free (dfa->edests); re_free (dfa->eclosures); re_free (dfa->inveclosures); re_free (dfa->nodes); if (dfa->state_table) for (i = 0; i <= dfa->state_hash_mask; ++i) { struct re_state_table_entry *entry = dfa->state_table + i; for (j = 0; j < entry->num; ++j) { re_dfastate_t *state = entry->array[j]; free_state (state); } re_free (entry->array); } re_free (dfa->state_table); #ifdef RE_ENABLE_I18N if (dfa->sb_char != utf8_sb_map) re_free (dfa->sb_char); #endif re_free (dfa->subexp_map); #ifdef DEBUG re_free (dfa->re_str); #endif re_free (dfa); } /* Free dynamically allocated space used by PREG. */ void regfree (preg) regex_t *preg; { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; if (BE (dfa != NULL, 1)) free_dfa_content (dfa); preg->buffer = NULL; preg->allocated = 0; re_free (preg->fastmap); preg->fastmap = NULL; re_free (preg->translate); preg->translate = NULL; } #ifdef _LIBC weak_alias (__regfree, regfree) #endif /* Entry points compatible with 4.2 BSD regex library. We don't define them unless specifically requested. */ #if defined _REGEX_RE_COMP || defined _LIBC /* BSD has one and only one pattern buffer. */ static struct re_pattern_buffer re_comp_buf; char * # ifdef _LIBC /* Make these definitions weak in libc, so POSIX programs can redefine these names if they don't use our functions, and still use regcomp/regexec above without link errors. */ weak_function # endif re_comp (s) const char *s; { reg_errcode_t ret; char *fastmap; if (!s) { if (!re_comp_buf.buffer) return gettext ("No previous regular expression"); return 0; } if (re_comp_buf.buffer) { fastmap = re_comp_buf.fastmap; re_comp_buf.fastmap = NULL; __regfree (&re_comp_buf); memset (&re_comp_buf, '\0', sizeof (re_comp_buf)); re_comp_buf.fastmap = fastmap; } if (re_comp_buf.fastmap == NULL) { re_comp_buf.fastmap = (char *) malloc (SBC_MAX); if (re_comp_buf.fastmap == NULL) return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) REG_ESPACE]); } /* Since `re_exec' always passes NULL for the `regs' argument, we don't need to initialize the pattern buffer fields which affect it. */ /* Match anchors at newlines. */ re_comp_buf.newline_anchor = 1; ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options); if (!ret) return NULL; /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */ return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]); } #ifdef _LIBC libc_freeres_fn (free_mem) { __regfree (&re_comp_buf); } #endif #endif /* _REGEX_RE_COMP */ /* Internal entry point. Compile the regular expression PATTERN, whose length is LENGTH. SYNTAX indicate regular expression's syntax. */ static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern, size_t length, reg_syntax_t syntax) { reg_errcode_t err = REG_NOERROR; re_dfa_t *dfa; re_string_t regexp; /* Initialize the pattern buffer. */ preg->fastmap_accurate = 0; preg->syntax = syntax; preg->not_bol = preg->not_eol = 0; preg->used = 0; preg->re_nsub = 0; preg->can_be_null = 0; preg->regs_allocated = REGS_UNALLOCATED; /* Initialize the dfa. */ dfa = (re_dfa_t *) preg->buffer; if (BE (preg->allocated < sizeof (re_dfa_t), 0)) { /* If zero allocated, but buffer is non-null, try to realloc enough space. This loses if buffer's address is bogus, but that is the user's responsibility. If ->buffer is NULL this is a simple allocation. */ dfa = re_realloc (preg->buffer, re_dfa_t, 1); if (dfa == NULL) return REG_ESPACE; preg->allocated = sizeof (re_dfa_t); preg->buffer = (unsigned char *) dfa; } preg->used = sizeof (re_dfa_t); err = init_dfa (dfa, length); if (BE (err != REG_NOERROR, 0)) { free_dfa_content (dfa); preg->buffer = NULL; preg->allocated = 0; return err; } #ifdef DEBUG /* Note: length+1 will not overflow since it is checked in init_dfa. */ dfa->re_str = re_malloc (char, length + 1); strncpy (dfa->re_str, pattern, length + 1); #endif __libc_lock_init (dfa->lock); err = re_string_construct (&regexp, pattern, length, preg->translate, syntax & RE_ICASE, dfa); if (BE (err != REG_NOERROR, 0)) { re_compile_internal_free_return: free_workarea_compile (preg); re_string_destruct (&regexp); free_dfa_content (dfa); preg->buffer = NULL; preg->allocated = 0; return err; } /* Parse the regular expression, and build a structure tree. */ preg->re_nsub = 0; dfa->str_tree = parse (&regexp, preg, syntax, &err); if (BE (dfa->str_tree == NULL, 0)) goto re_compile_internal_free_return; /* Analyze the tree and create the nfa. */ err = analyze (preg); if (BE (err != REG_NOERROR, 0)) goto re_compile_internal_free_return; #ifdef RE_ENABLE_I18N /* If possible, do searching in single byte encoding to speed things up. */ if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL) optimize_utf8 (dfa); #endif /* Then create the initial state of the dfa. */ err = create_initial_state (dfa); /* Release work areas. */ free_workarea_compile (preg); re_string_destruct (&regexp); if (BE (err != REG_NOERROR, 0)) { free_dfa_content (dfa); preg->buffer = NULL; preg->allocated = 0; } return err; } /* Initialize DFA. We use the length of the regular expression PAT_LEN as the initial length of some arrays. */ static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len) { unsigned int table_size; #ifndef _LIBC char *codeset_name; #endif memset (dfa, '\0', sizeof (re_dfa_t)); /* Force allocation of str_tree_storage the first time. */ dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE; /* Avoid overflows. */ if (pat_len == SIZE_MAX) return REG_ESPACE; dfa->nodes_alloc = pat_len + 1; dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc); /* table_size = 2 ^ ceil(log pat_len) */ for (table_size = 1; ; table_size <<= 1) if (table_size > pat_len) break; dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size); dfa->state_hash_mask = table_size - 1; dfa->mb_cur_max = MB_CUR_MAX; #ifdef _LIBC if (dfa->mb_cur_max == 6 && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0) dfa->is_utf8 = 1; dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII) != 0); #else # ifdef HAVE_LANGINFO_CODESET codeset_name = nl_langinfo (CODESET); # else codeset_name = getenv ("LC_ALL"); if (codeset_name == NULL || codeset_name[0] == '\0') codeset_name = getenv ("LC_CTYPE"); if (codeset_name == NULL || codeset_name[0] == '\0') codeset_name = getenv ("LANG"); if (codeset_name == NULL) codeset_name = ""; else if (strchr (codeset_name, '.') != NULL) codeset_name = strchr (codeset_name, '.') + 1; # endif if (strcasecmp (codeset_name, "UTF-8") == 0 || strcasecmp (codeset_name, "UTF8") == 0) dfa->is_utf8 = 1; /* We check exhaustively in the loop below if this charset is a superset of ASCII. */ dfa->map_notascii = 0; #endif #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) { if (dfa->is_utf8) dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map; else { int i, j, ch; dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); if (BE (dfa->sb_char == NULL, 0)) return REG_ESPACE; /* Set the bits corresponding to single byte chars. */ for (i = 0, ch = 0; i < BITSET_WORDS; ++i) for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) { wint_t wch = __btowc (ch); if (wch != WEOF) dfa->sb_char[i] |= (bitset_word_t) 1 << j; # ifndef _LIBC if (isascii (ch) && wch != ch) dfa->map_notascii = 1; # endif } } } #endif if (BE (dfa->nodes == NULL || dfa->state_table == NULL, 0)) return REG_ESPACE; return REG_NOERROR; } /* Initialize WORD_CHAR table, which indicate which character is "word". In this case "word" means that it is the word construction character used by some operators like "\<", "\>", etc. */ static void internal_function init_word_char (re_dfa_t *dfa) { int i, j, ch; dfa->word_ops_used = 1; for (i = 0, ch = 0; i < BITSET_WORDS; ++i) for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) if (isalnum (ch) || ch == '_') dfa->word_char[i] |= (bitset_word_t) 1 << j; } /* Free the work area which are only used while compiling. */ static void free_workarea_compile (regex_t *preg) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_storage_t *storage, *next; for (storage = dfa->str_tree_storage; storage; storage = next) { next = storage->next; re_free (storage); } dfa->str_tree_storage = NULL; dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE; dfa->str_tree = NULL; re_free (dfa->org_indices); dfa->org_indices = NULL; } /* Create initial states for all contexts. */ static reg_errcode_t create_initial_state (re_dfa_t *dfa) { int first, i; reg_errcode_t err; re_node_set init_nodes; /* Initial states have the epsilon closure of the node which is the first node of the regular expression. */ first = dfa->str_tree->first->node_idx; dfa->init_node = first; err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first); if (BE (err != REG_NOERROR, 0)) return err; /* The back-references which are in initial states can epsilon transit, since in this case all of the subexpressions can be null. Then we add epsilon closures of the nodes which are the next nodes of the back-references. */ if (dfa->nbackref > 0) for (i = 0; i < init_nodes.nelem; ++i) { int node_idx = init_nodes.elems[i]; re_token_type_t type = dfa->nodes[node_idx].type; int clexp_idx; if (type != OP_BACK_REF) continue; for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx) { re_token_t *clexp_node; clexp_node = dfa->nodes + init_nodes.elems[clexp_idx]; if (clexp_node->type == OP_CLOSE_SUBEXP && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx) break; } if (clexp_idx == init_nodes.nelem) continue; if (type == OP_BACK_REF) { int dest_idx = dfa->edests[node_idx].elems[0]; if (!re_node_set_contains (&init_nodes, dest_idx)) { re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx); i = 0; } } } /* It must be the first time to invoke acquire_state. */ dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0); /* We don't check ERR here, since the initial state must not be NULL. */ if (BE (dfa->init_state == NULL, 0)) return err; if (dfa->init_state->has_constraint) { dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes, CONTEXT_WORD); dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes, CONTEXT_NEWLINE); dfa->init_state_begbuf = re_acquire_state_context (&err, dfa, &init_nodes, CONTEXT_NEWLINE | CONTEXT_BEGBUF); if (BE (dfa->init_state_word == NULL || dfa->init_state_nl == NULL || dfa->init_state_begbuf == NULL, 0)) return err; } else dfa->init_state_word = dfa->init_state_nl = dfa->init_state_begbuf = dfa->init_state; re_node_set_free (&init_nodes); return REG_NOERROR; } #ifdef RE_ENABLE_I18N /* If it is possible to do searching in single byte encoding instead of UTF-8 to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change DFA nodes where needed. */ static void optimize_utf8 (re_dfa_t *dfa) { int node, i, mb_chars = 0, has_period = 0; for (node = 0; node < dfa->nodes_len; ++node) switch (dfa->nodes[node].type) { case CHARACTER: if (dfa->nodes[node].opr.c >= 0x80) mb_chars = 1; break; case ANCHOR: switch (dfa->nodes[node].opr.idx) { case LINE_FIRST: case LINE_LAST: case BUF_FIRST: case BUF_LAST: break; default: /* Word anchors etc. cannot be handled. */ return; } break; case OP_PERIOD: has_period = 1; break; case OP_BACK_REF: case OP_ALT: case END_OF_RE: case OP_DUP_ASTERISK: case OP_OPEN_SUBEXP: case OP_CLOSE_SUBEXP: break; case COMPLEX_BRACKET: return; case SIMPLE_BRACKET: /* Just double check. The non-ASCII range starts at 0x80. */ assert (0x80 % BITSET_WORD_BITS == 0); for (i = 0x80 / BITSET_WORD_BITS; i < BITSET_WORDS; ++i) if (dfa->nodes[node].opr.sbcset[i]) return; break; default: abort (); } if (mb_chars || has_period) for (node = 0; node < dfa->nodes_len; ++node) { if (dfa->nodes[node].type == CHARACTER && dfa->nodes[node].opr.c >= 0x80) dfa->nodes[node].mb_partial = 0; else if (dfa->nodes[node].type == OP_PERIOD) dfa->nodes[node].type = OP_UTF8_PERIOD; } /* The search can be in single byte locale. */ dfa->mb_cur_max = 1; dfa->is_utf8 = 0; dfa->has_mb_node = dfa->nbackref > 0 || has_period; } #endif /* Analyze the structure tree, and calculate "first", "next", "edest", "eclosure", and "inveclosure". */ static reg_errcode_t analyze (regex_t *preg) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; reg_errcode_t ret; /* Allocate arrays. */ dfa->nexts = re_malloc (int, dfa->nodes_alloc); dfa->org_indices = re_malloc (int, dfa->nodes_alloc); dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc); dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc); if (BE (dfa->nexts == NULL || dfa->org_indices == NULL || dfa->edests == NULL || dfa->eclosures == NULL, 0)) return REG_ESPACE; dfa->subexp_map = re_malloc (int, preg->re_nsub); if (dfa->subexp_map != NULL) { int i; for (i = 0; i < preg->re_nsub; i++) dfa->subexp_map[i] = i; preorder (dfa->str_tree, optimize_subexps, dfa); for (i = 0; i < preg->re_nsub; i++) if (dfa->subexp_map[i] != i) break; if (i == preg->re_nsub) { free (dfa->subexp_map); dfa->subexp_map = NULL; } } ret = postorder (dfa->str_tree, lower_subexps, preg); if (BE (ret != REG_NOERROR, 0)) return ret; ret = postorder (dfa->str_tree, calc_first, dfa); if (BE (ret != REG_NOERROR, 0)) return ret; preorder (dfa->str_tree, calc_next, dfa); ret = preorder (dfa->str_tree, link_nfa_nodes, dfa); if (BE (ret != REG_NOERROR, 0)) return ret; ret = calc_eclosure (dfa); if (BE (ret != REG_NOERROR, 0)) return ret; /* We only need this during the prune_impossible_nodes pass in regexec.c; skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */ if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match) || dfa->nbackref) { dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len); if (BE (dfa->inveclosures == NULL, 0)) return REG_ESPACE; ret = calc_inveclosure (dfa); } return ret; } /* Our parse trees are very unbalanced, so we cannot use a stack to implement parse tree visits. Instead, we use parent pointers and some hairy code in these two functions. */ static reg_errcode_t postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), void *extra) { bin_tree_t *node, *prev; for (node = root; ; ) { /* Descend down the tree, preferably to the left (or to the right if that's the only child). */ while (node->left || node->right) if (node->left) node = node->left; else node = node->right; do { reg_errcode_t err = fn (extra, node); if (BE (err != REG_NOERROR, 0)) return err; if (node->parent == NULL) return REG_NOERROR; prev = node; node = node->parent; } /* Go up while we have a node that is reached from the right. */ while (node->right == prev || node->right == NULL); node = node->right; } } static reg_errcode_t preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), void *extra) { bin_tree_t *node; for (node = root; ; ) { reg_errcode_t err = fn (extra, node); if (BE (err != REG_NOERROR, 0)) return err; /* Go to the left node, or up and to the right. */ if (node->left) node = node->left; else { bin_tree_t *prev = NULL; while (node->right == prev || node->right == NULL) { prev = node; node = node->parent; if (!node) return REG_NOERROR; } node = node->right; } } } /* Optimization pass: if a SUBEXP is entirely contained, strip it and tell re_search_internal to map the inner one's opr.idx to this one's. Adjust backreferences as well. Requires a preorder visit. */ static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node) { re_dfa_t *dfa = (re_dfa_t *) extra; if (node->token.type == OP_BACK_REF && dfa->subexp_map) { int idx = node->token.opr.idx; node->token.opr.idx = dfa->subexp_map[idx]; dfa->used_bkref_map |= 1 << node->token.opr.idx; } else if (node->token.type == SUBEXP && node->left && node->left->token.type == SUBEXP) { int other_idx = node->left->token.opr.idx; node->left = node->left->left; if (node->left) node->left->parent = node; dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx]; if (other_idx < BITSET_WORD_BITS) dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx); } return REG_NOERROR; } /* Lowering pass: Turn each SUBEXP node into the appropriate concatenation of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */ static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node) { regex_t *preg = (regex_t *) extra; reg_errcode_t err = REG_NOERROR; if (node->left && node->left->token.type == SUBEXP) { node->left = lower_subexp (&err, preg, node->left); if (node->left) node->left->parent = node; } if (node->right && node->right->token.type == SUBEXP) { node->right = lower_subexp (&err, preg, node->right); if (node->right) node->right->parent = node; } return err; } static bin_tree_t * lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_t *body = node->left; bin_tree_t *op, *cls, *tree1, *tree; if (preg->no_sub /* We do not optimize empty subexpressions, because otherwise we may have bad CONCAT nodes with NULL children. This is obviously not very common, so we do not lose much. An example that triggers this case is the sed "script" /\(\)/x. */ && node->left != NULL && (node->token.opr.idx >= BITSET_WORD_BITS || !(dfa->used_bkref_map & ((bitset_word_t) 1 << node->token.opr.idx)))) return node->left; /* Convert the SUBEXP node to the concatenation of an OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */ op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP); cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP); tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls; tree = create_tree (dfa, op, tree1, CONCAT); if (BE (tree == NULL || tree1 == NULL || op == NULL || cls == NULL, 0)) { *err = REG_ESPACE; return NULL; } op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx; op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp; return tree; } /* Pass 1 in building the NFA: compute FIRST and create unlinked automaton nodes. Requires a postorder visit. */ static reg_errcode_t calc_first (void *extra, bin_tree_t *node) { re_dfa_t *dfa = (re_dfa_t *) extra; if (node->token.type == CONCAT) { node->first = node->left->first; node->node_idx = node->left->node_idx; } else { node->first = node; node->node_idx = re_dfa_add_node (dfa, node->token); if (BE (node->node_idx == -1, 0)) return REG_ESPACE; } return REG_NOERROR; } /* Pass 2: compute NEXT on the tree. Preorder visit. */ static reg_errcode_t calc_next (void *extra, bin_tree_t *node) { switch (node->token.type) { case OP_DUP_ASTERISK: node->left->next = node; break; case CONCAT: node->left->next = node->right->first; node->right->next = node->next; break; default: if (node->left) node->left->next = node->next; if (node->right) node->right->next = node->next; break; } return REG_NOERROR; } /* Pass 3: link all DFA nodes to their NEXT node (any order will do). */ static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node) { re_dfa_t *dfa = (re_dfa_t *) extra; int idx = node->node_idx; reg_errcode_t err = REG_NOERROR; switch (node->token.type) { case CONCAT: break; case END_OF_RE: assert (node->next == NULL); break; case OP_DUP_ASTERISK: case OP_ALT: { int left, right; dfa->has_plural_match = 1; if (node->left != NULL) left = node->left->first->node_idx; else left = node->next->node_idx; if (node->right != NULL) right = node->right->first->node_idx; else right = node->next->node_idx; assert (left > -1); assert (right > -1); err = re_node_set_init_2 (dfa->edests + idx, left, right); } break; case ANCHOR: case OP_OPEN_SUBEXP: case OP_CLOSE_SUBEXP: err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx); break; case OP_BACK_REF: dfa->nexts[idx] = node->next->node_idx; if (node->token.type == OP_BACK_REF) re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]); break; default: assert (!IS_EPSILON_NODE (node->token.type)); dfa->nexts[idx] = node->next->node_idx; break; } return err; } /* Duplicate the epsilon closure of the node ROOT_NODE. Note that duplicated nodes have constraint INIT_CONSTRAINT in addition to their own constraint. */ static reg_errcode_t internal_function duplicate_node_closure (re_dfa_t *dfa, int top_org_node, int top_clone_node, int root_node, unsigned int init_constraint) { int org_node, clone_node, ret; unsigned int constraint = init_constraint; for (org_node = top_org_node, clone_node = top_clone_node;;) { int org_dest, clone_dest; if (dfa->nodes[org_node].type == OP_BACK_REF) { /* If the back reference epsilon-transit, its destination must also have the constraint. Then duplicate the epsilon closure of the destination of the back reference, and store it in edests of the back reference. */ org_dest = dfa->nexts[org_node]; re_node_set_empty (dfa->edests + clone_node); clone_dest = duplicate_node (dfa, org_dest, constraint); if (BE (clone_dest == -1, 0)) return REG_ESPACE; dfa->nexts[clone_node] = dfa->nexts[org_node]; ret = re_node_set_insert (dfa->edests + clone_node, clone_dest); if (BE (ret < 0, 0)) return REG_ESPACE; } else if (dfa->edests[org_node].nelem == 0) { /* In case of the node can't epsilon-transit, don't duplicate the destination and store the original destination as the destination of the node. */ dfa->nexts[clone_node] = dfa->nexts[org_node]; break; } else if (dfa->edests[org_node].nelem == 1) { /* In case of the node can epsilon-transit, and it has only one destination. */ org_dest = dfa->edests[org_node].elems[0]; re_node_set_empty (dfa->edests + clone_node); if (dfa->nodes[org_node].type == ANCHOR) { /* In case of the node has another constraint, append it. */ if (org_node == root_node && clone_node != org_node) { /* ...but if the node is root_node itself, it means the epsilon closure have a loop, then tie it to the destination of the root_node. */ ret = re_node_set_insert (dfa->edests + clone_node, org_dest); if (BE (ret < 0, 0)) return REG_ESPACE; break; } constraint |= dfa->nodes[org_node].opr.ctx_type; } clone_dest = duplicate_node (dfa, org_dest, constraint); if (BE (clone_dest == -1, 0)) return REG_ESPACE; ret = re_node_set_insert (dfa->edests + clone_node, clone_dest); if (BE (ret < 0, 0)) return REG_ESPACE; } else /* dfa->edests[org_node].nelem == 2 */ { /* In case of the node can epsilon-transit, and it has two destinations. In the bin_tree_t and DFA, that's '|' and '*'. */ org_dest = dfa->edests[org_node].elems[0]; re_node_set_empty (dfa->edests + clone_node); /* Search for a duplicated node which satisfies the constraint. */ clone_dest = search_duplicated_node (dfa, org_dest, constraint); if (clone_dest == -1) { /* There are no such a duplicated node, create a new one. */ reg_errcode_t err; clone_dest = duplicate_node (dfa, org_dest, constraint); if (BE (clone_dest == -1, 0)) return REG_ESPACE; ret = re_node_set_insert (dfa->edests + clone_node, clone_dest); if (BE (ret < 0, 0)) return REG_ESPACE; err = duplicate_node_closure (dfa, org_dest, clone_dest, root_node, constraint); if (BE (err != REG_NOERROR, 0)) return err; } else { /* There are a duplicated node which satisfy the constraint, use it to avoid infinite loop. */ ret = re_node_set_insert (dfa->edests + clone_node, clone_dest); if (BE (ret < 0, 0)) return REG_ESPACE; } org_dest = dfa->edests[org_node].elems[1]; clone_dest = duplicate_node (dfa, org_dest, constraint); if (BE (clone_dest == -1, 0)) return REG_ESPACE; ret = re_node_set_insert (dfa->edests + clone_node, clone_dest); if (BE (ret < 0, 0)) return REG_ESPACE; } org_node = org_dest; clone_node = clone_dest; } return REG_NOERROR; } /* Search for a node which is duplicated from the node ORG_NODE, and satisfies the constraint CONSTRAINT. */ static int search_duplicated_node (const re_dfa_t *dfa, int org_node, unsigned int constraint) { int idx; for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx) { if (org_node == dfa->org_indices[idx] && constraint == dfa->nodes[idx].constraint) return idx; /* Found. */ } return -1; /* Not found. */ } /* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT. Return the index of the new node, or -1 if insufficient storage is available. */ static int duplicate_node (re_dfa_t *dfa, int org_idx, unsigned int constraint) { int dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]); if (BE (dup_idx != -1, 1)) { dfa->nodes[dup_idx].constraint = constraint; if (dfa->nodes[org_idx].type == ANCHOR) dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].opr.ctx_type; dfa->nodes[dup_idx].duplicated = 1; /* Store the index of the original node. */ dfa->org_indices[dup_idx] = org_idx; } return dup_idx; } static reg_errcode_t calc_inveclosure (re_dfa_t *dfa) { int src, idx, ret; for (idx = 0; idx < dfa->nodes_len; ++idx) re_node_set_init_empty (dfa->inveclosures + idx); for (src = 0; src < dfa->nodes_len; ++src) { int *elems = dfa->eclosures[src].elems; for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx) { ret = re_node_set_insert_last (dfa->inveclosures + elems[idx], src); if (BE (ret == -1, 0)) return REG_ESPACE; } } return REG_NOERROR; } /* Calculate "eclosure" for all the node in DFA. */ static reg_errcode_t calc_eclosure (re_dfa_t *dfa) { int node_idx, incomplete; #ifdef DEBUG assert (dfa->nodes_len > 0); #endif incomplete = 0; /* For each nodes, calculate epsilon closure. */ for (node_idx = 0; ; ++node_idx) { reg_errcode_t err; re_node_set eclosure_elem; if (node_idx == dfa->nodes_len) { if (!incomplete) break; incomplete = 0; node_idx = 0; } #ifdef DEBUG assert (dfa->eclosures[node_idx].nelem != -1); #endif /* If we have already calculated, skip it. */ if (dfa->eclosures[node_idx].nelem != 0) continue; /* Calculate epsilon closure of `node_idx'. */ err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, 1); if (BE (err != REG_NOERROR, 0)) return err; if (dfa->eclosures[node_idx].nelem == 0) { incomplete = 1; re_node_set_free (&eclosure_elem); } } return REG_NOERROR; } /* Calculate epsilon closure of NODE. */ static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, int node, int root) { reg_errcode_t err; unsigned int constraint; int i, incomplete; re_node_set eclosure; incomplete = 0; err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1); if (BE (err != REG_NOERROR, 0)) return err; /* This indicates that we are calculating this node now. We reference this value to avoid infinite loop. */ dfa->eclosures[node].nelem = -1; constraint = ((dfa->nodes[node].type == ANCHOR) ? dfa->nodes[node].opr.ctx_type : 0); /* If the current node has constraints, duplicate all nodes. Since they must inherit the constraints. */ if (constraint && dfa->edests[node].nelem && !dfa->nodes[dfa->edests[node].elems[0]].duplicated) { err = duplicate_node_closure (dfa, node, node, node, constraint); if (BE (err != REG_NOERROR, 0)) return err; } /* Expand each epsilon destination nodes. */ if (IS_EPSILON_NODE(dfa->nodes[node].type)) for (i = 0; i < dfa->edests[node].nelem; ++i) { re_node_set eclosure_elem; int edest = dfa->edests[node].elems[i]; /* If calculating the epsilon closure of `edest' is in progress, return intermediate result. */ if (dfa->eclosures[edest].nelem == -1) { incomplete = 1; continue; } /* If we haven't calculated the epsilon closure of `edest' yet, calculate now. Otherwise use calculated epsilon closure. */ if (dfa->eclosures[edest].nelem == 0) { err = calc_eclosure_iter (&eclosure_elem, dfa, edest, 0); if (BE (err != REG_NOERROR, 0)) return err; } else eclosure_elem = dfa->eclosures[edest]; /* Merge the epsilon closure of `edest'. */ re_node_set_merge (&eclosure, &eclosure_elem); /* If the epsilon closure of `edest' is incomplete, the epsilon closure of this node is also incomplete. */ if (dfa->eclosures[edest].nelem == 0) { incomplete = 1; re_node_set_free (&eclosure_elem); } } /* Epsilon closures include itself. */ re_node_set_insert (&eclosure, node); if (incomplete && !root) dfa->eclosures[node].nelem = 0; else dfa->eclosures[node] = eclosure; *new_set = eclosure; return REG_NOERROR; } /* Functions for token which are used in the parser. */ /* Fetch a token from INPUT. We must not use this function inside bracket expressions. */ static void internal_function fetch_token (re_token_t *result, re_string_t *input, reg_syntax_t syntax) { re_string_skip_bytes (input, peek_token (result, input, syntax)); } /* Peek a token from INPUT, and return the length of the token. We must not use this function inside bracket expressions. */ static int internal_function peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax) { unsigned char c; if (re_string_eoi (input)) { token->type = END_OF_RE; return 0; } c = re_string_peek_byte (input, 0); token->opr.c = c; token->word_char = 0; #ifdef RE_ENABLE_I18N token->mb_partial = 0; if (input->mb_cur_max > 1 && !re_string_first_byte (input, re_string_cur_idx (input))) { token->type = CHARACTER; token->mb_partial = 1; return 1; } #endif if (c == '\\') { unsigned char c2; if (re_string_cur_idx (input) + 1 >= re_string_length (input)) { token->type = BACK_SLASH; return 1; } c2 = re_string_peek_byte_case (input, 1); token->opr.c = c2; token->type = CHARACTER; #ifdef RE_ENABLE_I18N if (input->mb_cur_max > 1) { wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input) + 1); token->word_char = IS_WIDE_WORD_CHAR (wc) != 0; } else #endif token->word_char = IS_WORD_CHAR (c2) != 0; switch (c2) { case '|': if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_NO_BK_VBAR)) token->type = OP_ALT; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!(syntax & RE_NO_BK_REFS)) { token->type = OP_BACK_REF; token->opr.idx = c2 - '1'; } break; case '<': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = WORD_FIRST; } break; case '>': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = WORD_LAST; } break; case 'b': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = WORD_DELIM; } break; case 'B': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = NOT_WORD_DELIM; } break; case 'w': if (!(syntax & RE_NO_GNU_OPS)) token->type = OP_WORD; break; case 'W': if (!(syntax & RE_NO_GNU_OPS)) token->type = OP_NOTWORD; break; case 's': if (!(syntax & RE_NO_GNU_OPS)) token->type = OP_SPACE; break; case 'S': if (!(syntax & RE_NO_GNU_OPS)) token->type = OP_NOTSPACE; break; case '`': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = BUF_FIRST; } break; case '\'': if (!(syntax & RE_NO_GNU_OPS)) { token->type = ANCHOR; token->opr.ctx_type = BUF_LAST; } break; case '(': if (!(syntax & RE_NO_BK_PARENS)) token->type = OP_OPEN_SUBEXP; break; case ')': if (!(syntax & RE_NO_BK_PARENS)) token->type = OP_CLOSE_SUBEXP; break; case '+': if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM)) token->type = OP_DUP_PLUS; break; case '?': if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM)) token->type = OP_DUP_QUESTION; break; case '{': if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES))) token->type = OP_OPEN_DUP_NUM; break; case '}': if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES))) token->type = OP_CLOSE_DUP_NUM; break; default: break; } return 2; } token->type = CHARACTER; #ifdef RE_ENABLE_I18N if (input->mb_cur_max > 1) { wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input)); token->word_char = IS_WIDE_WORD_CHAR (wc) != 0; } else #endif token->word_char = IS_WORD_CHAR (token->opr.c); switch (c) { case '\n': if (syntax & RE_NEWLINE_ALT) token->type = OP_ALT; break; case '|': if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_NO_BK_VBAR)) token->type = OP_ALT; break; case '*': token->type = OP_DUP_ASTERISK; break; case '+': if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM)) token->type = OP_DUP_PLUS; break; case '?': if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM)) token->type = OP_DUP_QUESTION; break; case '{': if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) token->type = OP_OPEN_DUP_NUM; break; case '}': if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) token->type = OP_CLOSE_DUP_NUM; break; case '(': if (syntax & RE_NO_BK_PARENS) token->type = OP_OPEN_SUBEXP; break; case ')': if (syntax & RE_NO_BK_PARENS) token->type = OP_CLOSE_SUBEXP; break; case '[': token->type = OP_OPEN_BRACKET; break; case '.': token->type = OP_PERIOD; break; case '^': if (!(syntax & (RE_CONTEXT_INDEP_ANCHORS | RE_CARET_ANCHORS_HERE)) && re_string_cur_idx (input) != 0) { char prev = re_string_peek_byte (input, -1); if (!(syntax & RE_NEWLINE_ALT) || prev != '\n') break; } token->type = ANCHOR; token->opr.ctx_type = LINE_FIRST; break; case '$': if (!(syntax & RE_CONTEXT_INDEP_ANCHORS) && re_string_cur_idx (input) + 1 != re_string_length (input)) { re_token_t next; re_string_skip_bytes (input, 1); peek_token (&next, input, syntax); re_string_skip_bytes (input, -1); if (next.type != OP_ALT && next.type != OP_CLOSE_SUBEXP) break; } token->type = ANCHOR; token->opr.ctx_type = LINE_LAST; break; default: break; } return 1; } /* Peek a token from INPUT, and return the length of the token. We must not use this function out of bracket expressions. */ static int internal_function peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax) { unsigned char c; if (re_string_eoi (input)) { token->type = END_OF_RE; return 0; } c = re_string_peek_byte (input, 0); token->opr.c = c; #ifdef RE_ENABLE_I18N if (input->mb_cur_max > 1 && !re_string_first_byte (input, re_string_cur_idx (input))) { token->type = CHARACTER; return 1; } #endif /* RE_ENABLE_I18N */ if (c == '\\' && (syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && re_string_cur_idx (input) + 1 < re_string_length (input)) { /* In this case, '\' escape a character. */ unsigned char c2; re_string_skip_bytes (input, 1); c2 = re_string_peek_byte (input, 0); token->opr.c = c2; token->type = CHARACTER; return 1; } if (c == '[') /* '[' is a special char in a bracket exps. */ { unsigned char c2; int token_len; if (re_string_cur_idx (input) + 1 < re_string_length (input)) c2 = re_string_peek_byte (input, 1); else c2 = 0; token->opr.c = c2; token_len = 2; switch (c2) { case '.': token->type = OP_OPEN_COLL_ELEM; break; case '=': token->type = OP_OPEN_EQUIV_CLASS; break; case ':': if (syntax & RE_CHAR_CLASSES) { token->type = OP_OPEN_CHAR_CLASS; break; } /* else fall through. */ default: token->type = CHARACTER; token->opr.c = c; token_len = 1; break; } return token_len; } switch (c) { case '-': token->type = OP_CHARSET_RANGE; break; case ']': token->type = OP_CLOSE_BRACKET; break; case '^': token->type = OP_NON_MATCH_LIST; break; default: token->type = CHARACTER; } return 1; } /* Functions for parser. */ /* Entry point of the parser. Parse the regular expression REGEXP and return the structure tree. If an error is occured, ERR is set by error code, and return NULL. This function build the following tree, from regular expression <reg_exp>: CAT / \ / \ <reg_exp> EOR CAT means concatenation. EOR means end of regular expression. */ static bin_tree_t * parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax, reg_errcode_t *err) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_t *tree, *eor, *root; re_token_t current_token; dfa->syntax = syntax; fetch_token (&current_token, regexp, syntax | RE_CARET_ANCHORS_HERE); tree = parse_reg_exp (regexp, preg, &current_token, syntax, 0, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; eor = create_tree (dfa, NULL, NULL, END_OF_RE); if (tree != NULL) root = create_tree (dfa, tree, eor, CONCAT); else root = eor; if (BE (eor == NULL || root == NULL, 0)) { *err = REG_ESPACE; return NULL; } return root; } /* This function build the following tree, from regular expression <branch1>|<branch2>: ALT / \ / \ <branch1> <branch2> ALT means alternative, which represents the operator `|'. */ static bin_tree_t * parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_t *tree, *branch = NULL; tree = parse_branch (regexp, preg, token, syntax, nest, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; while (token->type == OP_ALT) { fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE); if (token->type != OP_ALT && token->type != END_OF_RE && (nest == 0 || token->type != OP_CLOSE_SUBEXP)) { branch = parse_branch (regexp, preg, token, syntax, nest, err); if (BE (*err != REG_NOERROR && branch == NULL, 0)) return NULL; } else branch = NULL; tree = create_tree (dfa, tree, branch, OP_ALT); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } } return tree; } /* This function build the following tree, from regular expression <exp1><exp2>: CAT / \ / \ <exp1> <exp2> CAT means concatenation. */ static bin_tree_t * parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err) { bin_tree_t *tree, *exp; re_dfa_t *dfa = (re_dfa_t *) preg->buffer; tree = parse_expression (regexp, preg, token, syntax, nest, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; while (token->type != OP_ALT && token->type != END_OF_RE && (nest == 0 || token->type != OP_CLOSE_SUBEXP)) { exp = parse_expression (regexp, preg, token, syntax, nest, err); if (BE (*err != REG_NOERROR && exp == NULL, 0)) { return NULL; } if (tree != NULL && exp != NULL) { tree = create_tree (dfa, tree, exp, CONCAT); if (tree == NULL) { *err = REG_ESPACE; return NULL; } } else if (tree == NULL) tree = exp; /* Otherwise exp == NULL, we don't need to create new tree. */ } return tree; } /* This function build the following tree, from regular expression a*: * | a */ static bin_tree_t * parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_t *tree; switch (token->type) { case CHARACTER: tree = create_token_tree (dfa, NULL, NULL, token); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) { while (!re_string_eoi (regexp) && !re_string_first_byte (regexp, re_string_cur_idx (regexp))) { bin_tree_t *mbc_remain; fetch_token (token, regexp, syntax); mbc_remain = create_token_tree (dfa, NULL, NULL, token); tree = create_tree (dfa, tree, mbc_remain, CONCAT); if (BE (mbc_remain == NULL || tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } } } #endif break; case OP_OPEN_SUBEXP: tree = parse_sub_exp (regexp, preg, token, syntax, nest + 1, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; break; case OP_OPEN_BRACKET: tree = parse_bracket_exp (regexp, dfa, token, syntax, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; break; case OP_BACK_REF: if (!BE (dfa->completed_bkref_map & (1 << token->opr.idx), 1)) { *err = REG_ESUBREG; return NULL; } dfa->used_bkref_map |= 1 << token->opr.idx; tree = create_token_tree (dfa, NULL, NULL, token); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } ++dfa->nbackref; dfa->has_mb_node = 1; break; case OP_OPEN_DUP_NUM: if (syntax & RE_CONTEXT_INVALID_DUP) { *err = REG_BADRPT; return NULL; } /* FALLTHROUGH */ case OP_DUP_ASTERISK: case OP_DUP_PLUS: case OP_DUP_QUESTION: if (syntax & RE_CONTEXT_INVALID_OPS) { *err = REG_BADRPT; return NULL; } else if (syntax & RE_CONTEXT_INDEP_OPS) { fetch_token (token, regexp, syntax); return parse_expression (regexp, preg, token, syntax, nest, err); } /* else fall through */ case OP_CLOSE_SUBEXP: if ((token->type == OP_CLOSE_SUBEXP) && !(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)) { *err = REG_ERPAREN; return NULL; } /* else fall through */ case OP_CLOSE_DUP_NUM: /* We treat it as a normal character. */ /* Then we can these characters as normal characters. */ token->type = CHARACTER; /* mb_partial and word_char bits should be initialized already by peek_token. */ tree = create_token_tree (dfa, NULL, NULL, token); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } break; case ANCHOR: if ((token->opr.ctx_type & (WORD_DELIM | NOT_WORD_DELIM | WORD_FIRST | WORD_LAST)) && dfa->word_ops_used == 0) init_word_char (dfa); if (token->opr.ctx_type == WORD_DELIM || token->opr.ctx_type == NOT_WORD_DELIM) { bin_tree_t *tree_first, *tree_last; if (token->opr.ctx_type == WORD_DELIM) { token->opr.ctx_type = WORD_FIRST; tree_first = create_token_tree (dfa, NULL, NULL, token); token->opr.ctx_type = WORD_LAST; } else { token->opr.ctx_type = INSIDE_WORD; tree_first = create_token_tree (dfa, NULL, NULL, token); token->opr.ctx_type = INSIDE_NOTWORD; } tree_last = create_token_tree (dfa, NULL, NULL, token); tree = create_tree (dfa, tree_first, tree_last, OP_ALT); if (BE (tree_first == NULL || tree_last == NULL || tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } } else { tree = create_token_tree (dfa, NULL, NULL, token); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } } /* We must return here, since ANCHORs can't be followed by repetition operators. eg. RE"^*" is invalid or "<ANCHOR(^)><CHAR(*)>", it must not be "<ANCHOR(^)><REPEAT(*)>". */ fetch_token (token, regexp, syntax); return tree; case OP_PERIOD: tree = create_token_tree (dfa, NULL, NULL, token); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } if (dfa->mb_cur_max > 1) dfa->has_mb_node = 1; break; case OP_WORD: case OP_NOTWORD: tree = build_charclass_op (dfa, regexp->trans, (const unsigned char *) "alnum", (const unsigned char *) "_", token->type == OP_NOTWORD, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; break; case OP_SPACE: case OP_NOTSPACE: tree = build_charclass_op (dfa, regexp->trans, (const unsigned char *) "space", (const unsigned char *) "", token->type == OP_NOTSPACE, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; break; case OP_ALT: case END_OF_RE: return NULL; case BACK_SLASH: *err = REG_EESCAPE; return NULL; default: /* Must not happen? */ #ifdef DEBUG assert (0); #endif return NULL; } fetch_token (token, regexp, syntax); while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS || token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM) { tree = parse_dup_op (tree, regexp, dfa, token, syntax, err); if (BE (*err != REG_NOERROR && tree == NULL, 0)) return NULL; /* In BRE consecutive duplications are not allowed. */ if ((syntax & RE_CONTEXT_INVALID_DUP) && (token->type == OP_DUP_ASTERISK || token->type == OP_OPEN_DUP_NUM)) { *err = REG_BADRPT; return NULL; } } return tree; } /* This function build the following tree, from regular expression (<reg_exp>): SUBEXP | <reg_exp> */ static bin_tree_t * parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, reg_syntax_t syntax, int nest, reg_errcode_t *err) { re_dfa_t *dfa = (re_dfa_t *) preg->buffer; bin_tree_t *tree; size_t cur_nsub; cur_nsub = preg->re_nsub++; fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE); /* The subexpression may be a null string. */ if (token->type == OP_CLOSE_SUBEXP) tree = NULL; else { tree = parse_reg_exp (regexp, preg, token, syntax, nest, err); if (BE (*err == REG_NOERROR && token->type != OP_CLOSE_SUBEXP, 0)) *err = REG_EPAREN; if (BE (*err != REG_NOERROR, 0)) return NULL; } if (cur_nsub <= '9' - '1') dfa->completed_bkref_map |= 1 << cur_nsub; tree = create_tree (dfa, tree, NULL, SUBEXP); if (BE (tree == NULL, 0)) { *err = REG_ESPACE; return NULL; } tree->token.opr.idx = cur_nsub; return tree; } /* This function parse repetition operators like "*", "+", "{1,3}" etc. */ static bin_tree_t * parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa, re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err) { bin_tree_t *tree = NULL, *old_tree = NULL; int i, start, end, start_idx = re_string_cur_idx (regexp); re_token_t start_token = *token; if (token->type == OP_OPEN_DUP_NUM) { end = 0; start = fetch_number (regexp, token, syntax); if (start == -1) { if (token->type == CHARACTER && token->opr.c == ',') start = 0; /* We treat "{,m}" as "{0,m}". */ else { *err = REG_BADBR; /* <re>{} is invalid. */ return NULL; } } if (BE (start != -2, 1)) { /* We treat "{n}" as "{n,n}". */ end = ((token->type == OP_CLOSE_DUP_NUM) ? start : ((token->type == CHARACTER && token->opr.c == ',') ? fetch_number (regexp, token, syntax) : -2)); } if (BE (start == -2 || end == -2, 0)) { /* Invalid sequence. */ if (BE (!(syntax & RE_INVALID_INTERVAL_ORD), 0)) { if (token->type == END_OF_RE) *err = REG_EBRACE; else *err = REG_BADBR; return NULL; } /* If the syntax bit is set, rollback. */ re_string_set_index (regexp, start_idx); *token = start_token; token->type = CHARACTER; /* mb_partial and word_char bits should be already initialized by peek_token. */ return elem; } if (BE (end != -1 && start > end, 0)) { /* First number greater than second. */ *err = REG_BADBR; return NULL; } } else { start = (token->type == OP_DUP_PLUS) ? 1 : 0; end = (token->type == OP_DUP_QUESTION) ? 1 : -1; } fetch_token (token, regexp, syntax); if (BE (elem == NULL, 0)) return NULL; if (BE (start == 0 && end == 0, 0)) { postorder (elem, free_tree, NULL); return NULL; } /* Extract "<re>{n,m}" to "<re><re>...<re><re>{0,<m-n>}". */ if (BE (start > 0, 0)) { tree = elem; for (i = 2; i <= start; ++i) { elem = duplicate_tree (elem, dfa); tree = create_tree (dfa, tree, elem, CONCAT); if (BE (elem == NULL || tree == NULL, 0)) goto parse_dup_op_espace; } if (start == end) return tree; /* Duplicate ELEM before it is marked optional. */ elem = duplicate_tree (elem, dfa); old_tree = tree; } else old_tree = NULL; if (elem->token.type == SUBEXP) postorder (elem, mark_opt_subexp, (void *) (long) elem->token.opr.idx); tree = create_tree (dfa, elem, NULL, (end == -1 ? OP_DUP_ASTERISK : OP_ALT)); if (BE (tree == NULL, 0)) goto parse_dup_op_espace; /* This loop is actually executed only when end != -1, to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?... We have already created the start+1-th copy. */ for (i = start + 2; i <= end; ++i) { elem = duplicate_tree (elem, dfa); tree = create_tree (dfa, tree, elem, CONCAT); if (BE (elem == NULL || tree == NULL, 0)) goto parse_dup_op_espace; tree = create_tree (dfa, tree, NULL, OP_ALT); if (BE (tree == NULL, 0)) goto parse_dup_op_espace; } if (old_tree) tree = create_tree (dfa, old_tree, tree, CONCAT); return tree; parse_dup_op_espace: *err = REG_ESPACE; return NULL; } /* Size of the names for collating symbol/equivalence_class/character_class. I'm not sure, but maybe enough. */ #define BRACKET_NAME_BUF_SIZE 32 #ifndef _LIBC /* Local function for parse_bracket_exp only used in case of NOT _LIBC. Build the range expression which starts from START_ELEM, and ends at END_ELEM. The result are written to MBCSET and SBCSET. RANGE_ALLOC is the allocated size of mbcset->range_starts, and mbcset->range_ends, is a pointer argument sinse we may update it. */ static reg_errcode_t internal_function # ifdef RE_ENABLE_I18N build_range_exp (bitset_t sbcset, re_charset_t *mbcset, int *range_alloc, bracket_elem_t *start_elem, bracket_elem_t *end_elem) # else /* not RE_ENABLE_I18N */ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem, bracket_elem_t *end_elem) # endif /* not RE_ENABLE_I18N */ { unsigned int start_ch, end_ch; /* Equivalence Classes and Character Classes can't be a range start/end. */ if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS, 0)) return REG_ERANGE; /* We can handle no multi character collating elements without libc support. */ if (BE ((start_elem->type == COLL_SYM && strlen ((char *) start_elem->opr.name) > 1) || (end_elem->type == COLL_SYM && strlen ((char *) end_elem->opr.name) > 1), 0)) return REG_ECOLLATE; # ifdef RE_ENABLE_I18N { wchar_t wc; wint_t start_wc; wint_t end_wc; wchar_t cmp_buf[6] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'}; start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0] : 0)); end_ch = ((end_elem->type == SB_CHAR) ? end_elem->opr.ch : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0] : 0)); start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM) ? __btowc (start_ch) : start_elem->opr.wch); end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM) ? __btowc (end_ch) : end_elem->opr.wch); if (start_wc == WEOF || end_wc == WEOF) return REG_ECOLLATE; cmp_buf[0] = start_wc; cmp_buf[4] = end_wc; if (wcscoll (cmp_buf, cmp_buf + 4) > 0) return REG_ERANGE; /* Got valid collation sequence values, add them as a new entry. However, for !_LIBC we have no collation elements: if the character set is single byte, the single byte character set that we build below suffices. parse_bracket_exp passes no MBCSET if dfa->mb_cur_max == 1. */ if (mbcset) { /* Check the space of the arrays. */ if (BE (*range_alloc == mbcset->nranges, 0)) { /* There is not enough space, need realloc. */ wchar_t *new_array_start, *new_array_end; int new_nranges; /* +1 in case of mbcset->nranges is 0. */ new_nranges = 2 * mbcset->nranges + 1; /* Use realloc since mbcset->range_starts and mbcset->range_ends are NULL if *range_alloc == 0. */ new_array_start = re_realloc (mbcset->range_starts, wchar_t, new_nranges); new_array_end = re_realloc (mbcset->range_ends, wchar_t, new_nranges); if (BE (new_array_start == NULL || new_array_end == NULL, 0)) return REG_ESPACE; mbcset->range_starts = new_array_start; mbcset->range_ends = new_array_end; *range_alloc = new_nranges; } mbcset->range_starts[mbcset->nranges] = start_wc; mbcset->range_ends[mbcset->nranges++] = end_wc; } /* Build the table for single byte characters. */ for (wc = 0; wc < SBC_MAX; ++wc) { cmp_buf[2] = wc; if (wcscoll (cmp_buf, cmp_buf + 2) <= 0 && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0) bitset_set (sbcset, wc); } } # else /* not RE_ENABLE_I18N */ { unsigned int ch; start_ch = ((start_elem->type == SB_CHAR ) ? start_elem->opr.ch : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0] : 0)); end_ch = ((end_elem->type == SB_CHAR ) ? end_elem->opr.ch : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0] : 0)); if (start_ch > end_ch) return REG_ERANGE; /* Build the table for single byte characters. */ for (ch = 0; ch < SBC_MAX; ++ch) if (start_ch <= ch && ch <= end_ch) bitset_set (sbcset, ch); } # endif /* not RE_ENABLE_I18N */ return REG_NOERROR; } #endif /* not _LIBC */ #ifndef _LIBC /* Helper function for parse_bracket_exp only used in case of NOT _LIBC.. Build the collating element which is represented by NAME. The result are written to MBCSET and SBCSET. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a pointer argument since we may update it. */ static reg_errcode_t internal_function # ifdef RE_ENABLE_I18N build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset, int *coll_sym_alloc, const unsigned char *name) # else /* not RE_ENABLE_I18N */ build_collating_symbol (bitset_t sbcset, const unsigned char *name) # endif /* not RE_ENABLE_I18N */ { size_t name_len = strlen ((const char *) name); if (BE (name_len != 1, 0)) return REG_ECOLLATE; else { bitset_set (sbcset, name[0]); return REG_NOERROR; } } #endif /* not _LIBC */ /* This function parse bracket expression like "[abc]", "[a-c]", "[[.a-a.]]" etc. */ static bin_tree_t * parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err) { #ifdef _LIBC const unsigned char *collseqmb; const char *collseqwc; uint32_t nrules; int32_t table_size; const int32_t *symb_table; const unsigned char *extra; /* Local function for parse_bracket_exp used in _LIBC environement. Seek the collating symbol entry correspondings to NAME. Return the index of the symbol in the SYMB_TABLE. */ auto inline int32_t __attribute ((always_inline)) seek_collating_symbol_entry (name, name_len) const unsigned char *name; size_t name_len; { int32_t hash = elem_hash ((const char *) name, name_len); int32_t elem = hash % table_size; if (symb_table[2 * elem] != 0) { int32_t second = hash % (table_size - 2) + 1; do { /* First compare the hashing value. */ if (symb_table[2 * elem] == hash /* Compare the length of the name. */ && name_len == extra[symb_table[2 * elem + 1]] /* Compare the name. */ && memcmp (name, &extra[symb_table[2 * elem + 1] + 1], name_len) == 0) { /* Yep, this is the entry. */ break; } /* Next entry. */ elem += second; } while (symb_table[2 * elem] != 0); } return elem; } /* Local function for parse_bracket_exp used in _LIBC environement. Look up the collation sequence value of BR_ELEM. Return the value if succeeded, UINT_MAX otherwise. */ auto inline unsigned int __attribute ((always_inline)) lookup_collation_sequence_value (br_elem) bracket_elem_t *br_elem; { if (br_elem->type == SB_CHAR) { /* if (MB_CUR_MAX == 1) */ if (nrules == 0) return collseqmb[br_elem->opr.ch]; else { wint_t wc = __btowc (br_elem->opr.ch); return __collseq_table_lookup (collseqwc, wc); } } else if (br_elem->type == MB_CHAR) { return __collseq_table_lookup (collseqwc, br_elem->opr.wch); } else if (br_elem->type == COLL_SYM) { size_t sym_name_len = strlen ((char *) br_elem->opr.name); if (nrules != 0) { int32_t elem, idx; elem = seek_collating_symbol_entry (br_elem->opr.name, sym_name_len); if (symb_table[2 * elem] != 0) { /* We found the entry. */ idx = symb_table[2 * elem + 1]; /* Skip the name of collating element name. */ idx += 1 + extra[idx]; /* Skip the byte sequence of the collating element. */ idx += 1 + extra[idx]; /* Adjust for the alignment. */ idx = (idx + 3) & ~3; /* Skip the multibyte collation sequence value. */ idx += sizeof (unsigned int); /* Skip the wide char sequence of the collating element. */ idx += sizeof (unsigned int) * (1 + *(unsigned int *) (extra + idx)); /* Return the collation sequence value. */ return *(unsigned int *) (extra + idx); } else if (symb_table[2 * elem] == 0 && sym_name_len == 1) { /* No valid character. Match it as a single byte character. */ return collseqmb[br_elem->opr.name[0]]; } } else if (sym_name_len == 1) return collseqmb[br_elem->opr.name[0]]; } return UINT_MAX; } /* Local function for parse_bracket_exp used in _LIBC environement. Build the range expression which starts from START_ELEM, and ends at END_ELEM. The result are written to MBCSET and SBCSET. RANGE_ALLOC is the allocated size of mbcset->range_starts, and mbcset->range_ends, is a pointer argument sinse we may update it. */ auto inline reg_errcode_t __attribute ((always_inline)) build_range_exp (sbcset, mbcset, range_alloc, start_elem, end_elem) re_charset_t *mbcset; int *range_alloc; bitset_t sbcset; bracket_elem_t *start_elem, *end_elem; { unsigned int ch; uint32_t start_collseq; uint32_t end_collseq; /* Equivalence Classes and Character Classes can't be a range start/end. */ if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS, 0)) return REG_ERANGE; start_collseq = lookup_collation_sequence_value (start_elem); end_collseq = lookup_collation_sequence_value (end_elem); /* Check start/end collation sequence values. */ if (BE (start_collseq == UINT_MAX || end_collseq == UINT_MAX, 0)) return REG_ECOLLATE; if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_collseq > end_collseq, 0)) return REG_ERANGE; /* Got valid collation sequence values, add them as a new entry. However, if we have no collation elements, and the character set is single byte, the single byte character set that we build below suffices. */ if (nrules > 0 || dfa->mb_cur_max > 1) { /* Check the space of the arrays. */ if (BE (*range_alloc == mbcset->nranges, 0)) { /* There is not enough space, need realloc. */ uint32_t *new_array_start; uint32_t *new_array_end; int new_nranges; /* +1 in case of mbcset->nranges is 0. */ new_nranges = 2 * mbcset->nranges + 1; new_array_start = re_realloc (mbcset->range_starts, uint32_t, new_nranges); new_array_end = re_realloc (mbcset->range_ends, uint32_t, new_nranges); if (BE (new_array_start == NULL || new_array_end == NULL, 0)) return REG_ESPACE; mbcset->range_starts = new_array_start; mbcset->range_ends = new_array_end; *range_alloc = new_nranges; } mbcset->range_starts[mbcset->nranges] = start_collseq; mbcset->range_ends[mbcset->nranges++] = end_collseq; } /* Build the table for single byte characters. */ for (ch = 0; ch < SBC_MAX; ch++) { uint32_t ch_collseq; /* if (MB_CUR_MAX == 1) */ if (nrules == 0) ch_collseq = collseqmb[ch]; else ch_collseq = __collseq_table_lookup (collseqwc, __btowc (ch)); if (start_collseq <= ch_collseq && ch_collseq <= end_collseq) bitset_set (sbcset, ch); } return REG_NOERROR; } /* Local function for parse_bracket_exp used in _LIBC environement. Build the collating element which is represented by NAME. The result are written to MBCSET and SBCSET. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a pointer argument sinse we may update it. */ auto inline reg_errcode_t __attribute ((always_inline)) build_collating_symbol (sbcset, mbcset, coll_sym_alloc, name) re_charset_t *mbcset; int *coll_sym_alloc; bitset_t sbcset; const unsigned char *name; { int32_t elem, idx; size_t name_len = strlen ((const char *) name); if (nrules != 0) { elem = seek_collating_symbol_entry (name, name_len); if (symb_table[2 * elem] != 0) { /* We found the entry. */ idx = symb_table[2 * elem + 1]; /* Skip the name of collating element name. */ idx += 1 + extra[idx]; } else if (symb_table[2 * elem] == 0 && name_len == 1) { /* No valid character, treat it as a normal character. */ bitset_set (sbcset, name[0]); return REG_NOERROR; } else return REG_ECOLLATE; /* Got valid collation sequence, add it as a new entry. */ /* Check the space of the arrays. */ if (BE (*coll_sym_alloc == mbcset->ncoll_syms, 0)) { /* Not enough, realloc it. */ /* +1 in case of mbcset->ncoll_syms is 0. */ int new_coll_sym_alloc = 2 * mbcset->ncoll_syms + 1; /* Use realloc since mbcset->coll_syms is NULL if *alloc == 0. */ int32_t *new_coll_syms = re_realloc (mbcset->coll_syms, int32_t, new_coll_sym_alloc); if (BE (new_coll_syms == NULL, 0)) return REG_ESPACE; mbcset->coll_syms = new_coll_syms; *coll_sym_alloc = new_coll_sym_alloc; } mbcset->coll_syms[mbcset->ncoll_syms++] = idx; return REG_NOERROR; } else { if (BE (name_len != 1, 0)) return REG_ECOLLATE; else { bitset_set (sbcset, name[0]); return REG_NOERROR; } } } #endif re_token_t br_token; re_bitset_ptr_t sbcset; #ifdef RE_ENABLE_I18N re_charset_t *mbcset; int coll_sym_alloc = 0, range_alloc = 0, mbchar_alloc = 0; int equiv_class_alloc = 0, char_class_alloc = 0; #endif /* not RE_ENABLE_I18N */ int non_match = 0; bin_tree_t *work_tree; int token_len; int first_round = 1; #ifdef _LIBC collseqmb = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB); nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); if (nrules) { /* if (MB_CUR_MAX > 1) */ collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC); table_size = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_SYMB_HASH_SIZEMB); symb_table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_TABLEMB); extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB); } #endif sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); #ifdef RE_ENABLE_I18N mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1); #endif /* RE_ENABLE_I18N */ #ifdef RE_ENABLE_I18N if (BE (sbcset == NULL || mbcset == NULL, 0)) #else if (BE (sbcset == NULL, 0)) #endif /* RE_ENABLE_I18N */ { *err = REG_ESPACE; return NULL; } token_len = peek_token_bracket (token, regexp, syntax); if (BE (token->type == END_OF_RE, 0)) { *err = REG_BADPAT; goto parse_bracket_exp_free_return; } if (token->type == OP_NON_MATCH_LIST) { #ifdef RE_ENABLE_I18N mbcset->non_match = 1; #endif /* not RE_ENABLE_I18N */ non_match = 1; if (syntax & RE_HAT_LISTS_NOT_NEWLINE) bitset_set (sbcset, '\0'); re_string_skip_bytes (regexp, token_len); /* Skip a token. */ token_len = peek_token_bracket (token, regexp, syntax); if (BE (token->type == END_OF_RE, 0)) { *err = REG_BADPAT; goto parse_bracket_exp_free_return; } } /* We treat the first ']' as a normal character. */ if (token->type == OP_CLOSE_BRACKET) token->type = CHARACTER; while (1) { bracket_elem_t start_elem, end_elem; unsigned char start_name_buf[BRACKET_NAME_BUF_SIZE]; unsigned char end_name_buf[BRACKET_NAME_BUF_SIZE]; reg_errcode_t ret; int token_len2 = 0, is_range_exp = 0; re_token_t token2; start_elem.opr.name = start_name_buf; ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa, syntax, first_round); if (BE (ret != REG_NOERROR, 0)) { *err = ret; goto parse_bracket_exp_free_return; } first_round = 0; /* Get information about the next token. We need it in any case. */ token_len = peek_token_bracket (token, regexp, syntax); /* Do not check for ranges if we know they are not allowed. */ if (start_elem.type != CHAR_CLASS && start_elem.type != EQUIV_CLASS) { if (BE (token->type == END_OF_RE, 0)) { *err = REG_EBRACK; goto parse_bracket_exp_free_return; } if (token->type == OP_CHARSET_RANGE) { re_string_skip_bytes (regexp, token_len); /* Skip '-'. */ token_len2 = peek_token_bracket (&token2, regexp, syntax); if (BE (token2.type == END_OF_RE, 0)) { *err = REG_EBRACK; goto parse_bracket_exp_free_return; } if (token2.type == OP_CLOSE_BRACKET) { /* We treat the last '-' as a normal character. */ re_string_skip_bytes (regexp, -token_len); token->type = CHARACTER; } else is_range_exp = 1; } } if (is_range_exp == 1) { end_elem.opr.name = end_name_buf; ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2, dfa, syntax, 1); if (BE (ret != REG_NOERROR, 0)) { *err = ret; goto parse_bracket_exp_free_return; } token_len = peek_token_bracket (token, regexp, syntax); #ifdef _LIBC *err = build_range_exp (sbcset, mbcset, &range_alloc, &start_elem, &end_elem); #else # ifdef RE_ENABLE_I18N *err = build_range_exp (sbcset, dfa->mb_cur_max > 1 ? mbcset : NULL, &range_alloc, &start_elem, &end_elem); # else *err = build_range_exp (sbcset, &start_elem, &end_elem); # endif #endif /* RE_ENABLE_I18N */ if (BE (*err != REG_NOERROR, 0)) goto parse_bracket_exp_free_return; } else { switch (start_elem.type) { case SB_CHAR: bitset_set (sbcset, start_elem.opr.ch); break; #ifdef RE_ENABLE_I18N case MB_CHAR: /* Check whether the array has enough space. */ if (BE (mbchar_alloc == mbcset->nmbchars, 0)) { wchar_t *new_mbchars; /* Not enough, realloc it. */ /* +1 in case of mbcset->nmbchars is 0. */ mbchar_alloc = 2 * mbcset->nmbchars + 1; /* Use realloc since array is NULL if *alloc == 0. */ new_mbchars = re_realloc (mbcset->mbchars, wchar_t, mbchar_alloc); if (BE (new_mbchars == NULL, 0)) goto parse_bracket_exp_espace; mbcset->mbchars = new_mbchars; } mbcset->mbchars[mbcset->nmbchars++] = start_elem.opr.wch; break; #endif /* RE_ENABLE_I18N */ case EQUIV_CLASS: *err = build_equiv_class (sbcset, #ifdef RE_ENABLE_I18N mbcset, &equiv_class_alloc, #endif /* RE_ENABLE_I18N */ start_elem.opr.name); if (BE (*err != REG_NOERROR, 0)) goto parse_bracket_exp_free_return; break; case COLL_SYM: *err = build_collating_symbol (sbcset, #ifdef RE_ENABLE_I18N mbcset, &coll_sym_alloc, #endif /* RE_ENABLE_I18N */ start_elem.opr.name); if (BE (*err != REG_NOERROR, 0)) goto parse_bracket_exp_free_return; break; case CHAR_CLASS: *err = build_charclass (regexp->trans, sbcset, #ifdef RE_ENABLE_I18N mbcset, &char_class_alloc, #endif /* RE_ENABLE_I18N */ start_elem.opr.name, syntax); if (BE (*err != REG_NOERROR, 0)) goto parse_bracket_exp_free_return; break; default: assert (0); break; } } if (BE (token->type == END_OF_RE, 0)) { *err = REG_EBRACK; goto parse_bracket_exp_free_return; } if (token->type == OP_CLOSE_BRACKET) break; } re_string_skip_bytes (regexp, token_len); /* Skip a token. */ /* If it is non-matching list. */ if (non_match) bitset_not (sbcset); #ifdef RE_ENABLE_I18N /* Ensure only single byte characters are set. */ if (dfa->mb_cur_max > 1) bitset_mask (sbcset, dfa->sb_char); if (mbcset->nmbchars || mbcset->ncoll_syms || mbcset->nequiv_classes || mbcset->nranges || (dfa->mb_cur_max > 1 && (mbcset->nchar_classes || mbcset->non_match))) { bin_tree_t *mbc_tree; int sbc_idx; /* Build a tree for complex bracket. */ dfa->has_mb_node = 1; br_token.type = COMPLEX_BRACKET; br_token.opr.mbcset = mbcset; mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token); if (BE (mbc_tree == NULL, 0)) goto parse_bracket_exp_espace; for (sbc_idx = 0; sbc_idx < BITSET_WORDS; ++sbc_idx) if (sbcset[sbc_idx]) break; /* If there are no bits set in sbcset, there is no point of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */ if (sbc_idx < BITSET_WORDS) { /* Build a tree for simple bracket. */ br_token.type = SIMPLE_BRACKET; br_token.opr.sbcset = sbcset; work_tree = create_token_tree (dfa, NULL, NULL, &br_token); if (BE (work_tree == NULL, 0)) goto parse_bracket_exp_espace; /* Then join them by ALT node. */ work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT); if (BE (work_tree == NULL, 0)) goto parse_bracket_exp_espace; } else { re_free (sbcset); work_tree = mbc_tree; } } else #endif /* not RE_ENABLE_I18N */ { #ifdef RE_ENABLE_I18N free_charset (mbcset); #endif /* Build a tree for simple bracket. */ br_token.type = SIMPLE_BRACKET; br_token.opr.sbcset = sbcset; work_tree = create_token_tree (dfa, NULL, NULL, &br_token); if (BE (work_tree == NULL, 0)) goto parse_bracket_exp_espace; } return work_tree; parse_bracket_exp_espace: *err = REG_ESPACE; parse_bracket_exp_free_return: re_free (sbcset); #ifdef RE_ENABLE_I18N free_charset (mbcset); #endif /* RE_ENABLE_I18N */ return NULL; } /* Parse an element in the bracket expression. */ static reg_errcode_t parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp, re_token_t *token, int token_len, re_dfa_t *dfa, reg_syntax_t syntax, int accept_hyphen) { #ifdef RE_ENABLE_I18N int cur_char_size; cur_char_size = re_string_char_size_at (regexp, re_string_cur_idx (regexp)); if (cur_char_size > 1) { elem->type = MB_CHAR; elem->opr.wch = re_string_wchar_at (regexp, re_string_cur_idx (regexp)); re_string_skip_bytes (regexp, cur_char_size); return REG_NOERROR; } #endif /* RE_ENABLE_I18N */ re_string_skip_bytes (regexp, token_len); /* Skip a token. */ if (token->type == OP_OPEN_COLL_ELEM || token->type == OP_OPEN_CHAR_CLASS || token->type == OP_OPEN_EQUIV_CLASS) return parse_bracket_symbol (elem, regexp, token); if (BE (token->type == OP_CHARSET_RANGE, 0) && !accept_hyphen) { /* A '-' must only appear as anything but a range indicator before the closing bracket. Everything else is an error. */ re_token_t token2; (void) peek_token_bracket (&token2, regexp, syntax); if (token2.type != OP_CLOSE_BRACKET) /* The actual error value is not standardized since this whole case is undefined. But ERANGE makes good sense. */ return REG_ERANGE; } elem->type = SB_CHAR; elem->opr.ch = token->opr.c; return REG_NOERROR; } /* Parse a bracket symbol in the bracket expression. Bracket symbols are such as [:<character_class>:], [.<collating_element>.], and [=<equivalent_class>=]. */ static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp, re_token_t *token) { unsigned char ch, delim = token->opr.c; int i = 0; if (re_string_eoi(regexp)) return REG_EBRACK; for (;; ++i) { if (i >= BRACKET_NAME_BUF_SIZE) return REG_EBRACK; if (token->type == OP_OPEN_CHAR_CLASS) ch = re_string_fetch_byte_case (regexp); else ch = re_string_fetch_byte (regexp); if (re_string_eoi(regexp)) return REG_EBRACK; if (ch == delim && re_string_peek_byte (regexp, 0) == ']') break; elem->opr.name[i] = ch; } re_string_skip_bytes (regexp, 1); elem->opr.name[i] = '\0'; switch (token->type) { case OP_OPEN_COLL_ELEM: elem->type = COLL_SYM; break; case OP_OPEN_EQUIV_CLASS: elem->type = EQUIV_CLASS; break; case OP_OPEN_CHAR_CLASS: elem->type = CHAR_CLASS; break; default: break; } return REG_NOERROR; } /* Helper function for parse_bracket_exp. Build the equivalence class which is represented by NAME. The result are written to MBCSET and SBCSET. EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes, is a pointer argument sinse we may update it. */ static reg_errcode_t #ifdef RE_ENABLE_I18N build_equiv_class (bitset_t sbcset, re_charset_t *mbcset, int *equiv_class_alloc, const unsigned char *name) #else /* not RE_ENABLE_I18N */ build_equiv_class (bitset_t sbcset, const unsigned char *name) #endif /* not RE_ENABLE_I18N */ { #ifdef _LIBC uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); if (nrules != 0) { const int32_t *table, *indirect; const unsigned char *weights, *extra, *cp; unsigned char char_buf[2]; int32_t idx1, idx2; unsigned int ch; size_t len; /* This #include defines a local function! */ # include <locale/weight.h> /* Calculate the index for equivalence class. */ cp = name; table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB); extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB); idx1 = findidx (&cp); if (BE (idx1 == 0 || cp < name + strlen ((const char *) name), 0)) /* This isn't a valid character. */ return REG_ECOLLATE; /* Build single byte matcing table for this equivalence class. */ char_buf[1] = (unsigned char) '\0'; len = weights[idx1]; for (ch = 0; ch < SBC_MAX; ++ch) { char_buf[0] = ch; cp = char_buf; idx2 = findidx (&cp); /* idx2 = table[ch]; */ if (idx2 == 0) /* This isn't a valid character. */ continue; if (len == weights[idx2]) { int cnt = 0; while (cnt <= len && weights[idx1 + 1 + cnt] == weights[idx2 + 1 + cnt]) ++cnt; if (cnt > len) bitset_set (sbcset, ch); } } /* Check whether the array has enough space. */ if (BE (*equiv_class_alloc == mbcset->nequiv_classes, 0)) { /* Not enough, realloc it. */ /* +1 in case of mbcset->nequiv_classes is 0. */ int new_equiv_class_alloc = 2 * mbcset->nequiv_classes + 1; /* Use realloc since the array is NULL if *alloc == 0. */ int32_t *new_equiv_classes = re_realloc (mbcset->equiv_classes, int32_t, new_equiv_class_alloc); if (BE (new_equiv_classes == NULL, 0)) return REG_ESPACE; mbcset->equiv_classes = new_equiv_classes; *equiv_class_alloc = new_equiv_class_alloc; } mbcset->equiv_classes[mbcset->nequiv_classes++] = idx1; } else #endif /* _LIBC */ { if (BE (strlen ((const char *) name) != 1, 0)) return REG_ECOLLATE; bitset_set (sbcset, *name); } return REG_NOERROR; } /* Helper function for parse_bracket_exp. Build the character class which is represented by NAME. The result are written to MBCSET and SBCSET. CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes, is a pointer argument sinse we may update it. */ static reg_errcode_t #ifdef RE_ENABLE_I18N build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, re_charset_t *mbcset, int *char_class_alloc, const unsigned char *class_name, reg_syntax_t syntax) #else /* not RE_ENABLE_I18N */ build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, const unsigned char *class_name, reg_syntax_t syntax) #endif /* not RE_ENABLE_I18N */ { int i; const char *name = (const char *) class_name; /* In case of REG_ICASE "upper" and "lower" match the both of upper and lower cases. */ if ((syntax & RE_ICASE) && (strcmp (name, "upper") == 0 || strcmp (name, "lower") == 0)) name = "alpha"; #ifdef RE_ENABLE_I18N /* Check the space of the arrays. */ if (BE (*char_class_alloc == mbcset->nchar_classes, 0)) { /* Not enough, realloc it. */ /* +1 in case of mbcset->nchar_classes is 0. */ int new_char_class_alloc = 2 * mbcset->nchar_classes + 1; /* Use realloc since array is NULL if *alloc == 0. */ wctype_t *new_char_classes = re_realloc (mbcset->char_classes, wctype_t, new_char_class_alloc); if (BE (new_char_classes == NULL, 0)) return REG_ESPACE; mbcset->char_classes = new_char_classes; *char_class_alloc = new_char_class_alloc; } mbcset->char_classes[mbcset->nchar_classes++] = __wctype (name); #endif /* RE_ENABLE_I18N */ #define BUILD_CHARCLASS_LOOP(ctype_func) \ do { \ if (BE (trans != NULL, 0)) \ { \ for (i = 0; i < SBC_MAX; ++i) \ if (ctype_func (i)) \ bitset_set (sbcset, trans[i]); \ } \ else \ { \ for (i = 0; i < SBC_MAX; ++i) \ if (ctype_func (i)) \ bitset_set (sbcset, i); \ } \ } while (0) if (strcmp (name, "alnum") == 0) BUILD_CHARCLASS_LOOP (isalnum); else if (strcmp (name, "cntrl") == 0) BUILD_CHARCLASS_LOOP (iscntrl); else if (strcmp (name, "lower") == 0) BUILD_CHARCLASS_LOOP (islower); else if (strcmp (name, "space") == 0) BUILD_CHARCLASS_LOOP (isspace); else if (strcmp (name, "alpha") == 0) BUILD_CHARCLASS_LOOP (isalpha); else if (strcmp (name, "digit") == 0) BUILD_CHARCLASS_LOOP (isdigit); else if (strcmp (name, "print") == 0) BUILD_CHARCLASS_LOOP (isprint); else if (strcmp (name, "upper") == 0) BUILD_CHARCLASS_LOOP (isupper); else if (strcmp (name, "blank") == 0) BUILD_CHARCLASS_LOOP (isblank); else if (strcmp (name, "graph") == 0) BUILD_CHARCLASS_LOOP (isgraph); else if (strcmp (name, "punct") == 0) BUILD_CHARCLASS_LOOP (ispunct); else if (strcmp (name, "xdigit") == 0) BUILD_CHARCLASS_LOOP (isxdigit); else return REG_ECTYPE; return REG_NOERROR; } static bin_tree_t * build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans, const unsigned char *class_name, const unsigned char *extra, int non_match, reg_errcode_t *err) { re_bitset_ptr_t sbcset; #ifdef RE_ENABLE_I18N re_charset_t *mbcset; int alloc = 0; #endif /* not RE_ENABLE_I18N */ reg_errcode_t ret; re_token_t br_token; bin_tree_t *tree; sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); #ifdef RE_ENABLE_I18N mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1); #endif /* RE_ENABLE_I18N */ #ifdef RE_ENABLE_I18N if (BE (sbcset == NULL || mbcset == NULL, 0)) #else /* not RE_ENABLE_I18N */ if (BE (sbcset == NULL, 0)) #endif /* not RE_ENABLE_I18N */ { *err = REG_ESPACE; return NULL; } if (non_match) { #ifdef RE_ENABLE_I18N /* if (syntax & RE_HAT_LISTS_NOT_NEWLINE) bitset_set(cset->sbcset, '\0'); */ mbcset->non_match = 1; #endif /* not RE_ENABLE_I18N */ } /* We don't care the syntax in this case. */ ret = build_charclass (trans, sbcset, #ifdef RE_ENABLE_I18N mbcset, &alloc, #endif /* RE_ENABLE_I18N */ class_name, 0); if (BE (ret != REG_NOERROR, 0)) { re_free (sbcset); #ifdef RE_ENABLE_I18N free_charset (mbcset); #endif /* RE_ENABLE_I18N */ *err = ret; return NULL; } /* \w match '_' also. */ for (; *extra; extra++) bitset_set (sbcset, *extra); /* If it is non-matching list. */ if (non_match) bitset_not (sbcset); #ifdef RE_ENABLE_I18N /* Ensure only single byte characters are set. */ if (dfa->mb_cur_max > 1) bitset_mask (sbcset, dfa->sb_char); #endif /* Build a tree for simple bracket. */ br_token.type = SIMPLE_BRACKET; br_token.opr.sbcset = sbcset; tree = create_token_tree (dfa, NULL, NULL, &br_token); if (BE (tree == NULL, 0)) goto build_word_op_espace; #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) { bin_tree_t *mbc_tree; /* Build a tree for complex bracket. */ br_token.type = COMPLEX_BRACKET; br_token.opr.mbcset = mbcset; dfa->has_mb_node = 1; mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token); if (BE (mbc_tree == NULL, 0)) goto build_word_op_espace; /* Then join them by ALT node. */ tree = create_tree (dfa, tree, mbc_tree, OP_ALT); if (BE (mbc_tree != NULL, 1)) return tree; } else { free_charset (mbcset); return tree; } #else /* not RE_ENABLE_I18N */ return tree; #endif /* not RE_ENABLE_I18N */ build_word_op_espace: re_free (sbcset); #ifdef RE_ENABLE_I18N free_charset (mbcset); #endif /* RE_ENABLE_I18N */ *err = REG_ESPACE; return NULL; } /* This is intended for the expressions like "a{1,3}". Fetch a number from `input', and return the number. Return -1, if the number field is empty like "{,1}". Return -2, If an error is occured. */ static int fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax) { int num = -1; unsigned char c; while (1) { fetch_token (token, input, syntax); c = token->opr.c; if (BE (token->type == END_OF_RE, 0)) return -2; if (token->type == OP_CLOSE_DUP_NUM || c == ',') break; num = ((token->type != CHARACTER || c < '0' || '9' < c || num == -2) ? -2 : ((num == -1) ? c - '0' : num * 10 + c - '0')); num = (num > RE_DUP_MAX) ? -2 : num; } return num; } #ifdef RE_ENABLE_I18N static void free_charset (re_charset_t *cset) { re_free (cset->mbchars); # ifdef _LIBC re_free (cset->coll_syms); re_free (cset->equiv_classes); re_free (cset->range_starts); re_free (cset->range_ends); # endif re_free (cset->char_classes); re_free (cset); } #endif /* RE_ENABLE_I18N */ /* Functions for binary tree operation. */ /* Create a tree node. */ static bin_tree_t * create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, re_token_type_t type) { re_token_t t; t.type = type; return create_token_tree (dfa, left, right, &t); } static bin_tree_t * create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, const re_token_t *token) { bin_tree_t *tree; if (BE (dfa->str_tree_storage_idx == BIN_TREE_STORAGE_SIZE, 0)) { bin_tree_storage_t *storage = re_malloc (bin_tree_storage_t, 1); if (storage == NULL) return NULL; storage->next = dfa->str_tree_storage; dfa->str_tree_storage = storage; dfa->str_tree_storage_idx = 0; } tree = &dfa->str_tree_storage->data[dfa->str_tree_storage_idx++]; tree->parent = NULL; tree->left = left; tree->right = right; tree->token = *token; tree->token.duplicated = 0; tree->token.opt_subexp = 0; tree->first = NULL; tree->next = NULL; tree->node_idx = -1; if (left != NULL) left->parent = tree; if (right != NULL) right->parent = tree; return tree; } /* Mark the tree SRC as an optional subexpression. To be called from preorder or postorder. */ static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node) { int idx = (int) (long) extra; if (node->token.type == SUBEXP && node->token.opr.idx == idx) node->token.opt_subexp = 1; return REG_NOERROR; } /* Free the allocated memory inside NODE. */ static void free_token (re_token_t *node) { #ifdef RE_ENABLE_I18N if (node->type == COMPLEX_BRACKET && node->duplicated == 0) free_charset (node->opr.mbcset); else #endif /* RE_ENABLE_I18N */ if (node->type == SIMPLE_BRACKET && node->duplicated == 0) re_free (node->opr.sbcset); } /* Worker function for tree walking. Free the allocated memory inside NODE and its children. */ static reg_errcode_t free_tree (void *extra, bin_tree_t *node) { free_token (&node->token); return REG_NOERROR; } /* Duplicate the node SRC, and return new node. This is a preorder visit similar to the one implemented by the generic visitor, but we need more infrastructure to maintain two parallel trees --- so, it's easier to duplicate. */ static bin_tree_t * duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa) { const bin_tree_t *node; bin_tree_t *dup_root; bin_tree_t **p_new = &dup_root, *dup_node = root->parent; for (node = root; ; ) { /* Create a new tree and link it back to the current parent. */ *p_new = create_token_tree (dfa, NULL, NULL, &node->token); if (*p_new == NULL) return NULL; (*p_new)->parent = dup_node; (*p_new)->token.duplicated = 1; dup_node = *p_new; /* Go to the left node, or up and to the right. */ if (node->left) { node = node->left; p_new = &dup_node->left; } else { const bin_tree_t *prev = NULL; while (node->right == prev || node->right == NULL) { prev = node; node = node->parent; dup_node = dup_node->parent; if (!node) return dup_root; } node = node->right; p_new = &dup_node->right; } } } /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* GKINCLUDE #include "regexec.c" */ /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags, int n) internal_function; static void match_ctx_clean (re_match_context_t *mctx) internal_function; static void match_ctx_free (re_match_context_t *cache) internal_function; static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, int node, int str_idx, int from, int to) internal_function; static int search_cur_bkref_entry (const re_match_context_t *mctx, int str_idx) internal_function; static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, int node, int str_idx) internal_function; static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop, int node, int str_idx) internal_function; static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts, re_dfastate_t **limited_sts, int last_node, int last_str_idx) internal_function; static reg_errcode_t re_search_internal (const regex_t *preg, const char *string, int length, int start, int range, int stop, size_t nmatch, regmatch_t pmatch[], int eflags) internal_function; static int re_search_2_stub (struct re_pattern_buffer *bufp, const char *string1, int length1, const char *string2, int length2, int start, int range, struct re_registers *regs, int stop, int ret_len) internal_function; static int re_search_stub (struct re_pattern_buffer *bufp, const char *string, int length, int start, int range, int stop, struct re_registers *regs, int ret_len) internal_function; static unsigned re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, int nregs, int regs_allocated) internal_function; static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx) internal_function; static int check_matching (re_match_context_t *mctx, int fl_longest_match, int *p_match_first) internal_function; static int check_halt_state_context (const re_match_context_t *mctx, const re_dfastate_t *state, int idx) internal_function; static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch, regmatch_t *prev_idx_match, int cur_node, int cur_idx, int nmatch) internal_function; static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs, int str_idx, int dest_node, int nregs, regmatch_t *regs, re_node_set *eps_via_nodes) internal_function; static reg_errcode_t set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch, regmatch_t *pmatch, int fl_backtrack) internal_function; static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs) internal_function; #ifdef RE_ENABLE_I18N static int sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx, int node_idx, int str_idx, int max_str_idx) internal_function; #endif /* RE_ENABLE_I18N */ static reg_errcode_t sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx) internal_function; static reg_errcode_t build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, re_node_set *cur_dest) internal_function; static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, re_node_set *dest_nodes) internal_function; static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes, const re_node_set *candidates) internal_function; static int check_dst_limits (const re_match_context_t *mctx, re_node_set *limits, int dst_node, int dst_idx, int src_node, int src_idx) internal_function; static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries, int subexp_idx, int from_node, int bkref_idx) internal_function; static int check_dst_limits_calc_pos (const re_match_context_t *mctx, int limit, int subexp_idx, int node, int str_idx, int bkref_idx) internal_function; static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes, const re_node_set *candidates, re_node_set *limits, struct re_backref_cache_entry *bkref_ents, int str_idx) internal_function; static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, const re_node_set *candidates) internal_function; static reg_errcode_t merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst, re_dfastate_t **src, int num) internal_function; static re_dfastate_t *find_recover_state (reg_errcode_t *err, re_match_context_t *mctx) internal_function; static re_dfastate_t *transit_state (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *state) internal_function; static re_dfastate_t *merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *next_state) internal_function; static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes, int str_idx) internal_function; #if 0 static re_dfastate_t *transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *pstate) internal_function; #endif #ifdef RE_ENABLE_I18N static reg_errcode_t transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate) internal_function; #endif /* RE_ENABLE_I18N */ static reg_errcode_t transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes) internal_function; static reg_errcode_t get_subexp (re_match_context_t *mctx, int bkref_node, int bkref_str_idx) internal_function; static reg_errcode_t get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top, re_sub_match_last_t *sub_last, int bkref_node, int bkref_str) internal_function; static int find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes, int subexp_idx, int type) internal_function; static reg_errcode_t check_arrival (re_match_context_t *mctx, state_array_t *path, int top_node, int top_str, int last_node, int last_str, int type) internal_function; static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx, int str_idx, re_node_set *cur_nodes, re_node_set *next_nodes) internal_function; static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes, int ex_subexp, int type) internal_function; static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes, int target, int ex_subexp, int type) internal_function; static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes, int cur_str, int subexp_num, int type) internal_function; static int build_trtable (const re_dfa_t *dfa, re_dfastate_t *state) internal_function; #ifdef RE_ENABLE_I18N static int check_node_accept_bytes (const re_dfa_t *dfa, int node_idx, const re_string_t *input, int idx) internal_function; # ifdef _LIBC static unsigned int find_collation_sequence_value (const unsigned char *mbs, size_t name_len) internal_function; # endif /* _LIBC */ #endif /* RE_ENABLE_I18N */ static int group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state, re_node_set *states_node, bitset_t *states_ch) internal_function; static int check_node_accept (const re_match_context_t *mctx, const re_token_t *node, int idx) internal_function; static reg_errcode_t extend_buffers (re_match_context_t *mctx) internal_function; /* Entry point for POSIX code. */ /* regexec searches for a given pattern, specified by PREG, in the string STRING. If NMATCH is zero or REG_NOSUB was set in the cflags argument to `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at least NMATCH elements, and we set them to the offsets of the corresponding matched substrings. EFLAGS specifies `execution flags' which affect matching: if REG_NOTBOL is set, then ^ does not match at the beginning of the string; if REG_NOTEOL is set, then $ does not match at the end. We return 0 if we find a match and REG_NOMATCH if not. */ int regexec (preg, string, nmatch, pmatch, eflags) const regex_t *__restrict preg; const char *__restrict string; size_t nmatch; regmatch_t pmatch[]; int eflags; { reg_errcode_t err; int start, length; re_dfa_t *dfa = (re_dfa_t *) preg->buffer; if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND)) return REG_BADPAT; if (eflags & REG_STARTEND) { start = pmatch[0].rm_so; length = pmatch[0].rm_eo; } else { start = 0; length = strlen (string); } __libc_lock_lock (dfa->lock); if (preg->no_sub) err = re_search_internal (preg, string, length, start, length - start, length, 0, NULL, eflags); else err = re_search_internal (preg, string, length, start, length - start, length, nmatch, pmatch, eflags); __libc_lock_unlock (dfa->lock); return err != REG_NOERROR; } #ifdef _LIBC # include <shlib-compat.h> versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4); # if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4) __typeof__ (__regexec) __compat_regexec; int attribute_compat_text_section __compat_regexec (const regex_t *__restrict preg, const char *__restrict string, size_t nmatch, regmatch_t pmatch[], int eflags) { return regexec (preg, string, nmatch, pmatch, eflags & (REG_NOTBOL | REG_NOTEOL)); } compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0); # endif #endif /* Entry points for GNU code. */ /* re_match, re_search, re_match_2, re_search_2 The former two functions operate on STRING with length LENGTH, while the later two operate on concatenation of STRING1 and STRING2 with lengths LENGTH1 and LENGTH2, respectively. re_match() matches the compiled pattern in BUFP against the string, starting at index START. re_search() first tries matching at index START, then it tries to match starting from index START + 1, and so on. The last start position tried is START + RANGE. (Thus RANGE = 0 forces re_search to operate the same way as re_match().) The parameter STOP of re_{match,search}_2 specifies that no match exceeding the first STOP characters of the concatenation of the strings should be concerned. If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match and all groups is stroed in REGS. (For the "_2" variants, the offsets are computed relative to the concatenation, not relative to the individual strings.) On success, re_match* functions return the length of the match, re_search* return the position of the start of the match. Return value -1 means no match was found and -2 indicates an internal error. */ int re_match (bufp, string, length, start, regs) struct re_pattern_buffer *bufp; const char *string; int length, start; struct re_registers *regs; { return re_search_stub (bufp, string, length, start, 0, length, regs, 1); } #ifdef _LIBC weak_alias (__re_match, re_match) #endif int re_search (bufp, string, length, start, range, regs) struct re_pattern_buffer *bufp; const char *string; int length, start, range; struct re_registers *regs; { return re_search_stub (bufp, string, length, start, range, length, regs, 0); } #ifdef _LIBC weak_alias (__re_search, re_search) #endif int re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop) struct re_pattern_buffer *bufp; const char *string1, *string2; int length1, length2, start, stop; struct re_registers *regs; { return re_search_2_stub (bufp, string1, length1, string2, length2, start, 0, regs, stop, 1); } #ifdef _LIBC weak_alias (__re_match_2, re_match_2) #endif int re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop) struct re_pattern_buffer *bufp; const char *string1, *string2; int length1, length2, start, range, stop; struct re_registers *regs; { return re_search_2_stub (bufp, string1, length1, string2, length2, start, range, regs, stop, 0); } #ifdef _LIBC weak_alias (__re_search_2, re_search_2) #endif static int re_search_2_stub (bufp, string1, length1, string2, length2, start, range, regs, stop, ret_len) struct re_pattern_buffer *bufp; const char *string1, *string2; int length1, length2, start, range, stop, ret_len; struct re_registers *regs; { const char *str; int rval; int len = length1 + length2; int free_str = 0; if (BE (length1 < 0 || length2 < 0 || stop < 0, 0)) return -2; /* Concatenate the strings. */ if (length2 > 0) if (length1 > 0) { char *s = re_malloc (char, len); if (BE (s == NULL, 0)) return -2; #ifdef _LIBC memcpy (__mempcpy (s, string1, length1), string2, length2); #else memcpy (s, string1, length1); memcpy (s + length1, string2, length2); #endif str = s; free_str = 1; } else str = string2; else str = string1; rval = re_search_stub (bufp, str, len, start, range, stop, regs, ret_len); if (free_str) re_free ((char *) str); return rval; } /* The parameters have the same meaning as those of re_search. Additional parameters: If RET_LEN is nonzero the length of the match is returned (re_match style); otherwise the position of the match is returned. */ static int re_search_stub (bufp, string, length, start, range, stop, regs, ret_len) struct re_pattern_buffer *bufp; const char *string; int length, start, range, stop, ret_len; struct re_registers *regs; { reg_errcode_t result; regmatch_t *pmatch; int nregs, rval; int eflags = 0; re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; /* Check for out-of-range. */ if (BE (start < 0 || start > length, 0)) return -1; if (BE (start + range > length, 0)) range = length - start; else if (BE (start + range < 0, 0)) range = -start; __libc_lock_lock (dfa->lock); eflags |= (bufp->not_bol) ? REG_NOTBOL : 0; eflags |= (bufp->not_eol) ? REG_NOTEOL : 0; /* Compile fastmap if we haven't yet. */ if (range > 0 && bufp->fastmap != NULL && !bufp->fastmap_accurate) re_compile_fastmap (bufp); if (BE (bufp->no_sub, 0)) regs = NULL; /* We need at least 1 register. */ if (regs == NULL) nregs = 1; else if (BE (bufp->regs_allocated == REGS_FIXED && regs->num_regs < bufp->re_nsub + 1, 0)) { nregs = regs->num_regs; if (BE (nregs < 1, 0)) { /* Nothing can be copied to regs. */ regs = NULL; nregs = 1; } } else nregs = bufp->re_nsub + 1; pmatch = re_malloc (regmatch_t, nregs); if (BE (pmatch == NULL, 0)) { rval = -2; goto out; } result = re_search_internal (bufp, string, length, start, range, stop, nregs, pmatch, eflags); rval = 0; /* I hope we needn't fill ther regs with -1's when no match was found. */ if (result != REG_NOERROR) rval = -1; else if (regs != NULL) { /* If caller wants register contents data back, copy them. */ bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs, bufp->regs_allocated); if (BE (bufp->regs_allocated == REGS_UNALLOCATED, 0)) rval = -2; } if (BE (rval == 0, 1)) { if (ret_len) { assert (pmatch[0].rm_so == start); rval = pmatch[0].rm_eo - start; } else rval = pmatch[0].rm_so; } re_free (pmatch); out: __libc_lock_unlock (dfa->lock); return rval; } static unsigned re_copy_regs (regs, pmatch, nregs, regs_allocated) struct re_registers *regs; regmatch_t *pmatch; int nregs, regs_allocated; { int rval = REGS_REALLOCATE; int i; int need_regs = nregs + 1; /* We need one extra element beyond `num_regs' for the `-1' marker GNU code uses. */ /* Have the register data arrays been allocated? */ if (regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. */ regs->start = re_malloc (regoff_t, need_regs); regs->end = re_malloc (regoff_t, need_regs); if (BE (regs->start == NULL, 0) || BE (regs->end == NULL, 0)) return REGS_UNALLOCATED; regs->num_regs = need_regs; } else if (regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already allocated, reallocate them. If we need fewer, just leave it alone. */ if (BE (need_regs > regs->num_regs, 0)) { regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs); regoff_t *new_end = re_realloc (regs->end, regoff_t, need_regs); if (BE (new_start == NULL, 0) || BE (new_end == NULL, 0)) return REGS_UNALLOCATED; regs->start = new_start; regs->end = new_end; regs->num_regs = need_regs; } } else { assert (regs_allocated == REGS_FIXED); /* This function may not be called with REGS_FIXED and nregs too big. */ assert (regs->num_regs >= nregs); rval = REGS_FIXED; } /* Copy the regs. */ for (i = 0; i < nregs; ++i) { regs->start[i] = pmatch[i].rm_so; regs->end[i] = pmatch[i].rm_eo; } for ( ; i < regs->num_regs; ++i) regs->start[i] = regs->end[i] = -1; return rval; } /* Set REGS to hold NUM_REGS registers, storing them in STARTS and ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use this memory for recording register information. STARTS and ENDS must be allocated using the malloc library routine, and must each be at least NUM_REGS * sizeof (regoff_t) bytes long. If NUM_REGS == 0, then subsequent matches should allocate their own register data. Unless this function is called, the first search or match using PATTERN_BUFFER will allocate its own register data, without freeing the old data. */ void re_set_registers (bufp, regs, num_regs, starts, ends) struct re_pattern_buffer *bufp; struct re_registers *regs; unsigned num_regs; regoff_t *starts, *ends; { if (num_regs) { bufp->regs_allocated = REGS_REALLOCATE; regs->num_regs = num_regs; regs->start = starts; regs->end = ends; } else { bufp->regs_allocated = REGS_UNALLOCATED; regs->num_regs = 0; regs->start = regs->end = (regoff_t *) 0; } } #ifdef _LIBC weak_alias (__re_set_registers, re_set_registers) #endif /* Entry points compatible with 4.2 BSD regex library. We don't define them unless specifically requested. */ #if defined _REGEX_RE_COMP || defined _LIBC int # ifdef _LIBC weak_function # endif re_exec (s) const char *s; { return 0 == regexec (&re_comp_buf, s, 0, NULL, 0); } #endif /* _REGEX_RE_COMP */ /* Internal entry point. */ /* Searches for a compiled pattern PREG in the string STRING, whose length is LENGTH. NMATCH, PMATCH, and EFLAGS have the same mingings with regexec. START, and RANGE have the same meanings with re_search. Return REG_NOERROR if we find a match, and REG_NOMATCH if not, otherwise return the error code. Note: We assume front end functions already check ranges. (START + RANGE >= 0 && START + RANGE <= LENGTH) */ static reg_errcode_t re_search_internal (preg, string, length, start, range, stop, nmatch, pmatch, eflags) const regex_t *preg; const char *string; int length, start, range, stop, eflags; size_t nmatch; regmatch_t pmatch[]; { reg_errcode_t err; const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer; int left_lim, right_lim, incr; int fl_longest_match, match_first, match_kind, match_last = -1; int extra_nmatch; int sb, ch; #if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) re_match_context_t mctx = { .dfa = dfa }; #else re_match_context_t mctx; #endif char *fastmap = (preg->fastmap != NULL && preg->fastmap_accurate && range && !preg->can_be_null) ? preg->fastmap : NULL; RE_TRANSLATE_TYPE t = preg->translate; #if !(defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)) memset (&mctx, '\0', sizeof (re_match_context_t)); mctx.dfa = dfa; #endif extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0; nmatch -= extra_nmatch; /* Check if the DFA haven't been compiled. */ if (BE (preg->used == 0 || dfa->init_state == NULL || dfa->init_state_word == NULL || dfa->init_state_nl == NULL || dfa->init_state_begbuf == NULL, 0)) return REG_NOMATCH; #ifdef DEBUG /* We assume front-end functions already check them. */ assert (start + range >= 0 && start + range <= length); #endif /* If initial states with non-begbuf contexts have no elements, the regex must be anchored. If preg->newline_anchor is set, we'll never use init_state_nl, so do not check it. */ if (dfa->init_state->nodes.nelem == 0 && dfa->init_state_word->nodes.nelem == 0 && (dfa->init_state_nl->nodes.nelem == 0 || !preg->newline_anchor)) { if (start != 0 && start + range != 0) return REG_NOMATCH; start = range = 0; } /* We must check the longest matching, if nmatch > 0. */ fl_longest_match = (nmatch != 0 || dfa->nbackref); err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1, preg->translate, preg->syntax & RE_ICASE, dfa); if (BE (err != REG_NOERROR, 0)) goto free_return; mctx.input.stop = stop; mctx.input.raw_stop = stop; mctx.input.newline_anchor = preg->newline_anchor; err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2); if (BE (err != REG_NOERROR, 0)) goto free_return; /* We will log all the DFA states through which the dfa pass, if nmatch > 1, or this dfa has "multibyte node", which is a back-reference or a node which can accept multibyte character or multi character collating element. */ if (nmatch > 1 || dfa->has_mb_node) { mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1); if (BE (mctx.state_log == NULL, 0)) { err = REG_ESPACE; goto free_return; } } else mctx.state_log = NULL; match_first = start; mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF : CONTEXT_NEWLINE | CONTEXT_BEGBUF; /* Check incrementally whether of not the input string match. */ incr = (range < 0) ? -1 : 1; left_lim = (range < 0) ? start + range : start; right_lim = (range < 0) ? start : start + range; sb = dfa->mb_cur_max == 1; match_kind = (fastmap ? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0) | (range >= 0 ? 2 : 0) | (t != NULL ? 1 : 0)) : 8); for (;; match_first += incr) { err = REG_NOMATCH; if (match_first < left_lim || right_lim < match_first) goto free_return; /* Advance as rapidly as possible through the string, until we find a plausible place to start matching. This may be done with varying efficiency, so there are various possibilities: only the most common of them are specialized, in order to save on code size. We use a switch statement for speed. */ switch (match_kind) { case 8: /* No fastmap. */ break; case 7: /* Fastmap with single-byte translation, match forward. */ while (BE (match_first < right_lim, 1) && !fastmap[t[(unsigned char) string[match_first]]]) ++match_first; goto forward_match_found_start_or_reached_end; case 6: /* Fastmap without translation, match forward. */ while (BE (match_first < right_lim, 1) && !fastmap[(unsigned char) string[match_first]]) ++match_first; forward_match_found_start_or_reached_end: if (BE (match_first == right_lim, 0)) { ch = match_first >= length ? 0 : (unsigned char) string[match_first]; if (!fastmap[t ? t[ch] : ch]) goto free_return; } break; case 4: case 5: /* Fastmap without multi-byte translation, match backwards. */ while (match_first >= left_lim) { ch = match_first >= length ? 0 : (unsigned char) string[match_first]; if (fastmap[t ? t[ch] : ch]) break; --match_first; } if (match_first < left_lim) goto free_return; break; default: /* In this case, we can't determine easily the current byte, since it might be a component byte of a multibyte character. Then we use the constructed buffer instead. */ for (;;) { /* If MATCH_FIRST is out of the valid range, reconstruct the buffers. */ unsigned int offset = match_first - mctx.input.raw_mbs_idx; if (BE (offset >= (unsigned int) mctx.input.valid_raw_len, 0)) { err = re_string_reconstruct (&mctx.input, match_first, eflags); if (BE (err != REG_NOERROR, 0)) goto free_return; offset = match_first - mctx.input.raw_mbs_idx; } /* If MATCH_FIRST is out of the buffer, leave it as '\0'. Note that MATCH_FIRST must not be smaller than 0. */ ch = (match_first >= length ? 0 : re_string_byte_at (&mctx.input, offset)); if (fastmap[ch]) break; match_first += incr; if (match_first < left_lim || match_first > right_lim) { err = REG_NOMATCH; goto free_return; } } break; } /* Reconstruct the buffers so that the matcher can assume that the matching starts from the beginning of the buffer. */ err = re_string_reconstruct (&mctx.input, match_first, eflags); if (BE (err != REG_NOERROR, 0)) goto free_return; #ifdef RE_ENABLE_I18N /* Don't consider this char as a possible match start if it part, yet isn't the head, of a multibyte character. */ if (!sb && !re_string_first_byte (&mctx.input, 0)) continue; #endif /* It seems to be appropriate one, then use the matcher. */ /* We assume that the matching starts from 0. */ mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0; match_last = check_matching (&mctx, fl_longest_match, range >= 0 ? &match_first : NULL); if (match_last != -1) { if (BE (match_last == -2, 0)) { err = REG_ESPACE; goto free_return; } else { mctx.match_last = match_last; if ((!preg->no_sub && nmatch > 1) || dfa->nbackref) { re_dfastate_t *pstate = mctx.state_log[match_last]; mctx.last_node = check_halt_state_context (&mctx, pstate, match_last); } if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match) || dfa->nbackref) { err = prune_impossible_nodes (&mctx); if (err == REG_NOERROR) break; if (BE (err != REG_NOMATCH, 0)) goto free_return; match_last = -1; } else break; /* We found a match. */ } } match_ctx_clean (&mctx); } #ifdef DEBUG assert (match_last != -1); assert (err == REG_NOERROR); #endif /* Set pmatch[] if we need. */ if (nmatch > 0) { int reg_idx; /* Initialize registers. */ for (reg_idx = 1; reg_idx < nmatch; ++reg_idx) pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1; /* Set the points where matching start/end. */ pmatch[0].rm_so = 0; pmatch[0].rm_eo = mctx.match_last; if (!preg->no_sub && nmatch > 1) { err = set_regs (preg, &mctx, nmatch, pmatch, dfa->has_plural_match && dfa->nbackref > 0); if (BE (err != REG_NOERROR, 0)) goto free_return; } /* At last, add the offset to the each registers, since we slided the buffers so that we could assume that the matching starts from 0. */ for (reg_idx = 0; reg_idx < nmatch; ++reg_idx) if (pmatch[reg_idx].rm_so != -1) { #ifdef RE_ENABLE_I18N if (BE (mctx.input.offsets_needed != 0, 0)) { pmatch[reg_idx].rm_so = (pmatch[reg_idx].rm_so == mctx.input.valid_len ? mctx.input.valid_raw_len : mctx.input.offsets[pmatch[reg_idx].rm_so]); pmatch[reg_idx].rm_eo = (pmatch[reg_idx].rm_eo == mctx.input.valid_len ? mctx.input.valid_raw_len : mctx.input.offsets[pmatch[reg_idx].rm_eo]); } #else assert (mctx.input.offsets_needed == 0); #endif pmatch[reg_idx].rm_so += match_first; pmatch[reg_idx].rm_eo += match_first; } for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx) { pmatch[nmatch + reg_idx].rm_so = -1; pmatch[nmatch + reg_idx].rm_eo = -1; } if (dfa->subexp_map) for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++) if (dfa->subexp_map[reg_idx] != reg_idx) { pmatch[reg_idx + 1].rm_so = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so; pmatch[reg_idx + 1].rm_eo = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo; } } free_return: re_free (mctx.state_log); if (dfa->nbackref) match_ctx_free (&mctx); re_string_destruct (&mctx.input); return err; } static reg_errcode_t prune_impossible_nodes (mctx) re_match_context_t *mctx; { const re_dfa_t *const dfa = mctx->dfa; int halt_node, match_last; reg_errcode_t ret; re_dfastate_t **sifted_states; re_dfastate_t **lim_states = NULL; re_sift_context_t sctx; #ifdef DEBUG assert (mctx->state_log != NULL); #endif match_last = mctx->match_last; halt_node = mctx->last_node; sifted_states = re_malloc (re_dfastate_t *, match_last + 1); if (BE (sifted_states == NULL, 0)) { ret = REG_ESPACE; goto free_return; } if (dfa->nbackref) { lim_states = re_malloc (re_dfastate_t *, match_last + 1); if (BE (lim_states == NULL, 0)) { ret = REG_ESPACE; goto free_return; } while (1) { memset (lim_states, '\0', sizeof (re_dfastate_t *) * (match_last + 1)); sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last); ret = sift_states_backward (mctx, &sctx); re_node_set_free (&sctx.limits); if (BE (ret != REG_NOERROR, 0)) goto free_return; if (sifted_states[0] != NULL || lim_states[0] != NULL) break; do { --match_last; if (match_last < 0) { ret = REG_NOMATCH; goto free_return; } } while (mctx->state_log[match_last] == NULL || !mctx->state_log[match_last]->halt); halt_node = check_halt_state_context (mctx, mctx->state_log[match_last], match_last); } ret = merge_state_array (dfa, sifted_states, lim_states, match_last + 1); re_free (lim_states); lim_states = NULL; if (BE (ret != REG_NOERROR, 0)) goto free_return; } else { sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last); ret = sift_states_backward (mctx, &sctx); re_node_set_free (&sctx.limits); if (BE (ret != REG_NOERROR, 0)) goto free_return; } re_free (mctx->state_log); mctx->state_log = sifted_states; sifted_states = NULL; mctx->last_node = halt_node; mctx->match_last = match_last; ret = REG_NOERROR; free_return: re_free (sifted_states); re_free (lim_states); return ret; } /* Acquire an initial state and return it. We must select appropriate initial state depending on the context, since initial states may have constraints like "\<", "^", etc.. */ static inline re_dfastate_t * __attribute ((always_inline)) internal_function acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx, int idx) { const re_dfa_t *const dfa = mctx->dfa; if (dfa->init_state->has_constraint) { unsigned int context; context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags); if (IS_WORD_CONTEXT (context)) return dfa->init_state_word; else if (IS_ORDINARY_CONTEXT (context)) return dfa->init_state; else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context)) return dfa->init_state_begbuf; else if (IS_NEWLINE_CONTEXT (context)) return dfa->init_state_nl; else if (IS_BEGBUF_CONTEXT (context)) { /* It is relatively rare case, then calculate on demand. */ return re_acquire_state_context (err, dfa, dfa->init_state->entrance_nodes, context); } else /* Must not happen? */ return dfa->init_state; } else return dfa->init_state; } /* Check whether the regular expression match input string INPUT or not, and return the index where the matching end, return -1 if not match, or return -2 in case of an error. FL_LONGEST_MATCH means we want the POSIX longest matching. If P_MATCH_FIRST is not NULL, and the match fails, it is set to the next place where we may want to try matching. Note that the matcher assume that the maching starts from the current index of the buffer. */ static int internal_function check_matching (re_match_context_t *mctx, int fl_longest_match, int *p_match_first) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err; int match = 0; int match_last = -1; int cur_str_idx = re_string_cur_idx (&mctx->input); re_dfastate_t *cur_state; int at_init_state = p_match_first != NULL; int next_start_idx = cur_str_idx; err = REG_NOERROR; cur_state = acquire_init_state_context (&err, mctx, cur_str_idx); /* An initial state must not be NULL (invalid). */ if (BE (cur_state == NULL, 0)) { assert (err == REG_ESPACE); return -2; } if (mctx->state_log != NULL) { mctx->state_log[cur_str_idx] = cur_state; /* Check OP_OPEN_SUBEXP in the initial state in case that we use them later. E.g. Processing back references. */ if (BE (dfa->nbackref, 0)) { at_init_state = 0; err = check_subexp_matching_top (mctx, &cur_state->nodes, 0); if (BE (err != REG_NOERROR, 0)) return err; if (cur_state->has_backref) { err = transit_state_bkref (mctx, &cur_state->nodes); if (BE (err != REG_NOERROR, 0)) return err; } } } /* If the RE accepts NULL string. */ if (BE (cur_state->halt, 0)) { if (!cur_state->has_constraint || check_halt_state_context (mctx, cur_state, cur_str_idx)) { if (!fl_longest_match) return cur_str_idx; else { match_last = cur_str_idx; match = 1; } } } while (!re_string_eoi (&mctx->input)) { re_dfastate_t *old_state = cur_state; int next_char_idx = re_string_cur_idx (&mctx->input) + 1; if (BE (next_char_idx >= mctx->input.bufs_len, 0) || (BE (next_char_idx >= mctx->input.valid_len, 0) && mctx->input.valid_len < mctx->input.len)) { err = extend_buffers (mctx); if (BE (err != REG_NOERROR, 0)) { assert (err == REG_ESPACE); return -2; } } cur_state = transit_state (&err, mctx, cur_state); if (mctx->state_log != NULL) cur_state = merge_state_with_log (&err, mctx, cur_state); if (cur_state == NULL) { /* Reached the invalid state or an error. Try to recover a valid state using the state log, if available and if we have not already found a valid (even if not the longest) match. */ if (BE (err != REG_NOERROR, 0)) return -2; if (mctx->state_log == NULL || (match && !fl_longest_match) || (cur_state = find_recover_state (&err, mctx)) == NULL) break; } if (BE (at_init_state, 0)) { if (old_state == cur_state) next_start_idx = next_char_idx; else at_init_state = 0; } if (cur_state->halt) { /* Reached a halt state. Check the halt state can satisfy the current context. */ if (!cur_state->has_constraint || check_halt_state_context (mctx, cur_state, re_string_cur_idx (&mctx->input))) { /* We found an appropriate halt state. */ match_last = re_string_cur_idx (&mctx->input); match = 1; /* We found a match, do not modify match_first below. */ p_match_first = NULL; if (!fl_longest_match) break; } } } if (p_match_first) *p_match_first += next_start_idx; return match_last; } /* Check NODE match the current context. */ static int internal_function check_halt_node_context (const re_dfa_t *dfa, int node, unsigned int context) { re_token_type_t type = dfa->nodes[node].type; unsigned int constraint = dfa->nodes[node].constraint; if (type != END_OF_RE) return 0; if (!constraint) return 1; if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context)) return 0; return 1; } /* Check the halt state STATE match the current context. Return 0 if not match, if the node, STATE has, is a halt node and match the context, return the node. */ static int internal_function check_halt_state_context (const re_match_context_t *mctx, const re_dfastate_t *state, int idx) { int i; unsigned int context; #ifdef DEBUG assert (state->halt); #endif context = re_string_context_at (&mctx->input, idx, mctx->eflags); for (i = 0; i < state->nodes.nelem; ++i) if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context)) return state->nodes.elems[i]; return 0; } /* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA corresponding to the DFA). Return the destination node, and update EPS_VIA_NODES, return -1 in case of errors. */ static int internal_function proceed_next_node (const re_match_context_t *mctx, int nregs, regmatch_t *regs, int *pidx, int node, re_node_set *eps_via_nodes, struct re_fail_stack_t *fs) { const re_dfa_t *const dfa = mctx->dfa; int i, err; if (IS_EPSILON_NODE (dfa->nodes[node].type)) { re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes; re_node_set *edests = &dfa->edests[node]; int dest_node; err = re_node_set_insert (eps_via_nodes, node); if (BE (err < 0, 0)) return -2; /* Pick up a valid destination, or return -1 if none is found. */ for (dest_node = -1, i = 0; i < edests->nelem; ++i) { int candidate = edests->elems[i]; if (!re_node_set_contains (cur_nodes, candidate)) continue; if (dest_node == -1) dest_node = candidate; else { /* In order to avoid infinite loop like "(a*)*", return the second epsilon-transition if the first was already considered. */ if (re_node_set_contains (eps_via_nodes, dest_node)) return candidate; /* Otherwise, push the second epsilon-transition on the fail stack. */ else if (fs != NULL && push_fail_stack (fs, *pidx, candidate, nregs, regs, eps_via_nodes)) return -2; /* We know we are going to exit. */ break; } } return dest_node; } else { int naccepted = 0; re_token_type_t type = dfa->nodes[node].type; #ifdef RE_ENABLE_I18N if (dfa->nodes[node].accept_mb) naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx); else #endif /* RE_ENABLE_I18N */ if (type == OP_BACK_REF) { int subexp_idx = dfa->nodes[node].opr.idx + 1; naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so; if (fs != NULL) { if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1) return -1; else if (naccepted) { char *buf = (char *) re_string_get_buffer (&mctx->input); if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx, naccepted) != 0) return -1; } } if (naccepted == 0) { int dest_node; err = re_node_set_insert (eps_via_nodes, node); if (BE (err < 0, 0)) return -2; dest_node = dfa->edests[node].elems[0]; if (re_node_set_contains (&mctx->state_log[*pidx]->nodes, dest_node)) return dest_node; } } if (naccepted != 0 || check_node_accept (mctx, dfa->nodes + node, *pidx)) { int dest_node = dfa->nexts[node]; *pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted; if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL || !re_node_set_contains (&mctx->state_log[*pidx]->nodes, dest_node))) return -1; re_node_set_empty (eps_via_nodes); return dest_node; } } return -1; } static reg_errcode_t internal_function push_fail_stack (struct re_fail_stack_t *fs, int str_idx, int dest_node, int nregs, regmatch_t *regs, re_node_set *eps_via_nodes) { reg_errcode_t err; int num = fs->num++; if (fs->num == fs->alloc) { struct re_fail_stack_ent_t *new_array; new_array = realloc (fs->stack, (sizeof (struct re_fail_stack_ent_t) * fs->alloc * 2)); if (new_array == NULL) return REG_ESPACE; fs->alloc *= 2; fs->stack = new_array; } fs->stack[num].idx = str_idx; fs->stack[num].node = dest_node; fs->stack[num].regs = re_malloc (regmatch_t, nregs); if (fs->stack[num].regs == NULL) return REG_ESPACE; memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs); err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes); return err; } static int internal_function pop_fail_stack (struct re_fail_stack_t *fs, int *pidx, int nregs, regmatch_t *regs, re_node_set *eps_via_nodes) { int num = --fs->num; assert (num >= 0); *pidx = fs->stack[num].idx; memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs); re_node_set_free (eps_via_nodes); re_free (fs->stack[num].regs); *eps_via_nodes = fs->stack[num].eps_via_nodes; return fs->stack[num].node; } /* Set the positions where the subexpressions are starts/ends to registers PMATCH. Note: We assume that pmatch[0] is already set, and pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */ static reg_errcode_t internal_function set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch, regmatch_t *pmatch, int fl_backtrack) { const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer; int idx, cur_node; re_node_set eps_via_nodes; struct re_fail_stack_t *fs; struct re_fail_stack_t fs_body = { 0, 2, NULL }; regmatch_t *prev_idx_match; int prev_idx_match_malloced = 0; #ifdef DEBUG assert (nmatch > 1); assert (mctx->state_log != NULL); #endif if (fl_backtrack) { fs = &fs_body; fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc); if (fs->stack == NULL) return REG_ESPACE; } else fs = NULL; cur_node = dfa->init_node; re_node_set_init_empty (&eps_via_nodes); if (__libc_use_alloca (nmatch * sizeof (regmatch_t))) prev_idx_match = (regmatch_t *) alloca (nmatch * sizeof (regmatch_t)); else { prev_idx_match = re_malloc (regmatch_t, nmatch); if (prev_idx_match == NULL) { free_fail_stack_return (fs); return REG_ESPACE; } prev_idx_match_malloced = 1; } memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch); for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;) { update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch); if (idx == pmatch[0].rm_eo && cur_node == mctx->last_node) { int reg_idx; if (fs) { for (reg_idx = 0; reg_idx < nmatch; ++reg_idx) if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1) break; if (reg_idx == nmatch) { re_node_set_free (&eps_via_nodes); if (prev_idx_match_malloced) re_free (prev_idx_match); return free_fail_stack_return (fs); } cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch, &eps_via_nodes); } else { re_node_set_free (&eps_via_nodes); if (prev_idx_match_malloced) re_free (prev_idx_match); return REG_NOERROR; } } /* Proceed to next node. */ cur_node = proceed_next_node (mctx, nmatch, pmatch, &idx, cur_node, &eps_via_nodes, fs); if (BE (cur_node < 0, 0)) { if (BE (cur_node == -2, 0)) { re_node_set_free (&eps_via_nodes); if (prev_idx_match_malloced) re_free (prev_idx_match); free_fail_stack_return (fs); return REG_ESPACE; } if (fs) cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch, &eps_via_nodes); else { re_node_set_free (&eps_via_nodes); if (prev_idx_match_malloced) re_free (prev_idx_match); return REG_NOMATCH; } } } re_node_set_free (&eps_via_nodes); if (prev_idx_match_malloced) re_free (prev_idx_match); return free_fail_stack_return (fs); } static reg_errcode_t internal_function free_fail_stack_return (struct re_fail_stack_t *fs) { if (fs) { int fs_idx; for (fs_idx = 0; fs_idx < fs->num; ++fs_idx) { re_node_set_free (&fs->stack[fs_idx].eps_via_nodes); re_free (fs->stack[fs_idx].regs); } re_free (fs->stack); } return REG_NOERROR; } static void internal_function update_regs (const re_dfa_t *dfa, regmatch_t *pmatch, regmatch_t *prev_idx_match, int cur_node, int cur_idx, int nmatch) { int type = dfa->nodes[cur_node].type; if (type == OP_OPEN_SUBEXP) { int reg_num = dfa->nodes[cur_node].opr.idx + 1; /* We are at the first node of this sub expression. */ if (reg_num < nmatch) { pmatch[reg_num].rm_so = cur_idx; pmatch[reg_num].rm_eo = -1; } } else if (type == OP_CLOSE_SUBEXP) { int reg_num = dfa->nodes[cur_node].opr.idx + 1; if (reg_num < nmatch) { /* We are at the last node of this sub expression. */ if (pmatch[reg_num].rm_so < cur_idx) { pmatch[reg_num].rm_eo = cur_idx; /* This is a non-empty match or we are not inside an optional subexpression. Accept this right away. */ memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch); } else { if (dfa->nodes[cur_node].opt_subexp && prev_idx_match[reg_num].rm_so != -1) /* We transited through an empty match for an optional subexpression, like (a?)*, and this is not the subexp's first match. Copy back the old content of the registers so that matches of an inner subexpression are undone as well, like in ((a?))*. */ memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch); else /* We completed a subexpression, but it may be part of an optional one, so do not update PREV_IDX_MATCH. */ pmatch[reg_num].rm_eo = cur_idx; } } } } /* This function checks the STATE_LOG from the SCTX->last_str_idx to 0 and sift the nodes in each states according to the following rules. Updated state_log will be wrote to STATE_LOG. Rules: We throw away the Node `a' in the STATE_LOG[STR_IDX] if... 1. When STR_IDX == MATCH_LAST(the last index in the state_log): If `a' isn't the LAST_NODE and `a' can't epsilon transit to the LAST_NODE, we throw away the node `a'. 2. When 0 <= STR_IDX < MATCH_LAST and `a' accepts string `s' and transit to `b': i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw away the node `a'. ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is thrown away, we throw away the node `a'. 3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b': i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the node `a'. ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away, we throw away the node `a'. */ #define STATE_NODE_CONTAINS(state,node) \ ((state) != NULL && re_node_set_contains (&(state)->nodes, node)) static reg_errcode_t internal_function sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx) { reg_errcode_t err; int null_cnt = 0; int str_idx = sctx->last_str_idx; re_node_set cur_dest; #ifdef DEBUG assert (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL); #endif /* Build sifted state_log[str_idx]. It has the nodes which can epsilon transit to the last_node and the last_node itself. */ err = re_node_set_init_1 (&cur_dest, sctx->last_node); if (BE (err != REG_NOERROR, 0)) return err; err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest); if (BE (err != REG_NOERROR, 0)) goto free_return; /* Then check each states in the state_log. */ while (str_idx > 0) { /* Update counters. */ null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0; if (null_cnt > mctx->max_mb_elem_len) { memset (sctx->sifted_states, '\0', sizeof (re_dfastate_t *) * str_idx); re_node_set_free (&cur_dest); return REG_NOERROR; } re_node_set_empty (&cur_dest); --str_idx; if (mctx->state_log[str_idx]) { err = build_sifted_states (mctx, sctx, str_idx, &cur_dest); if (BE (err != REG_NOERROR, 0)) goto free_return; } /* Add all the nodes which satisfy the following conditions: - It can epsilon transit to a node in CUR_DEST. - It is in CUR_SRC. And update state_log. */ err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest); if (BE (err != REG_NOERROR, 0)) goto free_return; } err = REG_NOERROR; free_return: re_node_set_free (&cur_dest); return err; } static reg_errcode_t internal_function build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, re_node_set *cur_dest) { const re_dfa_t *const dfa = mctx->dfa; const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes; int i; /* Then build the next sifted state. We build the next sifted state on `cur_dest', and update `sifted_states[str_idx]' with `cur_dest'. Note: `cur_dest' is the sifted state from `state_log[str_idx + 1]'. `cur_src' points the node_set of the old `state_log[str_idx]' (with the epsilon nodes pre-filtered out). */ for (i = 0; i < cur_src->nelem; i++) { int prev_node = cur_src->elems[i]; int naccepted = 0; int ret; #ifdef DEBUG re_token_type_t type = dfa->nodes[prev_node].type; assert (!IS_EPSILON_NODE (type)); #endif #ifdef RE_ENABLE_I18N /* If the node may accept `multi byte'. */ if (dfa->nodes[prev_node].accept_mb) naccepted = sift_states_iter_mb (mctx, sctx, prev_node, str_idx, sctx->last_str_idx); #endif /* RE_ENABLE_I18N */ /* We don't check backreferences here. See update_cur_sifted_state(). */ if (!naccepted && check_node_accept (mctx, dfa->nodes + prev_node, str_idx) && STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1], dfa->nexts[prev_node])) naccepted = 1; if (naccepted == 0) continue; if (sctx->limits.nelem) { int to_idx = str_idx + naccepted; if (check_dst_limits (mctx, &sctx->limits, dfa->nexts[prev_node], to_idx, prev_node, str_idx)) continue; } ret = re_node_set_insert (cur_dest, prev_node); if (BE (ret == -1, 0)) return REG_ESPACE; } return REG_NOERROR; } /* Helper functions. */ static reg_errcode_t internal_function clean_state_log_if_needed (re_match_context_t *mctx, int next_state_log_idx) { int top = mctx->state_log_top; if (next_state_log_idx >= mctx->input.bufs_len || (next_state_log_idx >= mctx->input.valid_len && mctx->input.valid_len < mctx->input.len)) { reg_errcode_t err; err = extend_buffers (mctx); if (BE (err != REG_NOERROR, 0)) return err; } if (top < next_state_log_idx) { memset (mctx->state_log + top + 1, '\0', sizeof (re_dfastate_t *) * (next_state_log_idx - top)); mctx->state_log_top = next_state_log_idx; } return REG_NOERROR; } static reg_errcode_t internal_function merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst, re_dfastate_t **src, int num) { int st_idx; reg_errcode_t err; for (st_idx = 0; st_idx < num; ++st_idx) { if (dst[st_idx] == NULL) dst[st_idx] = src[st_idx]; else if (src[st_idx] != NULL) { re_node_set merged_set; err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes, &src[st_idx]->nodes); if (BE (err != REG_NOERROR, 0)) return err; dst[st_idx] = re_acquire_state (&err, dfa, &merged_set); re_node_set_free (&merged_set); if (BE (err != REG_NOERROR, 0)) return err; } } return REG_NOERROR; } static reg_errcode_t internal_function update_cur_sifted_state (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, re_node_set *dest_nodes) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err = REG_NOERROR; const re_node_set *candidates; candidates = ((mctx->state_log[str_idx] == NULL) ? NULL : &mctx->state_log[str_idx]->nodes); if (dest_nodes->nelem == 0) sctx->sifted_states[str_idx] = NULL; else { if (candidates) { /* At first, add the nodes which can epsilon transit to a node in DEST_NODE. */ err = add_epsilon_src_nodes (dfa, dest_nodes, candidates); if (BE (err != REG_NOERROR, 0)) return err; /* Then, check the limitations in the current sift_context. */ if (sctx->limits.nelem) { err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits, mctx->bkref_ents, str_idx); if (BE (err != REG_NOERROR, 0)) return err; } } sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes); if (BE (err != REG_NOERROR, 0)) return err; } if (candidates && mctx->state_log[str_idx]->has_backref) { err = sift_states_bkref (mctx, sctx, str_idx, candidates); if (BE (err != REG_NOERROR, 0)) return err; } return REG_NOERROR; } static reg_errcode_t internal_function add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes, const re_node_set *candidates) { reg_errcode_t err = REG_NOERROR; int i; re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes); if (BE (err != REG_NOERROR, 0)) return err; if (!state->inveclosure.alloc) { err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem); if (BE (err != REG_NOERROR, 0)) return REG_ESPACE; for (i = 0; i < dest_nodes->nelem; i++) re_node_set_merge (&state->inveclosure, dfa->inveclosures + dest_nodes->elems[i]); } return re_node_set_add_intersect (dest_nodes, candidates, &state->inveclosure); } static reg_errcode_t internal_function sub_epsilon_src_nodes (const re_dfa_t *dfa, int node, re_node_set *dest_nodes, const re_node_set *candidates) { int ecl_idx; reg_errcode_t err; re_node_set *inv_eclosure = dfa->inveclosures + node; re_node_set except_nodes; re_node_set_init_empty (&except_nodes); for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx) { int cur_node = inv_eclosure->elems[ecl_idx]; if (cur_node == node) continue; if (IS_EPSILON_NODE (dfa->nodes[cur_node].type)) { int edst1 = dfa->edests[cur_node].elems[0]; int edst2 = ((dfa->edests[cur_node].nelem > 1) ? dfa->edests[cur_node].elems[1] : -1); if ((!re_node_set_contains (inv_eclosure, edst1) && re_node_set_contains (dest_nodes, edst1)) || (edst2 > 0 && !re_node_set_contains (inv_eclosure, edst2) && re_node_set_contains (dest_nodes, edst2))) { err = re_node_set_add_intersect (&except_nodes, candidates, dfa->inveclosures + cur_node); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&except_nodes); return err; } } } } for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx) { int cur_node = inv_eclosure->elems[ecl_idx]; if (!re_node_set_contains (&except_nodes, cur_node)) { int idx = re_node_set_contains (dest_nodes, cur_node) - 1; re_node_set_remove_at (dest_nodes, idx); } } re_node_set_free (&except_nodes); return REG_NOERROR; } static int internal_function check_dst_limits (const re_match_context_t *mctx, re_node_set *limits, int dst_node, int dst_idx, int src_node, int src_idx) { const re_dfa_t *const dfa = mctx->dfa; int lim_idx, src_pos, dst_pos; int dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx); int src_bkref_idx = search_cur_bkref_entry (mctx, src_idx); for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx) { int subexp_idx; struct re_backref_cache_entry *ent; ent = mctx->bkref_ents + limits->elems[lim_idx]; subexp_idx = dfa->nodes[ent->node].opr.idx; dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx], subexp_idx, dst_node, dst_idx, dst_bkref_idx); src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx], subexp_idx, src_node, src_idx, src_bkref_idx); /* In case of: <src> <dst> ( <subexp> ) ( <subexp> ) <src> <dst> ( <subexp1> <src> <subexp2> <dst> <subexp3> ) */ if (src_pos == dst_pos) continue; /* This is unrelated limitation. */ else return 1; } return 0; } static int internal_function check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries, int subexp_idx, int from_node, int bkref_idx) { const re_dfa_t *const dfa = mctx->dfa; const re_node_set *eclosures = dfa->eclosures + from_node; int node_idx; /* Else, we are on the boundary: examine the nodes on the epsilon closure. */ for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx) { int node = eclosures->elems[node_idx]; switch (dfa->nodes[node].type) { case OP_BACK_REF: if (bkref_idx != -1) { struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx; do { int dst, cpos; if (ent->node != node) continue; if (subexp_idx < BITSET_WORD_BITS && !(ent->eps_reachable_subexps_map & ((bitset_word_t) 1 << subexp_idx))) continue; /* Recurse trying to reach the OP_OPEN_SUBEXP and OP_CLOSE_SUBEXP cases below. But, if the destination node is the same node as the source node, don't recurse because it would cause an infinite loop: a regex that exhibits this behavior is ()\1*\1* */ dst = dfa->edests[node].elems[0]; if (dst == from_node) { if (boundaries & 1) return -1; else /* if (boundaries & 2) */ return 0; } cpos = check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx, dst, bkref_idx); if (cpos == -1 /* && (boundaries & 1) */) return -1; if (cpos == 0 && (boundaries & 2)) return 0; if (subexp_idx < BITSET_WORD_BITS) ent->eps_reachable_subexps_map &= ~((bitset_word_t) 1 << subexp_idx); } while (ent++->more); } break; case OP_OPEN_SUBEXP: if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx) return -1; break; case OP_CLOSE_SUBEXP: if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx) return 0; break; default: break; } } return (boundaries & 2) ? 1 : 0; } static int internal_function check_dst_limits_calc_pos (const re_match_context_t *mctx, int limit, int subexp_idx, int from_node, int str_idx, int bkref_idx) { struct re_backref_cache_entry *lim = mctx->bkref_ents + limit; int boundaries; /* If we are outside the range of the subexpression, return -1 or 1. */ if (str_idx < lim->subexp_from) return -1; if (lim->subexp_to < str_idx) return 1; /* If we are within the subexpression, return 0. */ boundaries = (str_idx == lim->subexp_from); boundaries |= (str_idx == lim->subexp_to) << 1; if (boundaries == 0) return 0; /* Else, examine epsilon closure. */ return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx, from_node, bkref_idx); } /* Check the limitations of sub expressions LIMITS, and remove the nodes which are against limitations from DEST_NODES. */ static reg_errcode_t internal_function check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes, const re_node_set *candidates, re_node_set *limits, struct re_backref_cache_entry *bkref_ents, int str_idx) { reg_errcode_t err; int node_idx, lim_idx; for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx) { int subexp_idx; struct re_backref_cache_entry *ent; ent = bkref_ents + limits->elems[lim_idx]; if (str_idx <= ent->subexp_from || ent->str_idx < str_idx) continue; /* This is unrelated limitation. */ subexp_idx = dfa->nodes[ent->node].opr.idx; if (ent->subexp_to == str_idx) { int ops_node = -1; int cls_node = -1; for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) { int node = dest_nodes->elems[node_idx]; re_token_type_t type = dfa->nodes[node].type; if (type == OP_OPEN_SUBEXP && subexp_idx == dfa->nodes[node].opr.idx) ops_node = node; else if (type == OP_CLOSE_SUBEXP && subexp_idx == dfa->nodes[node].opr.idx) cls_node = node; } /* Check the limitation of the open subexpression. */ /* Note that (ent->subexp_to = str_idx != ent->subexp_from). */ if (ops_node >= 0) { err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes, candidates); if (BE (err != REG_NOERROR, 0)) return err; } /* Check the limitation of the close subexpression. */ if (cls_node >= 0) for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) { int node = dest_nodes->elems[node_idx]; if (!re_node_set_contains (dfa->inveclosures + node, cls_node) && !re_node_set_contains (dfa->eclosures + node, cls_node)) { /* It is against this limitation. Remove it form the current sifted state. */ err = sub_epsilon_src_nodes (dfa, node, dest_nodes, candidates); if (BE (err != REG_NOERROR, 0)) return err; --node_idx; } } } else /* (ent->subexp_to != str_idx) */ { for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) { int node = dest_nodes->elems[node_idx]; re_token_type_t type = dfa->nodes[node].type; if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP) { if (subexp_idx != dfa->nodes[node].opr.idx) continue; /* It is against this limitation. Remove it form the current sifted state. */ err = sub_epsilon_src_nodes (dfa, node, dest_nodes, candidates); if (BE (err != REG_NOERROR, 0)) return err; } } } } return REG_NOERROR; } static reg_errcode_t internal_function sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx, int str_idx, const re_node_set *candidates) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err; int node_idx, node; re_sift_context_t local_sctx; int first_idx = search_cur_bkref_entry (mctx, str_idx); if (first_idx == -1) return REG_NOERROR; local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized. */ for (node_idx = 0; node_idx < candidates->nelem; ++node_idx) { int enabled_idx; re_token_type_t type; struct re_backref_cache_entry *entry; node = candidates->elems[node_idx]; type = dfa->nodes[node].type; /* Avoid infinite loop for the REs like "()\1+". */ if (node == sctx->last_node && str_idx == sctx->last_str_idx) continue; if (type != OP_BACK_REF) continue; entry = mctx->bkref_ents + first_idx; enabled_idx = first_idx; do { int subexp_len; int to_idx; int dst_node; int ret; re_dfastate_t *cur_state; if (entry->node != node) continue; subexp_len = entry->subexp_to - entry->subexp_from; to_idx = str_idx + subexp_len; dst_node = (subexp_len ? dfa->nexts[node] : dfa->edests[node].elems[0]); if (to_idx > sctx->last_str_idx || sctx->sifted_states[to_idx] == NULL || !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node) || check_dst_limits (mctx, &sctx->limits, node, str_idx, dst_node, to_idx)) continue; if (local_sctx.sifted_states == NULL) { local_sctx = *sctx; err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits); if (BE (err != REG_NOERROR, 0)) goto free_return; } local_sctx.last_node = node; local_sctx.last_str_idx = str_idx; ret = re_node_set_insert (&local_sctx.limits, enabled_idx); if (BE (ret < 0, 0)) { err = REG_ESPACE; goto free_return; } cur_state = local_sctx.sifted_states[str_idx]; err = sift_states_backward (mctx, &local_sctx); if (BE (err != REG_NOERROR, 0)) goto free_return; if (sctx->limited_states != NULL) { err = merge_state_array (dfa, sctx->limited_states, local_sctx.sifted_states, str_idx + 1); if (BE (err != REG_NOERROR, 0)) goto free_return; } local_sctx.sifted_states[str_idx] = cur_state; re_node_set_remove (&local_sctx.limits, enabled_idx); /* mctx->bkref_ents may have changed, reload the pointer. */ entry = mctx->bkref_ents + enabled_idx; } while (enabled_idx++, entry++->more); } err = REG_NOERROR; free_return: if (local_sctx.sifted_states != NULL) { re_node_set_free (&local_sctx.limits); } return err; } #ifdef RE_ENABLE_I18N static int internal_function sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx, int node_idx, int str_idx, int max_str_idx) { const re_dfa_t *const dfa = mctx->dfa; int naccepted; /* Check the node can accept `multi byte'. */ naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx); if (naccepted > 0 && str_idx + naccepted <= max_str_idx && !STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted], dfa->nexts[node_idx])) /* The node can't accept the `multi byte', or the destination was already thrown away, then the node could't accept the current input `multi byte'. */ naccepted = 0; /* Otherwise, it is sure that the node could accept `naccepted' bytes input. */ return naccepted; } #endif /* RE_ENABLE_I18N */ /* Functions for state transition. */ /* Return the next state to which the current state STATE will transit by accepting the current input byte, and update STATE_LOG if necessary. If STATE can accept a multibyte char/collating element/back reference update the destination of STATE_LOG. */ static re_dfastate_t * internal_function transit_state (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *state) { re_dfastate_t **trtable; unsigned char ch; #ifdef RE_ENABLE_I18N /* If the current state can accept multibyte. */ if (BE (state->accept_mb, 0)) { *err = transit_state_mb (mctx, state); if (BE (*err != REG_NOERROR, 0)) return NULL; } #endif /* RE_ENABLE_I18N */ /* Then decide the next state with the single byte. */ #if 0 if (0) /* don't use transition table */ return transit_state_sb (err, mctx, state); #endif /* Use transition table */ ch = re_string_fetch_byte (&mctx->input); for (;;) { trtable = state->trtable; if (BE (trtable != NULL, 1)) return trtable[ch]; trtable = state->word_trtable; if (BE (trtable != NULL, 1)) { unsigned int context; context = re_string_context_at (&mctx->input, re_string_cur_idx (&mctx->input) - 1, mctx->eflags); if (IS_WORD_CONTEXT (context)) return trtable[ch + SBC_MAX]; else return trtable[ch]; } if (!build_trtable (mctx->dfa, state)) { *err = REG_ESPACE; return NULL; } /* Retry, we now have a transition table. */ } } /* Update the state_log if we need */ re_dfastate_t * internal_function merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *next_state) { const re_dfa_t *const dfa = mctx->dfa; int cur_idx = re_string_cur_idx (&mctx->input); if (cur_idx > mctx->state_log_top) { mctx->state_log[cur_idx] = next_state; mctx->state_log_top = cur_idx; } else if (mctx->state_log[cur_idx] == 0) { mctx->state_log[cur_idx] = next_state; } else { re_dfastate_t *pstate; unsigned int context; re_node_set next_nodes, *log_nodes, *table_nodes = NULL; /* If (state_log[cur_idx] != 0), it implies that cur_idx is the destination of a multibyte char/collating element/ back reference. Then the next state is the union set of these destinations and the results of the transition table. */ pstate = mctx->state_log[cur_idx]; log_nodes = pstate->entrance_nodes; if (next_state != NULL) { table_nodes = next_state->entrance_nodes; *err = re_node_set_init_union (&next_nodes, table_nodes, log_nodes); if (BE (*err != REG_NOERROR, 0)) return NULL; } else next_nodes = *log_nodes; /* Note: We already add the nodes of the initial state, then we don't need to add them here. */ context = re_string_context_at (&mctx->input, re_string_cur_idx (&mctx->input) - 1, mctx->eflags); next_state = mctx->state_log[cur_idx] = re_acquire_state_context (err, dfa, &next_nodes, context); /* We don't need to check errors here, since the return value of this function is next_state and ERR is already set. */ if (table_nodes != NULL) re_node_set_free (&next_nodes); } if (BE (dfa->nbackref, 0) && next_state != NULL) { /* Check OP_OPEN_SUBEXP in the current state in case that we use them later. We must check them here, since the back references in the next state might use them. */ *err = check_subexp_matching_top (mctx, &next_state->nodes, cur_idx); if (BE (*err != REG_NOERROR, 0)) return NULL; /* If the next state has back references. */ if (next_state->has_backref) { *err = transit_state_bkref (mctx, &next_state->nodes); if (BE (*err != REG_NOERROR, 0)) return NULL; next_state = mctx->state_log[cur_idx]; } } return next_state; } /* Skip bytes in the input that correspond to part of a multi-byte match, then look in the log for a state from which to restart matching. */ re_dfastate_t * internal_function find_recover_state (reg_errcode_t *err, re_match_context_t *mctx) { re_dfastate_t *cur_state; do { int max = mctx->state_log_top; int cur_str_idx = re_string_cur_idx (&mctx->input); do { if (++cur_str_idx > max) return NULL; re_string_skip_bytes (&mctx->input, 1); } while (mctx->state_log[cur_str_idx] == NULL); cur_state = merge_state_with_log (err, mctx, NULL); } while (*err == REG_NOERROR && cur_state == NULL); return cur_state; } /* Helper functions for transit_state. */ /* From the node set CUR_NODES, pick up the nodes whose types are OP_OPEN_SUBEXP and which have corresponding back references in the regular expression. And register them to use them later for evaluating the correspoding back references. */ static reg_errcode_t internal_function check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes, int str_idx) { const re_dfa_t *const dfa = mctx->dfa; int node_idx; reg_errcode_t err; /* TODO: This isn't efficient. Because there might be more than one nodes whose types are OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all nodes. E.g. RE: (a){2} */ for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx) { int node = cur_nodes->elems[node_idx]; if (dfa->nodes[node].type == OP_OPEN_SUBEXP && dfa->nodes[node].opr.idx < BITSET_WORD_BITS && (dfa->used_bkref_map & ((bitset_word_t) 1 << dfa->nodes[node].opr.idx))) { err = match_ctx_add_subtop (mctx, node, str_idx); if (BE (err != REG_NOERROR, 0)) return err; } } return REG_NOERROR; } #if 0 /* Return the next state to which the current state STATE will transit by accepting the current input byte. */ static re_dfastate_t * transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx, re_dfastate_t *state) { const re_dfa_t *const dfa = mctx->dfa; re_node_set next_nodes; re_dfastate_t *next_state; int node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input); unsigned int context; *err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1); if (BE (*err != REG_NOERROR, 0)) return NULL; for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt) { int cur_node = state->nodes.elems[node_cnt]; if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx)) { *err = re_node_set_merge (&next_nodes, dfa->eclosures + dfa->nexts[cur_node]); if (BE (*err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return NULL; } } } context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags); next_state = re_acquire_state_context (err, dfa, &next_nodes, context); /* We don't need to check errors here, since the return value of this function is next_state and ERR is already set. */ re_node_set_free (&next_nodes); re_string_skip_bytes (&mctx->input, 1); return next_state; } #endif #ifdef RE_ENABLE_I18N static reg_errcode_t internal_function transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err; int i; for (i = 0; i < pstate->nodes.nelem; ++i) { re_node_set dest_nodes, *new_nodes; int cur_node_idx = pstate->nodes.elems[i]; int naccepted, dest_idx; unsigned int context; re_dfastate_t *dest_state; if (!dfa->nodes[cur_node_idx].accept_mb) continue; if (dfa->nodes[cur_node_idx].constraint) { context = re_string_context_at (&mctx->input, re_string_cur_idx (&mctx->input), mctx->eflags); if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint, context)) continue; } /* How many bytes the node can accept? */ naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input, re_string_cur_idx (&mctx->input)); if (naccepted == 0) continue; /* The node can accepts `naccepted' bytes. */ dest_idx = re_string_cur_idx (&mctx->input) + naccepted; mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted : mctx->max_mb_elem_len); err = clean_state_log_if_needed (mctx, dest_idx); if (BE (err != REG_NOERROR, 0)) return err; #ifdef DEBUG assert (dfa->nexts[cur_node_idx] != -1); #endif new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx]; dest_state = mctx->state_log[dest_idx]; if (dest_state == NULL) dest_nodes = *new_nodes; else { err = re_node_set_init_union (&dest_nodes, dest_state->entrance_nodes, new_nodes); if (BE (err != REG_NOERROR, 0)) return err; } context = re_string_context_at (&mctx->input, dest_idx - 1, mctx->eflags); mctx->state_log[dest_idx] = re_acquire_state_context (&err, dfa, &dest_nodes, context); if (dest_state != NULL) re_node_set_free (&dest_nodes); if (BE (mctx->state_log[dest_idx] == NULL && err != REG_NOERROR, 0)) return err; } return REG_NOERROR; } #endif /* RE_ENABLE_I18N */ static reg_errcode_t internal_function transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err; int i; int cur_str_idx = re_string_cur_idx (&mctx->input); for (i = 0; i < nodes->nelem; ++i) { int dest_str_idx, prev_nelem, bkc_idx; int node_idx = nodes->elems[i]; unsigned int context; const re_token_t *node = dfa->nodes + node_idx; re_node_set *new_dest_nodes; /* Check whether `node' is a backreference or not. */ if (node->type != OP_BACK_REF) continue; if (node->constraint) { context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags); if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context)) continue; } /* `node' is a backreference. Check the substring which the substring matched. */ bkc_idx = mctx->nbkref_ents; err = get_subexp (mctx, node_idx, cur_str_idx); if (BE (err != REG_NOERROR, 0)) goto free_return; /* And add the epsilon closures (which is `new_dest_nodes') of the backreference to appropriate state_log. */ #ifdef DEBUG assert (dfa->nexts[node_idx] != -1); #endif for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx) { int subexp_len; re_dfastate_t *dest_state; struct re_backref_cache_entry *bkref_ent; bkref_ent = mctx->bkref_ents + bkc_idx; if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx) continue; subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from; new_dest_nodes = (subexp_len == 0 ? dfa->eclosures + dfa->edests[node_idx].elems[0] : dfa->eclosures + dfa->nexts[node_idx]); dest_str_idx = (cur_str_idx + bkref_ent->subexp_to - bkref_ent->subexp_from); context = re_string_context_at (&mctx->input, dest_str_idx - 1, mctx->eflags); dest_state = mctx->state_log[dest_str_idx]; prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0 : mctx->state_log[cur_str_idx]->nodes.nelem); /* Add `new_dest_node' to state_log. */ if (dest_state == NULL) { mctx->state_log[dest_str_idx] = re_acquire_state_context (&err, dfa, new_dest_nodes, context); if (BE (mctx->state_log[dest_str_idx] == NULL && err != REG_NOERROR, 0)) goto free_return; } else { re_node_set dest_nodes; err = re_node_set_init_union (&dest_nodes, dest_state->entrance_nodes, new_dest_nodes); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&dest_nodes); goto free_return; } mctx->state_log[dest_str_idx] = re_acquire_state_context (&err, dfa, &dest_nodes, context); re_node_set_free (&dest_nodes); if (BE (mctx->state_log[dest_str_idx] == NULL && err != REG_NOERROR, 0)) goto free_return; } /* We need to check recursively if the backreference can epsilon transit. */ if (subexp_len == 0 && mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem) { err = check_subexp_matching_top (mctx, new_dest_nodes, cur_str_idx); if (BE (err != REG_NOERROR, 0)) goto free_return; err = transit_state_bkref (mctx, new_dest_nodes); if (BE (err != REG_NOERROR, 0)) goto free_return; } } } err = REG_NOERROR; free_return: return err; } /* Enumerate all the candidates which the backreference BKREF_NODE can match at BKREF_STR_IDX, and register them by match_ctx_add_entry(). Note that we might collect inappropriate candidates here. However, the cost of checking them strictly here is too high, then we delay these checking for prune_impossible_nodes(). */ static reg_errcode_t internal_function get_subexp (re_match_context_t *mctx, int bkref_node, int bkref_str_idx) { const re_dfa_t *const dfa = mctx->dfa; int subexp_num, sub_top_idx; const char *buf = (const char *) re_string_get_buffer (&mctx->input); /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX. */ int cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx); if (cache_idx != -1) { const struct re_backref_cache_entry *entry = mctx->bkref_ents + cache_idx; do if (entry->node == bkref_node) return REG_NOERROR; /* We already checked it. */ while (entry++->more); } subexp_num = dfa->nodes[bkref_node].opr.idx; /* For each sub expression */ for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx) { reg_errcode_t err; re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx]; re_sub_match_last_t *sub_last; int sub_last_idx, sl_str, bkref_str_off; if (dfa->nodes[sub_top->node].opr.idx != subexp_num) continue; /* It isn't related. */ sl_str = sub_top->str_idx; bkref_str_off = bkref_str_idx; /* At first, check the last node of sub expressions we already evaluated. */ for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx) { int sl_str_diff; sub_last = sub_top->lasts[sub_last_idx]; sl_str_diff = sub_last->str_idx - sl_str; /* The matched string by the sub expression match with the substring at the back reference? */ if (sl_str_diff > 0) { if (BE (bkref_str_off + sl_str_diff > mctx->input.valid_len, 0)) { /* Not enough chars for a successful match. */ if (bkref_str_off + sl_str_diff > mctx->input.len) break; err = clean_state_log_if_needed (mctx, bkref_str_off + sl_str_diff); if (BE (err != REG_NOERROR, 0)) return err; buf = (const char *) re_string_get_buffer (&mctx->input); } if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0) /* We don't need to search this sub expression any more. */ break; } bkref_str_off += sl_str_diff; sl_str += sl_str_diff; err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node, bkref_str_idx); /* Reload buf, since the preceding call might have reallocated the buffer. */ buf = (const char *) re_string_get_buffer (&mctx->input); if (err == REG_NOMATCH) continue; if (BE (err != REG_NOERROR, 0)) return err; } if (sub_last_idx < sub_top->nlasts) continue; if (sub_last_idx > 0) ++sl_str; /* Then, search for the other last nodes of the sub expression. */ for (; sl_str <= bkref_str_idx; ++sl_str) { int cls_node, sl_str_off; const re_node_set *nodes; sl_str_off = sl_str - sub_top->str_idx; /* The matched string by the sub expression match with the substring at the back reference? */ if (sl_str_off > 0) { if (BE (bkref_str_off >= mctx->input.valid_len, 0)) { /* If we are at the end of the input, we cannot match. */ if (bkref_str_off >= mctx->input.len) break; err = extend_buffers (mctx); if (BE (err != REG_NOERROR, 0)) return err; buf = (const char *) re_string_get_buffer (&mctx->input); } if (buf [bkref_str_off++] != buf[sl_str - 1]) break; /* We don't need to search this sub expression any more. */ } if (mctx->state_log[sl_str] == NULL) continue; /* Does this state have a ')' of the sub expression? */ nodes = &mctx->state_log[sl_str]->nodes; cls_node = find_subexp_node (dfa, nodes, subexp_num, OP_CLOSE_SUBEXP); if (cls_node == -1) continue; /* No. */ if (sub_top->path == NULL) { sub_top->path = calloc (sizeof (state_array_t), sl_str - sub_top->str_idx + 1); if (sub_top->path == NULL) return REG_ESPACE; } /* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node in the current context? */ err = check_arrival (mctx, sub_top->path, sub_top->node, sub_top->str_idx, cls_node, sl_str, OP_CLOSE_SUBEXP); if (err == REG_NOMATCH) continue; if (BE (err != REG_NOERROR, 0)) return err; sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str); if (BE (sub_last == NULL, 0)) return REG_ESPACE; err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node, bkref_str_idx); if (err == REG_NOMATCH) continue; } } return REG_NOERROR; } /* Helper functions for get_subexp(). */ /* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR. If it can arrive, register the sub expression expressed with SUB_TOP and SUB_LAST. */ static reg_errcode_t internal_function get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top, re_sub_match_last_t *sub_last, int bkref_node, int bkref_str) { reg_errcode_t err; int to_idx; /* Can the subexpression arrive the back reference? */ err = check_arrival (mctx, &sub_last->path, sub_last->node, sub_last->str_idx, bkref_node, bkref_str, OP_OPEN_SUBEXP); if (err != REG_NOERROR) return err; err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx, sub_last->str_idx); if (BE (err != REG_NOERROR, 0)) return err; to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx; return clean_state_log_if_needed (mctx, to_idx); } /* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX. Search '(' if FL_OPEN, or search ')' otherwise. TODO: This function isn't efficient... Because there might be more than one nodes whose types are OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all nodes. E.g. RE: (a){2} */ static int internal_function find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes, int subexp_idx, int type) { int cls_idx; for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx) { int cls_node = nodes->elems[cls_idx]; const re_token_t *node = dfa->nodes + cls_node; if (node->type == type && node->opr.idx == subexp_idx) return cls_node; } return -1; } /* Check whether the node TOP_NODE at TOP_STR can arrive to the node LAST_NODE at LAST_STR. We record the path onto PATH since it will be heavily reused. Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */ static reg_errcode_t internal_function check_arrival (re_match_context_t *mctx, state_array_t *path, int top_node, int top_str, int last_node, int last_str, int type) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err = REG_NOERROR; int subexp_num, backup_cur_idx, str_idx, null_cnt; re_dfastate_t *cur_state = NULL; re_node_set *cur_nodes, next_nodes; re_dfastate_t **backup_state_log; unsigned int context; subexp_num = dfa->nodes[top_node].opr.idx; /* Extend the buffer if we need. */ if (BE (path->alloc < last_str + mctx->max_mb_elem_len + 1, 0)) { re_dfastate_t **new_array; int old_alloc = path->alloc; path->alloc += last_str + mctx->max_mb_elem_len + 1; new_array = re_realloc (path->array, re_dfastate_t *, path->alloc); if (BE (new_array == NULL, 0)) { path->alloc = old_alloc; return REG_ESPACE; } path->array = new_array; memset (new_array + old_alloc, '\0', sizeof (re_dfastate_t *) * (path->alloc - old_alloc)); } str_idx = path->next_idx ? path->next_idx : top_str; /* Temporary modify MCTX. */ backup_state_log = mctx->state_log; backup_cur_idx = mctx->input.cur_idx; mctx->state_log = path->array; mctx->input.cur_idx = str_idx; /* Setup initial node set. */ context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags); if (str_idx == top_str) { err = re_node_set_init_1 (&next_nodes, top_node); if (BE (err != REG_NOERROR, 0)) return err; err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } } else { cur_state = mctx->state_log[str_idx]; if (cur_state && cur_state->has_backref) { err = re_node_set_init_copy (&next_nodes, &cur_state->nodes); if (BE (err != REG_NOERROR, 0)) return err; } else re_node_set_init_empty (&next_nodes); } if (str_idx == top_str || (cur_state && cur_state->has_backref)) { if (next_nodes.nelem) { err = expand_bkref_cache (mctx, &next_nodes, str_idx, subexp_num, type); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } } cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context); if (BE (cur_state == NULL && err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } mctx->state_log[str_idx] = cur_state; } for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;) { re_node_set_empty (&next_nodes); if (mctx->state_log[str_idx + 1]) { err = re_node_set_merge (&next_nodes, &mctx->state_log[str_idx + 1]->nodes); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } } if (cur_state) { err = check_arrival_add_next_nodes (mctx, str_idx, &cur_state->non_eps_nodes, &next_nodes); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } } ++str_idx; if (next_nodes.nelem) { err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } err = expand_bkref_cache (mctx, &next_nodes, str_idx, subexp_num, type); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } } context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags); cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context); if (BE (cur_state == NULL && err != REG_NOERROR, 0)) { re_node_set_free (&next_nodes); return err; } mctx->state_log[str_idx] = cur_state; null_cnt = cur_state == NULL ? null_cnt + 1 : 0; } re_node_set_free (&next_nodes); cur_nodes = (mctx->state_log[last_str] == NULL ? NULL : &mctx->state_log[last_str]->nodes); path->next_idx = str_idx; /* Fix MCTX. */ mctx->state_log = backup_state_log; mctx->input.cur_idx = backup_cur_idx; /* Then check the current node set has the node LAST_NODE. */ if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node)) return REG_NOERROR; return REG_NOMATCH; } /* Helper functions for check_arrival. */ /* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them to NEXT_NODES. TODO: This function is similar to the functions transit_state*(), however this function has many additional works. Can't we unify them? */ static reg_errcode_t internal_function check_arrival_add_next_nodes (re_match_context_t *mctx, int str_idx, re_node_set *cur_nodes, re_node_set *next_nodes) { const re_dfa_t *const dfa = mctx->dfa; int result; int cur_idx; reg_errcode_t err = REG_NOERROR; re_node_set union_set; re_node_set_init_empty (&union_set); for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx) { int naccepted = 0; int cur_node = cur_nodes->elems[cur_idx]; #ifdef DEBUG re_token_type_t type = dfa->nodes[cur_node].type; assert (!IS_EPSILON_NODE (type)); #endif #ifdef RE_ENABLE_I18N /* If the node may accept `multi byte'. */ if (dfa->nodes[cur_node].accept_mb) { naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input, str_idx); if (naccepted > 1) { re_dfastate_t *dest_state; int next_node = dfa->nexts[cur_node]; int next_idx = str_idx + naccepted; dest_state = mctx->state_log[next_idx]; re_node_set_empty (&union_set); if (dest_state) { err = re_node_set_merge (&union_set, &dest_state->nodes); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&union_set); return err; } } result = re_node_set_insert (&union_set, next_node); if (BE (result < 0, 0)) { re_node_set_free (&union_set); return REG_ESPACE; } mctx->state_log[next_idx] = re_acquire_state (&err, dfa, &union_set); if (BE (mctx->state_log[next_idx] == NULL && err != REG_NOERROR, 0)) { re_node_set_free (&union_set); return err; } } } #endif /* RE_ENABLE_I18N */ if (naccepted || check_node_accept (mctx, dfa->nodes + cur_node, str_idx)) { result = re_node_set_insert (next_nodes, dfa->nexts[cur_node]); if (BE (result < 0, 0)) { re_node_set_free (&union_set); return REG_ESPACE; } } } re_node_set_free (&union_set); return REG_NOERROR; } /* For all the nodes in CUR_NODES, add the epsilon closures of them to CUR_NODES, however exclude the nodes which are: - inside the sub expression whose number is EX_SUBEXP, if FL_OPEN. - out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN. */ static reg_errcode_t internal_function check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes, int ex_subexp, int type) { reg_errcode_t err; int idx, outside_node; re_node_set new_nodes; #ifdef DEBUG assert (cur_nodes->nelem); #endif err = re_node_set_alloc (&new_nodes, cur_nodes->nelem); if (BE (err != REG_NOERROR, 0)) return err; /* Create a new node set NEW_NODES with the nodes which are epsilon closures of the node in CUR_NODES. */ for (idx = 0; idx < cur_nodes->nelem; ++idx) { int cur_node = cur_nodes->elems[idx]; const re_node_set *eclosure = dfa->eclosures + cur_node; outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type); if (outside_node == -1) { /* There are no problematic nodes, just merge them. */ err = re_node_set_merge (&new_nodes, eclosure); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&new_nodes); return err; } } else { /* There are problematic nodes, re-calculate incrementally. */ err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node, ex_subexp, type); if (BE (err != REG_NOERROR, 0)) { re_node_set_free (&new_nodes); return err; } } } re_node_set_free (cur_nodes); *cur_nodes = new_nodes; return REG_NOERROR; } /* Helper function for check_arrival_expand_ecl. Check incrementally the epsilon closure of TARGET, and if it isn't problematic append it to DST_NODES. */ static reg_errcode_t internal_function check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes, int target, int ex_subexp, int type) { int cur_node; for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);) { int err; if (dfa->nodes[cur_node].type == type && dfa->nodes[cur_node].opr.idx == ex_subexp) { if (type == OP_CLOSE_SUBEXP) { err = re_node_set_insert (dst_nodes, cur_node); if (BE (err == -1, 0)) return REG_ESPACE; } break; } err = re_node_set_insert (dst_nodes, cur_node); if (BE (err == -1, 0)) return REG_ESPACE; if (dfa->edests[cur_node].nelem == 0) break; if (dfa->edests[cur_node].nelem == 2) { err = check_arrival_expand_ecl_sub (dfa, dst_nodes, dfa->edests[cur_node].elems[1], ex_subexp, type); if (BE (err != REG_NOERROR, 0)) return err; } cur_node = dfa->edests[cur_node].elems[0]; } return REG_NOERROR; } /* For all the back references in the current state, calculate the destination of the back references by the appropriate entry in MCTX->BKREF_ENTS. */ static reg_errcode_t internal_function expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes, int cur_str, int subexp_num, int type) { const re_dfa_t *const dfa = mctx->dfa; reg_errcode_t err; int cache_idx_start = search_cur_bkref_entry (mctx, cur_str); struct re_backref_cache_entry *ent; if (cache_idx_start == -1) return REG_NOERROR; restart: ent = mctx->bkref_ents + cache_idx_start; do { int to_idx, next_node; /* Is this entry ENT is appropriate? */ if (!re_node_set_contains (cur_nodes, ent->node)) continue; /* No. */ to_idx = cur_str + ent->subexp_to - ent->subexp_from; /* Calculate the destination of the back reference, and append it to MCTX->STATE_LOG. */ if (to_idx == cur_str) { /* The backreference did epsilon transit, we must re-check all the node in the current state. */ re_node_set new_dests; reg_errcode_t err2, err3; next_node = dfa->edests[ent->node].elems[0]; if (re_node_set_contains (cur_nodes, next_node)) continue; err = re_node_set_init_1 (&new_dests, next_node); err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type); err3 = re_node_set_merge (cur_nodes, &new_dests); re_node_set_free (&new_dests); if (BE (err != REG_NOERROR || err2 != REG_NOERROR || err3 != REG_NOERROR, 0)) { err = (err != REG_NOERROR ? err : (err2 != REG_NOERROR ? err2 : err3)); return err; } /* TODO: It is still inefficient... */ goto restart; } else { re_node_set union_set; next_node = dfa->nexts[ent->node]; if (mctx->state_log[to_idx]) { int ret; if (re_node_set_contains (&mctx->state_log[to_idx]->nodes, next_node)) continue; err = re_node_set_init_copy (&union_set, &mctx->state_log[to_idx]->nodes); ret = re_node_set_insert (&union_set, next_node); if (BE (err != REG_NOERROR || ret < 0, 0)) { re_node_set_free (&union_set); err = err != REG_NOERROR ? err : REG_ESPACE; return err; } } else { err = re_node_set_init_1 (&union_set, next_node); if (BE (err != REG_NOERROR, 0)) return err; } mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set); re_node_set_free (&union_set); if (BE (mctx->state_log[to_idx] == NULL && err != REG_NOERROR, 0)) return err; } } while (ent++->more); return REG_NOERROR; } /* Build transition table for the state. Return 1 if succeeded, otherwise return NULL. */ static int internal_function build_trtable (const re_dfa_t *dfa, re_dfastate_t *state) { reg_errcode_t err; int i, j, ch, need_word_trtable = 0; bitset_word_t elem, mask; bool dests_node_malloced = false; bool dest_states_malloced = false; int ndests; /* Number of the destination states from `state'. */ re_dfastate_t **trtable; re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl; re_node_set follows, *dests_node; bitset_t *dests_ch; bitset_t acceptable; struct dests_alloc { re_node_set dests_node[SBC_MAX]; bitset_t dests_ch[SBC_MAX]; } *dests_alloc; /* We build DFA states which corresponds to the destination nodes from `state'. `dests_node[i]' represents the nodes which i-th destination state contains, and `dests_ch[i]' represents the characters which i-th destination state accepts. */ if (__libc_use_alloca (sizeof (struct dests_alloc))) dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc)); else { dests_alloc = re_malloc (struct dests_alloc, 1); if (BE (dests_alloc == NULL, 0)) return 0; dests_node_malloced = true; } dests_node = dests_alloc->dests_node; dests_ch = dests_alloc->dests_ch; /* Initialize transiton table. */ state->word_trtable = state->trtable = NULL; /* At first, group all nodes belonging to `state' into several destinations. */ ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch); if (BE (ndests <= 0, 0)) { if (dests_node_malloced) free (dests_alloc); /* Return 0 in case of an error, 1 otherwise. */ if (ndests == 0) { state->trtable = (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX); return 1; } return 0; } err = re_node_set_alloc (&follows, ndests + 1); if (BE (err != REG_NOERROR, 0)) goto out_free; if (__libc_use_alloca ((sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX + ndests * 3 * sizeof (re_dfastate_t *))) dest_states = (re_dfastate_t **) alloca (ndests * 3 * sizeof (re_dfastate_t *)); else { dest_states = (re_dfastate_t **) malloc (ndests * 3 * sizeof (re_dfastate_t *)); if (BE (dest_states == NULL, 0)) { out_free: if (dest_states_malloced) free (dest_states); re_node_set_free (&follows); for (i = 0; i < ndests; ++i) re_node_set_free (dests_node + i); if (dests_node_malloced) free (dests_alloc); return 0; } dest_states_malloced = true; } dest_states_word = dest_states + ndests; dest_states_nl = dest_states_word + ndests; bitset_empty (acceptable); /* Then build the states for all destinations. */ for (i = 0; i < ndests; ++i) { int next_node; re_node_set_empty (&follows); /* Merge the follows of this destination states. */ for (j = 0; j < dests_node[i].nelem; ++j) { next_node = dfa->nexts[dests_node[i].elems[j]]; if (next_node != -1) { err = re_node_set_merge (&follows, dfa->eclosures + next_node); if (BE (err != REG_NOERROR, 0)) goto out_free; } } dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0); if (BE (dest_states[i] == NULL && err != REG_NOERROR, 0)) goto out_free; /* If the new state has context constraint, build appropriate states for these contexts. */ if (dest_states[i]->has_constraint) { dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows, CONTEXT_WORD); if (BE (dest_states_word[i] == NULL && err != REG_NOERROR, 0)) goto out_free; if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1) need_word_trtable = 1; dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows, CONTEXT_NEWLINE); if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0)) goto out_free; } else { dest_states_word[i] = dest_states[i]; dest_states_nl[i] = dest_states[i]; } bitset_merge (acceptable, dests_ch[i]); } if (!BE (need_word_trtable, 0)) { /* We don't care about whether the following character is a word character, or we are in a single-byte character set so we can discern by looking at the character code: allocate a 256-entry transition table. */ trtable = state->trtable = (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX); if (BE (trtable == NULL, 0)) goto out_free; /* For all characters ch...: */ for (i = 0; i < BITSET_WORDS; ++i) for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1; elem; mask <<= 1, elem >>= 1, ++ch) if (BE (elem & 1, 0)) { /* There must be exactly one destination which accepts character ch. See group_nodes_into_DFAstates. */ for (j = 0; (dests_ch[j][i] & mask) == 0; ++j) ; /* j-th destination accepts the word character ch. */ if (dfa->word_char[i] & mask) trtable[ch] = dest_states_word[j]; else trtable[ch] = dest_states[j]; } } else { /* We care about whether the following character is a word character, and we are in a multi-byte character set: discern by looking at the character code: build two 256-entry transition tables, one starting at trtable[0] and one starting at trtable[SBC_MAX]. */ trtable = state->word_trtable = (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), 2 * SBC_MAX); if (BE (trtable == NULL, 0)) goto out_free; /* For all characters ch...: */ for (i = 0; i < BITSET_WORDS; ++i) for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1; elem; mask <<= 1, elem >>= 1, ++ch) if (BE (elem & 1, 0)) { /* There must be exactly one destination which accepts character ch. See group_nodes_into_DFAstates. */ for (j = 0; (dests_ch[j][i] & mask) == 0; ++j) ; /* j-th destination accepts the word character ch. */ trtable[ch] = dest_states[j]; trtable[ch + SBC_MAX] = dest_states_word[j]; } } /* new line */ if (bitset_contain (acceptable, NEWLINE_CHAR)) { /* The current state accepts newline character. */ for (j = 0; j < ndests; ++j) if (bitset_contain (dests_ch[j], NEWLINE_CHAR)) { /* k-th destination accepts newline character. */ trtable[NEWLINE_CHAR] = dest_states_nl[j]; if (need_word_trtable) trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j]; /* There must be only one destination which accepts newline. See group_nodes_into_DFAstates. */ break; } } if (dest_states_malloced) free (dest_states); re_node_set_free (&follows); for (i = 0; i < ndests; ++i) re_node_set_free (dests_node + i); if (dests_node_malloced) free (dests_alloc); return 1; } /* Group all nodes belonging to STATE into several destinations. Then for all destinations, set the nodes belonging to the destination to DESTS_NODE[i] and set the characters accepted by the destination to DEST_CH[i]. This function return the number of destinations. */ static int internal_function group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state, re_node_set *dests_node, bitset_t *dests_ch) { reg_errcode_t err; int result; int i, j, k; int ndests; /* Number of the destinations from `state'. */ bitset_t accepts; /* Characters a node can accept. */ const re_node_set *cur_nodes = &state->nodes; bitset_empty (accepts); ndests = 0; /* For all the nodes belonging to `state', */ for (i = 0; i < cur_nodes->nelem; ++i) { re_token_t *node = &dfa->nodes[cur_nodes->elems[i]]; re_token_type_t type = node->type; unsigned int constraint = node->constraint; /* Enumerate all single byte character this node can accept. */ if (type == CHARACTER) bitset_set (accepts, node->opr.c); else if (type == SIMPLE_BRACKET) { bitset_merge (accepts, node->opr.sbcset); } else if (type == OP_PERIOD) { #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) bitset_merge (accepts, dfa->sb_char); else #endif bitset_set_all (accepts); if (!(dfa->syntax & RE_DOT_NEWLINE)) bitset_clear (accepts, '\n'); if (dfa->syntax & RE_DOT_NOT_NULL) bitset_clear (accepts, '\0'); } #ifdef RE_ENABLE_I18N else if (type == OP_UTF8_PERIOD) { memset (accepts, '\xff', sizeof (bitset_t) / 2); if (!(dfa->syntax & RE_DOT_NEWLINE)) bitset_clear (accepts, '\n'); if (dfa->syntax & RE_DOT_NOT_NULL) bitset_clear (accepts, '\0'); } #endif else continue; /* Check the `accepts' and sift the characters which are not match it the context. */ if (constraint) { if (constraint & NEXT_NEWLINE_CONSTRAINT) { bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR); bitset_empty (accepts); if (accepts_newline) bitset_set (accepts, NEWLINE_CHAR); else continue; } if (constraint & NEXT_ENDBUF_CONSTRAINT) { bitset_empty (accepts); continue; } if (constraint & NEXT_WORD_CONSTRAINT) { bitset_word_t any_set = 0; if (type == CHARACTER && !node->word_char) { bitset_empty (accepts); continue; } #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) for (j = 0; j < BITSET_WORDS; ++j) any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j])); else #endif for (j = 0; j < BITSET_WORDS; ++j) any_set |= (accepts[j] &= dfa->word_char[j]); if (!any_set) continue; } if (constraint & NEXT_NOTWORD_CONSTRAINT) { bitset_word_t any_set = 0; if (type == CHARACTER && node->word_char) { bitset_empty (accepts); continue; } #ifdef RE_ENABLE_I18N if (dfa->mb_cur_max > 1) for (j = 0; j < BITSET_WORDS; ++j) any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j])); else #endif for (j = 0; j < BITSET_WORDS; ++j) any_set |= (accepts[j] &= ~dfa->word_char[j]); if (!any_set) continue; } } /* Then divide `accepts' into DFA states, or create a new state. Above, we make sure that accepts is not empty. */ for (j = 0; j < ndests; ++j) { bitset_t intersec; /* Intersection sets, see below. */ bitset_t remains; /* Flags, see below. */ bitset_word_t has_intersec, not_subset, not_consumed; /* Optimization, skip if this state doesn't accept the character. */ if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c)) continue; /* Enumerate the intersection set of this state and `accepts'. */ has_intersec = 0; for (k = 0; k < BITSET_WORDS; ++k) has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k]; /* And skip if the intersection set is empty. */ if (!has_intersec) continue; /* Then check if this state is a subset of `accepts'. */ not_subset = not_consumed = 0; for (k = 0; k < BITSET_WORDS; ++k) { not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k]; not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k]; } /* If this state isn't a subset of `accepts', create a new group state, which has the `remains'. */ if (not_subset) { bitset_copy (dests_ch[ndests], remains); bitset_copy (dests_ch[j], intersec); err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]); if (BE (err != REG_NOERROR, 0)) goto error_return; ++ndests; } /* Put the position in the current group. */ result = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]); if (BE (result < 0, 0)) goto error_return; /* If all characters are consumed, go to next node. */ if (!not_consumed) break; } /* Some characters remain, create a new group. */ if (j == ndests) { bitset_copy (dests_ch[ndests], accepts); err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]); if (BE (err != REG_NOERROR, 0)) goto error_return; ++ndests; bitset_empty (accepts); } } return ndests; error_return: for (j = 0; j < ndests; ++j) re_node_set_free (dests_node + j); return -1; } #ifdef RE_ENABLE_I18N /* Check how many bytes the node `dfa->nodes[node_idx]' accepts. Return the number of the bytes the node accepts. STR_IDX is the current index of the input string. This function handles the nodes which can accept one character, or one collating element like '.', '[a-z]', opposite to the other nodes can only accept one byte. */ static int internal_function check_node_accept_bytes (const re_dfa_t *dfa, int node_idx, const re_string_t *input, int str_idx) { const re_token_t *node = dfa->nodes + node_idx; int char_len, elem_len; int i; if (BE (node->type == OP_UTF8_PERIOD, 0)) { unsigned char c = re_string_byte_at (input, str_idx), d; if (BE (c < 0xc2, 1)) return 0; if (str_idx + 2 > input->len) return 0; d = re_string_byte_at (input, str_idx + 1); if (c < 0xe0) return (d < 0x80 || d > 0xbf) ? 0 : 2; else if (c < 0xf0) { char_len = 3; if (c == 0xe0 && d < 0xa0) return 0; } else if (c < 0xf8) { char_len = 4; if (c == 0xf0 && d < 0x90) return 0; } else if (c < 0xfc) { char_len = 5; if (c == 0xf8 && d < 0x88) return 0; } else if (c < 0xfe) { char_len = 6; if (c == 0xfc && d < 0x84) return 0; } else return 0; if (str_idx + char_len > input->len) return 0; for (i = 1; i < char_len; ++i) { d = re_string_byte_at (input, str_idx + i); if (d < 0x80 || d > 0xbf) return 0; } return char_len; } char_len = re_string_char_size_at (input, str_idx); if (node->type == OP_PERIOD) { if (char_len <= 1) return 0; /* FIXME: I don't think this if is needed, as both '\n' and '\0' are char_len == 1. */ /* '.' accepts any one character except the following two cases. */ if ((!(dfa->syntax & RE_DOT_NEWLINE) && re_string_byte_at (input, str_idx) == '\n') || ((dfa->syntax & RE_DOT_NOT_NULL) && re_string_byte_at (input, str_idx) == '\0')) return 0; return char_len; } elem_len = re_string_elem_size_at (input, str_idx); if ((elem_len <= 1 && char_len <= 1) || char_len == 0) return 0; if (node->type == COMPLEX_BRACKET) { const re_charset_t *cset = node->opr.mbcset; # ifdef _LIBC const unsigned char *pin = ((const unsigned char *) re_string_get_buffer (input) + str_idx); int j; uint32_t nrules; # endif /* _LIBC */ int match_len = 0; wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars) ? re_string_wchar_at (input, str_idx) : 0); /* match with multibyte character? */ for (i = 0; i < cset->nmbchars; ++i) if (wc == cset->mbchars[i]) { match_len = char_len; goto check_node_accept_bytes_match; } /* match with character_class? */ for (i = 0; i < cset->nchar_classes; ++i) { wctype_t wt = cset->char_classes[i]; if (__iswctype (wc, wt)) { match_len = char_len; goto check_node_accept_bytes_match; } } # ifdef _LIBC nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); if (nrules != 0) { unsigned int in_collseq = 0; const int32_t *table, *indirect; const unsigned char *weights, *extra; const char *collseqwc; int32_t idx; /* This #include defines a local function! */ # include <locale/weight.h> /* match with collating_symbol? */ if (cset->ncoll_syms) extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB); for (i = 0; i < cset->ncoll_syms; ++i) { const unsigned char *coll_sym = extra + cset->coll_syms[i]; /* Compare the length of input collating element and the length of current collating element. */ if (*coll_sym != elem_len) continue; /* Compare each bytes. */ for (j = 0; j < *coll_sym; j++) if (pin[j] != coll_sym[1 + j]) break; if (j == *coll_sym) { /* Match if every bytes is equal. */ match_len = j; goto check_node_accept_bytes_match; } } if (cset->nranges) { if (elem_len <= char_len) { collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC); in_collseq = __collseq_table_lookup (collseqwc, wc); } else in_collseq = find_collation_sequence_value (pin, elem_len); } /* match with range expression? */ for (i = 0; i < cset->nranges; ++i) if (cset->range_starts[i] <= in_collseq && in_collseq <= cset->range_ends[i]) { match_len = elem_len; goto check_node_accept_bytes_match; } /* match with equivalence_class? */ if (cset->nequiv_classes) { const unsigned char *cp = pin; table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB); extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB); idx = findidx (&cp); if (idx > 0) for (i = 0; i < cset->nequiv_classes; ++i) { int32_t equiv_class_idx = cset->equiv_classes[i]; size_t weight_len = weights[idx]; if (weight_len == weights[equiv_class_idx]) { int cnt = 0; while (cnt <= weight_len && (weights[equiv_class_idx + 1 + cnt] == weights[idx + 1 + cnt])) ++cnt; if (cnt > weight_len) { match_len = elem_len; goto check_node_accept_bytes_match; } } } } } else # endif /* _LIBC */ { /* match with range expression? */ #if __GNUC__ >= 2 wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'}; #else wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'}; cmp_buf[2] = wc; #endif for (i = 0; i < cset->nranges; ++i) { cmp_buf[0] = cset->range_starts[i]; cmp_buf[4] = cset->range_ends[i]; if (wcscoll (cmp_buf, cmp_buf + 2) <= 0 && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0) { match_len = char_len; goto check_node_accept_bytes_match; } } } check_node_accept_bytes_match: if (!cset->non_match) return match_len; else { if (match_len > 0) return 0; else return (elem_len > char_len) ? elem_len : char_len; } } return 0; } # ifdef _LIBC static unsigned int internal_function find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len) { uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); if (nrules == 0) { if (mbs_len == 1) { /* No valid character. Match it as a single byte character. */ const unsigned char *collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB); return collseq[mbs[0]]; } return UINT_MAX; } else { int32_t idx; const unsigned char *extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB); int32_t extrasize = (const unsigned char *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra; for (idx = 0; idx < extrasize;) { int mbs_cnt, found = 0; int32_t elem_mbs_len; /* Skip the name of collating element name. */ idx = idx + extra[idx] + 1; elem_mbs_len = extra[idx++]; if (mbs_len == elem_mbs_len) { for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt) if (extra[idx + mbs_cnt] != mbs[mbs_cnt]) break; if (mbs_cnt == elem_mbs_len) /* Found the entry. */ found = 1; } /* Skip the byte sequence of the collating element. */ idx += elem_mbs_len; /* Adjust for the alignment. */ idx = (idx + 3) & ~3; /* Skip the collation sequence value. */ idx += sizeof (uint32_t); /* Skip the wide char sequence of the collating element. */ idx = idx + sizeof (uint32_t) * (extra[idx] + 1); /* If we found the entry, return the sequence value. */ if (found) return *(uint32_t *) (extra + idx); /* Skip the collation sequence value. */ idx += sizeof (uint32_t); } return UINT_MAX; } } # endif /* _LIBC */ #endif /* RE_ENABLE_I18N */ /* Check whether the node accepts the byte which is IDX-th byte of the INPUT. */ static int internal_function check_node_accept (const re_match_context_t *mctx, const re_token_t *node, int idx) { unsigned char ch; ch = re_string_byte_at (&mctx->input, idx); switch (node->type) { case CHARACTER: if (node->opr.c != ch) return 0; break; case SIMPLE_BRACKET: if (!bitset_contain (node->opr.sbcset, ch)) return 0; break; #ifdef RE_ENABLE_I18N case OP_UTF8_PERIOD: if (ch >= 0x80) return 0; /* FALLTHROUGH */ #endif case OP_PERIOD: if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE)) || (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL))) return 0; break; default: return 0; } if (node->constraint) { /* The node has constraints. Check whether the current context satisfies the constraints. */ unsigned int context = re_string_context_at (&mctx->input, idx, mctx->eflags); if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context)) return 0; } return 1; } /* Extend the buffers, if the buffers have run out. */ static reg_errcode_t internal_function extend_buffers (re_match_context_t *mctx) { reg_errcode_t ret; re_string_t *pstr = &mctx->input; /* Double the lengthes of the buffers. */ ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2); if (BE (ret != REG_NOERROR, 0)) return ret; if (mctx->state_log != NULL) { /* And double the length of state_log. */ /* XXX We have no indication of the size of this buffer. If this allocation fail we have no indication that the state_log array does not have the right size. */ re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *, pstr->bufs_len + 1); if (BE (new_array == NULL, 0)) return REG_ESPACE; mctx->state_log = new_array; } /* Then reconstruct the buffers. */ if (pstr->icase) { #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) { ret = build_wcs_upper_buffer (pstr); if (BE (ret != REG_NOERROR, 0)) return ret; } else #endif /* RE_ENABLE_I18N */ build_upper_buffer (pstr); } else { #ifdef RE_ENABLE_I18N if (pstr->mb_cur_max > 1) build_wcs_buffer (pstr); else #endif /* RE_ENABLE_I18N */ { if (pstr->trans != NULL) re_string_translate_buffer (pstr); } } return REG_NOERROR; } /* Functions for matching context. */ /* Initialize MCTX. */ static reg_errcode_t internal_function match_ctx_init (re_match_context_t *mctx, int eflags, int n) { mctx->eflags = eflags; mctx->match_last = -1; if (n > 0) { mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n); mctx->sub_tops = re_malloc (re_sub_match_top_t *, n); if (BE (mctx->bkref_ents == NULL || mctx->sub_tops == NULL, 0)) return REG_ESPACE; } /* Already zero-ed by the caller. else mctx->bkref_ents = NULL; mctx->nbkref_ents = 0; mctx->nsub_tops = 0; */ mctx->abkref_ents = n; mctx->max_mb_elem_len = 1; mctx->asub_tops = n; return REG_NOERROR; } /* Clean the entries which depend on the current input in MCTX. This function must be invoked when the matcher changes the start index of the input, or changes the input string. */ static void internal_function match_ctx_clean (re_match_context_t *mctx) { int st_idx; for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx) { int sl_idx; re_sub_match_top_t *top = mctx->sub_tops[st_idx]; for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx) { re_sub_match_last_t *last = top->lasts[sl_idx]; re_free (last->path.array); re_free (last); } re_free (top->lasts); if (top->path) { re_free (top->path->array); re_free (top->path); } free (top); } mctx->nsub_tops = 0; mctx->nbkref_ents = 0; } /* Free all the memory associated with MCTX. */ static void internal_function match_ctx_free (re_match_context_t *mctx) { /* First, free all the memory associated with MCTX->SUB_TOPS. */ match_ctx_clean (mctx); re_free (mctx->sub_tops); re_free (mctx->bkref_ents); } /* Add a new backreference entry to MCTX. Note that we assume that caller never call this function with duplicate entry, and call with STR_IDX which isn't smaller than any existing entry. */ static reg_errcode_t internal_function match_ctx_add_entry (re_match_context_t *mctx, int node, int str_idx, int from, int to) { if (mctx->nbkref_ents >= mctx->abkref_ents) { struct re_backref_cache_entry* new_entry; new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry, mctx->abkref_ents * 2); if (BE (new_entry == NULL, 0)) { re_free (mctx->bkref_ents); return REG_ESPACE; } mctx->bkref_ents = new_entry; memset (mctx->bkref_ents + mctx->nbkref_ents, '\0', sizeof (struct re_backref_cache_entry) * mctx->abkref_ents); mctx->abkref_ents *= 2; } if (mctx->nbkref_ents > 0 && mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx) mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1; mctx->bkref_ents[mctx->nbkref_ents].node = node; mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx; mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from; mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to; /* This is a cache that saves negative results of check_dst_limits_calc_pos. If bit N is clear, means that this entry won't epsilon-transition to an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression. If it is set, check_dst_limits_calc_pos_1 will recurse and try to find one such node. A backreference does not epsilon-transition unless it is empty, so set to all zeros if FROM != TO. */ mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map = (from == to ? ~0 : 0); mctx->bkref_ents[mctx->nbkref_ents++].more = 0; if (mctx->max_mb_elem_len < to - from) mctx->max_mb_elem_len = to - from; return REG_NOERROR; } /* Search for the first entry which has the same str_idx, or -1 if none is found. Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX. */ static int internal_function search_cur_bkref_entry (const re_match_context_t *mctx, int str_idx) { int left, right, mid, last; last = right = mctx->nbkref_ents; for (left = 0; left < right;) { mid = (left + right) / 2; if (mctx->bkref_ents[mid].str_idx < str_idx) left = mid + 1; else right = mid; } if (left < last && mctx->bkref_ents[left].str_idx == str_idx) return left; else return -1; } /* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches at STR_IDX. */ static reg_errcode_t internal_function match_ctx_add_subtop (re_match_context_t *mctx, int node, int str_idx) { #ifdef DEBUG assert (mctx->sub_tops != NULL); assert (mctx->asub_tops > 0); #endif if (BE (mctx->nsub_tops == mctx->asub_tops, 0)) { int new_asub_tops = mctx->asub_tops * 2; re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops, re_sub_match_top_t *, new_asub_tops); if (BE (new_array == NULL, 0)) return REG_ESPACE; mctx->sub_tops = new_array; mctx->asub_tops = new_asub_tops; } mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t)); if (BE (mctx->sub_tops[mctx->nsub_tops] == NULL, 0)) return REG_ESPACE; mctx->sub_tops[mctx->nsub_tops]->node = node; mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx; return REG_NOERROR; } /* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP. */ static re_sub_match_last_t * internal_function match_ctx_add_sublast (re_sub_match_top_t *subtop, int node, int str_idx) { re_sub_match_last_t *new_entry; if (BE (subtop->nlasts == subtop->alasts, 0)) { int new_alasts = 2 * subtop->alasts + 1; re_sub_match_last_t **new_array = re_realloc (subtop->lasts, re_sub_match_last_t *, new_alasts); if (BE (new_array == NULL, 0)) return NULL; subtop->lasts = new_array; subtop->alasts = new_alasts; } new_entry = calloc (1, sizeof (re_sub_match_last_t)); if (BE (new_entry != NULL, 1)) { subtop->lasts[subtop->nlasts] = new_entry; new_entry->node = node; new_entry->str_idx = str_idx; ++subtop->nlasts; } return new_entry; } static void internal_function sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts, re_dfastate_t **limited_sts, int last_node, int last_str_idx) { sctx->sifted_states = sifted_sts; sctx->limited_states = limited_sts; sctx->last_node = last_node; sctx->last_str_idx = last_str_idx; re_node_set_init_empty (&sctx->limits); } /* Binary backward compatibility. */ #if _LIBC # include <shlib-compat.h> # if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3) link_warning (re_max_failures, "the 're_max_failures' variable is obsolete and will go away.") int re_max_failures = 2000; # endif #endif #endif
the_stack_data/103266084.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isspace.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jgelbard <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/23 14:39:59 by jgelbard #+# #+# */ /* Updated: 2018/02/24 23:56:45 by jgelbard ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isspace(int c) { return (c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' || c == ' '); }
the_stack_data/967983.c
#include <stdio.h> int main() { int num; int meaning_of_life = 42; printf("Enter a number: "); scanf("%i", &num); printf("Your number (%i) multiplied by the meaning of life (%i) = %i\n", num, meaning_of_life, (num*meaning_of_life)); return 0; }
the_stack_data/75138216.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp simd for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp simd for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp simd collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-simd.c:3:1, line:7:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1> // CHECK-NEXT: | `-OMPSimdDirective {{.*}} <line:4:1, col:17> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | | |-ForStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-simd.c:4:1) *const restrict' // CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1> // CHECK-NEXT: | `-OMPSimdDirective {{.*}} <line:10:1, col:17> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-simd.c:10:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1> // CHECK-NEXT: | `-OMPSimdDirective {{.*}} <line:17:1, col:29> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:18, col:28> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:27> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:27> 'int' 1 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-simd.c:17:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1> // CHECK-NEXT: | `-OMPSimdDirective {{.*}} <line:24:1, col:29> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:18, col:28> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:27> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:27> 'int' 2 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-simd.c:24:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1> // CHECK-NEXT: `-OMPSimdDirective {{.*}} <line:31:1, col:29> // CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:18, col:28> // CHECK-NEXT: | `-ConstantExpr {{.*}} <col:27> 'int' // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:27> 'int' 2 // CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9> openmp_structured_block // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-simd.c:31:1) *const restrict' // CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
the_stack_data/592444.c
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> int main(int argc, char *argv[]){ pid_t pid; int estado; if(argc<2 && argc%3!=0){ printf("Uso: ./ejercicio programa orden(bg/fg) \n"); //No ponemos & porque eso afectaría al propio proceso y no a la ejecución del exit(-1); // programa que ejecuta el proceso hijo } if( (pid=fork())<0) { perror("\nError en el fork"); exit(-1); }else if(pid==0) { for (int i = 1; i <= argc; ++i){ if (argv[i+1]=="bg"){ if( (execl(argv[1] , '&',NULL)<0)) { // En teoría funciona, pero el problema que tengo es si el programa perror("\nError en el execl"); // que va a ejecutar también necesita de parámetros al pasarlos no va exit(-1); // a ejecutar la orden } }else{ if( (execl(argv[1] ,NULL)<0)) { perror("\nError en el execl"); exit(-1); } } } } wait(&estado); printf("\nMi hijo %d ha finalizado con el estado %d\n",pid,estado); exit(0); }