file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/103265825.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum (int num1, int num2); int maximum (int num1, int num2); int multiply (int num1, int num2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum (num1, num2) { if (num1 > num2) { return num2; } else { return num1; } } int maximum (num1, num2) { if (num1 > num2) { return num1; } else { return num2; } } int multiply (num1, num2) { return num1 * num2; }
the_stack_data/677680.c
// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name loopmacro.c %s | FileCheck %s // CHECK: main // CHECK-NEXT: File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:2 = #0 // CHECK-NEXT: File 0, {{[0-9]+}}:6 -> {{[0-9]+}}:4 = (#0 + #1) // CHECK-NEXT: Expansion,File 0, {{[0-9]+}}:7 -> {{[0-9]+}}:20 = (#0 + #1) // CHECK-NEXT: File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:30 = (#0 + #1) // CHECK-NEXT: Branch,File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:30 = #1, #0 // CHECK-NEXT: File 1, [[@LINE+4]]:4 -> [[@LINE+6]]:23 = (#0 + #1) // CHECK-NEXT: Expansion,File 1, [[@LINE+3]]:5 -> [[@LINE+3]]:16 = (#0 + #1) // CHECK-NEXT: Expansion,File 1, [[@LINE+3]]:16 -> [[@LINE+3]]:21 = (#0 + #1) #define INSERT_STRING(s, match_head) \ (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \ prev[(s) & WMASK] = match_head = head[ins_h], \ head[ins_h] = (s)) // CHECK-NEXT: File 2, [[@LINE+3]]:26 -> [[@LINE+3]]:66 = (#0 + #1) // CHECK-NEXT: Expansion,File 2, [[@LINE+2]]:38 -> [[@LINE+2]]:45 = (#0 + #1) // CHECK-NEXT: Expansion,File 2, [[@LINE+1]]:56 -> [[@LINE+1]]:65 = (#0 + #1) #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK) // CHECK-NEXT: File 3, [[@LINE+1]]:15 -> [[@LINE+1]]:21 = (#0 + #1) #define WMASK 0xFFFF // CHECK-NEXT: File 4, [[@LINE+4]]:18 -> [[@LINE+4]]:53 = (#0 + #1) // CHECK-NEXT: Expansion,File 4, [[@LINE+3]]:20 -> [[@LINE+3]]:29 = (#0 + #1) // CHECK-NEXT: Expansion,File 4, [[@LINE+2]]:30 -> [[@LINE+2]]:39 = (#0 + #1) // CHECK-NEXT: Expansion,File 4, [[@LINE+1]]:43 -> [[@LINE+1]]:52 = (#0 + #1) #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH) // CHECK-NEXT: File 5, [[@LINE+1]]:19 -> [[@LINE+1]]:25 = (#0 + #1) #define HASH_MASK 0xFFFF // CHECK-NEXT: File 6, [[@LINE+1]]:20 -> [[@LINE+1]]:22 = (#0 + #1) #define HASH_BITS 15 // CHECK-NEXT: File 7, [[@LINE+2]]:20 -> [[@LINE+2]]:21 = (#0 + #1) // CHECK-NEXT: File 8, [[@LINE+1]]:20 -> [[@LINE+1]]:21 = (#0 + #1) #define MIN_MATCH 3 int main() { int strstart = 0; int hash_head = 2; int prev_length = 5; int ins_h = 1; int prev[32<<10] = { 0 }; int head[32<<10] = { 0 }; int window[1024] = { 0 }; do { strstart++; INSERT_STRING(strstart, hash_head); } while (--prev_length != 0); }
the_stack_data/111841.c
#include <stdio.h> int main() { int i, j; for (i = 5; i <= 1; ++i) { for (j = 5; 1 <= j >= i; --j) { printf("%d ", j); } printf("\n"); } }
the_stack_data/18888433.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } unsigned int __VERIFIER_nondet_uint(); unsigned int SIZE; int linear_search(int *a, int n, int q) { unsigned int j=0; while (j<n && a[j]!=q) { j++; if (j==20) j=-1; } if (j<SIZE) return 1; else return 0; } int main() { SIZE=(__VERIFIER_nondet_uint()/2)+1; int a[SIZE]; a[SIZE/2]=3; __VERIFIER_assert(linear_search(a,SIZE,3)); }
the_stack_data/339051.c
/* Implementation of Anagram in C programming. An anagram of a string is another string that contains the same characters, only the order of characters can be different. This program takes two strings from the user and checks whether they are anagrams of each other or not. */ #include<stdio.h> #include<string.h> // Function for swapping character char swap(char* p, char* q) { char t = *p; *p = *q; *q = t; } // Bubble sort for sorting characters of string in ascending order void bubble_sort(char b[], int n) { int i, j; for (i = 0;i < n - 1;i++) { for (j = 0;j < n - i - 1;j++) if (b[j] > b[j + 1]) // not in ascending order swap(&b[j], &b[j + 1]); //function call for swapping charaters } } int main(){ char str1[100], str2[100]; int l1 = 0, l2 = 0, status = 0, i; printf("Enter the first string:"); gets(str1); printf("Enter the second string: "); gets(str2); // length of strings l1 = strlen(str1); l2 = strlen(str2); // If strings of different length they're not anagrams if (l1 != l2) { printf("Given strings are not anagram of each other\n"); return 0; } // string sorting bubble_sort(str1, l1); bubble_sort(str2, l2); // checking for anagram for (i = 0; i < l1;i++) { if (str1[i] != str2[i]) { // Not anagrams status = 1; break; } } if (!status) printf("Given strings are Anagrams of each other\n"); else printf("Given strings are Not Anagram of each other\n"); return 0; } /* Sample input1: Hello Holel Output: Given strings are Anagrams of each other ----------------------------------------------- Sample input2: Hello Hi Output: Given strings are Not Anagrams of each other ----------------------------------------------- Sample input3: Hi Hello Output: Given strings are Not Anagrams of each other */
the_stack_data/14200916.c
/* 2020 June * Online Exam 3 * Version B */ #include<stdio.h> #define SIZE 10 // main function int main(void) { int seat[SIZE] = {0}; // seat nubers array int seatNum = 0; // seat number enterd by user int count = 0; // begin do while do { // user input for seat number printf("Pls input the seat number (1- 10): "); // prompt for input scanf("%d", &seatNum); // check if seat number valid if (seatNum <= SIZE && seatNum >= 1) { if (seat[seatNum -1] == 0) { seat[seatNum-1] = 1; } // end if else if (seat[seatNum -1] == 1) { printf("Sorry. The seat %d is reseved.\n", seatNum); } // end else if } else if (seatNum == -1) { break; } // end else if // invalid seat number error message else { printf("Sorry. Please input a valid seat number.\n"); continue; } // end else } while (seatNum != -1); // end do while // print reserved seat numbers printf("\nReserved seat numbers\n\n"); for (count = 0; count < SIZE; count++) { if (seat[count] == 1) { printf("S%d\n", count + 1); } } return 0; }
the_stack_data/20449540.c
/* This program asks the user to enter 2 integers and display the sum using pointer variables. Author: Robert Eviston Date: 25th November 2013 */ #include <stdio.h> main() { int num1; int num2; int *ptr1; int *ptr2; int *sum; ptr1 = &num1; ptr2 = &num2; printf("Please enter 2 integers\n"); scanf("%d", *ptr1); scanf("%d", *ptr2); flushall(); *sum = *ptr1 + *ptr2; printf("%d\n", *sum); getchar(); } // End main
the_stack_data/140781.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Copyright 2021 Melwyn Francis Carlo */ int main() { long int max_product_concat = 0; for (int tens = 8; tens >= 0; tens--) { for (int power = 1; power <= 4; power++) { int num = (9 * pow(10, power)) + (tens * pow(10, power - 1)); const int max_num = num + pow(10, power - 1); num--; while (++num != max_num) { char product_concat[100] = { 0 }; sprintf(&product_concat[0], "%d", num); int i = 2; int duplicate_found = 0; while (strlen(product_concat) < 9) { int product = num * i; int product_len = (int)log10(product) + 1; char product_str[product_len]; product_str[product_len-1] = 0; sprintf(&product_str[0], "%d", product); if (strchr(product_str, '0')) break; duplicate_found = 0; for (int j = 0; j < product_len; j++) { if (strchr(product_concat, product_str[j]) != NULL) { duplicate_found = 1; break; } } if ((strlen(product_concat) + product_len) > 9) duplicate_found = 1; if (duplicate_found) break; duplicate_found = 0; for (int j = 0; j < product_len; j++) { for (int k = 0; k < product_len; k++) { if (j == k) continue; if (product_str[j] == product_str[k]) { duplicate_found = 1; break; } } if (duplicate_found) break; } if (duplicate_found) break; memcpy( &product_concat[strlen(product_concat)], &product_str[0], product_len); i++; } if (!duplicate_found) if (strlen(product_concat) == 9) if (atol(product_concat) > max_product_concat) max_product_concat = atol(product_concat); } } } printf("%ld\n", max_product_concat); return 0; }
the_stack_data/48230.c
#include <stdio.h> #include <stdlib.h> int dfs(int i, int N, int* adj, int* color, int c) { color[i] = c; int j; for (j = 0; j < N; j++) { if (adj[i*N + j] == 0) { if (color[j] == -1) { if (!dfs(j, N, adj, color, 1 - c)) { return 0; } } else if (color[j] == c) { return 0; } } } return 1; } int bipartido(int N, int* adj) { int color[N]; int i; for (i = 0; i < N; i++) { color[i] = -1; } for (i = 0; i < N; i++) { if (color[i] == -1) { if (dfs(i, N, adj, color, 0)) { return 0; } } } return 1; } int main() { int N; scanf("%d", &N); int adj[N][N]; int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { scanf("%d", &(adj[i][j])); } } if (bipartido(N, adj)) { printf("Fail!\n"); } else { printf("Bazinga!\n"); } return 0; }
the_stack_data/151705835.c
void insert_sort(char a[], int n) { int i, j; char tmp; for (i = 1; i < n; i++) { tmp = a[i]; j = i - 1; while (j >= 0 && a[j] > tmp) { a[j + 1] = a[j]; j--; } a[j + 1] = tmp; } }
the_stack_data/22013170.c
// // main.c // 4 Byte Library Call // // Created by Tomy Hsieh on 2020/5/20. // Copyright © 2020 Tomy Hsieh. All rights reserved. // #include <stdio.h> // fopen(), fwrite(), fclose() #include <stdlib.h> #define __USE_GNU 1 #include <sys/time.h> // gettimeofday() int main(int argc, const char * argv[]) { // Initialization const int BATCH_SIZE = 4; // in Byte const int BATCH_NUM = 25*220; struct timeval t_begin, t_end; int8_t *buffer = valloc(sizeof(char) * BATCH_SIZE); // Open File Descriptor FILE* src_descriptor = fopen("testfile-src", "r"); if (src_descriptor == NULL) { printf("File Open Error\n"); exit(1); } FILE* dst_descriptor = fopen("testfile-dst", "w+"); if (dst_descriptor == NULL) { printf("File Open Error\n"); exit(1); } // Read File Sequantially gettimeofday(&t_begin, NULL); for (int i=0; i<BATCH_NUM; i++) { fread(buffer, sizeof(char), BATCH_SIZE, src_descriptor); fwrite(buffer, sizeof(char), BATCH_SIZE, dst_descriptor); } gettimeofday(&t_end, NULL); // Clean Up fclose(src_descriptor); fclose(dst_descriptor); free(buffer); // Print Result int64_t t_exe = 1000000 * (t_end.tv_sec - t_begin.tv_sec) + (t_end.tv_usec - t_begin.tv_usec); printf("4 Byte Library Copy-Write took %lld µs\n", t_exe); return 0; }
the_stack_data/20872.c
//dynamic array #include <stdio.h> #include <stdlib.h> int main() { int arr_size=2; int *arr = (int *)malloc(sizeof(int)*arr_size); //intially array size 1 //entering elements int n; //for entering number int i=0; //for insertion and element count while(1) { printf("ENTER ELEMENT or quit by -1: "); scanf("%d",&n); if(n==-1) { break; } if(i<arr_size) { arr[i]=n; i++; } else { //no space present to insert in an array int temp_size=arr_size; int temp_array[temp_size]; //copy elements of arr to temp array for(register int j=0;j<arr_size;j++) { temp_array[j] = arr[j]; } //increse size of array arr_size=arr_size*2; arr = (int *)malloc(sizeof(int)*arr_size); //copy temp_array to arr int k=0; for(k=0;k<temp_size;k++) { arr[k] = temp_array[k]; } i=k; arr[i]=n; //insert new element entered i++; } } //prnting array printf("ENTERED ARRAY of size %d\n",i); for(register int j=0;j<i;j++) { printf("%d ",arr[j]); } printf("\n"); }
the_stack_data/148576914.c
#include <stdio.h> int main() {}
the_stack_data/669444.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 alloca(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 alloca() #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_alloca(n) ((n) < 4032) # else /* alloca is implemented with malloc, so just use malloc. */ # define __libc_use_alloca(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/141409.c
#include <stdio.h> int main() { int a,b,i,j,k=0,l; printf("total no. of students:\n"); scanf("%d", &a); printf("no. of courses each student is studying:\n"); scanf("%d", &b); int c[a][b]; for(i=0;i<a;i++){ printf("Enter Student's Roll no. :\n"); scanf("%d", & c[i][0]); for(j=0;j<b;j++){ printf("Enter Student's Marks: \n"); scanf("%d", & c[i][j]); } } for(i=0;i<a;i++){ printf("Student's Roll no. is : %d\n", c[i][0]); for(j=0;j<b;j++){ k+=c[i][j]; l=k/2; } printf("Average Marks: %d\n", l); } return 0; }
the_stack_data/760431.c
#include <stdio.h> #include <string.h> struct renas { char nome[100]; int peso, idade, numRenas, totRenas; double altura; }; void ordena(struct renas r[], int totRenas) { int i, mudancas = 0; struct renas aux; i = 0; /*Rudolph 50 100 1.12 Dasher 10 121 1.98 Dancer 10 131 1.14 Vixen 50 110 1.42 Comet 50 121 1.21 Cupid 50 107 1.45 Donner 30 106 1.23 Blitzen 50 180 1.84 Prancer 7 142 1.36 */ // mudancas = 0 do { for (i = 0; i < totRenas; i++) { if (r[i].peso < r[i + 1].peso) { aux = r[i]; r[i] = r[i + 1]; r[i + 1] = aux; mudancas++; } // peso decrescente else if (r[i].peso == r[i + 1].peso) { if (r[i].idade > r[i + 1].idade) { aux = r[i]; r[i] = r[i + 1]; r[i + 1] = aux; mudancas++; } // idade crescente else if (r[i].idade == r[i + 1].idade) { if (r[i].altura < r[i + 1].altura) { aux = r[i]; r[i] = r[i + 1]; r[i + 1] = aux; mudancas++; } else if (r[i].altura == r[i + 1].altura) { if (strcmp(r[i].nome, r[i + 1].nome) > 0) { aux = r[i]; r[i] = r[i + 1]; r[i + 1] = aux; mudancas++; } } } } } if (mudancas == 0) { break; } else { mudancas = 0; } } while (1); }; void printa(struct renas r[], int numRenas, int casos) { int i, j,k=0; for (i = 0; i < casos; i++) { printf("CENARIO {%d}\n", i + 1); for (j = 0; j < numRenas; j++) { printf("%d - %s\n", j + 1, r[k].nome); k++; } k = numRenas; } } int main() { char nome[100]; int casos, totRenas, numRenas, peso, idade, i, j=0,k=0; double altura; struct renas r[1000]; scanf("%d", &casos); for (i = 0; i < casos; i++) { scanf("%d %d", &totRenas, &numRenas); for (j; j < totRenas; j++) { scanf("%s %d %d %lf", nome, &peso, &idade, &altura); strcpy(r[k].nome, nome); r[k].peso = peso; r[k].idade = idade; r[k].altura = altura; //r[j].numRenas = numRenas; //r[j].totRenas = totRenas; k++; } k = totRenas; } ordena(r, totRenas); printa(r, numRenas, casos); return 0; }
the_stack_data/187643489.c
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #if ((defined IEEE_MAX_TIMER_OBJECTS) && (IEEE_MAX_TIMER_OBJECTS > 0)) #include <stdio.h> #include <string.h> #include "usb_device_config.h" #include "usb.h" #include "fsl_device_registers.h" #include "ieee11073_timer.h" #include "board.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Prototypes ******************************************************************************/ static void IEEE_TimerISR(void); /******************************************************************************* * Variables ******************************************************************************/ /*! @brief array of timer objects */ ieee11073_timer_object_t s_ieee11073TimerObjectArray[IEEE_MAX_TIMER_OBJECTS]; /******************************************************************************* * Code ******************************************************************************/ /*! * @brief timer initialization. * * This function initializes the timer object queue and system clock counter. * * @param controller_ID the identify of timer controller. * * @retval success of error. */ void IEEE_TimerInit(void) { /* Configure the SysTick timer */ SysTick_Config(SystemCoreClock / 1000U); /* Disable the SysTick timer */ SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; /* Clear timer object array */ (void)memset(s_ieee11073TimerObjectArray, 0U, sizeof(s_ieee11073TimerObjectArray)); } /*! * @brief add timer queue. * * This function is called to add timer object to timer queue. * * @param timerObject Timer object. * * @retval timerIndex The timer queue is not full. * @retval -1 The input timer object is NULL. The timer queue is full. */ uint8_t IEEE_AddTimerQueue(ieee11073_timer_object_t *timerObject) { if (NULL != timerObject) { /* Timer Index return value */ uint8_t timerIndex = 0U; /* Queue full checking */ uint8_t isQueueFull = 1U; /* Disable the SysTick timer */ SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; /* Add timerObject to queue */ for (timerIndex = 0U; timerIndex < IEEE_MAX_TIMER_OBJECTS; timerIndex++) { if (s_ieee11073TimerObjectArray[timerIndex].timerCallback == NULL) { isQueueFull = 0U; (void)memcpy(&s_ieee11073TimerObjectArray[timerIndex], timerObject, sizeof(ieee11073_timer_object_t)); break; } } if (isQueueFull) { /* Timer queue is full */ return (uint8_t)-1; } else { /* Enable the SysTick timer */ SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; return timerIndex; } } /* Invalid parameter */ return (uint8_t)-1; } /*! * @brief remove timer queue. * * This function is called to remove timer object from timer queue. * * @param timerIndex index of timer object in queue. */ void IEEE_RemoveTimerQueue(uint8_t timerIndex) { if (timerIndex < IEEE_MAX_TIMER_OBJECTS) { /* Disable the SysTick timer */ SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; if (NULL != s_ieee11073TimerObjectArray[timerIndex].timerCallback) { /* Clear the time object in queue corresponding with timerIndex */ (void)memset(&s_ieee11073TimerObjectArray[timerIndex], 0U, sizeof(ieee11073_timer_object_t)); s_ieee11073TimerObjectArray[timerIndex].timerCallback = NULL; } /* Queue empty checking */ for (uint8_t i = 0U; i < IEEE_MAX_TIMER_OBJECTS; i++) { if (NULL != s_ieee11073TimerObjectArray[i].timerCallback) { /* Queue is not empty, enable the timer again */ SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; break; } } } } /*! * @brief timer interrupt service routine. * This function serves as the timer interrupt service routine. * * @return None. */ void SysTick_Handler(void) { IEEE_TimerISR(); } /*! * @brief timer interrupt service function. * * This function services programmable interrupt timer when a timer object * expired, then removes the timer object from timer queue and calls to the * callback function (if registered). */ static void IEEE_TimerISR(void) { uint8_t index; for (index = 0U; index < IEEE_MAX_TIMER_OBJECTS; index++) { if (NULL != s_ieee11073TimerObjectArray[index].timerCallback) { ieee11073_timer_object_t *timerObject = &s_ieee11073TimerObjectArray[index]; timerObject->timerCount--; if (timerObject->timerCount <= 0U) { /* Call Pending Timer CallBacks */ timerObject->timerCallback(timerObject->timerArgument); /* remove timer object from timer queue */ IEEE_RemoveTimerQueue(index); } } } } #endif
the_stack_data/80026.c
#include <stdint.h> #include <string.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #define WIDTH 80 #define HEIGHT 8 // saves one image in the animation static void save_image(int index, double field[][WIDTH], uint32_t palet[], int max_col, double scale) { FILE *file; char filename[128]; int row, col; uint32_t rgb; uint8_t b; sprintf(filename, "metaballs%03d.ppm", index); file = fopen(filename, "wb"); if (file != NULL) { fprintf(file, "P6\n%d %d\n%d\n", WIDTH, HEIGHT, 255); for (row = 0; row < HEIGHT; row++) { for (col = 0; col < WIDTH; col++) { double v = field[row][col]; int j = max_col * v / scale; if (j > max_col) { j = max_col; } rgb = palet[j]; b = (rgb >> 16) & 0xFF; fwrite(&b, 1, 1, file); b = (rgb >> 8) & 0xFF; fwrite(&b, 1, 1, file); b = (rgb >> 0) & 0xFF; fwrite(&b, 1, 1, file); } } fclose(file); } } typedef struct { double cx, cy; double vx, vy; double d; } move_t; double dropoff(double x, double y, double d) { double d2 = (x * x + y * y) / (d * d); if (d2 < 1.0) { double v = (1 - d2); return v * v; } else { return 0.0; } } static void move_ball(move_t *move) { move->cx += move->vx; if ((move->cx > WIDTH) || (move->cx < -WIDTH)) { move->vx = -move->vx; } move->cy += move->vy; if ((move->cy > 2*HEIGHT) || (move->cy < -2*HEIGHT)) { move->vy = -move->vy; } } static void draw_ball(double field[][WIDTH], move_t *move) { int row, col; double x = move->cx + (WIDTH / 2); double y = move->cy + (HEIGHT / 2); for (row = 0; row < HEIGHT; row++) { for (col = 0; col < WIDTH; col++) { field[row][col] += dropoff(col - x, row - y, move->d); } } } #define RAND_RANGE 1000000 double myrand(double range) { double d = rand() % RAND_RANGE; return range * d / RAND_RANGE; } static int create_palette(uint32_t palet[]) { int i; int k = 0; int r = 0, g = 0, b = 0; // black to red for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); r++; } // red to yellow for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); g++; } // yellow to green for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); r--; } // green to cyan for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); b++; } // cyan to blue for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); g--; } // blue to magenta for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); r++; } // magenta to white for (i = 0; i < 15; i++) { palet[k++] = (r << 20) + (g << 12) + (b << 4); g++; } return k; } #define NUM_BALLS 100 int main(int argc, char *argv[]) { int i; double field[HEIGHT][WIDTH]; uint32_t palet[256]; (void)argc; (void)argv; // create palette int numcol = create_palette(palet); // define movement move_t *moves[NUM_BALLS]; for (i = 0; i < NUM_BALLS; i++) { move_t *move = malloc(sizeof(move_t)); move->cx = myrand(2*WIDTH) - WIDTH; move->cy = myrand(4*HEIGHT) - 2*HEIGHT; move->vx = (2.0 - myrand(4.0)) / 10.0; move->vy = (2.0 - myrand(4.0)) / 10.0; move->d = 2.0 + myrand(12.0); moves[i] = move; } // draw metaballs int j; for (i = 0; i < 1000; i++) { memset(field, 0, sizeof(field)); for (j = 0; j < NUM_BALLS; j++) { move_ball(moves[j]); draw_ball(field, moves[j]); } save_image(i, field, palet, numcol - 1, 3.0); } // free for (i = 0; i < NUM_BALLS; i++) { free(moves[i]); } return 0; }
the_stack_data/211081770.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } extern int __VERIFIER_nondet_int(void); int N; int main() { N = __VERIFIER_nondet_int(); if(N <= 0) return 1; int i; int a[N]; int b[N]; for(i=0; i<N; i++) { if(i==0) { b[0] = 1; } else { b[i] = b[i-1] + 2; } } for(i=0; i<N; i++) { if(i==0) { a[0] = N + 1; } else { a[i] = a[i-1] + b[i-1] + 2; } } for(i=0; i<N; i++) { __VERIFIER_assert(a[i] == N + (i+1)*(i+1)); } return 1; }
the_stack_data/190768989.c
/* You all must have seen a seven segment display.If not here it is: Alice got a number written in seven segment format where each segment was creatted used a matchstick. Example: If Alice gets a number 123 so basically Alice used 12 matchsticks for this number. Alice is wondering what is the numerically largest value that she can generate by using at most the matchsticks that she currently possess.Help Alice out by telling her that number. Input Format: First line contains T (test cases). Next T lines contain a Number N. Output Format: Print the largest possible number numerically that can be generated using at max that many number of matchsticks which was used to generate N. Constraints: SAMPLE INPUT 2 1 0 SAMPLE OUTPUT 1 111 Explanation If you have 1 as your number that means you have 2 match sticks.You can generate 1 using this. If you have 0 as your number that means you have 6 match sticks.You can generate 111 using this. */ #include <stdio.h> #include <string.h> int main() { int T, size, ts; char N[101]; int a[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; scanf("%d", &T); for (int i = 0; i < T; i++) { scanf("%s", &N); size = strlen(N); ts = 0; for (int j = 0; j < size; j++) { ts += a[N[j] - '0']; } if (ts % 2) { printf("7"); ts = (ts - 3) / 2; for (int j = 0; j < ts; j++) { printf("1"); } } else { ts = ts / 2; for (int j = 0; j < ts; j++) { printf("1"); } } printf("\n"); } }
the_stack_data/187642701.c
#include <stdio.h> #include <stdlib.h> int main() { int a, b , c, condMultiplo; a = 100; c= 0; printf("Informe o segundo numero: "); scanf("%i", &b); condMultiplo = a % b; while(a != 0){ if (a >= b){ condMultiplo = a % b; }else{ condMultiplo = b % a; } if ( condMultiplo == 0) { printf("O numero %i eh multiplo de %i. \n", a, b); }else{ //printf("O numero %i nao eh multiplo de %i. \n", a, b); } a = a - 1; } return 0; }
the_stack_data/47226.c
#include <stdio.h> int main(void) { printf("Testing...\n..1\n...2\n....3\n"); return 0; }
the_stack_data/60560.c
// RUN: %clang_cc1 -triple s390x-linux-gnu -emit-llvm %s -o - | FileCheck %s // SystemZ prefers to align all global variables to two bytes. struct test { signed char a; }; char c; // CHECK-DAG: @c = common global i8 0, align 2 struct test s; // CHECK-DAG: @s = common global %struct._Z4test zeroinitializer, align 2 extern char ec; // CHECK-DAG: @ec = external global i8, align 2 extern struct test es; // CHECK-DAG: @es = external global %struct._Z4test, align 2 // Dummy function to make sure external symbols are used. void func (void) { c = ec; s = es; } // Alignment should be respected for coerced argument loads struct arg { long y __attribute__((packed, aligned(4))); }; extern struct arg x; void f(struct arg); void test (void) { f(x); } // CHECK-LABEL: @test // CHECK: load i64, i64* getelementptr inbounds (%struct.arg, %struct.arg* @x, i32 0, i32 0), align 4
the_stack_data/93887568.c
#include <stdlib.h> struct A { char x[1]; }; extern void abort (void); void __attribute__((noinline,noclone)) foo (struct A a) { if (a.x[0] != 'a') abort (); } int main () { struct A a; int i; for (i = 0; i < 1; ++i) a.x[i] = 'a'; foo (a); return 0; }
the_stack_data/151553.c
#include <unistd.h> #include <string.h> int main (void) { char wd[255]; int i; getcwd(wd,255); i = strlen(wd); write(STDOUT_FILENO,wd,i); write(STDOUT_FILENO,"\n",1); exit(0); }
the_stack_data/336047.c
#if ENABLE_FEATURE_AIX_LABEL /* * Copyright (C) Andreas Neuper, Sep 1998. * * Licensed under GPLv2, see file LICENSE in this tarball for details. */ typedef struct { unsigned int magic; /* expect AIX_LABEL_MAGIC */ unsigned int fillbytes1[124]; unsigned int physical_volume_id; unsigned int fillbytes2[124]; } aix_partition; #define AIX_LABEL_MAGIC 0xc9c2d4c1 #define AIX_LABEL_MAGIC_SWAPPED 0xc1d4c2c9 #define AIX_INFO_MAGIC 0x00072959 #define AIX_INFO_MAGIC_SWAPPED 0x59290700 #define aixlabel ((aix_partition *)MBRbuffer) /* Changes: * 1999-03-20 Arnaldo Carvalho de Melo <[email protected]> * Internationalization * * 2003-03-20 Phillip Kesling <[email protected]> * Some fixes */ static smallint aix_other_endian; /* bool */ static smallint aix_volumes = 1; /* max 15 */ /* * only dealing with free blocks here */ static void aix_info(void) { puts("\n" "There is a valid AIX label on this disk.\n" "Unfortunately Linux cannot handle these disks at the moment.\n" "Nevertheless some advice:\n" "1. fdisk will destroy its contents on write.\n" "2. Be sure that this disk is NOT a still vital part of a volume group.\n" " (Otherwise you may erase the other disks as well, if unmirrored.)\n" "3. Before deleting this physical volume be sure to remove the disk\n" " logically from your AIX machine. (Otherwise you become an AIXpert).\n" ); } static int check_aix_label(void) { if (aixlabel->magic != AIX_LABEL_MAGIC && aixlabel->magic != AIX_LABEL_MAGIC_SWAPPED) { current_label_type = 0; aix_other_endian = 0; return 0; } aix_other_endian = (aixlabel->magic == AIX_LABEL_MAGIC_SWAPPED); update_units(); current_label_type = LABEL_AIX; g_partitions = 1016; aix_volumes = 15; aix_info(); /*aix_nolabel();*/ /* %% */ /*aix_label = 1;*/ /* %% */ return 1; } #endif /* AIX_LABEL */
the_stack_data/30928.c
void ddpoly(float c[], int nc, float x, float pd[], int nd) { int nnd,j,i; float cnst=1.0; pd[0]=c[nc]; for (j=1;j<=nd;j++) pd[j]=0.0; for (i=nc-1;i>=0;i--) { nnd=(nd < (nc-i) ? nd : nc-i); for (j=nnd;j>=1;j--) pd[j]=pd[j]*x+pd[j-1]; pd[0]=pd[0]*x+c[i]; } for (i=2;i<=nd;i++) { cnst *= i; pd[i] *= cnst; } }
the_stack_data/218774.c
#include <stdio.h> int main() { int arr[100] = {0}; int i, x, pos, n = 10; for (i = 0; i < 10; i++) arr[i] = i + 1; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); x = 50; pos = 5; n++; for (i = n; i >= pos; i--) arr[i] = arr[i - 1]; arr[pos - 1] = x; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
the_stack_data/76700656.c
/*numPass=9, numTotal=9 Verdict:ACCEPTED, Visibility:1, Input:"jhggd g sdfghjk", ExpOutput:"jhsdfghjkggd", Output:"jhsdfghjkggd" Verdict:ACCEPTED, Visibility:1, Input:"abcde bc re", ExpOutput:"arebcde", Output:"arebcde" Verdict:ACCEPTED, Visibility:1, Input:"jhukfi kf tred", ExpOutput:"jhutredkfi", Output:"jhutredkfi" Verdict:ACCEPTED, Visibility:1, Input:"mississippi ss troll", ExpOutput:"mitrollssissippi", Output:"mitrollssissippi" Verdict:ACCEPTED, Visibility:1, Input:"Add-automated/pre-generated-test-cases-to-this-problem. pre com", ExpOutput:"Add-automated/compre-generated-test-cases-to-this-problem.", Output:"Add-automated/compre-generated-test-cases-to-this-problem." Verdict:ACCEPTED, Visibility:0, Input:"mississippi pp troll", ExpOutput:"mississitrollppi", Output:"mississitrollppi" Verdict:ACCEPTED, Visibility:0, Input:"underground under water", ExpOutput:"waterunderground", Output:"waterunderground" Verdict:ACCEPTED, Visibility:0, Input:"imindian indian proud", ExpOutput:"improudindian", Output:"improudindian" Verdict:ACCEPTED, Visibility:0, Input:"Add-automated/pre-generated-test-cases-to-this-problem. /pre -human", ExpOutput:"Add-automated-human/pre-generated-test-cases-to-this-problem.", Output:"Add-automated-human/pre-generated-test-cases-to-this-problem." */ #include <stdio.h> int read_string(char s[]) { int ch,i=0; scanf("%s",s);//reads the string while(s[i++]!='\0');//finds size of string return i-1;//returns size } int check_substring(char str[],char s1[],int length,int length1) //checks if s1 is substring of str { int i,j,k; for(i=0;i<length;i++) { if(str[i]==s1[0]) /*for substring first element of s1 should be in str*/ { for(j=0;j<length1;j++) { if(str[i+j]==s1[j]) k=1; else { k=0; break; } } if(k==1)//when entire s1 lies in str return i;//where substring lies in str } } return 0;//in case s1 is not substring of str } int main() { char str[50],s1[50],s2[50]; int length,length1,length2,place,i,newlength; length=read_string(str);//gives size of str length1=read_string(s1);//gives size of s1 length2=read_string(s2);//gives size of s2 place=check_substring(str,s1,length,length1); //place from where elements of s1 are in str /*if(place==0) //if not a substring str printed as it is { for(i=0;i<length;i++) { printf("%c",str[i]); } } else*/ //if s1 is substring then modifications done { for(i=0;i<place;i++) //prints str before place { printf("%c",str[i]); } for(i=0;i<length2;i++) //prints elements of s2 now { printf("%c",s2[i]); } for(i=place;i<length;i++) //prints remaining str { printf("%c",str[i]); } } return 0; }
the_stack_data/215769615.c
/* { dg-do compile } */ /* { dg-additional-options "-fno-tree-ch -fno-tree-cselim -fno-tree-dominator-opts" } */ int a, b, c, d, e, f; void foo (int x) { for (;;) { int g = c; if (x) { if (e) while (a) --f; } for (b = 5; b; b--) { } if (!g) x = 0; } }
the_stack_data/196753.c
/* ========================================================================== Licensed under BSD 2clause license See LICENSE file for more information Author: Michał Łyszczek <[email protected]> ========================================================================== _ __ __ ____ _ __ (_)____ _____ / /__ __ ____/ /___ / __/(_)/ /___ _____ / // __ \ / ___// // / / // __ // _ \ / /_ / // // _ \ / ___/ / // / / // /__ / // /_/ // /_/ // __/ / __// // // __/(__ ) /_//_/ /_/ \___//_/ \__,_/ \__,_/ \___/ /_/ /_//_/ \___//____/ ========================================================================== */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <limits.h> /* ========================================================================== __ __ __ _ ____/ /___ _____ / /____ _ _____ ____ _ / /_ (_)____ ____ _____ / __ // _ \ / ___// // __ `// ___// __ `// __// // __ \ / __ \ / ___/ / /_/ // __// /__ / // /_/ // / / /_/ // /_ / // /_/ // / / /(__ ) \__,_/ \___/ \___//_/ \__,_//_/ \__,_/ \__//_/ \____//_/ /_//____/ ========================================================================== */ #define die(S) do { fprintf(stderr, S "\n"); exit(1); } while (0) #define ret(S) do { fprintf(stderr, S "\n"); return -1; } while (0) #define diep(S) do { perror(S); exit(1); } while (0) #define retp(S) do { perror(S); return -1; } while (0) #define retpos(S) do { fprintf(stderr, "line %d: " S "\n", g_curr_line); \ return -1; } while (0) #define STRINGIFY(X) #X #define NSTR(N) STRINGIFY(N) #ifndef LINE_MAX # define LINE_MAX 4096 #endif #ifndef SINI_VERSION # define SINI_VERSION "9999" #endif #ifndef PRINT_HELP # define PRINT_HELP 1 #endif #ifndef PRINT_LONG_HELP # define PRINT_LONG_HELP 1 #endif #ifndef SINI_STANDALONE # define SINI_STANDALONE 1 #endif #define ACTION_GET 0 #define ACTION_SET 1 /* these are data gather from command line arguments */ static char *g_file; /* ini file to operate on */ static char *g_section; /* ini section to operate on */ static char *g_key; /* ini key to operate on */ static char *g_value; /* value to store to ini */ static int g_curr_line;/* current line number in ini */ /* ========================================================================== ____ __ _ / __/__ __ ____ _____ / /_ (_)____ ____ _____ / /_ / / / // __ \ / ___// __// // __ \ / __ \ / ___/ / __// /_/ // / / // /__ / /_ / // /_/ // / / /(__ ) /_/ \__,_//_/ /_/ \___/ \__//_/ \____//_/ /_//____/ ========================================================================== */ /* ========================================================================== It obviously prints help message. ========================================================================== */ static void print_usage(void) { #if PRINT_HELP printf( "sini - shell ini file manipulator\n" "\n" "Usage: sini [ -h | -v ]\n" " [get] [<file>] [<section>] <key>\n" " set [<file>] [<section>] <key> <value>\n"); #if PRINT_LONG_HELP printf( "\n" " get get <object> from <file>, used by defaul if not specified\n" " set set <value> in <object> in <file> in non-destructive way\n" " file ini file to manipulate on, optional when SINI_FILE envvar is set\n" " section section name, can be empty or ommited if there is no section\n" " key key of the option in section\n" " value value to store in <file>, put in file as-is\n" "\n"); printf( "examples:\n" "\n" " sini get config.ini server ip\n" " sini config.ini \"section space\" \"and key\"\n" " sini /etc/config.ini \"\" key-in-no-section\n" " sini /etc/config.ini key-no-section\n" " SINI_FILE=config.ini sini server ip\n" "\n" " sini set config.ini server ip 10.1.1.3\n" " sini set config.ini \"section space\" \"and key\" \"value with spaces\"\n" " SINI_FILE=config.ini sini set ip 10.1.1.1\n" ); #endif /* PRINT_LONG_HELP */ #endif /* PRINT_HELP */ } /* ========================================================================== Generates random alphanumeric data into 's'. 'l' number of bytes will be generated, including last '\0' terminator. So when l is 7, 6 random bytes will be stored into 's' and one '\0' at the end. String will contain [a-z] characters ========================================================================== */ void random_string ( char *s, /* generated data will be stored here */ size_t l /* length of the data to generate (with '\0') */ ) { size_t i; /* index */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ for (i = 0; i != l; ++i) s[i] = rand() % 26 + 'a'; s[i - 1] = '\0'; } /* ========================================================================== Checks if `line' contains requested `g_section' ini section. return -1 malformed section, found '[' but not matching ']' 0 this is not the section we are looking for 1 yep, this is the section ========================================================================== */ static int is_section ( char *line /* line to check for section */ ) { char *closing; /* pointer to closing ']' in section */ int ret; /* return code */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ if (*line++ != '[') return 0; if ((closing = strchr(line, ']')) == NULL) retpos("unterminated section found, aborting"); *closing = '\0'; ret = strcmp(line, g_section) == 0; *closing = ']'; return ret; } /* ========================================================================== Checks if `line' contains requested `g_key' ini field. If value is different than NULL, pointer to field value will be stored there. return -2 found '[' which starts new section -1 error parsing ini file 0 line does not contain requested key 1 yes, that line is the line with requested name ========================================================================== */ static int is_key ( char *line, /* line to check for name */ char **value /* pointer to name value will be stored here */ ) { char *delim; /* points to '=' delimiter */ char whites; /* saved whitespace character */ int ret; /* return code */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* check if we hit another section */ if (*line == '[') return -2; if (*line == '=') retpos("empty key detected, aborting"); if ((delim = strchr(line, '=')) == NULL) retpos("missing '=' in key=value, aborting"); if (value) { *value = delim + 1; while (isspace(**value)) ++*value; } while (isspace(delim[-1])) --delim; whites = *delim; *delim = '\0'; ret = strcmp(line, g_key) == 0; *delim = whites; return ret; } /* ========================================================================== Reads single line from ini file. Full line is stores in location pointed by `line' while linelen defines length of `line' buffer. When 0 is returned, `*l' will be pointing to first non-whitespace character in `line' return -2 end of file encountered and no data has been read -1 line too long to fit into `line' buffer 0 line read and it is neither comment nor blank line 1 line read but is unusable per se, it is comment or blank line ========================================================================== */ static int get_line ( FILE *f, char *line, size_t linelen, char **l ) { int overflow; /* flag to indicate too long line */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ *l = line; line[linelen - 1] = 0x7f; g_curr_line++; overflow = 0; if (fgets(line, linelen, f) == NULL) { if (feof(f)) return -2; retp("error reading ini file"); } /* if line is too long, do not quit right away, first let's check * if line is a comment, and if it indeed is we really do not care * if line is too long or not. We can safely ignore such lines */ if (line[linelen - 1] == '\0' && line[linelen - 2] != '\n') { int c; overflow = 1; /* discard whole line not much we can do with it anyway */ while ((c = getc(f)) != '\n' && c != EOF); } while (isspace(**l)) ++*l; /* skip comments and blank lines */ if (**l == ';' || **l == '\0') return 1; if (overflow) retpos("line longer than " NSTR(LINE_MAX) ". Sorry."); return 0; } /* ========================================================================== Reads `g_section'.`g_key' field from `f' file, and prints its value on standard output. ========================================================================== */ static int do_get ( FILE *f /* ini file being parsed */ ) { char *l; /* pointer to line[], for easy manipulation */ char *value; /* pointer to ini value for section.name */ char line[LINE_MAX]; /* line from ini file being curently parsed */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* we support ini without section, so if section was not set, * go right into name lookup */ if (g_section == NULL) goto got_section; /* at first, we need to locate section */ for (;;) { switch (get_line(f, line, sizeof(line), &l)) { case -2: ret("section not found"); /* eof */ case -1: return -1; /* fgets() error */ case 0: break; /* valid ini line */ case 1: continue; /* empty line or comment */ } switch (is_section(l)) { case -1: return -1; /* parse error */ case 1: goto got_section; /* our section found */ case 0: continue; /* not it, keep looking */ } } got_section: /* section found. look for name */ for (;;) { switch (get_line(f, line, sizeof(line), &l)) { case -2: ret("key not found"); /* eof */ case -1: return -1; /* error */ case 0: break; /* valid ini line */ case 1: continue; /* empty line or comment */ } switch (is_key(l, &value)) { case -2: ret("key not found"); /* another section found */ case -1: return -1; /* parse error */ case 0: continue; /* not our name */ case 1: break; /* that is our name, print value */ } fputs(value, stdout); return 0; } } /* ========================================================================== returns pointer to where basename of `s' starts without modifying source `s' pointer. Examples: path basename /path/to/file.c file.c path/to/file.c file.c /file.c file.c file.c file.c "" "" NULL segmentation fault ========================================================================== */ static const char *basenam ( const char *s /* string to basename */ ) { const char *base; /* pointer to base name of path */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ base = s; for (; *s; ++s) if (s[0] == '/' && s[1] != '\0') base = s + 1; return base; } /* ========================================================================== This function will store random temporary path in `path' in format g_file.XXXXXX, where XXXXXX is random string. So for `g_file' `../etc/options.ini' path named `../etc/options.ini.XXXXXX' will be generated. ========================================================================== */ static int gen_tmp_file ( char *path, /* generated path will be put here */ size_t path_size /* size of `path' buffer */ ) { char tmp_part[8]; /* tmp part of file: XXXXXX */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ if (strlen(g_file) + sizeof(tmp_part) > path_size) ret("can't create temp file, path to <file> too large"); if (strlen(basenam(g_file)) + sizeof(tmp_part) > NAME_MAX) ret("can't create temp file, <file> name too large"); tmp_part[0] = '.'; random_string(tmp_part + 1, sizeof(tmp_part) - 1); sprintf(path, "%s%s", g_file, tmp_part); return 0; } /* ========================================================================== Copies all contents from source `fsrc' file to desctination `fdst'. To save some stack memory, reuse memory from upper calls by accepting `line' pointer. Stream pointers are not modified in both `fsrc' and `fdst' before calling, and function will start reading from position that is currently in `fsrc' to position that is currently in `fdst'. Stream pointers will be modified after function is finished. returns 0 on success otherwise -1 is returned. ========================================================================== */ static int copy_file ( FILE *fsrc, /* source file */ FILE *fdst, /* destination file */ char *line, /* buffer to use in fgets() */ size_t linelen /* length of `line' buffer */ ) { size_t r; /* bytes read from fread() */ size_t w; /* bytes written by fwrite() */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ for (;;) { r = fread(line, 1, linelen, fsrc); w = fwrite(line, 1, r, fdst); if (w != r) retp("failed to write data to temp file"); if (r != linelen) { if (feof(fsrc)) return 0; if (ferror(fsrc)) retp("failed to write data to temp file, failed to read ini"); } } } /* ========================================================================== Changes specified `g_object' with new `g_value' value. If `g_object' does not exist, it will be created. ========================================================================== */ static int do_set ( FILE *f /* ini file being parsed */ ) { FILE *ftmp; /* temporary file with new ini content */ char *l; /* pointer to line[], for easy manipulation */ char *value; /* pointer to ini value for section.name */ char line[LINE_MAX]; /* line from ini file being curently parsed */ char tpath[PATH_MAX]; /* path to temporary file */ int ret; /* return code from function */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ ftmp = stdout; if (strcmp(g_file, "-")) { if (gen_tmp_file(tpath, sizeof(tpath)) != 0) return -1; if ((ftmp = fopen(tpath, "w")) == NULL) retp("failed to open temporary data"); } /* we support ini without section, so if section was not set, * go right into name lookup */ if (g_section == NULL) goto got_section; /* at first, we need to locate section */ for (;;) { switch ((ret = get_line(f, line, sizeof(line), &l))) { case -2: /* eof */ ret = 0; fprintf(ftmp, "[%s]\n%s = %s\n", g_section, g_key, g_value); case -1: goto end; /* error */ case 0: break; /* valid ini line */ case 1: fputs(line, ftmp); /* empty line or comment */ continue; } switch ((ret = is_section(l))) { case -1: goto end; /* parse error */ case 1: fputs(line, ftmp); /* our section found */ goto got_section; case 0: fputs(line, ftmp); /* not it, keep looking */ continue; } } got_section: for (;;) { switch ((ret = get_line(f, line, sizeof(line), &l))) { case -2: /* eof */ ret = 0; fprintf(ftmp, "%s = %s\n", g_key, g_value); case -1: goto end; /* error */ case 0: break; /* valid ini line */ case 1: fputs(line, ftmp); /* empty line or comment */ continue; } switch (is_key(l, &value)) { case -2: /* another section found, name not found, create it */ fprintf(ftmp, "%s = %s\n", g_key, g_value); fputs(line, ftmp); ret = copy_file(f, ftmp, line, sizeof(line)); goto end; case 1: /* that is our name, print our line, but do not print * old line (value), it's a replacement after all */ fprintf(ftmp, "%s = %s\n", g_key, g_value); ret = copy_file(f, ftmp, line, sizeof(line)); goto end; case -1: ret = -1; goto end; /* parse error */ case 0: fputs(line, ftmp); /* not our name */ } } end: if (ret == 0 && strcmp(g_file, "-")) if ((ret = rename(tpath, g_file))) perror("do_set(): rename()"); fclose(ftmp); return ret; } /* ========================================================================== _ ____ ___ ____ _ (_)____ / __ `__ \ / __ `// // __ \ / / / / / // /_/ // // / / / /_/ /_/ /_/ \__,_//_//_/ /_/ ========================================================================== */ #if SINI_STANDALONE int main #else int sini_main #endif ( int argc, /* number of arguments in argv */ char *argv[] /* program arguments from command line */ ) { int action; /* set or get from ini? */ int optind; /* current option index to parse */ int ret; /* return code from program */ int argsleft; /* number of arguments left to process */ int section_passed; /* flag, 1 if section is passed in arguments */ FILE *f; /* ini file to operate on */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* ================================================================== Prepare data - parse arguments. ================================================================== */ if (argc == 1) die("no arguments specified, check `sini -h'"); if (argv[1] && argv[1][0] == '-' && argv[1][1] != '\0') { if (argv[1][1] == 'h') print_usage(); if (argv[1][1] == 'v') printf("sini v" SINI_VERSION "\n" "by Michał Łyszczek <[email protected]>\n"); return 0; } /* if action is not specified, use GET by default, then file * will be at index 1 */ optind = 1; action = ACTION_GET; if (argv[1] && strcmp(argv[1], "get") == 0) optind = 2; if (argv[1] && strcmp(argv[1], "set") == 0) { optind = 2; action = ACTION_SET; } if ((g_file = getenv("SINI_FILE")) == NULL) if ((g_file = argv[optind++]) == NULL) die("file not specified, check `sini -h'"); argsleft = argc - optind; section_passed = action == ACTION_GET && argsleft == 2; section_passed = action == ACTION_SET && argsleft == 3 ? 1 : section_passed; if (section_passed) if ((g_section = argv[optind++]) == NULL || g_section[0] == '\0') g_section = NULL; if ((g_key = argv[optind++]) == NULL) die("missing key name, check `sini -h'"); if (action == ACTION_SET) if ((g_value = argv[optind++]) == NULL) die("value not specified, check `sini -h'"); /* ================================================================== Arguments should be parsed and validated by now, so just run requested action. ================================================================== */ if (strcmp(g_file, "-") == 0) f = stdin; /* altough we do not write to <file> with `set' command (we use * rename(3) so we need write permissions to directory not * file), we still try to open <file> with write access, as it * is not nice to write (or remove and create new in our case) * to a write protected fle */ else if ((f = fopen(g_file, action == ACTION_SET ? "r+" : "r")) == NULL) diep("failed to open <file>"); srand(time(NULL)); ret = action == ACTION_SET ? do_set(f) : do_get(f); /* we may close stdin here, but that's ok */ fclose(f); return -ret; }
the_stack_data/18887425.c
#include<stdio.h> int fact(int n) { if ( n>0 ) return n*fact(n-1); else return 1; } int main() { int num, res; printf("\nEnter a number : "); scanf("%d", &num); res = fact(num); printf("\n%d! = %d\n\n", num, res); return (0); }
the_stack_data/193892835.c
/* FNA3D - 3D Graphics Library for FNA * * Copyright (c) 2020-2021 Ethan Lee * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in a * product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * Ethan "flibitijibibo" Lee <[email protected]> * */ #if FNA3D_DRIVER_METAL #include "FNA3D_Driver_Metal.h" #include "FNA3D_PipelineCache.h" /* Internal Structures */ typedef struct MetalTexture /* Cast from FNA3D_Texture* */ { MTLTexture *handle; uint8_t hasMipmaps; int32_t width; int32_t height; uint8_t isPrivate; uint8_t bound; FNA3D_SurfaceFormat format; struct MetalTexture *next; /* FIXME: Remove this */ } MetalTexture; static MetalTexture NullTexture = { NULL, 0, 0, 0, 0, 0, FNA3D_SURFACEFORMAT_COLOR, NULL }; typedef struct MetalSubBuffer { MTLBuffer *buffer; uint8_t *ptr; int32_t offset; } MetalSubBuffer; typedef struct MetalBuffer /* Cast from FNA3D_Buffer* */ { int32_t size; int32_t subBufferCount; int32_t subBufferCapacity; int32_t currentSubBufferIndex; uint8_t bound; MetalSubBuffer *subBuffers; } MetalBuffer; typedef struct MetalBufferAllocator { #define PHYSICAL_BUFFER_BASE_SIZE 4000000 #define PHYSICAL_BUFFER_MAX_COUNT 7 MTLBuffer *physicalBuffers[PHYSICAL_BUFFER_MAX_COUNT]; int32_t totalAllocated[PHYSICAL_BUFFER_MAX_COUNT]; } MetalBufferAllocator; typedef struct MetalRenderbuffer /* Cast from FNA3D_Renderbuffer* */ { MTLTexture *handle; MTLTexture *multiSampleHandle; MTLPixelFormat pixelFormat; int32_t multiSampleCount; } MetalRenderbuffer; typedef struct MetalEffect /* Cast from FNA3D_Effect* */ { MOJOSHADER_effect *effect; void *library; /* MTLLibrary */ } MetalEffect; typedef struct MetalQuery /* Cast from FNA3D_Query* */ { MTLBuffer *handle; } MetalQuery; typedef struct MetalBackbuffer { int32_t width; int32_t height; FNA3D_SurfaceFormat surfaceFormat; FNA3D_DepthFormat depthFormat; int32_t multiSampleCount; uint8_t preserveDepthStencil; MTLTexture *colorBuffer; MTLTexture *multiSampleColorBuffer; MTLTexture *depthStencilBuffer; } MetalBackbuffer; typedef struct PackedRenderPipeline { MOJOSHADER_mtlShader *vshader, *pshader; PackedState blendState; MTLPixelFormat colorFormats[4]; MTLPixelFormat depthFormat; MTLVertexDescriptor *vertexDescriptor; int32_t sampleCount; } PackedRenderPipeline; typedef struct PackedRenderPipelineMap { PackedRenderPipeline key; MTLRenderPipelineState *value; } PackedRenderPipelineMap; typedef struct PackedRenderPipelineArray { PackedRenderPipelineMap *elements; int32_t count; int32_t capacity; } PackedRenderPipelineArray; typedef struct MetalRenderer /* Cast from FNA3D_Renderer* */ { /* Associated FNA3D_Device */ FNA3D_Device *parentDevice; /* The Faux-Backbuffer */ MetalBackbuffer *backbuffer; uint8_t backbufferSizeChanged; FNA3D_Rect prevSrcRect; FNA3D_Rect prevDstRect; MTLBuffer *backbufferDrawBuffer; MTLSamplerState *backbufferSamplerState; MTLRenderPipelineState *backbufferPipeline; /* Capabilities */ uint8_t isMac; uint8_t supportsS3tc; uint8_t supportsDxt1; uint8_t supportsOcclusionQueries; uint8_t maxMultiSampleCount; /* Basic Metal Objects */ SDL_MetalView view; CAMetalLayer *layer; MTLDevice *device; MTLCommandQueue *queue; /* Active Metal State */ MTLCommandBuffer *commandBuffer; MTLCommandBuffer *committedCommandBuffer; MTLRenderCommandEncoder *renderCommandEncoder; MTLBuffer *currentVisibilityBuffer; MTLVertexDescriptor *currentVertexDescriptor; uint8_t needNewRenderPass; uint8_t frameInProgress; /* Autorelease Pool */ NSAutoreleasePool *pool; /* Blend State */ FNA3D_Color blendColor; int32_t multiSampleMask; FNA3D_BlendState blendState; MTLRenderPipelineState *ldPipelineState; /* Stencil State */ int32_t stencilRef; /* Rasterizer State */ uint8_t scissorTestEnable; FNA3D_CullMode cullFrontFace; FNA3D_FillMode fillMode; float depthBias; float slopeScaleDepthBias; uint8_t multiSampleEnable; /* Viewport State */ FNA3D_Viewport viewport; FNA3D_Rect scissorRect; int32_t currentAttachmentWidth; int32_t currentAttachmentHeight; /* Textures */ MetalTexture *textures[MAX_TOTAL_SAMPLERS]; MTLSamplerState *samplers[MAX_TOTAL_SAMPLERS]; uint8_t textureNeedsUpdate[MAX_TOTAL_SAMPLERS]; uint8_t samplerNeedsUpdate[MAX_TOTAL_SAMPLERS]; MetalTexture *transientTextures; MetalTexture **texturesInUse; int32_t numTexturesInUse; int32_t maxTexturesInUse; /* Depth Stencil State */ FNA3D_DepthStencilState depthStencilState; MTLDepthStencilState *defaultDepthStencilState; MTLDepthStencilState *ldDepthStencilState; MTLPixelFormat D16Format; MTLPixelFormat D24Format; MTLPixelFormat D24S8Format; /* Buffers */ MetalBufferAllocator *bufferAllocator; MetalBuffer **buffersInUse; int32_t numBuffersInUse; int32_t maxBuffersInUse; MTLBuffer *ldUniformBuffer; int32_t ldVertUniformOffset; int32_t ldFragUniformOffset; MTLBuffer *ldVertexBuffers[MAX_BOUND_VERTEX_BUFFERS]; int32_t ldVertexBufferOffsets[MAX_BOUND_VERTEX_BUFFERS]; /* Render Targets */ MTLTexture *currentAttachments[MAX_RENDERTARGET_BINDINGS]; MTLPixelFormat currentColorFormats[MAX_RENDERTARGET_BINDINGS]; MTLTexture *currentMSAttachments[MAX_RENDERTARGET_BINDINGS]; FNA3D_CubeMapFace currentAttachmentSlices[MAX_RENDERTARGET_BINDINGS]; MTLTexture *currentDepthStencilBuffer; FNA3D_DepthFormat currentDepthFormat; int32_t currentSampleCount; uint8_t preserveDepthStencil; /* Clear Cache */ FNA3D_Vec4 clearColor; float clearDepth; int32_t clearStencil; uint8_t shouldClearColor; uint8_t shouldClearDepth; uint8_t shouldClearStencil; /* Pipeline State Object Caches */ PackedRenderPipelineArray pipelineStateCache; PackedStateArray depthStencilStateCache; PackedStateArray samplerStateCache; PackedVertexBufferBindingsArray vertexDescriptorCache; /* MojoShader Interop */ MOJOSHADER_mtlContext *mtlContext; MOJOSHADER_effect *currentEffect; const MOJOSHADER_effectTechnique *currentTechnique; uint32_t currentPass; } MetalRenderer; /* XNA->Metal Translation Arrays */ static MTLPixelFormat XNAToMTL_TextureFormat[] = { MTLPixelFormatRGBA8Unorm, /* SurfaceFormat.Color */ #if defined(__IPHONEOS__) || defined(__TVOS__) MTLPixelFormatB5G6R5Unorm, /* SurfaceFormat.Bgr565 */ MTLPixelFormatBGR5A1Unorm, /* SurfaceFormat.Bgra5551 */ MTLPixelFormatABGR4Unorm, /* SurfaceFormat.Bgra4444 */ #else MTLPixelFormatBGRA8Unorm, /* SurfaceFormat.Bgr565 */ MTLPixelFormatBGRA8Unorm, /* SurfaceFormat.Bgra5551 */ MTLPixelFormatBGRA8Unorm, /* SurfaceFormat.Bgra4444 */ #endif MTLPixelFormatBC1RGBA, /* SurfaceFormat.Dxt1 */ MTLPixelFormatBC2RGBA, /* SurfaceFormat.Dxt3 */ MTLPixelFormatBC3RGBA, /* SurfaceFormat.Dxt5 */ MTLPixelFormatRG8Snorm, /* SurfaceFormat.NormalizedByte2 */ MTLPixelFormatRG16Snorm, /* SurfaceFormat.NormalizedByte4 */ MTLPixelFormatRGB10A2Unorm, /* SurfaceFormat.Rgba1010102 */ MTLPixelFormatRG16Unorm, /* SurfaceFormat.Rg32 */ MTLPixelFormatRGBA16Unorm, /* SurfaceFormat.Rgba64 */ MTLPixelFormatA8Unorm, /* SurfaceFormat.Alpha8 */ MTLPixelFormatR32Float, /* SurfaceFormat.Single */ MTLPixelFormatRG32Float, /* SurfaceFormat.Vector2 */ MTLPixelFormatRGBA32Float, /* SurfaceFormat.Vector4 */ MTLPixelFormatR16Float, /* SurfaceFormat.HalfSingle */ MTLPixelFormatRG16Float, /* SurfaceFormat.HalfVector2 */ MTLPixelFormatRGBA16Float, /* SurfaceFormat.HalfVector4 */ MTLPixelFormatRGBA16Float, /* SurfaceFormat.HdrBlendable */ MTLPixelFormatBGRA8Unorm, /* SurfaceFormat.ColorBgraEXT */ }; static MTLPixelFormat XNAToMTL_DepthFormat( MetalRenderer *renderer, FNA3D_DepthFormat format ) { switch (format) { case FNA3D_DEPTHFORMAT_D16: return renderer->D16Format; case FNA3D_DEPTHFORMAT_D24: return renderer->D24Format; case FNA3D_DEPTHFORMAT_D24S8: return renderer->D24S8Format; case FNA3D_DEPTHFORMAT_NONE: return MTLPixelFormatInvalid; } } static MTLVertexFormat XNAToMTL_VertexAttribType[] = { MTLVertexFormatFloat, /* VertexElementFormat.Single */ MTLVertexFormatFloat2, /* VertexElementFormat.Vector2 */ MTLVertexFormatFloat3, /* VertexElementFormat.Vector3 */ MTLVertexFormatFloat4, /* VertexElementFormat.Vector4 */ MTLVertexFormatUChar4Normalized, /* VertexElementFormat.Color */ MTLVertexFormatUChar4, /* VertexElementFormat.Byte4 */ MTLVertexFormatShort2, /* VertexElementFormat.Short2 */ MTLVertexFormatShort4, /* VertexElementFormat.Short4 */ MTLVertexFormatShort2Normalized, /* VertexElementFormat.NormalizedShort2 */ MTLVertexFormatShort4Normalized, /* VertexElementFormat.NormalizedShort4 */ MTLVertexFormatHalf2, /* VertexElementFormat.HalfVector2 */ MTLVertexFormatHalf4 /* VertexElementFormat.HalfVector4 */ }; static MTLIndexType XNAToMTL_IndexType[] = { MTLIndexTypeUInt16, /* IndexElementSize.SixteenBits */ MTLIndexTypeUInt32 /* IndexElementSize.ThirtyTwoBits */ }; static MTLBlendFactor XNAToMTL_BlendMode[] = { MTLBlendFactorOne, /* Blend.One */ MTLBlendFactorZero, /* Blend.Zero */ MTLBlendFactorSourceColor, /* Blend.SourceColor */ MTLBlendFactorOneMinusSourceColor, /* Blend.InverseSourceColor */ MTLBlendFactorSourceAlpha, /* Blend.SourceAlpha */ MTLBlendFactorOneMinusSourceAlpha, /* Blend.InverseSourceAlpha */ MTLBlendFactorDestinationColor, /* Blend.DestinationColor */ MTLBlendFactorOneMinusDestinationColor, /* Blend.InverseDestinationColor */ MTLBlendFactorDestinationAlpha, /* Blend.DestinationAlpha */ MTLBlendFactorOneMinusDestinationAlpha, /* Blend.InverseDestinationAlpha */ MTLBlendFactorBlendColor, /* Blend.BlendFactor */ MTLBlendFactorOneMinusBlendColor, /* Blend.InverseBlendFactor */ MTLBlendFactorSourceAlphaSaturated /* Blend.SourceAlphaSaturation */ }; static MTLBlendOperation XNAToMTL_BlendOperation[] = { MTLBlendOperationAdd, /* BlendFunction.Add */ MTLBlendOperationSubtract, /* BlendFunction.Subtract */ MTLBlendOperationReverseSubtract, /* BlendFunction.ReverseSubtract */ MTLBlendOperationMax, /* BlendFunction.Max */ MTLBlendOperationMin /* BlendFunction.Min */ }; static int32_t XNAToMTL_ColorWriteMask(FNA3D_ColorWriteChannels channels) { if (channels == FNA3D_COLORWRITECHANNELS_NONE) { return 0x0; } if (channels == FNA3D_COLORWRITECHANNELS_ALL) { return 0xf; } int ret = 0; if ((channels & FNA3D_COLORWRITECHANNELS_RED) != 0) { ret |= (0x1 << 3); } if ((channels & FNA3D_COLORWRITECHANNELS_GREEN) != 0) { ret |= (0x1 << 2); } if ((channels & FNA3D_COLORWRITECHANNELS_BLUE) != 0) { ret |= (0x1 << 1); } if ((channels & FNA3D_COLORWRITECHANNELS_ALPHA) != 0) { ret |= (0x1 << 0); } return ret; } static MTLCompareFunction XNAToMTL_CompareFunc[] = { MTLCompareFunctionAlways, /* CompareFunction.Always */ MTLCompareFunctionNever, /* CompareFunction.Never */ MTLCompareFunctionLess, /* CompareFunction.Less */ MTLCompareFunctionLessEqual, /* CompareFunction.LessEqual */ MTLCompareFunctionEqual, /* CompareFunction.Equal */ MTLCompareFunctionGreaterEqual, /* CompareFunction.GreaterEqual */ MTLCompareFunctionGreater, /* CompareFunction.Greater */ MTLCompareFunctionNotEqual /* CompareFunction.NotEqual */ }; static MTLStencilOperation XNAToMTL_StencilOp[] = { MTLStencilOperationKeep, /* StencilOperation.Keep */ MTLStencilOperationZero, /* StencilOperation.Zero */ MTLStencilOperationReplace, /* StencilOperation.Replace */ MTLStencilOperationIncrementWrap, /* StencilOperation.Increment */ MTLStencilOperationDecrementWrap, /* StencilOperation.Decrement */ MTLStencilOperationIncrementClamp, /* StencilOperation.IncrementSaturation */ MTLStencilOperationDecrementClamp, /* StencilOperation.DecrementSaturation */ MTLStencilOperationInvert /* StencilOperation.Invert */ }; static MTLTriangleFillMode XNAToMTL_FillMode[] = { MTLTriangleFillModeFill, /* FillMode.Solid */ MTLTriangleFillModeLines, /* FillMode.WireFrame */ }; static float XNAToMTL_DepthBiasScale(MTLPixelFormat format) { switch (format) { case MTLPixelFormatDepth16Unorm: return (float) ((1 << 16) - 1); case MTLPixelFormatDepth24UnormStencil8: return (float) ((1 << 24) - 1); case MTLPixelFormatDepth32Float: case MTLPixelFormatDepth32FloatStencil8: return (float) ((1 << 23) - 1); default: return 0.0f; } SDL_assert(0 && "Invalid depth pixel format!"); } static MTLCullMode XNAToMTL_CullingEnabled[] = { MTLCullModeNone, /* CullMode.None */ MTLCullModeFront, /* CullMode.CullClockwiseFace */ MTLCullModeBack /* CullMode.CullCounterClockwiseFace */ }; static MTLSamplerAddressMode XNAToMTL_Wrap[] = { MTLSamplerAddressModeRepeat, /* TextureAddressMode.Wrap */ MTLSamplerAddressModeClampToEdge, /* TextureAddressMode.Clamp */ MTLSamplerAddressModeMirrorRepeat /* TextureAddressMode.Mirror */ }; static MTLSamplerMinMagFilter XNAToMTL_MagFilter[] = { MTLSamplerMinMagFilterLinear, /* TextureFilter.Linear */ MTLSamplerMinMagFilterNearest, /* TextureFilter.Point */ MTLSamplerMinMagFilterLinear, /* TextureFilter.Anisotropic */ MTLSamplerMinMagFilterLinear, /* TextureFilter.LinearMipPoint */ MTLSamplerMinMagFilterNearest, /* TextureFilter.PointMipLinear */ MTLSamplerMinMagFilterNearest, /* TextureFilter.MinLinearMagPointMipLinear */ MTLSamplerMinMagFilterNearest, /* TextureFilter.MinLinearMagPointMipPoint */ MTLSamplerMinMagFilterLinear, /* TextureFilter.MinPointMagLinearMipLinear */ MTLSamplerMinMagFilterLinear /* TextureFilter.MinPointMagLinearMipPoint */ }; static MTLSamplerMipFilter XNAToMTL_MipFilter[] = { MTLSamplerMipFilterLinear, /* TextureFilter.Linear */ MTLSamplerMipFilterNearest, /* TextureFilter.Point */ MTLSamplerMipFilterLinear, /* TextureFilter.Anisotropic */ MTLSamplerMipFilterNearest, /* TextureFilter.LinearMipPoint */ MTLSamplerMipFilterLinear, /* TextureFilter.PointMipLinear */ MTLSamplerMipFilterLinear, /* TextureFilter.MinLinearMagPointMipLinear */ MTLSamplerMipFilterNearest, /* TextureFilter.MinLinearMagPointMipPoint */ MTLSamplerMipFilterLinear, /* TextureFilter.MinPointMagLinearMipLinear */ MTLSamplerMipFilterNearest /* TextureFilter.MinPointMagLinearMipPoint */ }; static MTLSamplerMinMagFilter XNAToMTL_MinFilter[] = { MTLSamplerMinMagFilterLinear, /* TextureFilter.Linear */ MTLSamplerMinMagFilterNearest, /* TextureFilter.Point */ MTLSamplerMinMagFilterLinear, /* TextureFilter.Anisotropic */ MTLSamplerMinMagFilterLinear, /* TextureFilter.LinearMipPoint */ MTLSamplerMinMagFilterNearest, /* TextureFilter.PointMipLinear */ MTLSamplerMinMagFilterLinear, /* TextureFilter.MinLinearMagPointMipLinear */ MTLSamplerMinMagFilterLinear, /* TextureFilter.MinLinearMagPointMipPoint */ MTLSamplerMinMagFilterNearest, /* TextureFilter.MinPointMagLinearMipLinear */ MTLSamplerMinMagFilterNearest /* TextureFilter.MinPointMagLinearMipPoint */ }; static MTLPrimitiveType XNAToMTL_Primitive[] = { MTLPrimitiveTypeTriangle, /* PrimitiveType.TriangleList */ MTLPrimitiveTypeTriangleStrip, /* PrimitiveType.TriangleStrip */ MTLPrimitiveTypeLine, /* PrimitiveType.LineList */ MTLPrimitiveTypeLineStrip, /* PrimitiveType.LineStrip */ MTLPrimitiveTypePoint /* PrimitiveType.PointListEXT */ }; /* Texture Helper Functions */ static inline int32_t METAL_INTERNAL_ClosestMSAAPower(int32_t value) { /* Checking for the highest power of two _after_ than the given int: * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 * Take result, divide by 2, get the highest power of two _before_! * -flibit */ if (value == 1) { /* ... Except for 1, which is invalid for MSAA -flibit */ return 0; } int result = value - 1; result |= result >> 1; result |= result >> 2; result |= result >> 4; result |= result >> 8; result |= result >> 16; result += 1; if (result == value) { return result; } return result >> 1; } static inline int32_t METAL_INTERNAL_GetCompatibleSampleCount( MetalRenderer *renderer, int32_t sampleCount ) { /* If the device does not support the requested * multisample count, halve it until we find a * value that is supported. */ while ( sampleCount > 0 && !mtlDeviceSupportsSampleCount(renderer->device, sampleCount)) { sampleCount = METAL_INTERNAL_ClosestMSAAPower(sampleCount / 2); } return sampleCount; } static MetalTexture* CreateTexture( MetalRenderer *renderer, MTLTexture *texture, FNA3D_SurfaceFormat format, int32_t width, int32_t height, int32_t levelCount, uint8_t isRenderTarget ) { MetalTexture *result = SDL_malloc(sizeof(MetalTexture)); result->handle = texture; result->width = width; result->height = height; result->format = format; result->hasMipmaps = levelCount > 1; result->isPrivate = isRenderTarget; result->bound = 0; result->next = NULL; return result; } /* Render Command Encoder Functions */ static void METAL_INTERNAL_SetEncoderStencilReferenceValue( MetalRenderer *renderer ) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetStencilReferenceValue( renderer->renderCommandEncoder, renderer->stencilRef ); } } static void METAL_INTERNAL_SetEncoderBlendColor(MetalRenderer *renderer) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetBlendColor( renderer->renderCommandEncoder, renderer->blendColor.r / 255.0f, renderer->blendColor.g / 255.0f, renderer->blendColor.b / 255.0f, renderer->blendColor.a / 255.0f ); } } static void METAL_INTERNAL_SetEncoderViewport(MetalRenderer *renderer) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetViewport( renderer->renderCommandEncoder, renderer->viewport.x, renderer->viewport.y, renderer->viewport.w, renderer->viewport.h, (double) renderer->viewport.minDepth, (double) renderer->viewport.maxDepth ); } } static void METAL_INTERNAL_SetEncoderScissorRect(MetalRenderer *renderer) { FNA3D_Rect rect = renderer->scissorRect; int32_t x0, y0, x1, y1; if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { if (!renderer->scissorTestEnable) { /* Default to the size of the current RT */ x0 = 0; y0 = 0; x1 = renderer->currentAttachmentWidth; y1 = renderer->currentAttachmentHeight; } else { /* Keep the rect within the RT dimensions */ x0 = SDL_max(0, rect.x); y0 = SDL_max(0, rect.y); x1 = SDL_min(rect.x + rect.w, renderer->currentAttachmentWidth - 1); y1 = SDL_min(rect.y + rect.h, renderer->currentAttachmentHeight - 1); } mtlSetScissorRect( renderer->renderCommandEncoder, x0, y0, x1 - x0, y1 - y0 ); } } static void METAL_INTERNAL_SetEncoderCullMode(MetalRenderer *renderer) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetCullMode( renderer->renderCommandEncoder, XNAToMTL_CullingEnabled[renderer->cullFrontFace] ); } } static void METAL_INTERNAL_SetEncoderFillMode(MetalRenderer *renderer) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetTriangleFillMode( renderer->renderCommandEncoder, XNAToMTL_FillMode[renderer->fillMode] ); } } static void METAL_INTERNAL_SetEncoderDepthBias(MetalRenderer *renderer) { if ( renderer->renderCommandEncoder != NULL && !renderer->needNewRenderPass ) { mtlSetDepthBias( renderer->renderCommandEncoder, renderer->depthBias, renderer->slopeScaleDepthBias, 0.0f /* no clamp */ ); } } static void METAL_INTERNAL_EndPass(MetalRenderer *renderer) { if (renderer->renderCommandEncoder != NULL) { mtlEndEncoding(renderer->renderCommandEncoder); renderer->renderCommandEncoder = NULL; } } static void METAL_INTERNAL_BeginFrame(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; if (renderer->frameInProgress) return; /* Wait for the last command buffer to complete... */ if (renderer->committedCommandBuffer != NULL) { mtlWaitUntilCompleted(renderer->committedCommandBuffer); objc_release(renderer->committedCommandBuffer); renderer->committedCommandBuffer = NULL; } /* The cycle begins anew! */ renderer->frameInProgress = 1; renderer->pool = objc_autoreleasePoolPush(); renderer->commandBuffer = mtlMakeCommandBuffer(renderer->queue); } static void METAL_INTERNAL_UpdateRenderPass(MetalRenderer *renderer) { MTLRenderPassDescriptor *passDesc; MTLRenderPassColorAttachmentDescriptor *colorAttachment; MTLRenderPassDepthAttachmentDescriptor *depthAttachment; MTLRenderPassStencilAttachmentDescriptor *stencilAttachment; int32_t i; if (!renderer->needNewRenderPass) { /* Nothing for us to do! */ return; } /* Normally the frame begins in BeginDraw(), * but some games perform drawing outside * of the Draw method (e.g. initializing * render targets in LoadContent). This call * ensures that we catch any unexpected draws. * -caleb */ METAL_INTERNAL_BeginFrame((FNA3D_Renderer*) renderer); /* Wrap up rendering with the old encoder */ METAL_INTERNAL_EndPass(renderer); /* Generate the descriptor */ passDesc = mtlMakeRenderPassDescriptor(); /* Bind color attachments */ for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1) { if (renderer->currentAttachments[i] == NULL) { continue; } colorAttachment = mtlGetColorAttachment(passDesc, i); mtlSetAttachmentTexture( colorAttachment, renderer->currentAttachments[i] ); mtlSetAttachmentSlice( colorAttachment, renderer->currentAttachmentSlices[i] ); /* Multisample? */ if (renderer->currentSampleCount > 0) { mtlSetAttachmentTexture( colorAttachment, renderer->currentMSAttachments[i] ); mtlSetAttachmentSlice( colorAttachment, 0 ); mtlSetAttachmentResolveTexture( colorAttachment, renderer->currentAttachments[i] ); mtlSetAttachmentStoreAction( colorAttachment, MTLStoreActionMultisampleResolve ); mtlSetAttachmentResolveSlice( colorAttachment, renderer->currentAttachmentSlices[i] ); } /* Clear color */ if (renderer->shouldClearColor) { mtlSetAttachmentLoadAction( colorAttachment, MTLLoadActionClear ); mtlSetAttachmentClearColor( colorAttachment, renderer->clearColor.x, renderer->clearColor.y, renderer->clearColor.z, renderer->clearColor.w ); } else { mtlSetAttachmentLoadAction( colorAttachment, MTLLoadActionLoad ); } } /* Bind depth attachment */ if (renderer->currentDepthFormat != FNA3D_DEPTHFORMAT_NONE) { depthAttachment = mtlGetDepthAttachment(passDesc); mtlSetAttachmentTexture( depthAttachment, renderer->currentDepthStencilBuffer ); mtlSetAttachmentStoreAction( depthAttachment, (renderer->preserveDepthStencil) ? MTLStoreActionStore : MTLStoreActionDontCare ); /* Clear? */ if (renderer->shouldClearDepth) { mtlSetAttachmentLoadAction( depthAttachment, MTLLoadActionClear ); mtlSetAttachmentClearDepth( depthAttachment, renderer->clearDepth ); } else { mtlSetAttachmentLoadAction( depthAttachment, (renderer->preserveDepthStencil) ? MTLLoadActionLoad : MTLLoadActionDontCare ); } } /* Bind stencil attachment */ if (renderer->currentDepthFormat == FNA3D_DEPTHFORMAT_D24S8) { stencilAttachment = mtlGetStencilAttachment(passDesc); mtlSetAttachmentTexture( stencilAttachment, renderer->currentDepthStencilBuffer ); mtlSetAttachmentStoreAction( stencilAttachment, (renderer->preserveDepthStencil) ? MTLStoreActionStore : MTLStoreActionDontCare ); /* Clear? */ if (renderer->shouldClearStencil) { mtlSetAttachmentLoadAction( stencilAttachment, MTLLoadActionClear ); mtlSetAttachmentClearStencil( stencilAttachment, renderer->clearStencil ); } else { mtlSetAttachmentLoadAction( stencilAttachment, (renderer->preserveDepthStencil) ? MTLLoadActionLoad : MTLLoadActionDontCare ); } } /* Get attachment size */ renderer->currentAttachmentWidth = mtlGetTextureWidth( renderer->currentAttachments[0] ); renderer->currentAttachmentHeight = mtlGetTextureHeight( renderer->currentAttachments[0] ); /* Attach the visibility buffer, if needed */ if (renderer->currentVisibilityBuffer != NULL) { mtlSetVisibilityResultBuffer( passDesc, renderer->currentVisibilityBuffer ); } /* Make a new encoder */ renderer->renderCommandEncoder = mtlMakeRenderCommandEncoder( renderer->commandBuffer, passDesc ); /* Reset the flags */ renderer->needNewRenderPass = 0; renderer->shouldClearColor = 0; renderer->shouldClearDepth = 0; renderer->shouldClearStencil = 0; /* Apply the dynamic state */ METAL_INTERNAL_SetEncoderViewport(renderer); METAL_INTERNAL_SetEncoderScissorRect(renderer); METAL_INTERNAL_SetEncoderBlendColor(renderer); METAL_INTERNAL_SetEncoderStencilReferenceValue(renderer); METAL_INTERNAL_SetEncoderCullMode(renderer); METAL_INTERNAL_SetEncoderFillMode(renderer); METAL_INTERNAL_SetEncoderDepthBias(renderer); /* Start visibility buffer counting */ if (renderer->currentVisibilityBuffer != NULL) { mtlSetVisibilityResultMode( renderer->renderCommandEncoder, MTLVisibilityResultModeCounting, 0 ); } /* Reset the bindings */ for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1) { if (renderer->textures[i] != &NullTexture) { renderer->textureNeedsUpdate[i] = 1; } if (renderer->samplers[i] != NULL) { renderer->samplerNeedsUpdate[i] = 1; } } renderer->ldDepthStencilState = NULL; renderer->ldUniformBuffer = NULL; renderer->ldVertUniformOffset = 0; renderer->ldFragUniformOffset = 0; renderer->ldPipelineState = NULL; for (i = 0; i < MAX_BOUND_VERTEX_BUFFERS; i += 1) { renderer->ldVertexBuffers[i] = NULL; renderer->ldVertexBufferOffsets[i] = 0; } } /* Pipeline Flush Functions */ static void METAL_INTERNAL_MarkBufferAsBound( MetalRenderer *renderer, MetalBuffer *buf ) { if (buf->bound) return; buf->bound = 1; if (renderer->numBuffersInUse == renderer->maxBuffersInUse) { renderer->maxBuffersInUse *= 2; renderer->buffersInUse = SDL_realloc( renderer->buffersInUse, sizeof(MetalBuffer*) * renderer->maxBuffersInUse ); } renderer->buffersInUse[renderer->numBuffersInUse] = buf; renderer->numBuffersInUse += 1; } static inline void METAL_INTERNAL_ResetBuffers(MetalRenderer *renderer) { int32_t i; for (i = 0; i < renderer->numBuffersInUse; i += 1) { if (renderer->buffersInUse[i] != NULL) { renderer->buffersInUse[i]->bound = 0; renderer->buffersInUse[i]->currentSubBufferIndex = 0; renderer->buffersInUse[i] = NULL; } } renderer->numBuffersInUse = 0; } static void METAL_INTERNAL_MarkTextureAsBound( MetalRenderer *renderer, MetalTexture *tex ) { if (tex->bound) return; tex->bound = 1; if (renderer->numTexturesInUse == renderer->maxTexturesInUse) { renderer->maxTexturesInUse *= 2; renderer->texturesInUse = SDL_realloc( renderer->texturesInUse, sizeof(MetalTexture*) * renderer->maxTexturesInUse ); } renderer->texturesInUse[renderer->numTexturesInUse] = tex; renderer->numTexturesInUse += 1; } static inline void METAL_INTERNAL_ResetTextures(MetalRenderer *renderer) { int32_t i; for (i = 0; i < renderer->numTexturesInUse; i += 1) { if (renderer->texturesInUse[i] != NULL) { renderer->texturesInUse[i]->bound = 0; renderer->texturesInUse[i] = NULL; } } renderer->numTexturesInUse = 0; } static void METAL_INTERNAL_Flush(MetalRenderer *renderer) { METAL_INTERNAL_EndPass(renderer); mtlCommitCommandBuffer(renderer->commandBuffer); mtlWaitUntilCompleted(renderer->commandBuffer); renderer->commandBuffer = mtlMakeCommandBuffer(renderer->queue); renderer->needNewRenderPass = 1; METAL_INTERNAL_ResetBuffers(renderer); METAL_INTERNAL_ResetTextures(renderer); } /* Buffer Helper Functions */ static int32_t METAL_INTERNAL_NextHighestAlignment(int32_t n, int32_t align) { return align * ((n + align - 1) / align); } static void METAL_INTERNAL_AllocateSubBuffer( MetalRenderer *renderer, MetalBuffer *buffer ) { /* This allocation strategy uses a "bucketing" system with a fixed * number of buckets, each one larger than the last. Buffers will * go into the first available bucket that accomodates their size, * even if there is a larger bucket already allocated that they * could fit into. * * Depending on the data, this may lead to unnecessary allocations, * but on the other hand it ensures that small buffers don't crowd * out the larger buckets that are required for very big buffers. * The majority of FNA games probably won't exceed the first bucket. * * In the worst case, the first buffer allocated is >64MB and thus * requires the 128MB bucket. Any future buffers <64MB will *not* * get slotted into the 128MB bucket, even though they could fit. * Instead, smaller buckets will be allocated. The larger buckets * can receive overflow from the smaller buckets if they get full, * but all the smaller buckets will be allocated and filled first. * * The maximum bucket size is 256MB, which should be plenty of room. * If your game is using over 4+8+16+32+64+128+256 MB of buffer data, * you're probably doing something wrong. * * -caleb */ int32_t totalPhysicalSize, totalAllocated, i, alignedAlloc; MetalSubBuffer *subBuffer; /* Which physical buffer should we suballocate from? */ for (i = 0; i < PHYSICAL_BUFFER_MAX_COUNT; i += 1) { totalPhysicalSize = PHYSICAL_BUFFER_BASE_SIZE << i; totalAllocated = renderer->bufferAllocator->totalAllocated[i]; alignedAlloc = METAL_INTERNAL_NextHighestAlignment( totalAllocated + buffer->size, 4 ); if (alignedAlloc <= totalPhysicalSize) { /* It fits! */ break; } } if (i == PHYSICAL_BUFFER_MAX_COUNT) { /* FIXME: How should we handle this? */ FNA3D_LogError("Oh crap, we're totally out of buffer room!!!"); return; } /* Create the physical buffer if needed */ if (renderer->bufferAllocator->physicalBuffers[i] == NULL) { renderer->bufferAllocator->physicalBuffers[i] = mtlNewBuffer( renderer->device, totalPhysicalSize, 0 /* FIXME: MTLResourceHazardTrackingModeUntracked? */ ); } /* Reallocate the subbuffer array if we're at max capacity */ if (buffer->subBufferCount == buffer->subBufferCapacity) { buffer->subBufferCapacity *= 2; buffer->subBuffers = SDL_realloc( buffer->subBuffers, sizeof(MetalSubBuffer) * buffer->subBufferCapacity ); } /* Populate the given MetalSubBuffer */ subBuffer = &buffer->subBuffers[buffer->subBufferCount]; subBuffer->buffer = renderer->bufferAllocator->physicalBuffers[i]; subBuffer->offset = totalAllocated; subBuffer->ptr = ( (uint8_t*) mtlGetBufferContents(subBuffer->buffer) + subBuffer->offset ); /* Mark how much we've just allocated, rounding up for alignment */ renderer->bufferAllocator->totalAllocated[i] = alignedAlloc; buffer->subBufferCount += 1; } static FNA3D_Buffer* METAL_INTERNAL_CreateBuffer( FNA3D_Renderer *driverData, int32_t size ) { MetalBuffer *result = SDL_malloc(sizeof(MetalBuffer)); SDL_memset(result, '\0', sizeof(MetalBuffer)); result->size = size; result->subBufferCapacity = 4; result->subBuffers = SDL_malloc( sizeof(MetalSubBuffer) * result->subBufferCapacity ); return (FNA3D_Buffer*) result; } static void METAL_INTERNAL_DestroyBuffer( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalBuffer *mtlBuffer = (MetalBuffer*) buffer; int32_t i; if (mtlBuffer->bound) { for (i = 0; i < renderer->numBuffersInUse; i += 1) { if (renderer->buffersInUse[i] == mtlBuffer) { renderer->buffersInUse[i] = NULL; } } } SDL_free(mtlBuffer->subBuffers); mtlBuffer->subBuffers = NULL; SDL_free(mtlBuffer); } static void METAL_INTERNAL_SetBufferData( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer, int32_t offsetInBytes, void* data, int32_t dataLength, FNA3D_SetDataOptions options ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalBuffer *mtlBuffer = (MetalBuffer*) buffer; int32_t prevIndex; #define CURIDX mtlBuffer->currentSubBufferIndex #define SUBBUF mtlBuffer->subBuffers[CURIDX] prevIndex = CURIDX; if (mtlBuffer->bound) { if (options == FNA3D_SETDATAOPTIONS_NONE) { METAL_INTERNAL_Flush(renderer); mtlBuffer->bound = 1; } else if (options == FNA3D_SETDATAOPTIONS_DISCARD) { CURIDX += 1; } } /* Create a new SubBuffer if needed */ if (CURIDX == mtlBuffer->subBufferCount) { METAL_INTERNAL_AllocateSubBuffer(renderer, mtlBuffer); } /* Copy over previous contents when needed */ if ( options == FNA3D_SETDATAOPTIONS_NONE && dataLength < mtlBuffer->size && CURIDX != prevIndex ) { SDL_memcpy( SUBBUF.ptr, mtlBuffer->subBuffers[prevIndex].ptr, mtlBuffer->size ); } /* Copy the data! */ SDL_memcpy( SUBBUF.ptr + offsetInBytes, data, dataLength ); #undef SUBBUF #undef CURIDX } /* Pipeline State Object Creation / Retrieval */ static PackedRenderPipeline METAL_INTERNAL_GetPackedRenderPipeline( MetalRenderer *renderer ) { PackedRenderPipeline result; MOJOSHADER_mtlGetBoundShaders(&result.vshader, &result.pshader); result.blendState = GetPackedBlendState(renderer->blendState); result.colorFormats[0] = renderer->currentColorFormats[0]; result.colorFormats[1] = renderer->currentColorFormats[1]; result.colorFormats[2] = renderer->currentColorFormats[2]; result.colorFormats[3] = renderer->currentColorFormats[3]; result.depthFormat = XNAToMTL_DepthFormat( renderer, renderer->currentDepthFormat ); result.vertexDescriptor = renderer->currentVertexDescriptor; result.sampleCount = renderer->currentSampleCount; return result; } static MTLRenderPipelineState* METAL_INTERNAL_PackedRenderPipelineArray_Fetch( PackedRenderPipelineArray arr, PackedRenderPipeline key ) { int32_t i; PackedRenderPipeline other; for (i = 0; i < arr.count; i += 1) { other = arr.elements[i].key; if ( key.vshader == other.vshader && key.pshader == other.pshader && key.vertexDescriptor == other.vertexDescriptor && key.blendState.a == other.blendState.a && key.blendState.b == other.blendState.b && key.depthFormat == other.depthFormat && key.sampleCount == other.sampleCount && key.colorFormats[0] == other.colorFormats[0] && key.colorFormats[1] == other.colorFormats[1] && key.colorFormats[2] == other.colorFormats[2] && key.colorFormats[3] == other.colorFormats[3] ) { return arr.elements[i].value; } } return NULL; } static void METAL_INTERNAL_PackedRenderPipelineArray_Insert( PackedRenderPipelineArray *arr, PackedRenderPipeline key, MTLRenderPipelineState* value ) { PackedRenderPipelineMap map; map.key = key; map.value = value; EXPAND_ARRAY_IF_NEEDED(arr, 4, PackedRenderPipelineMap) arr->elements[arr->count] = map; arr->count += 1; } static MTLRenderPipelineState* METAL_INTERNAL_FetchRenderPipeline( MetalRenderer *renderer ) { PackedRenderPipeline packedPipeline; MTLRenderPipelineDescriptor *pipelineDesc; MTLFunction *vertHandle; MTLFunction *fragHandle; uint8_t alphaBlendEnable; int32_t i; MTLRenderPipelineColorAttachmentDescriptor *colorAttachment; MOJOSHADER_mtlShader *vert, *pixl; MTLRenderPipelineState *result; /* Can we just reuse an existing pipeline? */ packedPipeline = METAL_INTERNAL_GetPackedRenderPipeline(renderer); result = METAL_INTERNAL_PackedRenderPipelineArray_Fetch( renderer->pipelineStateCache, packedPipeline ); if (result != NULL) { /* We already have this state cached! */ return result; } /* We have to make a new pipeline... */ pipelineDesc = mtlNewRenderPipelineDescriptor(); MOJOSHADER_mtlGetBoundShaders(&vert, &pixl); vertHandle = MOJOSHADER_mtlGetFunctionHandle(vert); fragHandle = MOJOSHADER_mtlGetFunctionHandle(pixl); mtlSetPipelineVertexFunction( pipelineDesc, vertHandle ); mtlSetPipelineFragmentFunction( pipelineDesc, fragHandle ); mtlSetPipelineVertexDescriptor( pipelineDesc, renderer->currentVertexDescriptor ); mtlSetDepthAttachmentPixelFormat( pipelineDesc, XNAToMTL_DepthFormat(renderer, renderer->currentDepthFormat) ); if (renderer->currentDepthFormat == FNA3D_DEPTHFORMAT_D24S8) { mtlSetStencilAttachmentPixelFormat( pipelineDesc, XNAToMTL_DepthFormat(renderer, renderer->currentDepthFormat) ); } mtlSetPipelineSampleCount( pipelineDesc, SDL_max(1, renderer->currentSampleCount) ); /* Apply the blend state */ alphaBlendEnable = !( renderer->blendState.colorSourceBlend == FNA3D_BLEND_ONE && renderer->blendState.colorDestinationBlend == FNA3D_BLEND_ZERO && renderer->blendState.alphaSourceBlend == FNA3D_BLEND_ONE && renderer->blendState.alphaDestinationBlend == FNA3D_BLEND_ZERO ); for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1) { if (renderer->currentAttachments[i] == NULL) { /* There's no attachment bound at this index. */ continue; } colorAttachment = mtlGetColorAttachment( pipelineDesc, i ); mtlSetAttachmentPixelFormat( colorAttachment, renderer->currentColorFormats[i] ); mtlSetAttachmentBlendingEnabled( colorAttachment, alphaBlendEnable ); if (alphaBlendEnable) { mtlSetAttachmentSourceRGBBlendFactor( colorAttachment, XNAToMTL_BlendMode[ renderer->blendState.colorSourceBlend ] ); mtlSetAttachmentDestinationRGBBlendFactor( colorAttachment, XNAToMTL_BlendMode[ renderer->blendState.colorDestinationBlend ] ); mtlSetAttachmentSourceAlphaBlendFactor( colorAttachment, XNAToMTL_BlendMode[ renderer->blendState.alphaSourceBlend ] ); mtlSetAttachmentDestinationAlphaBlendFactor( colorAttachment, XNAToMTL_BlendMode[ renderer->blendState.alphaDestinationBlend ] ); mtlSetAttachmentRGBBlendOperation( colorAttachment, XNAToMTL_BlendOperation[ renderer->blendState.colorBlendFunction ] ); mtlSetAttachmentAlphaBlendOperation( colorAttachment, XNAToMTL_BlendOperation[ renderer->blendState.alphaBlendFunction ] ); } /* FIXME: So how exactly do we factor in * COLORWRITEENABLE for buffer 0? Do we just assume that * the default is just buffer 0, and all other calls * update the other write masks? */ if (i == 0) { mtlSetAttachmentWriteMask( colorAttachment, XNAToMTL_ColorWriteMask( renderer->blendState.colorWriteEnable ) ); } else if (i == 1) { mtlSetAttachmentWriteMask( mtlGetColorAttachment(pipelineDesc, 1), XNAToMTL_ColorWriteMask( renderer->blendState.colorWriteEnable1 ) ); } else if (i == 2) { mtlSetAttachmentWriteMask( mtlGetColorAttachment(pipelineDesc, 2), XNAToMTL_ColorWriteMask( renderer->blendState.colorWriteEnable2 ) ); } else if (i == 3) { mtlSetAttachmentWriteMask( mtlGetColorAttachment(pipelineDesc, 3), XNAToMTL_ColorWriteMask( renderer->blendState.colorWriteEnable3 ) ); } } /* Bake the render pipeline! */ result = mtlNewRenderPipelineState( renderer->device, pipelineDesc ); METAL_INTERNAL_PackedRenderPipelineArray_Insert( &renderer->pipelineStateCache, packedPipeline, result ); /* Clean up */ objc_release(pipelineDesc); /* Return the pipeline! */ return result; } static MTLDepthStencilState* METAL_INTERNAL_FetchDepthStencilState( MetalRenderer *renderer ) { PackedState packedState; MTLDepthStencilState *result; MTLDepthStencilDescriptor *dsDesc; MTLStencilDescriptor *front, *back; uint8_t zEnable, sEnable, zFormat; /* Just use the default depth-stencil state * if depth and stencil testing are disabled, * or if there is no bound depth attachment. * This wards off Metal validation errors. * -caleb */ zEnable = renderer->depthStencilState.depthBufferEnable; sEnable = renderer->depthStencilState.stencilEnable; zFormat = (renderer->currentDepthFormat != FNA3D_DEPTHFORMAT_NONE); if ((!zEnable && !sEnable) || (!zFormat)) { return renderer->defaultDepthStencilState; } /* Can we just reuse an existing state? */ packedState = GetPackedDepthStencilState(renderer->depthStencilState); result = PackedStateArray_Fetch( renderer->depthStencilStateCache, packedState ); if (result != NULL) { /* This state has already been cached! */ return result; } /* We have to make a new DepthStencilState... */ dsDesc = mtlNewDepthStencilDescriptor(); if (zEnable) { mtlSetDepthCompareFunction( dsDesc, XNAToMTL_CompareFunc[ renderer->depthStencilState.depthBufferFunction ] ); mtlSetDepthWriteEnabled( dsDesc, renderer->depthStencilState.depthBufferWriteEnable ); } /* Create stencil descriptors */ front = NULL; back = NULL; if (sEnable) { front = mtlNewStencilDescriptor(); mtlSetStencilFailureOperation( front, XNAToMTL_StencilOp[ renderer->depthStencilState.stencilFail ] ); mtlSetDepthFailureOperation( front, XNAToMTL_StencilOp[ renderer->depthStencilState.stencilDepthBufferFail ] ); mtlSetDepthStencilPassOperation( front, XNAToMTL_StencilOp[ renderer->depthStencilState.stencilPass ] ); mtlSetStencilCompareFunction( front, XNAToMTL_CompareFunc[ renderer->depthStencilState.stencilFunction ] ); mtlSetStencilReadMask( front, (uint32_t) renderer->depthStencilState.stencilMask ); mtlSetStencilWriteMask( front, (uint32_t) renderer->depthStencilState.stencilWriteMask ); if (!renderer->depthStencilState.twoSidedStencilMode) { back = front; } } if (front != back) { back = mtlNewStencilDescriptor(); mtlSetStencilFailureOperation( back, XNAToMTL_StencilOp[ renderer->depthStencilState.ccwStencilFail ] ); mtlSetDepthFailureOperation( back, XNAToMTL_StencilOp[ renderer->depthStencilState.ccwStencilDepthBufferFail ] ); mtlSetDepthStencilPassOperation( back, XNAToMTL_StencilOp[ renderer->depthStencilState.ccwStencilPass ] ); mtlSetStencilCompareFunction( back, XNAToMTL_CompareFunc[ renderer->depthStencilState.ccwStencilFunction ] ); mtlSetStencilReadMask( back, (uint32_t) renderer->depthStencilState.stencilMask ); mtlSetStencilWriteMask( back, (uint32_t) renderer->depthStencilState.stencilWriteMask ); } mtlSetFrontFaceStencil( dsDesc, front ); mtlSetBackFaceStencil( dsDesc, back ); /* Bake the state! */ result = mtlNewDepthStencilState( renderer->device, dsDesc ); PackedStateArray_Insert( &renderer->depthStencilStateCache, packedState, result ); /* Clean up */ objc_release(dsDesc); /* Return the state! */ return result; } static MTLSamplerState* METAL_INTERNAL_FetchSamplerState( MetalRenderer *renderer, FNA3D_SamplerState *samplerState, uint8_t hasMipmaps ) { PackedState packedState; MTLSamplerState *result; MTLSamplerDescriptor *desc; /* Can we reuse an existing state? */ packedState = GetPackedSamplerState(*samplerState); result = PackedStateArray_Fetch( renderer->samplerStateCache, packedState ); if (result != NULL) { /* This state has already been cached! */ return result; } /* We have to make a new sampler state... */ desc = mtlNewSamplerDescriptor(); mtlSetSampler_sAddressMode( desc, XNAToMTL_Wrap[samplerState->addressU] ); mtlSetSampler_tAddressMode( desc, XNAToMTL_Wrap[samplerState->addressV] ); mtlSetSampler_rAddressMode( desc, XNAToMTL_Wrap[samplerState->addressW] ); mtlSetSamplerMagFilter( desc, XNAToMTL_MagFilter[samplerState->filter] ); mtlSetSamplerMinFilter( desc, XNAToMTL_MinFilter[samplerState->filter] ); if (hasMipmaps) { mtlSetSamplerMipFilter( desc, XNAToMTL_MipFilter[samplerState->filter] ); } mtlSetSamplerLodMinClamp( desc, samplerState->maxMipLevel ); mtlSetSamplerMaxAnisotropy( desc, samplerState->filter == FNA3D_TEXTUREFILTER_ANISOTROPIC ? SDL_max(1, samplerState->maxAnisotropy) : 1 ); /* FIXME: * The only way to set lod bias in metal is via the MSL * bias() function in a shader. So we can't do: * * mtlSetSamplerLodBias( * samplerDesc, * samplerState.MipMapLevelOfDetailBias * ); * * What should we do instead? * * -caleb */ /* Bake the state! */ result = mtlNewSamplerState( renderer->device, desc ); PackedStateArray_Insert( &renderer->samplerStateCache, packedState, result ); /* Clean up */ objc_release(desc); /* Return the state! */ return result; } static MTLTexture* METAL_INTERNAL_FetchTransientTexture( MetalRenderer *renderer, MetalTexture *fromTexture ) { MTLTextureDescriptor *desc; MetalTexture *result, *curr; /* Can we just reuse an existing texture? */ curr = renderer->transientTextures; while (curr != NULL) { if ( curr->format == fromTexture->format && curr->width == fromTexture->width && curr->height == fromTexture->height && curr->hasMipmaps == fromTexture->hasMipmaps ) { mtlSetPurgeableState( curr->handle, MTLPurgeableStateNonVolatile ); return curr->handle; } curr = curr->next; } /* We have to make a new texture... */ desc = mtlMakeTexture2DDescriptor( XNAToMTL_TextureFormat[fromTexture->format], fromTexture->width, fromTexture->height, fromTexture->hasMipmaps ); result = CreateTexture( renderer, mtlNewTexture(renderer->device, desc), fromTexture->format, fromTexture->width, fromTexture->height, fromTexture->hasMipmaps ? 2 : 0, 0 ); LinkedList_Add(renderer->transientTextures, result, curr); return result->handle; } static MTLVertexDescriptor* METAL_INTERNAL_FetchVertexBufferBindingsDescriptor( MetalRenderer *renderer, FNA3D_VertexBufferBinding *bindings, int32_t numBindings ) { int32_t whatever, i, j, k, usage, index, attribLoc; uint32_t noReallyWhatever; uint8_t attrUse[MOJOSHADER_USAGE_TOTAL][16]; FNA3D_VertexDeclaration vertexDeclaration; FNA3D_VertexElement element; MTLVertexAttributeDescriptor *attrib; MTLVertexBufferLayoutDescriptor *layout; MOJOSHADER_mtlShader *vertexShader, *blah; MTLVertexDescriptor *result; /* We need the vertex shader... */ MOJOSHADER_mtlGetBoundShaders(&vertexShader, &blah); /* Can we just reuse an existing descriptor? */ result = PackedVertexBufferBindingsArray_Fetch( renderer->vertexDescriptorCache, bindings, numBindings, vertexShader, &whatever, &noReallyWhatever ); if (result != NULL) { /* This descriptor has already been cached! */ return result; } /* We have to make a new vertex descriptor... */ result = mtlMakeVertexDescriptor(); objc_retain(result); /* There's this weird case where you can have overlapping * vertex usage/index combinations. It seems like the first * attrib gets priority, so whenever a duplicate attribute * exists, give it the next available index. If that fails, we * have to crash :/ * -flibit */ SDL_memset(attrUse, '\0', sizeof(attrUse)); for (i = 0; i < numBindings; i += 1) { /* Describe vertex attributes */ vertexDeclaration = bindings[i].vertexDeclaration; for (j = 0; j < vertexDeclaration.elementCount; j += 1) { element = vertexDeclaration.elements[j]; usage = element.vertexElementUsage; index = element.usageIndex; if (attrUse[usage][index]) { index = -1; for (k = 0; k < 16; k += 1) { if (!attrUse[usage][k]) { index = k; break; } } if (index < 0) { FNA3D_LogError( "Vertex usage collision!" ); } } attrUse[usage][index] = 1; attribLoc = MOJOSHADER_mtlGetVertexAttribLocation( vertexShader, VertexAttribUsage(usage), index ); if (attribLoc == -1) { /* Stream not in use! */ continue; } attrib = mtlGetVertexAttributeDescriptor( result, attribLoc ); mtlSetVertexAttributeFormat( attrib, XNAToMTL_VertexAttribType[element.vertexElementFormat] ); mtlSetVertexAttributeOffset( attrib, element.offset ); mtlSetVertexAttributeBufferIndex( attrib, i ); } /* Describe vertex buffer layout */ layout = mtlGetVertexBufferLayoutDescriptor( result, i ); mtlSetVertexBufferLayoutStride( layout, vertexDeclaration.vertexStride ); if (bindings[i].instanceFrequency > 0) { mtlSetVertexBufferLayoutStepFunction( layout, MTLVertexStepFunctionPerInstance ); mtlSetVertexBufferLayoutStepRate( layout, bindings[i].instanceFrequency ); } } /* Store and return the vertex descriptor! */ PackedVertexBufferBindingsArray_Insert( &renderer->vertexDescriptorCache, bindings, numBindings, vertexShader, result ); return result; } /* Forward Declarations */ static void METAL_INTERNAL_DestroyFramebuffer(MetalRenderer *renderer); static void METAL_SetRenderTargets( FNA3D_Renderer *driverData, FNA3D_RenderTargetBinding *renderTargets, int32_t numRenderTargets, FNA3D_Renderbuffer *depthStencilBuffer, FNA3D_DepthFormat depthFormat, uint8_t preserveTargetContents ); static void METAL_GetTextureData2D( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t w, int32_t h, int32_t level, void* data, int32_t dataLength ); /* Renderer Implementation */ /* Quit */ static void METAL_DestroyDevice(FNA3D_Device *device) { MetalRenderer *renderer = (MetalRenderer*) device->driverData; int32_t i; MetalTexture *tex, *next; /* Stop rendering */ METAL_INTERNAL_EndPass(renderer); /* Release depth stencil states */ for (i = 0; i < renderer->depthStencilStateCache.count; i += 1) { objc_release(renderer->depthStencilStateCache.elements[i].value); } SDL_free(renderer->depthStencilStateCache.elements); /* Release sampler states */ for (i = 0; i < renderer->samplerStateCache.count; i += 1) { objc_release(renderer->samplerStateCache.elements[i].value); } SDL_free(renderer->samplerStateCache.elements); /* Release pipeline states */ for (i = 0; i < renderer->pipelineStateCache.count; i += 1) { objc_release(renderer->pipelineStateCache.elements[i].value); } SDL_free(renderer->pipelineStateCache.elements); /* Release vertex descriptors */ for (i = 0; i < renderer->vertexDescriptorCache.count; i += 1) { objc_release(renderer->vertexDescriptorCache.elements[i].value); } SDL_free(renderer->vertexDescriptorCache.elements); /* Release transient textures */ tex = renderer->transientTextures; while (tex != NULL) { next = tex->next; objc_release(tex->handle); SDL_free(tex); tex = next; } renderer->transientTextures = NULL; /* Destroy the physical buffers and allocator */ for (i = 0; i < PHYSICAL_BUFFER_MAX_COUNT; i += 1) { if (renderer->bufferAllocator->physicalBuffers[i] != NULL) { objc_release(renderer->bufferAllocator->physicalBuffers[i]); } } SDL_free(renderer->bufferAllocator); SDL_free(renderer->buffersInUse); /* Destroy the backbuffer */ METAL_INTERNAL_DestroyFramebuffer(renderer); SDL_free(renderer->backbuffer); /* Destroy the view */ SDL_Metal_DestroyView(renderer->view); /* Destroy the MojoShader context */ MOJOSHADER_mtlDestroyContext(renderer->mtlContext); SDL_free(renderer); SDL_free(device); } /* Presentation */ static void METAL_INTERNAL_UpdateBackbufferVertexBuffer( MetalRenderer *renderer, FNA3D_Rect *srcRect, FNA3D_Rect *dstRect, int32_t drawableWidth, int32_t drawableHeight ) { float backbufferWidth = (float) renderer->backbuffer->width; float backbufferHeight = (float) renderer->backbuffer->height; float sx0, sy0, sx1, sy1; float dx0, dy0, dx1, dy1; float data[16]; /* Cache the new info */ renderer->backbufferSizeChanged = 0; renderer->prevSrcRect = *srcRect; renderer->prevDstRect = *dstRect; /* Scale the texture coordinates to (0, 1) */ sx0 = srcRect->x / backbufferWidth; sy0 = srcRect->y / backbufferHeight; sx1 = (srcRect->x + srcRect->w) / backbufferWidth; sy1 = (srcRect->y + srcRect->h) / backbufferHeight; /* Scale the position coordinates to (-1, 1) */ dx0 = (dstRect->x / (float) drawableWidth) * 2.0f - 1.0f; dy0 = (dstRect->y / (float) drawableHeight) * 2.0f - 1.0f; dx1 = ((dstRect->x + dstRect->w) / (float) drawableWidth) * 2.0f - 1.0f; dy1 = ((dstRect->y + dstRect->h) / (float) drawableHeight) * 2.0f - 1.0f; /* Stuff the data into an array */ data[0] = dx0; data[1] = dy0; data[2] = sx0; data[3] = sy0; data[4] = dx1; data[5] = dy0; data[6] = sx1; data[7] = sy0; data[8] = dx1; data[9] = dy1; data[10] = sx1; data[11] = sy1; data[12] = dx0; data[13] = dy1; data[14] = sx0; data[15] = sy1; /* Copy the data into the buffer */ SDL_memcpy( mtlGetBufferContents(renderer->backbufferDrawBuffer), data, sizeof(data) ); } static void METAL_INTERNAL_BlitFramebuffer( MetalRenderer *renderer, MTLTexture *srcTex, MTLTexture *dstTex ) { MTLRenderPassDescriptor *pass; MTLRenderCommandEncoder *rce; pass = mtlMakeRenderPassDescriptor(); mtlSetAttachmentTexture( mtlGetColorAttachment(pass, 0), dstTex ); rce = mtlMakeRenderCommandEncoder( renderer->commandBuffer, pass ); mtlSetRenderPipelineState(rce, renderer->backbufferPipeline); mtlSetVertexBuffer(rce, renderer->backbufferDrawBuffer, 0, 0); mtlSetFragmentTexture(rce, srcTex, 0); mtlSetFragmentSamplerState(rce, renderer->backbufferSamplerState, 0); mtlDrawIndexedPrimitives( rce, MTLPrimitiveTypeTriangle, 6, MTLIndexTypeUInt16, renderer->backbufferDrawBuffer, 16 * sizeof(float), 1 ); mtlEndEncoding(rce); } static void METAL_SwapBuffers( FNA3D_Renderer *driverData, FNA3D_Rect *sourceRectangle, FNA3D_Rect *destinationRectangle, void* overrideWindowHandle ) { MetalRenderer *renderer = (MetalRenderer*) driverData; FNA3D_Rect srcRect, dstRect; CGSize drawableSize; MTLDrawable *drawable; /* Just in case Present() is called * before any rendering happens... */ METAL_INTERNAL_BeginFrame(driverData); /* Bind the backbuffer and finalize rendering */ METAL_SetRenderTargets( driverData, NULL, 0, NULL, FNA3D_DEPTHFORMAT_NONE, 0 ); METAL_INTERNAL_EndPass(renderer); /* Determine the regions to present */ drawableSize = mtlGetDrawableSize(renderer->layer); if (sourceRectangle != NULL) { srcRect.x = sourceRectangle->x; srcRect.y = sourceRectangle->y; srcRect.w = sourceRectangle->w; srcRect.h = sourceRectangle->h; } else { srcRect.x = 0; srcRect.y = 0; srcRect.w = renderer->backbuffer->width; srcRect.h = renderer->backbuffer->height; } if (destinationRectangle != NULL) { dstRect.x = destinationRectangle->x; dstRect.y = destinationRectangle->y; dstRect.w = destinationRectangle->w; dstRect.h = destinationRectangle->h; } else { dstRect.x = 0; dstRect.y = 0; dstRect.w = (int32_t) drawableSize.width; dstRect.h = (int32_t) drawableSize.height; } /* Update the cached vertex buffer, if needed */ if ( renderer->backbufferSizeChanged || renderer->prevSrcRect.x != srcRect.x || renderer->prevSrcRect.y != srcRect.y || renderer->prevSrcRect.w != srcRect.w || renderer->prevSrcRect.h != srcRect.h || renderer->prevDstRect.x != dstRect.x || renderer->prevDstRect.y != dstRect.y || renderer->prevDstRect.w != dstRect.w || renderer->prevDstRect.h != dstRect.h ) { METAL_INTERNAL_UpdateBackbufferVertexBuffer( renderer, &srcRect, &dstRect, (int32_t) drawableSize.width, (int32_t) drawableSize.height ); } /* Get the next drawable */ drawable = mtlNextDrawable(renderer->layer); /* "Blit" the backbuffer to the drawable */ if (srcRect.w != 0 && srcRect.h != 0 && dstRect.w != 0 && dstRect.h != 0) { METAL_INTERNAL_BlitFramebuffer( renderer, renderer->currentAttachments[0], mtlGetTextureFromDrawable(drawable) ); } /* Commit the command buffer for presentation */ mtlPresentDrawable(renderer->commandBuffer, drawable); mtlCommitCommandBuffer(renderer->commandBuffer); /* Track the committed command buffer */ objc_retain(renderer->commandBuffer); renderer->committedCommandBuffer = renderer->commandBuffer; renderer->commandBuffer = NULL; /* Release allocations from the past frame */ objc_autoreleasePoolPop(renderer->pool); /* Reset buffer and texture internal states */ METAL_INTERNAL_ResetBuffers(renderer); METAL_INTERNAL_ResetTextures(renderer); MOJOSHADER_mtlEndFrame(); /* We're done here. */ renderer->frameInProgress = 0; } /* Drawing */ static void METAL_Clear( FNA3D_Renderer *driverData, FNA3D_ClearOptions options, FNA3D_Vec4 *color, float depth, int32_t stencil ) { MetalRenderer *renderer = (MetalRenderer*) driverData; uint8_t clearTarget = (options & FNA3D_CLEAROPTIONS_TARGET) == FNA3D_CLEAROPTIONS_TARGET; uint8_t clearDepth = (options & FNA3D_CLEAROPTIONS_DEPTHBUFFER) == FNA3D_CLEAROPTIONS_DEPTHBUFFER; uint8_t clearStencil = (options & FNA3D_CLEAROPTIONS_STENCIL) == FNA3D_CLEAROPTIONS_STENCIL; if (clearTarget) { SDL_memcpy(&renderer->clearColor, color, sizeof(FNA3D_Vec4)); renderer->shouldClearColor = 1; } if (clearDepth) { renderer->clearDepth = depth; renderer->shouldClearDepth = 1; } if (clearStencil) { renderer->clearStencil = stencil; renderer->shouldClearStencil = 1; } renderer->needNewRenderPass |= clearTarget | clearDepth | clearStencil; } static void METAL_DrawInstancedPrimitives( FNA3D_Renderer *driverData, FNA3D_PrimitiveType primitiveType, int32_t baseVertex, int32_t minVertexIndex, int32_t numVertices, int32_t startIndex, int32_t primitiveCount, int32_t instanceCount, FNA3D_Buffer *indices, FNA3D_IndexElementSize indexElementSize ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalBuffer *indexBuffer = (MetalBuffer*) indices; MetalSubBuffer subbuf = indexBuffer->subBuffers[ indexBuffer->currentSubBufferIndex ]; int32_t totalIndexOffset; METAL_INTERNAL_MarkBufferAsBound(renderer, indexBuffer); totalIndexOffset = ( (startIndex * IndexSize(indexElementSize)) + subbuf.offset ); mtlDrawIndexedPrimitives( renderer->renderCommandEncoder, XNAToMTL_Primitive[primitiveType], PrimitiveVerts(primitiveType, primitiveCount), XNAToMTL_IndexType[indexElementSize], subbuf.buffer, totalIndexOffset, instanceCount ); } static void METAL_DrawIndexedPrimitives( FNA3D_Renderer *driverData, FNA3D_PrimitiveType primitiveType, int32_t baseVertex, int32_t minVertexIndex, int32_t numVertices, int32_t startIndex, int32_t primitiveCount, FNA3D_Buffer *indices, FNA3D_IndexElementSize indexElementSize ) { METAL_DrawInstancedPrimitives( driverData, primitiveType, baseVertex, minVertexIndex, numVertices, startIndex, primitiveCount, 1, indices, indexElementSize ); } static void METAL_DrawPrimitives( FNA3D_Renderer *driverData, FNA3D_PrimitiveType primitiveType, int32_t vertexStart, int32_t primitiveCount ) { MetalRenderer *renderer = (MetalRenderer*) driverData; mtlDrawPrimitives( renderer->renderCommandEncoder, XNAToMTL_Primitive[primitiveType], vertexStart, PrimitiveVerts(primitiveType, primitiveCount) ); } /* Mutable Render States */ static void METAL_SetViewport(FNA3D_Renderer *driverData, FNA3D_Viewport *viewport) { MetalRenderer *renderer = (MetalRenderer*) driverData; FNA3D_Viewport vp = *viewport; if ( vp.x != renderer->viewport.x || vp.y != renderer->viewport.y || vp.w != renderer->viewport.w || vp.h != renderer->viewport.h || vp.minDepth != renderer->viewport.minDepth || vp.maxDepth != renderer->viewport.maxDepth ) { renderer->viewport = vp; METAL_INTERNAL_SetEncoderViewport(renderer); /* Dynamic state! */ } } static void METAL_SetScissorRect(FNA3D_Renderer *driverData, FNA3D_Rect *scissor) { MetalRenderer *renderer = (MetalRenderer*) driverData; if ( scissor->x != renderer->scissorRect.x || scissor->y != renderer->scissorRect.y || scissor->w != renderer->scissorRect.w || scissor->h != renderer->scissorRect.h ) { renderer->scissorRect = *scissor; METAL_INTERNAL_SetEncoderScissorRect(renderer); /* Dynamic state! */ } } static void METAL_GetBlendFactor( FNA3D_Renderer *driverData, FNA3D_Color *blendFactor ) { MetalRenderer *renderer = (MetalRenderer*) driverData; SDL_memcpy(blendFactor, &renderer->blendColor, sizeof(FNA3D_Color)); } static void METAL_SetBlendFactor( FNA3D_Renderer *driverData, FNA3D_Color *blendFactor ) { MetalRenderer *renderer = (MetalRenderer*) driverData; if ( renderer->blendColor.r != blendFactor->r || renderer->blendColor.g != blendFactor->g || renderer->blendColor.b != blendFactor->b || renderer->blendColor.a != blendFactor->a ) { renderer->blendColor.r = blendFactor->r; renderer->blendColor.g = blendFactor->g; renderer->blendColor.b = blendFactor->b; renderer->blendColor.a = blendFactor->a; METAL_INTERNAL_SetEncoderBlendColor(renderer); } } static int32_t METAL_GetMultiSampleMask(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; return renderer->multiSampleMask; } static void METAL_SetMultiSampleMask(FNA3D_Renderer *driverData, int32_t mask) { MetalRenderer *renderer = (MetalRenderer*) driverData; renderer->multiSampleMask = mask; /* FIXME: Metal does not support multisample masks. Workarounds...? */ } static int32_t METAL_GetReferenceStencil(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; return renderer->stencilRef; } static void METAL_SetReferenceStencil(FNA3D_Renderer *driverData, int32_t ref) { MetalRenderer *renderer = (MetalRenderer*) driverData; if (renderer->stencilRef != ref) { renderer->stencilRef = ref; METAL_INTERNAL_SetEncoderStencilReferenceValue(renderer); } } /* Immutable Render States */ static void METAL_SetBlendState( FNA3D_Renderer *driverData, FNA3D_BlendState *blendState ) { MetalRenderer *renderer = (MetalRenderer*) driverData; SDL_memcpy( &renderer->blendState, blendState, sizeof(FNA3D_BlendState) ); METAL_SetBlendFactor( driverData, &blendState->blendFactor ); /* Dynamic state! */ } static void METAL_SetDepthStencilState( FNA3D_Renderer *driverData, FNA3D_DepthStencilState *depthStencilState ) { MetalRenderer *renderer = (MetalRenderer*) driverData; SDL_memcpy( &renderer->depthStencilState, depthStencilState, sizeof(FNA3D_DepthStencilState) ); METAL_SetReferenceStencil( driverData, depthStencilState->referenceStencil ); /* Dynamic state! */ } static void METAL_ApplyRasterizerState( FNA3D_Renderer *driverData, FNA3D_RasterizerState *rasterizerState ) { MetalRenderer *renderer = (MetalRenderer*) driverData; float realDepthBias; if (rasterizerState->scissorTestEnable != renderer->scissorTestEnable) { renderer->scissorTestEnable = rasterizerState->scissorTestEnable; METAL_INTERNAL_SetEncoderScissorRect(renderer); /* Dynamic state! */ } if (rasterizerState->cullMode != renderer->cullFrontFace) { renderer->cullFrontFace = rasterizerState->cullMode; METAL_INTERNAL_SetEncoderCullMode(renderer); /* Dynamic state! */ } if (rasterizerState->fillMode != renderer->fillMode) { renderer->fillMode = rasterizerState->fillMode; METAL_INTERNAL_SetEncoderFillMode(renderer); /* Dynamic state! */ } realDepthBias = rasterizerState->depthBias * XNAToMTL_DepthBiasScale( XNAToMTL_DepthFormat(renderer, renderer->currentDepthFormat) ); if ( realDepthBias != renderer->depthBias || rasterizerState->slopeScaleDepthBias != renderer->slopeScaleDepthBias) { renderer->depthBias = realDepthBias; renderer->slopeScaleDepthBias = rasterizerState->slopeScaleDepthBias; METAL_INTERNAL_SetEncoderDepthBias(renderer); /* Dynamic state! */ } if (rasterizerState->multiSampleAntiAlias != renderer->multiSampleEnable) { renderer->multiSampleEnable = rasterizerState->multiSampleAntiAlias; /* FIXME: Metal does not support toggling MSAA. Workarounds...? */ } } static void METAL_VerifySampler( FNA3D_Renderer *driverData, int32_t index, FNA3D_Texture *texture, FNA3D_SamplerState *sampler ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLSamplerState *mtlSamplerState; if (texture == NULL) { if (renderer->textures[index] != &NullTexture) { renderer->textures[index] = &NullTexture; renderer->textureNeedsUpdate[index] = 1; } if (renderer->samplers[index] == NULL) { /* Some shaders require non-null samplers * even if they aren't actually used. * -caleb */ renderer->samplers[index] = METAL_INTERNAL_FetchSamplerState( renderer, sampler, 0 ); renderer->samplerNeedsUpdate[index] = 1; } return; } /* Bind the correct texture */ if (mtlTexture != renderer->textures[index]) { renderer->textures[index] = mtlTexture; renderer->textureNeedsUpdate[index] = 1; } METAL_INTERNAL_MarkTextureAsBound(renderer, mtlTexture); /* Update the sampler state, if needed */ mtlSamplerState = METAL_INTERNAL_FetchSamplerState( renderer, sampler, mtlTexture->hasMipmaps ); if (mtlSamplerState != renderer->samplers[index]) { renderer->samplers[index] = mtlSamplerState; renderer->samplerNeedsUpdate[index] = 1; } } static void METAL_VerifyVertexSampler( FNA3D_Renderer *driverData, int32_t index, FNA3D_Texture *texture, FNA3D_SamplerState *sampler ) { METAL_VerifySampler( driverData, MAX_TEXTURE_SAMPLERS + index, texture, sampler ); } static void METAL_INTERNAL_BindResources(MetalRenderer *renderer) { int32_t i; MTLBuffer *ubo; int32_t vOff, fOff; MTLDepthStencilState *depthStencilState; MTLRenderPipelineState *pipelineState; /* Bind textures and their sampler states */ for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1) { if (renderer->textureNeedsUpdate[i]) { if (i < MAX_TEXTURE_SAMPLERS) { mtlSetFragmentTexture( renderer->renderCommandEncoder, renderer->textures[i]->handle, i ); } else { mtlSetVertexTexture( renderer->renderCommandEncoder, renderer->textures[i]->handle, i - MAX_TEXTURE_SAMPLERS ); } renderer->textureNeedsUpdate[i] = 0; } if (renderer->samplerNeedsUpdate[i]) { if (i < MAX_TEXTURE_SAMPLERS) { mtlSetFragmentSamplerState( renderer->renderCommandEncoder, renderer->samplers[i], i ); } else { mtlSetVertexSamplerState( renderer->renderCommandEncoder, renderer->samplers[i], i - MAX_TEXTURE_SAMPLERS ); } renderer->samplerNeedsUpdate[i] = 0; } } /* In MojoShader output, the uniform register is always 16 */ #define UNIFORM_REG 16 /* Bind the uniform buffers */ MOJOSHADER_mtlGetUniformData((void**) &ubo, &vOff, &fOff); if (ubo != renderer->ldUniformBuffer) { mtlSetVertexBuffer( renderer->renderCommandEncoder, ubo, vOff, UNIFORM_REG ); mtlSetFragmentBuffer( renderer->renderCommandEncoder, ubo, fOff, UNIFORM_REG ); renderer->ldUniformBuffer = ubo; renderer->ldVertUniformOffset = vOff; renderer->ldFragUniformOffset = fOff; } if (vOff != renderer->ldVertUniformOffset) { mtlSetVertexBufferOffset( renderer->renderCommandEncoder, vOff, UNIFORM_REG ); renderer->ldVertUniformOffset = vOff; } if (fOff != renderer->ldFragUniformOffset) { mtlSetFragmentBufferOffset( renderer->renderCommandEncoder, fOff, UNIFORM_REG ); renderer->ldFragUniformOffset = fOff; } #undef UNIFORM_REG /* Bind the depth-stencil state */ depthStencilState = METAL_INTERNAL_FetchDepthStencilState(renderer); if (depthStencilState != renderer->ldDepthStencilState) { mtlSetDepthStencilState( renderer->renderCommandEncoder, depthStencilState ); renderer->ldDepthStencilState = depthStencilState; } /* Finally, bind the pipeline state */ pipelineState = METAL_INTERNAL_FetchRenderPipeline(renderer); if (pipelineState != renderer->ldPipelineState) { mtlSetRenderPipelineState( renderer->renderCommandEncoder, pipelineState ); renderer->ldPipelineState = pipelineState; } } static void METAL_ApplyVertexBufferBindings( FNA3D_Renderer *driverData, FNA3D_VertexBufferBinding *bindings, int32_t numBindings, uint8_t bindingsUpdated, int32_t baseVertex ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalBuffer *vertexBuffer; MetalSubBuffer subbuf; int32_t i, offset; /* Translate the bindings array into a descriptor */ renderer->currentVertexDescriptor = METAL_INTERNAL_FetchVertexBufferBindingsDescriptor( renderer, bindings, numBindings ); /* Prepare for rendering */ METAL_INTERNAL_UpdateRenderPass(renderer); METAL_INTERNAL_BindResources(renderer); /* Bind the vertex buffers */ for (i = 0; i < numBindings; i += 1) { vertexBuffer = (MetalBuffer*) bindings[i].vertexBuffer; if (vertexBuffer == NULL) { continue; } subbuf = vertexBuffer->subBuffers[ vertexBuffer->currentSubBufferIndex ]; offset = subbuf.offset + ( (bindings[i].vertexOffset + baseVertex) * bindings[i].vertexDeclaration.vertexStride ); METAL_INTERNAL_MarkBufferAsBound(renderer, vertexBuffer); if (renderer->ldVertexBuffers[i] != subbuf.buffer) { mtlSetVertexBuffer( renderer->renderCommandEncoder, subbuf.buffer, offset, i ); renderer->ldVertexBuffers[i] = subbuf.buffer; renderer->ldVertexBufferOffsets[i] = offset; } else if (renderer->ldVertexBufferOffsets[i] != offset) { mtlSetVertexBufferOffset( renderer->renderCommandEncoder, offset, i ); renderer->ldVertexBufferOffsets[i] = offset; } } } /* Render Targets */ static void METAL_SetRenderTargets( FNA3D_Renderer *driverData, FNA3D_RenderTargetBinding *renderTargets, int32_t numRenderTargets, FNA3D_Renderbuffer *depthStencilBuffer, FNA3D_DepthFormat depthFormat, uint8_t preserveTargetContents ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalBackbuffer *bb; MetalRenderbuffer *rb; MetalTexture *tex; int32_t i; /* Perform any pending clears before switching render targets */ if ( renderer->shouldClearColor || renderer->shouldClearDepth || renderer->shouldClearStencil ) { METAL_INTERNAL_UpdateRenderPass(renderer); } /* Force an update to the render pass */ renderer->needNewRenderPass = 1; /* Reset attachments */ for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1) { renderer->currentAttachments[i] = NULL; renderer->currentColorFormats[i] = MTLPixelFormatInvalid; renderer->currentMSAttachments[i] = NULL; renderer->currentAttachmentSlices[i] = 0; } renderer->currentDepthStencilBuffer = NULL; renderer->currentDepthFormat = FNA3D_DEPTHFORMAT_NONE; renderer->currentSampleCount = 0; /* Bind the backbuffer, if applicable */ if (numRenderTargets <= 0) { bb = renderer->backbuffer; renderer->currentAttachments[0] = bb->colorBuffer; renderer->currentColorFormats[0] = XNAToMTL_TextureFormat[ bb->surfaceFormat ]; renderer->currentDepthStencilBuffer = bb->depthStencilBuffer; renderer->currentDepthFormat = bb->depthFormat; renderer->preserveDepthStencil = bb->preserveDepthStencil; renderer->currentSampleCount = bb->multiSampleCount; renderer->currentMSAttachments[0] = bb->multiSampleColorBuffer; renderer->currentAttachmentSlices[0] = 0; return; } /* Update color buffers */ for (i = 0; i < numRenderTargets; i += 1) { if (renderTargets[i].type == FNA3D_RENDERTARGET_TYPE_CUBE) { renderer->currentAttachmentSlices[i] = renderTargets[i].cube.face; } else { renderer->currentAttachmentSlices[i] = 0; } if (renderTargets[i].colorBuffer != NULL) { rb = (MetalRenderbuffer*) renderTargets[i].colorBuffer; renderer->currentAttachments[i] = rb->handle; renderer->currentColorFormats[i] = rb->pixelFormat; renderer->currentSampleCount = rb->multiSampleCount; renderer->currentMSAttachments[i] = rb->multiSampleHandle; } else { tex = (MetalTexture*) renderTargets[i].texture; renderer->currentAttachments[i] = tex->handle; renderer->currentColorFormats[i] = XNAToMTL_TextureFormat[ tex->format ]; renderer->currentSampleCount = 0; } } /* Update depth stencil buffer */ renderer->currentDepthStencilBuffer = ( depthStencilBuffer == NULL ? NULL : ((MetalRenderbuffer*) depthStencilBuffer)->handle ); renderer->currentDepthFormat = ( depthStencilBuffer == NULL ? FNA3D_DEPTHFORMAT_NONE : depthFormat ); renderer->preserveDepthStencil = preserveTargetContents; } static void METAL_ResolveTarget( FNA3D_Renderer *driverData, FNA3D_RenderTargetBinding *target ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *texture = (MetalTexture*) target->texture; MTLBlitCommandEncoder *blit; /* The target is resolved at the end of each render pass. */ /* If the target has mipmaps, regenerate them now. */ if (target->levelCount > 1) { METAL_INTERNAL_EndPass(renderer); blit = mtlMakeBlitCommandEncoder(renderer->commandBuffer); mtlGenerateMipmapsForTexture( blit, texture->handle ); mtlEndEncoding(blit); renderer->needNewRenderPass = 1; } } /* Backbuffer Functions */ static void METAL_INTERNAL_CreateFramebuffer( MetalRenderer *renderer, FNA3D_PresentationParameters *presentationParameters ) { int32_t newWidth, newHeight; MTLTextureDescriptor *colorBufferDesc; MTLTextureDescriptor *depthStencilBufferDesc; MetalBackbuffer *bb = renderer->backbuffer; /* Update the backbuffer size */ newWidth = presentationParameters->backBufferWidth; newHeight = presentationParameters->backBufferHeight; if (bb->width != newWidth || bb->height != newHeight) { renderer->backbufferSizeChanged = 1; } bb->width = newWidth; bb->height = newHeight; /* Update other presentation parameters */ bb->surfaceFormat = presentationParameters->backBufferFormat; bb->depthFormat = presentationParameters->depthStencilFormat; bb->multiSampleCount = METAL_INTERNAL_GetCompatibleSampleCount( renderer, presentationParameters->multiSampleCount ); /* Update color buffer to the new resolution */ colorBufferDesc = mtlMakeTexture2DDescriptor( XNAToMTL_TextureFormat[bb->surfaceFormat], bb->width, bb->height, 0 ); mtlSetStorageMode(colorBufferDesc, MTLStorageModePrivate); mtlSetTextureUsage( colorBufferDesc, MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead ); bb->colorBuffer = mtlNewTexture(renderer->device, colorBufferDesc); if (bb->multiSampleCount > 0) { mtlSetTextureType(colorBufferDesc, MTLTextureType2DMultisample); mtlSetTextureSampleCount(colorBufferDesc, bb->multiSampleCount); mtlSetTextureUsage(colorBufferDesc, MTLTextureUsageRenderTarget); bb->multiSampleColorBuffer = mtlNewTexture( renderer->device, colorBufferDesc ); } /* Update the depth/stencil buffer, if applicable */ if (bb->depthFormat != FNA3D_DEPTHFORMAT_NONE) { depthStencilBufferDesc = mtlMakeTexture2DDescriptor( XNAToMTL_DepthFormat(renderer, bb->depthFormat), bb->width, bb->height, 0 ); mtlSetStorageMode(depthStencilBufferDesc, MTLStorageModePrivate); mtlSetTextureUsage(depthStencilBufferDesc, MTLTextureUsageRenderTarget); if (bb->multiSampleCount > 0) { mtlSetTextureType( depthStencilBufferDesc, MTLTextureType2DMultisample ); mtlSetTextureSampleCount( depthStencilBufferDesc, bb->multiSampleCount ); } bb->depthStencilBuffer = mtlNewTexture( renderer->device, depthStencilBufferDesc ); bb->preserveDepthStencil = ( presentationParameters->renderTargetUsage != FNA3D_RENDERTARGETUSAGE_DISCARDCONTENTS ); } /* This is the default render target */ METAL_SetRenderTargets( (FNA3D_Renderer*) renderer, NULL, 0, NULL, FNA3D_DEPTHFORMAT_NONE, 0 ); } static void METAL_INTERNAL_DestroyFramebuffer(MetalRenderer *renderer) { objc_release(renderer->backbuffer->colorBuffer); renderer->backbuffer->colorBuffer = NULL; objc_release(renderer->backbuffer->multiSampleColorBuffer); renderer->backbuffer->multiSampleColorBuffer = NULL; objc_release(renderer->backbuffer->depthStencilBuffer); renderer->backbuffer->depthStencilBuffer = NULL; } static void METAL_INTERNAL_SetPresentationInterval( MetalRenderer *renderer, FNA3D_PresentInterval presentInterval ) { /* Toggling vsync is only supported on macOS 10.13+ */ if (!RespondsToSelector(renderer->layer, selDisplaySyncEnabled)) { FNA3D_LogWarn( "Cannot set presentation interval! " "Only vsync is supported." ); return; } if ( presentInterval == FNA3D_PRESENTINTERVAL_DEFAULT || presentInterval == FNA3D_PRESENTINTERVAL_ONE ) { mtlSetDisplaySyncEnabled(renderer->layer, 1); } else if (presentInterval == FNA3D_PRESENTINTERVAL_IMMEDIATE) { mtlSetDisplaySyncEnabled(renderer->layer, 0); } else if (presentInterval == FNA3D_PRESENTINTERVAL_TWO) { /* FIXME: * There is no built-in support for * present-every-other-frame in Metal. * We could work around this, but do * any games actually use this mode...? * -caleb */ mtlSetDisplaySyncEnabled(renderer->layer, 1); } else { SDL_assert(0 && "Unrecognized PresentInterval!"); } } static void METAL_ResetBackbuffer( FNA3D_Renderer *driverData, FNA3D_PresentationParameters *presentationParameters ) { MetalRenderer *renderer = (MetalRenderer*) driverData; METAL_INTERNAL_DestroyFramebuffer(renderer); METAL_INTERNAL_CreateFramebuffer( renderer, presentationParameters ); METAL_INTERNAL_SetPresentationInterval( renderer, presentationParameters->presentationInterval ); } static void METAL_ReadBackbuffer( FNA3D_Renderer *driverData, int32_t x, int32_t y, int32_t w, int32_t h, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture backbufferTexture; /* Create a pseudo-texture we can feed to GetTextureData2D. * These are the only members we need to initialize. * -caleb */ backbufferTexture.width = renderer->backbuffer->width; backbufferTexture.height = renderer->backbuffer->height; backbufferTexture.format = renderer->backbuffer->surfaceFormat; backbufferTexture.hasMipmaps = 0; backbufferTexture.isPrivate = 1; METAL_GetTextureData2D( driverData, (FNA3D_Texture*) &backbufferTexture, x, y, w, h, 0, data, dataLength ); } static void METAL_GetBackbufferSize( FNA3D_Renderer *driverData, int32_t *w, int32_t *h ) { MetalRenderer *renderer = (MetalRenderer*) driverData; *w = renderer->backbuffer->width; *h = renderer->backbuffer->height; } static FNA3D_SurfaceFormat METAL_GetBackbufferSurfaceFormat(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; return renderer->backbuffer->surfaceFormat; } static FNA3D_DepthFormat METAL_GetBackbufferDepthFormat(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; return renderer->backbuffer->depthFormat; } static int32_t METAL_GetBackbufferMultiSampleCount(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; return renderer->backbuffer->multiSampleCount; } /* Textures */ static FNA3D_Texture* METAL_CreateTexture2D( FNA3D_Renderer *driverData, FNA3D_SurfaceFormat format, int32_t width, int32_t height, int32_t levelCount, uint8_t isRenderTarget ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MTLTextureDescriptor *desc = mtlMakeTexture2DDescriptor( XNAToMTL_TextureFormat[format], width, height, levelCount > 1 ); if (isRenderTarget) { mtlSetStorageMode(desc, MTLStorageModePrivate); mtlSetTextureUsage( desc, MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead ); } return (FNA3D_Texture*) CreateTexture( renderer, mtlNewTexture(renderer->device, desc), format, width, height, levelCount, isRenderTarget ); } static FNA3D_Texture* METAL_CreateTexture3D( FNA3D_Renderer *driverData, FNA3D_SurfaceFormat format, int32_t width, int32_t height, int32_t depth, int32_t levelCount ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MTLTextureDescriptor *desc = mtlMakeTexture2DDescriptor( XNAToMTL_TextureFormat[format], width, height, levelCount > 1 ); /* Make it 3D! */ mtlSetTextureDepth(desc, depth); mtlSetTextureType(desc, MTLTextureType3DTexture); return (FNA3D_Texture*) CreateTexture( renderer, mtlNewTexture(renderer->device, desc), format, width, height, levelCount, 0 ); } static FNA3D_Texture* METAL_CreateTextureCube( FNA3D_Renderer *driverData, FNA3D_SurfaceFormat format, int32_t size, int32_t levelCount, uint8_t isRenderTarget ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MTLTextureDescriptor *desc = mtlMakeTextureCubeDescriptor( XNAToMTL_TextureFormat[format], size, levelCount > 1 ); if (isRenderTarget) { mtlSetStorageMode(desc, MTLStorageModePrivate); mtlSetTextureUsage( desc, MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead ); } return (FNA3D_Texture*) CreateTexture( renderer, mtlNewTexture(renderer->device, desc), format, size, size, levelCount, isRenderTarget ); } static void METAL_AddDisposeTexture( FNA3D_Renderer *driverData, FNA3D_Texture *texture ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; int32_t i; for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1) { if (mtlTexture->handle == renderer->currentAttachments[i]) { renderer->currentAttachments[i] = NULL; } } for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1) { if (mtlTexture->handle == renderer->textures[i]->handle) { renderer->textures[i] = &NullTexture; renderer->textureNeedsUpdate[i] = 1; } } objc_release(mtlTexture->handle); mtlTexture->handle = NULL; SDL_free(mtlTexture); } static void METAL_SetTextureData2D( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t w, int32_t h, int32_t level, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLTexture *handle = mtlTexture->handle; MTLBlitCommandEncoder *blit; MTLOrigin origin = {x, y, 0}; MTLSize size = {w, h, 1}; MTLRegion region = {origin, size}; if (mtlTexture->bound) { METAL_INTERNAL_Flush(renderer); } if (mtlTexture->isPrivate) { /* We need an active command buffer */ METAL_INTERNAL_BeginFrame(driverData); /* Fetch a CPU-accessible texture */ handle = METAL_INTERNAL_FetchTransientTexture( renderer, mtlTexture ); } /* Write the data */ mtlReplaceRegion( handle, region, level, 0, data, BytesPerRow(w, mtlTexture->format), 0 ); /* Blit the temp texture to the actual texture */ if (mtlTexture->isPrivate) { /* End the render pass */ METAL_INTERNAL_EndPass(renderer); /* Blit! */ blit = mtlMakeBlitCommandEncoder(renderer->commandBuffer); mtlBlitTextureToTexture( blit, handle, 0, level, origin, size, mtlTexture->handle, 0, level, origin ); /* Submit the blit command to the GPU and wait... */ mtlEndEncoding(blit); METAL_INTERNAL_Flush(renderer); /* We're done with the temp texture */ mtlSetPurgeableState( handle, MTLPurgeableStateEmpty ); } } static void METAL_SetTextureData3D( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t z, int32_t w, int32_t h, int32_t d, int32_t level, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLOrigin origin = {x, y, z}; MTLSize size = {w, h, d}; MTLRegion region = {origin, size}; if (mtlTexture->bound) { METAL_INTERNAL_Flush(renderer); } mtlReplaceRegion( mtlTexture->handle, region, level, 0, data, BytesPerRow(w, mtlTexture->format), BytesPerImage(w, h, mtlTexture->format) ); } static void METAL_SetTextureDataCube( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t w, int32_t h, FNA3D_CubeMapFace cubeMapFace, int32_t level, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLTexture *handle = mtlTexture->handle; MTLBlitCommandEncoder *blit; MTLOrigin origin = {x, y, 0}; MTLSize size = {w, h, 1}; MTLRegion region = {origin, size}; int32_t slice = cubeMapFace; if (mtlTexture->bound) { METAL_INTERNAL_Flush(renderer); } if (mtlTexture->isPrivate) { /* We need an active command buffer */ METAL_INTERNAL_BeginFrame(driverData); /* Fetch a CPU-accessible texture */ handle = METAL_INTERNAL_FetchTransientTexture( renderer, mtlTexture ); /* Transient textures have no slices */ slice = 0; } /* Write the data */ mtlReplaceRegion( handle, region, level, slice, data, BytesPerRow(w, mtlTexture->format), 0 ); /* Blit the temp texture to the actual texture */ if (mtlTexture->isPrivate) { /* End the render pass */ METAL_INTERNAL_EndPass(renderer); /* Blit! */ blit = mtlMakeBlitCommandEncoder(renderer->commandBuffer); mtlBlitTextureToTexture( blit, handle, slice, level, origin, size, mtlTexture->handle, cubeMapFace, level, origin ); /* Submit the blit command to the GPU and wait... */ mtlEndEncoding(blit); METAL_INTERNAL_Flush(renderer); /* We're done with the temp texture */ mtlSetPurgeableState( handle, MTLPurgeableStateEmpty ); } } static void METAL_SetTextureDataYUV( FNA3D_Renderer *driverData, FNA3D_Texture *y, FNA3D_Texture *u, FNA3D_Texture *v, int32_t yWidth, int32_t yHeight, int32_t uvWidth, int32_t uvHeight, void* data, int32_t dataLength ) { uint8_t* dataPtr = (uint8_t*) data; MTLOrigin origin = {0, 0, 0}; MTLSize sizeY = {yWidth, yHeight, 1}; MTLSize sizeUV = {uvWidth, uvHeight, 1}; MTLRegion regionY = {origin, sizeY}; MTLRegion regionUV = {origin, sizeUV}; mtlReplaceRegion( ((MetalTexture*) y)->handle, regionY, 0, 0, dataPtr, yWidth, 0 ); dataPtr += yWidth * yHeight; mtlReplaceRegion( ((MetalTexture*) u)->handle, regionUV, 0, 0, dataPtr, uvWidth, 0 ); dataPtr += uvWidth * uvHeight; mtlReplaceRegion( ((MetalTexture*) v)->handle, regionUV, 0, 0, dataPtr, uvWidth, 0 ); } static void METAL_GetTextureData2D( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t w, int32_t h, int32_t level, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLTexture *handle = mtlTexture->handle; MTLBlitCommandEncoder *blit; MTLOrigin origin = {x, y, 0}; MTLSize size = {w, h, 1}; MTLRegion region = {origin, size}; if (mtlTexture->isPrivate) { /* We need an active command buffer */ METAL_INTERNAL_BeginFrame(driverData); /* Fetch a CPU-accessible texture */ handle = METAL_INTERNAL_FetchTransientTexture( renderer, mtlTexture ); /* End the render pass */ METAL_INTERNAL_EndPass(renderer); /* Blit the actual texture to a CPU-accessible texture */ blit = mtlMakeBlitCommandEncoder(renderer->commandBuffer); mtlBlitTextureToTexture( blit, mtlTexture->handle, 0, level, origin, size, handle, 0, level, origin ); /* Managed resources require explicit synchronization */ if (renderer->isMac) { mtlSynchronizeResource(blit, handle); } /* Submit the blit command to the GPU and wait... */ mtlEndEncoding(blit); METAL_INTERNAL_Flush(renderer); } mtlGetTextureBytes( handle, data, BytesPerRow(w, mtlTexture->format), 0, region, level, 0 ); if (mtlTexture->isPrivate) { /* We're done with the temp texture */ mtlSetPurgeableState( handle, MTLPurgeableStateEmpty ); } } static void METAL_GetTextureData3D( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t z, int32_t w, int32_t h, int32_t d, int32_t level, void* data, int32_t dataLength ) { MetalTexture *mtlTexture = (MetalTexture*) texture; MTLOrigin origin = {x, y, z}; MTLSize size = {w, h, d}; MTLRegion region = {origin, size}; mtlGetTextureBytes( mtlTexture->handle, data, BytesPerRow(w, mtlTexture->format), BytesPerImage(w, h, mtlTexture->format), region, level, 0 ); } static void METAL_GetTextureDataCube( FNA3D_Renderer *driverData, FNA3D_Texture *texture, int32_t x, int32_t y, int32_t w, int32_t h, FNA3D_CubeMapFace cubeMapFace, int32_t level, void* data, int32_t dataLength ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalTexture *mtlTexture = (MetalTexture*) texture; MTLTexture *handle = mtlTexture->handle; MTLBlitCommandEncoder *blit; MTLOrigin origin = {x, y, 0}; MTLSize size = {w, h, 1}; MTLRegion region = {origin, size}; int32_t slice = cubeMapFace; if (mtlTexture->isPrivate) { /* We need an active command buffer */ METAL_INTERNAL_BeginFrame(driverData); /* Fetch a CPU-accessible texture */ handle = METAL_INTERNAL_FetchTransientTexture( renderer, mtlTexture ); /* Transient textures have no slices */ slice = 0; /* End the render pass */ METAL_INTERNAL_EndPass(renderer); /* Blit the actual texture to a CPU-accessible texture */ blit = mtlMakeBlitCommandEncoder(renderer->commandBuffer); mtlBlitTextureToTexture( blit, mtlTexture->handle, cubeMapFace, level, origin, size, handle, slice, level, origin ); /* Managed resources require explicit synchronization */ if (renderer->isMac) { mtlSynchronizeResource(blit, handle); } /* Submit the blit command to the GPU and wait... */ mtlEndEncoding(blit); METAL_INTERNAL_Flush(renderer); } mtlGetTextureBytes( handle, data, BytesPerRow(w, mtlTexture->format), 0, region, level, 0 ); if (mtlTexture->isPrivate) { /* We're done with the temp texture */ mtlSetPurgeableState( handle, MTLPurgeableStateEmpty ); } } /* Renderbuffers */ static FNA3D_Renderbuffer* METAL_GenColorRenderbuffer( FNA3D_Renderer *driverData, int32_t width, int32_t height, FNA3D_SurfaceFormat format, int32_t multiSampleCount, FNA3D_Texture *texture ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MTLPixelFormat pixelFormat = XNAToMTL_TextureFormat[format]; int32_t sampleCount = METAL_INTERNAL_GetCompatibleSampleCount( renderer, multiSampleCount ); MTLTextureDescriptor *desc; MTLTexture *multiSampleTexture; MetalRenderbuffer *result; /* Generate a multisample texture */ desc = mtlMakeTexture2DDescriptor( pixelFormat, width, height, 0 ); mtlSetStorageMode(desc, MTLStorageModePrivate); mtlSetTextureUsage(desc, MTLTextureUsageRenderTarget); mtlSetTextureType(desc, MTLTextureType2DMultisample); mtlSetTextureSampleCount(desc, sampleCount); multiSampleTexture = mtlNewTexture( renderer->device, desc ); /* Create and return the renderbuffer */ result = SDL_malloc(sizeof(MetalRenderbuffer)); result->handle = ((MetalTexture*) texture)->handle; result->pixelFormat = pixelFormat; result->multiSampleCount = sampleCount; result->multiSampleHandle = multiSampleTexture; return (FNA3D_Renderbuffer*) result; } static FNA3D_Renderbuffer* METAL_GenDepthStencilRenderbuffer( FNA3D_Renderer *driverData, int32_t width, int32_t height, FNA3D_DepthFormat format, int32_t multiSampleCount ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MTLPixelFormat pixelFormat = XNAToMTL_DepthFormat(renderer, format); int32_t sampleCount = METAL_INTERNAL_GetCompatibleSampleCount( renderer, multiSampleCount ); MTLTextureDescriptor *desc; MTLTexture *depthTexture; MetalRenderbuffer *result; /* Generate a depth texture */ desc = mtlMakeTexture2DDescriptor( pixelFormat, width, height, 0 ); mtlSetStorageMode(desc, MTLStorageModePrivate); mtlSetTextureUsage(desc, MTLTextureUsageRenderTarget); if (multiSampleCount > 0) { mtlSetTextureType(desc, MTLTextureType2DMultisample); mtlSetTextureSampleCount(desc, sampleCount); } depthTexture = mtlNewTexture( renderer->device, desc ); /* Create and return the renderbuffer */ result = SDL_malloc(sizeof(MetalRenderbuffer)); result->handle = depthTexture; result->pixelFormat = pixelFormat; result->multiSampleCount = sampleCount; result->multiSampleHandle = NULL; return (FNA3D_Renderbuffer*) result; } static void METAL_AddDisposeRenderbuffer( FNA3D_Renderer *driverData, FNA3D_Renderbuffer *renderbuffer ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalRenderbuffer *mtlRenderbuffer = (MetalRenderbuffer*) renderbuffer; uint8_t isDepthStencil = (mtlRenderbuffer->multiSampleHandle == NULL); int32_t i; if (isDepthStencil) { if (mtlRenderbuffer->handle == renderer->currentDepthStencilBuffer) { renderer->currentDepthStencilBuffer = NULL; } objc_release(mtlRenderbuffer->handle); mtlRenderbuffer->handle = NULL; } else { for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1) { if (mtlRenderbuffer->multiSampleHandle == renderer->currentMSAttachments[i]) { renderer->currentMSAttachments[i] = NULL; } } objc_release(mtlRenderbuffer->multiSampleHandle); mtlRenderbuffer->multiSampleHandle = NULL; /* Don't release the regular handle since * it's owned by the associated FNA3D_Texture. */ } SDL_free(mtlRenderbuffer); } /* Vertex Buffers */ static FNA3D_Buffer* METAL_GenVertexBuffer( FNA3D_Renderer *driverData, uint8_t dynamic, FNA3D_BufferUsage usage, int32_t sizeInBytes ) { /* Note that dynamic and usage are NOT used! */ return METAL_INTERNAL_CreateBuffer(driverData, sizeInBytes); } static void METAL_AddDisposeVertexBuffer( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer ) { METAL_INTERNAL_DestroyBuffer(driverData, buffer); } static void METAL_SetVertexBufferData( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer, int32_t offsetInBytes, void* data, int32_t elementCount, int32_t elementSizeInBytes, int32_t vertexStride, FNA3D_SetDataOptions options ) { /* FIXME: Staging buffer for elementSizeInBytes < vertexStride! */ METAL_INTERNAL_SetBufferData( driverData, buffer, offsetInBytes, data, elementCount * vertexStride, options ); } static void METAL_GetVertexBufferData( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer, int32_t offsetInBytes, void* data, int32_t elementCount, int32_t elementSizeInBytes, int32_t vertexStride ) { MetalBuffer *mtlBuffer = (MetalBuffer*) buffer; uint8_t *dataBytes, *cpy, *src, *dst; uint8_t useStagingBuffer; int32_t i; dataBytes = (uint8_t*) data; useStagingBuffer = elementSizeInBytes < vertexStride; if (useStagingBuffer) { cpy = (uint8_t*) SDL_malloc(elementCount * vertexStride); } else { cpy = dataBytes; } src = mtlBuffer->subBuffers[mtlBuffer->currentSubBufferIndex].ptr; SDL_memcpy( cpy, src + offsetInBytes, elementCount * vertexStride ); if (useStagingBuffer) { src = cpy; dst = dataBytes; for (i = 0; i < elementCount; i += 1) { SDL_memcpy(dst, src, elementSizeInBytes); dst += elementSizeInBytes; src += vertexStride; } SDL_free(cpy); } } /* Index Buffers */ static FNA3D_Buffer* METAL_GenIndexBuffer( FNA3D_Renderer *driverData, uint8_t dynamic, FNA3D_BufferUsage usage, int32_t sizeInBytes ) { /* Note that dynamic and usage are NOT used! */ return METAL_INTERNAL_CreateBuffer(driverData, sizeInBytes); } static void METAL_AddDisposeIndexBuffer( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer ) { METAL_INTERNAL_DestroyBuffer(driverData, buffer); } static void METAL_SetIndexBufferData( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer, int32_t offsetInBytes, void* data, int32_t dataLength, FNA3D_SetDataOptions options ) { METAL_INTERNAL_SetBufferData( driverData, buffer, offsetInBytes, data, dataLength, options ); } static void METAL_GetIndexBufferData( FNA3D_Renderer *driverData, FNA3D_Buffer *buffer, int32_t offsetInBytes, void* data, int32_t dataLength ) { MetalBuffer *mtlBuffer = (MetalBuffer*) buffer; uint8_t *ptr = mtlBuffer->subBuffers[mtlBuffer->currentSubBufferIndex].ptr; SDL_memcpy( data, ptr + offsetInBytes, dataLength ); } /* Effects */ static void METAL_INTERNAL_DeleteShader(void* shader) { MOJOSHADER_mtlShader *mtlShader = (MOJOSHADER_mtlShader*) shader; const MOJOSHADER_parseData *pd; MetalRenderer *renderer; PackedRenderPipelineArray *pArr; PackedVertexBufferBindingsArray *vArr; int32_t i; pd = MOJOSHADER_mtlGetShaderParseData(mtlShader); renderer = (MetalRenderer*) pd->malloc_data; pArr = &renderer->pipelineStateCache; vArr = &renderer->vertexDescriptorCache; /* Run through the caches in reverse order, to minimize the damage of * doing memmove a bunch of times. Also, do the pipeline cache first, * as they are dependent on the vertex descriptors. */ for (i = pArr->count - 1; i >= 0; i -= 1) { const PackedRenderPipelineMap *elem = &pArr->elements[i]; if ( shader == elem->key.vshader || shader == elem->key.pshader ) { objc_release(elem->value); SDL_memmove( pArr->elements + i, pArr->elements + i + 1, sizeof(PackedRenderPipelineMap) * (pArr->count - i - 1) ); pArr->count -= 1; } } for (i = vArr->count - 1; i >= 0; i -= 1) { const PackedVertexBufferBindingsMap *elem = &vArr->elements[i]; if (elem->key.vertexShader == shader) { objc_release(elem->value); SDL_memmove( vArr->elements + i, vArr->elements + i + 1, sizeof(PackedVertexBufferBindingsMap) * (vArr->count - i - 1) ); vArr->count -= 1; } } MOJOSHADER_mtlDeleteShader(mtlShader); } static void METAL_CreateEffect( FNA3D_Renderer *driverData, uint8_t *effectCode, uint32_t effectCodeLength, FNA3D_Effect **effect, MOJOSHADER_effect **effectData ) { int32_t i; MOJOSHADER_effectShaderContext shaderBackend; MetalEffect *result; shaderBackend.compileShader = (MOJOSHADER_compileShaderFunc) MOJOSHADER_mtlCompileShader; shaderBackend.shaderAddRef = (MOJOSHADER_shaderAddRefFunc) MOJOSHADER_mtlShaderAddRef; shaderBackend.deleteShader = METAL_INTERNAL_DeleteShader; shaderBackend.getParseData = (MOJOSHADER_getParseDataFunc) MOJOSHADER_mtlGetShaderParseData; shaderBackend.bindShaders = (MOJOSHADER_bindShadersFunc) MOJOSHADER_mtlBindShaders; shaderBackend.getBoundShaders = (MOJOSHADER_getBoundShadersFunc) MOJOSHADER_mtlGetBoundShaders; shaderBackend.mapUniformBufferMemory = MOJOSHADER_mtlMapUniformBufferMemory; shaderBackend.unmapUniformBufferMemory = MOJOSHADER_mtlUnmapUniformBufferMemory; shaderBackend.getError = MOJOSHADER_mtlGetError; shaderBackend.m = NULL; shaderBackend.f = NULL; shaderBackend.malloc_data = driverData; *effectData = MOJOSHADER_compileEffect( effectCode, effectCodeLength, NULL, 0, NULL, 0, &shaderBackend ); for (i = 0; i < (*effectData)->error_count; i += 1) { FNA3D_LogError( "MOJOSHADER_compileEffect Error: %s", (*effectData)->errors[i].error ); } result = (MetalEffect*) SDL_malloc(sizeof(MetalEffect)); result->effect = *effectData; result->library = MOJOSHADER_mtlCompileLibrary(*effectData); *effect = (FNA3D_Effect*) result; } static void METAL_CloneEffect( FNA3D_Renderer *driverData, FNA3D_Effect *cloneSource, FNA3D_Effect **effect, MOJOSHADER_effect **effectData ) { MetalEffect *mtlCloneSource = (MetalEffect*) cloneSource; MetalEffect *result; *effectData = MOJOSHADER_cloneEffect(mtlCloneSource->effect); if (*effectData == NULL) { FNA3D_LogError( "%s", MOJOSHADER_mtlGetError() ); } result = (MetalEffect*) SDL_malloc(sizeof(MetalEffect)); result->effect = *effectData; result->library = MOJOSHADER_mtlCompileLibrary(*effectData); *effect = (FNA3D_Effect*) result; } static void METAL_AddDisposeEffect( FNA3D_Renderer *driverData, FNA3D_Effect *effect ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalEffect *mtlEffect = (MetalEffect*) effect; if (mtlEffect->effect == renderer->currentEffect) { MOJOSHADER_effectEndPass(renderer->currentEffect); MOJOSHADER_effectEnd(renderer->currentEffect); renderer->currentEffect = NULL; renderer->currentTechnique = NULL; renderer->currentPass = 0; } MOJOSHADER_mtlDeleteLibrary(mtlEffect->library); MOJOSHADER_deleteEffect(mtlEffect->effect); SDL_free(effect); } static void METAL_SetEffectTechnique( FNA3D_Renderer *renderer, FNA3D_Effect *effect, MOJOSHADER_effectTechnique *technique ) { /* FIXME: Why doesn't this function do anything? */ MetalEffect *mtlEffect = (MetalEffect*) effect; MOJOSHADER_effectSetTechnique(mtlEffect->effect, technique); } static void METAL_ApplyEffect( FNA3D_Renderer *driverData, FNA3D_Effect *effect, uint32_t pass, MOJOSHADER_effectStateChanges *stateChanges ) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalEffect *fnaEffect = (MetalEffect*) effect; MOJOSHADER_effect *effectData = fnaEffect->effect; const MOJOSHADER_effectTechnique *technique = fnaEffect->effect->current_technique; uint32_t whatever; /* If a frame isn't already in progress, * wait until one begins to avoid overwriting * the previous frame's uniform buffers. */ METAL_INTERNAL_BeginFrame(driverData); if (effectData == renderer->currentEffect) { if ( technique == renderer->currentTechnique && pass == renderer->currentPass ) { MOJOSHADER_effectCommitChanges( renderer->currentEffect ); return; } MOJOSHADER_effectEndPass(renderer->currentEffect); MOJOSHADER_effectBeginPass(renderer->currentEffect, pass); renderer->currentTechnique = technique; renderer->currentPass = pass; return; } else if (renderer->currentEffect != NULL) { MOJOSHADER_effectEndPass(renderer->currentEffect); MOJOSHADER_effectEnd(renderer->currentEffect); } MOJOSHADER_effectBegin( effectData, &whatever, 0, stateChanges ); MOJOSHADER_effectBeginPass(effectData, pass); renderer->currentEffect = effectData; renderer->currentTechnique = technique; renderer->currentPass = pass; } static void METAL_BeginPassRestore( FNA3D_Renderer *driverData, FNA3D_Effect *effect, MOJOSHADER_effectStateChanges *stateChanges ) { MOJOSHADER_effect *effectData = ((MetalEffect*) effect)->effect; uint32_t whatever; /* If a frame isn't already in progress, * wait until one begins to avoid overwriting * the previous frame's uniform buffers. */ METAL_INTERNAL_BeginFrame(driverData); MOJOSHADER_effectBegin( effectData, &whatever, 1, stateChanges ); MOJOSHADER_effectBeginPass(effectData, 0); } static void METAL_EndPassRestore( FNA3D_Renderer *driverData, FNA3D_Effect *effect ) { MOJOSHADER_effect *effectData = ((MetalEffect*) effect)->effect; MOJOSHADER_effectEndPass(effectData); MOJOSHADER_effectEnd(effectData); } /* Queries */ static FNA3D_Query* METAL_CreateQuery(FNA3D_Renderer *driverData) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalQuery *result; SDL_assert(renderer->supportsOcclusionQueries); result = (MetalQuery*) SDL_malloc(sizeof(MetalQuery)); result->handle = mtlNewBuffer( renderer->device, sizeof(uint64_t), 0 ); return (FNA3D_Query*) result; } static void METAL_AddDisposeQuery(FNA3D_Renderer *driverData, FNA3D_Query *query) { MetalQuery *mtlQuery = (MetalQuery*) query; objc_release(mtlQuery->handle); mtlQuery->handle = NULL; SDL_free(mtlQuery); } static void METAL_QueryBegin(FNA3D_Renderer *driverData, FNA3D_Query *query) { MetalRenderer *renderer = (MetalRenderer*) driverData; MetalQuery *mtlQuery = (MetalQuery*) query; /* Stop the current pass */ METAL_INTERNAL_EndPass(renderer); /* Attach the visibility buffer to a new render pass */ renderer->currentVisibilityBuffer = mtlQuery->handle; renderer->needNewRenderPass = 1; } static void METAL_QueryEnd(FNA3D_Renderer *driverData, FNA3D_Query *query) { MetalRenderer *renderer = (MetalRenderer*) driverData; if (renderer->renderCommandEncoder != NULL) { /* Stop counting */ mtlSetVisibilityResultMode( renderer->renderCommandEncoder, MTLVisibilityResultModeDisabled, 0 ); } renderer->currentVisibilityBuffer = NULL; } static uint8_t METAL_QueryComplete(FNA3D_Renderer *driverData, FNA3D_Query *query) { /* FIXME: * There's no easy way to check for completion * of the query. The only accurate way would be * to monitor the completion of the command buffer * associated with each query, but that gets tricky * since in the event of a stalled buffer overwrite or * something similar, a new command buffer would be * created, likely screwing up the visibility test. * * The below code is obviously wrong, but it happens * to work for the Lens Flare XNA sample. Maybe it'll * work for your game too? * * (Although if you're making a new game with FNA, * you really shouldn't be using queries anyway...) * * -caleb */ return 1; } static int32_t METAL_QueryPixelCount( FNA3D_Renderer *driverData, FNA3D_Query *query ) { MetalQuery *mtlQuery = (MetalQuery*) query; void* contents = mtlGetBufferContents(mtlQuery->handle); return (int32_t) (*((uint64_t*) contents)); } /* Feature Queries */ static uint8_t METAL_SupportsDXT1(FNA3D_Renderer *driverData) { return ((MetalRenderer*) driverData)->supportsDxt1; } static uint8_t METAL_SupportsS3TC(FNA3D_Renderer *driverData) { return ((MetalRenderer*) driverData)->supportsS3tc; } static uint8_t METAL_SupportsHardwareInstancing(FNA3D_Renderer *driverData) { return 1; } static uint8_t METAL_SupportsNoOverwrite(FNA3D_Renderer *driverData) { return 1; } static void METAL_GetMaxTextureSlots( FNA3D_Renderer *driverData, int32_t *textures, int32_t *vertexTextures ) { *textures = MAX_TEXTURE_SAMPLERS; *vertexTextures = MAX_VERTEXTEXTURE_SAMPLERS; } static int32_t METAL_GetMaxMultiSampleCount( FNA3D_Renderer *driverData, FNA3D_SurfaceFormat format, int32_t multiSampleCount ) { MetalRenderer *renderer = (MetalRenderer*) driverData; /* FIXME: Format-specific MSAA queries? */ return SDL_min(renderer->maxMultiSampleCount, multiSampleCount); } /* Debugging */ static void METAL_SetStringMarker(FNA3D_Renderer *driverData, const char *text) { MetalRenderer *renderer = (MetalRenderer*) driverData; if (renderer->renderCommandEncoder != NULL) { mtlInsertDebugSignpost(renderer->renderCommandEncoder, text); } } /* External Interop */ static void METAL_GetSysRenderer( FNA3D_Renderer *driverData, FNA3D_SysRendererEXT *sysrenderer ) { MetalRenderer *renderer = (MetalRenderer*) driverData; sysrenderer->rendererType = FNA3D_RENDERER_TYPE_METAL_EXT; sysrenderer->renderer.metal.device = renderer->device; sysrenderer->renderer.metal.view = renderer->view; } static FNA3D_Texture* METAL_CreateSysTexture( FNA3D_Renderer *driverData, FNA3D_SysTextureEXT *systexture ) { MetalTexture *result; if (systexture->rendererType != FNA3D_RENDERER_TYPE_METAL_EXT) { return NULL; } result = (MetalTexture*) SDL_malloc(sizeof(MetalTexture)); SDL_zerop(result); result->handle = (MTLTexture*) systexture->texture.metal.handle; result->hasMipmaps = mtlGetTextureLevelCount(result->handle) > 1; /* Everything else either happens to be 0 or is unused anyway! */ objc_retain(result->handle); return (FNA3D_Texture*) result; } /* Driver */ static uint8_t METAL_PrepareWindowAttributes(uint32_t *flags) { /* Let's find out if the OS supports Metal... */ const char *osVersion = SDL_GetPlatform(); uint8_t isApplePlatform = ( (strcmp(osVersion, "Mac OS X") == 0) || (strcmp(osVersion, "iOS") == 0) || (strcmp(osVersion, "tvOS") == 0) ); void* metalFramework; if (!isApplePlatform) { /* What are you even doing here...? */ return 0; } /* Try loading MTLCreateSystemDefaultDevice */ metalFramework = SDL_LoadObject( "/System/Library/Frameworks/Metal.framework/Metal" ); if (metalFramework == NULL) { /* Can't load the Metal framework! */ return 0; } MTLCreateSystemDefaultDevice = (pfn_CreateSystemDefaultDevice) SDL_LoadFunction( metalFramework, "MTLCreateSystemDefaultDevice" ); if (MTLCreateSystemDefaultDevice() == NULL) { /* This OS is too old for Metal! */ return 0; } /* We're good to go, so initialize the Objective-C references. */ InitObjC(); #if SDL_VERSION_ATLEAST(2, 0, 13) *flags = SDL_WINDOW_METAL; #else SDL_SetHint(SDL_HINT_VIDEO_EXTERNAL_CONTEXT, "1"); #endif return 1; } void METAL_GetDrawableSize(void* window, int32_t *w, int32_t *h) { SDL_MetalView tempView = SDL_Metal_CreateView((SDL_Window*) window); CAMetalLayer *layer = mtlGetLayer(tempView); CGSize size = mtlGetDrawableSize(layer); *w = size.width; *h = size.height; SDL_Metal_DestroyView(tempView); } static void METAL_INTERNAL_InitializeFauxBackbuffer( MetalRenderer *renderer, uint8_t scaleNearest ) { uint16_t indices[6] = { 0, 1, 3, 1, 2, 3 }; uint8_t* ptr; const char *shaderSource; NSString *nsShaderSource, *nsVertShader, *nsFragShader; MTLLibrary *library; MTLFunction *vertexFunc, *fragFunc; MTLSamplerDescriptor *samplerDesc; MTLRenderPipelineDescriptor *pipelineDesc; MTLSamplerMinMagFilter filter = ( scaleNearest ? MTLSamplerMinMagFilterNearest : MTLSamplerMinMagFilterLinear ); /* Create a combined vertex / index buffer * for rendering the faux backbuffer. */ renderer->backbufferDrawBuffer = mtlNewBuffer( renderer->device, 16 * sizeof(float) + sizeof(indices), MTLResourceOptionsCPUCacheModeWriteCombined ); ptr = (uint8_t*) mtlGetBufferContents( renderer->backbufferDrawBuffer ); SDL_memcpy( ptr + (16 * sizeof(float)), indices, sizeof(indices) ); /* Create vertex and fragment shaders for the faux backbuffer */ shaderSource = "#include <metal_stdlib> \n" "using namespace metal; \n" "struct VertexIn { \n" " packed_float2 position; \n" " packed_float2 texCoord; \n" "}; \n" "struct VertexOut { \n" " float4 position [[ position ]]; \n" " float2 texCoord; \n" "}; \n" "vertex VertexOut vertexShader( \n" " uint vertexID [[ vertex_id ]], \n" " constant VertexIn *vertexArray [[ buffer(0) ]] \n" ") { \n" " VertexOut out; \n" " out.position = float4( \n" " vertexArray[vertexID].position, \n" " 0.0, \n" " 1.0 \n" " ); \n" " out.position.y *= -1; \n" " out.texCoord = vertexArray[vertexID].texCoord; \n" " return out; \n" "} \n" "fragment float4 fragmentShader( \n" " VertexOut in [[stage_in]], \n" " texture2d<half> colorTexture [[ texture(0) ]], \n" " sampler s0 [[sampler(0)]] \n" ") { \n" " const half4 colorSample = colorTexture.sample( \n" " s0, \n" " in.texCoord \n" " ); \n" " return float4(colorSample); \n" "} \n"; nsShaderSource = UTF8ToNSString(shaderSource); nsVertShader = UTF8ToNSString("vertexShader"); nsFragShader = UTF8ToNSString("fragmentShader"); library = mtlNewLibraryWithSource( renderer->device, nsShaderSource ); vertexFunc = mtlNewFunctionWithName(library, nsVertShader); fragFunc = mtlNewFunctionWithName(library, nsFragShader); objc_release(nsShaderSource); objc_release(nsVertShader); objc_release(nsFragShader); /* Create sampler state */ samplerDesc = mtlNewSamplerDescriptor(); mtlSetSamplerMinFilter(samplerDesc, filter); mtlSetSamplerMagFilter(samplerDesc, filter); renderer->backbufferSamplerState = mtlNewSamplerState( renderer->device, samplerDesc ); objc_release(samplerDesc); /* Create render pipeline */ pipelineDesc = mtlNewRenderPipelineDescriptor(); mtlSetPipelineVertexFunction(pipelineDesc, vertexFunc); mtlSetPipelineFragmentFunction(pipelineDesc, fragFunc); mtlSetAttachmentPixelFormat( mtlGetColorAttachment(pipelineDesc, 0), mtlGetLayerPixelFormat(renderer->layer) ); renderer->backbufferPipeline = mtlNewRenderPipelineState( renderer->device, pipelineDesc ); objc_release(pipelineDesc); objc_release(vertexFunc); objc_release(fragFunc); } FNA3D_Device* METAL_CreateDevice( FNA3D_PresentationParameters *presentationParameters, uint8_t debugMode ) { uint8_t supportsD24S8; int32_t i; MTLDepthStencilDescriptor *dsDesc; MetalRenderer *renderer; FNA3D_Device *result; /* Create the FNA3D_Device */ result = (FNA3D_Device*) SDL_malloc(sizeof(FNA3D_Device)); ASSIGN_DRIVER(METAL) /* Init the MetalRenderer */ renderer = (MetalRenderer*) SDL_malloc(sizeof(MetalRenderer)); SDL_memset(renderer, '\0', sizeof(MetalRenderer)); /* The FNA3D_Device and MetalRenderer need to reference each other */ renderer->parentDevice = result; result->driverData = (FNA3D_Renderer*) renderer; /* Create the MTLDevice and MTLCommandQueue */ renderer->device = MTLCreateSystemDefaultDevice(); renderer->queue = mtlNewCommandQueue(renderer->device); /* Create the Metal view and get its layer */ renderer->view = SDL_Metal_CreateView( (SDL_Window*) presentationParameters->deviceWindowHandle ); renderer->layer = mtlGetLayer(renderer->view); /* Set up the layer */ mtlSetLayerDevice(renderer->layer, renderer->device); mtlSetLayerFramebufferOnly(renderer->layer, 1); mtlSetLayerMagnificationFilter( renderer->layer, UTF8ToNSString("nearest") ); /* Log driver info */ FNA3D_LogInfo( "FNA3D Driver: Metal\nDevice Name: %s", mtlGetDeviceName(renderer->device) ); /* Set device properties */ renderer->isMac = (strcmp(SDL_GetPlatform(), "Mac OS X") == 0); renderer->supportsS3tc = renderer->supportsDxt1 = renderer->isMac; renderer->maxMultiSampleCount = ( mtlDeviceSupportsSampleCount(renderer->device, 8) ? 8 : 4 ); renderer->supportsOcclusionQueries = ( renderer->isMac || HasModernAppleGPU(renderer->device) ); /* Determine supported depth formats */ renderer->D16Format = MTLPixelFormatDepth32Float; renderer->D24Format = MTLPixelFormatDepth32Float; renderer->D24S8Format = MTLPixelFormatDepth32FloatStencil8; if (renderer->isMac) { supportsD24S8 = mtlDeviceSupportsDepth24Stencil8(renderer->device); if (supportsD24S8) { renderer->D24S8Format = MTLPixelFormatDepth24UnormStencil8; /* Gross, but at least it's a unorm format! -caleb */ renderer->D24Format = MTLPixelFormatDepth24UnormStencil8; renderer->D16Format = MTLPixelFormatDepth24UnormStencil8; } /* Depth16Unorm requires macOS 10.12+ */ if (OperatingSystemAtLeast(10, 12, 0)) { renderer->D16Format = MTLPixelFormatDepth16Unorm; } } else { /* Depth16Unorm requires iOS/tvOS 13+ */ if (OperatingSystemAtLeast(13, 0, 0)) { renderer->D16Format = MTLPixelFormatDepth16Unorm; } } /* Initialize MojoShader context */ renderer->mtlContext = MOJOSHADER_mtlCreateContext( renderer->device, NULL, NULL, renderer ); MOJOSHADER_mtlMakeContextCurrent(renderer->mtlContext); /* Initialize texture and sampler collections */ for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1) { renderer->textures[i] = &NullTexture; renderer->samplers[i] = NULL; } /* Create a default depth stencil state */ dsDesc = mtlNewDepthStencilDescriptor(); renderer->defaultDepthStencilState = mtlNewDepthStencilState( renderer->device, dsDesc ); objc_release(dsDesc); /* Create and initialize the faux-backbuffer */ renderer->backbuffer = (MetalBackbuffer*) SDL_malloc( sizeof(MetalBackbuffer) ); SDL_memset(renderer->backbuffer, '\0', sizeof(MetalBackbuffer)); METAL_INTERNAL_CreateFramebuffer( renderer, presentationParameters ); METAL_INTERNAL_InitializeFauxBackbuffer( renderer, SDL_GetHintBoolean("FNA3D_BACKBUFFER_SCALE_NEAREST", SDL_FALSE) ); METAL_INTERNAL_SetPresentationInterval( renderer, presentationParameters->presentationInterval ); /* Initialize buffer allocator */ renderer->bufferAllocator = (MetalBufferAllocator*) SDL_malloc( sizeof(MetalBufferAllocator) ); SDL_memset(renderer->bufferAllocator, '\0', sizeof(MetalBufferAllocator)); /* Initialize buffers/textures-in-use arrays */ renderer->maxBuffersInUse = 8; /* arbitrary! */ renderer->buffersInUse = (MetalBuffer**) SDL_malloc( sizeof(MetalBuffer*) * renderer->maxBuffersInUse ); renderer->maxTexturesInUse = 8; /* arbitrary! */ renderer->texturesInUse = (MetalTexture**) SDL_malloc( sizeof(MetalTexture*) * renderer->maxTexturesInUse ); /* Initialize renderer members not covered by SDL_memset('\0') */ renderer->multiSampleMask = -1; /* AKA 0xFFFFFFFF, ugh -flibit */ renderer->multiSampleEnable = 1; renderer->viewport.maxDepth = 1.0f; renderer->clearDepth = 1.0f; /* Return the FNA3D_Device */ return result; } FNA3D_Driver MetalDriver = { "Metal", METAL_PrepareWindowAttributes, METAL_GetDrawableSize, METAL_CreateDevice }; #else extern int this_tu_is_empty; #endif /* FNA3D_DRIVER_METAL */ /* vim: set noexpandtab shiftwidth=8 tabstop=8: */
the_stack_data/34513000.c
#include <stdio.h> double yes(double y); double no(double n); int main(void) { int choice; double price, d_a; printf("Please Enter Your Product Amount: "); scanf("%lf", &price); if(price < 100) { printf("\n\nYou have to pay %.2lf BDT\n\n", price); } else { printf("\n\nAre you a member?\n\n"); printf("1.YES\n2.NO\n\n=> "); scanf("%d", &choice); if(choice == 1) { double d_a = yes(price); printf("\n\nYou have to pay %.2lf BDT\n\n", d_a); } else if(choice == 2) { double d_a = no(price); printf("\n\nYou have to pay %.2lf BDT\n\n", d_a); } else { printf("\n\nInvalid Option Chosen! Please try again.\n\n"); } } return 0; } double yes(double y) { double result = y - 30*y/100; return result; } double no(double n) { double result = n - 10*n/100; return result; }
the_stack_data/89200176.c
#include <stdio.h> #define BIG_ENDIAN 0 #define LITTLE_ENDIAN 1 int TestByteOrder() { short int word = "SOMETHING"; char *byte = (char *) &word; return (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN); } int main() { int x, y, m, n; scanf ("%d %d", &x, &y); /* x > 0 and y > 0 */ m = x; n = y; while (m != n) { if(m>n) m = m - n; else n = n - m; } printf("%d", n); }
the_stack_data/153800.c
/* author : s.shivasurya date 11-3-2016 check that given number is power of 2 convert into binary - common pattern that 2^ something will have only 1 bit as 1 and rest zero take a number decreament and do AND operation if you get 1 then its not power of two else it is power of two And operation is just boolean Table and operation */ #include<stdio.h> void ispoweroftwo(int a){ if(a==0) printf("Not power of 2\n"); if((a & (a-1)) == 0) printf("power of 2\n"); else printf("Not power of 2\n"); } int main(){ ispoweroftwo(4); ispoweroftwo(128); ispoweroftwo(25000); ispoweroftwo(999); }
the_stack_data/12638909.c
#include <errno.h> #include <unistd.h> long __syscall_ret(unsigned long r) { if (r > -4096UL) { errno = -r; return -1; } return r; }
the_stack_data/272065.c
/******************************************************************************************************** * @file app_ui.c * * @brief This is the source file for app_ui * * @author Zigbee Group * @date 2021 * * @par Copyright (c) 2021, Telink Semiconductor (Shanghai) Co., Ltd. ("TELINK") * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************************************/ #if (__PROJECT_TL_SWITCH__) /********************************************************************** * INCLUDES */ #include "tl_common.h" #include "zb_api.h" #include "zcl_include.h" #include "sampleSwitch.h" #include "app_ui.h" /********************************************************************** * LOCAL CONSTANTS */ /********************************************************************** * TYPEDEFS */ /********************************************************************** * LOCAL FUNCTIONS */ void led_on(u32 pin) { drv_gpio_write(pin, LED_ON); } void led_off(u32 pin) { drv_gpio_write(pin, LED_OFF); } void light_on(void) { led_on(LED1); } void light_off(void) { led_off(LED1); } void light_init(void) { led_off(LED1); } s32 zclLightTimerCb(void *arg) { u32 interval = 0; if(g_switchAppCtx.sta == g_switchAppCtx.oriSta){ g_switchAppCtx.times--; if(g_switchAppCtx.times <= 0){ g_switchAppCtx.timerLedEvt = NULL; return -1; } } g_switchAppCtx.sta = !g_switchAppCtx.sta; if(g_switchAppCtx.sta){ light_on(); interval = g_switchAppCtx.ledOnTime; }else{ light_off(); interval = g_switchAppCtx.ledOffTime; } return interval; } void light_blink_start(u8 times, u16 ledOnTime, u16 ledOffTime) { u32 interval = 0; g_switchAppCtx.times = times; if(!g_switchAppCtx.timerLedEvt){ if(g_switchAppCtx.oriSta){ light_off(); g_switchAppCtx.sta = 0; interval = ledOffTime; }else{ light_on(); g_switchAppCtx.sta = 1; interval = ledOnTime; } g_switchAppCtx.ledOnTime = ledOnTime; g_switchAppCtx.ledOffTime = ledOffTime; g_switchAppCtx.timerLedEvt = TL_ZB_TIMER_SCHEDULE(zclLightTimerCb, NULL, interval); } } void light_blink_stop(void) { if(g_switchAppCtx.timerLedEvt){ TL_ZB_TIMER_CANCEL(&g_switchAppCtx.timerLedEvt); g_switchAppCtx.times = 0; if(g_switchAppCtx.oriSta){ light_on(); }else{ light_off(); } } } /******************************************************************* * @brief Button click detect: * SW1. keep press button1 5s === factory reset * SW1. short press button1 === send level step with OnOff command (Up) * SW2. keep press button2 5s === invoke EZ-Mode * SW2. short press button2 === send level step with OnOff command (Down) * */ void buttonKeepPressed(u8 btNum){ if(btNum == VK_SW1){ g_switchAppCtx.state = APP_FACTORY_NEW_DOING; zb_factoryReset(); }else if(btNum == VK_SW2){ } } void set_detect_voltage(s32 v){ g_switchAppCtx.Vbat = v; } ev_timer_event_t *brc_toggleEvt = NULL; s32 brc_toggleCb(void *arg) { epInfo_t dstEpInfo; TL_SETSTRUCTCONTENT(dstEpInfo, 0); dstEpInfo.dstAddrMode = APS_SHORT_DSTADDR_WITHEP; dstEpInfo.dstEp = SAMPLE_SWITCH_ENDPOINT; dstEpInfo.dstAddr.shortAddr = 0xfffc; dstEpInfo.profileId = HA_PROFILE_ID; zcl_onOff_toggleCmd(SAMPLE_SWITCH_ENDPOINT, &dstEpInfo, FALSE); return 0; } void brc_toggle(void) { if(!brc_toggleEvt){ brc_toggleEvt = TL_ZB_TIMER_SCHEDULE(brc_toggleCb, NULL, 1000); }else{ TL_ZB_TIMER_CANCEL(&brc_toggleEvt); } } void buttonShortPressed(u8 btNum){ if(btNum == VK_SW1){ if(zb_isDeviceJoinedNwk()){ #if 1 epInfo_t dstEpInfo; TL_SETSTRUCTCONTENT(dstEpInfo, 0); dstEpInfo.profileId = HA_PROFILE_ID; #if FIND_AND_BIND_SUPPORT dstEpInfo.dstAddrMode = APS_DSTADDR_EP_NOTPRESETNT; #else dstEpInfo.dstAddrMode = APS_SHORT_DSTADDR_WITHEP; dstEpInfo.dstEp = SAMPLE_SWITCH_ENDPOINT; dstEpInfo.dstAddr.shortAddr = 0xfffc; #endif zcl_onOff_toggleCmd(SAMPLE_SWITCH_ENDPOINT, &dstEpInfo, FALSE); #else brc_toggle(); #endif } }else if(btNum == VK_SW2){ if(zb_isDeviceJoinedNwk()){ static u8 lvl = 1; static bool dir = 1; epInfo_t dstEpInfo; TL_SETSTRUCTCONTENT(dstEpInfo, 0); dstEpInfo.dstAddrMode = APS_SHORT_DSTADDR_WITHEP; dstEpInfo.dstEp = SAMPLE_SWITCH_ENDPOINT; dstEpInfo.dstAddr.shortAddr = 0xfffc; dstEpInfo.profileId = HA_PROFILE_ID; moveToLvl_t move2Level; move2Level.optPresent = 0; move2Level.transitionTime = 0x0A; move2Level.level = lvl; zcl_level_move2levelCmd(SAMPLE_SWITCH_ENDPOINT, &dstEpInfo, FALSE, &move2Level); if(dir){ lvl += 50; if(lvl >= 250){ dir = 0; } }else{ lvl -= 50; if(lvl <= 1){ dir = 1; } } } } } void keyScan_keyPressedCB(kb_data_t *kbEvt){ //u8 toNormal = 0; u8 keyCode = kbEvt->keycode[0]; //static u8 lastKeyCode = 0xff; buttonShortPressed(keyCode); if(keyCode == VK_SW1){ g_switchAppCtx.keyPressedTime = clock_time(); g_switchAppCtx.state = APP_FACTORY_NEW_SET_CHECK; } } void keyScan_keyReleasedCB(u8 keyCode){ g_switchAppCtx.state = APP_STATE_NORMAL; } void app_key_handler(void){ static u8 valid_keyCode = 0xff; if(g_switchAppCtx.state == APP_FACTORY_NEW_SET_CHECK){ if(clock_time_exceed(g_switchAppCtx.keyPressedTime, 5*1000*1000)){ buttonKeepPressed(VK_SW1); } } if(kb_scan_key(0, 1)){ if(kb_event.cnt){ g_switchAppCtx.keyPressed = 1; keyScan_keyPressedCB(&kb_event); if(kb_event.cnt == 1){ valid_keyCode = kb_event.keycode[0]; } }else{ keyScan_keyReleasedCB(valid_keyCode); valid_keyCode = 0xff; g_switchAppCtx.keyPressed = 0; } } } #endif /* __PROJECT_TL_SWITCH__ */
the_stack_data/192331362.c
/** @Generated PIC24 / dsPIC33 / PIC32MM MCUs Source File @Company: Microchip Technology Inc. @File Name: mcc.c @Summary: This is the mcc.c file generated using PIC24 / dsPIC33 / PIC32MM MCUs @Description: The configuration contents of this file are moved to system.c and this file will be removed in future MCC releases. Generation Information : Product Revision : PIC24 / dsPIC33 / PIC32MM MCUs - 1.167.0 Device : dsPIC33CK256MP506 The generated drivers are tested against the following: Compiler : XC16 v1.50 MPLAB : MPLAB X v5.35 */ /* (c) 2020 Microchip Technology Inc. and its subsidiaries. You may use this software and any derivatives exclusively with Microchip products. THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. */ /** End of File */
the_stack_data/34512388.c
/* ********************************************************** * Copyright (c) 2003 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Build with: * gcc -o pthreads pthreads.c -lpthread -D_REENTRANT -I../lib -L../lib -ldynamo -ldl -lbfd -liberty */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #ifdef USE_DYNAMO #include "dynamorio.h" #endif volatile double pi = 0.0; /* Approximation to pi (shared) */ pthread_mutex_t pi_lock; /* Lock for above */ volatile double intervals; /* How many intervals? */ void * process(void *arg) { char *id = (char *) arg; register double width, localsum; register int i; register int iproc; #if VERBOSE fprintf(stderr, "\tthread %s starting\n", id); #endif iproc = (*((char *) arg) - '0'); /* Set width */ width = 1.0 / intervals; /* Do the local computations */ localsum = 0; for (i=iproc; i<intervals; i+=2) { register double x = (i + 0.5) * width; localsum += 4.0 / (1.0 + x * x); } localsum *= width; /* Lock pi for update, update it, and unlock */ pthread_mutex_lock(&pi_lock); pi += localsum; pthread_mutex_unlock(&pi_lock); #if VERBOSE fprintf(stderr, "\tthread %s exiting\n", id); #endif return(NULL); } int main(int argc, char **argv) { pthread_t thread0, thread1; void * retval; #ifdef USE_DYNAMO dynamorio_app_init(); dynamorio_app_start(); #endif #if 0 /* Get the number of intervals */ if (argc != 2) { fprintf(stderr, "Usage: %s <intervals>\n", argv[0]); exit(0); } intervals = atoi(argv[1]); #else /* for batch mode */ intervals = 10; #endif /* Initialize the lock on pi */ pthread_mutex_init(&pi_lock, NULL); /* Make the two threads */ if (pthread_create(&thread0, NULL, process, "0") || pthread_create(&thread1, NULL, process, "1")) { fprintf(stderr, "%s: cannot make thread\n", argv[0]); exit(1); } /* Join (collapse) the two threads */ if (pthread_join(thread0, &retval) || pthread_join(thread1, &retval)) { fprintf(stderr, "%s: thread join failed\n", argv[0]); exit(1); } /* Print the result */ printf("Estimation of pi is %16.15f\n", pi); #ifdef USE_DYNAMO dynamorio_app_stop(); dynamorio_app_exit(); #endif }
the_stack_data/115765955.c
#include <sys/ioctl.h> #include <termio.h> int tcgetattr(int fd, struct termios *term) { return ioctl(fd, TCGETS, (unsigned long)term); }
the_stack_data/50137895.c
/* ** my_str_isalpha.c for my_str_isnum.c in /home/cedric/delivery/CPool_Day06 ** ** Made by Cédric Thomas ** Login <[email protected]> ** ** Started on Mon Oct 10 17:24:58 2016 Cédric Thomas ** Last update Mon Oct 10 18:08:49 2016 Cédric Thomas */ #include <stdlib.h> int my_str_isalpha(char *str) { int i; int bool; i = 0; bool = 1; if (str == NULL) return (0); while (str[i] != 0) { if ((str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z')) bool = 0; i += 1; } return (bool); }
the_stack_data/125086.c
// RUN: %ucc -fsyntax-only %s void vla(int [*]); void vla(int [const *]); f(int *p) { int vla2[*(int *)p]; } g(int len, char data[len][len]) { }
the_stack_data/51700432.c
// Problem : GPE Exam 20210714 Problem D - Social Distancing 2 // Author : timwilliam // Compiled : 08/15/2021 #include <stdio.h> #include <stdlib.h> int main(void){ int N, M, P, i, j, distance, max_distance = 2; int **person_loc; scanf("%d %d %d", &N, &M, &P); person_loc = (int**) malloc(P * sizeof(int*)); for(i = 0; i < P; i++) person_loc[i] = (int*) malloc(2 * sizeof(int)); for(i = 0; i < P; i++) scanf("%d %d", &person_loc[i][0], &person_loc[i][1]); for(i = 0; i < P-1; i++){ distance = abs(person_loc[i][0] - person_loc[i+1][0]) + abs(person_loc[i][1] - person_loc[i+1][1]); if(distance > max_distance) max_distance = distance; } // check for the distance from the four courner for(i = 0; i < P && P == 1; i++){ // bottom left corner distance = abs(person_loc[i][0] - 0) + abs(person_loc[i][1] - 0); max_distance = distance > max_distance ? distance : max_distance; // bottom right corner distance = abs(person_loc[i][0] - (N-1)) + abs(person_loc[i][1] - 0); max_distance = distance > max_distance ? distance : max_distance; // top left corner distance = abs(person_loc[i][0] - 0) + abs(person_loc[i][1] - (M-1)); max_distance = distance > max_distance ? distance : max_distance; // top right corner distance = abs(person_loc[i][0] - (N-1)) + abs(person_loc[i][1] - (M-1)); max_distance = distance > max_distance ? distance : max_distance; } printf("%d\n", max_distance); return 0; }
the_stack_data/162643086.c
/* ** EPITECH PROJECT, 2018 ** Project ** File description: ** free_array.c */ #include <glob.h> #include <stdlib.h> void free_array(void **arr) { size_t i = 0; while (arr && arr[i]) { free(arr[i]); i += 1; } free(arr); }
the_stack_data/232955768.c
/* Complete Context Control Copyright (C) 1991-2012 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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, if not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <ucontext.h> #include <sys/time.h> /* Set by the signal handler. */ static volatile int expired; /* The contexts. */ static ucontext_t uc[3]; /* We do only a certain number of switches. */ static int switches; /* This is the function doing the work. It is just a skeleton, real code has to be filled in. */ static void f (int n) { int m = 0; while (1) { /* This is where the work would be done. */ if (++m % 100 == 0) { putchar ('.'); fflush (stdout); } /* Regularly the @var{expire} variable must be checked. */ if (expired) { /* We do not want the program to run forever. */ if (++switches == 20) return; printf ("\nswitching from %d to %d\n", n, 3 - n); expired = 0; /* Switch to the other context, saving the current one. */ swapcontext (&uc[n], &uc[3 - n]); } } } /* This is the signal handler which simply set the variable. */ void handler (int signal) { expired = 1; } int main (void) { struct sigaction sa; struct itimerval it; char st1[8192]; char st2[8192]; /* Initialize the data structures for the interval timer. */ sa.sa_flags = SA_RESTART; sigfillset (&sa.sa_mask); sa.sa_handler = handler; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 1; it.it_value = it.it_interval; /* Install the timer and get the context we can manipulate. */ if (sigaction (SIGPROF, &sa, NULL) < 0 || setitimer (ITIMER_PROF, &it, NULL) < 0 || getcontext (&uc[1]) == -1 || getcontext (&uc[2]) == -1) abort (); /* Create a context with a separate stack which causes the function @code{f} to be call with the parameter @code{1}. Note that the @code{uc_link} points to the main context which will cause the program to terminate once the function return. */ uc[1].uc_link = &uc[0]; uc[1].uc_stack.ss_sp = st1; uc[1].uc_stack.ss_size = sizeof st1; makecontext (&uc[1], (void (*) (void)) f, 1, 1); /* Similarly, but @code{2} is passed as the parameter to @code{f}. */ uc[2].uc_link = &uc[0]; uc[2].uc_stack.ss_sp = st2; uc[2].uc_stack.ss_size = sizeof st2; makecontext (&uc[2], (void (*) (void)) f, 1, 2); /* Start running. */ swapcontext (&uc[0], &uc[1]); putchar ('\n'); return 0; }
the_stack_data/90762598.c
#include <stdio.h> #include <math.h> int main() { int n,m; printf("Enter N and M\n"); scanf("%i%i",&n,&m); while (n!=m) { if (n%2!=0) printf("%i is odd\n",n); n++; } return 0; }
the_stack_data/126701818.c
void sprstx(float sa[], unsigned long ija[], float x[], float b[], unsigned long n) { void nrerror(char error_text[]); unsigned long i,j,k; if (ija[1] != n+2) nrerror("mismatched vector and matrix in sprstx"); for (i=1;i<=n;i++) b[i]=sa[i]*x[i]; for (i=1;i<=n;i++) { for (k=ija[i];k<=ija[i+1]-1;k++) { j=ija[k]; b[j] += sa[k]*x[i]; } } } /* (C) Copr. 1986-92 Numerical Recipes Software 7&X*. */
the_stack_data/64199573.c
#include<stdio.h> #include<elf.h> #include<unistd.h> #include<stdlib.h> #include<string.h> int main(int argc,char *argv[]) { if(argc<2) { printf("file name is missing.\n"); exit(1); } /* hold the Elf header */ Elf64_Ehdr header; /* hold the elf section */ Elf64_Shdr section; /* hold the address of section */ Elf32_Addr address; FILE *fptr; char *snames; int i,arr[5]; /* opening elf file in read mode */ fptr = fopen(argv[1],"r"); /* first 64 bytes in elf represents the ELF header. reading the header data structure of elf file */ fread(&header,1,sizeof(header),fptr); /* moving the file pointer position to the last section .shstrtab. This section contains the section names present in ELF file */ fseek(fptr,header.e_shoff+header.e_shstrndx*sizeof(section),SEEK_SET); /* reading the .shstrtab section data structure */ fread(&section,1,sizeof(section),fptr); /* allocating the memeory of size .shstrtab section to hold the all the data present in .shstrtab section. */ snames = (char *)malloc(section.sh_size); /* moving the file pointer position to offset address of .shstrtab section */ fseek(fptr,section.sh_offset,SEEK_SET); /* read the all data in the .shstrtab section into memmory pointed by snames */ fread(snames,1,section.sh_size,fptr); /* reading the all section names of ELF file */ for(i=0;i<header.e_shnum;i++) { /* hold the name of section */ char *name = ""; /* setting the file pointer position to each section using e_shoff address in the header */ fseek(fptr,header.e_shoff+i*sizeof(section),SEEK_SET); /* reading the data structure associated with section */ fread(&section,1,sizeof(section),fptr); if(section.sh_name) { name = snames+ section.sh_name; if(strcmp(name,".data")==0) { fseek(fptr,section.sh_offset+16,SEEK_SET); fread(arr,5,4,fptr); } } /* printing the sections name*/ printf("%2u %s\n",i,name); } printf("data in.data section: "); for(i=0;i<5;i++) { printf("%d ",arr[i]); } printf("\n"); return 0; }
the_stack_data/1212170.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SparseLinear.c" #else static int nn_(SparseLinear_updateOutput)(lua_State *L) { long i; THTensor * input = luaT_checkudata(L, 2, torch_Tensor); THTensor * weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor * bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor); THTensor * output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor); long dim = weight->size[0]; /* number of weights.. */ THTensor_(copy)(output, bias); for(i = 0; i < input->size[1]; i++) { long offset = (long)(THTensor_(get2d)(input, 0, i))-1; if(offset >= 0 && offset < dim) /* make sure indices are in bounds.. */ { real val = THTensor_(get2d)(input, 1, i); THBlas_(axpy)(output->size[0], val, THTensor_(data)(weight)+offset*weight->stride[0], weight->stride[1], THTensor_(data)(output), output->stride[0]); } else luaL_error(L, "index out of bound"); } return 1; } static int nn_(SparseLinear_accGradParameters)(lua_State *L) { long i; THTensor * input = luaT_checkudata(L, 2, torch_Tensor); THTensor * gradOutput = luaT_checkudata(L, 3, torch_Tensor); real scale = luaL_optnumber(L, 4, 1); THTensor * weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor * gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor); THTensor * gradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor); THTensor * lastInput = luaT_getfieldcheckudata(L, 1, "lastInput", torch_Tensor); real weightDecay = luaT_getfieldchecknumber(L, 1, "weightDecay"); long dim = gradWeight->size[0]; /* number of weights.. */ for(i = 0; i < input->size[1]; i++) { long offset = (long)(THTensor_(get2d)(input, 0, i))-1; if(offset >= 0 && offset < dim) /* make sure indices are in bounds.. */ { real val = scale*THTensor_(get2d)(input, 1, i); THBlas_(scal)(gradOutput->size[0], 0, THTensor_(data)(gradWeight)+offset*gradWeight->stride[0], gradWeight->stride[1]); /* zero */ THBlas_(axpy)(gradOutput->size[0], val, THTensor_(data)(gradOutput), gradOutput->stride[0], THTensor_(data)(gradWeight)+offset*gradWeight->stride[0], gradWeight->stride[1]); } else luaL_error(L, "index out of bound"); } THTensor_(cadd)(gradBias, gradBias, 1, gradOutput); if(weightDecay != 0) THTensor_(cadd)(gradWeight, gradWeight, weightDecay, weight); THTensor_(resizeAs)(lastInput, input); THTensor_(copy)(lastInput, input); return 0; } int nn_(SparseLinear_updateParameters)(lua_State *L) { long i; real learningRate = luaL_checknumber(L, 2); THTensor * weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor * bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor); THTensor * gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor); THTensor * gradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor); THTensor * lastInput = luaT_getfieldcheckudata(L, 1, "lastInput", torch_Tensor); long dim = weight->size[0]; /* number of weights.. */ THTensor_(cadd)(bias, bias, -learningRate, gradBias); for(i = 0; i < lastInput->size[1]; i++) { long offset = (long)(THTensor_(get2d)(lastInput, 0, i))-1; if(offset >= 0 && offset < dim) /* make sure indices are in bounds.. */ { THBlas_(axpy)(bias->size[0], -learningRate, THTensor_(data)(gradWeight)+offset*gradWeight->stride[0], gradWeight->stride[1], THTensor_(data)(weight)+offset*weight->stride[0], weight->stride[1]); } else luaL_error(L, "index out of bound"); } return 0; } static const struct luaL_Reg nn_(SparseLinear__) [] = { {"SparseLinear_updateOutput", nn_(SparseLinear_updateOutput)}, {"SparseLinear_accGradParameters", nn_(SparseLinear_accGradParameters)}, {"SparseLinear_updateParameters", nn_(SparseLinear_updateParameters)}, {NULL, NULL} }; void nn_(SparseLinear_init)(lua_State *L) { luaT_pushmetatable(L, torch_Tensor); luaT_registeratname(L, nn_(SparseLinear__), "nn"); lua_pop(L,1); } #endif
the_stack_data/1235636.c
// Ensure we support the -mtune flag. // // RUN: %clang -target x86_64-unknown-unknown -c -### %s -mtune=nocona 2>&1 \ // RUN: | FileCheck %s -check-prefix=nocona // nocona: "-tune-cpu" "nocona"
the_stack_data/1052322.c
#include <stdio.h> #include <stdlib.h> void InverteVetor(int vet[], int qtd); void ImprimeDadosDoVetor(int vet[], int qtd); int main(void) { int qtd, i; scanf("%d", &qtd); int vet[qtd]; for (i = 0; i < qtd; i++) scanf("%d", &vet[i]); InverteVetor(vet, qtd); ImprimeDadosDoVetor(vet, qtd); return 0; } void InverteVetor(int vet[], int qtd) { int vet2[qtd]; int i, j; j = qtd - 1; for (i = 0; i < qtd; i++, j--) vet2[j] = vet[i]; for (i = 0; i < qtd; i++) vet[i] = vet2[i]; } void ImprimeDadosDoVetor(int vet[], int qtd) { int i; if (qtd == 0) printf("{}"); if (qtd == 1) printf("{%d}", vet[0]); if (qtd != 0 && qtd != 1) { printf("{"); for (i = 0; i < qtd; i++) { printf("%d", vet[i]); if (i != qtd - 1) printf(", "); } if (i == qtd) printf("}"); } }
the_stack_data/62833.c
/* * ftruncate64 syscall. Copes with 64 bit and 32 bit machines * and on 32 bit machines this sends things into the kernel as * two 32-bit arguments (high and low 32 bits of length) that * are ordered based on endianess. It turns out endian.h has * just the macro we need to order things, __LONG_LONG_PAIR. * * Copyright (C) 2002 Erik Andersen <[email protected]> * * This file is subject to the terms and conditions of the GNU * Lesser General Public License. See the file COPYING.LIB in * the main directory of this archive for more details. */ #include <features.h> #include <unistd.h> #include <errno.h> #include <endian.h> #include <stdint.h> #include <sys/syscall.h> #if defined __NR_ftruncate64 #if __WORDSIZE == 64 || (defined(__powerpc__) && defined (__UCLIBC_HAS_LFS__)) /* For a 64 bit machine, life is simple... */ _syscall2(int, ftruncate64, int, fd, __off64_t, length); #elif __WORDSIZE == 32 #if defined __UCLIBC_HAS_LFS__ #ifndef INLINE_SYSCALL #define INLINE_SYSCALL(name, nr, args...) __syscall_ftruncate64 (args) #define __NR___syscall_ftruncate64 __NR_ftruncate64 static inline _syscall3(int, __syscall_ftruncate64, int, fd, int, high_length, int, low_length); #endif /* The exported ftruncate64 function. */ int ftruncate64 (int fd, __off64_t length) { uint32_t low = length & 0xffffffff; uint32_t high = length >> 32; return INLINE_SYSCALL(ftruncate64, 3, fd, __LONG_LONG_PAIR (high, low)); } #endif /* __UCLIBC_HAS_LFS__ */ #else /* __WORDSIZE */ #error Your machine is not 64 bit or 32 bit, I am dazed and confused. #endif /* __WORDSIZE */ #endif
the_stack_data/90763610.c
#include <stdio.h> #include <stdlib.h> int findMax(int **a, int m, int n) { int i, j, max = 0; for(i = 0; i <= m-1; i++) { for(j = 0; j <= n-1; j++) { if(max<a[i][j]) { max = a[i][j]; } } } return max; } int main() { int* a[20]; int i, j, r, c, s = 0; printf("Enter the number of rows in the matrix\n"); scanf("%d", &r); printf("Enter the number of columns in the matrix\n"); scanf("%d", &c); printf("Enter the elements in the matrix\n"); for(i = 0; i <= r-1; i++) { a[i] = malloc(sizeof(int)*c); for(j = 0; j <= c-1; j++) { scanf("%d", &a[i][j]); } } printf("The matrix is\n"); for(i = 0; i <= r-1; i++) { for(j = 0; j <= c-1; j++) { printf("%d", a[i][j]); } printf("\n"); } s = findMax(a,r,c); printf("The maximum element in the matrix is %d", s); for(i = 0; i<r; i++) { free(a[i]); } return 0; }
the_stack_data/103448.c
// SPDX-License-Identifier: GPL-2.0 #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/time.h> #include <unistd.h> static int child_pid; static unsigned long timediff(struct timeval s, struct timeval e) { unsigned long s_us, e_us; s_us = s.tv_sec * 1000000 + s.tv_usec; e_us = e.tv_sec * 1000000 + e.tv_usec; if (s_us > e_us) return 0; return e_us - s_us; } static void client(int port) { int sock = 0; struct sockaddr_in addr, laddr; socklen_t len = sizeof(laddr); struct linger sl; int flag = 1; int buffer; struct timeval start, end; unsigned long lat, sum_lat = 0, nr_lat = 0; while (1) { gettimeofday(&start, NULL); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) error(-1, errno, "socket creation"); sl.l_onoff = 1; sl.l_linger = 0; if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &sl, sizeof(sl))) error(-1, errno, "setsockopt(linger)"); if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag))) error(-1, errno, "setsockopt(nodelay)"); addr.sin_family = AF_INET; addr.sin_port = htons(port); if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) <= 0) error(-1, errno, "inet_pton"); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) error(-1, errno, "connect"); send(sock, &buffer, sizeof(buffer), 0); if (read(sock, &buffer, sizeof(buffer)) == -1) error(-1, errno, "waiting read"); gettimeofday(&end, NULL); lat = timediff(start, end); sum_lat += lat; nr_lat++; if (lat < 100000) goto close; if (getsockname(sock, (struct sockaddr *)&laddr, &len) == -1) error(-1, errno, "getsockname"); printf("port: %d, lat: %lu, avg: %lu, nr: %lu\n", ntohs(laddr.sin_port), lat, sum_lat / nr_lat, nr_lat); close: fflush(stdout); close(sock); } } static void server(int sock, struct sockaddr_in address) { int accepted; int addrlen = sizeof(address); int buffer; while (1) { accepted = accept(sock, (struct sockaddr *)&address, (socklen_t *)&addrlen); if (accepted < 0) error(-1, errno, "accept"); if (read(accepted, &buffer, sizeof(buffer)) == -1) error(-1, errno, "read"); close(accepted); } } static void sig_handler(int signum) { kill(SIGTERM, child_pid); exit(0); } int main(int argc, char const *argv[]) { int sock; int opt = 1; struct sockaddr_in address; struct sockaddr_in laddr; socklen_t len = sizeof(laddr); if (signal(SIGTERM, sig_handler) == SIG_ERR) error(-1, errno, "signal"); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) error(-1, errno, "socket"); if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) == -1) error(-1, errno, "setsockopt"); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; /* dynamically allocate unused port */ address.sin_port = 0; if (bind(sock, (struct sockaddr *)&address, sizeof(address)) < 0) error(-1, errno, "bind"); if (listen(sock, 3) < 0) error(-1, errno, "listen"); if (getsockname(sock, (struct sockaddr *)&laddr, &len) == -1) error(-1, errno, "getsockname"); fprintf(stderr, "server port: %d\n", ntohs(laddr.sin_port)); child_pid = fork(); if (!child_pid) client(ntohs(laddr.sin_port)); else server(sock, laddr); return 0; }
the_stack_data/96038.c
#include <stdio.h> #include <math.h> int main() { float alturap, arestex, area, raiz, volume, pot; scanf("%f %f",&alturap,&arestex); pot=pow(arestex,2); raiz=sqrt(3); area=((3*pot*raiz)/2); volume=((area*alturap)/3); printf("O VOLUME DA PIRAMIDE E = %0.2f METROS CUBICOS\n",volume); return 0; }
the_stack_data/390957.c
#include <nl_types.h> #include <errno.h> nl_catd catopen (const char *name, int oflag) { errno = EOPNOTSUPP; return (nl_catd)-1; }
the_stack_data/220456619.c
#include <stdio.h> int main() { int n; scanf("%d", &n); if(n <= 2 || n % 2 == 1) { printf("NIEPOPRAWNA LICZBA"); return 1; } int licznik = 0; int p,q = 2; for(q = 2 ; q <= n ; q++) { int j = 2; for(j = 2; j * j <= q; j++) //czy q nie pierwsza { if(q%j == 0) { j = 2; break; } } if(j != 2 || q == 2 || q == 3) //czy q jest pierwsza { p = n - q; if(p <= q) { int i = 2; for( i = 2; i * i <= p; i++) { if(p%i == 0) { i = 2; break; } } if(i != 2 || p == 2 || p == 3) { licznik = licznik + 1; } } } } printf("%d", licznik); return 0; }
the_stack_data/170453655.c
/* * shamelessly ripped from http://locklessinc.com/articles/mandelbrot/ * * THANKS A MILLION to the original authors. ;) */ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <err.h> #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xutil.h> /* X11 data */ static Display *dpy; static Window win; static XImage *bitmap; static Atom wmDeleteMessage; static GC gc; static void exit_x11(void) { XDestroyImage(bitmap); XDestroyWindow(dpy, win); XCloseDisplay(dpy); } static void init_x11(int size) { int bytes_per_pixel; /* Attempt to open the display */ dpy = XOpenDisplay(NULL); /* Failure */ if (!dpy) exit(0); unsigned long white = WhitePixel(dpy,DefaultScreen(dpy)); unsigned long black = BlackPixel(dpy,DefaultScreen(dpy)); win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, size, size, 0, black, white); /* We want to be notified when the window appears */ XSelectInput(dpy, win, StructureNotifyMask); /* Make it appear */ XMapWindow(dpy, win); while (1) { XEvent e; XNextEvent(dpy, &e); if (e.type == MapNotify) break; } XTextProperty tp; char name[128] = "Mandelbrot"; char *n = name; Status st = XStringListToTextProperty(&n, 1, &tp); if (st) XSetWMName(dpy, win, &tp); /* Wait for the MapNotify event */ XFlush(dpy); int ii, jj; int depth = DefaultDepth(dpy, DefaultScreen(dpy)); Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy)); int total; /* Determine total bytes needed for image */ ii = 1; jj = (depth - 1) >> 2; while (jj >>= 1) ii <<= 1; /* Pad the scanline to a multiple of 4 bytes */ total = size * ii; total = (total + 3) & ~3; total *= size; bytes_per_pixel = ii; if (bytes_per_pixel != 4) { printf("Need 32bit colour screen!"); } /* Make bitmap */ bitmap = XCreateImage(dpy, visual, depth, ZPixmap, 0, malloc(total), size, size, 32, 0); /* Init GC */ gc = XCreateGC(dpy, win, 0, NULL); XSetForeground(dpy, gc, black); if (bytes_per_pixel != 4) { printf("Need 32bit colour screen!\n"); exit_x11(); exit(0); } XSelectInput(dpy, win, ExposureMask | KeyPressMask | StructureNotifyMask); wmDeleteMessage = XInternAtom(dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(dpy, win, &wmDeleteMessage, 1); } #define MAX_ITER (1 << 14) static unsigned cols[MAX_ITER + 1]; static void init_colours(void) { int i; for (i = 0; i < MAX_ITER; i++) { char r = (rand() & 0xff) * MAX_ITER / (i + MAX_ITER + 1); char g = (rand() & 0xff) * MAX_ITER / (i + MAX_ITER + 1); char b = (rand() & 0xff) * MAX_ITER / (i + MAX_ITER + 1); cols[i] = b + 256 * g + 256 * 256 * r; } cols[MAX_ITER] = 0; } static unsigned mandel_long_double(long double cr, long double ci) { long double zr = cr, zi = ci; long double tmp; unsigned i; for (i = 0; i < MAX_ITER; i++) { tmp = zr * zr - zi * zi + cr; zi *= 2 * zr; zi += ci; zr = tmp; if (zr * zr + zi * zi > 4.0) break; } return i; } /* For each point, evaluate its colour */ static void display_long_double(int size, long double xmin, long double xmax, long double ymin, long double ymax) { int x, y; long double cr, ci; long double xscal = (xmax - xmin) / size; long double yscal = (ymax - ymin) / size; unsigned counts; for (y = 0; y < size; y++) { for (x = 0; x < size; x++) { cr = xmin + x * xscal; ci = ymin + y * yscal; counts = mandel_long_double(cr, ci); ((unsigned *) bitmap->data)[x + y*size] = cols[counts]; } /* Display it line-by-line for speed */ XPutImage(dpy, win, gc, bitmap, 0, y, 0, y, size, 1); } XFlush(dpy); } /* Image size */ #define ASIZE 1000 /* Comment out this for benchmarking */ #define WAIT_EXIT int main(void) { long double xmin = -2; long double xmax = 1.0; long double ymin = -1.5; long double ymax = 1.5; /* Make a window! */ init_x11(ASIZE); init_colours(); display_long_double(ASIZE, xmin, xmax, ymin, ymax); #ifdef WAIT_EXIT while(1) { XEvent event; KeySym key; char text[255]; XNextEvent(dpy, &event); /* Just redraw everything on expose */ if ((event.type == Expose) && !event.xexpose.count) { XPutImage(dpy, win, gc, bitmap, 0, 0, 0, 0, ASIZE, ASIZE); } /* Press 'q' to quit */ if ((event.type == KeyPress) && XLookupString(&event.xkey, text, 255, &key, 0) == 1) { if (text[0] == 'q') break; } /* Or simply close the window */ if ((event.type == ClientMessage) && ((Atom) event.xclient.data.l[0] == wmDeleteMessage)) { break; } } #endif /* Done! */ exit_x11(); return 0; }
the_stack_data/62636543.c
/* LL raised several warnings, ignore them */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #ifdef STM32F0xx #include "stm32f0xx_ll_rcc.c" #elif STM32F1xx #include "stm32f1xx_ll_rcc.c" #elif STM32F2xx #include "stm32f2xx_ll_rcc.c" #elif STM32F3xx #include "stm32f3xx_ll_rcc.c" #elif STM32F4xx #include "stm32f4xx_ll_rcc.c" #elif STM32F7xx #include "stm32f7xx_ll_rcc.c" #elif STM32G0xx #include "stm32g0xx_ll_rcc.c" #elif STM32G4xx #include "stm32g4xx_ll_rcc.c" #elif STM32H7xx #include "stm32h7xx_ll_rcc.c" #elif STM32L0xx #include "stm32l0xx_ll_rcc.c" #elif STM32L1xx #include "stm32l1xx_ll_rcc.c" #elif STM32L4xx #include "stm32l4xx_ll_rcc.c" #elif STM32L5xx #include "stm32l5xx_ll_rcc.c" #elif STM32MP1xx #include "stm32mp1xx_ll_rcc.c" #elif STM32WBxx #include "stm32wbxx_ll_rcc.c" #elif STM32WLxx #include "stm32wlxx_ll_rcc.c" #endif #pragma GCC diagnostic pop
the_stack_data/51238.c
#include <stdio.h> #include <math.h> int main() { int x, y, i, ar[9999]; long long S, T; while (scanf("%d %d", &x, &y) != EOF) { S = 0; T = 0; for (i = x; i <= y; i++) { ar[i] = i; if (ar[i] % 2 == 0) S += pow(ar[i], 2.0); else T += pow(ar[i], 3.0); } printf("%lld %lld\n", S, T); } return 0; }
the_stack_data/117905.c
#include <errno.h> #include <sys/sem.h> int r_semop(int semid, struct sembuf *sops, int nsops) { while (semop(semid, sops, nsops) == -1) if (errno != EINTR) return -1; return 0; }
the_stack_data/89174.c
/* *================================================================================== * Description * * Problems involving the computation of exact values of very large magnitude * and precision are common. For example, the computation of the national debt * is a taxing experience for many computer systems. * * This problem requires that you write a program to compute the exact value of * Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such * that 0 < n <= 25. * * Input * * The input will consist of a set of pairs of values for R and n. The R value * will occupy columns 1 through 6, and the n value will be in columns 8 and 9. * * Output * * The output will consist of one line for each line of input giving the exact * value of R^n. Leading zeros should be suppressed in the output. Insignificant * trailing zeros must not be printed. Don't print the decimal point if the result * is an integer. *================================================================================== */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <stdbool.h> #include <math.h> #include <assert.h> #define SAFE_RELEASE(x) \ do { \ if ((x)) { \ free((x)); \ (x) = 0; \ } \ } while (0) #ifndef max #define max(x, y) ((x) > (y) ? (x) : (y)) #endif typedef unsigned short digit; typedef unsigned long twodigits; typedef struct __big_number_t { size_t num_of_digits; size_t point_shift; // float point shift counting from back to front // (e.g. for 1.01, shift = 2) bool negative; digit digits[1]; } big_number_t; static void bn_print(big_number_t* bn) { if (!bn) return; size_t size = max(bn->num_of_digits, bn->point_shift) + (bn->point_shift ? 1 : 0); char* repr = (char*) malloc(size + 1); if (!repr) return; size_t i = bn->num_of_digits; char* p = repr; if (bn->num_of_digits < bn->point_shift) { *p++ = '.'; size_t num_of_heading_zero = bn->point_shift - bn->num_of_digits; while (num_of_heading_zero-- > 0) *p++ = '0'; while (i > 0) { *p++ = '0' + bn->digits[i - 1]; --i; } } else { while (i > 0) { *p++ = '0' + bn->digits[i - 1]; --i; if (i == bn->point_shift) *p++ = '.'; } } // remove trailing zeros for fraction part if (bn->point_shift) { while (*--p == '0'); if (*p == '.') --p; ++p; } *p = '\0'; printf("%s%s\n", bn->negative ? "-" : "", repr); SAFE_RELEASE(repr); } static big_number_t* create_big_number(size_t size) { if (size <= 0) return 0; big_number_t* bn = (big_number_t*) malloc( sizeof(big_number_t) + sizeof(digit) * (size - 1)); if (!bn) return 0; bn->num_of_digits = size; bn->point_shift = 0; bn->negative = false; memset(bn->digits, 0, sizeof(digit) * size); return bn; } static big_number_t* create_big_number_from_long(long n, size_t shift) { if (n == 0) { return create_big_number(1); } bool negative = (n < 0); n = abs(n); size_t size = (size_t)(floor(log10(n)) + 1); big_number_t* bn = create_big_number(size); if (!bn) return 0; bn->negative = negative; bn->point_shift = shift; digit* p = bn->digits; size_t i = size; while (i > 0) { assert(p < (bn->digits + size)); *p++ = n % 10; n /= 10; --i; } return bn; } static big_number_t* bn_copy(big_number_t* x) { if (!x) return 0; big_number_t* bn = create_big_number(x->num_of_digits); if (!bn) return 0; bn->negative = x->negative; bn->point_shift = x->point_shift; memcpy(bn->digits, x->digits, sizeof(digit) * bn->num_of_digits); return bn; } static bool bn_is_zero(big_number_t* x) { if (!x) return false; return (x->num_of_digits == 1 && x->digits[0] == 0); } static big_number_t* bn_mul(big_number_t* x, big_number_t* y) { if (!x || !y) return 0; if (x->num_of_digits == 0 || y->num_of_digits == 0) return 0; if (bn_is_zero(x) || bn_is_zero(y)) return create_big_number_from_long((long)0, 0); size_t size = x->num_of_digits + y->num_of_digits; big_number_t* z = create_big_number(size); if (!z) return 0; size_t i; for (i = 0; i < x->num_of_digits; ++i) { twodigits carry = 0; twodigits f = x->digits[i]; digit* pz = z->digits + i; digit* py = y->digits; digit* py_end = py + y->num_of_digits; while (py < py_end) { carry += *pz + *py++ * f; *pz++ = (digit)(carry % 10); carry /= 10; } if (carry) { *pz += (digit)(carry); } } // remove heading zeros i = size; while (i > 0 && z->digits[i - 1] == 0) { --i; } if (i != size) { z->num_of_digits = i; } // setting new shift z->point_shift = x->point_shift + y->point_shift; return z; } static big_number_t* bn_pow(big_number_t* base, long power) { if (!base) return 0; if (power == 0) return create_big_number_from_long((long)1, 0); if (power == 1) return bn_copy(base); big_number_t* b = bn_copy(base); big_number_t* r = create_big_number_from_long((long)1, 0); while (power != 0) { if (power & 1) { big_number_t* tmp = bn_mul(r, b); SAFE_RELEASE(r); r = tmp; } big_number_t* tmp = bn_mul(b, b); SAFE_RELEASE(b); b = tmp; power /= 2; } SAFE_RELEASE(b); return r; } static void conv_str_to_decimal(char* str, int* decimal, size_t* shift) { if (!str || !decimal || !shift) return; char* str_decimal = (char*) malloc(strlen(str) + 1); if (!str_decimal) return; memset(str_decimal, 0, strlen(str) + 1); char* c = str; char* p = str_decimal; while (c < (str + strlen(str))) { if (*c == '.') { *shift = strlen(str) - (c - str) - 1; } else { *p++ = *c; } ++c; } *decimal = atoi(str_decimal); SAFE_RELEASE(str_decimal); } static void calc_pow() { char str_base[7] = { '\0' }; int decimal = 0; size_t shift = 0; int power = 0; while (scanf("%s %d", str_base, &power) != EOF) { conv_str_to_decimal(str_base, &decimal, &shift); big_number_t* bn = create_big_number_from_long((long)decimal, shift); big_number_t* exp = bn_pow(bn, power); bn_print(exp); SAFE_RELEASE(bn); SAFE_RELEASE(exp); } } int main() { calc_pow(); return 0; }
the_stack_data/26936.c
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifdef PROFILING_ON #include <types.h> #include <errno.h> #include <irq.h> #include <per_cpu.h> #include <pgtable.h> #include <vmx.h> #include <cpuid.h> #include <vm.h> #include <sprintf.h> #include <logmsg.h> #define ACRN_DBG_PROFILING 5U #define ACRN_ERR_PROFILING 3U #define MAJOR_VERSION 1 #define MINOR_VERSION 0 #define LBR_NUM_REGISTERS 32U #define PERF_OVF_BIT_MASK 0xC0000070000000FULL #define LVT_PERFCTR_BIT_UNMASK 0xFFFEFFFFU #define LVT_PERFCTR_BIT_MASK 0x10000U #define VALID_DEBUGCTL_BIT_MASK 0x1801U static uint64_t sep_collection_switch; static uint64_t socwatch_collection_switch; static bool in_pmu_profiling; static uint32_t profiling_pmi_irq = IRQ_INVALID; extern struct irq_desc irq_desc_array[NR_IRQS]; static void profiling_initialize_vmsw(void) { dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); dev_dbg(ACRN_DBG_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } /* * Configure the PMU's for sep/socwatch profiling. * Initial write of PMU registers. * Walk through the entries and write the value of the register accordingly. * Note: current_group is always set to 0, only 1 group is supported. */ static void profiling_initialize_pmi(void) { uint32_t i, group_id; struct profiling_msr_op *msrop = NULL; struct sep_state *ss = &get_cpu_var(profiling_info.s_state); dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); if (ss == NULL) { dev_dbg(ACRN_ERR_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); return; } group_id = ss->current_pmi_group_id = 0U; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_initial_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_id == MSR_IA32_DEBUGCTL) { ss->guest_debugctl_value = msrop->value; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { msr_write(msrop->msr_id, msrop->value); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRWRITE cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), msrop->msr_id, msrop->value); } } } ss->pmu_state = PMU_SETUP; dev_dbg(ACRN_DBG_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } /* * Enable all the Performance Monitoring Control registers. */ static void profiling_enable_pmu(void) { uint32_t lvt_perf_ctr; uint32_t i; uint32_t group_id; uint32_t size; struct profiling_msr_op *msrop = NULL; struct sep_state *ss = &get_cpu_var(profiling_info.s_state); dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); if (ss == NULL) { dev_dbg(ACRN_ERR_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); return; } /* Unmask LAPIC LVT entry for PMC register */ lvt_perf_ctr = (uint32_t) msr_read(MSR_IA32_EXT_APIC_LVT_PMI); dev_dbg(ACRN_DBG_PROFILING, "%s: 0x%x, 0x%lx", __func__, MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); lvt_perf_ctr &= LVT_PERFCTR_BIT_UNMASK; msr_write(MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); dev_dbg(ACRN_DBG_PROFILING, "%s: 0x%x, 0x%lx", __func__, MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); if (ss->guest_debugctl_value != 0U) { /* Merge the msr vmexit loading list with HV */ if (ss->vmexit_msr_cnt == 0U) { struct acrn_vcpu *vcpu = get_ever_run_vcpu(get_pcpu_id()); size = sizeof(struct msr_store_entry) * MAX_HV_MSR_LIST_NUM; (void)memcpy_s(ss->vmexit_msr_list, size, vcpu->arch.msr_area.host, size); ss->vmexit_msr_cnt = MAX_HV_MSR_LIST_NUM; ss->vmexit_msr_list[MAX_HV_MSR_LIST_NUM].msr_index = MSR_IA32_DEBUGCTL; ss->vmexit_msr_list[MAX_HV_MSR_LIST_NUM].value = ss->guest_debugctl_value & VALID_DEBUGCTL_BIT_MASK; ss->vmexit_msr_cnt++; exec_vmwrite64(VMX_EXIT_MSR_LOAD_ADDR_FULL, hva2hpa(ss->vmexit_msr_list)); exec_vmwrite32(VMX_EXIT_MSR_LOAD_COUNT, ss->vmexit_msr_cnt); } /* VMCS GUEST field */ ss->saved_debugctl_value = exec_vmread64(VMX_GUEST_IA32_DEBUGCTL_FULL); exec_vmwrite64(VMX_GUEST_IA32_DEBUGCTL_FULL, (ss->guest_debugctl_value & VALID_DEBUGCTL_BIT_MASK)); } group_id = ss->current_pmi_group_id; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_start_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { msr_write(msrop->msr_id, msrop->value); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRWRITE cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), msrop->msr_id, msrop->value); } } } ss->pmu_state = PMU_RUNNING; dev_dbg(ACRN_DBG_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } /* * Disable all Performance Monitoring Control registers */ static void profiling_disable_pmu(void) { uint32_t lvt_perf_ctr; uint32_t i; uint32_t group_id; struct profiling_msr_op *msrop = NULL; struct sep_state *ss = &get_cpu_var(profiling_info.s_state); dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); if (ss != NULL) { if (ss->vmexit_msr_cnt != 0U) { /* Restore the msr exit loading list of HV */ struct acrn_vcpu *vcpu = get_ever_run_vcpu(get_pcpu_id()); exec_vmwrite64(VMX_EXIT_MSR_LOAD_ADDR_FULL, hva2hpa(vcpu->arch.msr_area.host)); exec_vmwrite32(VMX_EXIT_MSR_LOAD_COUNT, MAX_HV_MSR_LIST_NUM); ss->vmexit_msr_cnt = 0U; } group_id = ss->current_pmi_group_id; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_stop_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { msr_write(msrop->msr_id, msrop->value); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRWRITE cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), msrop->msr_id, msrop->value); } } } /* Mask LAPIC LVT entry for PMC register */ lvt_perf_ctr = (uint32_t) msr_read(MSR_IA32_EXT_APIC_LVT_PMI); lvt_perf_ctr |= LVT_PERFCTR_BIT_MASK; msr_write(MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); ss->pmu_state = PMU_SETUP; dev_dbg(ACRN_DBG_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } else { dev_dbg(ACRN_ERR_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } } /* * Writes specified size of data into sbuf */ static int32_t profiling_sbuf_put_variable(struct shared_buf *sbuf, uint8_t *data, uint32_t size) { uint32_t remaining_space, offset, next_tail; void *to; /* * 1. check for null pointers and non-zero size * 2. check if enough room available in the buffer * 2a. if not, drop the sample, increment count of dropped samples, * return * 2b. unless overwrite flag is enabled * 3. Continue if buffer has space for the sample * 4. Copy sample to buffer * 4a. Split variable sample to be copied if the sample is going to * wrap around the buffer * 4b. Otherwise do a simple copy * 5. return number of bytes of data put in buffer */ if ((sbuf == NULL) || (data == NULL)) { return -EINVAL; } if (size == 0U) { return 0; } stac(); if (sbuf->tail >= sbuf->head) { remaining_space = sbuf->size - (sbuf->tail - sbuf->head); } else { remaining_space = sbuf->head - sbuf->tail; } if (size >= remaining_space) { /* Only (remaining_space - 1) can be written to sbuf. * Since if the next_tail equals head, then it is assumed * that buffer is empty, not full */ clac(); return 0; } next_tail = sbuf_next_ptr(sbuf->tail, size, sbuf->size); to = (void *)sbuf + SBUF_HEAD_SIZE + sbuf->tail; if (next_tail < sbuf->tail) { /* wrap-around */ offset = sbuf->size - sbuf->tail; (void)memcpy_s(to, offset, data, offset); /* 2nd part */ to = (void *)sbuf + SBUF_HEAD_SIZE; if ((size - offset) > 0U) { (void)memcpy_s(to, size - offset, data + offset, size - offset); } } else { (void)memcpy_s(to, size, data, size); } sbuf->tail = next_tail; clac(); return (int32_t)size; } /* * Read profiling data and transferred to SOS * Drop transfer of profiling data if sbuf is full/insufficient and log it */ static int32_t profiling_generate_data(int32_t collector, uint32_t type) { uint64_t i; uint32_t remaining_space = 0U; int32_t ret = 0; struct data_header pkt_header; uint64_t payload_size = 0UL; void *payload = NULL; struct shared_buf *sbuf = NULL; struct sep_state *ss = &(get_cpu_var(profiling_info.s_state)); struct sw_msr_op_info *sw_msrop = &(get_cpu_var(profiling_info.sw_msr_info)); uint64_t rflags; spinlock_t *sw_lock = NULL; dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); if (collector == COLLECT_PROFILE_DATA) { sbuf = per_cpu(sbuf, get_pcpu_id())[ACRN_SEP]; if (sbuf == NULL) { ss->samples_dropped++; dev_dbg(ACRN_DBG_PROFILING, "%s: sbuf is NULL exiting cpu%d", __func__, get_pcpu_id()); return 0; } if (ss->pmu_state == PMU_RUNNING) { stac(); if (sbuf->tail >= sbuf->head) { remaining_space = sbuf->size - (sbuf->tail - sbuf->head); } else { remaining_space = sbuf->head - sbuf->tail; } clac(); /* populate the data header */ pkt_header.tsc = rdtsc(); pkt_header.collector_id = collector; pkt_header.cpu_id = get_pcpu_id(); pkt_header.data_type = 1U << type; pkt_header.reserved = MAGIC_NUMBER; switch (type) { case CORE_PMU_SAMPLING: payload_size = CORE_PMU_SAMPLE_SIZE; payload = &get_cpu_var(profiling_info.p_sample); break; case LBR_PMU_SAMPLING: payload_size = CORE_PMU_SAMPLE_SIZE + LBR_PMU_SAMPLE_SIZE; payload = &get_cpu_var(profiling_info.p_sample); break; case VM_SWITCH_TRACING: payload_size = VM_SWITCH_TRACE_SIZE; payload = &get_cpu_var(profiling_info.vm_trace); break; default: pr_err("%s: unknown data type %u on cpu %d", __func__, type, get_pcpu_id()); ret = -1; break; } if (ret == -1) { return 0; } pkt_header.payload_size = payload_size; if ((uint64_t)remaining_space < (DATA_HEADER_SIZE + payload_size)) { ss->samples_dropped++; dev_dbg(ACRN_DBG_PROFILING, "%s: not enough space left in sbuf[%d: %d] exiting cpu%d", __func__, remaining_space, DATA_HEADER_SIZE + payload_size, get_pcpu_id()); return 0; } for (i = 0U; i < (((DATA_HEADER_SIZE - 1U) / SEP_BUF_ENTRY_SIZE) + 1U); i++) { (void)sbuf_put(sbuf, (uint8_t *)&pkt_header + i * SEP_BUF_ENTRY_SIZE); } for (i = 0U; i < (((payload_size - 1U) / SEP_BUF_ENTRY_SIZE) + 1U); i++) { (void)sbuf_put(sbuf, (uint8_t *)payload + i * SEP_BUF_ENTRY_SIZE); } ss->samples_logged++; } } else if (collector == COLLECT_POWER_DATA) { sbuf = per_cpu(sbuf, get_pcpu_id())[ACRN_SOCWATCH]; if (sbuf == NULL) { dev_dbg(ACRN_DBG_PROFILING, "%s: socwatch buffers not initialized?", __func__); return 0; } sw_lock = &(get_cpu_var(profiling_info.sw_lock)); spinlock_irqsave_obtain(sw_lock, &rflags); stac(); if (sbuf->tail >= sbuf->head) { remaining_space = sbuf->size - (sbuf->tail - sbuf->head); } else { remaining_space = sbuf->head - sbuf->tail; } clac(); /* populate the data header */ pkt_header.tsc = rdtsc(); pkt_header.collector_id = collector; pkt_header.cpu_id = get_pcpu_id(); pkt_header.data_type = (uint16_t)type; switch (type) { case SOCWATCH_MSR_OP: dev_dbg(ACRN_DBG_PROFILING, "%s: generating cstate/pstate sample socwatch cpu %d", __func__, sw_msrop->cpu_id); pkt_header.cpu_id = (uint16_t)sw_msrop->cpu_id; pkt_header.data_type = sw_msrop->sample_id; payload_size = ((uint64_t)sw_msrop->valid_entries) * sizeof(uint64_t); payload = &(sw_msrop->core_msr[0]); break; case SOCWATCH_VM_SWITCH_TRACING: dev_dbg(ACRN_DBG_PROFILING, "%s: generating vm-switch sample", __func__); payload_size = VM_SWITCH_TRACE_SIZE; payload = &get_cpu_var(profiling_info.vm_trace); break; default: pr_err("%s: unknown data type %u on cpu %d", __func__, type, get_pcpu_id()); ret = -1; break; } if (ret == -1){ return 0; } pkt_header.payload_size = payload_size; if ((DATA_HEADER_SIZE + payload_size) >= (uint64_t)remaining_space) { pr_err("%s: not enough space in socwatch buffer on cpu %d", __func__, get_pcpu_id()); return 0; } /* copy header */ (void)profiling_sbuf_put_variable(sbuf, (uint8_t *)&pkt_header, (uint32_t)DATA_HEADER_SIZE); /* copy payload */ (void)profiling_sbuf_put_variable(sbuf, (uint8_t *)payload, (uint32_t)payload_size); spinlock_irqrestore_release(sw_lock, rflags); } else { dev_dbg(ACRN_ERR_PROFILING, "%s: Unknown collector type", __func__); return 0; } return 0; } /* * Performs MSR operations - read, write and clear */ static void profiling_handle_msrops(void) { uint32_t i, j; struct profiling_msr_ops_list *my_msr_node = get_cpu_var(profiling_info.msr_node); struct sw_msr_op_info *sw_msrop = &(get_cpu_var(profiling_info.sw_msr_info)); dev_dbg(ACRN_DBG_PROFILING, "%s: entering cpu%d", __func__, get_pcpu_id()); if ((my_msr_node == NULL) || (my_msr_node->msr_op_state != (int32_t)MSR_OP_REQUESTED)) { dev_dbg(ACRN_DBG_PROFILING, "%s: invalid my_msr_node on cpu%d", __func__, get_pcpu_id()); return; } if ((my_msr_node->num_entries == 0U) || (my_msr_node->num_entries >= MAX_MSR_LIST_NUM)) { dev_dbg(ACRN_DBG_PROFILING, "%s: invalid num_entries on cpu%d", __func__, get_pcpu_id()); return; } for (i = 0U; i < my_msr_node->num_entries; i++) { switch (my_msr_node->entries[i].msr_op_type) { case MSR_OP_READ: my_msr_node->entries[i].value = msr_read(my_msr_node->entries[i].msr_id); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRREAD cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), my_msr_node->entries[i].msr_id, my_msr_node->entries[i].value); break; case MSR_OP_READ_CLEAR: my_msr_node->entries[i].value = msr_read(my_msr_node->entries[i].msr_id); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRREADCLEAR cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), my_msr_node->entries[i].msr_id, my_msr_node->entries[i].value); msr_write(my_msr_node->entries[i].msr_id, 0U); break; case MSR_OP_WRITE: msr_write(my_msr_node->entries[i].msr_id, my_msr_node->entries[i].value); dev_dbg(ACRN_DBG_PROFILING, "%s: MSRWRITE cpu%d, msr_id=0x%x, msr_val=0x%lx", __func__, get_pcpu_id(), my_msr_node->entries[i].msr_id, my_msr_node->entries[i].value); break; default: pr_err("%s: unknown MSR op_type %u on cpu %d", __func__, my_msr_node->entries[i].msr_op_type, get_pcpu_id()); break; } } my_msr_node->msr_op_state = (int32_t)MSR_OP_HANDLED; /* Also generates sample */ if ((my_msr_node->collector_id == COLLECT_POWER_DATA) && (sw_msrop != NULL)) { sw_msrop->cpu_id = get_pcpu_id(); sw_msrop->valid_entries = my_msr_node->num_entries; /* * if 'param' is 0, then skip generating a sample since it is * an immediate MSR read operation. */ if (my_msr_node->entries[0].param != 0UL) { for (j = 0U; j < my_msr_node->num_entries; ++j) { sw_msrop->core_msr[j] = my_msr_node->entries[j].value; /* * socwatch uses the 'param' field to store the * sample id needed by socwatch to identify the * type of sample during post-processing */ sw_msrop->sample_id = my_msr_node->entries[j].param; } /* generate sample */ (void)profiling_generate_data(COLLECT_POWER_DATA, SOCWATCH_MSR_OP); } my_msr_node->msr_op_state = (int32_t)MSR_OP_REQUESTED; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); } /* * Interrupt handler for performance monitoring interrupts */ static void profiling_pmi_handler(uint32_t irq, __unused void *data) { uint64_t perf_ovf_status; uint32_t lvt_perf_ctr; uint32_t i; uint32_t group_id; struct profiling_msr_op *msrop = NULL; struct pmu_sample *psample = &(get_cpu_var(profiling_info.p_sample)); struct sep_state *ss = &(get_cpu_var(profiling_info.s_state)); if ((ss == NULL) || (psample == NULL)) { dev_dbg(ACRN_ERR_PROFILING, "%s: exiting cpu%d", __func__, get_pcpu_id()); return; } /* Stop all the counters first */ msr_write(MSR_IA32_PERF_GLOBAL_CTRL, 0x0U); group_id = ss->current_pmi_group_id; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_entry_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { msr_write(msrop->msr_id, msrop->value); } } } ss->total_pmi_count++; perf_ovf_status = msr_read(MSR_IA32_PERF_GLOBAL_STATUS); lvt_perf_ctr = (uint32_t)msr_read(MSR_IA32_EXT_APIC_LVT_PMI); if (perf_ovf_status == 0U) { goto reconfig; } if ((perf_ovf_status & 0x80000000000000FULL) == 0U) { ss->nofrozen_pmi++; } (void)memset(psample, 0U, sizeof(struct pmu_sample)); /* Attribute PMI to guest context */ if ((get_cpu_var(profiling_info.vm_info).vmexit_reason == VMX_EXIT_REASON_EXTERNAL_INTERRUPT) && ((uint64_t)get_cpu_var(profiling_info.vm_info).external_vector == VECTOR_PMI)) { psample->csample.os_id = get_cpu_var(profiling_info.vm_info).guest_vm_id; (void)memset(psample->csample.task, 0U, 16); psample->csample.cpu_id = get_pcpu_id(); psample->csample.process_id = 0U; psample->csample.task_id = 0U; psample->csample.overflow_status = perf_ovf_status; psample->csample.rip = get_cpu_var(profiling_info.vm_info).guest_rip; psample->csample.rflags = (uint32_t)get_cpu_var(profiling_info.vm_info).guest_rflags; psample->csample.cs = (uint32_t)get_cpu_var(profiling_info.vm_info).guest_cs; get_cpu_var(profiling_info.vm_info).vmexit_reason = 0U; get_cpu_var(profiling_info.vm_info).external_vector = -1; /* Attribute PMI to hypervisor context */ } else { psample->csample.os_id = 0xFFFFU; (void)memcpy_s(psample->csample.task, 16, "VMM\0", 4); psample->csample.cpu_id = get_pcpu_id(); psample->csample.process_id = 0U; psample->csample.task_id = 0U; psample->csample.overflow_status = perf_ovf_status; psample->csample.rip = irq_desc_array[irq].ctx_rip; psample->csample.rflags = (uint32_t)irq_desc_array[irq].ctx_rflags; psample->csample.cs = (uint32_t)irq_desc_array[irq].ctx_cs; } if ((sep_collection_switch & (1UL << (uint64_t)LBR_PMU_SAMPLING)) > 0UL) { psample->lsample.lbr_tos = msr_read(MSR_CORE_LASTBRANCH_TOS); for (i = 0U; i < LBR_NUM_REGISTERS; i++) { psample->lsample.lbr_from_ip[i] = msr_read(MSR_CORE_LASTBRANCH_0_FROM_IP + i); psample->lsample.lbr_to_ip[i] = msr_read(MSR_CORE_LASTBRANCH_0_TO_IP + i); } /* Generate core pmu sample and lbr data */ (void)profiling_generate_data(COLLECT_PROFILE_DATA, LBR_PMU_SAMPLING); } else { /* Generate core pmu sample only */ (void)profiling_generate_data(COLLECT_PROFILE_DATA, CORE_PMU_SAMPLING); } /* Clear PERF_GLOBAL_OVF_STATUS bits */ msr_write(MSR_IA32_PERF_GLOBAL_OVF_CTRL, perf_ovf_status & PERF_OVF_BIT_MASK); ss->valid_pmi_count++; group_id = ss->current_pmi_group_id; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_exit_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { if (msrop->reg_type != (uint8_t)PMU_MSR_DATA) { if (msrop->msr_id != MSR_IA32_PERF_GLOBAL_CTRL) { msr_write(msrop->msr_id, msrop->value); } } else { if (((perf_ovf_status >> msrop->param) & 0x1U) > 0U) { msr_write(msrop->msr_id, msrop->value); } } } } } reconfig: if (ss->pmu_state == PMU_RUNNING) { /* Unmask the interrupt */ lvt_perf_ctr &= LVT_PERFCTR_BIT_UNMASK; msr_write(MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); group_id = ss->current_pmi_group_id; for (i = 0U; i < MAX_MSR_LIST_NUM; i++) { msrop = &(ss->pmi_start_msr_list[group_id][i]); if (msrop != NULL) { if (msrop->msr_id == (uint32_t)-1) { break; } if (msrop->msr_op_type == (uint8_t)MSR_OP_WRITE) { msr_write(msrop->msr_id, msrop->value); } } } } else { /* Mask the interrupt */ lvt_perf_ctr |= LVT_PERFCTR_BIT_MASK; msr_write(MSR_IA32_EXT_APIC_LVT_PMI, lvt_perf_ctr); } } /* * Initialize sep state and enable PMU counters */ static void profiling_start_pmu(void) { uint16_t i; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (in_pmu_profiling) { return; } for (i = 0U; i < pcpu_nums; i++) { if (per_cpu(profiling_info.s_state, i).pmu_state != PMU_SETUP) { pr_err("%s: invalid pmu_state %u on cpu%d", __func__, get_cpu_var(profiling_info.s_state).pmu_state, i); return; } } for (i = 0U; i < pcpu_nums; i++) { per_cpu(profiling_info.ipi_cmd, i) = IPI_PMU_START; per_cpu(profiling_info.s_state, i).samples_logged = 0U; per_cpu(profiling_info.s_state, i).samples_dropped = 0U; per_cpu(profiling_info.s_state, i).valid_pmi_count = 0U; per_cpu(profiling_info.s_state, i).total_pmi_count = 0U; per_cpu(profiling_info.s_state, i).total_vmexit_count = 0U; per_cpu(profiling_info.s_state, i).frozen_well = 0U; per_cpu(profiling_info.s_state, i).frozen_delayed = 0U; per_cpu(profiling_info.s_state, i).nofrozen_pmi = 0U; per_cpu(profiling_info.s_state, i).pmu_state = PMU_RUNNING; } smp_call_function(get_active_pcpu_bitmap(), profiling_ipi_handler, NULL); in_pmu_profiling = true; dev_dbg(ACRN_DBG_PROFILING, "%s: done", __func__); } /* * Reset sep state and Disable all the PMU counters */ static void profiling_stop_pmu(void) { uint16_t i; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (in_pmu_profiling) { for (i = 0U; i < pcpu_nums; i++) { per_cpu(profiling_info.ipi_cmd, i) = IPI_PMU_STOP; if (per_cpu(profiling_info.s_state, i).pmu_state == PMU_RUNNING) { per_cpu(profiling_info.s_state, i).pmu_state = PMU_SETUP; } dev_dbg(ACRN_DBG_PROFILING, "%s: pmi_cnt[%d] = total:%u valid=%u, vmexit_cnt=%u", __func__, i, per_cpu(profiling_info.s_state, i).total_pmi_count, per_cpu(profiling_info.s_state, i).valid_pmi_count, per_cpu(profiling_info.s_state, i).total_vmexit_count); dev_dbg(ACRN_DBG_PROFILING, "%s: cpu%d frozen well:%u frozen delayed=%u, nofrozen_pmi=%u", __func__, i, per_cpu(profiling_info.s_state, i).frozen_well, per_cpu(profiling_info.s_state, i).frozen_delayed, per_cpu(profiling_info.s_state, i).nofrozen_pmi); dev_dbg(ACRN_DBG_PROFILING, "%s: cpu%d samples captured:%u samples dropped=%u", __func__, i, per_cpu(profiling_info.s_state, i).samples_logged, per_cpu(profiling_info.s_state, i).samples_dropped); } smp_call_function(get_active_pcpu_bitmap(), profiling_ipi_handler, NULL); in_pmu_profiling = false; dev_dbg(ACRN_DBG_PROFILING, "%s: done.", __func__); } } /* * Performs MSR operations on all the CPU's */ int32_t profiling_msr_ops_all_cpus(struct acrn_vm *vm, uint64_t addr) { uint16_t i; struct profiling_msr_ops_list msr_list[MAX_PCPU_NUM]; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &msr_list, addr, (uint32_t)pcpu_nums * sizeof(struct profiling_msr_ops_list)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } for (i = 0U; i < pcpu_nums; i++) { per_cpu(profiling_info.ipi_cmd, i) = IPI_MSR_OP; per_cpu(profiling_info.msr_node, i) = &(msr_list[i]); } smp_call_function(get_active_pcpu_bitmap(), profiling_ipi_handler, NULL); if (copy_to_gpa(vm, &msr_list, addr, sizeof(msr_list)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Generate VM info list */ int32_t profiling_vm_list_info(struct acrn_vm *vm, uint64_t addr) { struct acrn_vm *tmp_vm; struct acrn_vcpu *vcpu; int32_t vm_idx; uint16_t i, j; struct profiling_vm_info_list vm_info_list; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &vm_info_list, addr, sizeof(vm_info_list)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } vm_idx = 0; vm_info_list.vm_list[vm_idx].vm_id_num = -1; (void)memcpy_s((void *)vm_info_list.vm_list[vm_idx].vm_name, 4U, "VMM\0", 4U); for (i = 0U; i < pcpu_nums; i++) { vm_info_list.vm_list[vm_idx].cpu_map[i].vcpu_id = i; vm_info_list.vm_list[vm_idx].cpu_map[i].pcpu_id = i; vm_info_list.vm_list[vm_idx].cpu_map[i].apic_id = per_cpu(lapic_id, i); } vm_info_list.vm_list[vm_idx].num_vcpus = i; vm_info_list.num_vms = 1; for (j = 0U; j < CONFIG_MAX_VM_NUM; j++) { tmp_vm = get_vm_from_vmid(j); if (is_poweroff_vm(tmp_vm)) { break; } vm_info_list.num_vms++; vm_idx++; vm_info_list.vm_list[vm_idx].vm_id_num = tmp_vm->vm_id; (void)memcpy_s((void *)vm_info_list.vm_list[vm_idx].uuid, 16U, tmp_vm->uuid, 16U); snprintf(vm_info_list.vm_list[vm_idx].vm_name, 16U, "vm_%d", tmp_vm->vm_id, 16U); vm_info_list.vm_list[vm_idx].num_vcpus = 0; i = 0U; foreach_vcpu(i, tmp_vm, vcpu) { vm_info_list.vm_list[vm_idx].cpu_map[i].vcpu_id = vcpu->vcpu_id; vm_info_list.vm_list[vm_idx].cpu_map[i].pcpu_id = pcpuid_from_vcpu(vcpu); vm_info_list.vm_list[vm_idx].cpu_map[i].apic_id = 0; vm_info_list.vm_list[vm_idx].num_vcpus++; } } if (copy_to_gpa(vm, &vm_info_list, addr, sizeof(vm_info_list)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Sep/socwatch profiling version */ int32_t profiling_get_version_info(struct acrn_vm *vm, uint64_t addr) { struct profiling_version_info ver_info; dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &ver_info, addr, sizeof(ver_info)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } ver_info.major = MAJOR_VERSION; ver_info.minor = MINOR_VERSION; ver_info.supported_features = (int64_t) ((1U << (uint64_t)CORE_PMU_SAMPLING) | (1U << (uint64_t)CORE_PMU_COUNTING) | (1U << (uint64_t)LBR_PMU_SAMPLING) | (1U << (uint64_t)VM_SWITCH_TRACING)); if (copy_to_gpa(vm, &ver_info, addr, sizeof(ver_info)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Gets type of profiling - sep/socwatch */ int32_t profiling_get_control(struct acrn_vm *vm, uint64_t addr) { struct profiling_control prof_control; dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &prof_control, addr, sizeof(prof_control)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } switch (prof_control.collector_id) { case COLLECT_PROFILE_DATA: prof_control.switches = sep_collection_switch; break; case COLLECT_POWER_DATA: break; default: pr_err("%s: unknown collector %d", __func__, prof_control.collector_id); break; } if (copy_to_gpa(vm, &prof_control, addr, sizeof(prof_control)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Update the profiling type based on control switch */ int32_t profiling_set_control(struct acrn_vm *vm, uint64_t addr) { uint64_t old_switch; uint64_t new_switch; uint16_t i; uint16_t pcpu_nums = get_pcpu_nums(); struct profiling_control prof_control; dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &prof_control, addr, sizeof(prof_control)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } switch (prof_control.collector_id) { case COLLECT_PROFILE_DATA: old_switch = sep_collection_switch; new_switch = prof_control.switches; sep_collection_switch = prof_control.switches; dev_dbg(ACRN_DBG_PROFILING, " old_switch: %lu sep_collection_switch: %lu!", old_switch, sep_collection_switch); for (i = 0U; i < (uint16_t)MAX_SEP_FEATURE_ID; i++) { if (((new_switch ^ old_switch) & (0x1UL << i)) != 0UL) { switch (i) { case CORE_PMU_SAMPLING: case CORE_PMU_COUNTING: if ((new_switch & (0x1UL << i)) != 0UL) { profiling_start_pmu(); } else { profiling_stop_pmu(); } break; case LBR_PMU_SAMPLING: break; case VM_SWITCH_TRACING: break; default: dev_dbg(ACRN_DBG_PROFILING, "%s: feature not supported %u", __func__, i); break; } } } break; case COLLECT_POWER_DATA: dev_dbg(ACRN_DBG_PROFILING, "%s: configuring socwatch", __func__); socwatch_collection_switch = prof_control.switches; dev_dbg(ACRN_DBG_PROFILING, "socwatch_collection_switch: %lu!", socwatch_collection_switch); if (socwatch_collection_switch != 0UL) { dev_dbg(ACRN_DBG_PROFILING, "%s: socwatch start collection invoked!", __func__); for (i = 0U; i < (uint16_t)MAX_SOCWATCH_FEATURE_ID; i++) { if ((socwatch_collection_switch & (0x1UL << i)) != 0UL) { switch (i) { case SOCWATCH_COMMAND: break; case SOCWATCH_VM_SWITCH_TRACING: dev_dbg(ACRN_DBG_PROFILING, "%s: socwatch vm-switch feature requested!", __func__); break; default: dev_dbg(ACRN_DBG_PROFILING, "%s: socwatch feature not supported %u", __func__, i); break; } } } for (i = 0U; i < pcpu_nums ; i++) { per_cpu(profiling_info.soc_state, i) = SW_RUNNING; } } else { /* stop socwatch collection */ dev_dbg(ACRN_DBG_PROFILING, "%s: socwatch stop collection invoked or collection switch not set!", __func__); for (i = 0U; i < pcpu_nums ; i++) { per_cpu(profiling_info.soc_state, i) = SW_STOPPED; } } break; default: pr_err("%s: unknown collector %d", __func__, prof_control.collector_id); break; } if (copy_to_gpa(vm, &prof_control, addr, sizeof(prof_control)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Configure PMI on all cpus */ int32_t profiling_configure_pmi(struct acrn_vm *vm, uint64_t addr) { uint16_t i; struct profiling_pmi_config pmi_config; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &pmi_config, addr, sizeof(pmi_config)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } for (i = 0U; i < pcpu_nums; i++) { if (!((per_cpu(profiling_info.s_state, i).pmu_state == PMU_INITIALIZED) || (per_cpu(profiling_info.s_state, i).pmu_state == PMU_SETUP))) { pr_err("%s: invalid pmu_state %u on cpu%d", __func__, per_cpu(profiling_info.s_state, i).pmu_state, i); return -EINVAL; } } if (pmi_config.num_groups == 0U || pmi_config.num_groups > MAX_GROUP_NUM) { pr_err("%s: invalid num_groups %u", __func__, pmi_config.num_groups); return -EINVAL; } for (i = 0U; i < pcpu_nums; i++) { per_cpu(profiling_info.ipi_cmd, i) = IPI_PMU_CONFIG; per_cpu(profiling_info.s_state, i).num_pmi_groups = pmi_config.num_groups; (void)memcpy_s((void *)per_cpu(profiling_info.s_state, i).pmi_initial_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM, (void *)pmi_config.initial_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM); (void)memcpy_s((void *)per_cpu(profiling_info.s_state, i).pmi_start_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM, (void *)pmi_config.start_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM); (void)memcpy_s((void *)per_cpu(profiling_info.s_state, i).pmi_stop_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM, (void *)pmi_config.stop_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM); (void)memcpy_s((void *)per_cpu(profiling_info.s_state, i).pmi_entry_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM, (void *)pmi_config.entry_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM); (void)memcpy_s((void *)per_cpu(profiling_info.s_state, i).pmi_exit_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM, (void *)pmi_config.exit_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM*MAX_GROUP_NUM); } smp_call_function(get_active_pcpu_bitmap(), profiling_ipi_handler, NULL); if (copy_to_gpa(vm, &pmi_config, addr, sizeof(pmi_config)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Configure for VM-switch data on all cpus */ int32_t profiling_configure_vmsw(struct acrn_vm *vm, uint64_t addr) { uint16_t i; int32_t ret = 0; struct profiling_vmsw_config vmsw_config; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &vmsw_config, addr, sizeof(vmsw_config)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } switch (vmsw_config.collector_id) { case COLLECT_PROFILE_DATA: for (i = 0U; i < pcpu_nums; i++) { per_cpu(profiling_info.ipi_cmd, i) = IPI_VMSW_CONFIG; (void)memcpy_s( (void *)per_cpu(profiling_info.s_state, i).vmsw_initial_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM, (void *)vmsw_config.initial_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM); (void)memcpy_s( (void *)per_cpu(profiling_info.s_state, i).vmsw_entry_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM, (void *)vmsw_config.entry_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM); (void)memcpy_s( (void *)per_cpu(profiling_info.s_state, i).vmsw_exit_msr_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM, (void *)vmsw_config.exit_list, sizeof(struct profiling_msr_op)*MAX_MSR_LIST_NUM); } smp_call_function(get_active_pcpu_bitmap(), profiling_ipi_handler, NULL); break; case COLLECT_POWER_DATA: break; default: pr_err("%s: unknown collector %d", __func__, vmsw_config.collector_id); ret = -EINVAL; break; } if (copy_to_gpa(vm, &vmsw_config, addr, sizeof(vmsw_config)) != 0) { pr_err("%s: Unable to copy addr to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return ret; } /* * Get the physical cpu id */ int32_t profiling_get_pcpu_id(struct acrn_vm *vm, uint64_t addr) { struct profiling_pcpuid pcpuid; dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &pcpuid, addr, sizeof(pcpuid)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } cpuid_subleaf(pcpuid.leaf, pcpuid.subleaf, &pcpuid.eax, &pcpuid.ebx, &pcpuid.ecx, &pcpuid.edx); if (copy_to_gpa(vm, &pcpuid, addr, sizeof(pcpuid)) != 0) { pr_err("%s: Unable to copy param to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * Update collection statictics */ int32_t profiling_get_status_info(struct acrn_vm *vm, uint64_t gpa) { uint16_t i; struct profiling_status pstats[MAX_PCPU_NUM]; uint16_t pcpu_nums = get_pcpu_nums(); dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); if (copy_from_gpa(vm, &pstats, gpa, pcpu_nums*sizeof(struct profiling_status)) != 0) { pr_err("%s: Unable to copy addr from vm\n", __func__); return -EINVAL; } for (i = 0U; i < pcpu_nums; i++) { pstats[i].samples_logged = per_cpu(profiling_info.s_state, i).samples_logged; pstats[i].samples_dropped = per_cpu(profiling_info.s_state, i).samples_dropped; } if (copy_to_gpa(vm, &pstats, gpa, pcpu_nums*sizeof(struct profiling_status)) != 0) { pr_err("%s: Unable to copy param to vm\n", __func__); return -EINVAL; } dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); return 0; } /* * IPI interrupt handler function */ void profiling_ipi_handler(__unused void *data) { switch (get_cpu_var(profiling_info.ipi_cmd)) { case IPI_PMU_START: profiling_enable_pmu(); break; case IPI_PMU_STOP: profiling_disable_pmu(); break; case IPI_MSR_OP: profiling_handle_msrops(); break; case IPI_PMU_CONFIG: profiling_initialize_pmi(); break; case IPI_VMSW_CONFIG: profiling_initialize_vmsw(); break; default: pr_err("%s: unknown IPI command %d on cpu %d", __func__, get_cpu_var(profiling_info.ipi_cmd), get_pcpu_id()); break; } get_cpu_var(profiling_info.ipi_cmd) = IPI_UNKNOWN; } /* * Save the VCPU info on vmenter */ void profiling_vmenter_handler(__unused struct acrn_vcpu *vcpu) { if (((get_cpu_var(profiling_info.s_state).pmu_state == PMU_RUNNING) && ((sep_collection_switch & (1UL << (uint64_t)VM_SWITCH_TRACING)) > 0UL)) || ((get_cpu_var(profiling_info.soc_state) == SW_RUNNING) && ((socwatch_collection_switch & (1UL << (uint64_t)SOCWATCH_VM_SWITCH_TRACING)) > 0UL))) { get_cpu_var(profiling_info.vm_info).vmenter_tsc = rdtsc(); } } /* * Save the VCPU info on vmexit */ void profiling_pre_vmexit_handler(struct acrn_vcpu *vcpu) { uint64_t exit_reason = 0UL; exit_reason = vcpu->arch.exit_reason & 0xFFFFUL; if ((get_cpu_var(profiling_info.s_state).pmu_state == PMU_RUNNING) || (get_cpu_var(profiling_info.soc_state) == SW_RUNNING)) { get_cpu_var(profiling_info.vm_info).vmexit_tsc = rdtsc(); get_cpu_var(profiling_info.vm_info).vmexit_reason = exit_reason; if (exit_reason == VMX_EXIT_REASON_EXTERNAL_INTERRUPT) { get_cpu_var(profiling_info.vm_info).external_vector = (int32_t)(exec_vmread(VMX_EXIT_INT_INFO) & 0xFFUL); } else { get_cpu_var(profiling_info.vm_info).external_vector = -1; } get_cpu_var(profiling_info.vm_info).guest_rip = vcpu_get_rip(vcpu); get_cpu_var(profiling_info.vm_info).guest_rflags = vcpu_get_rflags(vcpu); get_cpu_var(profiling_info.vm_info).guest_cs = exec_vmread64(VMX_GUEST_CS_SEL); get_cpu_var(profiling_info.vm_info).guest_vm_id = (int16_t)vcpu->vm->vm_id; } } /* * Generate vmexit data */ void profiling_post_vmexit_handler(struct acrn_vcpu *vcpu) { per_cpu(profiling_info.s_state, pcpuid_from_vcpu(vcpu)).total_vmexit_count++; if ((get_cpu_var(profiling_info.s_state).pmu_state == PMU_RUNNING) || (get_cpu_var(profiling_info.soc_state) == SW_RUNNING)) { /* Generate vmswitch sample */ if (((sep_collection_switch & (1UL << (uint64_t)VM_SWITCH_TRACING)) > 0UL) || ((socwatch_collection_switch & (1UL << (uint64_t)SOCWATCH_VM_SWITCH_TRACING)) > 0UL)) { get_cpu_var(profiling_info.vm_trace).os_id = vcpu->vm->vm_id; get_cpu_var(profiling_info.vm_trace).vm_enter_tsc = get_cpu_var(profiling_info.vm_info).vmenter_tsc; get_cpu_var(profiling_info.vm_trace).vm_exit_tsc = get_cpu_var(profiling_info.vm_info).vmexit_tsc; get_cpu_var(profiling_info.vm_trace).vm_exit_reason = get_cpu_var(profiling_info.vm_info).vmexit_reason; if ((sep_collection_switch & (1UL << (uint64_t)VM_SWITCH_TRACING)) > 0UL) { (void)profiling_generate_data(COLLECT_PROFILE_DATA, VM_SWITCH_TRACING); } if ((socwatch_collection_switch & (1UL << (uint64_t)SOCWATCH_VM_SWITCH_TRACING)) > 0UL) { (void)profiling_generate_data(COLLECT_POWER_DATA, SOCWATCH_VM_SWITCH_TRACING); } } } } /* * Setup PMI irq vector */ void profiling_setup(void) { uint16_t cpu; int32_t retval; dev_dbg(ACRN_DBG_PROFILING, "%s: entering", __func__); cpu = get_pcpu_id(); /* support PMI notification, SOS_VM will register all CPU */ if ((cpu == BOOT_CPU_ID) && (profiling_pmi_irq == IRQ_INVALID)) { pr_info("%s: calling request_irq", __func__); retval = request_irq(PMI_IRQ, profiling_pmi_handler, NULL, IRQF_NONE); if (retval < 0) { pr_err("Failed to add PMI isr"); return; } profiling_pmi_irq = (uint32_t)retval; } per_cpu(profiling_info.s_state, cpu).valid_pmi_count = 0U; per_cpu(profiling_info.s_state, cpu).total_pmi_count = 0U; per_cpu(profiling_info.s_state, cpu).total_vmexit_count = 0U; per_cpu(profiling_info.s_state, cpu).pmu_state = PMU_INITIALIZED; per_cpu(profiling_info.s_state, cpu).vmexit_msr_cnt = 0U; per_cpu(profiling_info.s_state, cpu).samples_logged = 0U; per_cpu(profiling_info.s_state, cpu).samples_dropped = 0U; per_cpu(profiling_info.s_state, cpu).frozen_well = 0U; per_cpu(profiling_info.s_state, cpu).frozen_delayed = 0U; per_cpu(profiling_info.s_state, cpu).nofrozen_pmi = 0U; msr_write(MSR_IA32_EXT_APIC_LVT_PMI, VECTOR_PMI | LVT_PERFCTR_BIT_MASK); dev_dbg(ACRN_DBG_PROFILING, "%s: exiting", __func__); } #endif
the_stack_data/61074132.c
#include <stdlib.h> #include <pthread.h> _Bool set_done; int *ptr; void *set_x(void *arg) { *(int *)arg = 10; set_done = 1; } int main(int argc, char *argv[]) { __CPROVER_assume(argc >= sizeof(int)); ptr = malloc(argc); __CPROVER_ASYNC_1: set_x(ptr); __CPROVER_assume(set_done); assert(*ptr == 10); return 0; }
the_stack_data/320059.c
/* * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This software was developed by the Computer Systems Engineering group * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and * contributed to Berkeley. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Lawrence Berkeley Laboratories. * * %sccs.include.redist.c% * * @(#)kgdb_stub.c 8.4 (Berkeley) 01/12/94 */ /* * "Stub" to allow remote cpu to debug over a serial line using gdb. */ #ifdef KGDB #ifndef lint static char rcsid[] = "$Header: /usr/src/sys/hp300/hp300/RCS/kgdb_stub.c,v 1.5 92/12/20 15:49:01 mike Exp $"; #endif #include <sys/param.h> #include <sys/systm.h> #include <machine/trap.h> #include <machine/cpu.h> #include <machine/psl.h> #include <machine/reg.h> #include <machine/frame.h> #include <sys/buf.h> #include <hp/dev/cons.h> #include <hp300/hp300/kgdb_proto.h> #include <machine/remote-sl.h> extern int kernacc(); extern void chgkprot(); #ifndef KGDBDEV #define KGDBDEV NODEV #endif #ifndef KGDBRATE #define KGDBRATE 9600 #endif dev_t kgdb_dev = KGDBDEV; /* remote debugging device (NODEV if none) */ int kgdb_rate = KGDBRATE; /* remote debugging baud rate */ int kgdb_active = 0; /* remote debugging active if != 0 */ int kgdb_debug_init = 0; /* != 0 waits for remote at system init */ int kgdb_debug_panic = 1; /* != 0 waits for remote on panic */ int kgdb_debug = 0; #define GETC ((*kgdb_getc)(kgdb_dev)) #define PUTC(c) ((*kgdb_putc)(kgdb_dev, c)) #define PUTESC(c) { \ if (c == FRAME_END) { \ PUTC(FRAME_ESCAPE); \ c = TRANS_FRAME_END; \ } else if (c == FRAME_ESCAPE) { \ PUTC(FRAME_ESCAPE); \ c = TRANS_FRAME_ESCAPE; \ } else if (c == FRAME_START) { \ PUTC(FRAME_ESCAPE); \ c = TRANS_FRAME_START; \ } \ PUTC(c); \ } static int (*kgdb_getc)(); static int (*kgdb_putc)(); /* * Send a message. The host gets one chance to read it. */ static void kgdb_send(type, bp, len) register u_char type; register u_char *bp; register int len; { register u_char csum; register u_char *ep = bp + len; PUTC(FRAME_START); PUTESC(type); csum = type; while (bp < ep) { type = *bp++; csum += type; PUTESC(type) } csum = -csum; PUTESC(csum) PUTC(FRAME_END); } static int kgdb_recv(bp, lenp) u_char *bp; int *lenp; { register u_char c, csum; register int escape, len; register int type; restart: csum = len = escape = 0; type = -1; while (1) { c = GETC; switch (c) { case FRAME_ESCAPE: escape = 1; continue; case TRANS_FRAME_ESCAPE: if (escape) c = FRAME_ESCAPE; break; case TRANS_FRAME_END: if (escape) c = FRAME_END; break; case TRANS_FRAME_START: if (escape) c = FRAME_START; break; case FRAME_START: goto restart; case FRAME_END: if (type < 0 || --len < 0) { csum = len = escape = 0; type = -1; continue; } if (csum != 0) { return (0); } *lenp = len; return type; } csum += c; if (type < 0) { type = c; escape = 0; continue; } if (++len > SL_RPCSIZE) { while (GETC != FRAME_END) ; return (0); } *bp++ = c; escape = 0; } } /* * Translate a trap number into a unix compatible signal value. * (gdb only understands unix signal numbers). */ static int computeSignal(type) int type; { int sigval; switch (type) { case T_BUSERR: sigval = SIGBUS; break; case T_ADDRERR: sigval = SIGBUS; break; case T_ILLINST: sigval = SIGILL; break; case T_ZERODIV: sigval = SIGFPE; break; case T_CHKINST: sigval = SIGFPE; break; case T_TRAPVINST: sigval = SIGFPE; break; case T_PRIVINST: sigval = SIGILL; break; case T_TRACE: sigval = SIGTRAP; break; case T_MMUFLT: sigval = SIGSEGV; break; case T_SSIR: sigval = SIGSEGV; break; case T_FMTERR: sigval = SIGILL; break; case T_FPERR: sigval = SIGFPE; break; case T_COPERR: sigval = SIGFPE; break; case T_ASTFLT: sigval = SIGINT; break; case T_TRAP15: sigval = SIGTRAP; break; default: sigval = SIGEMT; break; } return (sigval); } /* * Trap into kgdb to wait for debugger to connect, * noting on the console why nothing else is going on. */ kgdb_connect(verbose) int verbose; { if (verbose) printf("kgdb waiting..."); /* trap into kgdb */ asm("trap #15;"); if (verbose) printf("connected.\n"); } /* * Decide what to do on panic. */ kgdb_panic() { if (kgdb_active == 0 && kgdb_debug_panic && kgdb_dev != NODEV) kgdb_connect(1); } /* * Definitions exported from gdb. */ #define NUM_REGS 18 #define REGISTER_BYTES ((16+2)*4) #define REGISTER_BYTE(N) ((N)*4) #define GDB_SR 16 #define GDB_PC 17 static inline void kgdb_copy(src, dst, nbytes) register u_char *src, *dst; register u_int nbytes; { register u_char *ep = src + nbytes; while (src < ep) *dst++ = *src++; } /* * There is a short pad word between SP (A7) and SR which keeps the * kernel stack long word aligned (note that this is in addition to * the stack adjust short that we treat as the upper half of a longword * SR). We must skip this when copying into and out of gdb. */ static inline void regs_to_gdb(fp, regs) struct frame *fp; u_long *regs; { kgdb_copy((u_char *)fp->f_regs, (u_char *)regs, 16*4); kgdb_copy((u_char *)&fp->f_stackadj, (u_char *)&regs[GDB_SR], 2*4); } static inline void gdb_to_regs(fp, regs) struct frame *fp; u_long *regs; { kgdb_copy((u_char *)regs, (u_char *)fp->f_regs, 16*4); kgdb_copy((u_char *)&regs[GDB_SR], (u_char *)&fp->f_stackadj, 2*4); } static u_long reg_cache[NUM_REGS]; static u_char inbuffer[SL_RPCSIZE+1]; static u_char outbuffer[SL_RPCSIZE]; /* * This function does all command procesing for interfacing to * a remote gdb. */ int kgdb_trap(type, frame) int type; struct frame *frame; { register u_long len; u_char *addr; register u_char *cp; register u_char out, in; register int outlen; int inlen; u_long gdb_regs[NUM_REGS]; if ((int)kgdb_dev < 0) { /* not debugging */ return (0); } if (kgdb_active == 0) { if (type != T_TRAP15) { /* No debugger active -- let trap handle this. */ return (0); } kgdb_getc = 0; for (inlen = 0; constab[inlen].cn_probe; inlen++) if (major(constab[inlen].cn_dev) == major(kgdb_dev)) { kgdb_getc = constab[inlen].cn_getc; kgdb_putc = constab[inlen].cn_putc; break; } if (kgdb_getc == 0 || kgdb_putc == 0) return (0); /* * If the packet that woke us up isn't an exec packet, * ignore it since there is no active debugger. Also, * we check that it's not an ack to be sure that the * remote side doesn't send back a response after the * local gdb has exited. Otherwise, the local host * could trap into gdb if it's running a gdb kernel too. */ in = GETC; /* * If we came in asynchronously through the serial line, * the framing character is eaten by the receive interrupt, * but if we come in through a synchronous trap (i.e., via * kgdb_connect()), we will see the extra character. */ if (in == FRAME_START) in = GETC; /* * Check that this is a debugger exec message. If so, * slurp up the entire message then ack it, and fall * through to the recv loop. */ if (KGDB_CMD(in) != KGDB_EXEC || (in & KGDB_ACK) != 0) return (0); while (GETC != FRAME_END) ; /* * Do the printf *before* we ack the message. This way * we won't drop any inbound characters while we're * doing the polling printf. */ printf("kgdb started from device %x\n", kgdb_dev); kgdb_send(in | KGDB_ACK, (u_char *)0, 0); kgdb_active = 1; } /* * Stick frame regs into our reg cache then tell remote host * that an exception has occured. */ regs_to_gdb(frame, gdb_regs); if (type != T_TRAP15) { /* * Only send an asynchronous SIGNAL message when we hit * a breakpoint. Otherwise, we will drop the incoming * packet while we output this one (and on entry the other * side isn't interested in the SIGNAL type -- if it is, * it will have used a signal packet.) */ outbuffer[0] = computeSignal(type); kgdb_send(KGDB_SIGNAL, outbuffer, 1); } while (1) { in = kgdb_recv(inbuffer, &inlen); if (in == 0 || (in & KGDB_ACK)) /* Ignore inbound acks and error conditions. */ continue; out = in | KGDB_ACK; switch (KGDB_CMD(in)) { case KGDB_SIGNAL: /* * if this command came from a running gdb, * answer it -- the other guy has no way of * knowing if we're in or out of this loop * when he issues a "remote-signal". (Note * that without the length check, we could * loop here forever if the ourput line is * looped back or the remote host is echoing.) */ if (inlen == 0) { outbuffer[0] = computeSignal(type); kgdb_send(KGDB_SIGNAL, outbuffer, 1); } continue; case KGDB_REG_R: case KGDB_REG_R | KGDB_DELTA: cp = outbuffer; outlen = 0; for (len = inbuffer[0]; len < NUM_REGS; ++len) { if (reg_cache[len] != gdb_regs[len] || (in & KGDB_DELTA) == 0) { if (outlen + 5 > SL_MAXDATA) { out |= KGDB_MORE; break; } cp[outlen] = len; kgdb_copy((u_char *)&gdb_regs[len], &cp[outlen + 1], 4); reg_cache[len] = gdb_regs[len]; outlen += 5; } } break; case KGDB_REG_W: case KGDB_REG_W | KGDB_DELTA: cp = inbuffer; for (len = 0; len < inlen; len += 5) { register int j = cp[len]; kgdb_copy(&cp[len + 1], (u_char *)&gdb_regs[j], 4); reg_cache[j] = gdb_regs[j]; } gdb_to_regs(frame, gdb_regs); outlen = 0; break; case KGDB_MEM_R: len = inbuffer[0]; kgdb_copy(&inbuffer[1], (u_char *)&addr, 4); if (len > SL_MAXDATA) { outlen = 1; outbuffer[0] = E2BIG; } else if (!kgdb_acc(addr, len, B_READ)) { outlen = 1; outbuffer[0] = EFAULT; } else { outlen = len + 1; outbuffer[0] = 0; kgdb_copy(addr, &outbuffer[1], len); } break; case KGDB_MEM_W: len = inlen - 4; kgdb_copy(inbuffer, (u_char *)&addr, 4); outlen = 1; if (!kgdb_acc(addr, len, B_READ)) outbuffer[0] = EFAULT; else { outbuffer[0] = 0; if (!kgdb_acc(addr, len, B_WRITE)) chgkprot(addr, len, B_WRITE); kgdb_copy(&inbuffer[4], addr, len); ICIA(); } break; case KGDB_KILL: kgdb_active = 0; printf("kgdb detached\n"); /* fall through */ case KGDB_CONT: kgdb_send(out, 0, 0); frame->f_sr &=~ PSL_T; return (1); case KGDB_STEP: kgdb_send(out, 0, 0); frame->f_sr |= PSL_T; return (1); case KGDB_EXEC: default: /* Unknown command. Ack with a null message. */ outlen = 0; break; } /* Send the reply */ kgdb_send(out, outbuffer, outlen); } } /* * XXX do kernacc call if safe, otherwise attempt * to simulate by simple bounds-checking. */ kgdb_acc(addr, len, rw) caddr_t addr; int len, rw; { extern char proc0paddr[], kstack[]; /* XXX */ extern char *kernel_map; /* XXX! */ if (kernel_map != NULL) return (kernacc(addr, len, rw)); if (addr < proc0paddr + UPAGES * NBPG || kstack <= addr && addr < kstack + UPAGES * NBPG) return (1); return (0); } #endif /* KGDB */
the_stack_data/175143237.c
// Função Malloc # include <stdio.h> # include <malloc.h> int main() { int* y = (int*) malloc(sizeof(int)); *y = 20; int z = sizeof(int); printf("*y= %i z= %i\n ymalloc= %i", *y, z,y); return 0; }
the_stack_data/237643230.c
#include <stdio.h> #include <math.h> // Estrutura para armazenar os valores para o retorno de ambos por referência struct calculo { float volume; float area; }; double areaVolumeEsfera (float *r, struct calculo *res) { res->volume = (4 * M_PI * pow(*r, 3)) / 3; res->area = 4 * M_PI * pow(*r, 2); } int main () { struct calculo res; float raio = 44; areaVolumeEsfera(&raio, &res); printf("Volume: %lf, Área: %lf\n", res.volume, res.area); return 0; }
the_stack_data/20450548.c
#include<stdio.h> int array[10] = {-11,-1, 0,10,21,6,4,2,8,11}; int sum = 10; int main() { //CreateHash Table //Find the size of hash Table int min =10000; int max = -1101; int i; for(i=0 ; i<10; i++) { if(max<array[i]) max = array[i]; if(min>array[i]) min = array[i]; } int hashSize = 0; if(max-min > sum) hashSize = max-min; else { min = 0; hashSize = sum; } int * hash = (int*)(malloc(sizeof(int)* hashSize)); for(i=0;i<10;i++) { hash[array[i]-min] = 1; } for(i=0;i<10;i++) { if(hash[sum-array[i]-min]==1) { printf("\n"); printf("%d and %d",array[i],sum-array[i]); } } }
the_stack_data/69432.c
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #define PROTOCOL_RESERVER 0 #define CONFIG_BUF 256 #define CONFIG "./config.ini" #define PORTFLAG "listen=" #define RECVBUFSIZE 4096 void *portprocess(void *param); int main(int argc, char **argv) { FILE *fd; char *buf; ssize_t read; size_t len; int thread_sum; fd = fopen(CONFIG, "r"); if(NULL == fd){ printf(strerror(errno)); exit(-1); } len = 0; buf = malloc(CONFIG_BUF); memset(buf, 0, CONFIG_BUF); while((read = getline(&buf, &len, fd)) != -1){ char *strport = buf; char *subsequce; if(subsequce = strstr(strport, PORTFLAG)){ char *port; strport += strlen(PORTFLAG); for((port = strtok(strport, ",")); port != NULL; (port = strtok(NULL, ","))){ printf("port %s \n", port); int iport = atoi(port); pthread_t thread; void *status; pthread_create(&thread, NULL, portprocess, (void*)&iport); pthread_join(thread, &status);// pthread_join problem } } } } void *portprocess(void *param) { int sock; int clientsock; struct sockaddr_in addr; struct sockaddr_in remote; socklen_t len; char buf[RECVBUFSIZE]; sock = socket(AF_INET, SOCK_STREAM, PROTOCOL_RESERVER); if(-1 == sock){ printf(strerror(errno)); exit(-1); } memset(&addr, 0, sizeof(struct sockaddr)); addr.sin_family = AF_INET; addr.sin_port = htons((*(unsigned short*)param)); addr.sin_addr.s_addr = htonl(INADDR_ANY); if((bind(sock, (struct sockaddr*)(&addr), sizeof(struct sockaddr_in))) < 0){ printf(strerror(errno)); exit(-1); } if(listen(sock, 50/*backlog size*/) < 0){ printf(strerror(errno)); exit(-1); } clientsock = accept(sock, (struct sockaddr*)&remote, &len); if(-1 == clientsock){ printf(strerror(errno)); exit(-1); } printf("remote addr is %s\n", inet_ntoa(remote.sin_addr)); printf("port is "); while(1){ memset(buf, 0, RECVBUFSIZE); if(-1 == recv(clientsock, buf, RECVBUFSIZE, MSG_WAITALL)){ printf(strerror(errno)); } printf("recv data is %s \n", buf); } return NULL; }
the_stack_data/620804.c
/* * @Author: gongluck * @Date: 2020-11-18 07:52:34 * @Last Modified by: gongluck * @Last Modified time: 2020-11-18 09:28:28 */ #include <stdio.h> #include <stdlib.h> #include <iconv.h> int main() { iconv_t cd = iconv_open("GBK", "UTF-8"); //UTF8 -> GBK if (cd == (iconv_t)-1) { printf("iconv_open failed.\n"); exit(-1); } char str[] = "iconv例子"; char *pstr = str; size_t len = sizeof(str); char out[100] = {0}; char *pout = out; size_t leftlen = sizeof(out); while (1) { pout = out; leftlen = sizeof(out); int n = iconv(cd, &pstr, &len, &pout, &leftlen); //printf("iconv return %d\n", n); if (pout != out)//有转换成功字符 { printf("%.*s", (int)(sizeof(out)-leftlen), out); } else { break; } if(n != -1) { pout = out; leftlen = sizeof(out); n = iconv(cd, NULL, NULL, &pout, &leftlen); if (pout != out) // 检测iconv内部是否还有缓存 { printf("%.*s", (int)(sizeof(out)-leftlen), out); } break; } } printf("\n"); iconv_close(cd); return 0; }
the_stack_data/306497.c
#include<stdio.h> int main() { int i,j,n1,n2; printf("enter the size of matrix\n"); scanf("%d%d",&n1,&n2); int a[n1][n2]; printf("enter the elements\n"); for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { scanf("%d",&a[i][j]); } } for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { if(a[i][j]==0) { a[0][j]=0; a[i][0]=0; } } } printf("printing the resultant array\n"); for(i=0;i<n1;++i) { printf("\n"); for(j=0;j<n2;++j) { printf("%d\t",a[i][j]); } } return 0; }
the_stack_data/31386844.c
#include<stdio.h> #define LEFT(i) 2*i+1 #define RIGHT(i) LEFT(i)+1 int is_sorted(int l[], int n){ int i; for(i = 0; (i < n-1) && (l[i] <= l[i+1]); i ++); return (i == n-1); } void pprint_array(int l[], int n){ for(int i=0; i<n; i++){ printf("%d\t", l[i]); if(!((i+1) % 5)) printf("\n"); } } void shiftDown_Seq(int a[], int start, int end) { int root = start; while( (2*root+1) <= end) { int child = 2*root+1; int swap = root; if (a[swap]<a[child]) swap = child; if ((child+1) <= end) if (a[swap]<a[child+1]) swap = child+1; if(swap==root) root=end; else { int tmp = a[swap]; a[swap]=a[root]; a[root]=tmp; root = swap; } } } void heapify(int a[], int count) { int start=(count-1)/2; while(start>=0) { shiftDown_Seq(a,start,count-1); start--; } }
the_stack_data/108849.c
// divide error in do_journal_end (2) // https://syzkaller.appspot.com/bug?id=7e1ae99949915745b8da // status:0 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/loop.h> static unsigned long long procid; static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct fs_image_segment { void* data; uintptr_t size; uintptr_t offset; }; #define IMAGE_MAX_SEGMENTS 4096 #define IMAGE_MAX_SIZE (129 << 20) #define sys_memfd_create 319 static unsigned long fs_image_segment_check(unsigned long size, unsigned long nsegs, struct fs_image_segment* segs) { if (nsegs > IMAGE_MAX_SEGMENTS) nsegs = IMAGE_MAX_SEGMENTS; for (size_t i = 0; i < nsegs; i++) { if (segs[i].size > IMAGE_MAX_SIZE) segs[i].size = IMAGE_MAX_SIZE; segs[i].offset %= IMAGE_MAX_SIZE; if (segs[i].offset > IMAGE_MAX_SIZE - segs[i].size) segs[i].offset = IMAGE_MAX_SIZE - segs[i].size; if (size < segs[i].offset + segs[i].offset) size = segs[i].offset + segs[i].offset; } if (size > IMAGE_MAX_SIZE) size = IMAGE_MAX_SIZE; return size; } static int setup_loop_device(long unsigned size, long unsigned nsegs, struct fs_image_segment* segs, const char* loopname, int* memfd_p, int* loopfd_p) { int err = 0, loopfd = -1; size = fs_image_segment_check(size, nsegs, segs); int memfd = syscall(sys_memfd_create, "syzkaller", 0); if (memfd == -1) { err = errno; goto error; } if (ftruncate(memfd, size)) { err = errno; goto error_close_memfd; } for (size_t i = 0; i < nsegs; i++) { if (pwrite(memfd, segs[i].data, segs[i].size, segs[i].offset) < 0) { } } loopfd = open(loopname, O_RDWR); if (loopfd == -1) { err = errno; goto error_close_memfd; } if (ioctl(loopfd, LOOP_SET_FD, memfd)) { if (errno != EBUSY) { err = errno; goto error_close_loop; } ioctl(loopfd, LOOP_CLR_FD, 0); usleep(1000); if (ioctl(loopfd, LOOP_SET_FD, memfd)) { err = errno; goto error_close_loop; } } *memfd_p = memfd; *loopfd_p = loopfd; return 0; error_close_loop: close(loopfd); error_close_memfd: close(memfd); error: errno = err; return -1; } static long syz_mount_image(volatile long fsarg, volatile long dir, volatile unsigned long size, volatile unsigned long nsegs, volatile long segments, volatile long flags, volatile long optsarg) { struct fs_image_segment* segs = (struct fs_image_segment*)segments; int res = -1, err = 0, loopfd = -1, memfd = -1, need_loop_device = !!segs; char* mount_opts = (char*)optsarg; char* target = (char*)dir; char* fs = (char*)fsarg; char* source = NULL; char loopname[64]; if (need_loop_device) { memset(loopname, 0, sizeof(loopname)); snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid); if (setup_loop_device(size, nsegs, segs, loopname, &memfd, &loopfd) == -1) return -1; source = loopname; } mkdir(target, 0777); char opts[256]; memset(opts, 0, sizeof(opts)); if (strlen(mount_opts) > (sizeof(opts) - 32)) { } strncpy(opts, mount_opts, sizeof(opts) - 32); if (strcmp(fs, "iso9660") == 0) { flags |= MS_RDONLY; } else if (strncmp(fs, "ext", 3) == 0) { if (strstr(opts, "errors=panic") || strstr(opts, "errors=remount-ro") == 0) strcat(opts, ",errors=continue"); } else if (strcmp(fs, "xfs") == 0) { strcat(opts, ",nouuid"); } res = mount(source, target, fs, flags, opts); if (res == -1) { err = errno; goto error_clear_loop; } res = open(target, O_RDONLY | O_DIRECTORY); if (res == -1) { err = errno; } error_clear_loop: if (need_loop_device) { ioctl(loopfd, LOOP_CLR_FD, 0); close(loopfd); close(memfd); } errno = err; return res; } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { int iter = 0; DIR* dp = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } struct dirent* ep = 0; while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); for (int i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void reset_loop() { char buf[64]; snprintf(buf, sizeof(buf), "/dev/loop%llu", procid); int loopfd = open(buf, O_RDWR); if (loopfd != -1) { ioctl(loopfd, LOOP_CLR_FD, 0); close(loopfd); } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter = 0; for (;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5000) { continue; } kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } void execute_one(void) { memcpy((void*)0x20000000, "reiserfs\000", 9); memcpy((void*)0x20000100, "./file0\000", 8); *(uint64_t*)0x20000200 = 0x20010000; memcpy((void*)0x20010000, "\x00\x40\x00\x00\xec\x1f\x00\x00\x13\x20\x00\x00\x0a\x00\x00\x00\x00" "\x00\x00\x00\x00\x20\x00\x00\x00\x04\x00\x00\x61\x1c\xad\x49\x84\x03" "\x00\x00\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x10\xcc\x03\x02\x00\x01" "\x00\x52\x65\x49\x73\x45\x72\x32\x46\x73\x00\x00\x00\x02\x00\x00\x00" "\x02\x00\x01\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x12" "\x31\x23\x12\x12\x33\x12\x33\x12\x31\x12\x34\x13\x41\x24\x12\x73\x79" "\x7a\x6b\x61\x6c\x6c\x65\x72\x00\x00\x00\x00\x00\x00\x00\x01\x00\x1e" "\x00\x3a\xc1\x65\x5f\x00\x4e\xed\x00", 128); *(uint64_t*)0x20000208 = 0x80; *(uint64_t*)0x20000210 = 0x10000; *(uint64_t*)0x20000218 = 0x20010100; memcpy((void*)0x20010100, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32); *(uint64_t*)0x20000220 = 0x20; *(uint64_t*)0x20000228 = 0x100c0; *(uint64_t*)0x20000230 = 0; *(uint64_t*)0x20000238 = 0; *(uint64_t*)0x20000240 = 0x11000; *(uint64_t*)0x20000248 = 0; *(uint64_t*)0x20000250 = 0; *(uint64_t*)0x20000258 = 0x11800; *(uint64_t*)0x20000260 = 0; *(uint64_t*)0x20000268 = 0; *(uint64_t*)0x20000270 = 0x2012000; *(uint64_t*)0x20000278 = 0x20011000; memcpy((void*)0x20011000, "\x01\x00\x02\x00\x5c\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x2c\x00\xd4\x0f\x01\x00\x01\x00\x00" "\x00\x02\x00\x00\x00\x01\x00\x00\x00\xf4\x01\x00\x00\x02\x00\x30\x00" "\xa4\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 96); *(uint64_t*)0x20000280 = 0x60; *(uint64_t*)0x20000288 = 0x2013000; *(uint64_t*)0x20000290 = 0x20011100; memcpy((void*)0x20011100, "\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x28" "\x00\x04\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x20\x00" "\x04\x00\x2e\x2e\x00\x00\x00\x00\x00\x00\x2e\x00\x00\x00\x00\x00\x00" "\x00\xed\x41\x00\x00\x03\x00\x00\x00\x30\x00\x00\x00\x00\x00\x00\x00" "\x5c\xf9\x01\x00\x53\x5f\x01\x00\x3a\xc1\x65\x5f\x3a\xc1\x65\x5f\x3a" "\xc1\x65\x5f\x01\x00\x00\x00\x00\x00\x00\x00", 96); *(uint64_t*)0x20000298 = 0x60; *(uint64_t*)0x200002a0 = 0x2013fa0; *(uint8_t*)0x20011200 = 0; syz_mount_image(0x20000000, 0x20000100, 0x4000000, 7, 0x20000200, 0, 0x20011200); } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); use_temporary_dir(); loop(); return 0; }
the_stack_data/67326121.c
int main() { double a; __VERIFIER_assume(a==a); double b = a; union { double f; long long unsigned int i; // needs to have 64 bits } au, bu; au.f = a; bu.f = b; assert(au.i == bu.i); assert(a == b); }
the_stack_data/1033832.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* _1_ft_putstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dakim <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/10 10:48:24 by dakim #+# #+# */ /* Updated: 2018/08/10 10:55:48 by dakim ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') { write(1, str[i], 1); i++; } }
the_stack_data/764826.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #define ETHSIZE 400 struct sockaddr_in serv, cli; int main () { char cadena[20] = "hola"; int fd, idb, cli_len, size_recv; char request [ETHSIZE]; puts ("Se crea el socket"); fd = socket (PF_INET, SOCK_DGRAM, 0); if (fd == -1) puts ("error, no se pudo crear el socket"); else puts ("Socket creado"); puts ("Asignando atributos al socket"); memset (&serv, sizeof (serv), 0); serv.sin_family = AF_INET; serv.sin_addr.s_addr = htonl (INADDR_ANY); serv.sin_port = htons (7778); idb = bind (fd, (struct sockaddr *)&serv, sizeof (serv)); if (idb < 0) puts ("No se asignaron los atributos "); else puts ("Si se asignaron los atributos"); while(1){ time_t tiempo = time(0); struct tm *hora = localtime(&tiempo); char output[50]; strftime(output,50,"%H:%M:%S\n",hora); char *datos_para_el_cliente = &output; //Salida de la hora /* Aqui esperamos la peticion del cliente */ cli_len = ETHSIZE; size_recv = recvfrom (fd,(void *)request, ETHSIZE,0, (struct sockaddr *)&cli, (socklen_t *)&cli_len); if (size_recv < 0) { puts ("hubo un problema con el recvfrom"); _exit (1); } else { puts ("el request recibido fue:"); puts (request); } if (request == 0) { return 0; } /* Aqui enviamos los datos al cliente */ sendto (fd,datos_para_el_cliente, strlen (datos_para_el_cliente),0, (struct sockaddr *)&cli, (socklen_t )cli_len); } return 0; }
the_stack_data/24465.c
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ char name[100]; printf("ENTER YOUR NAME -"); scanf("%[^\n]s" ,name); int a,b,c=1,turns,p1=0,cpu=0; printf("\nENTER THE NUMBER OF TURNS YOU WANT TO PLAY- "); scanf("%d" ,&turns); while(c<=turns){ c++; printf("\nCHOOSE - (1)ROCK (2)PAPER (3)SCISSOR"); printf("\nYOUR CHOICE-"); scanf("%d" ,&a); if(a>0 && a<=3){ if(a==1){ printf("\nVALID CHOICE - ROCK"); } if(a==2){ printf("\nVALID CHOICE - PAPER"); } if(a==3){ printf("\nVALID CHOICE - SCISSOR"); } } else{ printf("INVALID CHOICE"); } srand(time(NULL)); b = rand()%2; if(b==0){ printf("\nCPU CHOSE ROCK"); } if(b==1){ printf("\nCPU CHOSE PAPER"); } if(b==2){ printf("\nCPU CHOSE SCISSOR"); } if(a==1 && b==0){ printf("\nDRAW"); } if(a==2 && b==1){ printf("\nDRAW"); } if(a==3 && b==2){ printf("\nDRAW"); } if(a==1 && b==1){ printf("\nCPU WINS"); ++cpu; } if(a==1 && b==2){ printf("\n%s WIN" ,name); ++p1; } if(a==2 && b==0){ printf("\n%s WIN" ,name); ++p1; } if(a==2 && b==2){ printf("\nCPU WINS"); ++cpu; } if(a==3 && b==0){ printf("\nCPU WINS"); ++cpu; } if(a==3 && b==1){ printf("\n%s WIN" ,name); ++p1; } } if(p1>cpu){ printf("\n%s wins %d-%d" ,name,p1,cpu); } if(p1<cpu){ printf("\nCPU wins %d-%d" ,p1,cpu); } if(p1==cpu){ printf("\nTIE %d-%d" ,p1,cpu); } }
the_stack_data/183996.c
#include <stdio.h> #include <sys/types.h> int main(int argc, char* argv[]) { int size = sizeof(pid_t); printf("sizeof(pid_t) = %d\n", size); }
the_stack_data/182954259.c
//Write a Program to find if a given number is Armstrong number.Hint: (153 = 1^3 + 5^3 + 3^3) #include<stdio.h> int main() { int number, num, remainder, result=0; printf("\nEnter the three digit integer number:"); scanf("%d", &number); num = number; while(num > 0) { remainder = num%10; result += remainder*remainder*remainder; num /= 10; } if(number == result) printf("\nThe %d is an Armstrong number.", number); else printf("\nThe %d is not an Armstrong number.", number); printf("\n"); return 0; }
the_stack_data/248582092.c
/* vis: make funny characters visible (version 1) */ #include <stdio.h> #include <ctype.h> int main() { int c; while ((c = getchar()) != EOF) if (isascii(c) && (isprint(c) || c=='\n' || c=='\t' || c==' ')) { if (c == '\t') { printf("\\t"); } else if (c == '\\') { printf("\\\\"); } else { if (c == ' ') { putchar(' '); while ((c = getchar()) == ' ') { putchar(' '); } } if (c == '\n') { putchar('$'); } putchar(c); } } else { printf("\\%03o", c); } return 0; }
the_stack_data/45451233.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isascii.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: njacobso <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/21 13:26:37 by njacobso #+# #+# */ /* Updated: 2018/11/24 14:21:07 by njacobso ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isascii(int c) { if (c >= 0 && c <= 127) { return (1); } return (0); }
the_stack_data/605211.c
/* { dg-do compile { target { powerpc*-*-* } } } */ /* { dg-require-effective-target lp64 } */ /* { dg-options "-O -mno-popcntb" } */ /* { dg-final { scan-assembler-not "stwbrx" } } */ void write_reverse (unsigned long *addr, unsigned long val) { unsigned long reverse = __builtin_bswap64 (val); __atomic_store_n (addr, reverse, __ATOMIC_RELAXED); }
the_stack_data/26700808.c
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2018 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Pierre A. Joye <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef PHP_WIN32 #include "php.h" #include "php_filestat.h" #include "php_globals.h" #include <WinBase.h> #include <stdlib.h> #include <string.h> #if HAVE_PWD_H #include "win32/pwd.h" #endif #if HAVE_GRP_H #include "win32/grp.h" #endif #include <errno.h> #include <ctype.h> #include "php_link.h" #include "php_string.h" /* TODO: - Create php_readlink (done), php_link (done) and php_symlink (done) in win32/link.c - Expose them (PHPAPI) so extensions developers can use them - define link/readlink/symlink to their php_ equivalent and use them in ext/standard/link.c - this file is then useless and we have a portable link API */ #ifndef VOLUME_NAME_NT #define VOLUME_NAME_NT 0x2 #endif #ifndef VOLUME_NAME_DOS #define VOLUME_NAME_DOS 0x0 #endif /* {{{ proto string readlink(string filename) Return the target of a symbolic link */ PHP_FUNCTION(readlink) { char *link; ssize_t link_len; char target[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } if (OPENBASEDIR_CHECKPATH(link)) { RETURN_FALSE; } link_len = php_sys_readlink(link, target, MAXPATHLEN); if (link_len == -1) { php_error_docref(NULL, E_WARNING, "readlink failed to read the symbolic link (%s), error %d)", link, GetLastError()); RETURN_FALSE; } RETURN_STRING(target); } /* }}} */ /* {{{ proto int linkinfo(string filename) Returns the st_dev field of the UNIX C stat structure describing the link */ PHP_FUNCTION(linkinfo) { char *link; char *dirname; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } dirname = estrndup(link, link_len); php_dirname(dirname, link_len); if (php_check_open_basedir(dirname)) { efree(dirname); RETURN_FALSE; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); efree(dirname); RETURN_LONG(Z_L(-1)); } efree(dirname); RETURN_LONG((zend_long) sb.st_dev); } /* }}} */ /* {{{ proto int symlink(string target, string link) Create a symbolic link */ PHP_FUNCTION(symlink) { char *topath, *frompath; size_t topath_len, frompath_len; int ret; char source_p[MAXPATHLEN]; char dest_p[MAXPATHLEN]; char dirname[MAXPATHLEN]; size_t len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &topath, &topath_len, &frompath, &frompath_len) == FAILURE) { return; } if (!expand_filepath(frompath, source_p)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } memcpy(dirname, source_p, sizeof(source_p)); len = php_dirname(dirname, strlen(dirname)); if (!expand_filepath_ex(topath, dest_p, dirname, len)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) || php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ) { php_error_docref(NULL, E_WARNING, "Unable to symlink to a URL"); RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(dest_p)) { RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(source_p)) { RETURN_FALSE; } /* For the source, an expanded path must be used (in ZTS an other thread could have changed the CWD). * For the target the exact string given by the user must be used, relative or not, existing or not. * The target is relative to the link itself, not to the CWD. */ ret = php_sys_symlink(topath, source_p); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int link(string target, string link) Create a hard link */ PHP_FUNCTION(link) { char *topath, *frompath; size_t topath_len, frompath_len; int ret; char source_p[MAXPATHLEN]; char dest_p[MAXPATHLEN]; /*First argument to link function is the target and hence should go to frompath Second argument to link function is the link itself and hence should go to topath */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &frompath, &frompath_len, &topath, &topath_len) == FAILURE) { return; } if (!expand_filepath(frompath, source_p) || !expand_filepath(topath, dest_p)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) || php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ) { php_error_docref(NULL, E_WARNING, "Unable to link to a URL"); RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(source_p)) { RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(dest_p)) { RETURN_FALSE; } #ifndef ZTS ret = php_sys_link(topath, frompath); #else ret = php_sys_link(dest_p, source_p); #endif if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
the_stack_data/178265640.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993 * This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published. ***/ #include <stdint.h> #include <stdlib.h> /// Approximate function add8_144 /// Library = EvoApprox8b /// Circuit = add8_144 /// Area (180) = 1324 /// Delay (180) = 1.240 /// Power (180) = 416.80 /// Area (45) = 92 /// Delay (45) = 0.510 /// Power (45) = 34.31 /// Nodes = 28 /// HD = 134528 /// MAE = 1.59375 /// MSE = 4.00000 /// MRE = 0.86 % /// WCE = 5 /// WCRE = 200 % /// EP = 81.2 % uint16_t add8_144(uint8_t a, uint8_t b) { uint16_t c = 0; uint8_t n2 = (a >> 1) & 0x1; uint8_t n4 = (a >> 2) & 0x1; uint8_t n6 = (a >> 3) & 0x1; uint8_t n8 = (a >> 4) & 0x1; uint8_t n10 = (a >> 5) & 0x1; uint8_t n12 = (a >> 6) & 0x1; uint8_t n14 = (a >> 7) & 0x1; uint8_t n18 = (b >> 1) & 0x1; uint8_t n20 = (b >> 2) & 0x1; uint8_t n22 = (b >> 3) & 0x1; uint8_t n24 = (b >> 4) & 0x1; uint8_t n26 = (b >> 5) & 0x1; uint8_t n28 = (b >> 6) & 0x1; uint8_t n30 = (b >> 7) & 0x1; uint8_t n34; uint8_t n44; uint8_t n48; uint8_t n50; uint8_t n58; uint8_t n59; uint8_t n68; uint8_t n69; uint8_t n73; uint8_t n78; uint8_t n79; uint8_t n84; uint8_t n86; uint8_t n87; uint8_t n88; uint8_t n96; uint8_t n97; uint8_t n134; uint8_t n152; uint8_t n163; uint8_t n171; uint8_t n181; uint8_t n198; uint8_t n199; uint8_t n226; uint8_t n240; uint8_t n244; uint8_t n255; uint8_t n272; uint8_t n391; uint8_t n394; uint8_t n404; uint8_t n412; uint8_t n413; uint8_t n422; n34 = ~(n20 & n4 & n18); n44 = ~(n18 ^ n18); n48 = ~n34; n50 = n4 | n20; n58 = (n6 ^ n22) ^ n48; n59 = (n6 & n22) | (n22 & n48) | (n6 & n48); n68 = n8 ^ n24; n69 = n8 & n24; n73 = n10 | n26; n78 = n10 ^ n26; n79 = n10 & n26; n84 = n59; n86 = n12 ^ n28; n87 = n12 & n28; n88 = n24 | n8; n96 = n14 ^ n30; n97 = n14 & n30; n134 = n88 & n84; n152 = n69 | n134; n163 = n86 & n79; n171 = n86 & n78; n181 = n87 | n163; n198 = n152; n199 = n152; n226 = n73 & n198; n240 = ~n84; n244 = n79 | n226; n255 = n171 & n198; n272 = n181 | n255; n391 = ~(n240 ^ n68); n394 = n78 ^ n199; n404 = n86 ^ n244; n412 = n96 ^ n272; n413 = n96 & n272; n422 = n97 | n413; c |= (n2 & 0x1) << 0; c |= (n44 & 0x1) << 1; c |= (n50 & 0x1) << 2; c |= (n58 & 0x1) << 3; c |= (n391 & 0x1) << 4; c |= (n394 & 0x1) << 5; c |= (n404 & 0x1) << 6; c |= (n412 & 0x1) << 7; c |= (n422 & 0x1) << 8; return c; }
the_stack_data/59513748.c
#include <stdio.h> #include <stdlib.h> extern int foo(); int main() { int (*func)() = foo; if ( func != NULL ) (*func)(); return 0; }
the_stack_data/161081929.c
/* Fig. 10.2: fig10_02.c Using the structure member and structure pointer operators */ #include <stdio.h> /* card structure definition */ struct card { char *face; /* define pointer face */ char *suit; /* define pointer suit */ }; /* end structure card */ int main( void ) { struct card aCard; /* define one struct card variable */ struct card *cardPtr; /* define a pointer to a struct card */ /* place strings into aCard */ aCard.face = "Ace"; aCard.suit = "Spades"; cardPtr = &aCard; /* assign address of aCard to cardPtr */ printf( "%s%s%s\n%s%s%s\n%s%s%s\n", aCard.face, " of ", aCard.suit, cardPtr->face, " of ", cardPtr->suit, ( *cardPtr ).face, " of ", ( *cardPtr ).suit ); return 0; /* indicates successful termination */ } /* end main */ /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
the_stack_data/133098.c
/** * @file * SNTP client module */ /* * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Frédéric Bernon, Simon Goldschmidt */ /** * @defgroup sntp SNTP * @ingroup apps * * This is simple "SNTP" client for the lwIP raw API. * It is a minimal implementation of SNTPv4 as specified in RFC 4330. * * For a list of some public NTP servers, see this link : * http://support.ntp.org/bin/view/Servers/NTPPoolServers * * @todo: * - set/change servers at runtime * - complete SNTP_CHECK_RESPONSE checks 3 and 4 */ #ifdef LIBOHIBOARD_ETHERNET_LWIP_2_0_3 #include "lwip/apps/sntp.h" #include "lwip/opt.h" #include "lwip/timeouts.h" #include "lwip/udp.h" #include "lwip/dns.h" #include "lwip/ip_addr.h" #include "lwip/pbuf.h" #include "lwip/dhcp.h" #include <string.h> #include <time.h> #if LWIP_UDP /* Handle support for more than one server via SNTP_MAX_SERVERS */ #if SNTP_MAX_SERVERS > 1 #define SNTP_SUPPORT_MULTIPLE_SERVERS 1 #else /* NTP_MAX_SERVERS > 1 */ #define SNTP_SUPPORT_MULTIPLE_SERVERS 0 #endif /* NTP_MAX_SERVERS > 1 */ #if (SNTP_UPDATE_DELAY < 15000) && !defined(SNTP_SUPPRESS_DELAY_CHECK) #error "SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds (define SNTP_SUPPRESS_DELAY_CHECK to disable this error)!" #endif /* Configure behaviour depending on microsecond or second precision */ #ifdef SNTP_SET_SYSTEM_TIME_US #define SNTP_CALC_TIME_US 1 #define SNTP_RECEIVE_TIME_SIZE 2 #else #define SNTP_SET_SYSTEM_TIME_US(sec, us) #define SNTP_CALC_TIME_US 0 #define SNTP_RECEIVE_TIME_SIZE 1 #endif /* the various debug levels for this file */ #define SNTP_DEBUG_TRACE (SNTP_DEBUG | LWIP_DBG_TRACE) #define SNTP_DEBUG_STATE (SNTP_DEBUG | LWIP_DBG_STATE) #define SNTP_DEBUG_WARN (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING) #define SNTP_DEBUG_WARN_STATE (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE) #define SNTP_DEBUG_SERIOUS (SNTP_DEBUG | LWIP_DBG_LEVEL_SERIOUS) #define SNTP_ERR_KOD 1 /* SNTP protocol defines */ #define SNTP_MSG_LEN 48 #define SNTP_OFFSET_LI_VN_MODE 0 #define SNTP_LI_MASK 0xC0 #define SNTP_LI_NO_WARNING 0x00 #define SNTP_LI_LAST_MINUTE_61_SEC 0x01 #define SNTP_LI_LAST_MINUTE_59_SEC 0x02 #define SNTP_LI_ALARM_CONDITION 0x03 /* (clock not synchronized) */ #define SNTP_VERSION_MASK 0x38 #define SNTP_VERSION (4/* NTP Version 4*/<<3) #define SNTP_MODE_MASK 0x07 #define SNTP_MODE_CLIENT 0x03 #define SNTP_MODE_SERVER 0x04 #define SNTP_MODE_BROADCAST 0x05 #define SNTP_OFFSET_STRATUM 1 #define SNTP_STRATUM_KOD 0x00 #define SNTP_OFFSET_ORIGINATE_TIME 24 #define SNTP_OFFSET_RECEIVE_TIME 32 #define SNTP_OFFSET_TRANSMIT_TIME 40 /* number of seconds between 1900 and 1970 (MSB=1)*/ #define DIFF_SEC_1900_1970 (2208988800UL) /* number of seconds between 1970 and Feb 7, 2036 (6:28:16 UTC) (MSB=0) */ #define DIFF_SEC_1970_2036 (2085978496UL) /** * SNTP packet format (without optional fields) * Timestamps are coded as 64 bits: * - 32 bits seconds since Jan 01, 1970, 00:00 * - 32 bits seconds fraction (0-padded) * For future use, if the MSB in the seconds part is set, seconds are based * on Feb 07, 2036, 06:28:16. */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct sntp_msg { PACK_STRUCT_FLD_8(u8_t li_vn_mode); PACK_STRUCT_FLD_8(u8_t stratum); PACK_STRUCT_FLD_8(u8_t poll); PACK_STRUCT_FLD_8(u8_t precision); PACK_STRUCT_FIELD(u32_t root_delay); PACK_STRUCT_FIELD(u32_t root_dispersion); PACK_STRUCT_FIELD(u32_t reference_identifier); PACK_STRUCT_FIELD(u32_t reference_timestamp[2]); PACK_STRUCT_FIELD(u32_t originate_timestamp[2]); PACK_STRUCT_FIELD(u32_t receive_timestamp[2]); PACK_STRUCT_FIELD(u32_t transmit_timestamp[2]); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /* function prototypes */ static void sntp_request(void *arg); /** The operating mode */ static u8_t sntp_opmode; /** The UDP pcb used by the SNTP client */ static struct udp_pcb* sntp_pcb; /** Names/Addresses of servers */ struct sntp_server { #if SNTP_SERVER_DNS char* name; #endif /* SNTP_SERVER_DNS */ ip_addr_t addr; }; static struct sntp_server sntp_servers[SNTP_MAX_SERVERS]; #if SNTP_GET_SERVERS_FROM_DHCP static u8_t sntp_set_servers_from_dhcp; #endif /* SNTP_GET_SERVERS_FROM_DHCP */ #if SNTP_SUPPORT_MULTIPLE_SERVERS /** The currently used server (initialized to 0) */ static u8_t sntp_current_server; #else /* SNTP_SUPPORT_MULTIPLE_SERVERS */ #define sntp_current_server 0 #endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */ #if SNTP_RETRY_TIMEOUT_EXP #define SNTP_RESET_RETRY_TIMEOUT() sntp_retry_timeout = SNTP_RETRY_TIMEOUT /** Retry time, initialized with SNTP_RETRY_TIMEOUT and doubled with each retry. */ static u32_t sntp_retry_timeout; #else /* SNTP_RETRY_TIMEOUT_EXP */ #define SNTP_RESET_RETRY_TIMEOUT() #define sntp_retry_timeout SNTP_RETRY_TIMEOUT #endif /* SNTP_RETRY_TIMEOUT_EXP */ #if SNTP_CHECK_RESPONSE >= 1 /** Saves the last server address to compare with response */ static ip_addr_t sntp_last_server_address; #endif /* SNTP_CHECK_RESPONSE >= 1 */ #if SNTP_CHECK_RESPONSE >= 2 /** Saves the last timestamp sent (which is sent back by the server) * to compare against in response */ static u32_t sntp_last_timestamp_sent[2]; #endif /* SNTP_CHECK_RESPONSE >= 2 */ /** * SNTP processing of received timestamp */ static void sntp_process(u32_t *receive_timestamp) { /* convert SNTP time (1900-based) to unix GMT time (1970-based) * if MSB is 0, SNTP time is 2036-based! */ u32_t rx_secs = lwip_ntohl(receive_timestamp[0]); int is_1900_based = ((rx_secs & 0x80000000) != 0); u32_t t = is_1900_based ? (rx_secs - DIFF_SEC_1900_1970) : (rx_secs + DIFF_SEC_1970_2036); time_t tim = t; #if SNTP_CALC_TIME_US u32_t us = lwip_ntohl(receive_timestamp[1]) / 4295; SNTP_SET_SYSTEM_TIME_US(t, us); /* display local time from GMT time */ LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&tim), us)); #else /* SNTP_CALC_TIME_US */ /* change system time and/or the update the RTC clock */ SNTP_SET_SYSTEM_TIME(t); /* display local time from GMT time */ LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s", ctime(&tim))); #endif /* SNTP_CALC_TIME_US */ LWIP_UNUSED_ARG(tim); } /** * Initialize request struct to be sent to server. */ static void sntp_initialize_request(struct sntp_msg *req) { memset(req, 0, SNTP_MSG_LEN); req->li_vn_mode = SNTP_LI_NO_WARNING | SNTP_VERSION | SNTP_MODE_CLIENT; #if SNTP_CHECK_RESPONSE >= 2 { u32_t sntp_time_sec, sntp_time_us; /* fill in transmit timestamp and save it in 'sntp_last_timestamp_sent' */ SNTP_GET_SYSTEM_TIME(sntp_time_sec, sntp_time_us); sntp_last_timestamp_sent[0] = lwip_htonl(sntp_time_sec + DIFF_SEC_1900_1970); req->transmit_timestamp[0] = sntp_last_timestamp_sent[0]; /* we send/save us instead of fraction to be faster... */ sntp_last_timestamp_sent[1] = lwip_htonl(sntp_time_us); req->transmit_timestamp[1] = sntp_last_timestamp_sent[1]; } #endif /* SNTP_CHECK_RESPONSE >= 2 */ } /** * Retry: send a new request (and increase retry timeout). * * @param arg is unused (only necessary to conform to sys_timeout) */ static void sntp_retry(void* arg) { LWIP_UNUSED_ARG(arg); LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Next request will be sent in %"U32_F" ms\n", sntp_retry_timeout)); /* set up a timer to send a retry and increase the retry delay */ sys_timeout(sntp_retry_timeout, sntp_request, NULL); #if SNTP_RETRY_TIMEOUT_EXP { u32_t new_retry_timeout; /* increase the timeout for next retry */ new_retry_timeout = sntp_retry_timeout << 1; /* limit to maximum timeout and prevent overflow */ if ((new_retry_timeout <= SNTP_RETRY_TIMEOUT_MAX) && (new_retry_timeout > sntp_retry_timeout)) { sntp_retry_timeout = new_retry_timeout; } } #endif /* SNTP_RETRY_TIMEOUT_EXP */ } #if SNTP_SUPPORT_MULTIPLE_SERVERS /** * If Kiss-of-Death is received (or another packet parsing error), * try the next server or retry the current server and increase the retry * timeout if only one server is available. * (implicitly, SNTP_MAX_SERVERS > 1) * * @param arg is unused (only necessary to conform to sys_timeout) */ static void sntp_try_next_server(void* arg) { u8_t old_server, i; LWIP_UNUSED_ARG(arg); old_server = sntp_current_server; for (i = 0; i < SNTP_MAX_SERVERS - 1; i++) { sntp_current_server++; if (sntp_current_server >= SNTP_MAX_SERVERS) { sntp_current_server = 0; } if (!ip_addr_isany(&sntp_servers[sntp_current_server].addr) #if SNTP_SERVER_DNS || (sntp_servers[sntp_current_server].name != NULL) #endif ) { LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_try_next_server: Sending request to server %"U16_F"\n", (u16_t)sntp_current_server)); /* new server: reset retry timeout */ SNTP_RESET_RETRY_TIMEOUT(); /* instantly send a request to the next server */ sntp_request(NULL); return; } } /* no other valid server found */ sntp_current_server = old_server; sntp_retry(NULL); } #else /* SNTP_SUPPORT_MULTIPLE_SERVERS */ /* Always retry on error if only one server is supported */ #define sntp_try_next_server sntp_retry #endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */ /** UDP recv callback for the sntp pcb */ static void sntp_recv(void *arg, struct udp_pcb* pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) { u8_t mode; u8_t stratum; u32_t receive_timestamp[SNTP_RECEIVE_TIME_SIZE]; err_t err; LWIP_UNUSED_ARG(arg); LWIP_UNUSED_ARG(pcb); /* packet received: stop retry timeout */ sys_untimeout(sntp_try_next_server, NULL); sys_untimeout(sntp_request, NULL); err = ERR_ARG; #if SNTP_CHECK_RESPONSE >= 1 /* check server address and port */ if (((sntp_opmode != SNTP_OPMODE_POLL) || ip_addr_cmp(addr, &sntp_last_server_address)) && (port == SNTP_PORT)) #else /* SNTP_CHECK_RESPONSE >= 1 */ LWIP_UNUSED_ARG(addr); LWIP_UNUSED_ARG(port); #endif /* SNTP_CHECK_RESPONSE >= 1 */ { /* process the response */ if (p->tot_len == SNTP_MSG_LEN) { pbuf_copy_partial(p, &mode, 1, SNTP_OFFSET_LI_VN_MODE); mode &= SNTP_MODE_MASK; /* if this is a SNTP response... */ if (((sntp_opmode == SNTP_OPMODE_POLL) && (mode == SNTP_MODE_SERVER)) || ((sntp_opmode == SNTP_OPMODE_LISTENONLY) && (mode == SNTP_MODE_BROADCAST))) { pbuf_copy_partial(p, &stratum, 1, SNTP_OFFSET_STRATUM); if (stratum == SNTP_STRATUM_KOD) { /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */ err = SNTP_ERR_KOD; LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Received Kiss-of-Death\n")); } else { #if SNTP_CHECK_RESPONSE >= 2 /* check originate_timetamp against sntp_last_timestamp_sent */ u32_t originate_timestamp[2]; pbuf_copy_partial(p, &originate_timestamp, 8, SNTP_OFFSET_ORIGINATE_TIME); if ((originate_timestamp[0] != sntp_last_timestamp_sent[0]) || (originate_timestamp[1] != sntp_last_timestamp_sent[1])) { LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid originate timestamp in response\n")); } else #endif /* SNTP_CHECK_RESPONSE >= 2 */ /* @todo: add code for SNTP_CHECK_RESPONSE >= 3 and >= 4 here */ { /* correct answer */ err = ERR_OK; pbuf_copy_partial(p, &receive_timestamp, SNTP_RECEIVE_TIME_SIZE * 4, SNTP_OFFSET_TRANSMIT_TIME); } } } else { LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid mode in response: %"U16_F"\n", (u16_t)mode)); /* wait for correct response */ err = ERR_TIMEOUT; } } else { LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid packet length: %"U16_F"\n", p->tot_len)); } } #if SNTP_CHECK_RESPONSE >= 1 else { /* packet from wrong remote address or port, wait for correct response */ err = ERR_TIMEOUT; } #endif /* SNTP_CHECK_RESPONSE >= 1 */ pbuf_free(p); if (err == ERR_OK) { sntp_process(receive_timestamp); /* Set up timeout for next request (only if poll response was received)*/ if (sntp_opmode == SNTP_OPMODE_POLL) { /* Correct response, reset retry timeout */ SNTP_RESET_RETRY_TIMEOUT(); sys_timeout((u32_t)SNTP_UPDATE_DELAY, sntp_request, NULL); LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Scheduled next time request: %"U32_F" ms\n", (u32_t)SNTP_UPDATE_DELAY)); } } else if (err != ERR_TIMEOUT) { /* Errors are only processed in case of an explicit poll response */ if (sntp_opmode == SNTP_OPMODE_POLL) { if (err == SNTP_ERR_KOD) { /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */ sntp_try_next_server(NULL); } else { /* another error, try the same server again */ sntp_retry(NULL); } } } } /** Actually send an sntp request to a server. * * @param server_addr resolved IP address of the SNTP server */ static void sntp_send_request(const ip_addr_t *server_addr) { struct pbuf* p; p = pbuf_alloc(PBUF_TRANSPORT, SNTP_MSG_LEN, PBUF_RAM); if (p != NULL) { struct sntp_msg *sntpmsg = (struct sntp_msg *)p->payload; LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_send_request: Sending request to server\n")); /* initialize request message */ sntp_initialize_request(sntpmsg); /* send request */ udp_sendto(sntp_pcb, p, server_addr, SNTP_PORT); /* free the pbuf after sending it */ pbuf_free(p); /* set up receive timeout: try next server or retry on timeout */ sys_timeout((u32_t)SNTP_RECV_TIMEOUT, sntp_try_next_server, NULL); #if SNTP_CHECK_RESPONSE >= 1 /* save server address to verify it in sntp_recv */ ip_addr_set(&sntp_last_server_address, server_addr); #endif /* SNTP_CHECK_RESPONSE >= 1 */ } else { LWIP_DEBUGF(SNTP_DEBUG_SERIOUS, ("sntp_send_request: Out of memory, trying again in %"U32_F" ms\n", (u32_t)SNTP_RETRY_TIMEOUT)); /* out of memory: set up a timer to send a retry */ sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_request, NULL); } } #if SNTP_SERVER_DNS /** * DNS found callback when using DNS names as server address. */ static void sntp_dns_found(const char* hostname, const ip_addr_t *ipaddr, void *arg) { LWIP_UNUSED_ARG(hostname); LWIP_UNUSED_ARG(arg); if (ipaddr != NULL) { /* Address resolved, send request */ LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_dns_found: Server address resolved, sending request\n")); sntp_send_request(ipaddr); } else { /* DNS resolving failed -> try another server */ LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_dns_found: Failed to resolve server address resolved, trying next server\n")); sntp_try_next_server(NULL); } } #endif /* SNTP_SERVER_DNS */ /** * Send out an sntp request. * * @param arg is unused (only necessary to conform to sys_timeout) */ static void sntp_request(void *arg) { ip_addr_t sntp_server_address; err_t err; LWIP_UNUSED_ARG(arg); /* initialize SNTP server address */ #if SNTP_SERVER_DNS if (sntp_servers[sntp_current_server].name) { /* always resolve the name and rely on dns-internal caching & timeout */ ip_addr_set_zero(&sntp_servers[sntp_current_server].addr); err = dns_gethostbyname(sntp_servers[sntp_current_server].name, &sntp_server_address, sntp_dns_found, NULL); if (err == ERR_INPROGRESS) { /* DNS request sent, wait for sntp_dns_found being called */ LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_request: Waiting for server address to be resolved.\n")); return; } else if (err == ERR_OK) { sntp_servers[sntp_current_server].addr = sntp_server_address; } } else #endif /* SNTP_SERVER_DNS */ { sntp_server_address = sntp_servers[sntp_current_server].addr; err = (ip_addr_isany_val(sntp_server_address)) ? ERR_ARG : ERR_OK; } if (err == ERR_OK) { LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_request: current server address is %s\n", ipaddr_ntoa(&sntp_server_address))); sntp_send_request(&sntp_server_address); } else { /* address conversion failed, try another server */ LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_request: Invalid server address, trying next server.\n")); sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_try_next_server, NULL); } } /** * @ingroup sntp * Initialize this module. * Send out request instantly or after SNTP_STARTUP_DELAY(_FUNC). */ void sntp_init(void) { #ifdef SNTP_SERVER_ADDRESS #if SNTP_SERVER_DNS sntp_setservername(0, SNTP_SERVER_ADDRESS); #else #error SNTP_SERVER_ADDRESS string not supported SNTP_SERVER_DNS==0 #endif #endif /* SNTP_SERVER_ADDRESS */ if (sntp_pcb == NULL) { sntp_pcb = udp_new_ip_type(IPADDR_TYPE_ANY); LWIP_ASSERT("Failed to allocate udp pcb for sntp client", sntp_pcb != NULL); if (sntp_pcb != NULL) { udp_recv(sntp_pcb, sntp_recv, NULL); if (sntp_opmode == SNTP_OPMODE_POLL) { SNTP_RESET_RETRY_TIMEOUT(); #if SNTP_STARTUP_DELAY sys_timeout((u32_t)SNTP_STARTUP_DELAY_FUNC, sntp_request, NULL); #else sntp_request(NULL); #endif } else if (sntp_opmode == SNTP_OPMODE_LISTENONLY) { ip_set_option(sntp_pcb, SOF_BROADCAST); udp_bind(sntp_pcb, IP_ANY_TYPE, SNTP_PORT); } } } } /** * @ingroup sntp * Stop this module. */ void sntp_stop(void) { if (sntp_pcb != NULL) { sys_untimeout(sntp_request, NULL); sys_untimeout(sntp_try_next_server, NULL); udp_remove(sntp_pcb); sntp_pcb = NULL; } } /** * @ingroup sntp * Get enabled state. */ u8_t sntp_enabled(void) { return (sntp_pcb != NULL)? 1 : 0; } /** * @ingroup sntp * Sets the operating mode. * @param operating_mode one of the available operating modes */ void sntp_setoperatingmode(u8_t operating_mode) { LWIP_ASSERT("Invalid operating mode", operating_mode <= SNTP_OPMODE_LISTENONLY); LWIP_ASSERT("Operating mode must not be set while SNTP client is running", sntp_pcb == NULL); sntp_opmode = operating_mode; } /** * @ingroup sntp * Gets the operating mode. */ u8_t sntp_getoperatingmode(void) { return sntp_opmode; } #if SNTP_GET_SERVERS_FROM_DHCP /** * Config SNTP server handling by IP address, name, or DHCP; clear table * @param set_servers_from_dhcp enable or disable getting server addresses from dhcp */ void sntp_servermode_dhcp(int set_servers_from_dhcp) { u8_t new_mode = set_servers_from_dhcp ? 1 : 0; if (sntp_set_servers_from_dhcp != new_mode) { sntp_set_servers_from_dhcp = new_mode; } } #endif /* SNTP_GET_SERVERS_FROM_DHCP */ /** * @ingroup sntp * Initialize one of the NTP servers by IP address * * @param idx the index of the NTP server to set must be < SNTP_MAX_SERVERS * @param server IP address of the NTP server to set */ void sntp_setserver(u8_t idx, const ip_addr_t *server) { if (idx < SNTP_MAX_SERVERS) { if (server != NULL) { sntp_servers[idx].addr = (*server); } else { ip_addr_set_zero(&sntp_servers[idx].addr); } #if SNTP_SERVER_DNS sntp_servers[idx].name = NULL; #endif } } #if LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP /** * Initialize one of the NTP servers by IP address, required by DHCP * * @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS * @param dnsserver IP address of the NTP server to set */ void dhcp_set_ntp_servers(u8_t num, const ip4_addr_t *server) { LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: %s %u.%u.%u.%u as NTP server #%u via DHCP\n", (sntp_set_servers_from_dhcp ? "Got" : "Rejected"), ip4_addr1(server), ip4_addr2(server), ip4_addr3(server), ip4_addr4(server), num)); if (sntp_set_servers_from_dhcp && num) { u8_t i; for (i = 0; (i < num) && (i < SNTP_MAX_SERVERS); i++) { ip_addr_t addr; ip_addr_copy_from_ip4(addr, server[i]); sntp_setserver(i, &addr); } for (i = num; i < SNTP_MAX_SERVERS; i++) { sntp_setserver(i, NULL); } } } #endif /* LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP */ /** * @ingroup sntp * Obtain one of the currently configured by IP address (or DHCP) NTP servers * * @param idx the index of the NTP server * @return IP address of the indexed NTP server or "ip_addr_any" if the NTP * server has not been configured by address (or at all). */ const ip_addr_t* sntp_getserver(u8_t idx) { if (idx < SNTP_MAX_SERVERS) { return &sntp_servers[idx].addr; } return IP_ADDR_ANY; } #if SNTP_SERVER_DNS /** * Initialize one of the NTP servers by name * * @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS * @param dnsserver DNS name of the NTP server to set, to be resolved at contact time */ void sntp_setservername(u8_t idx, char *server) { if (idx < SNTP_MAX_SERVERS) { sntp_servers[idx].name = server; } } /** * Obtain one of the currently configured by name NTP servers. * * @param numdns the index of the NTP server * @return IP address of the indexed NTP server or NULL if the NTP * server has not been configured by name (or at all) */ char * sntp_getservername(u8_t idx) { if (idx < SNTP_MAX_SERVERS) { return sntp_servers[idx].name; } return NULL; } #endif /* SNTP_SERVER_DNS */ #endif /* LWIP_UDP */ #endif /* LIBOHIBOARD_ETHERNET_LWIP_2_0_3 */
the_stack_data/132952429.c
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(void) { int count = 1; int child; child = fork( ); if(child < 0) { perror("fork error : "); } else if(child == 0) { printf("This is son, his count is: %d (%p). and his pid is: %d\n", ++count, &count, getpid()); } else { printf("This is father, his count is: %d (%p), his pid is: %d\n", count, &count, getpid()); } return EXIT_SUCCESS; }
the_stack_data/150140003.c
/**************************************************************************** * tools/cnvwindeps.c * * Copyright (C) 2016 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #ifdef HOST_CYGWIN #include <sys/cygwin.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define MAX_LINE 1024 #define MAX_PATH 1024 /**************************************************************************** * Global Data ****************************************************************************/ static unsigned long g_lineno; static char g_line[MAX_LINE]; static char g_dequoted[MAX_PATH]; static char g_posix[MAX_PATH]; /**************************************************************************** * Private Functions ****************************************************************************/ static char *skip_spaces(char *ptr) { while (*ptr && isspace((int)*ptr)) ptr++; return ptr; } static char *find_spaces(char *ptr) { bool quoted = false; while (*ptr) { if (ptr[0] == '\\' && isspace((int)ptr[1])) { quoted = true; ptr++; } else if (!quoted && isspace((int)*ptr)) { break; } else { quoted = false; ptr++; } } return ptr; } static bool scour_path(const char *path) { /* KLUDGE: GNU make cannot handle dependencies with spaces in them. * There may be addition characters that cause problems too. */ return strchr(path, ' ') != NULL; } static bool dequote_path(const char *winpath) { char *dest = g_dequoted; const char *src = winpath; int len = 0; bool quoted = false; while (*src && len < MAX_PATH) { if (src[0] != '\\' || (src[1] != ' ' && src[1] != '(' && src[1] != ')')) { *dest++ = *src; len++; } else { quoted = true; } src++; } if (*src || len >= MAX_PATH) { fprintf(stderr, "%lu: Line truncated\n", g_lineno); exit(EXIT_FAILURE); } *dest = '\0'; return quoted; } static bool convert_path(const char *winpath) { ssize_t size; ssize_t ret; bool quoted; quoted = dequote_path(winpath); size = cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, g_dequoted, NULL, 0); if (size > MAX_PATH) { fprintf(stderr, "%lu: POSIX path too long: %lu\n", g_lineno, (unsigned long)size); exit(EXIT_FAILURE); } ret = cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, g_dequoted, g_posix, MAX_PATH); if (ret < 0) { fprintf(stderr, "%lu: cygwin_conv_path '%s' failed: %s\n", g_lineno, g_dequoted, strerror(errno)); exit(EXIT_FAILURE); } return quoted; } static void show_usage(const char *progname) { fprintf(stderr, "USAGE: %s <path-to-deps-file>\n", progname); exit(EXIT_FAILURE); } /**************************************************************************** * Public Functions ****************************************************************************/ int main(int argc, char **argv, char **envp) { char *path; char *next; FILE *stream; bool begin; bool quoted; bool scouring; if (argc != 2) { fprintf(stderr, "Unexpected number of arguments\n"); show_usage(argv[0]); } stream = fopen(argv[1], "r"); if (!stream) { fprintf(stderr, "open %s failed: %s\n", argv[1], strerror(errno)); exit(EXIT_FAILURE); } begin = true; scouring = false; g_lineno = 0; while (fgets(g_line, MAX_LINE, stream) != NULL) { g_lineno++; next = g_line; for (; ; ) { if (begin) { path = skip_spaces(next); if (*path == '#') { /* The reset of the line is comment */ puts(path); break; } next = strchr(path, ':'); if (!next) { fprintf(stderr, "%lu: Expected colon\n", g_lineno); exit(EXIT_FAILURE); } if (*next != '\0') { *next++ = '\0'; } scouring = scour_path(path); if (!scouring) { quoted = convert_path(path); if (quoted) { printf("\"%s\":", g_posix); } else { printf("%s:", g_posix); } } begin = false; } else { path = skip_spaces(next); next = find_spaces(path); if (path[0] == '\\') { break; } else if (strcmp(path, "") == 0) { printf("\n\n"); begin = true; scouring = false; break; } else { if (*next != '\0') { *next++ = '\0'; } if (!scouring && !scour_path(path)) { quoted = convert_path(path); if (quoted) { printf(" \\\n\t\"%s\"", g_posix); } else { printf(" \\\n\t%s", g_posix); } } } } } } fclose(stream); return 0; } #else /* HOST_CYGWIN */ int main(int argc, char **argv, char **envp) { fprintf(stderr, "ERROR: This tool is only available under Cygwin\n"); return EXIT_FAILURE; } #endif /* HOST_CYGWIN */
the_stack_data/132310.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int First = 1; typedef struct TNode *Tree; struct TNode { char Data; struct TNode *Left; struct TNode *Right; struct TNode *Father; int Traversed; }; int IsEmpty(Tree T); Tree InsertNode(int Data, Tree Father); void PostOrderTraversal(Tree T); Tree PopNode(Tree CurNode); int main() { FILE *fp; fp = fopen("input1.txt", "r"); int N = 0; fscanf(fp, "%d\n", &N); int (*Op)[2] = malloc(sizeof(int) * 2 * (2 * N)); char Operation[10]; char Node[10]; for (int i = 0; i < 2 * N; i++) { fscanf(fp, "%s", Operation); if (strcmp(Operation, "Push") == 0) { Op[i][0] = 1; fscanf(fp, "%s", Node); Op[i][1] = atoi(Node); } else if (strcmp(Operation, "Pop") == 0) { Op[i][0] = -1; Op[i][1] = -1; } } fclose(fp); if(N == 0) return 0; Tree T = InsertNode(Op[0][1], NULL); Tree CurNode = T; for (int i = 1; i < 2 * N; i++) { if (Op[i][0] == 1) { if (CurNode->Left == NULL) { CurNode->Left = InsertNode(Op[i][1], CurNode); CurNode = CurNode->Left; } else { CurNode->Right = InsertNode(Op[i][1], CurNode); CurNode = CurNode->Right; } } else if (Op[i][0] == -1) { CurNode = PopNode(CurNode); } } PostOrderTraversal(T); return 0; } int IsEmpty(Tree T) { return T == NULL; } Tree InsertNode(int Data, Tree Father) { Tree T = (Tree)malloc(sizeof(struct TNode)); T->Data = Data; T->Left = NULL; T->Right = NULL; T->Father = Father; T->Traversed = 0; return T; } void PostOrderTraversal(Tree T) { if (T == NULL) return; PostOrderTraversal(T->Left); PostOrderTraversal(T->Right); if (!First) printf(" "); printf("%d", T->Data); First = 0; } Tree PopNode(Tree CurNode){ if (CurNode->Traversed == 0) { CurNode->Traversed = 1; } else { CurNode = CurNode->Father; CurNode = PopNode(CurNode); } return CurNode; }
the_stack_data/115456.c
// Impact of conditions on points-to // Check the and operator #include <stdio.h> int main() { int *p=NULL, *q=NULL, i, j; if(!p&& !q) { p = &i; q = &j; } else if(!p) { *q = 2; } else if(!q) { *p = 1; } else { *p = 1; *q = 2; } return 0; }
the_stack_data/179830968.c
/* * COPYRIGHT * * sines.c * Copyright (C) 2014 Exstrom Laboratories LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * A copy of the GNU General Public License is available on the internet at: * http://www.gnu.org/copyleft/gpl.html * * or you can write to: * * The Free Software Foundation, Inc. * 675 Mass Ave * Cambridge, MA 02139, USA * * Exstrom Laboratories LLC contact: * stefan(AT)exstrom.com * * Exstrom Laboratories LLC * Longmont, CO 80503, USA * */ #include <stdlib.h> #include <stdio.h> #include <math.h> // Compile: gcc -lm -o sines sines.c // Input file format // n (number of sines) // a1 (amplitude) f1 (frequency) p1 (phase) // a2 f2 p2 // an fn pn double sumarray(int n, double *a) { int i; double s = 0.0; for(i=0; i<n; ++i) s+=a[i]; return(s); } int main( int argc, char *argv[] ) { if( argc != 4 ) { printf("Usage: %s file s n\n", argv[0]); printf("Produces n samples of the sine waves defined in file.\n"); printf(" s = sampling frequency\n"); exit( -1 ); } FILE *fp = fopen(argv[1], "r"); double s = strtod(argv[2], NULL); unsigned long is, ns = strtoul(argv[3], NULL, 10); int i, n; fscanf(fp, "%d", &n); double a, f, p, t; double *x = (double *)malloc(n*sizeof(double)); double *y = (double *)malloc(n*sizeof(double)); double *cs = (double *)malloc(n*sizeof(double)); double *sn = (double *)malloc(n*sizeof(double)); for(i=0; i<n; ++i){ fscanf(fp, "%lf %lf %lf", &a, &f, &p); t = 2.0*M_PI*f/s; cs[i] = cos(t); sn[i] = sin(t); x[i] = a*cos(p); y[i] = a*sin(p);} printf("%lf\n", sumarray(n,y)); for(is=1; is<ns; ++is){ for(i=0; i<n; ++i){ t = x[i]; x[i] = cs[i]*x[i] - sn[i]*y[i]; // x = samples of a*cos(2*pi*f*t + p) y[i] = sn[i]*t + cs[i]*y[i];} // y = samples of a*sin(2*pi*f*t + p) printf("%lf\n", sumarray(n,y));} return( 0 ); }
the_stack_data/43886842.c
int timestwo(int in) { return (in * 2); }
the_stack_data/68886879.c
#include<stdio.h> int main(){ int a, b, c, nump = 0, cont, div; printf("Digita o número a"); scanf("%d", &a); printf("Digite o número b"); scanf("%d", &b); if (a < b) { c = a; a = b; b = c; } while(a >= b){ cont= 0; div = 1; while(cont <= b){ if (b % cont == 0) { nump = nump + 1; } cont++; } if (nump == 2) { printf("%d", nump); } b = b + 1; cont = 0; nump =0; } return 0; }
the_stack_data/159515594.c
#include <stdio.h> main () { float b, h, area; printf("\n\t*******************\n"); printf("\t*AREA DO RETANGULO*"); printf("\n\t*******************\n"); printf("\nInsira a base: "); scanf("%f", &b); printf("Insira a altura :"); scanf("%f", &h); area = b * h; printf("Area: %.2f", area); }
the_stack_data/829052.c
/* * A buggy example using execl(2). It will behave differently on different * systems. On recent Linux kernels, the process is killed by SIGABRT. * * However, on older systems the 2nd argument is taken as an empty argv[0], and * /bin/ls will get whatever is on stack after that. That could be a list of * environment variables, for example (happened on FreeBSD in the past), making * it quite confusing: * * $ ./a.out * : BLOCKSIZE=K: No such file or directory * : FTP_PASSIVE_MODE=YES: No such file or directory * : HISTCONTROL=ignoredups: No such file or directory * : HISTSIZE=10000: No such file or directory * ... * ... */ #include <err.h> #include <unistd.h> int main(void) { execl("/bin/ls", NULL); err(1, "execl"); }
the_stack_data/492319.c
#include <stdio.h> int main(void) { int i; for (i = 0; i < 11; i++) { printf("%dx8 = %d\n", i, i * 8); } }
the_stack_data/13279.c
// RUN: %clang_cc1 -ffreestanding -triple x86_64-apple-macosx10.8.0 -target-feature +sse4.1 -debug-info-kind=limited -emit-llvm %s -o - | FileCheck %s // Test that intrinsic calls inlined from _mm_* wrappers have debug metadata. #include <xmmintrin.h> __m128 test_rsqrt_ss(__m128 x) { // CHECK: define {{.*}} @test_rsqrt_ss // CHECK: call <4 x float> @llvm.x86.sse.rsqrt.ss({{.*}}, !dbg !{{.*}} // CHECK: ret <4 x float> return _mm_rsqrt_ss(x); }
the_stack_data/97011672.c
//===-- main.c --------------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <stdint.h> #include <stdio.h> #include <string.h> int main (int argc, char const *argv[]) { struct Bits { uint32_t : 1, // Unnamed bitfield b1 : 1, b2 : 2, : 2, // Unnamed bitfield b3 : 3, : 2, // Unnamed bitfield (this will get removed) b4 __attribute__ ((aligned(16))), b5 : 5, b6 : 6, b7 : 7, four : 4; }; printf("%lu", sizeof(struct Bits)); struct Bits bits; int i; for (i=0; i<(1<<1); i++) bits.b1 = i; //// break $source:$line for (i=0; i<(1<<2); i++) bits.b2 = i; //// break $source:$line for (i=0; i<(1<<3); i++) bits.b3 = i; //// break $source:$line for (i=0; i<(1<<4); i++) bits.b4 = i; //// break $source:$line for (i=0; i<(1<<5); i++) bits.b5 = i; //// break $source:$line for (i=0; i<(1<<6); i++) bits.b6 = i; //// break $source:$line for (i=0; i<(1<<7); i++) bits.b7 = i; //// break $source:$line for (i=0; i<(1<<4); i++) bits.four = i; //// break $source:$line struct MoreBits { uint32_t a : 3; uint8_t : 1; uint8_t b : 1; uint8_t c : 1; uint8_t d : 1; }; struct MoreBits more_bits; more_bits.a = 3; more_bits.b = 0; more_bits.c = 1; more_bits.d = 0; struct EvenMoreBits { uint8_t b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1, b8 : 1, b9 : 1, b10 : 1, b11 : 1, b12 : 1, b13 : 1, b14 : 1, b15 : 1, b16 : 1, b17 : 1; }; struct EvenMoreBits even_more_bits; memset(&even_more_bits, 0, sizeof(even_more_bits)); even_more_bits.b1 = 1; even_more_bits.b5 = 1; even_more_bits.b7 = 1; even_more_bits.b13 = 1; #pragma pack(1) struct PackedBits { char a; uint32_t b : 5, c : 27; }; #pragma pack() struct PackedBits packed; packed.a = 'a'; packed.b = 10; packed.c = 0x7112233; struct LargePackedBits { uint64_t a: 36; uint64_t b: 36; } __attribute__((packed)); struct LargePackedBits large_packed = (struct LargePackedBits){ 0xcbbbbaaaa, 0xdffffeeee }; return 0; //// Set break point at this line. }