repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
php-src
php-src-master/ext/mysqlnd/mysqlnd_alloc.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_debug.h" #include "mysqlnd_wireprotocol.h" #include "mysqlnd_statistics.h" #define MYSQLND_DEBUG_MEMORY 1 static const char mysqlnd_emalloc_name[] = "_mysqlnd_emalloc"; static const char mysqlnd_pemalloc_name[] = "_mysqlnd_pemalloc"; static const char mysqlnd_ecalloc_name[] = "_mysqlnd_ecalloc"; static const char mysqlnd_pecalloc_name[] = "_mysqlnd_pecalloc"; static const char mysqlnd_erealloc_name[] = "_mysqlnd_erealloc"; static const char mysqlnd_perealloc_name[] = "_mysqlnd_perealloc"; static const char mysqlnd_efree_name[] = "_mysqlnd_efree"; static const char mysqlnd_pefree_name[] = "_mysqlnd_pefree"; static const char mysqlnd_pememdup_name[] = "_mysqlnd_pememdup"; static const char mysqlnd_pestrndup_name[] = "_mysqlnd_pestrndup"; static const char mysqlnd_pestrdup_name[] = "_mysqlnd_pestrdup"; PHPAPI const char * mysqlnd_debug_std_no_trace_funcs[] = { mysqlnd_emalloc_name, mysqlnd_ecalloc_name, mysqlnd_efree_name, mysqlnd_erealloc_name, mysqlnd_pemalloc_name, mysqlnd_pecalloc_name, mysqlnd_pefree_name, mysqlnd_perealloc_name, mysqlnd_pestrndup_name, mysqlnd_read_header_name, mysqlnd_read_body_name, NULL /* must be always last */ }; #if MYSQLND_DEBUG_MEMORY #if ZEND_DEBUG #else #define __zend_orig_filename "/unknown/unknown" #define __zend_orig_lineno 0 #endif #define EXTRA_SIZE ZEND_MM_ALIGNED_SIZE(sizeof(size_t)) #define REAL_SIZE(s) (collect_memory_statistics? (s) + EXTRA_SIZE : (s)) #define REAL_PTR(p) (collect_memory_statistics && (p)? (((char *)(p)) - EXTRA_SIZE) : (p)) #define FAKE_PTR(p) (collect_memory_statistics && (p)? (((char *)(p)) + EXTRA_SIZE) : (p)) /* {{{ _mysqlnd_emalloc */ static void * _mysqlnd_emalloc(size_t size MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_emalloc_name); ret = emalloc_rel(REAL_SIZE(size)); TRACE_ALLOC_INF_FMT("size=%zu ptr=%p", size, ret); if (collect_memory_statistics) { *(size_t *) ret = size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(STAT_MEM_EMALLOC_COUNT, 1, STAT_MEM_EMALLOC_AMOUNT, size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_pemalloc */ static void * _mysqlnd_pemalloc(size_t size, bool persistent MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pemalloc_name); ret = pemalloc_rel(REAL_SIZE(size), persistent); TRACE_ALLOC_INF_FMT("size=%zu ptr=%p persistent=%u", size, ret, persistent); if (collect_memory_statistics) { enum mysqlnd_collected_stats s1 = persistent? STAT_MEM_MALLOC_COUNT:STAT_MEM_EMALLOC_COUNT; enum mysqlnd_collected_stats s2 = persistent? STAT_MEM_MALLOC_AMOUNT:STAT_MEM_EMALLOC_AMOUNT; *(size_t *) ret = size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(s1, 1, s2, size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_ecalloc */ static void * _mysqlnd_ecalloc(unsigned int nmemb, size_t size MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_ecalloc_name); TRACE_ALLOC_INF_FMT("before: %zu", zend_memory_usage(FALSE)); ret = ecalloc_rel(nmemb, REAL_SIZE(size)); TRACE_ALLOC_INF_FMT("after : %zu", zend_memory_usage(FALSE)); TRACE_ALLOC_INF_FMT("size=%zu ptr=%p", size, ret); if (collect_memory_statistics) { *(size_t *) ret = size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(STAT_MEM_ECALLOC_COUNT, 1, STAT_MEM_ECALLOC_AMOUNT, size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_pecalloc */ static void * _mysqlnd_pecalloc(unsigned int nmemb, size_t size, bool persistent MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pecalloc_name); ret = pecalloc_rel(nmemb, REAL_SIZE(size), persistent); TRACE_ALLOC_INF_FMT("size=%zu ptr=%p", size, ret); if (collect_memory_statistics) { enum mysqlnd_collected_stats s1 = persistent? STAT_MEM_CALLOC_COUNT:STAT_MEM_ECALLOC_COUNT; enum mysqlnd_collected_stats s2 = persistent? STAT_MEM_CALLOC_AMOUNT:STAT_MEM_ECALLOC_AMOUNT; *(size_t *) ret = size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(s1, 1, s2, size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_erealloc */ static void * _mysqlnd_erealloc(void *ptr, size_t new_size MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); size_t old_size = collect_memory_statistics && ptr? *(size_t *) (((char*)ptr) - sizeof(size_t)) : 0; TRACE_ALLOC_ENTER(mysqlnd_erealloc_name); TRACE_ALLOC_INF_FMT("ptr=%p old_size=%zu, new_size=%zu", ptr, old_size, new_size); ret = erealloc_rel(REAL_PTR(ptr), REAL_SIZE(new_size)); TRACE_ALLOC_INF_FMT("new_ptr=%p", (char*)ret); if (collect_memory_statistics) { *(size_t *) ret = new_size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(STAT_MEM_EREALLOC_COUNT, 1, STAT_MEM_EREALLOC_AMOUNT, new_size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_perealloc */ static void * _mysqlnd_perealloc(void *ptr, size_t new_size, bool persistent MYSQLND_MEM_D) { void *ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); size_t old_size = collect_memory_statistics && ptr? *(size_t *) (((char*)ptr) - sizeof(size_t)) : 0; TRACE_ALLOC_ENTER(mysqlnd_perealloc_name); TRACE_ALLOC_INF_FMT("ptr=%p old_size=%zu new_size=%zu persistent=%u", ptr, old_size, new_size, persistent); ret = perealloc_rel(REAL_PTR(ptr), REAL_SIZE(new_size), persistent); TRACE_ALLOC_INF_FMT("new_ptr=%p", (char*)ret); if (collect_memory_statistics) { enum mysqlnd_collected_stats s1 = persistent? STAT_MEM_REALLOC_COUNT:STAT_MEM_EREALLOC_COUNT; enum mysqlnd_collected_stats s2 = persistent? STAT_MEM_REALLOC_AMOUNT:STAT_MEM_EREALLOC_AMOUNT; *(size_t *) ret = new_size; MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(s1, 1, s2, new_size); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_efree */ static void _mysqlnd_efree(void *ptr MYSQLND_MEM_D) { size_t free_amount = 0; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_efree_name); #if PHP_DEBUG { char * fn = strrchr(__zend_filename, PHP_DIR_SEPARATOR); TRACE_ALLOC_INF_FMT("file=%-15s line=%4d", fn? fn + 1:__zend_filename, __zend_lineno); } #endif TRACE_ALLOC_INF_FMT("ptr=%p", ptr); if (ptr) { if (collect_memory_statistics) { free_amount = *(size_t *)(((char*)ptr) - sizeof(size_t)); TRACE_ALLOC_INF_FMT("ptr=%p size=%zu", ((char*)ptr) - sizeof(size_t), free_amount); } efree_rel(REAL_PTR(ptr)); } if (collect_memory_statistics) { MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(STAT_MEM_EFREE_COUNT, 1, STAT_MEM_EFREE_AMOUNT, free_amount); } TRACE_ALLOC_VOID_RETURN; } /* }}} */ /* {{{ _mysqlnd_pefree */ static void _mysqlnd_pefree(void *ptr, bool persistent MYSQLND_MEM_D) { size_t free_amount = 0; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pefree_name); #if PHP_DEBUG { char * fn = strrchr(__zend_filename, PHP_DIR_SEPARATOR); TRACE_ALLOC_INF_FMT("file=%-15s line=%4d", fn? fn + 1:__zend_filename, __zend_lineno); } #endif TRACE_ALLOC_INF_FMT("ptr=%p persistent=%u", ptr, persistent); if (ptr) { if (collect_memory_statistics) { free_amount = *(size_t *)(((char*)ptr) - sizeof(size_t)); TRACE_ALLOC_INF_FMT("ptr=%p size=%zu", ((char*)ptr) - sizeof(size_t), free_amount); } pefree_rel(REAL_PTR(ptr), persistent); } if (collect_memory_statistics) { MYSQLND_INC_GLOBAL_STATISTIC_W_VALUE2(persistent? STAT_MEM_FREE_COUNT:STAT_MEM_EFREE_COUNT, 1, persistent? STAT_MEM_FREE_AMOUNT:STAT_MEM_EFREE_AMOUNT, free_amount); } TRACE_ALLOC_VOID_RETURN; } /* }}} */ /* {{{ _mysqlnd_pememdup */ static char * _mysqlnd_pememdup(const char * const ptr, size_t length, bool persistent MYSQLND_MEM_D) { char * ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pememdup_name); #if PHP_DEBUG { char * fn = strrchr(__zend_filename, PHP_DIR_SEPARATOR); TRACE_ALLOC_INF_FMT("file=%-15s line=%4d", fn? fn + 1:__zend_filename, __zend_lineno); } #endif TRACE_ALLOC_INF_FMT("ptr=%p", ptr); ret = pemalloc_rel(REAL_SIZE(length + 1), persistent); { char * dest = (char *) FAKE_PTR(ret); memcpy(dest, ptr, length); } if (collect_memory_statistics) { *(size_t *) ret = length; MYSQLND_INC_GLOBAL_STATISTIC(persistent? STAT_MEM_DUP_COUNT : STAT_MEM_EDUP_COUNT); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ /* {{{ _mysqlnd_pestrndup */ static char * _mysqlnd_pestrndup(const char * const ptr, size_t length, bool persistent MYSQLND_MEM_D) { char * ret; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pestrndup_name); #if PHP_DEBUG { char * fn = strrchr(__zend_filename, PHP_DIR_SEPARATOR); TRACE_ALLOC_INF_FMT("file=%-15s line=%4d", fn? fn + 1:__zend_filename, __zend_lineno); } #endif TRACE_ALLOC_INF_FMT("ptr=%p", ptr); ret = pemalloc_rel(REAL_SIZE(length + 1), persistent); { size_t l = length; char * p = (char *) ptr; char * dest = (char *) FAKE_PTR(ret); while (*p && l--) { *dest++ = *p++; } *dest = '\0'; } if (collect_memory_statistics) { *(size_t *) ret = length; MYSQLND_INC_GLOBAL_STATISTIC(persistent? STAT_MEM_STRNDUP_COUNT : STAT_MEM_ESTRNDUP_COUNT); } TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ #define SMART_STR_START_SIZE 2048 #define SMART_STR_PREALLOC 512 #include "zend_smart_str.h" /* {{{ _mysqlnd_pestrdup */ static char * _mysqlnd_pestrdup(const char * const ptr, bool persistent MYSQLND_MEM_D) { char * ret; smart_str tmp_str = {0, 0}; const char * p = ptr; bool collect_memory_statistics = MYSQLND_G(collect_memory_statistics); TRACE_ALLOC_ENTER(mysqlnd_pestrdup_name); #if PHP_DEBUG { char * fn = strrchr(__zend_filename, PHP_DIR_SEPARATOR); TRACE_ALLOC_INF_FMT("file=%-15s line=%4d", fn? fn + 1:__zend_filename, __zend_lineno); } #endif TRACE_ALLOC_INF_FMT("ptr=%p", ptr); do { smart_str_appendc(&tmp_str, *p); } while (*p++); ret = pemalloc_rel(REAL_SIZE(ZSTR_LEN(tmp_str.s)), persistent); memcpy(FAKE_PTR(ret), ZSTR_VAL(tmp_str.s), ZSTR_LEN(tmp_str.s)); if (ret && collect_memory_statistics) { *(size_t *) ret = ZSTR_LEN(tmp_str.s); MYSQLND_INC_GLOBAL_STATISTIC(persistent? STAT_MEM_STRDUP_COUNT : STAT_MEM_ESTRDUP_COUNT); } smart_str_free(&tmp_str); TRACE_ALLOC_RETURN(FAKE_PTR(ret)); } /* }}} */ #else /* {{{ mysqlnd_zend_mm_emalloc */ static void * mysqlnd_zend_mm_emalloc(size_t size MYSQLND_MEM_D) { return emalloc_rel(size); } /* }}} */ /* {{{ mysqlnd_zend_mm_pemalloc */ static void * mysqlnd_zend_mm_pemalloc(size_t size, bool persistent MYSQLND_MEM_D) { return pemalloc_rel(size, persistent); } /* }}} */ /* {{{ mysqlnd_zend_mm_ecalloc */ static void * mysqlnd_zend_mm_ecalloc(unsigned int nmemb, size_t size MYSQLND_MEM_D) { return ecalloc_rel(nmemb, size); } /* }}} */ /* {{{ mysqlnd_zend_mm_pecalloc */ static void * mysqlnd_zend_mm_pecalloc(unsigned int nmemb, size_t size, bool persistent MYSQLND_MEM_D) { return pecalloc_rel(nmemb, size, persistent); } /* }}} */ /* {{{ mysqlnd_zend_mm_erealloc */ static void * mysqlnd_zend_mm_erealloc(void *ptr, size_t new_size MYSQLND_MEM_D) { return erealloc_rel(ptr, new_size); } /* }}} */ /* {{{ mysqlnd_zend_mm_perealloc */ static void * mysqlnd_zend_mm_perealloc(void *ptr, size_t new_size, bool persistent MYSQLND_MEM_D) { return perealloc_rel(ptr, new_size, persistent); } /* }}} */ /* {{{ mysqlnd_zend_mm_efree */ static void mysqlnd_zend_mm_efree(void * ptr MYSQLND_MEM_D) { efree_rel(ptr); } /* }}} */ /* {{{ mysqlnd_zend_mm_pefree */ static void mysqlnd_zend_mm_pefree(void * ptr, bool persistent MYSQLND_MEM_D) { pefree_rel(ptr, persistent); } /* }}} */ /* {{{ mysqlnd_zend_mm_pememdup */ static char * mysqlnd_zend_mm_pememdup(const char * const ptr, size_t length, bool persistent MYSQLND_MEM_D) { char * dest = pemalloc_rel(length, persistent); if (dest) { memcpy(dest, ptr, length); } return dest; } /* }}} */ /* {{{ mysqlnd_zend_mm_pestrndup */ static char * mysqlnd_zend_mm_pestrndup(const char * const ptr, size_t length, bool persistent MYSQLND_MEM_D) { return persistent? zend_strndup(ptr, length ) : estrndup_rel(ptr, length); } /* }}} */ /* {{{ mysqlnd_zend_mm_pestrdup */ static char * mysqlnd_zend_mm_pestrdup(const char * const ptr, bool persistent MYSQLND_MEM_D) { return pestrdup_rel(ptr, persistent); } /* }}} */ #endif /* MYSQLND_DEBUG_MEMORY */ PHPAPI struct st_mysqlnd_allocator_methods mysqlnd_allocator = { #if MYSQLND_DEBUG_MEMORY == 1 _mysqlnd_emalloc, _mysqlnd_pemalloc, _mysqlnd_ecalloc, _mysqlnd_pecalloc, _mysqlnd_erealloc, _mysqlnd_perealloc, _mysqlnd_efree, _mysqlnd_pefree, _mysqlnd_pememdup, _mysqlnd_pestrndup, _mysqlnd_pestrdup #else mysqlnd_zend_mm_emalloc, mysqlnd_zend_mm_pemalloc, mysqlnd_zend_mm_ecalloc, mysqlnd_zend_mm_pecalloc, mysqlnd_zend_mm_erealloc, mysqlnd_zend_mm_perealloc, mysqlnd_zend_mm_efree, mysqlnd_zend_mm_pefree, mysqlnd_zend_mm_pememdup, mysqlnd_zend_mm_pestrndup, mysqlnd_zend_mm_pestrdup #endif };
14,357
28.482546
110
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_alloc.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_ALLOC_H #define MYSQLND_ALLOC_H PHPAPI extern const char * mysqlnd_debug_std_no_trace_funcs[]; #define MYSQLND_MEM_D ZEND_FILE_LINE_DC #define MYSQLND_MEM_C ZEND_FILE_LINE_CC struct st_mysqlnd_allocator_methods { void * (*m_emalloc)(size_t size MYSQLND_MEM_D); void * (*m_pemalloc)(size_t size, bool persistent MYSQLND_MEM_D); void * (*m_ecalloc)(unsigned int nmemb, size_t size MYSQLND_MEM_D); void * (*m_pecalloc)(unsigned int nmemb, size_t size, bool persistent MYSQLND_MEM_D); void * (*m_erealloc)(void *ptr, size_t new_size MYSQLND_MEM_D); void * (*m_perealloc)(void *ptr, size_t new_size, bool persistent MYSQLND_MEM_D); void (*m_efree)(void *ptr MYSQLND_MEM_D); void (*m_pefree)(void *ptr, bool persistent MYSQLND_MEM_D); char * (*m_pememdup)(const char * const ptr, size_t size, bool persistent MYSQLND_MEM_D); char * (*m_pestrndup)(const char * const ptr, size_t size, bool persistent MYSQLND_MEM_D); char * (*m_pestrdup)(const char * const ptr, bool persistent MYSQLND_MEM_D); }; PHPAPI extern struct st_mysqlnd_allocator_methods mysqlnd_allocator; #define mnd_emalloc(size) mysqlnd_allocator.m_emalloc((size) MYSQLND_MEM_C) #define mnd_pemalloc(size, pers) mysqlnd_allocator.m_pemalloc((size), (pers) MYSQLND_MEM_C) #define mnd_ecalloc(nmemb, size) mysqlnd_allocator.m_ecalloc((nmemb), (size) MYSQLND_MEM_C) #define mnd_pecalloc(nmemb, size, p) mysqlnd_allocator.m_pecalloc((nmemb), (size), (p) MYSQLND_MEM_C) #define mnd_erealloc(ptr, new_size) mysqlnd_allocator.m_erealloc((ptr), (new_size) MYSQLND_MEM_C) #define mnd_perealloc(ptr, new_size, p) mysqlnd_allocator.m_perealloc((ptr), (new_size), (p) MYSQLND_MEM_C) #define mnd_efree(ptr) mysqlnd_allocator.m_efree((ptr) MYSQLND_MEM_C) #define mnd_pefree(ptr, pers) mysqlnd_allocator.m_pefree((ptr), (pers) MYSQLND_MEM_C) #define mnd_pememdup(ptr, size, pers) mysqlnd_allocator.m_pememdup((ptr), (size), (pers) MYSQLND_MEM_C) #define mnd_pestrndup(ptr, size, pers) mysqlnd_allocator.m_pestrndup((ptr), (size), (pers) MYSQLND_MEM_C) #define mnd_pestrdup(ptr, pers) mysqlnd_allocator.m_pestrdup((ptr), (pers) MYSQLND_MEM_C) #define mnd_sprintf(p, mx_len, fmt,...) spprintf((p), (mx_len), (fmt), __VA_ARGS__) #define mnd_vsprintf(p, mx_len, fmt,ap) vspprintf((p), (mx_len), (fmt), (ap)) #define mnd_sprintf_free(p) efree((p)) static inline MYSQLND_STRING mnd_dup_cstring(const MYSQLND_CSTRING str, const bool persistent) { const MYSQLND_STRING ret = {(char*) mnd_pemalloc(str.l + 1, persistent), str.l}; if (ret.s) { memcpy(ret.s, str.s, str.l); ret.s[str.l] = '\0'; } return ret; } static inline MYSQLND_CSTRING mnd_str2c(const MYSQLND_STRING str) { const MYSQLND_CSTRING ret = {str.s, str.l}; return ret; } static inline void mysqlnd_set_string(MYSQLND_STRING *buf, const char *string, size_t len) { if (buf->s) { mnd_efree(buf->s); buf->s = NULL; buf->l = 0; } if (string) { buf->s = mnd_pestrndup(string, len, 0); buf->l = len; } } static inline void mysqlnd_set_persistent_string(MYSQLND_STRING *buf, const char *string, size_t len, bool persistent) { if (buf->s) { mnd_pefree(buf->s, persistent); buf->s = NULL; buf->l = 0; } if (string) { buf->s = mnd_pestrndup(string, len, persistent); buf->l = len; } } #endif /* MYSQLND_ALLOC_H */
4,349
42.939394
120
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_block_alloc.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_block_alloc.h" #include "mysqlnd_debug.h" #include "mysqlnd_priv.h" /* {{{ mysqlnd_mempool_get_chunk */ static void * mysqlnd_mempool_get_chunk(MYSQLND_MEMORY_POOL * pool, size_t size) { DBG_ENTER("mysqlnd_mempool_get_chunk"); DBG_RETURN(zend_arena_alloc(&pool->arena, size)); } /* }}} */ /* {{{ mysqlnd_mempool_create */ PHPAPI MYSQLND_MEMORY_POOL * mysqlnd_mempool_create(size_t arena_size) { zend_arena * arena; MYSQLND_MEMORY_POOL * ret; DBG_ENTER("mysqlnd_mempool_create"); arena = zend_arena_create(MAX(arena_size, ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena)))); ret = zend_arena_alloc(&arena, sizeof(MYSQLND_MEMORY_POOL)); ret->arena = arena; ret->checkpoint = NULL; ret->get_chunk = mysqlnd_mempool_get_chunk; DBG_RETURN(ret); } /* }}} */ /* {{{ mysqlnd_mempool_destroy */ PHPAPI void mysqlnd_mempool_destroy(MYSQLND_MEMORY_POOL * pool) { DBG_ENTER("mysqlnd_mempool_destroy"); /* mnd_free will reference LOCK_access and might crash, depending on the caller...*/ zend_arena_destroy(pool->arena); DBG_VOID_RETURN; } /* }}} */ /* {{{ mysqlnd_mempool_save_state */ PHPAPI void mysqlnd_mempool_save_state(MYSQLND_MEMORY_POOL * pool) { DBG_ENTER("mysqlnd_mempool_save_state"); pool->checkpoint = zend_arena_checkpoint(pool->arena); DBG_VOID_RETURN; } /* }}} */ /* {{{ mysqlnd_mempool_restore_state */ PHPAPI void mysqlnd_mempool_restore_state(MYSQLND_MEMORY_POOL * pool) { DBG_ENTER("mysqlnd_mempool_restore_state"); #if ZEND_DEBUG ZEND_ASSERT(pool->checkpoint); #endif if (pool->checkpoint) { zend_arena_release(&pool->arena, pool->checkpoint); pool->checkpoint = NULL; } DBG_VOID_RETURN; } /* }}} */
2,823
30.730337
86
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_block_alloc.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_BLOCK_ALLOC_H #define MYSQLND_BLOCK_ALLOC_H PHPAPI MYSQLND_MEMORY_POOL * mysqlnd_mempool_create(size_t arena_size); PHPAPI void mysqlnd_mempool_destroy(MYSQLND_MEMORY_POOL * pool); PHPAPI void mysqlnd_mempool_save_state(MYSQLND_MEMORY_POOL * pool); PHPAPI void mysqlnd_mempool_restore_state(MYSQLND_MEMORY_POOL * pool); #endif /* MYSQLND_BLOCK_ALLOC_H */
1,445
52.555556
75
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_commands.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_COMMANDS_H #define MYSQLND_COMMANDS_H //extern func_mysqlnd__run_command mysqlnd_run_command; #endif /* MYSQLND_COMMANDS_H */
1,201
49.083333
74
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_connection.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_CONNECTION_H #define MYSQLND_CONNECTION_H PHPAPI extern const char * const mysqlnd_out_of_sync; PHPAPI extern const char * const mysqlnd_server_gone; PHPAPI extern const char * const mysqlnd_out_of_memory; void mysqlnd_upsert_status_init(MYSQLND_UPSERT_STATUS * const upsert_status); #define UPSERT_STATUS_RESET(status) (status)->m->reset((status)) #define UPSERT_STATUS_GET_SERVER_STATUS(status) (status)->server_status #define UPSERT_STATUS_SET_SERVER_STATUS(status, server_st) (status)->server_status = (server_st) #define UPSERT_STATUS_GET_WARNINGS(status) (status)->warning_count #define UPSERT_STATUS_SET_WARNINGS(status, warnings) (status)->warning_count = (warnings) #define UPSERT_STATUS_GET_AFFECTED_ROWS(status) (status)->affected_rows #define UPSERT_STATUS_SET_AFFECTED_ROWS(status, rows) (status)->affected_rows = (rows) #define UPSERT_STATUS_SET_AFFECTED_ROWS_TO_ERROR(status) (status)->m->set_affected_rows_to_error((status)) #define UPSERT_STATUS_GET_LAST_INSERT_ID(status) (status)->last_insert_id #define UPSERT_STATUS_SET_LAST_INSERT_ID(status, id) (status)->last_insert_id = (id) PHPAPI void mysqlnd_error_info_init(MYSQLND_ERROR_INFO * const info, const bool persistent); PHPAPI void mysqlnd_error_info_free_contents(MYSQLND_ERROR_INFO * const info); #define GET_CONNECTION_STATE(state_struct) (state_struct)->m->get((state_struct)) #define SET_CONNECTION_STATE(state_struct, s) (state_struct)->m->set((state_struct), (s)) PHPAPI void mysqlnd_connection_state_init(struct st_mysqlnd_connection_state * const state); #endif /* MYSQLND_CONNECTION_H */
2,678
50.519231
106
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_ext_plugin.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Johannes Schlüter <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_result.h" #include "mysqlnd_debug.h" #include "mysqlnd_commands.h" #include "mysqlnd_ext_plugin.h" static struct st_mysqlnd_conn_methods * mysqlnd_conn_methods; static struct st_mysqlnd_conn_data_methods * mysqlnd_conn_data_methods; static struct st_mysqlnd_stmt_methods * mysqlnd_stmt_methods; /* {{{ mysqlnd_plugin__get_plugin_connection_data */ static void ** mysqlnd_plugin__get_plugin_connection_data(const MYSQLND * conn, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_connection_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!conn || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)conn + sizeof(MYSQLND) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_connection_data_data */ static void ** mysqlnd_plugin__get_plugin_connection_data_data(const MYSQLND_CONN_DATA * conn, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_connection_data_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!conn || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)conn + sizeof(MYSQLND_CONN_DATA) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_result_data */ static void ** mysqlnd_plugin__get_plugin_result_data(const MYSQLND_RES * result, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_result_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!result || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)result + sizeof(MYSQLND_RES) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ _mysqlnd_plugin__get_plugin_result_unbuffered_data */ static void ** mysqlnd_plugin__get_plugin_result_unbuffered_data(const MYSQLND_RES_UNBUFFERED * result, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_result_unbuffered_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!result || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)result + sizeof(MYSQLND_RES_UNBUFFERED) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_result_buffered_data */ static void ** mysqlnd_plugin__get_plugin_result_buffered_data(const MYSQLND_RES_BUFFERED * result, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_result_buffered_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!result || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)result + sizeof(MYSQLND_RES_BUFFERED) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_protocol_data */ static void ** mysqlnd_plugin__get_plugin_protocol_data(const MYSQLND_PROTOCOL_PAYLOAD_DECODER_FACTORY * factory, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_protocol_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!factory || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)factory + sizeof(MYSQLND_PROTOCOL_PAYLOAD_DECODER_FACTORY) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_stmt_data */ static void ** mysqlnd_plugin__get_plugin_stmt_data(const MYSQLND_STMT * stmt, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_stmt_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!stmt || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)stmt + sizeof(MYSQLND_STMT) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ mysqlnd_plugin__get_plugin_pfc_data */ static void ** mysqlnd_plugin__get_plugin_pfc_data(const MYSQLND_PFC * pfc, const unsigned int plugin_id) { DBG_ENTER("mysqlnd_plugin__get_plugin_pfc_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!pfc || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)pfc + sizeof(MYSQLND_PFC) + plugin_id * sizeof(void *))); } /* }}} */ /* {{{ _mysqlnd_plugin__get_plugin_vio_data */ static void ** mysqlnd_plugin__get_plugin_vio_data(const MYSQLND_VIO * vio, const unsigned int plugin_id) { DBG_ENTER("_mysqlnd_plugin__get_plugin_vio_data"); DBG_INF_FMT("plugin_id=%u", plugin_id); if (!vio || plugin_id >= mysqlnd_plugin_count()) { return NULL; } DBG_RETURN((void *)((char *)vio + sizeof(MYSQLND_VIO) + plugin_id * sizeof(void *))); } /* }}} */ struct st_mysqlnd_plugin__plugin_area_getters mysqlnd_plugin_area_getters = { mysqlnd_plugin__get_plugin_connection_data, mysqlnd_plugin__get_plugin_connection_data_data, mysqlnd_plugin__get_plugin_result_data, mysqlnd_plugin__get_plugin_result_unbuffered_data, mysqlnd_plugin__get_plugin_result_buffered_data, mysqlnd_plugin__get_plugin_stmt_data, mysqlnd_plugin__get_plugin_protocol_data, mysqlnd_plugin__get_plugin_pfc_data, mysqlnd_plugin__get_plugin_vio_data, }; /* {{{ _mysqlnd_object_factory_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_object_factory) * _mysqlnd_object_factory_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_object_factory); } /* }}} */ /* {{{ mysqlnd_conn_set_methods */ static void _mysqlnd_object_factory_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_object_factory) *methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_object_factory) = *methods; } /* }}} */ /* {{{ _mysqlnd_conn_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_conn) * _mysqlnd_conn_get_methods(void) { return mysqlnd_conn_methods; } /* }}} */ /* {{{ _mysqlnd_conn_set_methods */ static void _mysqlnd_conn_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_conn) *methods) { mysqlnd_conn_methods = methods; } /* }}} */ /* {{{ _mysqlnd_conn_data_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_conn_data) * _mysqlnd_conn_data_get_methods(void) { return mysqlnd_conn_data_methods; } /* }}} */ /* {{{ _mysqlnd_conn_data_set_methods */ static void _mysqlnd_conn_data_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_conn_data) * methods) { mysqlnd_conn_data_methods = methods; } /* }}} */ /* {{{ _mysqlnd_result_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_res) * _mysqlnd_result_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_res); } /* }}} */ /* {{{ _mysqlnd_result_set_methods */ static void _mysqlnd_result_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_res) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_res) = *methods; } /* }}} */ /* {{{ _mysqlnd_result_unbuffered_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_result_unbuffered) * _mysqlnd_result_unbuffered_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_result_unbuffered); } /* }}} */ /* {{{ _mysqlnd_result_unbuffered_set_methods */ static void _mysqlnd_result_unbuffered_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_result_unbuffered) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_result_unbuffered) = *methods; } /* }}} */ /* {{{ _mysqlnd_result_buffered_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_result_buffered) * _mysqlnd_result_buffered_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_result_buffered); } /* }}} */ /* {{{ _mysqlnd_result_buffered_set_methods */ static void _mysqlnd_result_buffered_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_result_buffered) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_result_buffered) = *methods; } /* }}} */ /* {{{ _mysqlnd_stmt_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_stmt) * _mysqlnd_stmt_get_methods(void) { return mysqlnd_stmt_methods; } /* }}} */ /* {{{ _mysqlnd_stmt_set_methods */ static void _mysqlnd_stmt_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_stmt) *methods) { mysqlnd_stmt_methods = methods; } /* }}} */ /* {{{ _mysqlnd_protocol_payload_decoder_factory_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_protocol_payload_decoder_factory) * _mysqlnd_protocol_payload_decoder_factory_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_protocol_payload_decoder_factory); } /* }}} */ /* {{{ _mysqlnd_protocol_payload_decoder_factory_set_methods */ static void _mysqlnd_protocol_payload_decoder_factory_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_protocol_payload_decoder_factory) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_protocol_payload_decoder_factory) = *methods; } /* }}} */ /* {{{ _mysqlnd_pfc_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_protocol_packet_frame_codec) * _mysqlnd_pfc_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_protocol_packet_frame_codec); } /* }}} */ /* {{{ _mysqlnd_pfc_set_methods */ static void _mysqlnd_pfc_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_protocol_packet_frame_codec) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_protocol_packet_frame_codec) = *methods; } /* }}} */ /* {{{ _mysqlnd_vio_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_vio) * _mysqlnd_vio_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_vio); } /* }}} */ /* {{{ _mysqlnd_vio_set_methods */ static void _mysqlnd_vio_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_vio) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_vio) = *methods; } /* }}} */ /* {{{ mysqlnd_command_factory_get */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_command) * _mysqlnd_command_factory_get(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_command); } /* }}} */ /* {{{ mysqlnd_command_factory_set */ static void _mysqlnd_command_factory_set(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_command) * methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_command) = *methods; } /* }}} */ /* {{{ _mysqlnd_error_info_get_methods */ static MYSQLND_CLASS_METHODS_TYPE(mysqlnd_error_info) * _mysqlnd_error_info_get_methods(void) { return &MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_error_info); } /* }}} */ /* {{{ _mysqlnd_error_info_set_methods */ static void _mysqlnd_error_info_set_methods(MYSQLND_CLASS_METHODS_TYPE(mysqlnd_error_info) *methods) { MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_error_info) = *methods; } /* }}} */ struct st_mysqlnd_plugin_methods_xetters mysqlnd_plugin_methods_xetters = { { _mysqlnd_object_factory_get_methods, _mysqlnd_object_factory_set_methods }, { _mysqlnd_conn_get_methods, _mysqlnd_conn_set_methods, }, { _mysqlnd_conn_data_get_methods, _mysqlnd_conn_data_set_methods, }, { _mysqlnd_result_get_methods, _mysqlnd_result_set_methods, }, { _mysqlnd_result_unbuffered_get_methods, _mysqlnd_result_unbuffered_set_methods, }, { _mysqlnd_result_buffered_get_methods, _mysqlnd_result_buffered_set_methods, }, { _mysqlnd_stmt_get_methods, _mysqlnd_stmt_set_methods, }, { _mysqlnd_protocol_payload_decoder_factory_get_methods, _mysqlnd_protocol_payload_decoder_factory_set_methods, }, { _mysqlnd_pfc_get_methods, _mysqlnd_pfc_set_methods, }, { _mysqlnd_vio_get_methods, _mysqlnd_vio_set_methods, }, { _mysqlnd_error_info_get_methods, _mysqlnd_error_info_set_methods, }, { _mysqlnd_command_factory_get, _mysqlnd_command_factory_set, }, };
12,277
27.290323
133
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_libmysql_compat.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | | Georg Richter <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_LIBMYSQL_COMPAT_H #define MYSQLND_LIBMYSQL_COMPAT_H /* Global types and definitions*/ #define MYSQL_NO_DATA MYSQLND_NO_DATA #define MYSQL_DATA_TRUNCATED MYSQLND_DATA_TRUNCATED #define MYSQL_STMT MYSQLND_STMT #define MYSQL_FIELD MYSQLND_FIELD #define MYSQL_RES MYSQLND_RES #define MYSQL_ROW MYSQLND_ROW_C #define MYSQL MYSQLND #define my_bool bool #define my_ulonglong uint64_t #define MYSQL_VERSION_ID MYSQLND_VERSION_ID #define MYSQL_SERVER_VERSION PHP_MYSQLND_VERSION #define MYSQL_ERRMSG_SIZE MYSQLND_ERRMSG_SIZE #define SQLSTATE_LENGTH MYSQLND_SQLSTATE_LENGTH /* functions */ #define mysql_affected_rows(r) mysqlnd_affected_rows((r)) #define mysql_autocommit(r,m) mysqlnd_autocommit((r),(m)) #define mysql_change_user(r,a,b,c) mysqlnd_change_user((r), (a), (b), (c), false) #define mysql_character_set_name(c) mysqlnd_character_set_name((c)) #define mysql_close(r) mysqlnd_close((r), MYSQLND_CLOSE_EXPLICIT) #define mysql_commit(r) mysqlnd_commit((r), TRANS_COR_NO_OPT, NULL) #define mysql_data_seek(r,o) mysqlnd_data_seek((r),(o)) #define mysql_debug(x) mysqlnd_debug((x)) #define mysql_dump_debug_info(r) mysqlnd_dump_debug_info((r)) #define mysql_errno(r) mysqlnd_errno((r)) #define mysql_error(r) mysqlnd_error((r)) #define mysql_escape_string(a,b,c) mysqlnd_escape_string((a), (b), (c)) #define mysql_fetch_field(r) mysqlnd_fetch_field((r)) #define mysql_fetch_field_direct(r,o) mysqlnd_fetch_field_direct((r), (o)) #define mysql_fetch_fields(r) mysqlnd_fetch_fields((r)) #define mysql_fetch_lengths(r) mysqlnd_fetch_lengths((r)) #define mysql_fetch_row(r) mysqlnd_fetch_row_c((r)) #define mysql_field_count(r) mysqlnd_field_count((r)) #define mysql_field_seek(r,o) mysqlnd_field_seek((r), (o)) #define mysql_field_tell(r) mysqlnd_field_tell((r)) #define mysql_init(a) mysqlnd_connection_init((a), false) #define mysql_insert_id(r) mysqlnd_insert_id((r)) #define mysql_kill(r,n) mysqlnd_kill((r), (n)) #define mysql_list_dbs(c, wild) mysqlnd_list_dbs((c), (wild)) #define mysql_list_processes(c) mysqlnd_list_processes((c)) #define mysql_list_tables(c, wild) mysqlnd_list_tables((c), (wild)) #define mysql_more_results(r) mysqlnd_more_results((r)) #define mysql_next_result(r) mysqlnd_next_result((r)) #define mysql_num_fields(r) mysqlnd_num_fields((r)) #define mysql_num_rows(r) mysqlnd_num_rows((r)) #define mysql_ping(r) mysqlnd_ping((r)) #define mysql_real_escape_string(r,a,b,c) mysqlnd_real_escape_string((r), (a), (b), (c)) #define mysql_real_query(r,a,b) mysqlnd_query((r), (a), (b)) #define mysql_refresh(conn, options) mysqlnd_refresh((conn), (options)) #define mysql_rollback(r) mysqlnd_rollback((r), TRANS_COR_NO_OPT, NULL) #define mysql_select_db(r,a) mysqlnd_select_db((r), (a) ,strlen((a))) #define mysql_set_server_option(r,o) mysqlnd_set_server_option((r), (o)) #define mysql_set_character_set(r,a) mysqlnd_set_character_set((r), (a)) #define mysql_sqlstate(r) mysqlnd_sqlstate((r)) #define mysql_ssl_set(c,key,cert,ca,capath,cipher) mysqlnd_ssl_set((c), (key), (cert), (ca), (capath), (cipher)) #define mysql_stmt_affected_rows(s) mysqlnd_stmt_affected_rows((s)) #define mysql_stmt_field_count(s) mysqlnd_stmt_field_count((s)) #define mysql_stmt_param_count(s) mysqlnd_stmt_param_count((s)) #define mysql_stmt_num_rows(s) mysqlnd_stmt_num_rows((s)) #define mysql_stmt_insert_id(s) mysqlnd_stmt_insert_id((s)) #define mysql_stmt_close(s) mysqlnd_stmt_close((s), 0) #define mysql_stmt_bind_param(s,b) mysqlnd_stmt_bind_param((s), (b)) #define mysql_stmt_bind_result(s,b) mysqlnd_stmt_bind_result((s), (b)) #define mysql_stmt_errno(s) mysqlnd_stmt_errno((s)) #define mysql_stmt_error(s) mysqlnd_stmt_error((s)) #define mysql_stmt_sqlstate(s) mysqlnd_stmt_sqlstate((s)) #define mysql_stmt_prepare(s,q,l) mysqlnd_stmt_prepare((s), (q), (l)) #define mysql_stmt_execute(s) mysqlnd_stmt_execute((s)) #define mysql_stmt_reset(s) mysqlnd_stmt_reset((s)) #define mysql_stmt_store_result(s) mysqlnd_stmt_store_result((s)) #define mysql_stmt_free_result(s) mysqlnd_stmt_free_result((s)) #define mysql_stmt_data_seek(s,r) mysqlnd_stmt_data_seek((s), (r)) #define mysql_stmt_send_long_data(s,p,d,l) mysqlnd_stmt_send_long_data((s), (p), (d), (l)) #define mysql_stmt_attr_get(s,a,v) mysqlnd_stmt_attr_get((s), (a), (v)) #define mysql_stmt_attr_set(s,a,v) mysqlnd_stmt_attr_set((s), (a), (v)) #define mysql_stmt_result_metadata(s) mysqlnd_stmt_result_metadata((s)) #define mysql_stmt_next_result(s) mysqlnd_stmt_next_result((s)) #define mysql_stmt_more_results(s) mysqlnd_stmt_more_results((s)) #define mysql_thread_safe() mysqlnd_thread_safe() #define mysql_info(r) mysqlnd_info((r)) #define mysql_options(c,a,v) mysqlnd_options((c), (a), (v)) #define mysql_options4(c,a,k,v) mysqlnd_options4((c), (a), (k), (v)) #define mysql_stmt_init(r) mysqlnd_stmt_init((r)) #define mysql_free_result(r) mysqlnd_free_result((r), false) #define mysql_store_result(r) mysqlnd_store_result((r)) #define mysql_use_result(r) mysqlnd_use_result((r)) #define mysql_async_store_result(r) mysqlnd_async_store_result((r)) #define mysql_thread_id(r) mysqlnd_thread_id((r)) #define mysql_get_client_info() mysqlnd_get_client_info() #define mysql_get_client_version() mysqlnd_get_client_version() #define mysql_get_host_info(r) mysqlnd_get_host_info((r)) #define mysql_get_proto_info(r) mysqlnd_get_proto_info((r)) #define mysql_get_server_info(r) mysqlnd_get_server_info((r)) #define mysql_get_server_version(r) mysqlnd_get_server_version((r)) #define mysql_warning_count(r) mysqlnd_warning_count((r)) #define mysql_eof(r) (((r)->unbuf && (r)->unbuf->eof_reached) || (r)->stored_data) #define REFRESH_GRANT MYSQLND_REFRESH_GRANT #define REFRESH_LOG MYSQLND_REFRESH_LOG #define REFRESH_TABLES MYSQLND_REFRESH_TABLES #define REFRESH_HOSTS MYSQLND_REFRESH_HOSTS #define REFRESH_STATUS MYSQLND_REFRESH_STATUS #define REFRESH_THREADS MYSQLND_REFRESH_THREADS #define REFRESH_SLAVE MYSQLND_REFRESH_SLAVE #define REFRESH_REPLICA MYSQLND_REFRESH_REPLICA #define REFRESH_MASTER MYSQLND_REFRESH_MASTER #define REFRESH_BACKUP_LOG MYSQLND_REFRESH_BACKUP_LOG #endif /* MYSQLND_LIBMYSQL_COMPAT_H */
7,420
55.219697
112
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_loaddata.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | | Georg Richter <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_wireprotocol.h" #include "mysqlnd_priv.h" #include "mysqlnd_debug.h" /* {{{ mysqlnd_local_infile_init */ static int mysqlnd_local_infile_init(void ** ptr, const char * const filename) { MYSQLND_INFILE_INFO *info; php_stream_context *context = NULL; DBG_ENTER("mysqlnd_local_infile_init"); info = ((MYSQLND_INFILE_INFO *)mnd_ecalloc(1, sizeof(MYSQLND_INFILE_INFO))); if (!info) { DBG_RETURN(1); } *ptr = info; /* check open_basedir */ if (PG(open_basedir)) { if (php_check_open_basedir_ex(filename, 0) == -1) { strcpy(info->error_msg, "open_basedir restriction in effect. Unable to open file"); info->error_no = CR_UNKNOWN_ERROR; DBG_RETURN(1); } } info->filename = filename; info->fd = php_stream_open_wrapper_ex((char *)filename, "r", 0, NULL, context); if (info->fd == NULL) { snprintf((char *)info->error_msg, sizeof(info->error_msg), "Can't find file '%-.64s'.", filename); info->error_no = MYSQLND_EE_FILENOTFOUND; DBG_RETURN(1); } DBG_RETURN(0); } /* }}} */ /* {{{ mysqlnd_local_infile_read */ static int mysqlnd_local_infile_read(void * ptr, zend_uchar * buf, unsigned int buf_len) { MYSQLND_INFILE_INFO *info = (MYSQLND_INFILE_INFO *)ptr; int count; DBG_ENTER("mysqlnd_local_infile_read"); count = (int) php_stream_read(info->fd, (char *) buf, buf_len); if (count < 0) { strcpy(info->error_msg, "Error reading file"); info->error_no = CR_UNKNOWN_ERROR; } DBG_RETURN(count); } /* }}} */ /* {{{ mysqlnd_local_infile_error */ static int mysqlnd_local_infile_error(void * ptr, char *error_buf, unsigned int error_buf_len) { MYSQLND_INFILE_INFO *info = (MYSQLND_INFILE_INFO *)ptr; DBG_ENTER("mysqlnd_local_infile_error"); if (info) { strlcpy(error_buf, info->error_msg, error_buf_len); DBG_INF_FMT("have info, %d", info->error_no); DBG_RETURN(info->error_no); } strlcpy(error_buf, "Unknown error", error_buf_len); DBG_INF_FMT("no info, %d", CR_UNKNOWN_ERROR); DBG_RETURN(CR_UNKNOWN_ERROR); } /* }}} */ /* {{{ mysqlnd_local_infile_end */ static void mysqlnd_local_infile_end(void * ptr) { MYSQLND_INFILE_INFO *info = (MYSQLND_INFILE_INFO *)ptr; if (info) { /* php_stream_close segfaults on NULL */ if (info->fd) { php_stream_close(info->fd); info->fd = NULL; } mnd_efree(info); } } /* }}} */ /* {{{ mysqlnd_local_infile_default */ PHPAPI void mysqlnd_local_infile_default(MYSQLND_CONN_DATA * conn) { conn->infile.local_infile_init = mysqlnd_local_infile_init; conn->infile.local_infile_read = mysqlnd_local_infile_read; conn->infile.local_infile_error = mysqlnd_local_infile_error; conn->infile.local_infile_end = mysqlnd_local_infile_end; } /* }}} */ static const char *lost_conn = "Lost connection to MySQL server during LOAD DATA of a local file"; /* {{{ mysqlnd_handle_local_infile */ enum_func_status mysqlnd_handle_local_infile(MYSQLND_CONN_DATA * conn, const char * const filename, bool * is_warning) { zend_uchar *buf = NULL; zend_uchar empty_packet[MYSQLND_HEADER_SIZE]; enum_func_status result = FAIL; unsigned int buflen = 4096; void *info = NULL; int bufsize; size_t ret; MYSQLND_INFILE infile; MYSQLND_PFC * net = conn->protocol_frame_codec; MYSQLND_VIO * vio = conn->vio; bool is_local_infile_enabled = (conn->options->flags & CLIENT_LOCAL_FILES) == CLIENT_LOCAL_FILES; const char* local_infile_directory = conn->options->local_infile_directory; bool is_local_infile_dir_set = local_infile_directory != NULL; bool prerequisities_ok = TRUE; DBG_ENTER("mysqlnd_handle_local_infile"); /* if local_infile is disabled, and local_infile_dir is not set, then operation is forbidden */ if (!is_local_infile_enabled && !is_local_infile_dir_set) { SET_CLIENT_ERROR(conn->error_info, CR_LOAD_DATA_LOCAL_INFILE_REJECTED, UNKNOWN_SQLSTATE, "LOAD DATA LOCAL INFILE is forbidden, check related settings like " "mysqli.allow_local_infile|mysqli.local_infile_directory or " "PDO::MYSQL_ATTR_LOCAL_INFILE|PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY"); prerequisities_ok = FALSE; } /* if local_infile_dir is set, then check whether it actually exists, and is accessible */ if (is_local_infile_dir_set) { php_stream *stream = php_stream_opendir(local_infile_directory, REPORT_ERRORS, NULL); if (stream) { php_stream_closedir(stream); } else { SET_CLIENT_ERROR(conn->error_info, CR_LOAD_DATA_LOCAL_INFILE_REJECTED, UNKNOWN_SQLSTATE, "cannot open local_infile_directory"); prerequisities_ok = FALSE; } } /* if local_infile is disabled and local_infile_dir is set, then we have to check whether filename is located inside its subtree but only in such a case, because when local_infile is enabled, then local_infile_dir is ignored */ if (prerequisities_ok && !is_local_infile_enabled && is_local_infile_dir_set) { if (php_check_specific_open_basedir(local_infile_directory, filename) == -1) { SET_CLIENT_ERROR(conn->error_info, CR_LOAD_DATA_LOCAL_INFILE_REJECTED, UNKNOWN_SQLSTATE, "LOAD DATA LOCAL INFILE DIRECTORY restriction in effect. Unable to open file"); prerequisities_ok = FALSE; } } if (!prerequisities_ok) { /* write empty packet to server */ ret = net->data->m.send(net, vio, empty_packet, 0, conn->stats, conn->error_info); *is_warning = TRUE; goto infile_error; } infile = conn->infile; /* allocate buffer for reading data */ buf = (zend_uchar *) mnd_ecalloc(1, buflen); *is_warning = FALSE; /* init handler: allocate read buffer and open file */ if (infile.local_infile_init(&info, (char *)filename)) { char tmp_buf[sizeof(conn->error_info->error)]; int tmp_error_no; *is_warning = TRUE; /* error occurred */ tmp_error_no = infile.local_infile_error(info, tmp_buf, sizeof(tmp_buf)); SET_CLIENT_ERROR(conn->error_info, tmp_error_no, UNKNOWN_SQLSTATE, tmp_buf); /* write empty packet to server */ ret = net->data->m.send(net, vio, empty_packet, 0, conn->stats, conn->error_info); goto infile_error; } /* read data */ while ((bufsize = infile.local_infile_read (info, buf + MYSQLND_HEADER_SIZE, buflen - MYSQLND_HEADER_SIZE)) > 0) { if ((ret = net->data->m.send(net, vio, buf, bufsize, conn->stats, conn->error_info)) == 0) { DBG_ERR_FMT("Error during read : %d %s %s", CR_SERVER_LOST, UNKNOWN_SQLSTATE, lost_conn); SET_CLIENT_ERROR(conn->error_info, CR_SERVER_LOST, UNKNOWN_SQLSTATE, lost_conn); goto infile_error; } } /* send empty packet for eof */ if ((ret = net->data->m.send(net, vio, empty_packet, 0, conn->stats, conn->error_info)) == 0) { SET_CLIENT_ERROR(conn->error_info, CR_SERVER_LOST, UNKNOWN_SQLSTATE, lost_conn); goto infile_error; } /* error during read occurred */ if (bufsize < 0) { char tmp_buf[sizeof(conn->error_info->error)]; int tmp_error_no; *is_warning = TRUE; DBG_ERR_FMT("Bufsize < 0, warning, %d %s %s", CR_SERVER_LOST, UNKNOWN_SQLSTATE, lost_conn); tmp_error_no = infile.local_infile_error(info, tmp_buf, sizeof(tmp_buf)); SET_CLIENT_ERROR(conn->error_info, tmp_error_no, UNKNOWN_SQLSTATE, tmp_buf); goto infile_error; } result = PASS; infile_error: /* get response from server and update upsert values */ if (FAIL == conn->payload_decoder_factory->m.send_command_handle_response( conn->payload_decoder_factory, PROT_OK_PACKET, FALSE, COM_QUERY, FALSE, conn->error_info, conn->upsert_status, &conn->last_message)) { result = FAIL; } (*conn->infile.local_infile_end)(info); if (buf) { mnd_efree(buf); } DBG_INF_FMT("%s", result == PASS? "PASS":"FAIL"); DBG_RETURN(result); } /* }}} */
8,791
31.684015
130
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_plugin.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_statistics.h" #include "mysqlnd_debug.h" /*--------------------------------------------------------------------*/ #if MYSQLND_DBG_ENABLED == 1 static enum_func_status mysqlnd_example_plugin_end(void * p); static MYSQLND_STATS * mysqlnd_plugin_example_stats = NULL; enum mysqlnd_plugin_example_collected_stats { EXAMPLE_STAT1, EXAMPLE_STAT2, EXAMPLE_STAT_LAST }; static const MYSQLND_STRING mysqlnd_plugin_example_stats_values_names[EXAMPLE_STAT_LAST] = { { MYSQLND_STR_W_LEN("stat1") }, { MYSQLND_STR_W_LEN("stat2") } }; static struct st_mysqlnd_typeii_plugin_example mysqlnd_example_plugin = { { MYSQLND_PLUGIN_API_VERSION, "example", 10001L, "1.00.01", "PHP License", "Andrey Hristov <[email protected]>", { NULL, /* will be filled later */ mysqlnd_plugin_example_stats_values_names, }, { mysqlnd_example_plugin_end } }, NULL, /* methods */ 0 }; /* {{{ mysqlnd_example_plugin_end */ static enum_func_status mysqlnd_example_plugin_end(void * p) { struct st_mysqlnd_typeii_plugin_example * plugin = (struct st_mysqlnd_typeii_plugin_example *) p; DBG_ENTER("mysqlnd_example_plugin_end"); mysqlnd_stats_end(plugin->plugin_header.plugin_stats.values, 1); plugin->plugin_header.plugin_stats.values = NULL; DBG_RETURN(PASS); } /* }}} */ /* {{{ mysqlnd_example_plugin_register */ void mysqlnd_example_plugin_register(void) { mysqlnd_stats_init(&mysqlnd_plugin_example_stats, EXAMPLE_STAT_LAST, 1); mysqlnd_example_plugin.plugin_header.plugin_stats.values = mysqlnd_plugin_example_stats; mysqlnd_plugin_register_ex((struct st_mysqlnd_plugin_header *) &mysqlnd_example_plugin); } /* }}} */ #endif /* MYSQLND_DBG_ENABLED == 1 */ /*--------------------------------------------------------------------*/ static HashTable mysqlnd_registered_plugins; static unsigned int mysqlnd_plugins_counter = 0; /* {{{ mysqlnd_plugin_subsystem_init */ void mysqlnd_plugin_subsystem_init(void) { zend_hash_init(&mysqlnd_registered_plugins, 4 /* initial hash size */, NULL /* hash_func */, NULL /* dtor */, TRUE /* pers */); } /* }}} */ /* {{{ mysqlnd_plugin_end_apply_func */ int mysqlnd_plugin_end_apply_func(zval *el) { struct st_mysqlnd_plugin_header * plugin_header = (struct st_mysqlnd_plugin_header *)Z_PTR_P(el); if (plugin_header->m.plugin_shutdown) { plugin_header->m.plugin_shutdown(plugin_header); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ mysqlnd_plugin_subsystem_end */ void mysqlnd_plugin_subsystem_end(void) { zend_hash_apply(&mysqlnd_registered_plugins, mysqlnd_plugin_end_apply_func); zend_hash_destroy(&mysqlnd_registered_plugins); } /* }}} */ /* {{{ mysqlnd_plugin_register */ PHPAPI unsigned int mysqlnd_plugin_register(void) { return mysqlnd_plugin_register_ex(NULL); } /* }}} */ /* {{{ mysqlnd_plugin_register_ex */ PHPAPI unsigned int mysqlnd_plugin_register_ex(struct st_mysqlnd_plugin_header * plugin) { if (plugin) { if (plugin->plugin_api_version == MYSQLND_PLUGIN_API_VERSION) { zend_hash_str_update_ptr(&mysqlnd_registered_plugins, plugin->plugin_name, strlen(plugin->plugin_name), plugin); } else { php_error_docref(NULL, E_WARNING, "Plugin API version mismatch while loading plugin %s. Expected %d, got %d", plugin->plugin_name, MYSQLND_PLUGIN_API_VERSION, plugin->plugin_api_version); return 0xCAFE; } } return mysqlnd_plugins_counter++; } /* }}} */ /* {{{ mysqlnd_plugin_find */ PHPAPI void * mysqlnd_plugin_find(const char * const name) { void * plugin; if ((plugin = zend_hash_str_find_ptr(&mysqlnd_registered_plugins, name, strlen(name))) != NULL) { return plugin; } return NULL; } /* }}} */ /* {{{ mysqlnd_plugin_apply_with_argument */ PHPAPI void mysqlnd_plugin_apply_with_argument(apply_func_arg_t apply_func, void * argument) { zval *val; int result; ZEND_HASH_MAP_FOREACH_VAL(&mysqlnd_registered_plugins, val) { result = apply_func(val, argument); if (result & ZEND_HASH_APPLY_REMOVE) { php_error_docref(NULL, E_WARNING, "mysqlnd_plugin_apply_with_argument must not remove table entries"); } if (result & ZEND_HASH_APPLY_STOP) { break; } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ mysqlnd_plugin_count */ PHPAPI unsigned int mysqlnd_plugin_count(void) { return mysqlnd_plugins_counter; } /* }}} */
5,398
27.566138
128
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_plugin.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_PLUGIN_H #define MYSQLND_PLUGIN_H void mysqlnd_plugin_subsystem_init(void); void mysqlnd_plugin_subsystem_end(void); void mysqlnd_register_builtin_authentication_plugins(void); void mysqlnd_example_plugin_register(void); #endif /* MYSQLND_PLUGIN_H */
1,329
43.333333
74
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_portability.h
/* Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB This file is public domain and comes with NO WARRANTY of any kind */ /* Parts of the original, which are not applicable to mysqlnd have been removed. With small modifications, mostly casting but adding few more macros by Andrey Hristov <[email protected]> . The additions are in the public domain and were added to improve the header file, to get it more consistent. */ #ifndef MYSQLND_PORTABILITY_H #define MYSQLND_PORTABILITY_H #ifndef __attribute #if !defined(__GNUC__) #define __attribute(A) #endif #endif #ifdef __CYGWIN__ /* We use a Unix API, so pretend it's not Windows */ #undef WIN #undef WIN32 #undef _WIN #undef _WIN32 #undef _WIN64 #undef __WIN__ #undef __WIN32__ #endif /* __CYGWIN__ */ #if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32) # include "ext/mysqlnd/config-win.h" #endif /* _WIN32... */ #if __STDC_VERSION__ < 199901L && !defined(atoll) /* "inline" is a keyword */ #define atoll atol #endif #include <stdint.h> #if SIZEOF_LONG_LONG > 4 && !defined(_LONG_LONG) #define _LONG_LONG 1 /* For AIX string library */ #endif /* Go around some bugs in different OS and compilers */ #ifdef PHP_WIN32 #ifndef L64 #define L64(x) x##i64 #endif #else #ifndef L64 #define L64(x) x##LL #endif #endif #define int1store(T,A) do { *((int8_t*) (T)) = (A); } while(0) #define uint1korr(A) (*(((uint8_t*)(A)))) /* Bit values are sent in reverted order of bytes, compared to normal !!! */ #define bit_uint2korr(A) ((uint16_t) (((uint16_t) (((unsigned char*) (A))[1])) +\ ((uint16_t) (((unsigned char*) (A))[0]) << 8))) #define bit_uint3korr(A) ((uint32_t) (((uint32_t) (((unsigned char*) (A))[2])) +\ (((uint32_t) (((unsigned char*) (A))[1])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[0])) << 16))) #define bit_uint4korr(A) ((uint32_t) (((uint32_t) (((unsigned char*) (A))[3])) +\ (((uint32_t) (((unsigned char*) (A))[2])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[1])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[0])) << 24))) #define bit_uint5korr(A) ((uint64_t)(((uint32_t) (((unsigned char*) (A))[4])) +\ (((uint32_t) (((unsigned char*) (A))[3])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[2])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[1])) << 24)) +\ (((uint64_t) (((unsigned char*) (A))[0])) << 32)) #define bit_uint6korr(A) ((uint64_t)(((uint32_t) (((unsigned char*) (A))[5])) +\ (((uint32_t) (((unsigned char*) (A))[4])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[3])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[2])) << 24)) +\ (((uint64_t) (((uint32_t) (((unsigned char*) (A))[1])) +\ (((uint32_t) (((unsigned char*) (A))[0]) << 8)))) <<\ 32)) #define bit_uint7korr(A) ((uint64_t)(((uint32_t) (((unsigned char*) (A))[6])) +\ (((uint32_t) (((unsigned char*) (A))[5])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[4])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[3])) << 24)) +\ (((uint64_t) (((uint32_t) (((unsigned char*) (A))[2])) +\ (((uint32_t) (((unsigned char*) (A))[1])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[0])) << 16))) <<\ 32)) #define bit_uint8korr(A) ((uint64_t)(((uint32_t) (((unsigned char*) (A))[7])) +\ (((uint32_t) (((unsigned char*) (A))[6])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[5])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[4])) << 24)) +\ (((uint64_t) (((uint32_t) (((unsigned char*) (A))[3])) +\ (((uint32_t) (((unsigned char*) (A))[2])) << 8) +\ (((uint32_t) (((unsigned char*) (A))[1])) << 16) +\ (((uint32_t) (((unsigned char*) (A))[0])) << 24))) <<\ 32)) /* ** Define-funktions for reading and storing in machine independent format ** (low byte first) */ /* Optimized store functions for Intel x86, non-valid for WIN64. __i386__ is GCC */ #if defined(__i386__) && !defined(_WIN64) #define sint2korr(A) (*((int16_t *) (A))) #define sint3korr(A) ((int32_t) ((((zend_uchar) (A)[2]) & 128) ? \ (((uint32_t) 255L << 24) | \ (((uint32_t) (zend_uchar) (A)[2]) << 16) |\ (((uint32_t) (zend_uchar) (A)[1]) << 8) | \ ((uint32_t) (zend_uchar) (A)[0])) : \ (((uint32_t) (zend_uchar) (A)[2]) << 16) |\ (((uint32_t) (zend_uchar) (A)[1]) << 8) | \ ((uint32_t) (zend_uchar) (A)[0]))) #define sint4korr(A) (*((zend_long *) (A))) #define uint2korr(A) (*((uint16_t *) (A))) #define uint3korr(A) (uint32_t) (((uint32_t) ((zend_uchar) (A)[0])) +\ (((uint32_t) ((zend_uchar) (A)[1])) << 8) +\ (((uint32_t) ((zend_uchar) (A)[2])) << 16)) #define uint4korr(A) (*((zend_ulong *) (A))) #define uint8korr(A) (*((uint64_t *) (A))) #define sint8korr(A) (*((int64_t *) (A))) #define int2store(T,A) *((uint16_t*) (T))= (uint16_t) (A) #define int3store(T,A) { \ *(T)= (zend_uchar) ((A));\ *(T+1)=(zend_uchar) (((uint32_t) (A) >> 8));\ *(T+2)=(zend_uchar) (((A) >> 16)); } #define int4store(T,A) *((zend_long *) (T))= (zend_long) (A) #define int5store(T,A) { \ *((zend_uchar *)(T))= (zend_uchar)((A));\ *(((zend_uchar *)(T))+1)=(zend_uchar) (((A) >> 8));\ *(((zend_uchar *)(T))+2)=(zend_uchar) (((A) >> 16));\ *(((zend_uchar *)(T))+3)=(zend_uchar) (((A) >> 24)); \ *(((zend_uchar *)(T))+4)=(zend_uchar) (((A) >> 32)); } #define int8store(T,A) *((uint64_t *) (T))= (uint64_t) (A) typedef union { double v; zend_long m[2]; } float8get_union; #define float8get(V,M) { ((float8get_union *)&(V))->m[0] = *((zend_long*) (M)); \ ((float8get_union *)&(V))->m[1] = *(((zend_long*) (M))+1); } #define float8store(T,V) { *((zend_long *) (T)) = ((float8get_union *)&(V))->m[0]; \ *(((zend_long *) (T))+1) = ((float8get_union *)&(V))->m[1]; } #define float4get(V,M) { *((float *) &(V)) = *((float*) (M)); } /* From Andrey Hristov based on float8get */ #define floatget(V,M) memcpy((char*) &(V),(char*) (M),sizeof(float)) #endif /* __i386__ */ /* If we haven't defined sint2korr, which is because the platform is not x86 or it's WIN64 */ #ifndef sint2korr #define sint2korr(A) (int16_t) (((int16_t) ((zend_uchar) (A)[0])) +\ ((int16_t) ((int16_t) (A)[1]) << 8)) #define sint3korr(A) ((int32_t) ((((zend_uchar) (A)[2]) & 128) ? \ (((uint32_t) 255L << 24) | \ (((uint32_t) (zend_uchar) (A)[2]) << 16) |\ (((uint32_t) (zend_uchar) (A)[1]) << 8) | \ ((uint32_t) (zend_uchar) (A)[0])) : \ (((uint32_t) (zend_uchar) (A)[2]) << 16) |\ (((uint32_t) (zend_uchar) (A)[1]) << 8) | \ ((uint32_t) (zend_uchar) (A)[0]))) #define sint4korr(A) (int32_t) (((uint32_t) ((A)[0])) +\ (((uint32_t) ((A)[1]) << 8)) +\ (((uint32_t) ((A)[2]) << 16)) +\ (((uint32_t) ((A)[3]) << 24))) #define sint8korr(A) (int64_t) uint8korr(A) #define uint2korr(A) (uint16_t) (((uint16_t) ((zend_uchar) (A)[0])) +\ ((uint16_t) ((zend_uchar) (A)[1]) << 8)) #define uint3korr(A) (uint32_t) (((uint32_t) ((zend_uchar) (A)[0])) +\ (((uint32_t) ((zend_uchar) (A)[1])) << 8) +\ (((uint32_t) ((zend_uchar) (A)[2])) << 16)) #define uint4korr(A) (uint32_t) (((uint32_t) ((zend_uchar) (A)[0])) +\ (((uint32_t) ((zend_uchar) (A)[1])) << 8) +\ (((uint32_t) ((zend_uchar) (A)[2])) << 16) +\ (((uint32_t) ((zend_uchar) (A)[3])) << 24)) #define uint8korr(A) ((uint64_t)(((uint32_t) ((zend_uchar) (A)[0])) +\ (((uint32_t) ((zend_uchar) (A)[1])) << 8) +\ (((uint32_t) ((zend_uchar) (A)[2])) << 16) +\ (((uint32_t) ((zend_uchar) (A)[3])) << 24)) +\ (((uint64_t) (((uint32_t) ((zend_uchar) (A)[4])) +\ (((uint32_t) ((zend_uchar) (A)[5])) << 8) +\ (((uint32_t) ((zend_uchar) (A)[6])) << 16) +\ (((uint32_t) ((zend_uchar) (A)[7])) << 24))) << 32)) #define int2store(T,A) do { uint32_t def_temp= (uint32_t) (A) ;\ *((zend_uchar*) (T)) = (zend_uchar)(def_temp); \ *((zend_uchar*) (T+1)) = (zend_uchar)((def_temp >> 8)); } while (0) #define int3store(T,A) do { /*lint -save -e734 */\ *(((char *)(T))) = (char) ((A));\ *(((char *)(T))+1) = (char) (((A) >> 8));\ *(((char *)(T))+2) = (char) (((A) >> 16)); \ /*lint -restore */} while (0) #define int4store(T,A) do { \ *(((char *)(T))) = (char) ((A));\ *(((char *)(T))+1) = (char) (((A) >> 8));\ *(((char *)(T))+2) = (char) (((A) >> 16));\ *(((char *)(T))+3) = (char) (((A) >> 24)); } while (0) #define int5store(T,A) do { \ *(((char *)(T))) = (char)((A));\ *(((char *)(T))+1) = (char)(((A) >> 8));\ *(((char *)(T))+2) = (char)(((A) >> 16));\ *(((char *)(T))+3) = (char)(((A) >> 24)); \ *(((char *)(T))+4) = (char)(((A) >> 32)); } while (0) #define int8store(T,A) { uint32_t def_temp= (uint32_t) (A), def_temp2= (uint32_t) ((A) >> 32); \ int4store((T),def_temp); \ int4store((T+4),def_temp2); \ } #ifdef WORDS_BIGENDIAN #define float4get(V,M) do { float def_temp;\ ((char*) &def_temp)[0] = (M)[3];\ ((char*) &def_temp)[1] = (M)[2];\ ((char*) &def_temp)[2] = (M)[1];\ ((char*) &def_temp)[3] = (M)[0];\ (V)=def_temp; } while (0) #define float8store(T,V) do { \ *(((char *)(T))) = (char) ((char *) &(V))[7];\ *(((char *)(T))+1) = (char) ((char *) &(V))[6];\ *(((char *)(T))+2) = (char) ((char *) &(V))[5];\ *(((char *)(T))+3) = (char) ((char *) &(V))[4];\ *(((char *)(T))+4) = (char) ((char *) &(V))[3];\ *(((char *)(T))+5) = (char) ((char *) &(V))[2];\ *(((char *)(T))+6) = (char) ((char *) &(V))[1];\ *(((char *)(T))+7) = (char) ((char *) &(V))[0]; } while (0) #define float8get(V,M) do { double def_temp;\ ((char*) &def_temp)[0] = (M)[7];\ ((char*) &def_temp)[1] = (M)[6];\ ((char*) &def_temp)[2] = (M)[5];\ ((char*) &def_temp)[3] = (M)[4];\ ((char*) &def_temp)[4] = (M)[3];\ ((char*) &def_temp)[5] = (M)[2];\ ((char*) &def_temp)[6] = (M)[1];\ ((char*) &def_temp)[7] = (M)[0];\ (V) = def_temp; \ } while (0) #else #define float4get(V,M) memcpy((char*) &(V),(char*) (M),sizeof(float)) #if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) #define float8store(T,V) do { \ *(((char *)(T)))= ((char *) &(V))[4];\ *(((char *)(T))+1)=(char) ((char *) &(V))[5];\ *(((char *)(T))+2)=(char) ((char *) &(V))[6];\ *(((char *)(T))+3)=(char) ((char *) &(V))[7];\ *(((char *)(T))+4)=(char) ((char *) &(V))[0];\ *(((char *)(T))+5)=(char) ((char *) &(V))[1];\ *(((char *)(T))+6)=(char) ((char *) &(V))[2];\ *(((char *)(T))+7)=(char) ((char *) &(V))[3];} while (0) #define float8get(V,M) do { double def_temp;\ ((char*) &def_temp)[0]=(M)[4];\ ((char*) &def_temp)[1]=(M)[5];\ ((char*) &def_temp)[2]=(M)[6];\ ((char*) &def_temp)[3]=(M)[7];\ ((char*) &def_temp)[4]=(M)[0];\ ((char*) &def_temp)[5]=(M)[1];\ ((char*) &def_temp)[6]=(M)[2];\ ((char*) &def_temp)[7]=(M)[3];\ (V) = def_temp; } while (0) #endif /* __FLOAT_WORD_ORDER */ #endif /* WORDS_BIGENDIAN */ #endif /* sint2korr */ /* To here if the platform is not x86 or it's WIN64 */ /* Define-funktions for reading and storing in machine format from/to short/long to/from some place in memory V should be a (not register) variable, M is a pointer to byte */ #ifndef float8get #ifdef WORDS_BIGENDIAN #define float8get(V,M) memcpy((char*) &(V),(char*) (M), sizeof(double)) #define float8store(T,V) memcpy((char*) (T),(char*) &(V), sizeof(double)) #else #define float8get(V,M) memcpy((char*) &(V),(char*) (M),sizeof(double)) #define float8store(T,V) memcpy((char*) (T),(char*) &(V),sizeof(double)) #endif /* WORDS_BIGENDIAN */ #endif /* float8get */ #endif /* MYSQLND_PORTABILITY_H */
14,424
47.244147
103
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_priv.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_PRIV_H #define MYSQLND_PRIV_H PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_object_factory); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_conn); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_conn_data); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_res); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_result_unbuffered); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_result_buffered); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_protocol_payload_decoder_factory); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_protocol_packet_frame_codec); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_vio); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_upsert_status); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_error_info); PHPAPI extern MYSQLND_CLASS_METHOD_TABLE_NAME_FORWARD(mysqlnd_command); enum_func_status mysqlnd_handle_local_infile(MYSQLND_CONN_DATA * conn, const char * const filename, bool * is_warning); #endif /* MYSQLND_PRIV_H */
2,186
61.485714
119
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_read_buffer.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_debug.h" #include "mysqlnd_read_buffer.h" /* {{{ mysqlnd_read_buffer_is_empty */ static bool mysqlnd_read_buffer_is_empty(const MYSQLND_READ_BUFFER * const buffer) { return buffer->len? FALSE:TRUE; } /* }}} */ /* {{{ mysqlnd_read_buffer_read */ static void mysqlnd_read_buffer_read(MYSQLND_READ_BUFFER * buffer, const size_t count, zend_uchar * dest) { if (buffer->len >= count) { memcpy(dest, buffer->data + buffer->offset, count); buffer->offset += count; buffer->len -= count; } } /* }}} */ /* {{{ mysqlnd_read_buffer_bytes_left */ static size_t mysqlnd_read_buffer_bytes_left(const MYSQLND_READ_BUFFER * const buffer) { return buffer->len; } /* }}} */ /* {{{ mysqlnd_read_buffer_free */ static void mysqlnd_read_buffer_free(MYSQLND_READ_BUFFER ** buffer) { DBG_ENTER("mysqlnd_read_buffer_free"); if (*buffer) { mnd_efree((*buffer)->data); mnd_efree(*buffer); *buffer = NULL; } DBG_VOID_RETURN; } /* }}} */ /* {{{ mysqlnd_create_read_buffer */ PHPAPI MYSQLND_READ_BUFFER * mysqlnd_create_read_buffer(const size_t count) { MYSQLND_READ_BUFFER * ret = mnd_emalloc(sizeof(MYSQLND_READ_BUFFER)); DBG_ENTER("mysqlnd_create_read_buffer"); ret->is_empty = mysqlnd_read_buffer_is_empty; ret->read = mysqlnd_read_buffer_read; ret->bytes_left = mysqlnd_read_buffer_bytes_left; ret->free_buffer = mysqlnd_read_buffer_free; ret->data = mnd_emalloc(count); ret->size = ret->len = count; ret->offset = 0; DBG_RETURN(ret); } /* }}} */
2,576
28.965116
93
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_read_buffer.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_READ_BUFFER_H #define MYSQLND_READ_BUFFER_H PHPAPI MYSQLND_READ_BUFFER * mysqlnd_create_read_buffer(const size_t count); #endif /* MYSQLND_READ_BUFFER_H */
1,231
50.333333
76
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_result_meta.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Johannes Schlüter <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_RESULT_META_H #define MYSQLND_RESULT_META_H PHPAPI MYSQLND_RES_METADATA * mysqlnd_result_meta_init(MYSQLND_RES * result, unsigned int field_count); PHPAPI struct st_mysqlnd_res_meta_methods * mysqlnd_result_metadata_get_methods(void); PHPAPI void ** _mysqlnd_plugin_get_plugin_result_metadata_data(const MYSQLND_RES_METADATA * meta, unsigned int plugin_id); #endif /* MYSQLND_RESULT_META_H */
1,543
56.185185
122
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_reverse_api.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Johannes Schlüter <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_debug.h" #include "mysqlnd_reverse_api.h" static HashTable mysqlnd_api_ext_ht; /* {{{ mysqlnd_reverse_api_init */ PHPAPI void mysqlnd_reverse_api_init(void) { zend_hash_init(&mysqlnd_api_ext_ht, 3, NULL, NULL, 1); } /* }}} */ /* {{{ mysqlnd_reverse_api_end */ PHPAPI void mysqlnd_reverse_api_end(void) { zend_hash_destroy(&mysqlnd_api_ext_ht); } /* }}} */ /* {{{ myslqnd_get_api_extensions */ PHPAPI HashTable * mysqlnd_reverse_api_get_api_list(void) { return &mysqlnd_api_ext_ht; } /* }}} */ /* {{{ mysqlnd_reverse_api_register_api */ PHPAPI void mysqlnd_reverse_api_register_api(const MYSQLND_REVERSE_API * apiext) { zend_hash_str_add_ptr(&mysqlnd_api_ext_ht, apiext->module->name, strlen(apiext->module->name), (void*)apiext); } /* }}} */ /* {{{ zval_to_mysqlnd */ PHPAPI MYSQLND * zval_to_mysqlnd(zval * zv, const unsigned int client_api_capabilities, unsigned int * save_client_api_capabilities) { MYSQLND_REVERSE_API *api; ZEND_HASH_MAP_FOREACH_PTR(&mysqlnd_api_ext_ht, api) { if (api->conversion_cb) { MYSQLND *retval = api->conversion_cb(zv); if (retval) { if (retval->data) { *save_client_api_capabilities = retval->data->m->negotiate_client_api_capabilities(retval->data, client_api_capabilities); } return retval; } } } ZEND_HASH_FOREACH_END(); return NULL; } /* }}} */
2,545
29.309524
127
c
php-src
php-src-master/ext/mysqlnd/mysqlnd_reverse_api.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | | Georg Richter <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MYSQLND_REVERSE_API_H #define MYSQLND_REVERSE_API_H typedef struct st_mysqlnd_reverse_api { zend_module_entry * module; MYSQLND *(*conversion_cb)(zval * zv); } MYSQLND_REVERSE_API; PHPAPI void mysqlnd_reverse_api_init(void); PHPAPI void mysqlnd_reverse_api_end(void); PHPAPI HashTable * mysqlnd_reverse_api_get_api_list(void); PHPAPI void mysqlnd_reverse_api_register_api(const MYSQLND_REVERSE_API * apiext); PHPAPI MYSQLND * zval_to_mysqlnd(zval * zv, const unsigned int client_api_capabilities, unsigned int * save_client_api_capabilities); #endif /* MYSQLND_REVERSE_API_H */
1,725
45.648649
133
h
php-src
php-src-master/ext/mysqlnd/mysqlnd_statistics.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | | Georg Richter <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_statistics.h" #include "mysqlnd_debug.h" /* {{{ mysqlnd_stats_values_names */ const MYSQLND_STRING mysqlnd_stats_values_names[STAT_LAST] = { { MYSQLND_STR_W_LEN("bytes_sent") }, { MYSQLND_STR_W_LEN("bytes_received") }, { MYSQLND_STR_W_LEN("packets_sent") }, { MYSQLND_STR_W_LEN("packets_received") }, { MYSQLND_STR_W_LEN("protocol_overhead_in") }, { MYSQLND_STR_W_LEN("protocol_overhead_out") }, { MYSQLND_STR_W_LEN("bytes_received_ok_packet") }, { MYSQLND_STR_W_LEN("bytes_received_eof_packet") }, { MYSQLND_STR_W_LEN("bytes_received_rset_header_packet") }, { MYSQLND_STR_W_LEN("bytes_received_rset_field_meta_packet") }, { MYSQLND_STR_W_LEN("bytes_received_rset_row_packet") }, { MYSQLND_STR_W_LEN("bytes_received_prepare_response_packet") }, { MYSQLND_STR_W_LEN("bytes_received_change_user_packet") }, { MYSQLND_STR_W_LEN("packets_sent_command") }, { MYSQLND_STR_W_LEN("packets_received_ok") }, { MYSQLND_STR_W_LEN("packets_received_eof") }, { MYSQLND_STR_W_LEN("packets_received_rset_header") }, { MYSQLND_STR_W_LEN("packets_received_rset_field_meta") }, { MYSQLND_STR_W_LEN("packets_received_rset_row") }, { MYSQLND_STR_W_LEN("packets_received_prepare_response") }, { MYSQLND_STR_W_LEN("packets_received_change_user") }, { MYSQLND_STR_W_LEN("result_set_queries") }, { MYSQLND_STR_W_LEN("non_result_set_queries") }, { MYSQLND_STR_W_LEN("no_index_used") }, { MYSQLND_STR_W_LEN("bad_index_used") }, { MYSQLND_STR_W_LEN("slow_queries") }, { MYSQLND_STR_W_LEN("buffered_sets") }, { MYSQLND_STR_W_LEN("unbuffered_sets") }, { MYSQLND_STR_W_LEN("ps_buffered_sets") }, { MYSQLND_STR_W_LEN("ps_unbuffered_sets") }, { MYSQLND_STR_W_LEN("flushed_normal_sets") }, { MYSQLND_STR_W_LEN("flushed_ps_sets") }, { MYSQLND_STR_W_LEN("ps_prepared_never_executed") }, { MYSQLND_STR_W_LEN("ps_prepared_once_executed") }, { MYSQLND_STR_W_LEN("rows_fetched_from_server_normal") }, { MYSQLND_STR_W_LEN("rows_fetched_from_server_ps") }, { MYSQLND_STR_W_LEN("rows_buffered_from_client_normal") }, { MYSQLND_STR_W_LEN("rows_buffered_from_client_ps") }, { MYSQLND_STR_W_LEN("rows_fetched_from_client_normal_buffered") }, { MYSQLND_STR_W_LEN("rows_fetched_from_client_normal_unbuffered") }, { MYSQLND_STR_W_LEN("rows_fetched_from_client_ps_buffered") }, { MYSQLND_STR_W_LEN("rows_fetched_from_client_ps_unbuffered") }, { MYSQLND_STR_W_LEN("rows_fetched_from_client_ps_cursor") }, { MYSQLND_STR_W_LEN("rows_affected_normal") }, { MYSQLND_STR_W_LEN("rows_affected_ps") }, { MYSQLND_STR_W_LEN("rows_skipped_normal") }, { MYSQLND_STR_W_LEN("rows_skipped_ps") }, { MYSQLND_STR_W_LEN("copy_on_write_saved") }, { MYSQLND_STR_W_LEN("copy_on_write_performed") }, { MYSQLND_STR_W_LEN("command_buffer_too_small") }, { MYSQLND_STR_W_LEN("connect_success") }, { MYSQLND_STR_W_LEN("connect_failure") }, { MYSQLND_STR_W_LEN("connection_reused") }, { MYSQLND_STR_W_LEN("reconnect") }, { MYSQLND_STR_W_LEN("pconnect_success") }, { MYSQLND_STR_W_LEN("active_connections") }, { MYSQLND_STR_W_LEN("active_persistent_connections") }, { MYSQLND_STR_W_LEN("explicit_close") }, { MYSQLND_STR_W_LEN("implicit_close") }, { MYSQLND_STR_W_LEN("disconnect_close") }, { MYSQLND_STR_W_LEN("in_middle_of_command_close") }, { MYSQLND_STR_W_LEN("explicit_free_result") }, { MYSQLND_STR_W_LEN("implicit_free_result") }, { MYSQLND_STR_W_LEN("explicit_stmt_close") }, { MYSQLND_STR_W_LEN("implicit_stmt_close") }, { MYSQLND_STR_W_LEN("mem_emalloc_count") }, { MYSQLND_STR_W_LEN("mem_emalloc_amount") }, { MYSQLND_STR_W_LEN("mem_ecalloc_count") }, { MYSQLND_STR_W_LEN("mem_ecalloc_amount") }, { MYSQLND_STR_W_LEN("mem_erealloc_count") }, { MYSQLND_STR_W_LEN("mem_erealloc_amount") }, { MYSQLND_STR_W_LEN("mem_efree_count") }, { MYSQLND_STR_W_LEN("mem_efree_amount") }, { MYSQLND_STR_W_LEN("mem_malloc_count") }, { MYSQLND_STR_W_LEN("mem_malloc_amount") }, { MYSQLND_STR_W_LEN("mem_calloc_count") }, { MYSQLND_STR_W_LEN("mem_calloc_amount") }, { MYSQLND_STR_W_LEN("mem_realloc_count") }, { MYSQLND_STR_W_LEN("mem_realloc_amount") }, { MYSQLND_STR_W_LEN("mem_free_count") }, { MYSQLND_STR_W_LEN("mem_free_amount") }, { MYSQLND_STR_W_LEN("mem_estrndup_count") }, { MYSQLND_STR_W_LEN("mem_strndup_count") }, { MYSQLND_STR_W_LEN("mem_estrdup_count") }, { MYSQLND_STR_W_LEN("mem_strdup_count") }, { MYSQLND_STR_W_LEN("mem_edupl_count") }, { MYSQLND_STR_W_LEN("mem_dupl_count") }, { MYSQLND_STR_W_LEN("proto_text_fetched_null") }, { MYSQLND_STR_W_LEN("proto_text_fetched_bit") }, { MYSQLND_STR_W_LEN("proto_text_fetched_tinyint") }, { MYSQLND_STR_W_LEN("proto_text_fetched_short") }, { MYSQLND_STR_W_LEN("proto_text_fetched_int24") }, { MYSQLND_STR_W_LEN("proto_text_fetched_int") }, { MYSQLND_STR_W_LEN("proto_text_fetched_bigint") }, { MYSQLND_STR_W_LEN("proto_text_fetched_decimal") }, { MYSQLND_STR_W_LEN("proto_text_fetched_float") }, { MYSQLND_STR_W_LEN("proto_text_fetched_double") }, { MYSQLND_STR_W_LEN("proto_text_fetched_date") }, { MYSQLND_STR_W_LEN("proto_text_fetched_year") }, { MYSQLND_STR_W_LEN("proto_text_fetched_time") }, { MYSQLND_STR_W_LEN("proto_text_fetched_datetime") }, { MYSQLND_STR_W_LEN("proto_text_fetched_timestamp") }, { MYSQLND_STR_W_LEN("proto_text_fetched_string") }, { MYSQLND_STR_W_LEN("proto_text_fetched_blob") }, { MYSQLND_STR_W_LEN("proto_text_fetched_enum") }, { MYSQLND_STR_W_LEN("proto_text_fetched_set") }, { MYSQLND_STR_W_LEN("proto_text_fetched_geometry") }, { MYSQLND_STR_W_LEN("proto_text_fetched_other") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_null") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_bit") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_tinyint") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_short") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_int24") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_int") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_bigint") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_decimal") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_float") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_double") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_date") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_year") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_time") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_datetime") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_timestamp") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_string") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_json") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_blob") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_enum") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_set") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_geometry") }, { MYSQLND_STR_W_LEN("proto_binary_fetched_other") }, { MYSQLND_STR_W_LEN("init_command_executed_count") }, { MYSQLND_STR_W_LEN("init_command_failed_count") }, { MYSQLND_STR_W_LEN("com_quit") }, { MYSQLND_STR_W_LEN("com_init_db") }, { MYSQLND_STR_W_LEN("com_query") }, { MYSQLND_STR_W_LEN("com_field_list") }, { MYSQLND_STR_W_LEN("com_create_db") }, { MYSQLND_STR_W_LEN("com_drop_db") }, { MYSQLND_STR_W_LEN("com_refresh") }, { MYSQLND_STR_W_LEN("com_shutdown") }, { MYSQLND_STR_W_LEN("com_statistics") }, { MYSQLND_STR_W_LEN("com_process_info") }, { MYSQLND_STR_W_LEN("com_connect") }, { MYSQLND_STR_W_LEN("com_process_kill") }, { MYSQLND_STR_W_LEN("com_debug") }, { MYSQLND_STR_W_LEN("com_ping") }, { MYSQLND_STR_W_LEN("com_time") }, { MYSQLND_STR_W_LEN("com_delayed_insert") }, { MYSQLND_STR_W_LEN("com_change_user") }, { MYSQLND_STR_W_LEN("com_binlog_dump") }, { MYSQLND_STR_W_LEN("com_table_dump") }, { MYSQLND_STR_W_LEN("com_connect_out") }, { MYSQLND_STR_W_LEN("com_register_slave") }, { MYSQLND_STR_W_LEN("com_stmt_prepare") }, { MYSQLND_STR_W_LEN("com_stmt_execute") }, { MYSQLND_STR_W_LEN("com_stmt_send_long_data") }, { MYSQLND_STR_W_LEN("com_stmt_close") }, { MYSQLND_STR_W_LEN("com_stmt_reset") }, { MYSQLND_STR_W_LEN("com_stmt_set_option") }, { MYSQLND_STR_W_LEN("com_stmt_fetch") }, { MYSQLND_STR_W_LEN("com_deamon") }, { MYSQLND_STR_W_LEN("bytes_received_real_data_normal") }, { MYSQLND_STR_W_LEN("bytes_received_real_data_ps") } }; /* }}} */ /* {{{ mysqlnd_fill_stats_hash */ PHPAPI void mysqlnd_fill_stats_hash(const MYSQLND_STATS * const stats, const MYSQLND_STRING * names, zval *return_value ZEND_FILE_LINE_DC) { unsigned int i; array_init_size(return_value, stats->count); for (i = 0; i < stats->count; i++) { char tmp[25]; sprintf((char *)&tmp, "%" PRIu64, stats->values[i]); add_assoc_string_ex(return_value, names[i].s, names[i].l, tmp); } } /* }}} */ /* {{{ mysqlnd_stats_init */ PHPAPI void mysqlnd_stats_init(MYSQLND_STATS ** stats, const size_t statistic_count, const bool persistent) { *stats = pecalloc(1, sizeof(MYSQLND_STATS), persistent); (*stats)->values = pecalloc(statistic_count, sizeof(uint64_t), persistent); (*stats)->count = statistic_count; #ifdef ZTS (*stats)->LOCK_access = tsrm_mutex_alloc(); #endif } /* }}} */ /* {{{ mysqlnd_stats_end */ PHPAPI void mysqlnd_stats_end(MYSQLND_STATS * stats, const bool persistent) { #ifdef ZTS tsrm_mutex_free(stats->LOCK_access); #endif pefree(stats->values, persistent); /* mnd_free will reference LOCK_access and crash...*/ pefree(stats, persistent); } /* }}} */ /************ MYSQLND specific code **********/ /* {{{ _mysqlnd_get_client_stats */ PHPAPI void _mysqlnd_get_client_stats(MYSQLND_STATS * stats_ptr, zval *return_value ZEND_FILE_LINE_DC) { MYSQLND_STATS stats; DBG_ENTER("_mysqlnd_get_client_stats"); if (!stats_ptr) { memset(&stats, 0, sizeof(stats)); stats_ptr = &stats; } mysqlnd_fill_stats_hash(stats_ptr, mysqlnd_stats_values_names, return_value ZEND_FILE_LINE_CC); DBG_VOID_RETURN; } /* }}} */
10,916
41.478599
126
c
php-src
php-src-master/ext/mysqlnd/php_mysqlnd.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <[email protected]> | | Ulf Wendel <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_MYSQLND_H #define PHP_MYSQLND_H #define phpext_mysqlnd_ptr &mysqlnd_module_entry extern zend_module_entry mysqlnd_module_entry; #endif /* PHP_MYSQLND_H */
1,226
48.08
74
h
php-src
php-src-master/ext/oci8/php_oci8.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Stig Sæther Bakken <[email protected]> | | Thies C. Arntzen <[email protected]> | | | | Collection support by Andy Sautins <[email protected]> | | Temporary LOB support by David Benson <[email protected]> | | ZTS per process OCIPLogon by Harald Radi <[email protected]> | | | | Redesigned by: Antony Dovgal <[email protected]> | | Andi Gutmans <[email protected]> | | Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_OCI8 # ifndef PHP_OCI8_H # define PHP_OCI8_H #ifdef ZTS # include "TSRM.h" #endif /* * The version of the OCI8 extension. */ #ifdef PHP_OCI8_VERSION /* The definition of PHP_OCI8_VERSION changed in PHP 5.3 and building * this code with PHP 5.2 (e.g. when using OCI8 from PECL) will conflict. */ #undef PHP_OCI8_VERSION #endif #define PHP_OCI8_VERSION "3.3.0" extern zend_module_entry oci8_module_entry; #define phpext_oci8_ptr &oci8_module_entry #define phpext_oci8_11g_ptr &oci8_module_entry #define phpext_oci8_12c_ptr &oci8_module_entry #define phpext_oci8_19_ptr &oci8_module_entry PHP_MINIT_FUNCTION(oci); PHP_RINIT_FUNCTION(oci); PHP_MSHUTDOWN_FUNCTION(oci); PHP_RSHUTDOWN_FUNCTION(oci); PHP_MINFO_FUNCTION(oci); # endif /* !PHP_OCI8_H */ #else /* !HAVE_OCI8 */ # define oci8_module_ptr NULL #endif /* HAVE_OCI8 */
2,525
38.46875
75
h
php-src
php-src-master/ext/odbc/odbc_utils.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Calvin Buckley <[email protected]> | +----------------------------------------------------------------------+ */ #include "php.h" #include "php_odbc_utils.h" /* * Utility functions for dealing with ODBC connection strings and other common * functionality. * * While useful for PDO_ODBC too, this lives in ext/odbc because there isn't a * better place for it. */ PHP_FUNCTION(odbc_connection_string_is_quoted) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); bool is_quoted = php_odbc_connstr_is_quoted(ZSTR_VAL(str)); RETURN_BOOL(is_quoted); } PHP_FUNCTION(odbc_connection_string_should_quote) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); bool should_quote = php_odbc_connstr_should_quote(ZSTR_VAL(str)); RETURN_BOOL(should_quote); } PHP_FUNCTION(odbc_connection_string_quote) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); size_t new_size = php_odbc_connstr_estimate_quote_length(ZSTR_VAL(str)); zend_string *new_string = zend_string_alloc(new_size, 0); php_odbc_connstr_quote(ZSTR_VAL(new_string), ZSTR_VAL(str), new_size); /* reset length */ ZSTR_LEN(new_string) = strlen(ZSTR_VAL(new_string)); RETURN_STR(new_string); }
2,208
31.014493
78
c
php-src
php-src-master/ext/odbc/php_odbc.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Stig Sæther Bakken <[email protected]> | | Andreas Karajannis <[email protected]> | | Kevin N. Shallow <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_ODBC_H #define PHP_ODBC_H #ifdef HAVE_UODBC #ifdef ZTS #include "TSRM.h" #endif extern zend_module_entry odbc_module_entry; #define odbc_module_ptr &odbc_module_entry #include "php_version.h" #define PHP_ODBC_VERSION PHP_VERSION #if defined(HAVE_DBMAKER) || defined(PHP_WIN32) || defined(HAVE_IBMDB2) || defined(HAVE_UNIXODBC) || defined(HAVE_IODBC) # define PHP_ODBC_HAVE_FETCH_HASH 1 #endif /* user functions */ PHP_MINIT_FUNCTION(odbc); PHP_MSHUTDOWN_FUNCTION(odbc); PHP_RINIT_FUNCTION(odbc); PHP_RSHUTDOWN_FUNCTION(odbc); PHP_MINFO_FUNCTION(odbc); #ifdef PHP_WIN32 # define PHP_ODBC_API __declspec(dllexport) #elif defined(__GNUC__) && __GNUC__ >= 4 # define PHP_ODBC_API __attribute__ ((visibility("default"))) #else # define PHP_ODBC_API #endif #else #define odbc_module_ptr NULL #endif /* HAVE_UODBC */ #define phpext_odbc_ptr odbc_module_ptr #endif /* PHP_ODBC_H */
2,042
31.951613
120
h
php-src
php-src-master/ext/odbc/php_odbc_includes.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Stig Sæther Bakken <[email protected]> | | Andreas Karajannis <[email protected]> | | Kevin N. Shallow <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_ODBC_INCLUDES_H #define PHP_ODBC_INCLUDES_H #ifdef HAVE_UODBC /* checking in the same order as in configure.ac */ #if defined(HAVE_SOLID) || defined(HAVE_SOLID_30) || defined(HAVE_SOLID_35) /* Solid Server */ #define ODBC_TYPE "Solid" #if defined(HAVE_SOLID) # include <cli0core.h> # include <cli0ext1.h> # include <cli0env.h> #elif defined(HAVE_SOLID_30) # include <cli0cli.h> # include <cli0defs.h> # include <cli0env.h> #elif defined(HAVE_SOLID_35) # include <sqlunix.h> # include <sqltypes.h> # include <sqlucode.h> # include <sqlext.h> # include <sql.h> #endif /* end: #if defined(HAVE_SOLID) */ #undef HAVE_SQL_EXTENDED_FETCH #define SQLSMALLINT SWORD #define SQLUSMALLINT UWORD #ifndef SQL_SUCCEEDED #define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) #endif #elif defined(HAVE_EMPRESS) /* Empress */ #define ODBC_TYPE "Empress" #include <sql.h> #include <sqlext.h> #undef HAVE_SQL_EXTENDED_FETCH #elif defined(HAVE_ADABAS) /* Adabas D */ #define ODBC_TYPE "Adabas D" #include <WINDOWS.H> #include <sql.h> #include <sqlext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) #define SQLINTEGER ULONG #define SQLUSMALLINT USHORT #elif defined(HAVE_SAPDB) /* SAP DB */ #define ODBC_TYPE "SAP DB" #include <WINDOWS.H> #include <sql.h> #include <sqlext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) #elif defined(HAVE_IODBC) /* iODBC library */ #ifdef CHAR #undef CHAR #endif #ifdef SQLCHAR #undef SQLCHAR #endif #define ODBC_TYPE "iODBC" #include <sql.h> #include <sqlext.h> #include <iodbcext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #elif defined(HAVE_UNIXODBC) /* unixODBC library */ #ifdef CHAR #undef CHAR #endif #ifdef SQLCHAR #undef SQLCHAR #endif #define ODBC_TYPE "unixODBC" #undef ODBCVER #include <sql.h> #include <sqlext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #elif defined(HAVE_ESOOB) /* Easysoft ODBC-ODBC Bridge library */ #define ODBC_TYPE "ESOOB" #include <sql.h> #include <sqlext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #elif defined(HAVE_OPENLINK) /* OpenLink ODBC drivers */ #define ODBC_TYPE "Openlink" #include <iodbc.h> #include <isql.h> #include <isqlext.h> #include <udbcext.h> #define HAVE_SQL_EXTENDED_FETCH 1 #ifndef SQLSMALLINT #define SQLSMALLINT SWORD #endif #ifndef SQLUSMALLINT #define SQLUSMALLINT UWORD #endif #elif defined(HAVE_DBMAKER) /* DBMaker */ #define ODBC_TYPE "DBMaker" #undef ODBCVER #define ODBCVER 0x0300 #define HAVE_SQL_EXTENDED_FETCH 1 #include <odbc.h> #elif defined(HAVE_CODBC) /* Custom ODBC */ #define ODBC_TYPE "Custom ODBC" #define HAVE_SQL_EXTENDED_FETCH 1 #include <odbc.h> #elif defined(HAVE_IBMDB2) /* DB2 CLI */ #define ODBC_TYPE "IBM DB2 CLI" #define HAVE_SQL_EXTENDED_FETCH 1 #include <sqlcli1.h> #ifdef DB268K /* Need to include ASLM for 68K applications */ #include <LibraryManager.h> #endif #else /* MS ODBC */ #define HAVE_SQL_EXTENDED_FETCH 1 #include <WINDOWS.H> #include <sql.h> #include <sqlext.h> #endif #ifdef PHP_WIN32 #include <winsock2.h> #define ODBC_TYPE "Win32" #define PHP_ODBC_TYPE ODBC_TYPE #endif /* Common defines */ #if defined( HAVE_IBMDB2 ) || defined( HAVE_UNIXODBC ) || defined (HAVE_IODBC) #define ODBC_SQL_ENV_T SQLHANDLE #define ODBC_SQL_CONN_T SQLHANDLE #define ODBC_SQL_STMT_T SQLHANDLE #elif defined( HAVE_SOLID_35 ) || defined( HAVE_SAPDB ) || defined ( HAVE_EMPRESS ) #define ODBC_SQL_ENV_T SQLHENV #define ODBC_SQL_CONN_T SQLHDBC #define ODBC_SQL_STMT_T SQLHSTMT #else #define ODBC_SQL_ENV_T HENV #define ODBC_SQL_CONN_T HDBC #define ODBC_SQL_STMT_T HSTMT #endif typedef struct odbc_connection { ODBC_SQL_ENV_T henv; ODBC_SQL_CONN_T hdbc; char laststate[6]; char lasterrormsg[SQL_MAX_MESSAGE_LENGTH]; zend_resource *res; int persistent; } odbc_connection; typedef struct odbc_result_value { char name[256]; char *value; SQLLEN vallen; SQLLEN coltype; } odbc_result_value; typedef struct odbc_param_info { SQLSMALLINT sqltype; SQLSMALLINT scale; SQLSMALLINT nullable; SQLULEN precision; } odbc_param_info; typedef struct odbc_result { ODBC_SQL_STMT_T stmt; odbc_result_value *values; SQLSMALLINT numcols; SQLSMALLINT numparams; # if HAVE_SQL_EXTENDED_FETCH int fetch_abs; # endif zend_long longreadlen; int binmode; int fetched; odbc_param_info * param_info; odbc_connection *conn_ptr; } odbc_result; ZEND_BEGIN_MODULE_GLOBALS(odbc) char *defDB; char *defUser; char *defPW; bool allow_persistent; bool check_persistent; zend_long max_persistent; zend_long max_links; zend_long num_persistent; zend_long num_links; int defConn; zend_long defaultlrl; zend_long defaultbinmode; zend_long default_cursortype; char laststate[6]; char lasterrormsg[SQL_MAX_MESSAGE_LENGTH]; HashTable *resource_list; HashTable *resource_plist; ZEND_END_MODULE_GLOBALS(odbc) int odbc_add_result(HashTable *list, odbc_result *result); odbc_result *odbc_get_result(HashTable *list, int count); void odbc_del_result(HashTable *list, int count); int odbc_add_conn(HashTable *list, HDBC conn); odbc_connection *odbc_get_conn(HashTable *list, int count); void odbc_del_conn(HashTable *list, int ind); int odbc_bindcols(odbc_result *result); #define ODBC_SQL_ERROR_PARAMS odbc_connection *conn_resource, ODBC_SQL_STMT_T stmt, char *func void odbc_sql_error(ODBC_SQL_ERROR_PARAMS); #if defined(ODBCVER) && (ODBCVER >= 0x0300) #define IS_SQL_LONG(x) (x == SQL_LONGVARBINARY || x == SQL_LONGVARCHAR || x == SQL_WLONGVARCHAR) #define PHP_ODBC_SQLCOLATTRIBUTE SQLColAttribute #define PHP_ODBC_SQLALLOCSTMT(hdbc, phstmt) SQLAllocHandle(SQL_HANDLE_STMT, hdbc, phstmt) #define PHP_ODBC_SQL_DESC_NAME SQL_DESC_NAME #else #define IS_SQL_LONG(x) (x == SQL_LONGVARBINARY || x == SQL_LONGVARCHAR) #define PHP_ODBC_SQLCOLATTRIBUTE SQLColAttributes #define PHP_ODBC_SQLALLOCSTMT SQLAllocStmt #define PHP_ODBC_SQL_DESC_NAME SQL_COLUMN_NAME #endif #define IS_SQL_BINARY(x) (x == SQL_BINARY || x == SQL_VARBINARY || x == SQL_LONGVARBINARY) PHP_ODBC_API ZEND_EXTERN_MODULE_GLOBALS(odbc) #define ODBCG(v) ZEND_MODULE_GLOBALS_ACCESSOR(odbc, v) #if defined(ZTS) && defined(COMPILE_DL_ODBC) ZEND_TSRMLS_CACHE_EXTERN() #endif #endif /* HAVE_UODBC */ #endif /* PHP_ODBC_INCLUDES_H */
7,349
24.789474
96
h
php-src
php-src-master/ext/opcache/ZendAccelerator.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_H #define ZEND_ACCELERATOR_H #ifdef HAVE_CONFIG_H # include <config.h> #endif #define ACCELERATOR_PRODUCT_NAME "Zend OPcache" /* 2 - added Profiler support, on 20010712 */ /* 3 - added support for Optimizer's encoded-only-files mode */ /* 4 - works with the new Optimizer, that supports the file format with licenses */ /* 5 - API 4 didn't really work with the license-enabled file format. v5 does. */ /* 6 - Monitor was removed from ZendPlatform.so, to a module of its own */ /* 7 - Optimizer was embedded into Accelerator */ /* 8 - Standalone Open Source Zend OPcache */ #define ACCELERATOR_API_NO 8 #if ZEND_WIN32 # include "zend_config.w32.h" #else #include "zend_config.h" # include <sys/time.h> # include <sys/resource.h> #endif #if HAVE_UNISTD_H # include "unistd.h" #endif #include "zend_extensions.h" #include "zend_compile.h" #include "Optimizer/zend_optimizer.h" #include "zend_accelerator_hash.h" #include "zend_accelerator_debug.h" #ifndef PHPAPI # ifdef ZEND_WIN32 # define PHPAPI __declspec(dllimport) # else # define PHPAPI # endif #endif #ifndef ZEND_EXT_API # ifdef ZEND_WIN32 # define ZEND_EXT_API __declspec(dllexport) # elif defined(__GNUC__) && __GNUC__ >= 4 # define ZEND_EXT_API __attribute__ ((visibility("default"))) # else # define ZEND_EXT_API # endif #endif #ifdef ZEND_WIN32 # ifndef MAXPATHLEN # include "win32/ioutil.h" # define MAXPATHLEN PHP_WIN32_IOUTIL_MAXPATHLEN # endif # include <direct.h> #else # ifndef MAXPATHLEN # define MAXPATHLEN 4096 # endif # include <sys/param.h> #endif /*** file locking ***/ #ifndef ZEND_WIN32 extern int lock_file; #endif #if defined(ZEND_WIN32) # define ENABLE_FILE_CACHE_FALLBACK 1 #else # define ENABLE_FILE_CACHE_FALLBACK 0 #endif #if ZEND_WIN32 typedef unsigned __int64 accel_time_t; #else typedef time_t accel_time_t; #endif typedef enum _zend_accel_restart_reason { ACCEL_RESTART_OOM, /* restart because of out of memory */ ACCEL_RESTART_HASH, /* restart because of hash overflow */ ACCEL_RESTART_USER /* restart scheduled by opcache_reset() */ } zend_accel_restart_reason; typedef struct _zend_early_binding { zend_string *lcname; zend_string *rtd_key; zend_string *lc_parent_name; uint32_t cache_slot; } zend_early_binding; typedef struct _zend_persistent_script { zend_script script; zend_long compiler_halt_offset; /* position of __HALT_COMPILER or -1 */ int ping_auto_globals_mask; /* which autoglobals are used by the script */ accel_time_t timestamp; /* the script modification time */ bool corrupted; bool is_phar; bool empty; uint32_t num_warnings; uint32_t num_early_bindings; zend_error_info **warnings; zend_early_binding *early_bindings; void *mem; /* shared memory area used by script structures */ size_t size; /* size of used shared memory */ /* All entries that shouldn't be counted in the ADLER32 * checksum must be declared in this struct */ struct zend_persistent_script_dynamic_members { time_t last_used; zend_ulong hits; unsigned int memory_consumption; unsigned int checksum; time_t revalidate; } dynamic_members; } zend_persistent_script; typedef struct _zend_accel_directives { zend_long memory_consumption; zend_long max_accelerated_files; double max_wasted_percentage; char *user_blacklist_filename; zend_long consistency_checks; zend_long force_restart_timeout; bool use_cwd; bool ignore_dups; bool validate_timestamps; bool revalidate_path; bool save_comments; bool record_warnings; bool protect_memory; bool file_override_enabled; bool enable_cli; bool validate_permission; #ifndef ZEND_WIN32 bool validate_root; #endif zend_ulong revalidate_freq; zend_ulong file_update_protection; char *error_log; #ifdef ZEND_WIN32 char *mmap_base; #endif char *memory_model; zend_long log_verbosity_level; zend_long optimization_level; zend_long opt_debug_level; zend_long max_file_size; zend_long interned_strings_buffer; char *restrict_api; #ifndef ZEND_WIN32 char *lockfile_path; #endif char *file_cache; bool file_cache_only; bool file_cache_consistency_checks; #if ENABLE_FILE_CACHE_FALLBACK bool file_cache_fallback; #endif #ifdef HAVE_HUGE_CODE_PAGES bool huge_code_pages; #endif char *preload; #ifndef ZEND_WIN32 char *preload_user; #endif #ifdef ZEND_WIN32 char *cache_id; #endif } zend_accel_directives; typedef struct _zend_accel_globals { bool counted; /* the process uses shared memory */ bool enabled; bool locked; /* thread obtained exclusive lock */ bool accelerator_enabled; /* accelerator enabled for current request */ bool pcre_reseted; zend_accel_directives accel_directives; zend_string *cwd; /* current working directory or NULL */ zend_string *include_path; /* current value of "include_path" directive */ char include_path_key[32]; /* key of current "include_path" */ char cwd_key[32]; /* key of current working directory */ int include_path_key_len; bool include_path_check; int cwd_key_len; bool cwd_check; int auto_globals_mask; time_t request_time; time_t last_restart_time; /* used to synchronize SHM and in-process caches */ HashTable xlat_table; #ifndef ZEND_WIN32 zend_ulong root_hash; #endif /* preallocated shared-memory block to save current script */ void *mem; zend_persistent_script *current_persistent_script; /* cache to save hash lookup on the same INCLUDE opcode */ const zend_op *cache_opline; zend_persistent_script *cache_persistent_script; /* preallocated buffer for keys */ zend_string key; char _key[MAXPATHLEN * 8]; } zend_accel_globals; typedef struct _zend_string_table { uint32_t nTableMask; uint32_t nNumOfElements; zend_string *start; zend_string *top; zend_string *end; zend_string *saved_top; } zend_string_table; typedef struct _zend_accel_shared_globals { /* Cache Data Structures */ zend_ulong hits; zend_ulong misses; zend_ulong blacklist_misses; zend_ulong oom_restarts; /* number of restarts because of out of memory */ zend_ulong hash_restarts; /* number of restarts because of hash overflow */ zend_ulong manual_restarts; /* number of restarts scheduled by opcache_reset() */ zend_accel_hash hash; /* hash table for cached scripts */ size_t map_ptr_last; /* Directives & Maintenance */ time_t start_time; time_t last_restart_time; time_t force_restart_time; bool accelerator_enabled; bool restart_pending; zend_accel_restart_reason restart_reason; bool cache_status_before_restart; #ifdef ZEND_WIN32 LONGLONG mem_usage; LONGLONG restart_in; #endif bool restart_in_progress; /* Preloading */ zend_persistent_script *preload_script; zend_persistent_script **saved_scripts; /* uninitialized HashTable Support */ uint32_t uninitialized_bucket[-HT_MIN_MASK]; /* Tracing JIT */ void *jit_traces; const void **jit_exit_groups; /* Interned Strings Support (must be the last element) */ zend_string_table interned_strings; } zend_accel_shared_globals; #ifdef ZEND_WIN32 extern char accel_uname_id[32]; #endif extern bool accel_startup_ok; extern bool file_cache_only; #if ENABLE_FILE_CACHE_FALLBACK extern bool fallback_process; #endif extern zend_accel_shared_globals *accel_shared_globals; #define ZCSG(element) (accel_shared_globals->element) #ifdef ZTS # define ZCG(v) ZEND_TSRMG(accel_globals_id, zend_accel_globals *, v) extern int accel_globals_id; # ifdef COMPILE_DL_OPCACHE ZEND_TSRMLS_CACHE_EXTERN() # endif #else # define ZCG(v) (accel_globals.v) extern zend_accel_globals accel_globals; #endif extern const char *zps_api_failure_reason; BEGIN_EXTERN_C() void accel_shutdown(void); zend_result accel_activate(INIT_FUNC_ARGS); zend_result accel_post_deactivate(void); void zend_accel_schedule_restart(zend_accel_restart_reason reason); void zend_accel_schedule_restart_if_necessary(zend_accel_restart_reason reason); accel_time_t zend_get_file_handle_timestamp(zend_file_handle *file_handle, size_t *size); zend_result validate_timestamp_and_record(zend_persistent_script *persistent_script, zend_file_handle *file_handle); zend_result validate_timestamp_and_record_ex(zend_persistent_script *persistent_script, zend_file_handle *file_handle); zend_result zend_accel_invalidate(zend_string *filename, bool force); zend_result accelerator_shm_read_lock(void); void accelerator_shm_read_unlock(void); zend_string *accel_make_persistent_key(zend_string *path); zend_op_array *persistent_compile_file(zend_file_handle *file_handle, int type); #define IS_ACCEL_INTERNED(str) \ ((char*)(str) >= (char*)ZCSG(interned_strings).start && (char*)(str) < (char*)ZCSG(interned_strings).top) zend_string* ZEND_FASTCALL accel_new_interned_string(zend_string *str); uint32_t zend_accel_get_class_name_map_ptr(zend_string *type_name); END_EXTERN_C() /* memory write protection */ #define SHM_PROTECT() \ do { \ if (ZCG(accel_directives).protect_memory) { \ zend_accel_shared_protect(true); \ } \ } while (0) #define SHM_UNPROTECT() \ do { \ if (ZCG(accel_directives).protect_memory) { \ zend_accel_shared_protect(false); \ } \ } while (0) #endif /* ZEND_ACCELERATOR_H */
11,294
31.088068
119
h
php-src
php-src-master/ext/opcache/opcache_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: 81f337ea4ac5361ca4a0873fcd3b033beaf524c6 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_opcache_reset, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_opcache_get_status, 0, 0, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, include_scripts, _IS_BOOL, 0, "true") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_opcache_compile_file, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_opcache_invalidate, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, force, _IS_BOOL, 0, "false") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_opcache_get_configuration, 0, 0, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_END_ARG_INFO() #define arginfo_opcache_is_script_cached arginfo_opcache_compile_file ZEND_FUNCTION(opcache_reset); ZEND_FUNCTION(opcache_get_status); ZEND_FUNCTION(opcache_compile_file); ZEND_FUNCTION(opcache_invalidate); ZEND_FUNCTION(opcache_get_configuration); ZEND_FUNCTION(opcache_is_script_cached); static const zend_function_entry ext_functions[] = { ZEND_FE(opcache_reset, arginfo_opcache_reset) ZEND_FE(opcache_get_status, arginfo_opcache_get_status) ZEND_FE(opcache_compile_file, arginfo_opcache_compile_file) ZEND_FE(opcache_invalidate, arginfo_opcache_invalidate) ZEND_FE(opcache_get_configuration, arginfo_opcache_get_configuration) ZEND_FE(opcache_is_script_cached, arginfo_opcache_is_script_cached) ZEND_FE_END };
1,663
37.697674
107
h
php-src
php-src-master/ext/opcache/zend_accelerator_blacklist.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_BLACKLIST_H #define ZEND_ACCELERATOR_BLACKLIST_H typedef struct _zend_regexp_list zend_regexp_list; typedef struct _zend_blacklist_entry { char *path; int path_length; int id; } zend_blacklist_entry; typedef struct _zend_blacklist { zend_blacklist_entry *entries; int size; int pos; zend_regexp_list *regexp_list; } zend_blacklist; typedef int (*blacklist_apply_func_arg_t)(zend_blacklist_entry *, zval *); extern zend_blacklist accel_blacklist; void zend_accel_blacklist_init(zend_blacklist *blacklist); void zend_accel_blacklist_shutdown(zend_blacklist *blacklist); void zend_accel_blacklist_load(zend_blacklist *blacklist, char *filename); bool zend_accel_blacklist_is_blacklisted(zend_blacklist *blacklist, char *verify_path, size_t verify_path_len); void zend_accel_blacklist_apply(zend_blacklist *blacklist, blacklist_apply_func_arg_t func, void *argument); #endif /* ZEND_ACCELERATOR_BLACKLIST_H */
2,371
44.615385
111
h
php-src
php-src-master/ext/opcache/zend_accelerator_debug.c
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #ifdef ZEND_WIN32 # include <process.h> #endif #include "ZendAccelerator.h" static void zend_accel_error_va_args(int type, const char *format, va_list args) { time_t timestamp; char *time_string; FILE * fLog = NULL; if (type <= ZCG(accel_directives).log_verbosity_level) { timestamp = time(NULL); time_string = asctime(localtime(&timestamp)); time_string[24] = 0; if (!ZCG(accel_directives).error_log || !*ZCG(accel_directives).error_log || strcmp(ZCG(accel_directives).error_log, "stderr") == 0) { fLog = stderr; } else { fLog = fopen(ZCG(accel_directives).error_log, "a"); if (!fLog) { fLog = stderr; } } #ifdef ZTS fprintf(fLog, "%s (" ZEND_ULONG_FMT "): ", time_string, (zend_ulong)tsrm_thread_id()); #else fprintf(fLog, "%s (%d): ", time_string, getpid()); #endif switch (type) { case ACCEL_LOG_FATAL: fprintf(fLog, "Fatal Error "); break; case ACCEL_LOG_ERROR: fprintf(fLog, "Error "); break; case ACCEL_LOG_WARNING: fprintf(fLog, "Warning "); break; case ACCEL_LOG_INFO: fprintf(fLog, "Message "); break; case ACCEL_LOG_DEBUG: fprintf(fLog, "Debug "); break; } vfprintf(fLog, format, args); fprintf(fLog, "\n"); fflush(fLog); if (fLog != stderr) { fclose(fLog); } } /* perform error handling even without logging the error */ switch (type) { case ACCEL_LOG_ERROR: zend_bailout(); break; case ACCEL_LOG_FATAL: exit(-2); break; } } void zend_accel_error(int type, const char *format, ...) { va_list args; va_start(args, format); zend_accel_error_va_args(type, format, args); va_end(args); } ZEND_NORETURN void zend_accel_error_noreturn(int type, const char *format, ...) { va_list args; va_start(args, format); ZEND_ASSERT(type == ACCEL_LOG_FATAL || type == ACCEL_LOG_ERROR); zend_accel_error_va_args(type, format, args); va_end(args); /* Should never reach this. */ abort(); }
3,379
27.888889
88
c
php-src
php-src-master/ext/opcache/zend_accelerator_debug.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_DEBUG_H #define ZEND_ACCELERATOR_DEBUG_H #define ACCEL_LOG_FATAL 0 #define ACCEL_LOG_ERROR 1 #define ACCEL_LOG_WARNING 2 #define ACCEL_LOG_INFO 3 #define ACCEL_LOG_DEBUG 4 BEGIN_EXTERN_C() void zend_accel_error(int type, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3); ZEND_NORETURN void zend_accel_error_noreturn(int type, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3); END_EXTERN_C() #endif /* _ZEND_ACCELERATOR_DEBUG_H */
1,878
47.179487
116
h
php-src
php-src-master/ext/opcache/zend_accelerator_hash.c
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "ZendAccelerator.h" #include "zend_accelerator_hash.h" #include "zend_hash.h" #include "zend_shared_alloc.h" /* Generated on an Octa-ALPHA 300MHz CPU & 2.5GB RAM monster */ static const uint32_t prime_numbers[] = {5, 11, 19, 53, 107, 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793 }; static const uint32_t num_prime_numbers = sizeof(prime_numbers) / sizeof(uint32_t); void zend_accel_hash_clean(zend_accel_hash *accel_hash) { accel_hash->num_entries = 0; accel_hash->num_direct_entries = 0; memset(accel_hash->hash_table, 0, sizeof(zend_accel_hash_entry *)*accel_hash->max_num_entries); } void zend_accel_hash_init(zend_accel_hash *accel_hash, uint32_t hash_size) { uint32_t i; for (i=0; i<num_prime_numbers; i++) { if (hash_size <= prime_numbers[i]) { hash_size = prime_numbers[i]; break; } } accel_hash->num_entries = 0; accel_hash->num_direct_entries = 0; accel_hash->max_num_entries = hash_size; /* set up hash pointers table */ accel_hash->hash_table = zend_shared_alloc(sizeof(zend_accel_hash_entry *)*accel_hash->max_num_entries); if (!accel_hash->hash_table) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Insufficient shared memory!"); return; } /* set up hash values table */ accel_hash->hash_entries = zend_shared_alloc(sizeof(zend_accel_hash_entry)*accel_hash->max_num_entries); if (!accel_hash->hash_entries) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Insufficient shared memory!"); return; } memset(accel_hash->hash_table, 0, sizeof(zend_accel_hash_entry *)*accel_hash->max_num_entries); } /* Returns NULL if hash is full * Returns pointer the actual hash entry on success * key needs to be already allocated as it is not copied */ zend_accel_hash_entry* zend_accel_hash_update(zend_accel_hash *accel_hash, zend_string *key, bool indirect, void *data) { zend_ulong hash_value; zend_ulong index; zend_accel_hash_entry *entry; zend_accel_hash_entry *indirect_bucket = NULL; if (indirect) { indirect_bucket = (zend_accel_hash_entry*)data; while (indirect_bucket->indirect) { indirect_bucket = (zend_accel_hash_entry*)indirect_bucket->data; } } hash_value = zend_string_hash_val(key); #ifndef ZEND_WIN32 hash_value ^= ZCG(root_hash); #endif index = hash_value % accel_hash->max_num_entries; /* try to see if the element already exists in the hash */ entry = accel_hash->hash_table[index]; while (entry) { if (entry->hash_value == hash_value && zend_string_equals(entry->key, key)) { if (entry->indirect) { if (indirect_bucket) { entry->data = indirect_bucket; } else { ((zend_accel_hash_entry*)entry->data)->data = data; } } else { if (indirect_bucket) { accel_hash->num_direct_entries--; entry->data = indirect_bucket; entry->indirect = 1; } else { entry->data = data; } } return entry; } entry = entry->next; } /* Does not exist, add a new entry */ if (accel_hash->num_entries == accel_hash->max_num_entries) { return NULL; } entry = &accel_hash->hash_entries[accel_hash->num_entries++]; if (indirect) { entry->data = indirect_bucket; entry->indirect = 1; } else { accel_hash->num_direct_entries++; entry->data = data; entry->indirect = 0; } entry->hash_value = hash_value; entry->key = key; entry->next = accel_hash->hash_table[index]; accel_hash->hash_table[index] = entry; return entry; } static zend_always_inline void* zend_accel_hash_find_ex(zend_accel_hash *accel_hash, zend_string *key, int data) { zend_ulong index; zend_accel_hash_entry *entry; zend_ulong hash_value; hash_value = zend_string_hash_val(key); #ifndef ZEND_WIN32 hash_value ^= ZCG(root_hash); #endif index = hash_value % accel_hash->max_num_entries; entry = accel_hash->hash_table[index]; while (entry) { if (entry->hash_value == hash_value && zend_string_equals(entry->key, key)) { if (entry->indirect) { if (data) { return ((zend_accel_hash_entry*)entry->data)->data; } else { return entry->data; } } else { if (data) { return entry->data; } else { return entry; } } } entry = entry->next; } return NULL; } /* Returns the data associated with key on success * Returns NULL if data doesn't exist */ void* zend_accel_hash_find(zend_accel_hash *accel_hash, zend_string *key) { return zend_accel_hash_find_ex(accel_hash, key, 1); } /* Returns the hash entry associated with key on success * Returns NULL if it doesn't exist */ zend_accel_hash_entry* zend_accel_hash_find_entry(zend_accel_hash *accel_hash, zend_string *key) { return (zend_accel_hash_entry *)zend_accel_hash_find_ex(accel_hash, key, 0); } int zend_accel_hash_unlink(zend_accel_hash *accel_hash, zend_string *key) { zend_ulong hash_value; zend_ulong index; zend_accel_hash_entry *entry, *last_entry=NULL; hash_value = zend_string_hash_val(key); #ifndef ZEND_WIN32 hash_value ^= ZCG(root_hash); #endif index = hash_value % accel_hash->max_num_entries; entry = accel_hash->hash_table[index]; while (entry) { if (entry->hash_value == hash_value && zend_string_equals(entry->key, key)) { if (!entry->indirect) { accel_hash->num_direct_entries--; } if (last_entry) { last_entry->next = entry->next; } else { accel_hash->hash_table[index] = entry->next; } return SUCCESS; } last_entry = entry; entry = entry->next; } return FAILURE; }
6,815
29.565022
119
c
php-src
php-src-master/ext/opcache/zend_accelerator_hash.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_HASH_H #define ZEND_ACCELERATOR_HASH_H #include "zend.h" /* zend_accel_hash - is a hash table allocated in shared memory and distributed across simultaneously running processes. The hash tables have fixed sizen selected during construction by zend_accel_hash_init(). All the hash entries are preallocated in the 'hash_entries' array. 'num_entries' is initialized by zero and grows when new data is added. zend_accel_hash_update() just takes the next entry from 'hash_entries' array and puts it into appropriate place of 'hash_table'. Hash collisions are resolved by separate chaining with linked lists, however, entries are still taken from the same 'hash_entries' array. 'key' and 'data' passed to zend_accel_hash_update() must be already allocated in shared memory. Few keys may be resolved to the same data. using 'indirect' entries, that point to other entries ('data' is actually a pointer to another zend_accel_hash_entry). zend_accel_hash_update() requires exclusive lock, however, zend_accel_hash_find() does not. */ typedef struct _zend_accel_hash_entry zend_accel_hash_entry; struct _zend_accel_hash_entry { zend_ulong hash_value; zend_string *key; zend_accel_hash_entry *next; void *data; bool indirect; }; typedef struct _zend_accel_hash { zend_accel_hash_entry **hash_table; zend_accel_hash_entry *hash_entries; uint32_t num_entries; uint32_t max_num_entries; uint32_t num_direct_entries; } zend_accel_hash; BEGIN_EXTERN_C() void zend_accel_hash_init(zend_accel_hash *accel_hash, uint32_t hash_size); void zend_accel_hash_clean(zend_accel_hash *accel_hash); zend_accel_hash_entry* zend_accel_hash_update( zend_accel_hash *accel_hash, zend_string *key, bool indirect, void *data); void* zend_accel_hash_find( zend_accel_hash *accel_hash, zend_string *key); zend_accel_hash_entry* zend_accel_hash_find_entry( zend_accel_hash *accel_hash, zend_string *key); int zend_accel_hash_unlink( zend_accel_hash *accel_hash, zend_string *key); static inline bool zend_accel_hash_is_full(zend_accel_hash *accel_hash) { if (accel_hash->num_entries == accel_hash->max_num_entries) { return 1; } else { return 0; } } END_EXTERN_C() #endif /* ZEND_ACCELERATOR_HASH_H */
3,839
38.183673
76
h
php-src
php-src-master/ext/opcache/zend_accelerator_module.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_MODULE_H #define ZEND_ACCELERATOR_MODULE_H int start_accel_module(void); void zend_accel_override_file_functions(void); #endif /* _ZEND_ACCELERATOR_MODULE_H */
1,563
51.133333
75
h
php-src
php-src-master/ext/opcache/zend_accelerator_util_funcs.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ACCELERATOR_UTIL_FUNCS_H #define ZEND_ACCELERATOR_UTIL_FUNCS_H #include "zend.h" #include "ZendAccelerator.h" BEGIN_EXTERN_C() zend_persistent_script* create_persistent_script(void); void free_persistent_script(zend_persistent_script *persistent_script, int destroy_elements); void zend_accel_move_user_functions(HashTable *str, uint32_t count, zend_script *script); void zend_accel_move_user_classes(HashTable *str, uint32_t count, zend_script *script); void zend_accel_build_delayed_early_binding_list(zend_persistent_script *persistent_script); void zend_accel_finalize_delayed_early_binding_list(zend_persistent_script *persistent_script); void zend_accel_free_delayed_early_binding_list(zend_persistent_script *persistent_script); zend_op_array* zend_accel_load_script(zend_persistent_script *persistent_script, int from_shared_memory); #define ADLER32_INIT 1 /* initial Adler-32 value */ unsigned int zend_adler32(unsigned int checksum, unsigned char *buf, uint32_t len); unsigned int zend_accel_script_checksum(zend_persistent_script *persistent_script); END_EXTERN_C() #endif /* ZEND_ACCELERATOR_UTIL_FUNCS_H */
2,522
49.46
105
h
php-src
php-src-master/ext/opcache/zend_file_cache.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_FILE_CACHE_H #define ZEND_FILE_CACHE_H int zend_file_cache_script_store(zend_persistent_script *script, bool in_shm); zend_persistent_script *zend_file_cache_script_load(zend_file_handle *file_handle); void zend_file_cache_invalidate(zend_string *full_path); #endif /* ZEND_FILE_CACHE_H */
1,452
52.814815
83
h
php-src
php-src-master/ext/opcache/zend_persist.h
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_PERSIST_H #define ZEND_PERSIST_H BEGIN_EXTERN_C() uint32_t zend_accel_script_persist_calc(zend_persistent_script *script, int for_shm); zend_persistent_script *zend_accel_script_persist(zend_persistent_script *script, int for_shm); void zend_persist_class_entry_calc(zend_class_entry *ce); zend_class_entry *zend_persist_class_entry(zend_class_entry *ce); void zend_update_parent_ce(zend_class_entry *ce); void zend_persist_warnings_calc(uint32_t num_warnings, zend_error_info **warnings); zend_error_info **zend_persist_warnings(uint32_t num_warnings, zend_error_info **warnings); END_EXTERN_C() #endif /* ZEND_PERSIST_H */
2,018
50.769231
95
h
php-src
php-src-master/ext/opcache/zend_persist_calc.c
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "ZendAccelerator.h" #include "zend_persist.h" #include "zend_extensions.h" #include "zend_shared_alloc.h" #include "zend_operators.h" #include "zend_attributes.h" #define ADD_DUP_SIZE(m,s) ZCG(current_persistent_script)->size += zend_shared_memdup_size((void*)m, s) #define ADD_SIZE(m) ZCG(current_persistent_script)->size += ZEND_ALIGNED_SIZE(m) # define ADD_STRING(str) ADD_DUP_SIZE((str), _ZSTR_STRUCT_SIZE(ZSTR_LEN(str))) # define ADD_INTERNED_STRING(str) do { \ if (ZCG(current_persistent_script)->corrupted) { \ ADD_STRING(str); \ } else if (!IS_ACCEL_INTERNED(str)) { \ zend_string *tmp = accel_new_interned_string(str); \ if (tmp != (str)) { \ (str) = tmp; \ } else { \ ADD_STRING(str); \ } \ } \ } while (0) static void zend_persist_zval_calc(zval *z); static void zend_persist_op_array_calc(zval *zv); static void zend_hash_persist_calc(HashTable *ht) { if ((HT_FLAGS(ht) & HASH_FLAG_UNINITIALIZED) || ht->nNumUsed == 0) { return; } if (HT_IS_PACKED(ht)) { ADD_SIZE(HT_PACKED_USED_SIZE(ht)); } else if (ht->nNumUsed > HT_MIN_SIZE && ht->nNumUsed < (uint32_t)(-(int32_t)ht->nTableMask) / 4) { /* compact table */ uint32_t hash_size; hash_size = (uint32_t)(-(int32_t)ht->nTableMask); while (hash_size >> 2 > ht->nNumUsed) { hash_size >>= 1; } ADD_SIZE(hash_size * sizeof(uint32_t) + ht->nNumUsed * sizeof(Bucket)); } else { ADD_SIZE(HT_USED_SIZE(ht)); } } static void zend_persist_ast_calc(zend_ast *ast) { uint32_t i; if (ast->kind == ZEND_AST_ZVAL || ast->kind == ZEND_AST_CONSTANT) { ADD_SIZE(sizeof(zend_ast_zval)); zend_persist_zval_calc(&((zend_ast_zval*)(ast))->val); } else if (zend_ast_is_list(ast)) { zend_ast_list *list = zend_ast_get_list(ast); ADD_SIZE(sizeof(zend_ast_list) - sizeof(zend_ast *) + sizeof(zend_ast *) * list->children); for (i = 0; i < list->children; i++) { if (list->child[i]) { zend_persist_ast_calc(list->child[i]); } } } else { uint32_t children = zend_ast_get_num_children(ast); ADD_SIZE(sizeof(zend_ast) - sizeof(zend_ast *) + sizeof(zend_ast *) * children); for (i = 0; i < children; i++) { if (ast->child[i]) { zend_persist_ast_calc(ast->child[i]); } } } } static void zend_persist_zval_calc(zval *z) { uint32_t size; switch (Z_TYPE_P(z)) { case IS_STRING: ADD_INTERNED_STRING(Z_STR_P(z)); if (ZSTR_IS_INTERNED(Z_STR_P(z))) { Z_TYPE_FLAGS_P(z) = 0; } break; case IS_ARRAY: if (!ZCG(current_persistent_script)->corrupted && zend_accel_in_shm(Z_ARR_P(z))) { return; } size = zend_shared_memdup_size(Z_ARR_P(z), sizeof(zend_array)); if (size) { HashTable *ht = Z_ARRVAL_P(z); ADD_SIZE(size); zend_hash_persist_calc(ht); if (HT_IS_PACKED(ht)) { zval *zv; ZEND_HASH_PACKED_FOREACH_VAL(Z_ARRVAL_P(z), zv) { zend_persist_zval_calc(zv); } ZEND_HASH_FOREACH_END(); } else { Bucket *p; ZEND_HASH_MAP_FOREACH_BUCKET(Z_ARRVAL_P(z), p) { if (p->key) { ADD_INTERNED_STRING(p->key); } zend_persist_zval_calc(&p->val); } ZEND_HASH_FOREACH_END(); } } break; case IS_CONSTANT_AST: if (ZCG(current_persistent_script)->corrupted || !zend_accel_in_shm(Z_AST_P(z))) { size = zend_shared_memdup_size(Z_AST_P(z), sizeof(zend_ast_ref)); if (size) { ADD_SIZE(size); zend_persist_ast_calc(Z_ASTVAL_P(z)); } } break; default: ZEND_ASSERT(Z_TYPE_P(z) < IS_STRING); break; } } static void zend_persist_attributes_calc(HashTable *attributes) { if (!zend_shared_alloc_get_xlat_entry(attributes) && (ZCG(current_persistent_script)->corrupted || !zend_accel_in_shm(attributes))) { zend_attribute *attr; uint32_t i; zend_shared_alloc_register_xlat_entry(attributes, attributes); ADD_SIZE(sizeof(HashTable)); zend_hash_persist_calc(attributes); ZEND_HASH_PACKED_FOREACH_PTR(attributes, attr) { ADD_SIZE(ZEND_ATTRIBUTE_SIZE(attr->argc)); ADD_INTERNED_STRING(attr->name); ADD_INTERNED_STRING(attr->lcname); for (i = 0; i < attr->argc; i++) { if (attr->args[i].name) { ADD_INTERNED_STRING(attr->args[i].name); } zend_persist_zval_calc(&attr->args[i].value); } } ZEND_HASH_FOREACH_END(); } } static void zend_persist_type_calc(zend_type *type) { if (ZEND_TYPE_HAS_LIST(*type)) { ADD_SIZE(ZEND_TYPE_LIST_SIZE(ZEND_TYPE_LIST(*type)->num_types)); } zend_type *single_type; ZEND_TYPE_FOREACH(*type, single_type) { if (ZEND_TYPE_HAS_LIST(*single_type)) { zend_persist_type_calc(single_type); continue; } if (ZEND_TYPE_HAS_NAME(*single_type)) { zend_string *type_name = ZEND_TYPE_NAME(*single_type); ADD_INTERNED_STRING(type_name); ZEND_TYPE_SET_PTR(*single_type, type_name); } } ZEND_TYPE_FOREACH_END(); } static void zend_persist_op_array_calc_ex(zend_op_array *op_array) { if (op_array->function_name) { zend_string *old_name = op_array->function_name; ADD_INTERNED_STRING(op_array->function_name); /* Remember old function name, so it can be released multiple times if shared. */ if (op_array->function_name != old_name && !zend_shared_alloc_get_xlat_entry(&op_array->function_name)) { zend_shared_alloc_register_xlat_entry(&op_array->function_name, old_name); } } if (op_array->scope) { if (zend_shared_alloc_get_xlat_entry(op_array->opcodes)) { /* already stored */ ADD_SIZE(ZEND_ALIGNED_SIZE(zend_extensions_op_array_persist_calc(op_array))); return; } } if (op_array->scope && !(op_array->fn_flags & ZEND_ACC_CLOSURE) && (op_array->scope->ce_flags & ZEND_ACC_CACHED)) { return; } if (op_array->static_variables && !zend_accel_in_shm(op_array->static_variables)) { if (!zend_shared_alloc_get_xlat_entry(op_array->static_variables)) { Bucket *p; zend_shared_alloc_register_xlat_entry(op_array->static_variables, op_array->static_variables); ADD_SIZE(sizeof(HashTable)); zend_hash_persist_calc(op_array->static_variables); ZEND_HASH_MAP_FOREACH_BUCKET(op_array->static_variables, p) { ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); zend_persist_zval_calc(&p->val); } ZEND_HASH_FOREACH_END(); } } if (op_array->literals) { zval *p = op_array->literals; zval *end = p + op_array->last_literal; ADD_SIZE(sizeof(zval) * op_array->last_literal); while (p < end) { zend_persist_zval_calc(p); p++; } } zend_shared_alloc_register_xlat_entry(op_array->opcodes, op_array->opcodes); ADD_SIZE(sizeof(zend_op) * op_array->last); if (op_array->filename) { ADD_STRING(op_array->filename); } if (op_array->arg_info) { zend_arg_info *arg_info = op_array->arg_info; uint32_t num_args = op_array->num_args; uint32_t i; if (op_array->fn_flags & ZEND_ACC_VARIADIC) { num_args++; } if (op_array->fn_flags & ZEND_ACC_HAS_RETURN_TYPE) { arg_info--; num_args++; } ADD_SIZE(sizeof(zend_arg_info) * num_args); for (i = 0; i < num_args; i++) { if (arg_info[i].name) { ADD_INTERNED_STRING(arg_info[i].name); } zend_persist_type_calc(&arg_info[i].type); } } if (op_array->live_range) { ADD_SIZE(sizeof(zend_live_range) * op_array->last_live_range); } if (ZCG(accel_directives).save_comments && op_array->doc_comment) { ADD_STRING(op_array->doc_comment); } if (op_array->attributes) { zend_persist_attributes_calc(op_array->attributes); } if (op_array->try_catch_array) { ADD_SIZE(sizeof(zend_try_catch_element) * op_array->last_try_catch); } if (op_array->vars) { int i; ADD_SIZE(sizeof(zend_string*) * op_array->last_var); for (i = 0; i < op_array->last_var; i++) { ADD_INTERNED_STRING(op_array->vars[i]); } } if (op_array->num_dynamic_func_defs) { ADD_SIZE(sizeof(void *) * op_array->num_dynamic_func_defs); for (uint32_t i = 0; i < op_array->num_dynamic_func_defs; i++) { zval tmp; ZVAL_PTR(&tmp, op_array->dynamic_func_defs[i]); zend_persist_op_array_calc(&tmp); } } ADD_SIZE(ZEND_ALIGNED_SIZE(zend_extensions_op_array_persist_calc(op_array))); } static void zend_persist_op_array_calc(zval *zv) { zend_op_array *op_array = Z_PTR_P(zv); ZEND_ASSERT(op_array->type == ZEND_USER_FUNCTION); if (!zend_shared_alloc_get_xlat_entry(op_array)) { zend_shared_alloc_register_xlat_entry(op_array, op_array); ADD_SIZE(sizeof(zend_op_array)); zend_persist_op_array_calc_ex(op_array); } else { /* This can happen during preloading, if a dynamic function definition is declared. */ } } static void zend_persist_class_method_calc(zval *zv) { zend_op_array *op_array = Z_PTR_P(zv); zend_op_array *old_op_array; if (op_array->type != ZEND_USER_FUNCTION) { ZEND_ASSERT(op_array->type == ZEND_INTERNAL_FUNCTION); if (op_array->fn_flags & ZEND_ACC_ARENA_ALLOCATED) { old_op_array = zend_shared_alloc_get_xlat_entry(op_array); if (!old_op_array) { ADD_SIZE(sizeof(zend_internal_function)); zend_shared_alloc_register_xlat_entry(op_array, Z_PTR_P(zv)); } } return; } if ((op_array->fn_flags & ZEND_ACC_IMMUTABLE) && !ZCG(current_persistent_script)->corrupted && zend_accel_in_shm(op_array)) { zend_shared_alloc_register_xlat_entry(op_array, op_array); return; } old_op_array = zend_shared_alloc_get_xlat_entry(op_array); if (!old_op_array) { ADD_SIZE(sizeof(zend_op_array)); zend_persist_op_array_calc_ex(Z_PTR_P(zv)); zend_shared_alloc_register_xlat_entry(op_array, Z_PTR_P(zv)); } else { /* If op_array is shared, the function name refcount is still incremented for each use, * so we need to release it here. We remembered the original function name in xlat. */ zend_string *old_function_name = zend_shared_alloc_get_xlat_entry(&old_op_array->function_name); if (old_function_name) { zend_string_release_ex(old_function_name, 0); } } } static void zend_persist_property_info_calc(zend_property_info *prop) { ADD_SIZE(sizeof(zend_property_info)); ADD_INTERNED_STRING(prop->name); zend_persist_type_calc(&prop->type); if (ZCG(accel_directives).save_comments && prop->doc_comment) { ADD_STRING(prop->doc_comment); } if (prop->attributes) { zend_persist_attributes_calc(prop->attributes); } } static void zend_persist_class_constant_calc(zval *zv) { zend_class_constant *c = Z_PTR_P(zv); if (!zend_shared_alloc_get_xlat_entry(c)) { if (!ZCG(current_persistent_script)->corrupted && zend_accel_in_shm(Z_PTR_P(zv))) { return; } zend_shared_alloc_register_xlat_entry(c, c); ADD_SIZE(sizeof(zend_class_constant)); zend_persist_zval_calc(&c->value); if (ZCG(accel_directives).save_comments && c->doc_comment) { ADD_STRING(c->doc_comment); } if (c->attributes) { zend_persist_attributes_calc(c->attributes); } zend_persist_type_calc(&c->type); } } void zend_persist_class_entry_calc(zend_class_entry *ce) { Bucket *p; if (ce->type == ZEND_USER_CLASS) { /* The same zend_class_entry may be reused by class_alias */ if (zend_shared_alloc_get_xlat_entry(ce)) { return; } zend_shared_alloc_register_xlat_entry(ce, ce); ADD_SIZE(sizeof(zend_class_entry)); if (!(ce->ce_flags & ZEND_ACC_CACHED)) { ADD_INTERNED_STRING(ce->name); if (ce->parent_name && !(ce->ce_flags & ZEND_ACC_LINKED)) { ADD_INTERNED_STRING(ce->parent_name); } } zend_hash_persist_calc(&ce->function_table); ZEND_HASH_MAP_FOREACH_BUCKET(&ce->function_table, p) { ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); zend_persist_class_method_calc(&p->val); } ZEND_HASH_FOREACH_END(); if (ce->default_properties_table) { int i; ADD_SIZE(sizeof(zval) * ce->default_properties_count); for (i = 0; i < ce->default_properties_count; i++) { zend_persist_zval_calc(&ce->default_properties_table[i]); } } if (ce->default_static_members_table) { int i; ADD_SIZE(sizeof(zval) * ce->default_static_members_count); for (i = 0; i < ce->default_static_members_count; i++) { if (Z_TYPE(ce->default_static_members_table[i]) != IS_INDIRECT) { zend_persist_zval_calc(&ce->default_static_members_table[i]); } } } zend_hash_persist_calc(&ce->constants_table); ZEND_HASH_MAP_FOREACH_BUCKET(&ce->constants_table, p) { ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); zend_persist_class_constant_calc(&p->val); } ZEND_HASH_FOREACH_END(); zend_hash_persist_calc(&ce->properties_info); ZEND_HASH_MAP_FOREACH_BUCKET(&ce->properties_info, p) { zend_property_info *prop = Z_PTR(p->val); ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); if (prop->ce == ce) { zend_persist_property_info_calc(prop); } } ZEND_HASH_FOREACH_END(); if (ce->properties_info_table) { ADD_SIZE(sizeof(zend_property_info *) * ce->default_properties_count); } if (ce->num_interfaces && (ce->ce_flags & ZEND_ACC_LINKED)) { ADD_SIZE(sizeof(zend_class_entry*) * ce->num_interfaces); } if (ce->iterator_funcs_ptr) { ADD_SIZE(sizeof(zend_class_iterator_funcs)); } if (ce->arrayaccess_funcs_ptr) { ADD_SIZE(sizeof(zend_class_arrayaccess_funcs)); } if (ce->ce_flags & ZEND_ACC_CACHED) { return; } if (ce->info.user.filename) { ADD_STRING(ce->info.user.filename); } if (ZCG(accel_directives).save_comments && ce->info.user.doc_comment) { ADD_STRING(ce->info.user.doc_comment); } if (ce->attributes) { zend_persist_attributes_calc(ce->attributes); } if (ce->num_interfaces) { uint32_t i; if (!(ce->ce_flags & ZEND_ACC_LINKED)) { for (i = 0; i < ce->num_interfaces; i++) { ADD_INTERNED_STRING(ce->interface_names[i].name); ADD_INTERNED_STRING(ce->interface_names[i].lc_name); } ADD_SIZE(sizeof(zend_class_name) * ce->num_interfaces); } } if (ce->num_traits) { uint32_t i; for (i = 0; i < ce->num_traits; i++) { ADD_INTERNED_STRING(ce->trait_names[i].name); ADD_INTERNED_STRING(ce->trait_names[i].lc_name); } ADD_SIZE(sizeof(zend_class_name) * ce->num_traits); if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method.method_name) { ADD_INTERNED_STRING(ce->trait_aliases[i]->trait_method.method_name); } if (ce->trait_aliases[i]->trait_method.class_name) { ADD_INTERNED_STRING(ce->trait_aliases[i]->trait_method.class_name); } if (ce->trait_aliases[i]->alias) { ADD_INTERNED_STRING(ce->trait_aliases[i]->alias); } ADD_SIZE(sizeof(zend_trait_alias)); i++; } ADD_SIZE(sizeof(zend_trait_alias*) * (i + 1)); } if (ce->trait_precedences) { int j; i = 0; while (ce->trait_precedences[i]) { ADD_INTERNED_STRING(ce->trait_precedences[i]->trait_method.method_name); ADD_INTERNED_STRING(ce->trait_precedences[i]->trait_method.class_name); for (j = 0; j < ce->trait_precedences[i]->num_excludes; j++) { ADD_INTERNED_STRING(ce->trait_precedences[i]->exclude_class_names[j]); } ADD_SIZE(sizeof(zend_trait_precedence) + (ce->trait_precedences[i]->num_excludes - 1) * sizeof(zend_string*)); i++; } ADD_SIZE(sizeof(zend_trait_precedence*) * (i + 1)); } } } } static void zend_accel_persist_class_table_calc(HashTable *class_table) { Bucket *p; zend_hash_persist_calc(class_table); ZEND_HASH_MAP_FOREACH_BUCKET(class_table, p) { ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); zend_persist_class_entry_calc(Z_CE(p->val)); } ZEND_HASH_FOREACH_END(); } void zend_persist_warnings_calc(uint32_t num_warnings, zend_error_info **warnings) { ADD_SIZE(num_warnings * sizeof(zend_error_info *)); for (uint32_t i = 0; i < num_warnings; i++) { ADD_SIZE(sizeof(zend_error_info)); ADD_STRING(warnings[i]->filename); ADD_STRING(warnings[i]->message); } } static void zend_persist_early_bindings_calc( uint32_t num_early_bindings, zend_early_binding *early_bindings) { ADD_SIZE(sizeof(zend_early_binding) * num_early_bindings); for (uint32_t i = 0; i < num_early_bindings; i++) { zend_early_binding *early_binding = &early_bindings[i]; ADD_INTERNED_STRING(early_binding->lcname); ADD_INTERNED_STRING(early_binding->rtd_key); ADD_INTERNED_STRING(early_binding->lc_parent_name); } } uint32_t zend_accel_script_persist_calc(zend_persistent_script *new_persistent_script, int for_shm) { Bucket *p; new_persistent_script->mem = NULL; new_persistent_script->size = 0; new_persistent_script->corrupted = false; ZCG(current_persistent_script) = new_persistent_script; if (!for_shm) { /* script is not going to be saved in SHM */ new_persistent_script->corrupted = true; } ADD_SIZE(sizeof(zend_persistent_script)); ADD_INTERNED_STRING(new_persistent_script->script.filename); #if defined(__AVX__) || defined(__SSE2__) /* Align size to 64-byte boundary */ new_persistent_script->size = (new_persistent_script->size + 63) & ~63; #endif if (new_persistent_script->script.class_table.nNumUsed != new_persistent_script->script.class_table.nNumOfElements) { zend_hash_rehash(&new_persistent_script->script.class_table); } zend_accel_persist_class_table_calc(&new_persistent_script->script.class_table); if (new_persistent_script->script.function_table.nNumUsed != new_persistent_script->script.function_table.nNumOfElements) { zend_hash_rehash(&new_persistent_script->script.function_table); } zend_hash_persist_calc(&new_persistent_script->script.function_table); ZEND_HASH_MAP_FOREACH_BUCKET(&new_persistent_script->script.function_table, p) { ZEND_ASSERT(p->key != NULL); ADD_INTERNED_STRING(p->key); zend_persist_op_array_calc(&p->val); } ZEND_HASH_FOREACH_END(); zend_persist_op_array_calc_ex(&new_persistent_script->script.main_op_array); zend_persist_warnings_calc( new_persistent_script->num_warnings, new_persistent_script->warnings); zend_persist_early_bindings_calc( new_persistent_script->num_early_bindings, new_persistent_script->early_bindings); new_persistent_script->corrupted = false; ZCG(current_persistent_script) = NULL; return new_persistent_script->size; }
19,416
29.434169
124
c
php-src
php-src-master/ext/opcache/jit/zend_elf.c
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #include <sys/types.h> #include <sys/stat.h> #if defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/sysctl.h> #elif defined(__HAIKU__) #include <FindDirectory.h> #endif #include <fcntl.h> #include <unistd.h> #include "zend_API.h" #include "zend_elf.h" static void* zend_elf_read_sect(int fd, zend_elf_sectheader *sect) { void *s = emalloc(sect->size); if (lseek(fd, sect->ofs, SEEK_SET) < 0) { efree(s); return NULL; } if (read(fd, s, sect->size) != (ssize_t)sect->size) { efree(s); return NULL; } return s; } void zend_elf_load_symbols(void) { zend_elf_header hdr; zend_elf_sectheader sect; int i; #if defined(__linux__) int fd = open("/proc/self/exe", O_RDONLY); #elif defined(__NetBSD__) int fd = open("/proc/curproc/exe", O_RDONLY); #elif defined(__FreeBSD__) || defined(__DragonFly__) char path[PATH_MAX]; size_t pathlen = sizeof(path); int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; if (sysctl(mib, 4, path, &pathlen, NULL, 0) == -1) { return; } int fd = open(path, O_RDONLY); #elif defined(__sun) int fd = open("/proc/self/path/a.out", O_RDONLY); #elif defined(__HAIKU__) char path[PATH_MAX]; if (find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, path, sizeof(path)) != B_OK) { return; } int fd = open(path, O_RDONLY); #else // To complete eventually for other ELF platforms. // Otherwise APPLE is Mach-O int fd = -1; #endif if (fd >= 0) { if (read(fd, &hdr, sizeof(hdr)) == sizeof(hdr) && hdr.emagic[0] == '\177' && hdr.emagic[1] == 'E' && hdr.emagic[2] == 'L' && hdr.emagic[3] == 'F' && lseek(fd, hdr.shofs, SEEK_SET) >= 0) { for (i = 0; i < hdr.shnum; i++) { if (read(fd, &sect, sizeof(sect)) == sizeof(sect) && sect.type == ELFSECT_TYPE_SYMTAB) { uint32_t n, count = sect.size / sizeof(zend_elf_symbol); zend_elf_symbol *syms = zend_elf_read_sect(fd, &sect); char *str_tbl; if (syms) { if (lseek(fd, hdr.shofs + sect.link * sizeof(sect), SEEK_SET) >= 0 && read(fd, &sect, sizeof(sect)) == sizeof(sect) && (str_tbl = (char*)zend_elf_read_sect(fd, &sect)) != NULL) { for (n = 0; n < count; n++) { if (syms[n].name && (ELFSYM_TYPE(syms[n].info) == ELFSYM_TYPE_FUNC /*|| ELFSYM_TYPE(syms[n].info) == ELFSYM_TYPE_DATA*/) && (ELFSYM_BIND(syms[n].info) == ELFSYM_BIND_LOCAL /*|| ELFSYM_BIND(syms[n].info) == ELFSYM_BIND_GLOBAL*/)) { zend_jit_disasm_add_symbol(str_tbl + syms[n].name, syms[n].value, syms[n].size); } } efree(str_tbl); } efree(syms); } if (lseek(fd, hdr.shofs + (i + 1) * sizeof(sect), SEEK_SET) < 0) { break; } } } } close(fd); } }
3,954
31.418033
89
c
php-src
php-src-master/ext/opcache/jit/zend_elf.h
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ELF #define ZEND_ELF #if SIZEOF_SIZE_T == 8 # define ELF64 #else # undef ELF64 #endif typedef struct _zend_elf_header { uint8_t emagic[4]; uint8_t eclass; uint8_t eendian; uint8_t eversion; uint8_t eosabi; uint8_t eabiversion; uint8_t epad[7]; uint16_t type; uint16_t machine; uint32_t version; uintptr_t entry; uintptr_t phofs; uintptr_t shofs; uint32_t flags; uint16_t ehsize; uint16_t phentsize; uint16_t phnum; uint16_t shentsize; uint16_t shnum; uint16_t shstridx; } zend_elf_header; typedef struct zend_elf_sectheader { uint32_t name; uint32_t type; uintptr_t flags; uintptr_t addr; uintptr_t ofs; uintptr_t size; uint32_t link; uint32_t info; uintptr_t align; uintptr_t entsize; } zend_elf_sectheader; #define ELFSECT_IDX_ABS 0xfff1 enum { ELFSECT_TYPE_PROGBITS = 1, ELFSECT_TYPE_SYMTAB = 2, ELFSECT_TYPE_STRTAB = 3, ELFSECT_TYPE_NOBITS = 8, ELFSECT_TYPE_DYNSYM = 11, }; #define ELFSECT_FLAGS_WRITE (1 << 0) #define ELFSECT_FLAGS_ALLOC (1 << 1) #define ELFSECT_FLAGS_EXEC (1 << 2) #define ELFSECT_FLAGS_TLS (1 << 10) typedef struct zend_elf_symbol { #ifdef ELF64 uint32_t name; uint8_t info; uint8_t other; uint16_t sectidx; uintptr_t value; uint64_t size; #else uint32_t name; uintptr_t value; uint32_t size; uint8_t info; uint8_t other; uint16_t sectidx; #endif } zend_elf_symbol; #define ELFSYM_BIND(info) ((info) >> 4) #define ELFSYM_TYPE(info) ((info) & 0xf) #define ELFSYM_INFO(bind, type) (((bind) << 4) | (type)) enum { ELFSYM_TYPE_DATA = 2, ELFSYM_TYPE_FUNC = 2, ELFSYM_TYPE_FILE = 4, }; enum { ELFSYM_BIND_LOCAL = 0, ELFSYM_BIND_GLOBAL = 1, }; void zend_elf_load_symbols(void); #endif
2,964
24.560345
75
h
php-src
php-src-master/ext/opcache/jit/zend_jit.h
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef HAVE_JIT_H #define HAVE_JIT_H #if defined(__x86_64__) || defined(i386) || defined(ZEND_WIN32) # define ZEND_JIT_TARGET_X86 1 # define ZEND_JIT_TARGET_ARM64 0 #elif defined (__aarch64__) # define ZEND_JIT_TARGET_X86 0 # define ZEND_JIT_TARGET_ARM64 1 #else # error "JIT not supported on this platform" #endif #define ZEND_JIT_LEVEL_NONE 0 /* no JIT */ #define ZEND_JIT_LEVEL_MINIMAL 1 /* minimal JIT (subroutine threading) */ #define ZEND_JIT_LEVEL_INLINE 2 /* selective inline threading */ #define ZEND_JIT_LEVEL_OPT_FUNC 3 /* optimized JIT based on Type-Inference */ #define ZEND_JIT_LEVEL_OPT_FUNCS 4 /* optimized JIT based on Type-Inference and call-tree */ #define ZEND_JIT_LEVEL_OPT_SCRIPT 5 /* optimized JIT based on Type-Inference and inner-procedure analysis */ #define ZEND_JIT_ON_SCRIPT_LOAD 0 #define ZEND_JIT_ON_FIRST_EXEC 1 #define ZEND_JIT_ON_PROF_REQUEST 2 /* compile the most frequently caled on first request functions */ #define ZEND_JIT_ON_HOT_COUNTERS 3 /* compile functions after N calls or loop iterations */ #define ZEND_JIT_ON_DOC_COMMENT 4 /* compile functions with "@jit" tag in doc-comments */ #define ZEND_JIT_ON_HOT_TRACE 5 /* trace functions after N calls or loop iterations */ #define ZEND_JIT_REG_ALLOC_LOCAL (1<<0) /* local linear scan register allocation */ #define ZEND_JIT_REG_ALLOC_GLOBAL (1<<1) /* global linear scan register allocation */ #define ZEND_JIT_CPU_AVX (1<<2) /* use AVX instructions, if available */ #define ZEND_JIT_DEFAULT_BUFFER_SIZE "0" #define ZEND_JIT_COUNTER_INIT 32531 #define ZEND_JIT_DEBUG_ASM (1<<0) #define ZEND_JIT_DEBUG_SSA (1<<1) #define ZEND_JIT_DEBUG_REG_ALLOC (1<<2) #define ZEND_JIT_DEBUG_ASM_STUBS (1<<3) #define ZEND_JIT_DEBUG_PERF (1<<4) #define ZEND_JIT_DEBUG_PERF_DUMP (1<<5) #define ZEND_JIT_DEBUG_VTUNE (1<<7) #define ZEND_JIT_DEBUG_GDB (1<<8) #define ZEND_JIT_DEBUG_SIZE (1<<9) #define ZEND_JIT_DEBUG_ASM_ADDR (1<<10) #define ZEND_JIT_DEBUG_TRACE_START (1<<12) #define ZEND_JIT_DEBUG_TRACE_STOP (1<<13) #define ZEND_JIT_DEBUG_TRACE_COMPILED (1<<14) #define ZEND_JIT_DEBUG_TRACE_EXIT (1<<15) #define ZEND_JIT_DEBUG_TRACE_ABORT (1<<16) #define ZEND_JIT_DEBUG_TRACE_BLACKLIST (1<<17) #define ZEND_JIT_DEBUG_TRACE_BYTECODE (1<<18) #define ZEND_JIT_DEBUG_TRACE_TSSA (1<<19) #define ZEND_JIT_DEBUG_TRACE_EXIT_INFO (1<<20) #define ZEND_JIT_DEBUG_PERSISTENT 0x1f0 /* profile and debugger flags can't be changed at run-time */ #define ZEND_JIT_TRACE_MAX_LENGTH 1024 /* max length of single trace */ #define ZEND_JIT_TRACE_MAX_EXITS 512 /* max number of side exits per trace */ #define ZEND_JIT_TRACE_MAX_FUNCS 30 /* max number of different functions in a single trace */ #define ZEND_JIT_TRACE_MAX_CALL_DEPTH 10 /* max depth of inlined calls */ #define ZEND_JIT_TRACE_MAX_RET_DEPTH 4 /* max depth of inlined returns */ #define ZEND_JIT_TRACE_MAX_LOOPS_UNROLL 10 /* max number of unrolled loops */ #define ZEND_JIT_TRACE_BAD_ROOT_SLOTS 64 /* number of slots in bad root trace cache */ typedef struct _zend_jit_trace_rec zend_jit_trace_rec; typedef struct _zend_jit_trace_stack_frame zend_jit_trace_stack_frame; typedef struct _sym_node zend_sym_node; typedef struct _zend_jit_globals { bool enabled; bool on; uint8_t trigger; uint8_t opt_level; uint32_t opt_flags; const char *options; zend_long buffer_size; zend_long debug; zend_long bisect_limit; double prof_threshold; zend_long max_root_traces; /* max number of root traces */ zend_long max_side_traces; /* max number of side traces (per root trace) */ zend_long max_exit_counters; /* max total number of side exits for all traces */ zend_long hot_loop; zend_long hot_func; zend_long hot_return; zend_long hot_side_exit; /* number of exits before taking side trace */ zend_long blacklist_root_trace; /* number of attempts to JIT a root trace before blacklist it */ zend_long blacklist_side_trace; /* number of attempts to JIT a side trace before blacklist it */ zend_long max_loop_unrolls; /* max number of unrolled loops */ zend_long max_recursive_calls; /* max number of recursive inlined call unrolls */ zend_long max_recursive_returns; /* max number of recursive inlined return unrolls */ zend_long max_polymorphic_calls; /* max number of inlined polymorphic calls */ zend_long max_trace_length; /* max length of a single trace */ zend_sym_node *symbols; /* symbols for disassembler */ bool tracing; zend_jit_trace_rec *current_trace; zend_jit_trace_stack_frame *current_frame; const zend_op *bad_root_cache_opline[ZEND_JIT_TRACE_BAD_ROOT_SLOTS]; uint8_t bad_root_cache_count[ZEND_JIT_TRACE_BAD_ROOT_SLOTS]; uint8_t bad_root_cache_stop[ZEND_JIT_TRACE_BAD_ROOT_SLOTS]; uint32_t bad_root_slot; uint8_t *exit_counters; } zend_jit_globals; #ifdef ZTS # define JIT_G(v) ZEND_TSRMG(jit_globals_id, zend_jit_globals *, v) extern int jit_globals_id; #else # define JIT_G(v) (jit_globals.v) extern zend_jit_globals jit_globals; #endif ZEND_EXT_API int zend_jit_op_array(zend_op_array *op_array, zend_script *script); ZEND_EXT_API int zend_jit_script(zend_script *script); ZEND_EXT_API void zend_jit_unprotect(void); ZEND_EXT_API void zend_jit_protect(void); ZEND_EXT_API void zend_jit_init(void); ZEND_EXT_API int zend_jit_config(zend_string *jit_options, int stage); ZEND_EXT_API int zend_jit_debug_config(zend_long old_val, zend_long new_val, int stage); ZEND_EXT_API int zend_jit_check_support(void); ZEND_EXT_API int zend_jit_startup(void *jit_buffer, size_t size, bool reattached); ZEND_EXT_API void zend_jit_shutdown(void); ZEND_EXT_API void zend_jit_activate(void); ZEND_EXT_API void zend_jit_deactivate(void); ZEND_EXT_API void zend_jit_status(zval *ret); ZEND_EXT_API void zend_jit_restart(void); typedef struct _zend_lifetime_interval zend_lifetime_interval; typedef struct _zend_life_range zend_life_range; struct _zend_life_range { uint32_t start; uint32_t end; zend_life_range *next; }; #define ZREG_FLAGS_SHIFT 8 #define ZREG_STORE (1<<0) #define ZREG_LOAD (1<<1) #define ZREG_LAST_USE (1<<2) #define ZREG_SPLIT (1<<3) struct _zend_lifetime_interval { int ssa_var; union { struct { ZEND_ENDIAN_LOHI_3( int8_t reg, uint8_t flags, uint16_t reserved )}; uint32_t reg_flags; }; zend_life_range range; zend_lifetime_interval *hint; zend_lifetime_interval *used_as_hint; zend_lifetime_interval *list_next; }; #endif /* HAVE_JIT_H */
7,932
40.317708
113
h
php-src
php-src-master/ext/opcache/jit/zend_jit_arm64.h
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Hao Sun <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef HAVE_JIT_ARM64_H #define HAVE_JIT_ARM64_H typedef enum _zend_reg { ZREG_NONE = -1, ZREG_X0, ZREG_X1, ZREG_X2, ZREG_X3, ZREG_X4, ZREG_X5, ZREG_X6, ZREG_X7, ZREG_X8, ZREG_X9, ZREG_X10, ZREG_X11, ZREG_X12, ZREG_X13, ZREG_X14, ZREG_X15, ZREG_X16, ZREG_X17, ZREG_X18, ZREG_X19, ZREG_X20, ZREG_X21, ZREG_X22, ZREG_X23, ZREG_X24, ZREG_X25, ZREG_X26, ZREG_X27, ZREG_X28, ZREG_X29, ZREG_X30, ZREG_X31, ZREG_V0, ZREG_V1, ZREG_V2, ZREG_V3, ZREG_V4, ZREG_V5, ZREG_V6, ZREG_V7, ZREG_V8, ZREG_V9, ZREG_V10, ZREG_V11, ZREG_V12, ZREG_V13, ZREG_V14, ZREG_V15, ZREG_V16, ZREG_V17, ZREG_V18, ZREG_V19, ZREG_V20, ZREG_V21, ZREG_V22, ZREG_V23, ZREG_V24, ZREG_V25, ZREG_V26, ZREG_V27, ZREG_V28, ZREG_V29, ZREG_V30, ZREG_V31, ZREG_NUM, ZREG_THIS, /* used for delayed FETCH_THIS deoptimization */ /* pseudo constants used by deoptimizer */ ZREG_LONG_MIN_MINUS_1, ZREG_LONG_MIN, ZREG_LONG_MAX, ZREG_LONG_MAX_PLUS_1, ZREG_NULL, ZREG_ZVAL_TRY_ADDREF, ZREG_ZVAL_COPY_GPR0, } zend_reg; typedef struct _zend_jit_registers_buf { uint64_t gpr[32]; /* general purpose integer register */ double fpr[32]; /* floating point registers */ } zend_jit_registers_buf; #define ZREG_RSP ZREG_X31 #define ZREG_RLR ZREG_X30 #define ZREG_RFP ZREG_X29 #define ZREG_RPR ZREG_X18 #define ZREG_FP ZREG_X27 #define ZREG_IP ZREG_X28 #define ZREG_RX ZREG_IP #define ZREG_REG0 ZREG_X8 #define ZREG_REG1 ZREG_X9 #define ZREG_REG2 ZREG_X10 #define ZREG_FPR0 ZREG_V0 #define ZREG_FPR1 ZREG_V1 #define ZREG_TMP1 ZREG_X15 #define ZREG_TMP2 ZREG_X16 #define ZREG_TMP3 ZREG_X17 #define ZREG_FPTMP ZREG_V16 #define ZREG_COPY ZREG_REG0 #define ZREG_FIRST_FPR ZREG_V0 typedef uint64_t zend_regset; #define ZEND_REGSET_64BIT 1 # define ZEND_REGSET_FIXED \ (ZEND_REGSET(ZREG_RSP) | ZEND_REGSET(ZREG_RLR) | ZEND_REGSET(ZREG_RFP) | \ ZEND_REGSET(ZREG_RPR) | ZEND_REGSET(ZREG_FP) | ZEND_REGSET(ZREG_IP) | \ ZEND_REGSET_INTERVAL(ZREG_TMP1, ZREG_TMP3) | ZEND_REGSET(ZREG_FPTMP)) # define ZEND_REGSET_GP \ ZEND_REGSET_DIFFERENCE(ZEND_REGSET_INTERVAL(ZREG_X0, ZREG_X30), ZEND_REGSET_FIXED) # define ZEND_REGSET_FP \ ZEND_REGSET_DIFFERENCE(ZEND_REGSET_INTERVAL(ZREG_V0, ZREG_V31), ZEND_REGSET_FIXED) # define ZEND_REGSET_SCRATCH \ (ZEND_REGSET_INTERVAL(ZREG_X0, ZREG_X17) | ZEND_REGSET_INTERVAL(ZREG_V0, ZREG_V7) | \ ZEND_REGSET_INTERVAL(ZREG_V16, ZREG_V31)) # define ZEND_REGSET_PRESERVED \ (ZEND_REGSET_INTERVAL(ZREG_X19, ZREG_X28) | ZEND_REGSET_INTERVAL(ZREG_V8, ZREG_V15)) #define ZEND_REGSET_LOW_PRIORITY \ (ZEND_REGSET(ZREG_REG0) | ZEND_REGSET(ZREG_REG1) | ZEND_REGSET(ZREG_FPR0) | ZEND_REGSET(ZREG_FPR1)) #endif /* ZEND_JIT_ARM64_H */
3,941
23.949367
100
h
php-src
php-src-master/ext/opcache/jit/zend_jit_disasm.c
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | | Hao Sun <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CAPSTONE # define HAVE_DISASM 1 # include <capstone.h> # define HAVE_CAPSTONE_ITER 1 #elif ZEND_JIT_TARGET_X86 # define HAVE_DISASM 1 # define DISASM_INTEL_SYNTAX 0 # include "jit/libudis86/itab.c" # include "jit/libudis86/decode.c" # include "jit/libudis86/syn.c" # if DISASM_INTEL_SYNTAX # include "jit/libudis86/syn-intel.c" # else # include "jit/libudis86/syn-att.c" # endif # include "jit/libudis86/udis86.c" #endif /* HAVE_CAPSTONE */ #ifdef HAVE_DISASM static void zend_jit_disasm_add_symbol(const char *name, uint64_t addr, uint64_t size); #ifndef _WIN32 # include "jit/zend_elf.c" #endif #include "zend_sort.h" #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #ifndef _WIN32 #include <dlfcn.h> #endif struct _sym_node { uint64_t addr; uint64_t end; struct _sym_node *parent; struct _sym_node *child[2]; unsigned char info; char name[1]; }; static void zend_syms_rotateleft(zend_sym_node *p) { zend_sym_node *r = p->child[1]; p->child[1] = r->child[0]; if (r->child[0]) { r->child[0]->parent = p; } r->parent = p->parent; if (p->parent == NULL) { JIT_G(symbols) = r; } else if (p->parent->child[0] == p) { p->parent->child[0] = r; } else { p->parent->child[1] = r; } r->child[0] = p; p->parent = r; } static void zend_syms_rotateright(zend_sym_node *p) { zend_sym_node *l = p->child[0]; p->child[0] = l->child[1]; if (l->child[1]) { l->child[1]->parent = p; } l->parent = p->parent; if (p->parent == NULL) { JIT_G(symbols) = l; } else if (p->parent->child[1] == p) { p->parent->child[1] = l; } else { p->parent->child[0] = l; } l->child[1] = p; p->parent = l; } static void zend_jit_disasm_add_symbol(const char *name, uint64_t addr, uint64_t size) { zend_sym_node *sym; size_t len = strlen(name); sym = malloc(sizeof(zend_sym_node) + len + 1); if (!sym) { return; } sym->addr = addr; sym->end = (addr + size - 1); memcpy((char*)&sym->name, name, len + 1); sym->parent = sym->child[0] = sym->child[1] = NULL; sym->info = 1; if (JIT_G(symbols)) { zend_sym_node *node = JIT_G(symbols); /* insert it into rbtree */ do { if (sym->addr > node->addr) { ZEND_ASSERT(sym->addr > (node->end)); if (node->child[1]) { node = node->child[1]; } else { node->child[1] = sym; sym->parent = node; break; } } else if (sym->addr < node->addr) { if (node->child[0]) { node = node->child[0]; } else { node->child[0] = sym; sym->parent = node; break; } } else { ZEND_ASSERT(sym->addr == node->addr); if (strcmp(name, node->name) == 0 && sym->end < node->end) { /* reduce size of the existing symbol */ node->end = sym->end; } free(sym); return; } } while (1); /* fix rbtree after instering */ while (sym && sym != JIT_G(symbols) && sym->parent->info == 1) { if (sym->parent == sym->parent->parent->child[0]) { node = sym->parent->parent->child[1]; if (node && node->info == 1) { sym->parent->info = 0; node->info = 0; sym->parent->parent->info = 1; sym = sym->parent->parent; } else { if (sym == sym->parent->child[1]) { sym = sym->parent; zend_syms_rotateleft(sym); } sym->parent->info = 0; sym->parent->parent->info = 1; zend_syms_rotateright(sym->parent->parent); } } else { node = sym->parent->parent->child[0]; if (node && node->info == 1) { sym->parent->info = 0; node->info = 0; sym->parent->parent->info = 1; sym = sym->parent->parent; } else { if (sym == sym->parent->child[0]) { sym = sym->parent; zend_syms_rotateright(sym); } sym->parent->info = 0; sym->parent->parent->info = 1; zend_syms_rotateleft(sym->parent->parent); } } } } else { JIT_G(symbols) = sym; } JIT_G(symbols)->info = 0; } static void zend_jit_disasm_destroy_symbols(zend_sym_node *n) { if (n) { if (n->child[0]) { zend_jit_disasm_destroy_symbols(n->child[0]); } if (n->child[1]) { zend_jit_disasm_destroy_symbols(n->child[1]); } free(n); } } static const char* zend_jit_disasm_find_symbol(uint64_t addr, int64_t *offset) { zend_sym_node *node = JIT_G(symbols); while (node) { if (addr < node->addr) { node = node->child[0]; } else if (addr > node->end) { node = node->child[1]; } else { *offset = addr - node->addr; return node->name; } } return NULL; } #ifdef HAVE_CAPSTONE static uint64_t zend_jit_disasm_branch_target(csh cs, const cs_insn *insn) { unsigned int i; #if ZEND_JIT_TARGET_X86 if (cs_insn_group(cs, insn, X86_GRP_JUMP)) { for (i = 0; i < insn->detail->x86.op_count; i++) { if (insn->detail->x86.operands[i].type == X86_OP_IMM) { return insn->detail->x86.operands[i].imm; } } } #elif ZEND_JIT_TARGET_ARM64 if (cs_insn_group(cs, insn, ARM64_GRP_JUMP) || insn->id == ARM64_INS_BL || insn->id == ARM64_INS_ADR) { for (i = 0; i < insn->detail->arm64.op_count; i++) { if (insn->detail->arm64.operands[i].type == ARM64_OP_IMM) return insn->detail->arm64.operands[i].imm; } } #endif return 0; } #endif static const char* zend_jit_disasm_resolver( #ifndef HAVE_CAPSTONE struct ud *ud, #endif uint64_t addr, int64_t *offset) { #ifndef _WIN32 # ifndef HAVE_CAPSTONE ((void)ud); # endif const char *name; void *a = (void*)(uintptr_t)(addr); Dl_info info; name = zend_jit_disasm_find_symbol(addr, offset); if (name) { return name; } if (dladdr(a, &info) && info.dli_sname != NULL && info.dli_saddr == a) { return info.dli_sname; } #else const char *name; name = zend_jit_disasm_find_symbol(addr, offset); if (name) { return name; } #endif return NULL; } static int zend_jit_cmp_labels(Bucket *b1, Bucket *b2) { return ((b1->h > b2->h) > 0) ? 1 : -1; } static int zend_jit_disasm(const char *name, const char *filename, const zend_op_array *op_array, zend_cfg *cfg, const void *start, size_t size) { const void *end = (void *)((char *)start + size); zval zv, *z; zend_long n, m; HashTable labels; uint64_t addr; int b; #ifdef HAVE_CAPSTONE csh cs; cs_insn *insn; # ifdef HAVE_CAPSTONE_ITER const uint8_t *cs_code; size_t cs_size; uint64_t cs_addr; # else size_t count, i; # endif const char *sym; int64_t offset = 0; char *p, *q, *r; #else struct ud ud; const struct ud_operand *op; #endif #ifdef HAVE_CAPSTONE # if ZEND_JIT_TARGET_X86 # if defined(__x86_64__) || defined(_WIN64) if (cs_open(CS_ARCH_X86, CS_MODE_64, &cs) != CS_ERR_OK) return 0; # else if (cs_open(CS_ARCH_X86, CS_MODE_32, &cs) != CS_ERR_OK) return 0; # endif cs_option(cs, CS_OPT_DETAIL, CS_OPT_ON); # if DISASM_INTEL_SYNTAX cs_option(cs, CS_OPT_SYNTAX, CS_OPT_SYNTAX_INTEL); # else cs_option(cs, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT); # endif # elif ZEND_JIT_TARGET_ARM64 if (cs_open(CS_ARCH_ARM64, CS_MODE_ARM, &cs) != CS_ERR_OK) return 0; cs_option(cs, CS_OPT_DETAIL, CS_OPT_ON); cs_option(cs, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT); # endif #else ud_init(&ud); # if defined(__x86_64__) || defined(_WIN64) ud_set_mode(&ud, 64); # else ud_set_mode(&ud, 32); # endif # if DISASM_INTEL_SYNTAX ud_set_syntax(&ud, UD_SYN_INTEL); # else ud_set_syntax(&ud, UD_SYN_ATT); # endif ud_set_sym_resolver(&ud, zend_jit_disasm_resolver); #endif /* HAVE_CAPSTONE */ if (name) { fprintf(stderr, "%s: ; (%s)\n", name, filename ? filename : "unknown"); } #ifndef HAVE_CAPSTONE ud_set_input_buffer(&ud, (uint8_t*)start, (uint8_t*)end - (uint8_t*)start); ud_set_pc(&ud, (uint64_t)(uintptr_t)start); #endif zend_hash_init(&labels, 8, NULL, NULL, 0); if (op_array && cfg) { ZVAL_FALSE(&zv); for (b = 0; b < cfg->blocks_count; b++) { if (cfg->blocks[b].flags & (ZEND_BB_ENTRY|ZEND_BB_RECV_ENTRY)) { addr = (uint64_t)(uintptr_t)op_array->opcodes[cfg->blocks[b].start].handler; if (addr >= (uint64_t)(uintptr_t)start && addr < (uint64_t)(uintptr_t)end) { zend_hash_index_add(&labels, addr, &zv); } } } } #ifdef HAVE_CAPSTONE ZVAL_TRUE(&zv); # ifdef HAVE_CAPSTONE_ITER cs_code = start; cs_size = (uint8_t*)end - (uint8_t*)start; cs_addr = (uint64_t)(uintptr_t)cs_code; insn = cs_malloc(cs); while (cs_disasm_iter(cs, &cs_code, &cs_size, &cs_addr, insn)) { if ((addr = zend_jit_disasm_branch_target(cs, insn))) { # else count = cs_disasm(cs, start, (uint8_t*)end - (uint8_t*)start, (uintptr_t)start, 0, &insn); for (i = 0; i < count; i++) { if ((addr = zend_jit_disasm_branch_target(cs, &(insn[i])))) { # endif if (addr >= (uint64_t)(uintptr_t)start && addr < (uint64_t)(uintptr_t)end) { zend_hash_index_add(&labels, addr, &zv); } } } #else ZVAL_TRUE(&zv); while (ud_disassemble(&ud)) { op = ud_insn_opr(&ud, 0); if (op && op->type == UD_OP_JIMM) { addr = ud_syn_rel_target(&ud, (struct ud_operand*)op); if (addr >= (uint64_t)(uintptr_t)start && addr < (uint64_t)(uintptr_t)end) { zend_hash_index_add(&labels, addr, &zv); } } } #endif zend_hash_sort(&labels, zend_jit_cmp_labels, 0); /* label numbering */ n = 0; m = 0; ZEND_HASH_MAP_FOREACH_VAL(&labels, z) { if (Z_TYPE_P(z) == IS_FALSE) { m--; ZVAL_LONG(z, m); } else { n++; ZVAL_LONG(z, n); } } ZEND_HASH_FOREACH_END(); #ifdef HAVE_CAPSTONE # ifdef HAVE_CAPSTONE_ITER cs_code = start; cs_size = (uint8_t*)end - (uint8_t*)start; cs_addr = (uint64_t)(uintptr_t)cs_code; while (cs_disasm_iter(cs, &cs_code, &cs_size, &cs_addr, insn)) { z = zend_hash_index_find(&labels, insn->address); # else for (i = 0; i < count; i++) { z = zend_hash_index_find(&labels, insn[i].address); # endif if (z) { if (Z_LVAL_P(z) < 0) { fprintf(stderr, ".ENTRY" ZEND_LONG_FMT ":\n", -Z_LVAL_P(z)); } else { fprintf(stderr, ".L" ZEND_LONG_FMT ":\n", Z_LVAL_P(z)); } } # ifdef HAVE_CAPSTONE_ITER if (JIT_G(debug) & ZEND_JIT_DEBUG_ASM_ADDR) { fprintf(stderr, " %" PRIx64 ":", insn->address); } fprintf(stderr, "\t%s ", insn->mnemonic); p = insn->op_str; # else if (JIT_G(debug) & ZEND_JIT_DEBUG_ASM_ADDR) { fprintf(stderr, " %" PRIx64 ":", insn[i].address); } fprintf(stderr, "\t%s ", insn[i].mnemonic); p = insn[i].op_str; # endif /* Try to replace the target addresses with a symbols */ while ((q = strchr(p, 'x')) != NULL) { if (p != q && *(q-1) == '0') { r = q + 1; addr = 0; while (1) { if (*r >= '0' && *r <= '9') { addr = addr * 16 + (*r - '0'); } else if (*r >= 'A' && *r <= 'F') { addr = addr * 16 + (*r - 'A' + 10); } else if (*r >= 'a' && *r <= 'f') { addr = addr * 16 + (*r - 'a' + 10); } else { break; } r++; } if (addr >= (uint64_t)(uintptr_t)start && addr < (uint64_t)(uintptr_t)end) { if ((z = zend_hash_index_find(&labels, addr))) { if (Z_LVAL_P(z) < 0) { fwrite(p, 1, q - p - 1, stderr); fprintf(stderr, ".ENTRY" ZEND_LONG_FMT, -Z_LVAL_P(z)); } else { fwrite(p, 1, q - p - 1, stderr); fprintf(stderr, ".L" ZEND_LONG_FMT, Z_LVAL_P(z)); } } else { fwrite(p, 1, r - p, stderr); } } else if ((sym = zend_jit_disasm_resolver(addr, &offset))) { fwrite(p, 1, q - p - 1, stderr); fputs(sym, stderr); if (offset != 0) { if (offset > 0) { fprintf(stderr, "+%" PRIx64, offset); } else { fprintf(stderr, "-%" PRIx64, offset); } } } else { fwrite(p, 1, r - p, stderr); } p = r; } else { fwrite(p, 1, q - p + 1, stderr); p = q + 1; } } fprintf(stderr, "%s\n", p); } # ifdef HAVE_CAPSTONE_ITER cs_free(insn, 1); # else cs_free(insn, count); # endif #else ud_set_input_buffer(&ud, (uint8_t*)start, (uint8_t*)end - (uint8_t*)start); ud_set_pc(&ud, (uint64_t)(uintptr_t)start); while (ud_disassemble(&ud)) { addr = ud_insn_off(&ud); z = zend_hash_index_find(&labels, addr); if (z) { if (Z_LVAL_P(z) < 0) { fprintf(stderr, ".ENTRY" ZEND_LONG_FMT ":\n", -Z_LVAL_P(z)); } else { fprintf(stderr, ".L" ZEND_LONG_FMT ":\n", Z_LVAL_P(z)); } } op = ud_insn_opr(&ud, 0); if (op && op->type == UD_OP_JIMM) { addr = ud_syn_rel_target(&ud, (struct ud_operand*)op); if (addr >= (uint64_t)(uintptr_t)start && addr < (uint64_t)(uintptr_t)end) { z = zend_hash_index_find(&labels, addr); if (z) { const char *str = ud_insn_asm(&ud); int len; len = 0; while (str[len] != 0 && str[len] != ' ' && str[len] != '\t') { len++; } if (str[len] != 0) { while (str[len] == ' ' || str[len] == '\t') { len++; } if (Z_LVAL_P(z) < 0) { fprintf(stderr, "\t%.*s.ENTRY" ZEND_LONG_FMT "\n", len, str, -Z_LVAL_P(z)); } else { fprintf(stderr, "\t%.*s.L" ZEND_LONG_FMT "\n", len, str, Z_LVAL_P(z)); } continue; } } } } if (JIT_G(debug) & ZEND_JIT_DEBUG_ASM_ADDR) { fprintf(stderr, " %" PRIx64 ":", ud_insn_off(&ud)); } fprintf(stderr, "\t%s\n", ud_insn_asm(&ud)); } #endif fprintf(stderr, "\n"); zend_hash_destroy(&labels); #ifdef HAVE_CAPSTONE cs_close(&cs); #endif return 1; } static int zend_jit_disasm_init(void) { #ifndef ZTS #define REGISTER_EG(n) \ zend_jit_disasm_add_symbol("EG("#n")", \ (uint64_t)(uintptr_t)&executor_globals.n, sizeof(executor_globals.n)) REGISTER_EG(uninitialized_zval); REGISTER_EG(exception); REGISTER_EG(vm_interrupt); REGISTER_EG(exception_op); REGISTER_EG(timed_out); REGISTER_EG(current_execute_data); REGISTER_EG(vm_stack_top); REGISTER_EG(vm_stack_end); REGISTER_EG(symbol_table); REGISTER_EG(jit_trace_num); #undef REGISTER_EG #define REGISTER_CG(n) \ zend_jit_disasm_add_symbol("CG("#n")", \ (uint64_t)(uintptr_t)&compiler_globals.n, sizeof(compiler_globals.n)) REGISTER_CG(map_ptr_base); #undef REGISTER_CG #endif /* Register JIT helper functions */ #define REGISTER_HELPER(n) \ zend_jit_disasm_add_symbol(#n, \ (uint64_t)(uintptr_t)n, sizeof(void*)); REGISTER_HELPER(memcmp); REGISTER_HELPER(zend_jit_init_func_run_time_cache_helper); REGISTER_HELPER(zend_jit_find_func_helper); REGISTER_HELPER(zend_jit_find_ns_func_helper); REGISTER_HELPER(zend_jit_find_method_helper); REGISTER_HELPER(zend_jit_find_method_tmp_helper); REGISTER_HELPER(zend_jit_push_static_metod_call_frame); REGISTER_HELPER(zend_jit_push_static_metod_call_frame_tmp); REGISTER_HELPER(zend_jit_invalid_method_call); REGISTER_HELPER(zend_jit_invalid_method_call_tmp); REGISTER_HELPER(zend_jit_unref_helper); REGISTER_HELPER(zend_jit_extend_stack_helper); REGISTER_HELPER(zend_jit_int_extend_stack_helper); REGISTER_HELPER(zend_jit_leave_nested_func_helper); REGISTER_HELPER(zend_jit_leave_top_func_helper); REGISTER_HELPER(zend_jit_leave_func_helper); REGISTER_HELPER(zend_jit_symtable_find); REGISTER_HELPER(zend_jit_hash_index_lookup_rw_no_packed); REGISTER_HELPER(zend_jit_hash_index_lookup_rw); REGISTER_HELPER(zend_jit_hash_lookup_rw); REGISTER_HELPER(zend_jit_symtable_lookup_rw); REGISTER_HELPER(zend_jit_symtable_lookup_w); REGISTER_HELPER(zend_jit_undefined_op_helper); REGISTER_HELPER(zend_jit_fetch_dim_r_helper); REGISTER_HELPER(zend_jit_fetch_dim_is_helper); REGISTER_HELPER(zend_jit_fetch_dim_isset_helper); REGISTER_HELPER(zend_jit_fetch_dim_str_offset_r_helper); REGISTER_HELPER(zend_jit_fetch_dim_str_r_helper); REGISTER_HELPER(zend_jit_fetch_dim_str_is_helper); REGISTER_HELPER(zend_jit_fetch_dim_obj_r_helper); REGISTER_HELPER(zend_jit_fetch_dim_obj_is_helper); REGISTER_HELPER(zend_jit_fetch_dim_rw_helper); REGISTER_HELPER(zend_jit_fetch_dim_w_helper); REGISTER_HELPER(zend_jit_fetch_dim_obj_rw_helper); REGISTER_HELPER(zend_jit_fetch_dim_obj_w_helper); // REGISTER_HELPER(zend_jit_fetch_dim_obj_unset_helper); REGISTER_HELPER(zend_jit_assign_dim_helper); REGISTER_HELPER(zend_jit_assign_dim_op_helper); REGISTER_HELPER(zend_jit_fast_assign_concat_helper); REGISTER_HELPER(zend_jit_fast_concat_helper); REGISTER_HELPER(zend_jit_fast_concat_tmp_helper); REGISTER_HELPER(zend_jit_isset_dim_helper); REGISTER_HELPER(zend_jit_free_call_frame); REGISTER_HELPER(zend_jit_fetch_global_helper); REGISTER_HELPER(zend_jit_verify_arg_slow); REGISTER_HELPER(zend_jit_verify_return_slow); REGISTER_HELPER(zend_jit_fetch_obj_r_slow); REGISTER_HELPER(zend_jit_fetch_obj_r_dynamic); REGISTER_HELPER(zend_jit_fetch_obj_is_slow); REGISTER_HELPER(zend_jit_fetch_obj_is_dynamic); REGISTER_HELPER(zend_jit_fetch_obj_w_slow); REGISTER_HELPER(zend_jit_check_array_promotion); REGISTER_HELPER(zend_jit_create_typed_ref); REGISTER_HELPER(zend_jit_extract_helper); REGISTER_HELPER(zend_jit_vm_stack_free_args_helper); REGISTER_HELPER(zend_jit_copy_extra_args_helper); REGISTER_HELPER(zend_jit_deprecated_helper); REGISTER_HELPER(zend_jit_assign_const_to_typed_ref); REGISTER_HELPER(zend_jit_assign_tmp_to_typed_ref); REGISTER_HELPER(zend_jit_assign_var_to_typed_ref); REGISTER_HELPER(zend_jit_assign_cv_to_typed_ref); REGISTER_HELPER(zend_jit_assign_const_to_typed_ref2); REGISTER_HELPER(zend_jit_assign_tmp_to_typed_ref2); REGISTER_HELPER(zend_jit_assign_var_to_typed_ref2); REGISTER_HELPER(zend_jit_assign_cv_to_typed_ref2); REGISTER_HELPER(zend_jit_pre_inc_typed_ref); REGISTER_HELPER(zend_jit_pre_dec_typed_ref); REGISTER_HELPER(zend_jit_post_inc_typed_ref); REGISTER_HELPER(zend_jit_post_dec_typed_ref); REGISTER_HELPER(zend_jit_assign_op_to_typed_ref); REGISTER_HELPER(zend_jit_assign_op_to_typed_ref_tmp); REGISTER_HELPER(zend_jit_only_vars_by_reference); REGISTER_HELPER(zend_jit_invalid_array_access); REGISTER_HELPER(zend_jit_invalid_property_read); REGISTER_HELPER(zend_jit_invalid_property_write); REGISTER_HELPER(zend_jit_invalid_property_incdec); REGISTER_HELPER(zend_jit_invalid_property_assign); REGISTER_HELPER(zend_jit_invalid_property_assign_op); REGISTER_HELPER(zend_jit_prepare_assign_dim_ref); REGISTER_HELPER(zend_jit_pre_inc); REGISTER_HELPER(zend_jit_pre_dec); REGISTER_HELPER(zend_runtime_jit); REGISTER_HELPER(zend_jit_hot_func); REGISTER_HELPER(zend_jit_check_constant); REGISTER_HELPER(zend_jit_get_constant); REGISTER_HELPER(zend_jit_array_free); REGISTER_HELPER(zend_jit_zval_array_dup); REGISTER_HELPER(zend_jit_add_arrays_helper); REGISTER_HELPER(zend_jit_assign_obj_helper); REGISTER_HELPER(zend_jit_assign_obj_op_helper); REGISTER_HELPER(zend_jit_assign_to_typed_prop); REGISTER_HELPER(zend_jit_assign_op_to_typed_prop); REGISTER_HELPER(zend_jit_inc_typed_prop); REGISTER_HELPER(zend_jit_dec_typed_prop); REGISTER_HELPER(zend_jit_pre_inc_typed_prop); REGISTER_HELPER(zend_jit_pre_dec_typed_prop); REGISTER_HELPER(zend_jit_post_inc_typed_prop); REGISTER_HELPER(zend_jit_post_dec_typed_prop); REGISTER_HELPER(zend_jit_pre_inc_obj_helper); REGISTER_HELPER(zend_jit_pre_dec_obj_helper); REGISTER_HELPER(zend_jit_post_inc_obj_helper); REGISTER_HELPER(zend_jit_post_dec_obj_helper); REGISTER_HELPER(zend_jit_rope_end); REGISTER_HELPER(zend_jit_free_trampoline_helper); REGISTER_HELPER(zend_jit_exception_in_interrupt_handler_helper); #undef REGISTER_HELPER #ifndef _WIN32 zend_elf_load_symbols(); #endif if (zend_vm_kind() == ZEND_VM_KIND_HYBRID) { zend_op opline; memset(&opline, 0, sizeof(opline)); opline.opcode = ZEND_DO_UCALL; opline.result_type = IS_UNUSED; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_UCALL_SPEC_RETVAL_UNUSED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_DO_UCALL; opline.result_type = IS_VAR; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_UCALL_SPEC_RETVAL_USED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_DO_FCALL_BY_NAME; opline.result_type = IS_UNUSED; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_FCALL_BY_NAME_SPEC_RETVAL_UNUSED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_DO_FCALL_BY_NAME; opline.result_type = IS_VAR; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_FCALL_BY_NAME_SPEC_RETVAL_USED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_DO_FCALL; opline.result_type = IS_UNUSED; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_FCALL_SPEC_RETVAL_UNUSED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_DO_FCALL; opline.result_type = IS_VAR; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_DO_FCALL_SPEC_RETVAL_USED_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_RETURN; opline.op1_type = IS_CONST; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_RETURN_SPEC_CONST_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_RETURN; opline.op1_type = IS_TMP_VAR; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_RETURN_SPEC_TMP_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_RETURN; opline.op1_type = IS_VAR; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_RETURN_SPEC_VAR_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); opline.opcode = ZEND_RETURN; opline.op1_type = IS_CV; zend_vm_set_opcode_handler(&opline); zend_jit_disasm_add_symbol("ZEND_RETURN_SPEC_CV_LABEL", (uint64_t)(uintptr_t)opline.handler, sizeof(void*)); zend_jit_disasm_add_symbol("ZEND_HYBRID_HALT_LABEL", (uint64_t)(uintptr_t)zend_jit_halt_op->handler, sizeof(void*)); } return 1; } static void zend_jit_disasm_shutdown(void) { if (JIT_G(symbols)) { zend_jit_disasm_destroy_symbols(JIT_G(symbols)); JIT_G(symbols) = NULL; } } #endif /* HAVE_DISASM */
23,592
29.170077
131
c
php-src
php-src-master/ext/opcache/jit/zend_jit_gdb.h
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef HAVE_ZEND_JIT_GDB_H #define HAVE_ZEND_JIT_GDB_H #include "zend_compile.h" #define HAVE_GDB int zend_jit_gdb_register(const char *name, const zend_op_array *op_array, const void *start, size_t size, uint32_t sp_offset, uint32_t sp_adjustment); int zend_jit_gdb_unregister(void); void zend_jit_gdb_init(void); #endif /* HAVE_ZEND_JIT_GDB_H */
1,733
44.631579
75
h
php-src
php-src-master/ext/opcache/jit/zend_jit_perf_dump.c
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #define HAVE_PERFTOOLS 1 #include <stdio.h> #include <unistd.h> #include <time.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if !defined(HAVE_OS_SIGNPOST_H) #if defined(__linux__) #include <sys/syscall.h> #elif defined(__darwin__) # include <pthread.h> #elif defined(__FreeBSD__) # include <sys/thr.h> # include <sys/sysctl.h> #elif defined(__NetBSD__) # include <lwp.h> #elif defined(__DragonFly__) # include <sys/lwp.h> # include <sys/sysctl.h> #elif defined(__sun) // avoiding thread.h inclusion as it conflicts with vtunes types. extern unsigned int thr_self(void); #elif defined(__HAIKU__) #include <FindDirectory.h> #endif #include "zend_elf.h" #include "zend_mmap.h" /* * 1) Profile using perf-<pid>.map * * perf record php -d opcache.huge_code_pages=0 -d opcache.jit_debug=0x10 bench.php * perf report * * 2) Profile using jit-<pid>.dump * * perf record -k 1 php -d opcache.huge_code_pages=0 -d opcache.jit_debug=0x20 bench.php * perf inject -j -i perf.data -o perf.data.jitted * perf report -i perf.data.jitted * */ #define ZEND_PERF_JITDUMP_HEADER_MAGIC 0x4A695444 #define ZEND_PERF_JITDUMP_HEADER_VERSION 1 #define ZEND_PERF_JITDUMP_RECORD_LOAD 0 #define ZEND_PERF_JITDUMP_RECORD_MOVE 1 #define ZEND_PERF_JITDUMP_RECORD_DEBUG_INFO 2 #define ZEND_PERF_JITDUMP_RECORD_CLOSE 3 #define ZEND_PERF_JITDUMP_UNWINDING_UNFO 4 #define ALIGN8(size) (((size) + 7) & ~7) #define PADDING8(size) (ALIGN8(size) - (size)) typedef struct zend_perf_jitdump_header { uint32_t magic; uint32_t version; uint32_t size; uint32_t elf_mach_target; uint32_t reserved; uint32_t process_id; uint64_t time_stamp; uint64_t flags; } zend_perf_jitdump_header; typedef struct _zend_perf_jitdump_record { uint32_t event; uint32_t size; uint64_t time_stamp; } zend_perf_jitdump_record; typedef struct _zend_perf_jitdump_load_record { zend_perf_jitdump_record hdr; uint32_t process_id; uint32_t thread_id; uint64_t vma; uint64_t code_address; uint64_t code_size; uint64_t code_id; } zend_perf_jitdump_load_record; static int jitdump_fd = -1; static void *jitdump_mem = MAP_FAILED; static uint64_t zend_perf_timestamp(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { return 0; } return ((uint64_t)ts.tv_sec * 1000000000) + ts.tv_nsec; } static void zend_jit_perf_jitdump_open(void) { char filename[64]; int fd, ret; zend_elf_header elf_hdr; zend_perf_jitdump_header jit_hdr; sprintf(filename, "/tmp/jit-%d.dump", getpid()); if (!zend_perf_timestamp()) { return; } #if defined(__linux__) fd = open("/proc/self/exe", O_RDONLY); #elif defined(__NetBSD__) fd = open("/proc/curproc/exe", O_RDONLY); #elif defined(__FreeBSD__) || defined(__DragonFly__) char path[PATH_MAX]; size_t pathlen = sizeof(path); int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; if (sysctl(mib, 4, path, &pathlen, NULL, 0) == -1) { return; } fd = open(path, O_RDONLY); #elif defined(__sun) fd = open("/proc/self/path/a.out", O_RDONLY); #elif defined(__HAIKU__) char path[PATH_MAX]; if (find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, path, sizeof(path)) != B_OK) { return; } fd = open(path, O_RDONLY); #else fd = -1; #endif if (fd < 0) { return; } ret = read(fd, &elf_hdr, sizeof(elf_hdr)); close(fd); if (ret != sizeof(elf_hdr) || elf_hdr.emagic[0] != 0x7f || elf_hdr.emagic[1] != 'E' || elf_hdr.emagic[2] != 'L' || elf_hdr.emagic[3] != 'F') { return; } jitdump_fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0666); if (jitdump_fd < 0) { return; } const size_t page_size = sysconf(_SC_PAGESIZE); jitdump_mem = mmap(NULL, page_size, PROT_READ|PROT_EXEC, MAP_PRIVATE, jitdump_fd, 0); if (jitdump_mem == MAP_FAILED) { close(jitdump_fd); jitdump_fd = -1; return; } zend_mmap_set_name(jitdump_mem, page_size, "zend_jitdump"); memset(&jit_hdr, 0, sizeof(jit_hdr)); jit_hdr.magic = ZEND_PERF_JITDUMP_HEADER_MAGIC; jit_hdr.version = ZEND_PERF_JITDUMP_HEADER_VERSION; jit_hdr.size = sizeof(jit_hdr); jit_hdr.elf_mach_target = elf_hdr.machine; jit_hdr.process_id = getpid(); jit_hdr.time_stamp = zend_perf_timestamp(); jit_hdr.flags = 0; zend_quiet_write(jitdump_fd, &jit_hdr, sizeof(jit_hdr)); } static void zend_jit_perf_jitdump_close(void) { if (jitdump_fd >= 0) { zend_perf_jitdump_record rec; rec.event = ZEND_PERF_JITDUMP_RECORD_CLOSE; rec.size = sizeof(rec); rec.time_stamp = zend_perf_timestamp(); zend_quiet_write(jitdump_fd, &rec, sizeof(rec)); close(jitdump_fd); if (jitdump_mem != MAP_FAILED) { munmap(jitdump_mem, sysconf(_SC_PAGESIZE)); } } } static void zend_jit_perf_jitdump_register(const char *name, void *start, size_t size) { if (jitdump_fd >= 0) { static uint64_t id = 1; zend_perf_jitdump_load_record rec; size_t len = strlen(name); uint32_t thread_id = 0; #if defined(__linux__) thread_id = syscall(SYS_gettid); #elif defined(__darwin__) uint64_t thread_id_u64; pthread_threadid_np(NULL, &thread_id_u64); thread_id = (uint32_t) thread_id_u64; #elif defined(__FreeBSD__) long tid; thr_self(&tid); thread_id = (uint32_t)tid; #elif defined(__OpenBSD__) thread_id = getthrid(); #elif defined(__NetBSD__) thread_id = _lwp_self(); #elif defined(__DragonFly__) thread_id = lwp_gettid(); #elif defined(__sun) thread_id = thr_self(); #endif memset(&rec, 0, sizeof(rec)); rec.hdr.event = ZEND_PERF_JITDUMP_RECORD_LOAD; rec.hdr.size = sizeof(rec) + len + 1 + size; rec.hdr.time_stamp = zend_perf_timestamp(); rec.process_id = getpid(); rec.thread_id = thread_id; rec.vma = (uint64_t)(uintptr_t)start; rec.code_address = (uint64_t)(uintptr_t)start; rec.code_size = (uint64_t)size; rec.code_id = id++; zend_quiet_write(jitdump_fd, &rec, sizeof(rec)); zend_quiet_write(jitdump_fd, name, len + 1); zend_quiet_write(jitdump_fd, start, size); } } static void zend_jit_perf_map_register(const char *name, void *start, size_t size) { static FILE *fp = NULL; if (!fp) { char filename[64]; sprintf(filename, "/tmp/perf-%d.map", getpid()); fp = fopen(filename, "w"); if (!fp) { return; } setlinebuf(fp); } fprintf(fp, "%zx %zx %s\n", (size_t)(uintptr_t)start, size, name); } #else #include <os/log.h> #include <os/signpost.h> /* * 1) To generate an Instrument tracing data: * xcrun xctrace record --template <Template name> --launch -- php * xcrun xctrace record --template Logging --launch -- php -dopcache.jit=1255 -dopcache.jit_debug=32 bench.php * 2) An instrument trace folder is created: * e.g. open Launch_php_2022-07-03_15.41.05_5F96D825.trace */ static os_log_t jitdump_fd; static os_signpost_id_t jitdump_sp = OS_SIGNPOST_ID_NULL; static void zend_jit_perf_jitdump_open(void) { /** * The `os_log_t` list per namespace is maintained by the os * and are not deallocated by (and not deallocatable) * but are reusable. */ jitdump_fd = os_log_create("net.php.opcache.jit", OS_LOG_CATEGORY_POINTS_OF_INTEREST); jitdump_sp = os_signpost_id_generate(jitdump_fd); if (jitdump_sp != OS_SIGNPOST_ID_NULL && jitdump_sp != OS_SIGNPOST_ID_INVALID) { os_signpost_interval_begin(jitdump_fd, jitdump_sp, "zend_jitdump"); } } static void zend_jit_perf_jitdump_close(void) { if (jitdump_sp != OS_SIGNPOST_ID_NULL && jitdump_sp != OS_SIGNPOST_ID_INVALID) { os_signpost_interval_end(jitdump_fd, jitdump_sp, "zend_jitdump"); } } static void zend_jit_perf_jitdump_register(const char *name, void *start, size_t size) { } static void zend_jit_perf_map_register(const char *name, void *start, size_t size) { os_signpost_id_t map = os_signpost_id_make_with_pointer(jitdump_fd, start); if (map != OS_SIGNPOST_ID_NULL && map != OS_SIGNPOST_ID_INVALID) { os_signpost_event_emit(jitdump_fd, map, "zend_jitdump_name", "%s", name); os_signpost_event_emit(jitdump_fd, map, "zend_jitdump_size", "%lu", size); } } #endif
9,210
27.082317
110
c
php-src
php-src-master/ext/opcache/jit/zend_jit_vtune.c
/* +----------------------------------------------------------------------+ | Zend JIT | +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #if defined(__x86_64__) || defined(i386) #define HAVE_VTUNE 1 #include "jit/vtune/jitprofiling.h" #include "jit/vtune/jitprofiling.c" static void zend_jit_vtune_register(const char *name, const void *start, size_t size) { iJIT_Method_Load jmethod = {0}; if (iJIT_IsProfilingActive() != iJIT_SAMPLING_ON) { return; } jmethod.method_id = iJIT_GetNewMethodID(); jmethod.method_name = (char*)name; jmethod.class_file_name = NULL; jmethod.source_file_name = NULL; jmethod.method_load_address = (void*)start; jmethod.method_size = size; iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, (void*)&jmethod); } #endif /* defined(__x86_64__) || defined(i386) */
1,899
39.425532
75
c
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_arm.h
/* ** DynASM ARM encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "arm" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. */ enum { DASM_STOP, DASM_SECTION, DASM_ESC, DASM_REL_EXT, /* The following actions need a buffer position. */ DASM_ALIGN, DASM_REL_LG, DASM_LABEL_LG, /* The following actions also have an argument. */ DASM_REL_PC, DASM_LABEL_PC, DASM_IMM, DASM_IMM12, DASM_IMM16, DASM_IMML8, DASM_IMML12, DASM_IMMV8, DASM__MAX }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_REL 0x15000000 #define DASM_S_UNDEF_LG 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned int *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; D->globals = gl - 10; /* Negative bias to compensate for locals. */ DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status = DASM_S_RANGE_##st|(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif static int dasm_imm12(unsigned int n) { int i; for (i = 0; i < 16; i++, n = (n << 2) | (n >> 30)) if (n <= 255) return (int)(n + (i << 8)); return -1; } /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); if (action >= DASM__MAX) { ofs += 4; } else { int *pl, n = action >= DASM_REL_PC ? va_arg(ap, int) : 0; switch (action) { case DASM_STOP: goto stop; case DASM_SECTION: n = (ins & 255); CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; goto stop; case DASM_ESC: p++; ofs += 4; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs += (ins & 255); b[pos++] = ofs; break; case DASM_REL_LG: n = (ins & 2047) - 10; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n >= 0) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl += 10; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: pl = D->pclabels + n; CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; break; case DASM_LABEL_LG: pl = D->lglabels + (ins & 2047) - 10; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + n; CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_IMM: case DASM_IMM16: #ifdef DASM_CHECKS CK((n & ((1<<((ins>>10)&31))-1)) == 0, RANGE_I); if ((ins & 0x8000)) CK(((n + (1<<(((ins>>5)&31)-1)))>>((ins>>5)&31)) == 0, RANGE_I); else CK((n>>((ins>>5)&31)) == 0, RANGE_I); #endif b[pos++] = n; break; case DASM_IMMV8: CK((n & 3) == 0, RANGE_I); n >>= 2; /* fallthrough */ case DASM_IMML8: case DASM_IMML12: CK(n >= 0 ? ((n>>((ins>>5)&31)) == 0) : (((-n)>>((ins>>5)&31)) == 0), RANGE_I); b[pos++] = n; break; case DASM_IMM12: CK(dasm_imm12((unsigned int)n) != -1, RANGE_I); b[pos++] = n; break; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: p++; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs -= (b[pos++] + ofs) & (ins & 255); break; case DASM_REL_LG: case DASM_REL_PC: pos++; break; case DASM_LABEL_LG: case DASM_LABEL_PC: b[pos++] += ofs; break; case DASM_IMM: case DASM_IMM12: case DASM_IMM16: case DASM_IMML8: case DASM_IMML12: case DASM_IMMV8: pos++; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) return DASM_S_##st|(p-D->actionlist-1); } while (0) #else #define CK(x, st) ((void)0) #endif /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; char *base = (char *)buffer; unsigned int *cp = (unsigned int *)buffer; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = sec->rbuf + sec->pos; while (b != endb) { dasm_ActList p = D->actionlist + *b++; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); int n = (action >= DASM_ALIGN && action < DASM__MAX) ? *b++ : 0; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: *cp++ = *p++; break; case DASM_REL_EXT: n = DASM_EXTERN(Dst, (unsigned char *)cp, (ins&2047), !(ins&2048)); goto patchrel; case DASM_ALIGN: ins &= 255; while ((((char *)cp - base) & ins)) *cp++ = 0xe1a00000; break; case DASM_REL_LG: if (n < 0) { n = (int)((ptrdiff_t)D->globals[-n] - (ptrdiff_t)cp - 4); goto patchrel; } /* fallthrough */ case DASM_REL_PC: CK(n >= 0, UNDEF_PC); n = *DASM_POS2PTR(D, n) - (int)((char *)cp - base) - 4; patchrel: if ((ins & 0x800) == 0) { CK((n & 3) == 0 && ((n+0x02000000) >> 26) == 0, RANGE_REL); cp[-1] |= ((n >> 2) & 0x00ffffff); } else if ((ins & 0x1000)) { CK((n & 3) == 0 && -256 <= n && n <= 256, RANGE_REL); goto patchimml8; } else if ((ins & 0x2000) == 0) { CK((n & 3) == 0 && -4096 <= n && n <= 4096, RANGE_REL); goto patchimml; } else { CK((n & 3) == 0 && -1020 <= n && n <= 1020, RANGE_REL); n >>= 2; goto patchimml; } break; case DASM_LABEL_LG: ins &= 2047; if (ins >= 20) D->globals[ins-10] = (void *)(base + n); break; case DASM_LABEL_PC: break; case DASM_IMM: cp[-1] |= ((n>>((ins>>10)&31)) & ((1<<((ins>>5)&31))-1)) << (ins&31); break; case DASM_IMM12: cp[-1] |= dasm_imm12((unsigned int)n); break; case DASM_IMM16: cp[-1] |= ((n & 0xf000) << 4) | (n & 0x0fff); break; case DASM_IMML8: patchimml8: cp[-1] |= n >= 0 ? (0x00800000 | (n & 0x0f) | ((n & 0xf0) << 4)) : ((-n & 0x0f) | ((-n & 0xf0) << 4)); break; case DASM_IMML12: case DASM_IMMV8: patchimml: cp[-1] |= n >= 0 ? (0x00800000 | n) : (-n); break; default: *cp++ = ins; break; } } stop: (void)0; } } if (base + D->codesize != (char *)cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } #undef CK /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_LG|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(D->section-D->sections); return D->status; } #endif
13,542
28.313853
80
h
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_arm64.h
/* ** DynASM ARM64 encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "arm64" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. */ enum { DASM_STOP, DASM_SECTION, DASM_ESC, DASM_REL_EXT, /* The following actions need a buffer position. */ DASM_ALIGN, DASM_REL_LG, DASM_LABEL_LG, /* The following actions also have an argument. */ DASM_REL_PC, DASM_LABEL_PC, DASM_REL_A, DASM_IMM, DASM_IMM6, DASM_IMM12, DASM_IMM13W, DASM_IMM13X, DASM_IMML, DASM_IMMV, DASM_VREG, DASM__MAX }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_REL 0x15000000 #define DASM_S_RANGE_VREG 0x16000000 #define DASM_S_UNDEF_LG 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned int *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; D->globals = gl - 10; /* Negative bias to compensate for locals. */ DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status = DASM_S_RANGE_##st|(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif static int dasm_imm12(unsigned int n) { if ((n >> 12) == 0) return n; else if ((n & 0xff000fff) == 0) return (n >> 12) | 0x1000; else return -1; } static int dasm_ffs(unsigned long long x) { int n = -1; while (x) { x >>= 1; n++; } return n; } static int dasm_imm13(int lo, int hi) { int inv = 0, w = 64, s = 0xfff, xa, xb; unsigned long long n = (((unsigned long long)hi) << 32) | (unsigned int)lo; unsigned long long m = 1ULL, a, b, c; if (n & 1) { n = ~n; inv = 1; } a = n & -n; b = (n+a)&-(n+a); c = (n+a-b)&-(n+a-b); xa = dasm_ffs(a); xb = dasm_ffs(b); if (c) { w = dasm_ffs(c) - xa; if (w == 32) m = 0x0000000100000001UL; else if (w == 16) m = 0x0001000100010001UL; else if (w == 8) m = 0x0101010101010101UL; else if (w == 4) m = 0x1111111111111111UL; else if (w == 2) m = 0x5555555555555555UL; else return -1; s = (-2*w & 0x3f) - 1; } else if (!a) { return -1; } else if (xb == -1) { xb = 64; } if ((b-a) * m != n) return -1; if (inv) { return ((w - xb) << 6) | (s+w+xa-xb); } else { return ((w - xa) << 6) | (s+xb-xa); } return -1; } /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); if (action >= DASM__MAX) { ofs += 4; } else { int *pl, n = action >= DASM_REL_PC ? va_arg(ap, int) : 0; switch (action) { case DASM_STOP: goto stop; case DASM_SECTION: n = (ins & 255); CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; goto stop; case DASM_ESC: p++; ofs += 4; break; case DASM_REL_EXT: if ((ins & 0x8000)) ofs += 8; break; case DASM_ALIGN: ofs += (ins & 255); b[pos++] = ofs; break; case DASM_REL_LG: n = (ins & 2047) - 10; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n >= 0) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl += 10; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: pl = D->pclabels + n; CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; if ((ins & 0x8000)) ofs += 8; break; case DASM_REL_A: b[pos++] = n; b[pos++] = va_arg(ap, int); break; case DASM_LABEL_LG: pl = D->lglabels + (ins & 2047) - 10; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + n; CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_IMM: CK((n & ((1<<((ins>>10)&31))-1)) == 0, RANGE_I); n >>= ((ins>>10)&31); #ifdef DASM_CHECKS if ((ins & 0x8000)) CK(((n + (1<<(((ins>>5)&31)-1)))>>((ins>>5)&31)) == 0, RANGE_I); else CK((n>>((ins>>5)&31)) == 0, RANGE_I); #endif b[pos++] = n; break; case DASM_IMM6: CK((n >> 6) == 0, RANGE_I); b[pos++] = n; break; case DASM_IMM12: CK(dasm_imm12((unsigned int)n) != -1, RANGE_I); b[pos++] = n; break; case DASM_IMM13W: CK(dasm_imm13(n, n) != -1, RANGE_I); b[pos++] = n; break; case DASM_IMM13X: { int m = va_arg(ap, int); CK(dasm_imm13(n, m) != -1, RANGE_I); b[pos++] = n; b[pos++] = m; break; } case DASM_IMML: { #ifdef DASM_CHECKS int scale = (ins & 3); CK((!(n & ((1<<scale)-1)) && (unsigned int)(n>>scale) < 4096) || (unsigned int)(n+256) < 512, RANGE_I); #endif b[pos++] = n; break; } case DASM_IMMV: ofs += 4; b[pos++] = n; break; case DASM_VREG: CK(n < 32, RANGE_VREG); b[pos++] = n; break; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: p++; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs -= (b[pos++] + ofs) & (ins & 255); break; case DASM_REL_LG: case DASM_REL_PC: pos++; break; case DASM_LABEL_LG: case DASM_LABEL_PC: b[pos++] += ofs; break; case DASM_IMM: case DASM_IMM6: case DASM_IMM12: case DASM_IMM13W: case DASM_IMML: case DASM_IMMV: case DASM_VREG: pos++; break; case DASM_IMM13X: case DASM_REL_A: pos += 2; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #ifdef DASM_ADD_VENEER #define CK_REL(x, o) \ do { if (!(x) && !(n = DASM_ADD_VENEER(D, buffer, ins, b, cp, o))) \ return DASM_S_RANGE_REL|(p-D->actionlist-1); \ } while (0) #else #define CK_REL(x, o) CK(x, RANGE_REL) #endif #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) return DASM_S_##st|(p-D->actionlist-1); } while (0) #else #define CK(x, st) ((void)0) #endif /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; char *base = (char *)buffer; unsigned int *cp = (unsigned int *)buffer; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = sec->rbuf + sec->pos; while (b != endb) { dasm_ActList p = D->actionlist + *b++; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); int n = (action >= DASM_ALIGN && action < DASM__MAX) ? *b++ : 0; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: *cp++ = *p++; break; case DASM_REL_EXT: n = DASM_EXTERN(Dst, (unsigned char *)cp, (ins&2047), !(ins&2048)); goto patchrel; case DASM_ALIGN: ins &= 255; while ((((char *)cp - base) & ins)) *cp++ = 0xe1a00000; break; case DASM_REL_LG: if (n < 0) { ptrdiff_t na = (ptrdiff_t)D->globals[-n] - (ptrdiff_t)cp + 4; n = (int)na; CK_REL((ptrdiff_t)n == na, na); goto patchrel; } /* fallthrough */ case DASM_REL_PC: CK(n >= 0, UNDEF_PC); n = *DASM_POS2PTR(D, n) - (int)((char *)cp - base) + 4; patchrel: if (!(ins & 0xf800)) { /* B, BL */ CK_REL((n & 3) == 0 && ((n+0x08000000) >> 28) == 0, n); cp[-1] |= ((n >> 2) & 0x03ffffff); } else if ((ins & 0x800)) { /* B.cond, CBZ, CBNZ, LDR* literal */ CK_REL((n & 3) == 0 && ((n+0x00100000) >> 21) == 0, n); cp[-1] |= ((n << 3) & 0x00ffffe0); } else if ((ins & 0x3000) == 0x2000) { /* ADR */ CK_REL(((n+0x00100000) >> 21) == 0, n); cp[-1] |= ((n << 3) & 0x00ffffe0) | ((n & 3) << 29); } else if ((ins & 0x3000) == 0x3000) { /* ADRP */ cp[-1] |= ((n >> 9) & 0x00ffffe0) | (((n >> 12) & 3) << 29); } else if ((ins & 0x1000)) { /* TBZ, TBNZ */ CK_REL((n & 3) == 0 && ((n+0x00008000) >> 16) == 0, n); cp[-1] |= ((n << 3) & 0x0007ffe0); } else if ((ins & 0x8000)) { /* absolute */ cp[0] = (unsigned int)((ptrdiff_t)cp - 4 + n); cp[1] = (unsigned int)(((ptrdiff_t)cp - 4 + n) >> 32); cp += 2; } break; case DASM_REL_A: { ptrdiff_t na = (((ptrdiff_t)(*b++) << 32) | (unsigned int)n); if ((ins & 0x3000) == 0x3000) { /* ADRP */ ins &= ~0x1000; na = (na >> 12) - (((ptrdiff_t)cp - 4) >> 12); } else { na = na - (ptrdiff_t)cp + 4; } n = (int)na; CK_REL((ptrdiff_t)n == na, na); goto patchrel; } case DASM_LABEL_LG: ins &= 2047; if (ins >= 20) D->globals[ins-10] = (void *)(base + n); break; case DASM_LABEL_PC: break; case DASM_IMM: cp[-1] |= (n & ((1<<((ins>>5)&31))-1)) << (ins&31); break; case DASM_IMM6: cp[-1] |= ((n&31) << 19) | ((n&32) << 26); break; case DASM_IMM12: cp[-1] |= (dasm_imm12((unsigned int)n) << 10); break; case DASM_IMM13W: cp[-1] |= (dasm_imm13(n, n) << 10); break; case DASM_IMM13X: cp[-1] |= (dasm_imm13(n, *b++) << 10); break; case DASM_IMML: { int scale = (ins & 3); cp[-1] |= (!(n & ((1<<scale)-1)) && (unsigned int)(n>>scale) < 4096) ? ((n << (10-scale)) | 0x01000000) : ((n & 511) << 12); break; } case DASM_IMMV: *cp++ = n; break; case DASM_VREG: cp[-1] |= (n & 0x1f) << (ins & 0x1f); break; default: *cp++ = ins; break; } } stop: (void)0; } } if (base + D->codesize != (char *)cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } #undef CK /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_LG|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(D->section-D->sections); return D->status; } #endif
16,417
27.753065
80
h
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_mips.h
/* ** DynASM MIPS encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "mips" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. */ enum { DASM_STOP, DASM_SECTION, DASM_ESC, DASM_REL_EXT, /* The following actions need a buffer position. */ DASM_ALIGN, DASM_REL_LG, DASM_LABEL_LG, /* The following actions also have an argument. */ DASM_REL_PC, DASM_LABEL_PC, DASM_IMM, DASM_IMMS, DASM__MAX }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_REL 0x15000000 #define DASM_S_UNDEF_LG 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned int *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; D->globals = gl - 10; /* Negative bias to compensate for locals. */ DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status = DASM_S_RANGE_##st|(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; if (action >= DASM__MAX) { ofs += 4; } else { int *pl, n = action >= DASM_REL_PC ? va_arg(ap, int) : 0; switch (action) { case DASM_STOP: goto stop; case DASM_SECTION: n = (ins & 255); CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; goto stop; case DASM_ESC: p++; ofs += 4; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs += (ins & 255); b[pos++] = ofs; break; case DASM_REL_LG: n = (ins & 2047) - 10; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n >= 0) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl += 10; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: pl = D->pclabels + n; CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; break; case DASM_LABEL_LG: pl = D->lglabels + (ins & 2047) - 10; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + n; CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_IMM: case DASM_IMMS: #ifdef DASM_CHECKS CK((n & ((1<<((ins>>10)&31))-1)) == 0, RANGE_I); #endif n >>= ((ins>>10)&31); #ifdef DASM_CHECKS if (ins & 0x8000) CK(((n + (1<<(((ins>>5)&31)-1)))>>((ins>>5)&31)) == 0, RANGE_I); else CK((n>>((ins>>5)&31)) == 0, RANGE_I); #endif b[pos++] = n; break; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: p++; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs -= (b[pos++] + ofs) & (ins & 255); break; case DASM_REL_LG: case DASM_REL_PC: pos++; break; case DASM_LABEL_LG: case DASM_LABEL_PC: b[pos++] += ofs; break; case DASM_IMM: case DASM_IMMS: pos++; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) return DASM_S_##st|(p-D->actionlist-1); } while (0) #else #define CK(x, st) ((void)0) #endif /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; char *base = (char *)buffer; unsigned int *cp = (unsigned int *)buffer; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = sec->rbuf + sec->pos; while (b != endb) { dasm_ActList p = D->actionlist + *b++; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; int n = (action >= DASM_ALIGN && action < DASM__MAX) ? *b++ : 0; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: *cp++ = *p++; break; case DASM_REL_EXT: n = DASM_EXTERN(Dst, (unsigned char *)cp, (ins & 2047), 1); goto patchrel; case DASM_ALIGN: ins &= 255; while ((((char *)cp - base) & ins)) *cp++ = 0x60000000; break; case DASM_REL_LG: if (n < 0) { n = (int)((ptrdiff_t)D->globals[-n] - (ptrdiff_t)cp); goto patchrel; } /* fallthrough */ case DASM_REL_PC: CK(n >= 0, UNDEF_PC); n = *DASM_POS2PTR(D, n); if (ins & 2048) n = (n + (int)(size_t)base) & 0x0fffffff; else n = n - (int)((char *)cp - base); patchrel: { unsigned int e = 16 + ((ins >> 12) & 15); CK((n & 3) == 0 && ((n + ((ins & 2048) ? 0 : (1<<(e+1)))) >> (e+2)) == 0, RANGE_REL); cp[-1] |= ((n>>2) & ((1<<e)-1)); } break; case DASM_LABEL_LG: ins &= 2047; if (ins >= 20) D->globals[ins-10] = (void *)(base + n); break; case DASM_LABEL_PC: break; case DASM_IMMS: cp[-1] |= ((n>>3) & 4); n &= 0x1f; /* fallthrough */ case DASM_IMM: cp[-1] |= (n & ((1<<((ins>>5)&31))-1)) << (ins&31); break; default: *cp++ = ins; break; } } stop: (void)0; } } if (base + D->codesize != (char *)cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } #undef CK /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_LG|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(D->section-D->sections); return D->status; } #endif
12,419
28.223529
80
h
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_ppc.h
/* ** DynASM PPC/PPC64 encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "ppc" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. */ enum { DASM_STOP, DASM_SECTION, DASM_ESC, DASM_REL_EXT, /* The following actions need a buffer position. */ DASM_ALIGN, DASM_REL_LG, DASM_LABEL_LG, /* The following actions also have an argument. */ DASM_REL_PC, DASM_LABEL_PC, DASM_IMM, DASM_IMMSH, DASM__MAX }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_REL 0x15000000 #define DASM_S_UNDEF_LG 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned int *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; D->globals = gl - 10; /* Negative bias to compensate for locals. */ DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status = DASM_S_RANGE_##st|(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); if (action >= DASM__MAX) { ofs += 4; } else { int *pl, n = action >= DASM_REL_PC ? va_arg(ap, int) : 0; switch (action) { case DASM_STOP: goto stop; case DASM_SECTION: n = (ins & 255); CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; goto stop; case DASM_ESC: p++; ofs += 4; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs += (ins & 255); b[pos++] = ofs; break; case DASM_REL_LG: n = (ins & 2047) - 10; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n >= 0) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl += 10; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: pl = D->pclabels + n; CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; break; case DASM_LABEL_LG: pl = D->lglabels + (ins & 2047) - 10; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + n; CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_IMM: #ifdef DASM_CHECKS CK((n & ((1<<((ins>>10)&31))-1)) == 0, RANGE_I); #endif n >>= ((ins>>10)&31); #ifdef DASM_CHECKS if (ins & 0x8000) CK(((n + (1<<(((ins>>5)&31)-1)))>>((ins>>5)&31)) == 0, RANGE_I); else CK((n>>((ins>>5)&31)) == 0, RANGE_I); #endif b[pos++] = n; break; case DASM_IMMSH: CK((n >> 6) == 0, RANGE_I); b[pos++] = n; break; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: p++; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs -= (b[pos++] + ofs) & (ins & 255); break; case DASM_REL_LG: case DASM_REL_PC: pos++; break; case DASM_LABEL_LG: case DASM_LABEL_PC: b[pos++] += ofs; break; case DASM_IMM: case DASM_IMMSH: pos++; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) return DASM_S_##st|(p-D->actionlist-1); } while (0) #else #define CK(x, st) ((void)0) #endif /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; char *base = (char *)buffer; unsigned int *cp = (unsigned int *)buffer; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = sec->rbuf + sec->pos; while (b != endb) { dasm_ActList p = D->actionlist + *b++; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16); int n = (action >= DASM_ALIGN && action < DASM__MAX) ? *b++ : 0; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: *cp++ = *p++; break; case DASM_REL_EXT: n = DASM_EXTERN(Dst, (unsigned char *)cp, (ins & 2047), 1) - 4; goto patchrel; case DASM_ALIGN: ins &= 255; while ((((char *)cp - base) & ins)) *cp++ = 0x60000000; break; case DASM_REL_LG: if (n < 0) { n = (int)((ptrdiff_t)D->globals[-n] - (ptrdiff_t)cp); goto patchrel; } /* fallthrough */ case DASM_REL_PC: CK(n >= 0, UNDEF_PC); n = *DASM_POS2PTR(D, n) - (int)((char *)cp - base); patchrel: CK((n & 3) == 0 && (((n+4) + ((ins & 2048) ? 0x00008000 : 0x02000000)) >> ((ins & 2048) ? 16 : 26)) == 0, RANGE_REL); cp[-1] |= ((n+4) & ((ins & 2048) ? 0x0000fffc: 0x03fffffc)); break; case DASM_LABEL_LG: ins &= 2047; if (ins >= 20) D->globals[ins-10] = (void *)(base + n); break; case DASM_LABEL_PC: break; case DASM_IMM: cp[-1] |= (n & ((1<<((ins>>5)&31))-1)) << (ins&31); break; case DASM_IMMSH: cp[-1] |= (ins & 1) ? ((n&31)<<11)|((n&32)>>4) : ((n&31)<<6)|(n&32); break; default: *cp++ = ins; break; } } stop: (void)0; } } if (base + D->codesize != (char *)cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } #undef CK /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_LG|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(D->section-D->sections); return D->status; } #endif
12,416
28.285377
80
h
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_proto.h
/* ** DynASM encoding engine prototypes. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #ifndef _DASM_PROTO_H #define _DASM_PROTO_H #include <stddef.h> #include <stdarg.h> #define DASM_IDENT "DynASM 1.5.0" #define DASM_VERSION 10500 /* 1.5.0 */ #ifndef Dst_DECL #define Dst_DECL dasm_State **Dst #endif #ifndef Dst_REF #define Dst_REF (*Dst) #endif #ifndef DASM_FDEF #define DASM_FDEF extern #endif #ifndef DASM_M_GROW #define DASM_M_GROW(ctx, t, p, sz, need) \ do { \ size_t _sz = (sz), _need = (need); \ if (_sz < _need) { \ if (_sz < 16) _sz = 16; \ while (_sz < _need) _sz += _sz; \ (p) = (t *)realloc((p), _sz); \ if ((p) == NULL) exit(1); \ (sz) = _sz; \ } \ } while(0) #endif #ifndef DASM_M_FREE #define DASM_M_FREE(ctx, p, sz) free(p) #endif /* Internal DynASM encoder state. */ typedef struct dasm_State dasm_State; /* Initialize and free DynASM state. */ DASM_FDEF void dasm_init(Dst_DECL, int maxsection); DASM_FDEF void dasm_free(Dst_DECL); /* Setup global array. Must be called before dasm_setup(). */ DASM_FDEF void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl); /* Grow PC label array. Can be called after dasm_setup(), too. */ DASM_FDEF void dasm_growpc(Dst_DECL, unsigned int maxpc); /* Setup encoder. */ DASM_FDEF void dasm_setup(Dst_DECL, const void *actionlist); /* Feed encoder with actions. Calls are generated by pre-processor. */ DASM_FDEF void dasm_put(Dst_DECL, int start, ...); /* Link sections and return the resulting size. */ DASM_FDEF int dasm_link(Dst_DECL, size_t *szp); /* Encode sections into buffer. */ DASM_FDEF int dasm_encode(Dst_DECL, void *buffer); /* Get PC label offset. */ DASM_FDEF int dasm_getpclabel(Dst_DECL, unsigned int pc); #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ DASM_FDEF int dasm_checkstep(Dst_DECL, int secmatch); #else #define dasm_checkstep(a, b) 0 #endif #endif /* _DASM_PROTO_H */
2,062
23.559524
76
h
php-src
php-src-master/ext/opcache/jit/dynasm/dasm_x86.h
/* ** DynASM x86 encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "x86" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. DASM_STOP must be 255. */ enum { DASM_DISP = 233, DASM_IMM_S, DASM_IMM_B, DASM_IMM_W, DASM_IMM_D, DASM_IMM_WB, DASM_IMM_DB, DASM_VREG, DASM_SPACE, DASM_SETLABEL, DASM_REL_A, DASM_REL_LG, DASM_REL_PC, DASM_IMM_LG, DASM_IMM_PC, DASM_LABEL_LG, DASM_LABEL_PC, DASM_ALIGN, DASM_EXTERN, DASM_ESC, DASM_MARK, DASM_SECTION, DASM_STOP }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_VREG 0x15000000 #define DASM_S_UNDEF_L 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned char *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Perform potentially overflowing pointer operations in a way that avoids UB. */ #define DASM_PTR_SUB(p1, off) ((void *) ((uintptr_t) (p1) - sizeof(*p1) * (uintptr_t) (off))) #define DASM_PTR_ADD(p1, off) ((void *) ((uintptr_t) (p1) + sizeof(*p1) * (uintptr_t) (off))) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = DASM_PTR_SUB(D->sections[i].buf, DASM_SEC2POS(i)); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Warray-bounds" #endif D->globals = gl - 10; /* Negative bias to compensate for locals. */ #ifdef __GNUC__ # pragma GCC diagnostic pop #endif DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(int)(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status=DASM_S_RANGE_##st|(int)(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs, mrm = -1; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { int action = *p++; if (action < DASM_DISP) { ofs++; } else if (action <= DASM_REL_A) { int n = va_arg(ap, int); b[pos++] = n; switch (action) { case DASM_DISP: if (n == 0) { if (mrm < 0) mrm = p[-2]; if ((mrm&7) != 5) break; } /* fallthrough */ case DASM_IMM_DB: if ((((unsigned)n+128)&-256) == 0) goto ob; /* fallthrough */ case DASM_REL_A: /* Assumes ptrdiff_t is int. !x64 */ case DASM_IMM_D: ofs += 4; break; case DASM_IMM_S: CK(((n+128)&-256) == 0, RANGE_I); goto ob; case DASM_IMM_B: CK((n&-256) == 0, RANGE_I); ob: ofs++; break; case DASM_IMM_WB: if (((n+128)&-256) == 0) goto ob; /* fallthrough */ case DASM_IMM_W: CK((n&-65536) == 0, RANGE_I); ofs += 2; break; case DASM_SPACE: p++; ofs += n; break; case DASM_SETLABEL: b[pos-2] = -0x40000000; break; /* Neg. label ofs. */ case DASM_VREG: CK((n&-16) == 0 && (n != 4 || (*p>>5) != 2), RANGE_VREG); if (*p < 0x40 && p[1] == DASM_DISP) mrm = n; if (*p < 0x20 && (n&7) == 4) ofs++; switch ((*p++ >> 3) & 3) { case 3: n |= b[pos-3]; /* fallthrough */ case 2: n |= b[pos-2]; /* fallthrough */ case 1: if (n <= 7) { b[pos-1] |= 0x10; ofs--; } } continue; } mrm = -1; } else { int *pl, n; switch (action) { case DASM_REL_LG: case DASM_IMM_LG: n = *p++; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n <= 246) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl -= 246; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: case DASM_IMM_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; ofs += 4; /* Maximum offset needed. */ if (action == DASM_REL_LG || action == DASM_REL_PC) { b[pos++] = ofs; /* Store pass1 offset estimate. */ } else if (sizeof(ptrdiff_t) == 8) { ofs += 4; } break; case DASM_LABEL_LG: pl = D->lglabels + *p++; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_ALIGN: ofs += *p++; /* Maximum alignment needed (arg is 2**n-1). */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_EXTERN: p += 2; ofs += 4; break; case DASM_ESC: p++; ofs++; break; case DASM_MARK: mrm = p[-2]; break; case DASM_SECTION: n = *p; CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; case DASM_STOP: goto stop; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink branches/aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; int op = 0; while (1) { int action = *p++; switch (action) { case DASM_REL_LG: p++; /* fallthrough */ case DASM_REL_PC: { int shrink = op == 0xe9 ? 3 : ((op&0xf0) == 0x80 ? 4 : 0); if (shrink) { /* Shrinkable branch opcode? */ int lofs, lpos = b[pos]; if (lpos < 0) goto noshrink; /* Ext global? */ lofs = *DASM_POS2PTR(D, lpos); if (lpos > pos) { /* Fwd label: add cumulative section offsets. */ int i; for (i = secnum; i < DASM_POS2SEC(lpos); i++) lofs += D->sections[i].ofs; } else { lofs -= ofs; /* Bkwd label: unfix offset. */ } lofs -= b[pos+1]; /* Short branch ok? */ if (lofs >= -128-shrink && lofs <= 127) ofs -= shrink; /* Yes. */ else { noshrink: shrink = 0; } /* No, cannot shrink op. */ } b[pos+1] = shrink; pos += 2; break; } /* fallthrough */ case DASM_SPACE: case DASM_IMM_LG: case DASM_VREG: p++; case DASM_DISP: case DASM_IMM_S: case DASM_IMM_B: case DASM_IMM_W: case DASM_IMM_D: case DASM_IMM_WB: case DASM_IMM_DB: case DASM_SETLABEL: case DASM_REL_A: case DASM_IMM_PC: pos++; break; case DASM_LABEL_LG: p++; /* fallthrough */ case DASM_LABEL_PC: b[pos++] += ofs; break; /* Fix label offset. */ case DASM_ALIGN: ofs -= (b[pos++]+ofs)&*p++; break; /* Adjust ofs. */ case DASM_EXTERN: p += 2; break; case DASM_ESC: op = *p++; break; case DASM_MARK: break; case DASM_SECTION: case DASM_STOP: goto stop; default: op = action; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #define dasmb(x) *cp++ = (unsigned char)(x) #ifndef DASM_ALIGNED_WRITES typedef ZEND_SET_ALIGNED(1, unsigned short unaligned_short); typedef ZEND_SET_ALIGNED(1, unsigned int unaligned_int); typedef ZEND_SET_ALIGNED(1, unsigned long long unaligned_long_long); #define dasmw(x) \ do { *((unaligned_short *)cp) = (unsigned short)(x); cp+=2; } while (0) #define dasmd(x) \ do { *((unaligned_int *)cp) = (unsigned int)(x); cp+=4; } while (0) #define dasmq(x) \ do { *((unaligned_long_long *)cp) = (unsigned long long)(x); cp+=8; } while (0) #else #define dasmw(x) do { dasmb(x); dasmb((x)>>8); } while (0) #define dasmd(x) do { dasmw(x); dasmw((x)>>16); } while (0) #define dasmq(x) do { dasmd(x); dasmd((x)>>32); } while (0) #endif static unsigned char *dasma_(unsigned char *cp, ptrdiff_t x) { if (sizeof(ptrdiff_t) == 8) dasmq((unsigned long long)x); else dasmd((unsigned int)x); return cp; } #define dasma(x) (cp = dasma_(cp, (x))) /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; unsigned char *base = (unsigned char *)buffer; unsigned char *cp = base; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = DASM_PTR_ADD(sec->rbuf, sec->pos); while (b != endb) { dasm_ActList p = D->actionlist + *b++; unsigned char *mark = NULL; while (1) { int action = *p++; int n = (action >= DASM_DISP && action <= DASM_ALIGN) ? *b++ : 0; switch (action) { case DASM_DISP: if (!mark) mark = cp; { unsigned char *mm = mark; if (*p != DASM_IMM_DB && *p != DASM_IMM_WB) mark = NULL; if (n == 0) { int mrm = mm[-1]&7; if (mrm == 4) mrm = mm[0]&7; if (mrm != 5) { mm[-1] -= 0x80; break; } } if ((((unsigned)n+128) & -256) != 0) goto wd; else mm[-1] -= 0x40; } /* fallthrough */ case DASM_IMM_S: case DASM_IMM_B: wb: dasmb(n); break; case DASM_IMM_DB: if ((((unsigned)n+128)&-256) == 0) { db: if (!mark) mark = cp; mark[-2] += 2; mark = NULL; goto wb; } else mark = NULL; /* fallthrough */ case DASM_IMM_D: wd: dasmd(n); break; case DASM_IMM_WB: if ((((unsigned)n+128)&-256) == 0) goto db; else mark = NULL; /* fallthrough */ case DASM_IMM_W: dasmw(n); break; case DASM_VREG: { int t = *p++; unsigned char *ex = cp - (t&7); if ((n & 8) && t < 0xa0) { if (*ex & 0x80) ex[1] ^= 0x20 << (t>>6); else *ex ^= 1 << (t>>6); n &= 7; } else if (n & 0x10) { if (*ex & 0x80) { *ex = 0xc5; ex[1] = (ex[1] & 0x80) | ex[2]; ex += 2; } while (++ex < cp) ex[-1] = *ex; if (mark) mark--; cp--; n &= 7; } if (t >= 0xc0) n <<= 4; else if (t >= 0x40) n <<= 3; else if (n == 4 && t < 0x20) { cp[-1] ^= n; *cp++ = 0x20; } cp[-1] ^= n; break; } case DASM_REL_LG: p++; if (n >= 0) goto rel_pc; b++; n = (int)(ptrdiff_t)D->globals[-n]; /* fallthrough */ case DASM_REL_A: rel_a: n -= (unsigned int)(ptrdiff_t)(cp+4); goto wd; /* !x64 */ case DASM_REL_PC: rel_pc: { int shrink = *b++; int *pb = DASM_POS2PTR(D, n); if (*pb < 0) { n = pb[1]; goto rel_a; } n = *pb - ((int)(cp-base) + 4-shrink); if (shrink == 0) goto wd; if (shrink == 4) { cp--; cp[-1] = *cp-0x10; } else cp[-1] = 0xeb; goto wb; } case DASM_IMM_LG: p++; if (n < 0) { dasma((ptrdiff_t)D->globals[-n]); break; } /* fallthrough */ case DASM_IMM_PC: { int *pb = DASM_POS2PTR(D, n); dasma(*pb < 0 ? (ptrdiff_t)pb[1] : (*pb + (ptrdiff_t)base)); break; } case DASM_LABEL_LG: { int idx = *p++; if (idx >= 10) D->globals[idx] = (void *)(base + (*p == DASM_SETLABEL ? *b : n)); break; } case DASM_LABEL_PC: case DASM_SETLABEL: break; case DASM_SPACE: { int fill = *p++; while (n--) *cp++ = fill; break; } case DASM_ALIGN: n = *p++; while (((cp-base) & n)) *cp++ = 0x90; /* nop */ break; case DASM_EXTERN: n = DASM_EXTERN(Dst, cp, p[1], *p); p += 2; goto wd; case DASM_MARK: mark = cp; break; case DASM_ESC: action = *p++; /* fallthrough */ default: *cp++ = action; break; case DASM_SECTION: case DASM_STOP: goto stop; } } stop: (void)0; } } if (base + D->codesize != cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_L|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(int)(D->section-D->sections); return D->status; } #endif
17,358
31.086876
93
h
php-src
php-src-master/ext/opcache/jit/libudis86/decode.h
/* udis86 - libudis86/decode.h * * Copyright (c) 2002-2009 Vivek Thampi * 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. * * 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. */ #ifndef UD_DECODE_H #define UD_DECODE_H #include "types.h" #include "udint.h" #include "itab.h" #define MAX_INSN_LENGTH 15 /* itab prefix bits */ #define P_none ( 0 ) #define P_inv64 ( 1 << 0 ) #define P_INV64(n) ( ( n >> 0 ) & 1 ) #define P_def64 ( 1 << 1 ) #define P_DEF64(n) ( ( n >> 1 ) & 1 ) #define P_oso ( 1 << 2 ) #define P_OSO(n) ( ( n >> 2 ) & 1 ) #define P_aso ( 1 << 3 ) #define P_ASO(n) ( ( n >> 3 ) & 1 ) #define P_rexb ( 1 << 4 ) #define P_REXB(n) ( ( n >> 4 ) & 1 ) #define P_rexw ( 1 << 5 ) #define P_REXW(n) ( ( n >> 5 ) & 1 ) #define P_rexr ( 1 << 6 ) #define P_REXR(n) ( ( n >> 6 ) & 1 ) #define P_rexx ( 1 << 7 ) #define P_REXX(n) ( ( n >> 7 ) & 1 ) #define P_seg ( 1 << 8 ) #define P_SEG(n) ( ( n >> 8 ) & 1 ) #define P_vexl ( 1 << 9 ) #define P_VEXL(n) ( ( n >> 9 ) & 1 ) #define P_vexw ( 1 << 10 ) #define P_VEXW(n) ( ( n >> 10 ) & 1 ) #define P_str ( 1 << 11 ) #define P_STR(n) ( ( n >> 11 ) & 1 ) #define P_strz ( 1 << 12 ) #define P_STR_ZF(n) ( ( n >> 12 ) & 1 ) /* operand type constants -- order is important! */ enum ud_operand_code { OP_NONE, OP_A, OP_E, OP_M, OP_G, OP_I, OP_F, OP_R0, OP_R1, OP_R2, OP_R3, OP_R4, OP_R5, OP_R6, OP_R7, OP_AL, OP_CL, OP_DL, OP_AX, OP_CX, OP_DX, OP_eAX, OP_eCX, OP_eDX, OP_rAX, OP_rCX, OP_rDX, OP_ES, OP_CS, OP_SS, OP_DS, OP_FS, OP_GS, OP_ST0, OP_ST1, OP_ST2, OP_ST3, OP_ST4, OP_ST5, OP_ST6, OP_ST7, OP_J, OP_S, OP_O, OP_I1, OP_I3, OP_sI, OP_V, OP_W, OP_Q, OP_P, OP_U, OP_N, OP_MU, OP_H, OP_L, OP_R, OP_C, OP_D, OP_MR } UD_ATTR_PACKED; /* * Operand size constants * * Symbolic constants for various operand sizes. Some of these constants * are given a value equal to the width of the data (SZ_B == 8), such * that they maybe used interchangeably in the internals. Modifying them * will most certainly break things! */ typedef uint16_t ud_operand_size_t; #define SZ_NA 0 #define SZ_Z 1 #define SZ_V 2 #define SZ_Y 3 #define SZ_X 4 #define SZ_RDQ 7 #define SZ_B 8 #define SZ_W 16 #define SZ_D 32 #define SZ_Q 64 #define SZ_T 80 #define SZ_O 12 #define SZ_DQ 128 /* double quad */ #define SZ_QQ 256 /* quad quad */ /* * Complex size types; that encode sizes for operands of type MR (memory or * register); for internal use only. Id space above 256. */ #define SZ_BD ((SZ_B << 8) | SZ_D) #define SZ_BV ((SZ_B << 8) | SZ_V) #define SZ_WD ((SZ_W << 8) | SZ_D) #define SZ_WV ((SZ_W << 8) | SZ_V) #define SZ_WY ((SZ_W << 8) | SZ_Y) #define SZ_DY ((SZ_D << 8) | SZ_Y) #define SZ_WO ((SZ_W << 8) | SZ_O) #define SZ_DO ((SZ_D << 8) | SZ_O) #define SZ_QO ((SZ_Q << 8) | SZ_O) /* resolve complex size type. */ static UD_INLINE ud_operand_size_t Mx_mem_size(ud_operand_size_t size) { return (size >> 8) & 0xff; } static UD_INLINE ud_operand_size_t Mx_reg_size(ud_operand_size_t size) { return size & 0xff; } /* A single operand of an entry in the instruction table. * (internal use only) */ struct ud_itab_entry_operand { enum ud_operand_code type; ud_operand_size_t size; }; /* A single entry in an instruction table. *(internal use only) */ struct ud_itab_entry { enum ud_mnemonic_code mnemonic; struct ud_itab_entry_operand operand1; struct ud_itab_entry_operand operand2; struct ud_itab_entry_operand operand3; struct ud_itab_entry_operand operand4; uint32_t prefix; }; struct ud_lookup_table_list_entry { const uint16_t *table; enum ud_table_type type; const char *meta; }; extern struct ud_itab_entry ud_itab[]; extern struct ud_lookup_table_list_entry ud_lookup_table_list[]; #endif /* UD_DECODE_H */ /* vim:cindent * vim:expandtab * vim:ts=4 * vim:sw=4 */
5,593
27.252525
84
h
php-src
php-src-master/ext/opcache/jit/libudis86/extern.h
/* udis86 - libudis86/extern.h * * Copyright (c) 2002-2009, 2013 Vivek Thampi * 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. * * 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. */ #ifndef UD_EXTERN_H #define UD_EXTERN_H #ifdef __cplusplus extern "C" { #endif #include "types.h" #if defined(_MSC_VER) && defined(_USRDLL) # ifdef LIBUDIS86_EXPORTS # define LIBUDIS86_DLLEXTERN __declspec(dllexport) # else # define LIBUDIS86_DLLEXTERN __declspec(dllimport) # endif #else # define LIBUDIS86_DLLEXTERN #endif /* ============================= PUBLIC API ================================= */ extern LIBUDIS86_DLLEXTERN void ud_init(struct ud*); extern LIBUDIS86_DLLEXTERN void ud_set_mode(struct ud*, uint8_t); extern LIBUDIS86_DLLEXTERN void ud_set_pc(struct ud*, uint64_t); extern LIBUDIS86_DLLEXTERN void ud_set_input_hook(struct ud*, int (*)(struct ud*)); extern LIBUDIS86_DLLEXTERN void ud_set_input_buffer(struct ud*, const uint8_t*, size_t); #ifndef __UD_STANDALONE__ extern LIBUDIS86_DLLEXTERN void ud_set_input_file(struct ud*, FILE*); #endif /* __UD_STANDALONE__ */ extern LIBUDIS86_DLLEXTERN void ud_set_vendor(struct ud*, unsigned); extern LIBUDIS86_DLLEXTERN void ud_set_syntax(struct ud*, void (*)(struct ud*)); extern LIBUDIS86_DLLEXTERN void ud_input_skip(struct ud*, size_t); extern LIBUDIS86_DLLEXTERN int ud_input_end(const struct ud*); extern LIBUDIS86_DLLEXTERN unsigned int ud_decode(struct ud*); extern LIBUDIS86_DLLEXTERN unsigned int ud_disassemble(struct ud*); extern LIBUDIS86_DLLEXTERN void ud_translate_intel(struct ud*); extern LIBUDIS86_DLLEXTERN void ud_translate_att(struct ud*); extern LIBUDIS86_DLLEXTERN const char* ud_insn_asm(const struct ud* u); extern LIBUDIS86_DLLEXTERN const uint8_t* ud_insn_ptr(const struct ud* u); extern LIBUDIS86_DLLEXTERN uint64_t ud_insn_off(const struct ud*); extern LIBUDIS86_DLLEXTERN const char* ud_insn_hex(struct ud*); extern LIBUDIS86_DLLEXTERN unsigned int ud_insn_len(const struct ud* u); extern LIBUDIS86_DLLEXTERN const struct ud_operand* ud_insn_opr(const struct ud *u, unsigned int n); extern LIBUDIS86_DLLEXTERN int ud_opr_is_sreg(const struct ud_operand *opr); extern LIBUDIS86_DLLEXTERN int ud_opr_is_gpr(const struct ud_operand *opr); extern LIBUDIS86_DLLEXTERN enum ud_mnemonic_code ud_insn_mnemonic(const struct ud *u); extern LIBUDIS86_DLLEXTERN const char* ud_lookup_mnemonic(enum ud_mnemonic_code c); extern LIBUDIS86_DLLEXTERN void ud_set_user_opaque_data(struct ud*, void*); extern LIBUDIS86_DLLEXTERN void* ud_get_user_opaque_data(const struct ud*); extern LIBUDIS86_DLLEXTERN void ud_set_asm_buffer(struct ud *u, char *buf, size_t size); extern LIBUDIS86_DLLEXTERN void ud_set_sym_resolver(struct ud *u, const char* (*resolver)(struct ud*, uint64_t addr, int64_t *offset)); /* ========================================================================== */ #ifdef __cplusplus } #endif #endif /* UD_EXTERN_H */
4,338
37.061404
100
h
php-src
php-src-master/ext/opcache/jit/libudis86/syn-att.c
/* udis86 - libudis86/syn-att.c * * Copyright (c) 2002-2009 Vivek Thampi * 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. * * 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. */ #include "types.h" #include "extern.h" #include "decode.h" #include "itab.h" #include "syn.h" #include "udint.h" /* ----------------------------------------------------------------------------- * opr_cast() - Prints an operand cast. * ----------------------------------------------------------------------------- */ static void opr_cast(struct ud* u, struct ud_operand* op) { switch(op->size) { case 16 : case 32 : ud_asmprintf(u, "*"); break; default: break; } } /* ----------------------------------------------------------------------------- * gen_operand() - Generates assembly output for each operand. * ----------------------------------------------------------------------------- */ static void gen_operand(struct ud* u, struct ud_operand* op) { switch(op->type) { case UD_OP_CONST: ud_asmprintf(u, "$0x%x", op->lval.udword); break; case UD_OP_REG: ud_asmprintf(u, "%%%s", ud_reg_tab[op->base - UD_R_AL]); break; case UD_OP_MEM: if (u->br_far) { opr_cast(u, op); } if (u->pfx_seg) { ud_asmprintf(u, "%%%s:", ud_reg_tab[u->pfx_seg - UD_R_AL]); } if (op->offset != 0) { ud_syn_print_mem_disp(u, op, 0); } if (op->base) { ud_asmprintf(u, "(%%%s", ud_reg_tab[op->base - UD_R_AL]); } if (op->index) { if (op->base) { ud_asmprintf(u, ","); } else { ud_asmprintf(u, "("); } ud_asmprintf(u, "%%%s", ud_reg_tab[op->index - UD_R_AL]); } if (op->scale) { ud_asmprintf(u, ",%d", op->scale); } if (op->base || op->index) { ud_asmprintf(u, ")"); } break; case UD_OP_IMM: ud_asmprintf(u, "$"); ud_syn_print_imm(u, op); break; case UD_OP_JIMM: ud_syn_print_addr(u, ud_syn_rel_target(u, op)); break; case UD_OP_PTR: switch (op->size) { case 32: ud_asmprintf(u, "$0x%x, $0x%x", op->lval.ptr.seg, op->lval.ptr.off & 0xFFFF); break; case 48: ud_asmprintf(u, "$0x%x, $0x%x", op->lval.ptr.seg, op->lval.ptr.off); break; } break; default: return; } } /* ============================================================================= * translates to AT&T syntax * ============================================================================= */ extern void ud_translate_att(struct ud *u) { int size = 0; int star = 0; /* check if P_OSO prefix is used */ if (! P_OSO(u->itab_entry->prefix) && u->pfx_opr) { switch (u->dis_mode) { case 16: ud_asmprintf(u, "o32 "); break; case 32: case 64: ud_asmprintf(u, "o16 "); break; } } /* check if P_ASO prefix was used */ if (! P_ASO(u->itab_entry->prefix) && u->pfx_adr) { switch (u->dis_mode) { case 16: ud_asmprintf(u, "a32 "); break; case 32: ud_asmprintf(u, "a16 "); break; case 64: ud_asmprintf(u, "a32 "); break; } } if (u->pfx_lock) ud_asmprintf(u, "lock "); if (u->pfx_rep) { ud_asmprintf(u, "rep "); } else if (u->pfx_repe) { ud_asmprintf(u, "repe "); } else if (u->pfx_repne) { ud_asmprintf(u, "repne "); } /* special instructions */ switch (u->mnemonic) { case UD_Iretf: ud_asmprintf(u, "lret "); break; case UD_Idb: ud_asmprintf(u, ".byte 0x%x", u->operand[0].lval.ubyte); return; case UD_Ijmp: case UD_Icall: if (u->br_far) ud_asmprintf(u, "l"); if (u->operand[0].type == UD_OP_REG) { star = 1; } ud_asmprintf(u, "%s", ud_lookup_mnemonic(u->mnemonic)); break; case UD_Ibound: case UD_Ienter: if (u->operand[0].type != UD_NONE) gen_operand(u, &u->operand[0]); if (u->operand[1].type != UD_NONE) { ud_asmprintf(u, ","); gen_operand(u, &u->operand[1]); } return; default: ud_asmprintf(u, "%s", ud_lookup_mnemonic(u->mnemonic)); } if (size == 8) { ud_asmprintf(u, "b"); } else if (size == 16) { ud_asmprintf(u, "w"); } else if (size == 64) { ud_asmprintf(u, "q"); } if (star) { ud_asmprintf(u, " *"); } else { ud_asmprintf(u, " "); } if (u->operand[3].type != UD_NONE) { gen_operand(u, &u->operand[3]); ud_asmprintf(u, ", "); } if (u->operand[2].type != UD_NONE) { gen_operand(u, &u->operand[2]); ud_asmprintf(u, ", "); } if (u->operand[1].type != UD_NONE) { gen_operand(u, &u->operand[1]); ud_asmprintf(u, ", "); } if (u->operand[0].type != UD_NONE) { gen_operand(u, &u->operand[0]); } } /* vim: set ts=2 sw=2 expandtab */
6,041
25.384279
84
c
php-src
php-src-master/ext/opcache/jit/libudis86/syn-intel.c
/* udis86 - libudis86/syn-intel.c * * Copyright (c) 2002-2013 Vivek Thampi * 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. * * 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. */ #include "types.h" #include "extern.h" #include "decode.h" #include "itab.h" #include "syn.h" #include "udint.h" /* ----------------------------------------------------------------------------- * opr_cast() - Prints an operand cast. * ----------------------------------------------------------------------------- */ static void opr_cast(struct ud* u, struct ud_operand* op) { if (u->br_far) { ud_asmprintf(u, "far "); } switch(op->size) { case 8: ud_asmprintf(u, "byte " ); break; case 16: ud_asmprintf(u, "word " ); break; case 32: ud_asmprintf(u, "dword "); break; case 64: ud_asmprintf(u, "qword "); break; case 80: ud_asmprintf(u, "tword "); break; case 128: ud_asmprintf(u, "oword "); break; case 256: ud_asmprintf(u, "yword "); break; default: break; } } /* ----------------------------------------------------------------------------- * gen_operand() - Generates assembly output for each operand. * ----------------------------------------------------------------------------- */ static void gen_operand(struct ud* u, struct ud_operand* op, int syn_cast) { switch(op->type) { case UD_OP_REG: ud_asmprintf(u, "%s", ud_reg_tab[op->base - UD_R_AL]); break; case UD_OP_MEM: if (syn_cast) { opr_cast(u, op); } ud_asmprintf(u, "["); if (u->pfx_seg) { ud_asmprintf(u, "%s:", ud_reg_tab[u->pfx_seg - UD_R_AL]); } if (op->base) { ud_asmprintf(u, "%s", ud_reg_tab[op->base - UD_R_AL]); } if (op->index) { ud_asmprintf(u, "%s%s", op->base != UD_NONE? "+" : "", ud_reg_tab[op->index - UD_R_AL]); if (op->scale) { ud_asmprintf(u, "*%d", op->scale); } } if (op->offset != 0) { ud_syn_print_mem_disp(u, op, (op->base != UD_NONE || op->index != UD_NONE) ? 1 : 0); } ud_asmprintf(u, "]"); break; case UD_OP_IMM: ud_syn_print_imm(u, op); break; case UD_OP_JIMM: ud_syn_print_addr(u, ud_syn_rel_target(u, op)); break; case UD_OP_PTR: switch (op->size) { case 32: ud_asmprintf(u, "word 0x%x:0x%x", op->lval.ptr.seg, op->lval.ptr.off & 0xFFFF); break; case 48: ud_asmprintf(u, "dword 0x%x:0x%x", op->lval.ptr.seg, op->lval.ptr.off); break; } break; case UD_OP_CONST: if (syn_cast) opr_cast(u, op); ud_asmprintf(u, "%d", op->lval.udword); break; default: return; } } /* ============================================================================= * translates to intel syntax * ============================================================================= */ extern void ud_translate_intel(struct ud* u) { /* check if P_OSO prefix is used */ if (!P_OSO(u->itab_entry->prefix) && u->pfx_opr) { switch (u->dis_mode) { case 16: ud_asmprintf(u, "o32 "); break; case 32: case 64: ud_asmprintf(u, "o16 "); break; } } /* check if P_ASO prefix was used */ if (!P_ASO(u->itab_entry->prefix) && u->pfx_adr) { switch (u->dis_mode) { case 16: ud_asmprintf(u, "a32 "); break; case 32: ud_asmprintf(u, "a16 "); break; case 64: ud_asmprintf(u, "a32 "); break; } } if (u->pfx_seg && u->operand[0].type != UD_OP_MEM && u->operand[1].type != UD_OP_MEM ) { ud_asmprintf(u, "%s ", ud_reg_tab[u->pfx_seg - UD_R_AL]); } if (u->pfx_lock) { ud_asmprintf(u, "lock "); } if (u->pfx_rep) { ud_asmprintf(u, "rep "); } else if (u->pfx_repe) { ud_asmprintf(u, "repe "); } else if (u->pfx_repne) { ud_asmprintf(u, "repne "); } /* print the instruction mnemonic */ ud_asmprintf(u, "%s", ud_lookup_mnemonic(u->mnemonic)); if (u->operand[0].type != UD_NONE) { int cast = 0; ud_asmprintf(u, " "); if (u->operand[0].type == UD_OP_MEM) { if (u->operand[1].type == UD_OP_IMM || u->operand[1].type == UD_OP_CONST || u->operand[1].type == UD_NONE || (u->operand[0].size != u->operand[1].size)) { cast = 1; } else if (u->operand[1].type == UD_OP_REG && u->operand[1].base == UD_R_CL) { switch (u->mnemonic) { case UD_Ircl: case UD_Irol: case UD_Iror: case UD_Ircr: case UD_Ishl: case UD_Ishr: case UD_Isar: cast = 1; break; default: break; } } } gen_operand(u, &u->operand[0], cast); } if (u->operand[1].type != UD_NONE) { int cast = 0; ud_asmprintf(u, ", "); if (u->operand[1].type == UD_OP_MEM && u->operand[0].size != u->operand[1].size && !ud_opr_is_sreg(&u->operand[0])) { cast = 1; } gen_operand(u, &u->operand[1], cast); } if (u->operand[2].type != UD_NONE) { int cast = 0; ud_asmprintf(u, ", "); if (u->operand[2].type == UD_OP_MEM && u->operand[2].size != u->operand[1].size) { cast = 1; } gen_operand(u, &u->operand[2], cast); } if (u->operand[3].type != UD_NONE) { ud_asmprintf(u, ", "); gen_operand(u, &u->operand[3], 0); } } /* vim: set ts=2 sw=2 expandtab */
6,662
28.613333
84
c
php-src
php-src-master/ext/opcache/jit/libudis86/syn.c
/* udis86 - libudis86/syn.c * * Copyright (c) 2002-2013 Vivek Thampi * 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. * * 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. */ #include "types.h" #include "decode.h" #include "syn.h" #include "udint.h" /* * Register Table - Order Matters (types.h)! * */ const char* ud_reg_tab[] = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b", "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d", "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "es", "cs", "ss", "ds", "fs", "gs", "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9", "cr10", "cr11", "cr12", "cr13", "cr14", "cr15", "dr0", "dr1", "dr2", "dr3", "dr4", "dr5", "dr6", "dr7", "dr8", "dr9", "dr10", "dr11", "dr12", "dr13", "dr14", "dr15", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15", "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15", "rip" }; uint64_t ud_syn_rel_target(struct ud *u, struct ud_operand *opr) { #if 1 const uint64_t trunc_mask = 0xffffffffffffffffull >> (64 - u->adr_mode); #else const uint64_t trunc_mask = 0xffffffffffffffffull >> (64 - u->opr_mode); #endif switch (opr->size) { case 8 : return (u->pc + opr->lval.sbyte) & trunc_mask; case 16: return (u->pc + opr->lval.sword) & trunc_mask; case 32: return (u->pc + opr->lval.sdword) & trunc_mask; default: UD_ASSERT(!"invalid relative offset size."); return 0ull; } } /* * asmprintf * Printf style function for printing translated assembly * output. Returns the number of characters written and * moves the buffer pointer forward. On an overflow, * returns a negative number and truncates the output. */ int ud_asmprintf(struct ud *u, const char *fmt, ...) { int ret; int avail; va_list ap; va_start(ap, fmt); avail = u->asm_buf_size - u->asm_buf_fill - 1 /* nullchar */; ret = vsnprintf((char*) u->asm_buf + u->asm_buf_fill, avail, fmt, ap); if (ret < 0 || ret > avail) { u->asm_buf_fill = u->asm_buf_size - 1; } else { u->asm_buf_fill += ret; } va_end(ap); return ret; } void ud_syn_print_addr(struct ud *u, uint64_t addr) { const char *name = NULL; if (u->sym_resolver) { int64_t offset = 0; name = u->sym_resolver(u, addr, &offset); if (name) { if (offset) { ud_asmprintf(u, "%s%+" FMT64 "d", name, offset); } else { ud_asmprintf(u, "%s", name); } return; } } ud_asmprintf(u, "0x%" FMT64 "x", addr); } void ud_syn_print_imm(struct ud* u, const struct ud_operand *op) { uint64_t v; if (op->_oprcode == OP_sI && op->size != u->opr_mode) { if (op->size == 8) { v = (int64_t)op->lval.sbyte; } else { UD_ASSERT(op->size == 32); v = (int64_t)op->lval.sdword; } if (u->opr_mode < 64) { v = v & ((1ull << u->opr_mode) - 1ull); } } else { switch (op->size) { case 8 : v = op->lval.ubyte; break; case 16: v = op->lval.uword; break; case 32: v = op->lval.udword; break; case 64: v = op->lval.uqword; break; default: UD_ASSERT(!"invalid offset"); v = 0; /* keep cc happy */ } } #if 1 if (u->sym_resolver) { int64_t offset = 0; const char *name = u->sym_resolver(u, v, &offset); if (name) { if (offset) { ud_asmprintf(u, "%s%+" FMT64 "d", name, offset); } else { ud_asmprintf(u, "%s", name); } return; } } #endif ud_asmprintf(u, "0x%" FMT64 "x", v); } void ud_syn_print_mem_disp(struct ud* u, const struct ud_operand *op, int sign) { UD_ASSERT(op->offset != 0); if (op->base == UD_NONE && op->index == UD_NONE) { uint64_t v; UD_ASSERT(op->scale == UD_NONE && op->offset != 8); /* unsigned mem-offset */ switch (op->offset) { case 16: v = op->lval.uword; break; case 32: v = op->lval.udword; break; case 64: v = op->lval.uqword; break; default: UD_ASSERT(!"invalid offset"); v = 0; /* keep cc happy */ } #if 1 if (u->sym_resolver) { int64_t offset = 0; const char *name = u->sym_resolver(u, v, &offset); if (name) { if (offset) { ud_asmprintf(u, "%s%+" FMT64 "d", name, offset); } else { ud_asmprintf(u, "%s", name); } return; } } #endif ud_asmprintf(u, "0x%" FMT64 "x", v); } else { int64_t v; UD_ASSERT(op->offset != 64); switch (op->offset) { case 8 : v = op->lval.sbyte; break; case 16: v = op->lval.sword; break; case 32: v = op->lval.sdword; break; default: UD_ASSERT(!"invalid offset"); v = 0; /* keep cc happy */ } #if 1 if (u->sym_resolver) { int64_t offset = 0; const char *name = u->sym_resolver(u, v, &offset); if (name) { if (offset) { ud_asmprintf(u, "%s%+" FMT64 "d", name, offset); } else { ud_asmprintf(u, "%s", name); } return; } } #endif if (v < 0) { ud_asmprintf(u, "-0x%" FMT64 "x", -v); } else if (v > 0) { ud_asmprintf(u, "%s0x%" FMT64 "x", sign? "+" : "", v); } } } /* vim: set ts=2 sw=2 expandtab */
7,154
26.625483
84
c
php-src
php-src-master/ext/opcache/jit/libudis86/syn.h
/* udis86 - libudis86/syn.h * * Copyright (c) 2002-2009 * 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. * * 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. */ #ifndef UD_SYN_H #define UD_SYN_H #include "types.h" #ifndef __UD_STANDALONE__ # include <stdarg.h> #endif /* __UD_STANDALONE__ */ extern const char* ud_reg_tab[]; uint64_t ud_syn_rel_target(struct ud*, struct ud_operand*); #ifdef __GNUC__ int ud_asmprintf(struct ud *u, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); #else int ud_asmprintf(struct ud *u, const char *fmt, ...); #endif void ud_syn_print_addr(struct ud *u, uint64_t addr); void ud_syn_print_imm(struct ud* u, const struct ud_operand *op); void ud_syn_print_mem_disp(struct ud* u, const struct ud_operand *, int sign); #endif /* UD_SYN_H */ /* vim: set ts=2 sw=2 expandtab */
2,085
37.62963
84
h
php-src
php-src-master/ext/opcache/jit/libudis86/types.h
/* udis86 - libudis86/types.h * * Copyright (c) 2002-2013 Vivek Thampi * 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. * * 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. */ #ifndef UD_TYPES_H #define UD_TYPES_H #ifdef __KERNEL__ /* * -D__KERNEL__ is automatically passed on the command line when * building something as part of the Linux kernel. Assume standalone * mode. */ # include <linux/kernel.h> # include <linux/string.h> # ifndef __UD_STANDALONE__ # define __UD_STANDALONE__ 1 # endif #endif /* __KERNEL__ */ #if !defined(__UD_STANDALONE__) # include <stdint.h> # include <stdio.h> #endif /* gcc specific extensions */ #ifdef __GNUC__ # define UD_ATTR_PACKED __attribute__((packed)) #else # define UD_ATTR_PACKED #endif /* UD_ATTR_PACKED */ /* ----------------------------------------------------------------------------- * All possible "types" of objects in udis86. Order is Important! * ----------------------------------------------------------------------------- */ enum ud_type { UD_NONE, /* 8 bit GPRs */ UD_R_AL, UD_R_CL, UD_R_DL, UD_R_BL, UD_R_AH, UD_R_CH, UD_R_DH, UD_R_BH, UD_R_SPL, UD_R_BPL, UD_R_SIL, UD_R_DIL, UD_R_R8B, UD_R_R9B, UD_R_R10B, UD_R_R11B, UD_R_R12B, UD_R_R13B, UD_R_R14B, UD_R_R15B, /* 16 bit GPRs */ UD_R_AX, UD_R_CX, UD_R_DX, UD_R_BX, UD_R_SP, UD_R_BP, UD_R_SI, UD_R_DI, UD_R_R8W, UD_R_R9W, UD_R_R10W, UD_R_R11W, UD_R_R12W, UD_R_R13W, UD_R_R14W, UD_R_R15W, /* 32 bit GPRs */ UD_R_EAX, UD_R_ECX, UD_R_EDX, UD_R_EBX, UD_R_ESP, UD_R_EBP, UD_R_ESI, UD_R_EDI, UD_R_R8D, UD_R_R9D, UD_R_R10D, UD_R_R11D, UD_R_R12D, UD_R_R13D, UD_R_R14D, UD_R_R15D, /* 64 bit GPRs */ UD_R_RAX, UD_R_RCX, UD_R_RDX, UD_R_RBX, UD_R_RSP, UD_R_RBP, UD_R_RSI, UD_R_RDI, UD_R_R8, UD_R_R9, UD_R_R10, UD_R_R11, UD_R_R12, UD_R_R13, UD_R_R14, UD_R_R15, /* segment registers */ UD_R_ES, UD_R_CS, UD_R_SS, UD_R_DS, UD_R_FS, UD_R_GS, /* control registers*/ UD_R_CR0, UD_R_CR1, UD_R_CR2, UD_R_CR3, UD_R_CR4, UD_R_CR5, UD_R_CR6, UD_R_CR7, UD_R_CR8, UD_R_CR9, UD_R_CR10, UD_R_CR11, UD_R_CR12, UD_R_CR13, UD_R_CR14, UD_R_CR15, /* debug registers */ UD_R_DR0, UD_R_DR1, UD_R_DR2, UD_R_DR3, UD_R_DR4, UD_R_DR5, UD_R_DR6, UD_R_DR7, UD_R_DR8, UD_R_DR9, UD_R_DR10, UD_R_DR11, UD_R_DR12, UD_R_DR13, UD_R_DR14, UD_R_DR15, /* mmx registers */ UD_R_MM0, UD_R_MM1, UD_R_MM2, UD_R_MM3, UD_R_MM4, UD_R_MM5, UD_R_MM6, UD_R_MM7, /* x87 registers */ UD_R_ST0, UD_R_ST1, UD_R_ST2, UD_R_ST3, UD_R_ST4, UD_R_ST5, UD_R_ST6, UD_R_ST7, /* extended multimedia registers */ UD_R_XMM0, UD_R_XMM1, UD_R_XMM2, UD_R_XMM3, UD_R_XMM4, UD_R_XMM5, UD_R_XMM6, UD_R_XMM7, UD_R_XMM8, UD_R_XMM9, UD_R_XMM10, UD_R_XMM11, UD_R_XMM12, UD_R_XMM13, UD_R_XMM14, UD_R_XMM15, /* 256B multimedia registers */ UD_R_YMM0, UD_R_YMM1, UD_R_YMM2, UD_R_YMM3, UD_R_YMM4, UD_R_YMM5, UD_R_YMM6, UD_R_YMM7, UD_R_YMM8, UD_R_YMM9, UD_R_YMM10, UD_R_YMM11, UD_R_YMM12, UD_R_YMM13, UD_R_YMM14, UD_R_YMM15, UD_R_RIP, /* Operand Types */ UD_OP_REG, UD_OP_MEM, UD_OP_PTR, UD_OP_IMM, UD_OP_JIMM, UD_OP_CONST }; #include "itab.h" union ud_lval { int8_t sbyte; uint8_t ubyte; int16_t sword; uint16_t uword; int32_t sdword; uint32_t udword; int64_t sqword; uint64_t uqword; struct { uint16_t seg; uint32_t off; } ptr; }; /* ----------------------------------------------------------------------------- * struct ud_operand - Disassembled instruction Operand. * ----------------------------------------------------------------------------- */ struct ud_operand { enum ud_type type; uint16_t size; enum ud_type base; enum ud_type index; uint8_t scale; uint8_t offset; union ud_lval lval; /* * internal use only */ uint64_t _legacy; /* this will be removed in 1.8 */ uint8_t _oprcode; }; /* ----------------------------------------------------------------------------- * struct ud - The udis86 object. * ----------------------------------------------------------------------------- */ struct ud { /* * input buffering */ int (*inp_hook) (struct ud*); #ifndef __UD_STANDALONE__ FILE* inp_file; #endif const uint8_t* inp_buf; size_t inp_buf_size; size_t inp_buf_index; uint8_t inp_curr; size_t inp_ctr; uint8_t inp_sess[64]; int inp_end; int inp_peek; void (*translator)(struct ud*); uint64_t insn_offset; char insn_hexcode[64]; /* * Assembly output buffer */ char *asm_buf; size_t asm_buf_size; size_t asm_buf_fill; char asm_buf_int[128]; /* * Symbol resolver for use in the translation phase. */ const char* (*sym_resolver)(struct ud*, uint64_t addr, int64_t *offset); uint8_t dis_mode; uint64_t pc; uint8_t vendor; enum ud_mnemonic_code mnemonic; struct ud_operand operand[4]; uint8_t error; uint8_t _rex; uint8_t pfx_rex; uint8_t pfx_seg; uint8_t pfx_opr; uint8_t pfx_adr; uint8_t pfx_lock; uint8_t pfx_str; uint8_t pfx_rep; uint8_t pfx_repe; uint8_t pfx_repne; uint8_t opr_mode; uint8_t adr_mode; uint8_t br_far; uint8_t br_near; uint8_t have_modrm; uint8_t modrm; uint8_t modrm_offset; uint8_t vex_op; uint8_t vex_b1; uint8_t vex_b2; uint8_t primary_opcode; void * user_opaque_data; struct ud_itab_entry * itab_entry; struct ud_lookup_table_list_entry *le; }; /* ----------------------------------------------------------------------------- * Type-definitions * ----------------------------------------------------------------------------- */ typedef enum ud_type ud_type_t; typedef enum ud_mnemonic_code ud_mnemonic_code_t; typedef struct ud ud_t; typedef struct ud_operand ud_operand_t; #define UD_SYN_INTEL ud_translate_intel #define UD_SYN_ATT ud_translate_att #define UD_EOI (-1) #define UD_INP_CACHE_SZ 32 #define UD_VENDOR_AMD 0 #define UD_VENDOR_INTEL 1 #define UD_VENDOR_ANY 2 #endif /* vim: set ts=2 sw=2 expandtab */
7,500
27.739464
84
h
php-src
php-src-master/ext/opcache/jit/libudis86/udint.h
/* udis86 - libudis86/udint.h -- definitions for internal use only * * Copyright (c) 2002-2009 Vivek Thampi * 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. * * 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. */ #ifndef _UDINT_H_ #define _UDINT_H_ #include "types.h" #ifdef HAVE_CONFIG_H # include <config.h> #endif /* HAVE_CONFIG_H */ #if defined(UD_DEBUG) && HAVE_ASSERT_H # include <assert.h> # define UD_ASSERT(_x) assert(_x) #else # define UD_ASSERT(_x) #endif /* !HAVE_ASSERT_H */ #if defined(UD_DEBUG) #define UDERR(u, msg) \ do { \ (u)->error = 1; \ fprintf(stderr, "decode-error: %s:%d: %s", \ __FILE__, __LINE__, (msg)); \ } while (0) #else #define UDERR(u, m) \ do { \ (u)->error = 1; \ } while (0) #endif /* !LOGERR */ #define UD_RETURN_ON_ERROR(u) \ do { \ if ((u)->error != 0) { \ return (u)->error; \ } \ } while (0) #define UD_RETURN_WITH_ERROR(u, m) \ do { \ UDERR(u, m); \ return (u)->error; \ } while (0) #ifndef __UD_STANDALONE__ # define UD_NON_STANDALONE(x) x #else # define UD_NON_STANDALONE(x) #endif /* printf formatting int64 specifier */ #ifdef FMT64 # undef FMT64 #endif #if defined(_MSC_VER) || defined(__BORLANDC__) # define FMT64 "I64" #else # if defined(__APPLE__) || defined(__OpenBSD__) # define FMT64 "ll" # elif defined(__amd64__) || defined(__x86_64__) # define FMT64 "l" # else # define FMT64 "ll" # endif /* !x64 */ #endif /* define an inline macro */ #if defined(_MSC_VER) || defined(__BORLANDC__) # define UD_INLINE __inline /* MS Visual Studio requires __inline instead of inline for C code */ #else # define UD_INLINE inline #endif #endif /* _UDINT_H_ */
2,984
28.85
84
h
php-src
php-src-master/ext/opcache/jit/libudis86/udis86.c
/* udis86 - libudis86/udis86.c * * Copyright (c) 2002-2013 Vivek Thampi * 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. * * 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. */ #include "udint.h" #include "extern.h" #include "decode.h" #if !defined(__UD_STANDALONE__) # if HAVE_STRING_H # include <string.h> # endif #endif /* !__UD_STANDALONE__ */ static void ud_inp_init(struct ud *u); /* ============================================================================= * ud_init * Initializes ud_t object. * ============================================================================= */ extern void ud_init(struct ud* u) { memset((void*)u, 0, sizeof(struct ud)); ud_set_mode(u, 16); u->mnemonic = UD_Iinvalid; ud_set_pc(u, 0); #ifndef __UD_STANDALONE__ ud_set_input_file(u, stdin); #endif /* __UD_STANDALONE__ */ ud_set_asm_buffer(u, u->asm_buf_int, sizeof(u->asm_buf_int)); } /* ============================================================================= * ud_disassemble * Disassembles one instruction and returns the number of * bytes disassembled. A zero means end of disassembly. * ============================================================================= */ extern unsigned int ud_disassemble(struct ud* u) { int len; if (u->inp_end) { return 0; } if ((len = ud_decode(u)) > 0) { if (u->translator != NULL) { u->asm_buf[0] = '\0'; u->translator(u); } } return len; } /* ============================================================================= * ud_set_mode() - Set Disassemly Mode. * ============================================================================= */ extern void ud_set_mode(struct ud* u, uint8_t m) { switch(m) { case 16: case 32: case 64: u->dis_mode = m ; return; default: u->dis_mode = 16; return; } } /* ============================================================================= * ud_set_vendor() - Set vendor. * ============================================================================= */ extern void ud_set_vendor(struct ud* u, unsigned v) { switch(v) { case UD_VENDOR_INTEL: u->vendor = v; break; case UD_VENDOR_ANY: u->vendor = v; break; default: u->vendor = UD_VENDOR_AMD; } } /* ============================================================================= * ud_set_pc() - Sets code origin. * ============================================================================= */ extern void ud_set_pc(struct ud* u, uint64_t o) { u->pc = o; } /* ============================================================================= * ud_set_syntax() - Sets the output syntax. * ============================================================================= */ extern void ud_set_syntax(struct ud* u, void (*t)(struct ud*)) { u->translator = t; } /* ============================================================================= * ud_insn() - returns the disassembled instruction * ============================================================================= */ const char* ud_insn_asm(const struct ud* u) { return u->asm_buf; } /* ============================================================================= * ud_insn_offset() - Returns the offset. * ============================================================================= */ uint64_t ud_insn_off(const struct ud* u) { return u->insn_offset; } /* ============================================================================= * ud_insn_hex() - Returns hex form of disassembled instruction. * ============================================================================= */ const char* ud_insn_hex(struct ud* u) { u->insn_hexcode[0] = 0; if (!u->error) { unsigned int i; const unsigned char *src_ptr = ud_insn_ptr(u); char* src_hex; src_hex = (char*) u->insn_hexcode; /* for each byte used to decode instruction */ for (i = 0; i < ud_insn_len(u) && i < sizeof(u->insn_hexcode) / 2; ++i, ++src_ptr) { sprintf(src_hex, "%02x", *src_ptr & 0xFF); src_hex += 2; } } return u->insn_hexcode; } /* ============================================================================= * ud_insn_ptr * Returns a pointer to buffer containing the bytes that were * disassembled. * ============================================================================= */ extern const uint8_t* ud_insn_ptr(const struct ud* u) { return (u->inp_buf == NULL) ? u->inp_sess : u->inp_buf + (u->inp_buf_index - u->inp_ctr); } /* ============================================================================= * ud_insn_len * Returns the count of bytes disassembled. * ============================================================================= */ extern unsigned int ud_insn_len(const struct ud* u) { return u->inp_ctr; } /* ============================================================================= * ud_insn_get_opr * Return the operand struct representing the nth operand of * the currently disassembled instruction. Returns NULL if * there's no such operand. * ============================================================================= */ const struct ud_operand* ud_insn_opr(const struct ud *u, unsigned int n) { if (n > 3 || u->operand[n].type == UD_NONE) { return NULL; } else { return &u->operand[n]; } } /* ============================================================================= * ud_opr_is_sreg * Returns non-zero if the given operand is of a segment register type. * ============================================================================= */ int ud_opr_is_sreg(const struct ud_operand *opr) { return opr->type == UD_OP_REG && opr->base >= UD_R_ES && opr->base <= UD_R_GS; } /* ============================================================================= * ud_opr_is_sreg * Returns non-zero if the given operand is of a general purpose * register type. * ============================================================================= */ int ud_opr_is_gpr(const struct ud_operand *opr) { return opr->type == UD_OP_REG && opr->base >= UD_R_AL && opr->base <= UD_R_R15; } /* ============================================================================= * ud_set_user_opaque_data * ud_get_user_opaque_data * Get/set user opaqute data pointer * ============================================================================= */ void ud_set_user_opaque_data(struct ud * u, void* opaque) { u->user_opaque_data = opaque; } void* ud_get_user_opaque_data(const struct ud *u) { return u->user_opaque_data; } /* ============================================================================= * ud_set_asm_buffer * Allow the user to set an assembler output buffer. If `buf` is NULL, * we switch back to the internal buffer. * ============================================================================= */ void ud_set_asm_buffer(struct ud *u, char *buf, size_t size) { if (buf == NULL) { ud_set_asm_buffer(u, u->asm_buf_int, sizeof(u->asm_buf_int)); } else { u->asm_buf = buf; u->asm_buf_size = size; } } /* ============================================================================= * ud_set_sym_resolver * Set symbol resolver for relative targets used in the translation * phase. * * The resolver is a function that takes a uint64_t address and returns a * symbolic name for the that address. The function also takes a second * argument pointing to an integer that the client can optionally set to a * non-zero value for offsetted targets. (symbol+offset) The function may * also return NULL, in which case the translator only prints the target * address. * * The function pointer maybe NULL which resets symbol resolution. * ============================================================================= */ void ud_set_sym_resolver(struct ud *u, const char* (*resolver)(struct ud*, uint64_t addr, int64_t *offset)) { u->sym_resolver = resolver; } /* ============================================================================= * ud_insn_mnemonic * Return the current instruction mnemonic. * ============================================================================= */ enum ud_mnemonic_code ud_insn_mnemonic(const struct ud *u) { return u->mnemonic; } /* ============================================================================= * ud_lookup_mnemonic * Looks up mnemonic code in the mnemonic string table. * Returns NULL if the mnemonic code is invalid. * ============================================================================= */ const char* ud_lookup_mnemonic(enum ud_mnemonic_code c) { if (c < UD_MAX_MNEMONIC_CODE) { return ud_mnemonics_str[c]; } else { return "???"; } } /* * ud_inp_init * Initializes the input system. */ static void ud_inp_init(struct ud *u) { u->inp_hook = NULL; u->inp_buf = NULL; u->inp_buf_size = 0; u->inp_buf_index = 0; u->inp_curr = 0; u->inp_ctr = 0; u->inp_end = 0; u->inp_peek = UD_EOI; UD_NON_STANDALONE(u->inp_file = NULL); } /* ============================================================================= * ud_inp_set_hook * Sets input hook. * ============================================================================= */ void ud_set_input_hook(register struct ud* u, int (*hook)(struct ud*)) { ud_inp_init(u); u->inp_hook = hook; } /* ============================================================================= * ud_inp_set_buffer * Set buffer as input. * ============================================================================= */ void ud_set_input_buffer(register struct ud* u, const uint8_t* buf, size_t len) { ud_inp_init(u); u->inp_buf = buf; u->inp_buf_size = len; u->inp_buf_index = 0; } #ifndef __UD_STANDALONE__ /* ============================================================================= * ud_input_set_file * Set FILE as input. * ============================================================================= */ static int inp_file_hook(struct ud* u) { return fgetc(u->inp_file); } void ud_set_input_file(register struct ud* u, FILE* f) { ud_inp_init(u); u->inp_hook = inp_file_hook; u->inp_file = f; } #endif /* __UD_STANDALONE__ */ /* ============================================================================= * ud_input_skip * Skip n input bytes. * ============================================================================ */ void ud_input_skip(struct ud* u, size_t n) { if (u->inp_end) { return; } if (u->inp_buf == NULL) { while (n--) { int c = u->inp_hook(u); if (c == UD_EOI) { goto eoi; } } return; } else { if (n > u->inp_buf_size || u->inp_buf_index > u->inp_buf_size - n) { u->inp_buf_index = u->inp_buf_size; goto eoi; } u->inp_buf_index += n; return; } eoi: u->inp_end = 1; UDERR(u, "cannot skip, eoi received\b"); return; } /* ============================================================================= * ud_input_end * Returns non-zero on end-of-input. * ============================================================================= */ int ud_input_end(const struct ud *u) { return u->inp_end; } /* vim:set ts=2 sw=2 expandtab */
12,798
26.884532
84
c
php-src
php-src-master/ext/opcache/jit/vtune/ittnotify_types.h
/* <copyright> This file is provided under a dual BSD/GPLv2 license. When using or redistributing this file, you may do so under either license. GPL LICENSE SUMMARY Copyright (c) 2005-2014 Intel Corporation. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called LICENSE.GPL. Contact Information: http://software.intel.com/en-us/articles/intel-vtune-amplifier-xe/ BSD LICENSE Copyright (c) 2005-2014 Intel Corporation. All rights reserved. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. </copyright> */ #ifndef _ITTNOTIFY_TYPES_H_ #define _ITTNOTIFY_TYPES_H_ typedef enum ___itt_group_id { __itt_group_none = 0, __itt_group_legacy = 1<<0, __itt_group_control = 1<<1, __itt_group_thread = 1<<2, __itt_group_mark = 1<<3, __itt_group_sync = 1<<4, __itt_group_fsync = 1<<5, __itt_group_jit = 1<<6, __itt_group_model = 1<<7, __itt_group_splitter_min = 1<<7, __itt_group_counter = 1<<8, __itt_group_frame = 1<<9, __itt_group_stitch = 1<<10, __itt_group_heap = 1<<11, __itt_group_splitter_max = 1<<12, __itt_group_structure = 1<<12, __itt_group_suppress = 1<<13, __itt_group_arrays = 1<<14, __itt_group_all = -1 } __itt_group_id; #pragma pack(push, 8) typedef struct ___itt_group_list { __itt_group_id id; const char* name; } __itt_group_list; #pragma pack(pop) #define ITT_GROUP_LIST(varname) \ static __itt_group_list varname[] = { \ { __itt_group_all, "all" }, \ { __itt_group_control, "control" }, \ { __itt_group_thread, "thread" }, \ { __itt_group_mark, "mark" }, \ { __itt_group_sync, "sync" }, \ { __itt_group_fsync, "fsync" }, \ { __itt_group_jit, "jit" }, \ { __itt_group_model, "model" }, \ { __itt_group_counter, "counter" }, \ { __itt_group_frame, "frame" }, \ { __itt_group_stitch, "stitch" }, \ { __itt_group_heap, "heap" }, \ { __itt_group_structure, "structure" }, \ { __itt_group_suppress, "suppress" }, \ { __itt_group_arrays, "arrays" }, \ { __itt_group_none, NULL } \ } #endif /* _ITTNOTIFY_TYPES_H_ */
4,523
38
76
h
php-src
php-src-master/ext/opcache/jit/vtune/jitprofiling.c
/* <copyright> This file is provided under a dual BSD/GPLv2 license. When using or redistributing this file, you may do so under either license. GPL LICENSE SUMMARY Copyright (c) 2005-2014 Intel Corporation. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called LICENSE.GPL. Contact Information: http://software.intel.com/en-us/articles/intel-vtune-amplifier-xe/ BSD LICENSE Copyright (c) 2005-2014 Intel Corporation. All rights reserved. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. </copyright> */ #include "ittnotify_config.h" #if ITT_PLATFORM==ITT_PLATFORM_WIN #include <windows.h> #pragma optimize("", off) #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ #include <stdlib.h> #include "jitprofiling.h" static const char rcsid[] = "\n@(#) $Revision: 463960 $\n"; #define DLL_ENVIRONMENT_VAR "VS_PROFILER" #ifndef NEW_DLL_ENVIRONMENT_VAR #if ITT_ARCH==ITT_ARCH_IA32 #define NEW_DLL_ENVIRONMENT_VAR "INTEL_JIT_PROFILER32" #else #define NEW_DLL_ENVIRONMENT_VAR "INTEL_JIT_PROFILER64" #endif #endif /* NEW_DLL_ENVIRONMENT_VAR */ #if ITT_PLATFORM==ITT_PLATFORM_WIN #define DEFAULT_DLLNAME "JitPI.dll" HINSTANCE m_libHandle = NULL; #elif ITT_PLATFORM==ITT_PLATFORM_MAC #define DEFAULT_DLLNAME "libJitPI.dylib" void* m_libHandle = NULL; #else #define DEFAULT_DLLNAME "libJitPI.so" void* m_libHandle = NULL; #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ /* default location of JIT profiling agent on Android */ #define ANDROID_JIT_AGENT_PATH "/data/intel/libittnotify.so" /* the function pointers */ typedef unsigned int(JITAPI *TPInitialize)(void); static TPInitialize FUNC_Initialize=NULL; typedef unsigned int(JITAPI *TPNotify)(unsigned int, void*); static TPNotify FUNC_NotifyEvent=NULL; static iJIT_IsProfilingActiveFlags executionMode = iJIT_NOTHING_RUNNING; /* end collector dll part. */ /* loadiJIT_Funcs() : this function is called just in the beginning * and is responsible to load the functions from BistroJavaCollector.dll * result: * on success: the functions loads, iJIT_DLL_is_missing=0, return value = 1 * on failure: the functions are NULL, iJIT_DLL_is_missing=1, return value = 0 */ static int loadiJIT_Funcs(void); /* global representing whether the collector can't be loaded */ static int iJIT_DLL_is_missing = 0; ITT_EXTERN_C int JITAPI iJIT_NotifyEvent(iJIT_JVM_EVENT event_type, void *EventSpecificData) { int ReturnValue; /* initialization part - the collector has not been loaded yet. */ if (!FUNC_NotifyEvent) { if (iJIT_DLL_is_missing) return 0; if (!loadiJIT_Funcs()) return 0; } if (event_type == iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED || event_type == iJVM_EVENT_TYPE_METHOD_UPDATE) { if (((piJIT_Method_Load)EventSpecificData)->method_id == 0) return 0; } else if (event_type == iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED_V2) { if (((piJIT_Method_Load_V2)EventSpecificData)->method_id == 0) return 0; } else if (event_type == iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED_V3) { if (((piJIT_Method_Load_V3)EventSpecificData)->method_id == 0) return 0; } else if (event_type == iJVM_EVENT_TYPE_METHOD_INLINE_LOAD_FINISHED) { if (((piJIT_Method_Inline_Load)EventSpecificData)->method_id == 0 || ((piJIT_Method_Inline_Load)EventSpecificData)->parent_method_id == 0) return 0; } ReturnValue = (int)FUNC_NotifyEvent(event_type, EventSpecificData); return ReturnValue; } ITT_EXTERN_C iJIT_IsProfilingActiveFlags JITAPI iJIT_IsProfilingActive(void) { if (!iJIT_DLL_is_missing) { loadiJIT_Funcs(); } return executionMode; } /* This function loads the collector dll and the relevant functions. * on success: all functions load, iJIT_DLL_is_missing = 0, return value = 1 * on failure: all functions are NULL, iJIT_DLL_is_missing = 1, return value = 0 */ static int loadiJIT_Funcs(void) { static int bDllWasLoaded = 0; char *dllName = (char*)rcsid; /* !! Just to avoid unused code elimination */ #if ITT_PLATFORM==ITT_PLATFORM_WIN DWORD dNameLength = 0; #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if(bDllWasLoaded) { /* dll was already loaded, no need to do it for the second time */ return 1; } /* Assumes that the DLL will not be found */ iJIT_DLL_is_missing = 1; FUNC_NotifyEvent = NULL; if (m_libHandle) { #if ITT_PLATFORM==ITT_PLATFORM_WIN FreeLibrary(m_libHandle); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ dlclose(m_libHandle); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ m_libHandle = NULL; } /* Try to get the dll name from the environment */ #if ITT_PLATFORM==ITT_PLATFORM_WIN dNameLength = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, NULL, 0); if (dNameLength) { DWORD envret = 0; dllName = (char*)malloc(sizeof(char) * (dNameLength + 1)); if(dllName != NULL) { envret = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, dllName, dNameLength); if (envret) { /* Try to load the dll from the PATH... */ m_libHandle = LoadLibraryExA(dllName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } free(dllName); } } else { /* Try to use old VS_PROFILER variable */ dNameLength = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, NULL, 0); if (dNameLength) { DWORD envret = 0; dllName = (char*)malloc(sizeof(char) * (dNameLength + 1)); if(dllName != NULL) { envret = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, dllName, dNameLength); if (envret) { /* Try to load the dll from the PATH... */ m_libHandle = LoadLibraryA(dllName); } free(dllName); } } } #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ dllName = getenv(NEW_DLL_ENVIRONMENT_VAR); if (!dllName) dllName = getenv(DLL_ENVIRONMENT_VAR); #if defined(__ANDROID__) || defined(ANDROID) if (!dllName) dllName = ANDROID_JIT_AGENT_PATH; #endif if (dllName) { /* Try to load the dll from the PATH... */ m_libHandle = dlopen(dllName, RTLD_LAZY); } #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!m_libHandle) { #if ITT_PLATFORM==ITT_PLATFORM_WIN m_libHandle = LoadLibraryA(DEFAULT_DLLNAME); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ m_libHandle = dlopen(DEFAULT_DLLNAME, RTLD_LAZY); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ } /* if the dll wasn't loaded - exit. */ if (!m_libHandle) { iJIT_DLL_is_missing = 1; /* don't try to initialize * JIT agent the second time */ return 0; } #if ITT_PLATFORM==ITT_PLATFORM_WIN FUNC_NotifyEvent = (TPNotify)GetProcAddress(m_libHandle, "NotifyEvent"); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ FUNC_NotifyEvent = (TPNotify)dlsym(m_libHandle, "NotifyEvent"); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!FUNC_NotifyEvent) { FUNC_Initialize = NULL; return 0; } #if ITT_PLATFORM==ITT_PLATFORM_WIN FUNC_Initialize = (TPInitialize)GetProcAddress(m_libHandle, "Initialize"); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ FUNC_Initialize = (TPInitialize)dlsym(m_libHandle, "Initialize"); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!FUNC_Initialize) { FUNC_NotifyEvent = NULL; return 0; } executionMode = (iJIT_IsProfilingActiveFlags)FUNC_Initialize(); bDllWasLoaded = 1; iJIT_DLL_is_missing = 0; /* DLL is ok. */ return 1; } ITT_EXTERN_C unsigned int JITAPI iJIT_GetNewMethodID(void) { static unsigned int methodID = 1; if (methodID == 0) return 0; /* ERROR : this is not a valid value */ return methodID++; }
10,448
32.383387
82
c
php-src
php-src-master/ext/openssl/php_openssl.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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. | +----------------------------------------------------------------------+ | Authors: Stig Venaas <[email protected]> | | Wez Furlong <[email protected] | +----------------------------------------------------------------------+ */ #ifndef PHP_OPENSSL_H #define PHP_OPENSSL_H /* HAVE_OPENSSL would include SSL MySQL stuff */ #ifdef HAVE_OPENSSL_EXT extern zend_module_entry openssl_module_entry; #define phpext_openssl_ptr &openssl_module_entry #include "php_version.h" #define PHP_OPENSSL_VERSION PHP_VERSION #include <openssl/opensslv.h> #if defined(LIBRESSL_VERSION_NUMBER) /* LibreSSL version check */ #if LIBRESSL_VERSION_NUMBER < 0x20700000L #define PHP_OPENSSL_API_VERSION 0x10001 #else #define PHP_OPENSSL_API_VERSION 0x10100 #endif #else /* OpenSSL version check */ #if OPENSSL_VERSION_NUMBER < 0x10100000L #define PHP_OPENSSL_API_VERSION 0x10002 #elif OPENSSL_VERSION_NUMBER < 0x30000000L #define PHP_OPENSSL_API_VERSION 0x10100 #else #define PHP_OPENSSL_API_VERSION 0x30000 #endif #endif #define OPENSSL_RAW_DATA 1 #define OPENSSL_ZERO_PADDING 2 #define OPENSSL_DONT_ZERO_PAD_KEY 4 #define OPENSSL_ERROR_X509_PRIVATE_KEY_VALUES_MISMATCH 0x0B080074 /* Used for client-initiated handshake renegotiation DoS protection*/ #define OPENSSL_DEFAULT_RENEG_LIMIT 2 #define OPENSSL_DEFAULT_RENEG_WINDOW 300 #define OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH 9 #define OPENSSL_DEFAULT_STREAM_CIPHERS "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" \ "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:" \ "DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:" \ "ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" \ "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:" \ "DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:" \ "AES256-GCM-SHA384:AES128:AES256:HIGH:!SSLv2:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!RC4:!ADH" #include <openssl/err.h> #ifdef PHP_WIN32 # define PHP_OPENSSL_API __declspec(dllexport) #elif defined(__GNUC__) && __GNUC__ >= 4 # define PHP_OPENSSL_API __attribute__((visibility("default"))) #else # define PHP_OPENSSL_API #endif struct php_openssl_errors { int buffer[ERR_NUM_ERRORS]; int top; int bottom; }; ZEND_BEGIN_MODULE_GLOBALS(openssl) struct php_openssl_errors *errors; struct php_openssl_errors *errors_mark; ZEND_END_MODULE_GLOBALS(openssl) #define OPENSSL_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(openssl, v) #if defined(ZTS) && defined(COMPILE_DL_OPENSSL) ZEND_TSRMLS_CACHE_EXTERN(); #endif php_stream_transport_factory_func php_openssl_ssl_socket_factory; void php_openssl_store_errors(void); /* openssl file path extra */ bool php_openssl_check_path_ex( const char *file_path, size_t file_path_len, char *real_path, uint32_t arg_num, bool contains_file_protocol, bool is_from_array, const char *option_name); /* openssl file path check */ static inline bool php_openssl_check_path( const char *file_path, size_t file_path_len, char *real_path, uint32_t arg_num) { return php_openssl_check_path_ex( file_path, file_path_len, real_path, arg_num, false, false, NULL); } /* openssl file path extra check with zend string */ static inline bool php_openssl_check_path_str_ex( zend_string *file_path, char *real_path, uint32_t arg_num, bool contains_file_protocol, bool is_from_array, const char *option_name) { return php_openssl_check_path_ex( ZSTR_VAL(file_path), ZSTR_LEN(file_path), real_path, arg_num, contains_file_protocol, is_from_array, option_name); } /* openssl file path check with zend string */ static inline bool php_openssl_check_path_str( zend_string *file_path, char *real_path, uint32_t arg_num) { return php_openssl_check_path_str_ex(file_path, real_path, arg_num, true, false, NULL); } PHP_OPENSSL_API zend_long php_openssl_cipher_iv_length(const char *method); PHP_OPENSSL_API zend_long php_openssl_cipher_key_length(const char *method); PHP_OPENSSL_API zend_string* php_openssl_random_pseudo_bytes(zend_long length); PHP_OPENSSL_API zend_string* php_openssl_encrypt( const char *data, size_t data_len, const char *method, size_t method_len, const char *password, size_t password_len, zend_long options, const char *iv, size_t iv_len, zval *tag, zend_long tag_len, const char *aad, size_t aad_len); PHP_OPENSSL_API zend_string* php_openssl_decrypt( const char *data, size_t data_len, const char *method, size_t method_len, const char *password, size_t password_len, zend_long options, const char *iv, size_t iv_len, const char *tag, zend_long tag_len, const char *aad, size_t aad_len); /* OpenSSLCertificate class */ typedef struct _php_openssl_certificate_object { X509 *x509; zend_object std; } php_openssl_certificate_object; extern zend_class_entry *php_openssl_certificate_ce; static inline php_openssl_certificate_object *php_openssl_certificate_from_obj(zend_object *obj) { return (php_openssl_certificate_object *)((char *)(obj) - XtOffsetOf(php_openssl_certificate_object, std)); } #define Z_OPENSSL_CERTIFICATE_P(zv) php_openssl_certificate_from_obj(Z_OBJ_P(zv)) PHP_MINIT_FUNCTION(openssl); PHP_MSHUTDOWN_FUNCTION(openssl); PHP_MINFO_FUNCTION(openssl); PHP_GINIT_FUNCTION(openssl); PHP_GSHUTDOWN_FUNCTION(openssl); #ifdef PHP_WIN32 #define PHP_OPENSSL_BIO_MODE_R(flags) (((flags) & PKCS7_BINARY) ? "rb" : "r") #define PHP_OPENSSL_BIO_MODE_W(flags) (((flags) & PKCS7_BINARY) ? "wb" : "w") #else #define PHP_OPENSSL_BIO_MODE_R(flags) "r" #define PHP_OPENSSL_BIO_MODE_W(flags) "w" #endif #else #define phpext_openssl_ptr NULL #endif #endif
6,517
34.617486
108
h
php-src
php-src-master/ext/pcntl/pcntl_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: 3b03373d1bb68de779baaa62db14d98ca9018339 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_fork, 0, 0, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_waitpid, 0, 2, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, process_id, IS_LONG, 0) ZEND_ARG_INFO(1, status) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, resource_usage, "[]") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_wait, 0, 1, IS_LONG, 0) ZEND_ARG_INFO(1, status) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, resource_usage, "[]") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_signal, 0, 2, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, signal, IS_LONG, 0) ZEND_ARG_INFO(0, handler) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, restart_syscalls, _IS_BOOL, 0, "true") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pcntl_signal_get_handler, 0, 0, 1) ZEND_ARG_TYPE_INFO(0, signal, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_signal_dispatch, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() #if defined(HAVE_SIGPROCMASK) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_sigprocmask, 0, 2, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, mode, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, signals, IS_ARRAY, 0) ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, old_signals, "null") ZEND_END_ARG_INFO() #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_pcntl_sigwaitinfo, 0, 1, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, signals, IS_ARRAY, 0) ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, info, "[]") ZEND_END_ARG_INFO() #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_pcntl_sigtimedwait, 0, 1, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, signals, IS_ARRAY, 0) ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, info, "[]") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, seconds, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, nanoseconds, IS_LONG, 0, "0") ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_wifexited, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, status, IS_LONG, 0) ZEND_END_ARG_INFO() #define arginfo_pcntl_wifstopped arginfo_pcntl_wifexited #if defined(HAVE_WCONTINUED) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_wifcontinued, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, status, IS_LONG, 0) ZEND_END_ARG_INFO() #endif #define arginfo_pcntl_wifsignaled arginfo_pcntl_wifexited ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_pcntl_wexitstatus, 0, 1, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, status, IS_LONG, 0) ZEND_END_ARG_INFO() #define arginfo_pcntl_wtermsig arginfo_pcntl_wexitstatus #define arginfo_pcntl_wstopsig arginfo_pcntl_wexitstatus ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_exec, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, path, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, args, IS_ARRAY, 0, "[]") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, env_vars, IS_ARRAY, 0, "[]") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_alarm, 0, 1, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, seconds, IS_LONG, 0) ZEND_END_ARG_INFO() #define arginfo_pcntl_get_last_error arginfo_pcntl_fork #define arginfo_pcntl_errno arginfo_pcntl_fork #if defined(HAVE_GETPRIORITY) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_pcntl_getpriority, 0, 0, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, process_id, IS_LONG, 1, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, mode, IS_LONG, 0, "PRIO_PROCESS") ZEND_END_ARG_INFO() #endif #if defined(HAVE_SETPRIORITY) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_setpriority, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, priority, IS_LONG, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, process_id, IS_LONG, 1, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, mode, IS_LONG, 0, "PRIO_PROCESS") ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_strerror, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, error_code, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_async_signals, 0, 0, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, enable, _IS_BOOL, 1, "null") ZEND_END_ARG_INFO() #if defined(HAVE_UNSHARE) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_unshare, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, flags, IS_LONG, 0) ZEND_END_ARG_INFO() #endif #if defined(HAVE_RFORK) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_rfork, 0, 1, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, flags, IS_LONG, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, signal, IS_LONG, 0, "0") ZEND_END_ARG_INFO() #endif #if defined(HAVE_FORKX) ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pcntl_forkx, 0, 1, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, flags, IS_LONG, 0) ZEND_END_ARG_INFO() #endif ZEND_FUNCTION(pcntl_fork); ZEND_FUNCTION(pcntl_waitpid); ZEND_FUNCTION(pcntl_wait); ZEND_FUNCTION(pcntl_signal); ZEND_FUNCTION(pcntl_signal_get_handler); ZEND_FUNCTION(pcntl_signal_dispatch); #if defined(HAVE_SIGPROCMASK) ZEND_FUNCTION(pcntl_sigprocmask); #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_FUNCTION(pcntl_sigwaitinfo); #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_FUNCTION(pcntl_sigtimedwait); #endif ZEND_FUNCTION(pcntl_wifexited); ZEND_FUNCTION(pcntl_wifstopped); #if defined(HAVE_WCONTINUED) ZEND_FUNCTION(pcntl_wifcontinued); #endif ZEND_FUNCTION(pcntl_wifsignaled); ZEND_FUNCTION(pcntl_wexitstatus); ZEND_FUNCTION(pcntl_wtermsig); ZEND_FUNCTION(pcntl_wstopsig); ZEND_FUNCTION(pcntl_exec); ZEND_FUNCTION(pcntl_alarm); ZEND_FUNCTION(pcntl_get_last_error); #if defined(HAVE_GETPRIORITY) ZEND_FUNCTION(pcntl_getpriority); #endif #if defined(HAVE_SETPRIORITY) ZEND_FUNCTION(pcntl_setpriority); #endif ZEND_FUNCTION(pcntl_strerror); ZEND_FUNCTION(pcntl_async_signals); #if defined(HAVE_UNSHARE) ZEND_FUNCTION(pcntl_unshare); #endif #if defined(HAVE_RFORK) ZEND_FUNCTION(pcntl_rfork); #endif #if defined(HAVE_FORKX) ZEND_FUNCTION(pcntl_forkx); #endif static const zend_function_entry ext_functions[] = { ZEND_FE(pcntl_fork, arginfo_pcntl_fork) ZEND_FE(pcntl_waitpid, arginfo_pcntl_waitpid) ZEND_FE(pcntl_wait, arginfo_pcntl_wait) ZEND_FE(pcntl_signal, arginfo_pcntl_signal) ZEND_FE(pcntl_signal_get_handler, arginfo_pcntl_signal_get_handler) ZEND_FE(pcntl_signal_dispatch, arginfo_pcntl_signal_dispatch) #if defined(HAVE_SIGPROCMASK) ZEND_FE(pcntl_sigprocmask, arginfo_pcntl_sigprocmask) #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_FE(pcntl_sigwaitinfo, arginfo_pcntl_sigwaitinfo) #endif #if defined(HAVE_STRUCT_SIGINFO_T) && (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) ZEND_FE(pcntl_sigtimedwait, arginfo_pcntl_sigtimedwait) #endif ZEND_FE(pcntl_wifexited, arginfo_pcntl_wifexited) ZEND_FE(pcntl_wifstopped, arginfo_pcntl_wifstopped) #if defined(HAVE_WCONTINUED) ZEND_FE(pcntl_wifcontinued, arginfo_pcntl_wifcontinued) #endif ZEND_FE(pcntl_wifsignaled, arginfo_pcntl_wifsignaled) ZEND_FE(pcntl_wexitstatus, arginfo_pcntl_wexitstatus) ZEND_FE(pcntl_wtermsig, arginfo_pcntl_wtermsig) ZEND_FE(pcntl_wstopsig, arginfo_pcntl_wstopsig) ZEND_FE(pcntl_exec, arginfo_pcntl_exec) ZEND_FE(pcntl_alarm, arginfo_pcntl_alarm) ZEND_FE(pcntl_get_last_error, arginfo_pcntl_get_last_error) ZEND_FALIAS(pcntl_errno, pcntl_get_last_error, arginfo_pcntl_errno) #if defined(HAVE_GETPRIORITY) ZEND_FE(pcntl_getpriority, arginfo_pcntl_getpriority) #endif #if defined(HAVE_SETPRIORITY) ZEND_FE(pcntl_setpriority, arginfo_pcntl_setpriority) #endif ZEND_FE(pcntl_strerror, arginfo_pcntl_strerror) ZEND_FE(pcntl_async_signals, arginfo_pcntl_async_signals) #if defined(HAVE_UNSHARE) ZEND_FE(pcntl_unshare, arginfo_pcntl_unshare) #endif #if defined(HAVE_RFORK) ZEND_FE(pcntl_rfork, arginfo_pcntl_rfork) #endif #if defined(HAVE_FORKX) ZEND_FE(pcntl_forkx, arginfo_pcntl_forkx) #endif ZEND_FE_END }; static void register_pcntl_symbols(int module_number) { #if defined(WNOHANG) REGISTER_LONG_CONSTANT("WNOHANG", LONG_CONST(WNOHANG), CONST_PERSISTENT); #endif #if defined(WUNTRACED) REGISTER_LONG_CONSTANT("WUNTRACED", LONG_CONST(WUNTRACED), CONST_PERSISTENT); #endif #if defined(HAVE_WCONTINUED) REGISTER_LONG_CONSTANT("WCONTINUED", LONG_CONST(WCONTINUED), CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("SIG_IGN", LONG_CONST(SIG_IGN), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIG_DFL", LONG_CONST(SIG_DFL), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIG_ERR", LONG_CONST(SIG_ERR), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGHUP", LONG_CONST(SIGHUP), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGINT", LONG_CONST(SIGINT), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGQUIT", LONG_CONST(SIGQUIT), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGILL", LONG_CONST(SIGILL), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGTRAP", LONG_CONST(SIGTRAP), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGABRT", LONG_CONST(SIGABRT), CONST_PERSISTENT); #if defined(SIGIOT) REGISTER_LONG_CONSTANT("SIGIOT", LONG_CONST(SIGIOT), CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("SIGBUS", LONG_CONST(SIGBUS), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGFPE", LONG_CONST(SIGFPE), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGKILL", LONG_CONST(SIGKILL), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGUSR1", LONG_CONST(SIGUSR1), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGSEGV", LONG_CONST(SIGSEGV), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGUSR2", LONG_CONST(SIGUSR2), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGPIPE", LONG_CONST(SIGPIPE), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGALRM", LONG_CONST(SIGALRM), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGTERM", LONG_CONST(SIGTERM), CONST_PERSISTENT); #if defined(SIGSTKFLT) REGISTER_LONG_CONSTANT("SIGSTKFLT", LONG_CONST(SIGSTKFLT), CONST_PERSISTENT); #endif #if defined(SIGCLD) REGISTER_LONG_CONSTANT("SIGCLD", LONG_CONST(SIGCLD), CONST_PERSISTENT); #endif #if defined(SIGCHLD) REGISTER_LONG_CONSTANT("SIGCHLD", LONG_CONST(SIGCHLD), CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("SIGCONT", LONG_CONST(SIGCONT), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGSTOP", LONG_CONST(SIGSTOP), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGTSTP", LONG_CONST(SIGTSTP), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGTTIN", LONG_CONST(SIGTTIN), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGTTOU", LONG_CONST(SIGTTOU), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGURG", LONG_CONST(SIGURG), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGXCPU", LONG_CONST(SIGXCPU), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGXFSZ", LONG_CONST(SIGXFSZ), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGVTALRM", LONG_CONST(SIGVTALRM), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGPROF", LONG_CONST(SIGPROF), CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SIGWINCH", LONG_CONST(SIGWINCH), CONST_PERSISTENT); #if defined(SIGPOLL) REGISTER_LONG_CONSTANT("SIGPOLL", LONG_CONST(SIGPOLL), CONST_PERSISTENT); #endif #if defined(SIGIO) REGISTER_LONG_CONSTANT("SIGIO", LONG_CONST(SIGIO), CONST_PERSISTENT); #endif #if defined(SIGPWR) REGISTER_LONG_CONSTANT("SIGPWR", LONG_CONST(SIGPWR), CONST_PERSISTENT); #endif #if defined(SIGINFO) REGISTER_LONG_CONSTANT("SIGINFO", LONG_CONST(SIGINFO), CONST_PERSISTENT); #endif #if defined(SIGSYS) REGISTER_LONG_CONSTANT("SIGSYS", LONG_CONST(SIGSYS), CONST_PERSISTENT); #endif #if defined(SIGSYS) REGISTER_LONG_CONSTANT("SIGBABY", LONG_CONST(SIGSYS), CONST_PERSISTENT); #endif #if defined(SIGRTMIN) REGISTER_LONG_CONSTANT("SIGRTMIN", LONG_CONST(SIGRTMIN), CONST_PERSISTENT); #endif #if defined(SIGRTMAX) REGISTER_LONG_CONSTANT("SIGRTMAX", LONG_CONST(SIGRTMAX), CONST_PERSISTENT); #endif #if (defined(HAVE_GETPRIORITY) || defined(HAVE_SETPRIORITY)) REGISTER_LONG_CONSTANT("PRIO_PGRP", PRIO_PGRP, CONST_PERSISTENT); #endif #if (defined(HAVE_GETPRIORITY) || defined(HAVE_SETPRIORITY)) REGISTER_LONG_CONSTANT("PRIO_USER", PRIO_USER, CONST_PERSISTENT); #endif #if (defined(HAVE_GETPRIORITY) || defined(HAVE_SETPRIORITY)) REGISTER_LONG_CONSTANT("PRIO_PROCESS", PRIO_PROCESS, CONST_PERSISTENT); #endif #if (defined(HAVE_GETPRIORITY) || defined(HAVE_SETPRIORITY)) && defined(PRIO_DARWIN_BG) REGISTER_LONG_CONSTANT("PRIO_DARWIN_BG", PRIO_DARWIN_BG, CONST_PERSISTENT); #endif #if (defined(HAVE_GETPRIORITY) || defined(HAVE_SETPRIORITY)) && defined(PRIO_DARWIN_BG) REGISTER_LONG_CONSTANT("PRIO_DARWIN_THREAD", PRIO_DARWIN_THREAD, CONST_PERSISTENT); #endif #if defined(HAVE_SIGPROCMASK) REGISTER_LONG_CONSTANT("SIG_BLOCK", SIG_BLOCK, CONST_PERSISTENT); #endif #if defined(HAVE_SIGPROCMASK) REGISTER_LONG_CONSTANT("SIG_UNBLOCK", SIG_UNBLOCK, CONST_PERSISTENT); #endif #if defined(HAVE_SIGPROCMASK) REGISTER_LONG_CONSTANT("SIG_SETMASK", SIG_SETMASK, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) REGISTER_LONG_CONSTANT("SI_USER", SI_USER, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SI_NOINFO) REGISTER_LONG_CONSTANT("SI_NOINFO", SI_NOINFO, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SI_KERNEL) REGISTER_LONG_CONSTANT("SI_KERNEL", SI_KERNEL, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) REGISTER_LONG_CONSTANT("SI_QUEUE", SI_QUEUE, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) REGISTER_LONG_CONSTANT("SI_TIMER", SI_TIMER, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) REGISTER_LONG_CONSTANT("SI_MESGQ", SI_MESGQ, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) REGISTER_LONG_CONSTANT("SI_ASYNCIO", SI_ASYNCIO, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SI_SIGIO) REGISTER_LONG_CONSTANT("SI_SIGIO", SI_SIGIO, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SI_TKILL) REGISTER_LONG_CONSTANT("SI_TKILL", SI_TKILL, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_EXITED) REGISTER_LONG_CONSTANT("CLD_EXITED", CLD_EXITED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_KILLED) REGISTER_LONG_CONSTANT("CLD_KILLED", CLD_KILLED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_DUMPED) REGISTER_LONG_CONSTANT("CLD_DUMPED", CLD_DUMPED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_TRAPPED) REGISTER_LONG_CONSTANT("CLD_TRAPPED", CLD_TRAPPED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_STOPPED) REGISTER_LONG_CONSTANT("CLD_STOPPED", CLD_STOPPED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(CLD_CONTINUED) REGISTER_LONG_CONSTANT("CLD_CONTINUED", CLD_CONTINUED, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(TRAP_BRKPT) REGISTER_LONG_CONSTANT("TRAP_BRKPT", TRAP_BRKPT, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(TRAP_TRACE) REGISTER_LONG_CONSTANT("TRAP_TRACE", TRAP_TRACE, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_IN) REGISTER_LONG_CONSTANT("POLL_IN", POLL_IN, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_OUT) REGISTER_LONG_CONSTANT("POLL_OUT", POLL_OUT, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_MSG) REGISTER_LONG_CONSTANT("POLL_MSG", POLL_MSG, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_ERR) REGISTER_LONG_CONSTANT("POLL_ERR", POLL_ERR, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_PRI) REGISTER_LONG_CONSTANT("POLL_PRI", POLL_PRI, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(POLL_HUP) REGISTER_LONG_CONSTANT("POLL_HUP", POLL_HUP, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_ILLOPC) REGISTER_LONG_CONSTANT("ILL_ILLOPC", ILL_ILLOPC, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_ILLOPN) REGISTER_LONG_CONSTANT("ILL_ILLOPN", ILL_ILLOPN, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_ILLADR) REGISTER_LONG_CONSTANT("ILL_ILLADR", ILL_ILLADR, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_ILLTRP) REGISTER_LONG_CONSTANT("ILL_ILLTRP", ILL_ILLTRP, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_PRVOPC) REGISTER_LONG_CONSTANT("ILL_PRVOPC", ILL_PRVOPC, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_PRVREG) REGISTER_LONG_CONSTANT("ILL_PRVREG", ILL_PRVREG, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_COPROC) REGISTER_LONG_CONSTANT("ILL_COPROC", ILL_COPROC, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(ILL_BADSTK) REGISTER_LONG_CONSTANT("ILL_BADSTK", ILL_BADSTK, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_INTDIV) REGISTER_LONG_CONSTANT("FPE_INTDIV", FPE_INTDIV, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_INTOVF) REGISTER_LONG_CONSTANT("FPE_INTOVF", FPE_INTOVF, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTDIV) REGISTER_LONG_CONSTANT("FPE_FLTDIV", FPE_FLTDIV, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTOVF) REGISTER_LONG_CONSTANT("FPE_FLTOVF", FPE_FLTOVF, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTUND) REGISTER_LONG_CONSTANT("FPE_FLTUND", FPE_FLTUND, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTRES) REGISTER_LONG_CONSTANT("FPE_FLTRES", FPE_FLTRES, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTINV) REGISTER_LONG_CONSTANT("FPE_FLTINV", FPE_FLTINV, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(FPE_FLTSUB) REGISTER_LONG_CONSTANT("FPE_FLTSUB", FPE_FLTSUB, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SEGV_MAPERR) REGISTER_LONG_CONSTANT("SEGV_MAPERR", SEGV_MAPERR, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(SEGV_ACCERR) REGISTER_LONG_CONSTANT("SEGV_ACCERR", SEGV_ACCERR, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(BUS_ADRALN) REGISTER_LONG_CONSTANT("BUS_ADRALN", BUS_ADRALN, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(BUS_ADRERR) REGISTER_LONG_CONSTANT("BUS_ADRERR", BUS_ADRERR, CONST_PERSISTENT); #endif #if (defined(HAVE_SIGWAITINFO) && defined(HAVE_SIGTIMEDWAIT)) && defined(BUS_OBJERR) REGISTER_LONG_CONSTANT("BUS_OBJERR", BUS_OBJERR, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) REGISTER_LONG_CONSTANT("CLONE_NEWNS", CLONE_NEWNS, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWIPC) REGISTER_LONG_CONSTANT("CLONE_NEWIPC", CLONE_NEWIPC, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWUTS) REGISTER_LONG_CONSTANT("CLONE_NEWUTS", CLONE_NEWUTS, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWNET) REGISTER_LONG_CONSTANT("CLONE_NEWNET", CLONE_NEWNET, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWPID) REGISTER_LONG_CONSTANT("CLONE_NEWPID", CLONE_NEWPID, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWUSER) REGISTER_LONG_CONSTANT("CLONE_NEWUSER", CLONE_NEWUSER, CONST_PERSISTENT); #endif #if defined(HAVE_UNSHARE) && defined(CLONE_NEWCGROUP) REGISTER_LONG_CONSTANT("CLONE_NEWCGROUP", CLONE_NEWCGROUP, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFPROC) REGISTER_LONG_CONSTANT("RFPROC", RFPROC, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFNOWAIT) REGISTER_LONG_CONSTANT("RFNOWAIT", RFNOWAIT, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFCFDG) REGISTER_LONG_CONSTANT("RFCFDG", RFCFDG, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFFDG) REGISTER_LONG_CONSTANT("RFFDG", RFFDG, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFLINUXTHPN) REGISTER_LONG_CONSTANT("RFLINUXTHPN", RFLINUXTHPN, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFTSIGZMB) REGISTER_LONG_CONSTANT("RFTSIGZMB", RFTSIGZMB, CONST_PERSISTENT); #endif #if defined(HAVE_RFORK) && defined(RFTHREAD) REGISTER_LONG_CONSTANT("RFTHREAD", RFTHREAD, CONST_PERSISTENT); #endif #if defined(HAVE_FORKX) REGISTER_LONG_CONSTANT("FORK_NOSIGCHLD", FORK_NOSIGCHLD, CONST_PERSISTENT); #endif #if defined(HAVE_FORKX) REGISTER_LONG_CONSTANT("FORK_WAITPID", FORK_WAITPID, CONST_PERSISTENT); #endif #if defined(EINTR) REGISTER_LONG_CONSTANT("PCNTL_EINTR", EINTR, CONST_PERSISTENT); #endif #if defined(ECHILD) REGISTER_LONG_CONSTANT("PCNTL_ECHILD", ECHILD, CONST_PERSISTENT); #endif #if defined(EINVAL) REGISTER_LONG_CONSTANT("PCNTL_EINVAL", EINVAL, CONST_PERSISTENT); #endif #if defined(EAGAIN) REGISTER_LONG_CONSTANT("PCNTL_EAGAIN", EAGAIN, CONST_PERSISTENT); #endif #if defined(ESRCH) REGISTER_LONG_CONSTANT("PCNTL_ESRCH", ESRCH, CONST_PERSISTENT); #endif #if defined(EACCES) REGISTER_LONG_CONSTANT("PCNTL_EACCES", EACCES, CONST_PERSISTENT); #endif #if defined(EPERM) REGISTER_LONG_CONSTANT("PCNTL_EPERM", EPERM, CONST_PERSISTENT); #endif #if defined(ENOMEM) REGISTER_LONG_CONSTANT("PCNTL_ENOMEM", ENOMEM, CONST_PERSISTENT); #endif #if defined(E2BIG) REGISTER_LONG_CONSTANT("PCNTL_E2BIG", E2BIG, CONST_PERSISTENT); #endif #if defined(EFAULT) REGISTER_LONG_CONSTANT("PCNTL_EFAULT", EFAULT, CONST_PERSISTENT); #endif #if defined(EIO) REGISTER_LONG_CONSTANT("PCNTL_EIO", EIO, CONST_PERSISTENT); #endif #if defined(EISDIR) REGISTER_LONG_CONSTANT("PCNTL_EISDIR", EISDIR, CONST_PERSISTENT); #endif #if defined(ELIBBAD) REGISTER_LONG_CONSTANT("PCNTL_ELIBBAD", ELIBBAD, CONST_PERSISTENT); #endif #if defined(ELOOP) REGISTER_LONG_CONSTANT("PCNTL_ELOOP", ELOOP, CONST_PERSISTENT); #endif #if defined(EMFILE) REGISTER_LONG_CONSTANT("PCNTL_EMFILE", EMFILE, CONST_PERSISTENT); #endif #if defined(ENAMETOOLONG) REGISTER_LONG_CONSTANT("PCNTL_ENAMETOOLONG", ENAMETOOLONG, CONST_PERSISTENT); #endif #if defined(ENFILE) REGISTER_LONG_CONSTANT("PCNTL_ENFILE", ENFILE, CONST_PERSISTENT); #endif #if defined(ENOENT) REGISTER_LONG_CONSTANT("PCNTL_ENOENT", ENOENT, CONST_PERSISTENT); #endif #if defined(ENOEXEC) REGISTER_LONG_CONSTANT("PCNTL_ENOEXEC", ENOEXEC, CONST_PERSISTENT); #endif #if defined(ENOTDIR) REGISTER_LONG_CONSTANT("PCNTL_ENOTDIR", ENOTDIR, CONST_PERSISTENT); #endif #if defined(ETXTBSY) REGISTER_LONG_CONSTANT("PCNTL_ETXTBSY", ETXTBSY, CONST_PERSISTENT); #endif #if defined(ENOSPC) REGISTER_LONG_CONSTANT("PCNTL_ENOSPC", ENOSPC, CONST_PERSISTENT); #endif #if defined(EUSERS) REGISTER_LONG_CONSTANT("PCNTL_EUSERS", EUSERS, CONST_PERSISTENT); #endif #if defined(ECAPMODE) REGISTER_LONG_CONSTANT("PCNTL_ECAPMODE", ECAPMODE, CONST_PERSISTENT); #endif }
24,345
40.688356
99
h
php-src
php-src-master/ext/pcntl/php_pcntl.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_PCNTL_H #define PHP_PCNTL_H #if defined(WCONTINUED) && defined(WIFCONTINUED) #define HAVE_WCONTINUED 1 #endif extern zend_module_entry pcntl_module_entry; #define phpext_pcntl_ptr &pcntl_module_entry #include "php_version.h" #define PHP_PCNTL_VERSION PHP_VERSION PHP_MINIT_FUNCTION(pcntl); PHP_MSHUTDOWN_FUNCTION(pcntl); PHP_RINIT_FUNCTION(pcntl); PHP_RSHUTDOWN_FUNCTION(pcntl); PHP_MINFO_FUNCTION(pcntl); struct php_pcntl_pending_signal { struct php_pcntl_pending_signal *next; zend_long signo; #ifdef HAVE_STRUCT_SIGINFO_T siginfo_t siginfo; #endif }; ZEND_BEGIN_MODULE_GLOBALS(pcntl) HashTable php_signal_table; int processing_signal_queue; struct php_pcntl_pending_signal *head, *tail, *spares; int last_error; volatile char pending_signals; bool async_signals; unsigned num_signals; ZEND_END_MODULE_GLOBALS(pcntl) #if defined(ZTS) && defined(COMPILE_DL_PCNTL) ZEND_TSRMLS_CACHE_EXTERN() #endif ZEND_EXTERN_MODULE_GLOBALS(pcntl) #define PCNTL_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(pcntl, v) #endif /* PHP_PCNTL_H */
2,043
31.967742
75
h
php-src
php-src-master/ext/pcntl/php_signal.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ #include "TSRM.h" #include "php_signal.h" #include "Zend/zend.h" #include "Zend/zend_signal.h" /* php_signal using sigaction is derived from Advanced Programming * in the Unix Environment by W. Richard Stevens p 298. */ Sigfunc *php_signal4(int signo, Sigfunc *func, int restart, int mask_all) { struct sigaction act,oact; #ifdef HAVE_STRUCT_SIGINFO_T act.sa_sigaction = func; #else act.sa_handler = func; #endif if (mask_all) { sigfillset(&act.sa_mask); } else { sigemptyset(&act.sa_mask); } act.sa_flags = SA_ONSTACK; #ifdef HAVE_STRUCT_SIGINFO_T act.sa_flags |= SA_SIGINFO; #endif if (!restart) { #ifdef SA_INTERRUPT act.sa_flags |= SA_INTERRUPT; /* SunOS */ #endif } else { #ifdef SA_RESTART act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */ #endif } zend_sigaction(signo, &act, &oact); #ifdef HAVE_STRUCT_SIGINFO_T return oact.sa_sigaction; #else return oact.sa_handler; #endif } Sigfunc *php_signal(int signo, Sigfunc *func, int restart) { return php_signal4(signo, func, restart, 0); }
2,014
30.484375
75
c
php-src
php-src-master/ext/pcntl/php_signal.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ #include <signal.h> #ifndef PHP_SIGNAL_H #define PHP_SIGNAL_H #ifdef HAVE_STRUCT_SIGINFO_T typedef void Sigfunc(int, siginfo_t*, void*); #else typedef void Sigfunc(int); #endif Sigfunc *php_signal(int signo, Sigfunc *func, int restart); Sigfunc *php_signal4(int signo, Sigfunc *func, int restart, int mask_all); #endif
1,316
42.9
75
h
php-src
php-src-master/ext/pcre/php_pcre_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: 7f27807e45df9c9b5011aa20263c9789896acfbc */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_match, 0, 2, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, pattern, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, subject, IS_STRING, 0) ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, matches, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, offset, IS_LONG, 0, "0") ZEND_END_ARG_INFO() #define arginfo_preg_match_all arginfo_preg_match ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_replace, 0, 3, MAY_BE_STRING|MAY_BE_ARRAY|MAY_BE_NULL) ZEND_ARG_TYPE_MASK(0, pattern, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_MASK(0, replacement, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_MASK(0, subject, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, limit, IS_LONG, 0, "-1") ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, count, "null") ZEND_END_ARG_INFO() #define arginfo_preg_filter arginfo_preg_replace ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_replace_callback, 0, 3, MAY_BE_STRING|MAY_BE_ARRAY|MAY_BE_NULL) ZEND_ARG_TYPE_MASK(0, pattern, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0) ZEND_ARG_TYPE_MASK(0, subject, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, limit, IS_LONG, 0, "-1") ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, count, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_replace_callback_array, 0, 2, MAY_BE_STRING|MAY_BE_ARRAY|MAY_BE_NULL) ZEND_ARG_TYPE_INFO(0, pattern, IS_ARRAY, 0) ZEND_ARG_TYPE_MASK(0, subject, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, limit, IS_LONG, 0, "-1") ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, count, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_split, 0, 2, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, pattern, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, subject, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, limit, IS_LONG, 0, "-1") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_preg_quote, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, str, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, delimiter, IS_STRING, 1, "null") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_preg_grep, 0, 2, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, pattern, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, array, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_preg_last_error, 0, 0, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_preg_last_error_msg, 0, 0, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(preg_match); ZEND_FUNCTION(preg_match_all); ZEND_FUNCTION(preg_replace); ZEND_FUNCTION(preg_filter); ZEND_FUNCTION(preg_replace_callback); ZEND_FUNCTION(preg_replace_callback_array); ZEND_FUNCTION(preg_split); ZEND_FUNCTION(preg_quote); ZEND_FUNCTION(preg_grep); ZEND_FUNCTION(preg_last_error); ZEND_FUNCTION(preg_last_error_msg); static const zend_function_entry ext_functions[] = { ZEND_FE(preg_match, arginfo_preg_match) ZEND_FE(preg_match_all, arginfo_preg_match_all) ZEND_FE(preg_replace, arginfo_preg_replace) ZEND_FE(preg_filter, arginfo_preg_filter) ZEND_FE(preg_replace_callback, arginfo_preg_replace_callback) ZEND_FE(preg_replace_callback_array, arginfo_preg_replace_callback_array) ZEND_FE(preg_split, arginfo_preg_split) ZEND_SUPPORTS_COMPILE_TIME_EVAL_FE(preg_quote, arginfo_preg_quote) ZEND_FE(preg_grep, arginfo_preg_grep) ZEND_FE(preg_last_error, arginfo_preg_last_error) ZEND_FE(preg_last_error_msg, arginfo_preg_last_error_msg) ZEND_FE_END }; static void register_php_pcre_symbols(int module_number) { REGISTER_LONG_CONSTANT("PREG_PATTERN_ORDER", PREG_PATTERN_ORDER, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_SET_ORDER", PREG_SET_ORDER, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_OFFSET_CAPTURE", PREG_OFFSET_CAPTURE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_UNMATCHED_AS_NULL", PREG_UNMATCHED_AS_NULL, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_SPLIT_NO_EMPTY", PREG_SPLIT_NO_EMPTY, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_SPLIT_DELIM_CAPTURE", PREG_SPLIT_DELIM_CAPTURE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_SPLIT_OFFSET_CAPTURE", PREG_SPLIT_OFFSET_CAPTURE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_GREP_INVERT", PREG_GREP_INVERT, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_NO_ERROR", PHP_PCRE_NO_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_INTERNAL_ERROR", PHP_PCRE_INTERNAL_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_BACKTRACK_LIMIT_ERROR", PHP_PCRE_BACKTRACK_LIMIT_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_RECURSION_LIMIT_ERROR", PHP_PCRE_RECURSION_LIMIT_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_ERROR", PHP_PCRE_BAD_UTF8_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_OFFSET_ERROR", PHP_PCRE_BAD_UTF8_OFFSET_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PREG_JIT_STACKLIMIT_ERROR", PHP_PCRE_JIT_STACKLIMIT_ERROR, CONST_PERSISTENT); REGISTER_STRING_CONSTANT("PCRE_VERSION", php_pcre_version, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PCRE_VERSION_MAJOR", PCRE2_MAJOR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PCRE_VERSION_MINOR", PCRE2_MINOR, CONST_PERSISTENT); REGISTER_BOOL_CONSTANT("PCRE_JIT_SUPPORT", PHP_PCRE_JIT_SUPPORT, CONST_PERSISTENT); }
5,805
49.051724
122
h
php-src
php-src-master/ext/pcre/pcre2lib/config.h
#include <php_compat.h> #ifdef PHP_WIN32 # include <config.w32.h> #else # include <php_config.h> #endif #define SUPPORT_UNICODE 1 #define SUPPORT_PCRE2_8 1 #if defined(__GNUC__) && __GNUC__ >= 4 # ifdef __cplusplus # define PCRE2_EXP_DECL extern "C" __attribute__ ((visibility("default"))) # else # define PCRE2_EXP_DECL extern __attribute__ ((visibility("default"))) # endif # define PCRE2_EXP_DEFN __attribute__ ((visibility("default"))) #endif /* Define to any value for valgrind support to find invalid memory reads. */ #ifdef HAVE_PCRE_VALGRIND_SUPPORT #define SUPPORT_VALGRIND 1 #endif /* Define to any value to enable support for Just-In-Time compiling. */ #ifdef HAVE_PCRE_JIT_SUPPORT #define SUPPORT_JIT #endif /* This limits the amount of memory that pcre2_match() may use while matching a pattern. The value is in kilobytes. */ #ifndef HEAP_LIMIT #define HEAP_LIMIT 20000000 #endif /* The value of PARENS_NEST_LIMIT specifies the maximum depth of nested parentheses (of any kind) in a pattern. This limits the amount of system stack that is used while compiling a pattern. */ #ifndef PARENS_NEST_LIMIT #define PARENS_NEST_LIMIT 250 #endif /* The value of MATCH_LIMIT determines the default number of times the pcre2_match() function can record a backtrack position during a single matching attempt. There is a runtime interface for setting a different limit. The limit exists in order to catch runaway regular expressions that take for ever to determine that they do not match. The default is set very large so that it does not accidentally catch legitimate cases. */ #ifndef MATCH_LIMIT #define MATCH_LIMIT 10000000 #endif /* The above limit applies to all backtracks, whether or not they are nested. In some environments it is desirable to limit the nesting of backtracking (that is, the depth of tree that is searched) more strictly, in order to restrict the maximum amount of heap memory that is used. The value of MATCH_LIMIT_DEPTH provides this facility. To have any useful effect, it must be less than the value of MATCH_LIMIT. The default is to use the same value as MATCH_LIMIT. There is a runtime method for setting a different limit. */ #ifndef MATCH_LIMIT_DEPTH #define MATCH_LIMIT_DEPTH MATCH_LIMIT #endif /* This limit is parameterized just in case anybody ever wants to change it. Care must be taken if it is increased, because it guards against integer overflow caused by enormously large patterns. */ #ifndef MAX_NAME_COUNT #define MAX_NAME_COUNT 10000 #endif /* This limit is parameterized just in case anybody ever wants to change it. Care must be taken if it is increased, because it guards against integer overflow caused by enormously large patterns. */ #ifndef MAX_NAME_SIZE #define MAX_NAME_SIZE 32 #endif /* Defining NEVER_BACKSLASH_C locks out the use of \C in all patterns. */ /* #undef NEVER_BACKSLASH_C */ /* The value of NEWLINE_DEFAULT determines the default newline character sequence. PCRE2 client programs can override this by selecting other values at run time. The valid values are 1 (CR), 2 (LF), 3 (CRLF), 4 (ANY), 5 (ANYCRLF), and 6 (NUL). */ #ifndef NEWLINE_DEFAULT #define NEWLINE_DEFAULT 2 #endif /* The value of LINK_SIZE determines the number of bytes used to store links as offsets within the compiled regex. The default is 2, which allows for compiled patterns up to 64K long. This covers the vast majority of cases. However, PCRE2 can also be compiled to use 3 or 4 bytes instead. This allows for longer patterns in extreme cases. */ #ifndef LINK_SIZE #define LINK_SIZE 2 #endif
3,636
35.009901
78
h
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_chartables.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* This file was automatically written by the pcre2_dftables auxiliary program. It contains character tables that are used when no external tables are passed to PCRE2 by the application that calls it. The tables are used only for characters whose code values are less than 256. */ /* This set of tables was written in the C locale. */ /* The pcre2_ftables program (which is distributed with PCRE2) can be used to build alternative versions of this file. This is necessary if you are running in an EBCDIC environment, or if you want to default to a different encoding, for example ISO-8859-1. When pcre2_dftables is run, it creates these tables in the "C" locale by default. This happens automatically if PCRE2 is configured with --enable-rebuild-chartables. However, you can run pcre2_dftables manually with the -L option to build tables using the LC_ALL locale. */ /* The following #include is present because without it gcc 4.x may remove the array definition from the final binary if PCRE2 is built into a static library and dead code stripping is activated. This leads to link errors. Pulling in the header ensures that the array gets flagged as "someone outside this compilation unit might reference this" and so it will always be supplied to the linker. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" const uint8_t PRIV(default_tables)[] = { /* This table is a lower casing table. */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119, 120,121,122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119, 120,121,122,123,124,125,126,127, 128,129,130,131,132,133,134,135, 136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151, 152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167, 168,169,170,171,172,173,174,175, 176,177,178,179,180,181,182,183, 184,185,186,187,188,189,190,191, 192,193,194,195,196,197,198,199, 200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231, 232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255, /* This table is a case flipping table. */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111, 112,113,114,115,116,117,118,119, 120,121,122, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127, 128,129,130,131,132,133,134,135, 136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151, 152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167, 168,169,170,171,172,173,174,175, 176,177,178,179,180,181,182,183, 184,185,186,187,188,189,190,191, 192,193,194,195,196,197,198,199, 200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231, 232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255, /* This table contains bit maps for various character classes. Each map is 32 bytes long and the bits run from the least significant end of each byte. The classes that have their own maps are: space, xdigit, digit, upper, lower, word, graph, print, punct, and cntrl. Other classes are built from combinations. */ 0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, /* space */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* xdigit */ 0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* digit */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* upper */ 0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* lower */ 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* word */ 0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, /* graph */ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, /* print */ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, /* punct */ 0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, /* cntrl */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* This table identifies various classes of character by individual bits: 0x01 white space character 0x02 letter 0x04 lower case letter 0x08 decimal digit 0x10 alphanumeric or '_' */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ 0x00,0x01,0x01,0x01,0x01,0x01,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ 0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, /* 0 - 7 */ 0x18,0x18,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* @ - G */ 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */ 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */ 0x12,0x12,0x12,0x00,0x00,0x00,0x00,0x10, /* X - _ */ 0x00,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* ` - g */ 0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* h - o */ 0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* p - w */ 0x16,0x16,0x16,0x00,0x00,0x00,0x00,0x00, /* x -127 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ /* End of pcre2_chartables.c */
8,105
38.931034
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_config.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2020 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* Save the configured link size, which is in bytes. In 16-bit and 32-bit modes its value gets changed by pcre2_intmodedep.h (included by pcre2_internal.h) to be in code units. */ static int configured_link_size = LINK_SIZE; #include "pcre2_internal.h" /* These macros are the standard way of turning unquoted text into C strings. They allow macros like PCRE2_MAJOR to be defined without quotes, which is convenient for user programs that want to test their values. */ #define STRING(a) # a #define XSTRING(s) STRING(s) /************************************************* * Return info about what features are configured * *************************************************/ /* If where is NULL, the length of memory required is returned. Arguments: what what information is required where where to put the information Returns: 0 if a numerical value is returned >= 0 if a string value PCRE2_ERROR_BADOPTION if "where" not recognized or JIT target requested when JIT not enabled */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_config(uint32_t what, void *where) { if (where == NULL) /* Requests a length */ { switch(what) { default: return PCRE2_ERROR_BADOPTION; case PCRE2_CONFIG_BSR: case PCRE2_CONFIG_COMPILED_WIDTHS: case PCRE2_CONFIG_DEPTHLIMIT: case PCRE2_CONFIG_HEAPLIMIT: case PCRE2_CONFIG_JIT: case PCRE2_CONFIG_LINKSIZE: case PCRE2_CONFIG_MATCHLIMIT: case PCRE2_CONFIG_NEVER_BACKSLASH_C: case PCRE2_CONFIG_NEWLINE: case PCRE2_CONFIG_PARENSLIMIT: case PCRE2_CONFIG_STACKRECURSE: /* Obsolete */ case PCRE2_CONFIG_TABLES_LENGTH: case PCRE2_CONFIG_UNICODE: return sizeof(uint32_t); /* These are handled below */ case PCRE2_CONFIG_JITTARGET: case PCRE2_CONFIG_UNICODE_VERSION: case PCRE2_CONFIG_VERSION: break; } } switch (what) { default: return PCRE2_ERROR_BADOPTION; case PCRE2_CONFIG_BSR: #ifdef BSR_ANYCRLF *((uint32_t *)where) = PCRE2_BSR_ANYCRLF; #else *((uint32_t *)where) = PCRE2_BSR_UNICODE; #endif break; case PCRE2_CONFIG_COMPILED_WIDTHS: *((uint32_t *)where) = 0 #ifdef SUPPORT_PCRE2_8 + 1 #endif #ifdef SUPPORT_PCRE2_16 + 2 #endif #ifdef SUPPORT_PCRE2_32 + 4 #endif ; break; case PCRE2_CONFIG_DEPTHLIMIT: *((uint32_t *)where) = MATCH_LIMIT_DEPTH; break; case PCRE2_CONFIG_HEAPLIMIT: *((uint32_t *)where) = HEAP_LIMIT; break; case PCRE2_CONFIG_JIT: #ifdef SUPPORT_JIT *((uint32_t *)where) = 1; #else *((uint32_t *)where) = 0; #endif break; case PCRE2_CONFIG_JITTARGET: #ifdef SUPPORT_JIT { const char *v = PRIV(jit_get_target)(); return (int)(1 + ((where == NULL)? strlen(v) : PRIV(strcpy_c8)((PCRE2_UCHAR *)where, v))); } #else return PCRE2_ERROR_BADOPTION; #endif case PCRE2_CONFIG_LINKSIZE: *((uint32_t *)where) = (uint32_t)configured_link_size; break; case PCRE2_CONFIG_MATCHLIMIT: *((uint32_t *)where) = MATCH_LIMIT; break; case PCRE2_CONFIG_NEWLINE: *((uint32_t *)where) = NEWLINE_DEFAULT; break; case PCRE2_CONFIG_NEVER_BACKSLASH_C: #ifdef NEVER_BACKSLASH_C *((uint32_t *)where) = 1; #else *((uint32_t *)where) = 0; #endif break; case PCRE2_CONFIG_PARENSLIMIT: *((uint32_t *)where) = PARENS_NEST_LIMIT; break; /* This is now obsolete. The stack is no longer used via recursion for handling backtracking in pcre2_match(). */ case PCRE2_CONFIG_STACKRECURSE: *((uint32_t *)where) = 0; break; case PCRE2_CONFIG_TABLES_LENGTH: *((uint32_t *)where) = TABLES_LENGTH; break; case PCRE2_CONFIG_UNICODE_VERSION: { #if defined SUPPORT_UNICODE const char *v = PRIV(unicode_version); #else const char *v = "Unicode not supported"; #endif return (int)(1 + ((where == NULL)? strlen(v) : PRIV(strcpy_c8)((PCRE2_UCHAR *)where, v))); } break; case PCRE2_CONFIG_UNICODE: #if defined SUPPORT_UNICODE *((uint32_t *)where) = 1; #else *((uint32_t *)where) = 0; #endif break; /* The hackery in setting "v" below is to cope with the case when PCRE2_PRERELEASE is set to an empty string (which it is for real releases). If the second alternative is used in this case, it does not leave a space before the date. On the other hand, if all four macros are put into a single XSTRING when PCRE2_PRERELEASE is not empty, an unwanted space is inserted. There are problems using an "obvious" approach like this: XSTRING(PCRE2_MAJOR) "." XSTRING(PCRE_MINOR) XSTRING(PCRE2_PRERELEASE) " " XSTRING(PCRE_DATE) because, when PCRE2_PRERELEASE is empty, this leads to an attempted expansion of STRING(). The C standard states: "If (before argument substitution) any argument consists of no preprocessing tokens, the behavior is undefined." It turns out the gcc treats this case as a single empty string - which is what we really want - but Visual C grumbles about the lack of an argument for the macro. Unfortunately, both are within their rights. As there seems to be no way to test for a macro's value being empty at compile time, we have to resort to a runtime test. */ case PCRE2_CONFIG_VERSION: { const char *v = (XSTRING(Z PCRE2_PRERELEASE)[1] == 0)? XSTRING(PCRE2_MAJOR.PCRE2_MINOR PCRE2_DATE) : XSTRING(PCRE2_MAJOR.PCRE2_MINOR) XSTRING(PCRE2_PRERELEASE PCRE2_DATE); return (int)(1 + ((where == NULL)? strlen(v) : PRIV(strcpy_c8)((PCRE2_UCHAR *)where, v))); } } return 0; } /* End of pcre2_config.c */
7,740
29.596838
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_context.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2018 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Default malloc/free functions * *************************************************/ /* Ignore the "user data" argument in each case. */ static void *default_malloc(size_t size, void *data) { (void)data; return malloc(size); } static void default_free(void *block, void *data) { (void)data; free(block); } /************************************************* * Get a block and save memory control * *************************************************/ /* This internal function is called to get a block of memory in which the memory control data is to be stored at the start for future use. Arguments: size amount of memory required memctl pointer to a memctl block or NULL Returns: pointer to memory or NULL on failure */ extern void * PRIV(memctl_malloc)(size_t size, pcre2_memctl *memctl) { pcre2_memctl *newmemctl; void *yield = (memctl == NULL)? malloc(size) : memctl->malloc(size, memctl->memory_data); if (yield == NULL) return NULL; newmemctl = (pcre2_memctl *)yield; if (memctl == NULL) { newmemctl->malloc = default_malloc; newmemctl->free = default_free; newmemctl->memory_data = NULL; } else *newmemctl = *memctl; return yield; } /************************************************* * Create and initialize contexts * *************************************************/ /* Initializing for compile and match contexts is done in separate, private functions so that these can be called from functions such as pcre2_compile() when an external context is not supplied. The initializing functions have an option to set up default memory management. */ PCRE2_EXP_DEFN pcre2_general_context * PCRE2_CALL_CONVENTION pcre2_general_context_create(void *(*private_malloc)(size_t, void *), void (*private_free)(void *, void *), void *memory_data) { pcre2_general_context *gcontext; if (private_malloc == NULL) private_malloc = default_malloc; if (private_free == NULL) private_free = default_free; gcontext = private_malloc(sizeof(pcre2_real_general_context), memory_data); if (gcontext == NULL) return NULL; gcontext->memctl.malloc = private_malloc; gcontext->memctl.free = private_free; gcontext->memctl.memory_data = memory_data; return gcontext; } /* A default compile context is set up to save having to initialize at run time when no context is supplied to the compile function. */ const pcre2_compile_context PRIV(default_compile_context) = { { default_malloc, default_free, NULL }, /* Default memory handling */ NULL, /* Stack guard */ NULL, /* Stack guard data */ PRIV(default_tables), /* Character tables */ PCRE2_UNSET, /* Max pattern length */ BSR_DEFAULT, /* Backslash R default */ NEWLINE_DEFAULT, /* Newline convention */ PARENS_NEST_LIMIT, /* As it says */ 0 }; /* Extra options */ /* The create function copies the default into the new memory, but must override the default memory handling functions if a gcontext was provided. */ PCRE2_EXP_DEFN pcre2_compile_context * PCRE2_CALL_CONVENTION pcre2_compile_context_create(pcre2_general_context *gcontext) { pcre2_compile_context *ccontext = PRIV(memctl_malloc)( sizeof(pcre2_real_compile_context), (pcre2_memctl *)gcontext); if (ccontext == NULL) return NULL; *ccontext = PRIV(default_compile_context); if (gcontext != NULL) *((pcre2_memctl *)ccontext) = *((pcre2_memctl *)gcontext); return ccontext; } /* A default match context is set up to save having to initialize at run time when no context is supplied to a match function. */ const pcre2_match_context PRIV(default_match_context) = { { default_malloc, default_free, NULL }, #ifdef SUPPORT_JIT NULL, /* JIT callback */ NULL, /* JIT callback data */ #endif NULL, /* Callout function */ NULL, /* Callout data */ NULL, /* Substitute callout function */ NULL, /* Substitute callout data */ PCRE2_UNSET, /* Offset limit */ HEAP_LIMIT, MATCH_LIMIT, MATCH_LIMIT_DEPTH }; /* The create function copies the default into the new memory, but must override the default memory handling functions if a gcontext was provided. */ PCRE2_EXP_DEFN pcre2_match_context * PCRE2_CALL_CONVENTION pcre2_match_context_create(pcre2_general_context *gcontext) { pcre2_match_context *mcontext = PRIV(memctl_malloc)( sizeof(pcre2_real_match_context), (pcre2_memctl *)gcontext); if (mcontext == NULL) return NULL; *mcontext = PRIV(default_match_context); if (gcontext != NULL) *((pcre2_memctl *)mcontext) = *((pcre2_memctl *)gcontext); return mcontext; } /* A default convert context is set up to save having to initialize at run time when no context is supplied to the convert function. */ const pcre2_convert_context PRIV(default_convert_context) = { { default_malloc, default_free, NULL }, /* Default memory handling */ #ifdef _WIN32 CHAR_BACKSLASH, /* Default path separator */ CHAR_GRAVE_ACCENT /* Default escape character */ #else /* Not Windows */ CHAR_SLASH, /* Default path separator */ CHAR_BACKSLASH /* Default escape character */ #endif }; /* The create function copies the default into the new memory, but must override the default memory handling functions if a gcontext was provided. */ PCRE2_EXP_DEFN pcre2_convert_context * PCRE2_CALL_CONVENTION pcre2_convert_context_create(pcre2_general_context *gcontext) { pcre2_convert_context *ccontext = PRIV(memctl_malloc)( sizeof(pcre2_real_convert_context), (pcre2_memctl *)gcontext); if (ccontext == NULL) return NULL; *ccontext = PRIV(default_convert_context); if (gcontext != NULL) *((pcre2_memctl *)ccontext) = *((pcre2_memctl *)gcontext); return ccontext; } /************************************************* * Context copy functions * *************************************************/ PCRE2_EXP_DEFN pcre2_general_context * PCRE2_CALL_CONVENTION pcre2_general_context_copy(pcre2_general_context *gcontext) { pcre2_general_context *new = gcontext->memctl.malloc(sizeof(pcre2_real_general_context), gcontext->memctl.memory_data); if (new == NULL) return NULL; memcpy(new, gcontext, sizeof(pcre2_real_general_context)); return new; } PCRE2_EXP_DEFN pcre2_compile_context * PCRE2_CALL_CONVENTION pcre2_compile_context_copy(pcre2_compile_context *ccontext) { pcre2_compile_context *new = ccontext->memctl.malloc(sizeof(pcre2_real_compile_context), ccontext->memctl.memory_data); if (new == NULL) return NULL; memcpy(new, ccontext, sizeof(pcre2_real_compile_context)); return new; } PCRE2_EXP_DEFN pcre2_match_context * PCRE2_CALL_CONVENTION pcre2_match_context_copy(pcre2_match_context *mcontext) { pcre2_match_context *new = mcontext->memctl.malloc(sizeof(pcre2_real_match_context), mcontext->memctl.memory_data); if (new == NULL) return NULL; memcpy(new, mcontext, sizeof(pcre2_real_match_context)); return new; } PCRE2_EXP_DEFN pcre2_convert_context * PCRE2_CALL_CONVENTION pcre2_convert_context_copy(pcre2_convert_context *ccontext) { pcre2_convert_context *new = ccontext->memctl.malloc(sizeof(pcre2_real_convert_context), ccontext->memctl.memory_data); if (new == NULL) return NULL; memcpy(new, ccontext, sizeof(pcre2_real_convert_context)); return new; } /************************************************* * Context free functions * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_general_context_free(pcre2_general_context *gcontext) { if (gcontext != NULL) gcontext->memctl.free(gcontext, gcontext->memctl.memory_data); } PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_compile_context_free(pcre2_compile_context *ccontext) { if (ccontext != NULL) ccontext->memctl.free(ccontext, ccontext->memctl.memory_data); } PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_match_context_free(pcre2_match_context *mcontext) { if (mcontext != NULL) mcontext->memctl.free(mcontext, mcontext->memctl.memory_data); } PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_convert_context_free(pcre2_convert_context *ccontext) { if (ccontext != NULL) ccontext->memctl.free(ccontext, ccontext->memctl.memory_data); } /************************************************* * Set values in contexts * *************************************************/ /* All these functions return 0 for success or PCRE2_ERROR_BADDATA if invalid data is given. Only some of the functions are able to test the validity of the data. */ /* ------------ Compile context ------------ */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_character_tables(pcre2_compile_context *ccontext, const uint8_t *tables) { ccontext->tables = tables; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_bsr(pcre2_compile_context *ccontext, uint32_t value) { switch(value) { case PCRE2_BSR_ANYCRLF: case PCRE2_BSR_UNICODE: ccontext->bsr_convention = value; return 0; default: return PCRE2_ERROR_BADDATA; } } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_max_pattern_length(pcre2_compile_context *ccontext, PCRE2_SIZE length) { ccontext->max_pattern_length = length; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_newline(pcre2_compile_context *ccontext, uint32_t newline) { switch(newline) { case PCRE2_NEWLINE_CR: case PCRE2_NEWLINE_LF: case PCRE2_NEWLINE_CRLF: case PCRE2_NEWLINE_ANY: case PCRE2_NEWLINE_ANYCRLF: case PCRE2_NEWLINE_NUL: ccontext->newline_convention = newline; return 0; default: return PCRE2_ERROR_BADDATA; } } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_parens_nest_limit(pcre2_compile_context *ccontext, uint32_t limit) { ccontext->parens_nest_limit = limit; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_compile_extra_options(pcre2_compile_context *ccontext, uint32_t options) { ccontext->extra_options = options; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_compile_recursion_guard(pcre2_compile_context *ccontext, int (*guard)(uint32_t, void *), void *user_data) { ccontext->stack_guard = guard; ccontext->stack_guard_data = user_data; return 0; } /* ------------ Match context ------------ */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_callout(pcre2_match_context *mcontext, int (*callout)(pcre2_callout_block *, void *), void *callout_data) { mcontext->callout = callout; mcontext->callout_data = callout_data; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_substitute_callout(pcre2_match_context *mcontext, int (*substitute_callout)(pcre2_substitute_callout_block *, void *), void *substitute_callout_data) { mcontext->substitute_callout = substitute_callout; mcontext->substitute_callout_data = substitute_callout_data; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_heap_limit(pcre2_match_context *mcontext, uint32_t limit) { mcontext->heap_limit = limit; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_match_limit(pcre2_match_context *mcontext, uint32_t limit) { mcontext->match_limit = limit; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_depth_limit(pcre2_match_context *mcontext, uint32_t limit) { mcontext->depth_limit = limit; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_offset_limit(pcre2_match_context *mcontext, PCRE2_SIZE limit) { mcontext->offset_limit = limit; return 0; } /* This function became obsolete at release 10.30. It is kept as a synonym for backwards compatibility. */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_recursion_limit(pcre2_match_context *mcontext, uint32_t limit) { return pcre2_set_depth_limit(mcontext, limit); } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_recursion_memory_management(pcre2_match_context *mcontext, void *(*mymalloc)(size_t, void *), void (*myfree)(void *, void *), void *mydata) { (void)mcontext; (void)mymalloc; (void)myfree; (void)mydata; return 0; } /* ------------ Convert context ------------ */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_glob_separator(pcre2_convert_context *ccontext, uint32_t separator) { if (separator != CHAR_SLASH && separator != CHAR_BACKSLASH && separator != CHAR_DOT) return PCRE2_ERROR_BADDATA; ccontext->glob_separator = separator; return 0; } PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_set_glob_escape(pcre2_convert_context *ccontext, uint32_t escape) { if (escape > 255 || (escape != 0 && !ispunct(escape))) return PCRE2_ERROR_BADDATA; ccontext->glob_escape = escape; return 0; } /* End of pcre2_context.c */
15,120
29.92229
82
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_error.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2021 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" #define STRING(a) # a #define XSTRING(s) STRING(s) /* The texts of compile-time error messages. Compile-time error numbers start at COMPILE_ERROR_BASE (100). This used to be a table of strings, but in order to reduce the number of relocations needed when a shared library is loaded dynamically, it is now one long string. We cannot use a table of offsets, because the lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, pcre2_get_error_message() counts through to the one it wants - this isn't a performance issue because these strings are used only when there is an error. Each substring ends with \0 to insert a null character. This includes the final substring, so that the whole string ends with \0\0, which can be detected when counting through. */ static const unsigned char compile_error_texts[] = "no error\0" "\\ at end of pattern\0" "\\c at end of pattern\0" "unrecognized character follows \\\0" "numbers out of order in {} quantifier\0" /* 5 */ "number too big in {} quantifier\0" "missing terminating ] for character class\0" "escape sequence is invalid in character class\0" "range out of order in character class\0" "quantifier does not follow a repeatable item\0" /* 10 */ "internal error: unexpected repeat\0" "unrecognized character after (? or (?-\0" "POSIX named classes are supported only within a class\0" "POSIX collating elements are not supported\0" "missing closing parenthesis\0" /* 15 */ "reference to non-existent subpattern\0" "pattern passed as NULL\0" "unrecognised compile-time option bit(s)\0" "missing ) after (?# comment\0" "parentheses are too deeply nested\0" /* 20 */ "regular expression is too large\0" "failed to allocate heap memory\0" "unmatched closing parenthesis\0" "internal error: code overflow\0" "missing closing parenthesis for condition\0" /* 25 */ "lookbehind assertion is not fixed length\0" "a relative value of zero is not allowed\0" "conditional subpattern contains more than two branches\0" "assertion expected after (?( or (?(?C)\0" "digit expected after (?+ or (?-\0" /* 30 */ "unknown POSIX class name\0" "internal error in pcre2_study(): should not occur\0" "this version of PCRE2 does not have Unicode support\0" "parentheses are too deeply nested (stack check)\0" "character code point value in \\x{} or \\o{} is too large\0" /* 35 */ "lookbehind is too complicated\0" "\\C is not allowed in a lookbehind assertion in UTF-" XSTRING(PCRE2_CODE_UNIT_WIDTH) " mode\0" "PCRE2 does not support \\F, \\L, \\l, \\N{name}, \\U, or \\u\0" "number after (?C is greater than 255\0" "closing parenthesis for (?C expected\0" /* 40 */ "invalid escape sequence in (*VERB) name\0" "unrecognized character after (?P\0" "syntax error in subpattern name (missing terminator?)\0" "two named subpatterns have the same name (PCRE2_DUPNAMES not set)\0" "subpattern name must start with a non-digit\0" /* 45 */ "this version of PCRE2 does not have support for \\P, \\p, or \\X\0" "malformed \\P or \\p sequence\0" "unknown property after \\P or \\p\0" "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " code units)\0" "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0" /* 50 */ "invalid range in character class\0" "octal value is greater than \\377 in 8-bit non-UTF-8 mode\0" "internal error: overran compiling workspace\0" "internal error: previously-checked referenced subpattern not found\0" "DEFINE subpattern contains more than one branch\0" /* 55 */ "missing opening brace after \\o\0" "internal error: unknown newline setting\0" "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0" "(?R (recursive pattern call) must be followed by a closing parenthesis\0" /* "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0" */ "obsolete error (should not occur)\0" /* Was the above */ /* 60 */ "(*VERB) not recognized or malformed\0" "subpattern number is too big\0" "subpattern name expected\0" "internal error: parsed pattern overflow\0" "non-octal character in \\o{} (closing brace missing?)\0" /* 65 */ "different names for subpatterns of the same number are not allowed\0" "(*MARK) must have an argument\0" "non-hex character in \\x{} (closing brace missing?)\0" #ifndef EBCDIC "\\c must be followed by a printable ASCII character\0" #else "\\c must be followed by a letter or one of [\\]^_?\0" #endif "\\k is not followed by a braced, angle-bracketed, or quoted name\0" /* 70 */ "internal error: unknown meta code in check_lookbehinds()\0" "\\N is not supported in a class\0" "callout string is too long\0" "disallowed Unicode code point (>= 0xd800 && <= 0xdfff)\0" "using UTF is disabled by the application\0" /* 75 */ "using UCP is disabled by the application\0" "name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)\0" "character code point value in \\u.... sequence is too large\0" "digits missing in \\x{} or \\o{} or \\N{U+}\0" "syntax error or number too big in (?(VERSION condition\0" /* 80 */ "internal error: unknown opcode in auto_possessify()\0" "missing terminating delimiter for callout with string argument\0" "unrecognized string delimiter follows (?C\0" "using \\C is disabled by the application\0" "(?| and/or (?J: or (?x: parentheses are too deeply nested\0" /* 85 */ "using \\C is disabled in this PCRE2 library\0" "regular expression is too complicated\0" "lookbehind assertion is too long\0" "pattern string is longer than the limit set by the application\0" "internal error: unknown code in parsed pattern\0" /* 90 */ "internal error: bad code value in parsed_skip()\0" "PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES is not allowed in UTF-16 mode\0" "invalid option bits with PCRE2_LITERAL\0" "\\N{U+dddd} is supported only in Unicode (UTF) mode\0" "invalid hyphen in option setting\0" /* 95 */ "(*alpha_assertion) not recognized\0" "script runs require Unicode support, which this version of PCRE2 does not have\0" "too many capturing groups (maximum 65535)\0" "atomic assertion expected after (?( or (?(?C)\0" "\\K is not allowed in lookarounds (but see PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK)\0" ; /* Match-time and UTF error texts are in the same format. */ static const unsigned char match_error_texts[] = "no error\0" "no match\0" "partial match\0" "UTF-8 error: 1 byte missing at end\0" "UTF-8 error: 2 bytes missing at end\0" /* 5 */ "UTF-8 error: 3 bytes missing at end\0" "UTF-8 error: 4 bytes missing at end\0" "UTF-8 error: 5 bytes missing at end\0" "UTF-8 error: byte 2 top bits not 0x80\0" "UTF-8 error: byte 3 top bits not 0x80\0" /* 10 */ "UTF-8 error: byte 4 top bits not 0x80\0" "UTF-8 error: byte 5 top bits not 0x80\0" "UTF-8 error: byte 6 top bits not 0x80\0" "UTF-8 error: 5-byte character is not allowed (RFC 3629)\0" "UTF-8 error: 6-byte character is not allowed (RFC 3629)\0" /* 15 */ "UTF-8 error: code points greater than 0x10ffff are not defined\0" "UTF-8 error: code points 0xd800-0xdfff are not defined\0" "UTF-8 error: overlong 2-byte sequence\0" "UTF-8 error: overlong 3-byte sequence\0" "UTF-8 error: overlong 4-byte sequence\0" /* 20 */ "UTF-8 error: overlong 5-byte sequence\0" "UTF-8 error: overlong 6-byte sequence\0" "UTF-8 error: isolated byte with 0x80 bit set\0" "UTF-8 error: illegal byte (0xfe or 0xff)\0" "UTF-16 error: missing low surrogate at end\0" /* 25 */ "UTF-16 error: invalid low surrogate\0" "UTF-16 error: isolated low surrogate\0" "UTF-32 error: code points 0xd800-0xdfff are not defined\0" "UTF-32 error: code points greater than 0x10ffff are not defined\0" "bad data value\0" /* 30 */ "patterns do not all use the same character tables\0" "magic number missing\0" "pattern compiled in wrong mode: 8/16/32-bit error\0" "bad offset value\0" "bad option value\0" /* 35 */ "invalid replacement string\0" "bad offset into UTF string\0" "callout error code\0" /* Never returned by PCRE2 itself */ "invalid data in workspace for DFA restart\0" "too much recursion for DFA matching\0" /* 40 */ "backreference condition or recursion test is not supported for DFA matching\0" "function is not supported for DFA matching\0" "pattern contains an item that is not supported for DFA matching\0" "workspace size exceeded in DFA matching\0" "internal error - pattern overwritten?\0" /* 45 */ "bad JIT option\0" "JIT stack limit reached\0" "match limit exceeded\0" "no more memory\0" "unknown substring\0" /* 50 */ "non-unique substring name\0" "NULL argument passed with non-zero length\0" "nested recursion at the same subject position\0" "matching depth limit exceeded\0" "requested value is not available\0" /* 55 */ "requested value is not set\0" "offset limit set without PCRE2_USE_OFFSET_LIMIT\0" "bad escape sequence in replacement string\0" "expected closing curly bracket in replacement string\0" "bad substitution in replacement string\0" /* 60 */ "match with end before start or start moved backwards is not supported\0" "too many replacements (more than INT_MAX)\0" "bad serialized data\0" "heap limit exceeded\0" "invalid syntax\0" /* 65 */ "internal error - duplicate substitution match\0" "PCRE2_MATCH_INVALID_UTF is not supported for DFA matching\0" ; /************************************************* * Return error message * *************************************************/ /* This function copies an error message into a buffer whose units are of an appropriate width. Error numbers are positive for compile-time errors, and negative for match-time errors (except for UTF errors), but the numbers are all distinct. Arguments: enumber error number buffer where to put the message (zero terminated) size size of the buffer in code units Returns: length of message if all is well negative on error */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_get_error_message(int enumber, PCRE2_UCHAR *buffer, PCRE2_SIZE size) { const unsigned char *message; PCRE2_SIZE i; int n; if (size == 0) return PCRE2_ERROR_NOMEMORY; if (enumber >= COMPILE_ERROR_BASE) /* Compile error */ { message = compile_error_texts; n = enumber - COMPILE_ERROR_BASE; } else if (enumber < 0) /* Match or UTF error */ { message = match_error_texts; n = -enumber; } else /* Invalid error number */ { message = (unsigned char *)"\0"; /* Empty message list */ n = 1; } for (; n > 0; n--) { while (*message++ != CHAR_NUL) {}; if (*message == CHAR_NUL) return PCRE2_ERROR_BADDATA; } for (i = 0; *message != 0; i++) { if (i >= size - 1) { buffer[i] = 0; /* Terminate partial message */ return PCRE2_ERROR_NOMEMORY; } buffer[i] = *message++; } buffer[i] = 0; return (int)i; } /* End of pcre2_error.c */
13,322
37.95614
98
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_extuni.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2021 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains an internal function that is used to match a Unicode extended grapheme sequence. It is used by both pcre2_match() and pcre2_def_match(). However, it is called only when Unicode support is being compiled. Nevertheless, we provide a dummy function when there is no Unicode support, because some compilers do not like functionless source files. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /* Dummy function */ #ifndef SUPPORT_UNICODE PCRE2_SPTR PRIV(extuni)(uint32_t c, PCRE2_SPTR eptr, PCRE2_SPTR start_subject, PCRE2_SPTR end_subject, BOOL utf, int *xcount) { (void)c; (void)eptr; (void)start_subject; (void)end_subject; (void)utf; (void)xcount; return NULL; } #else /************************************************* * Match an extended grapheme sequence * *************************************************/ /* Arguments: c the first character eptr pointer to next character start_subject pointer to start of subject end_subject pointer to end of subject utf TRUE if in UTF mode xcount pointer to count of additional characters, or NULL if count not needed Returns: pointer after the end of the sequence */ PCRE2_SPTR PRIV(extuni)(uint32_t c, PCRE2_SPTR eptr, PCRE2_SPTR start_subject, PCRE2_SPTR end_subject, BOOL utf, int *xcount) { int lgb = UCD_GRAPHBREAK(c); while (eptr < end_subject) { int rgb; int len = 1; if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } rgb = UCD_GRAPHBREAK(c); if ((PRIV(ucp_gbtable)[lgb] & (1u << rgb)) == 0) break; /* Not breaking between Regional Indicators is allowed only if there are an even number of preceding RIs. */ if (lgb == ucp_gbRegional_Indicator && rgb == ucp_gbRegional_Indicator) { int ricount = 0; PCRE2_SPTR bptr = eptr - 1; if (utf) BACKCHAR(bptr); /* bptr is pointing to the left-hand character */ while (bptr > start_subject) { bptr--; if (utf) { BACKCHAR(bptr); GETCHAR(c, bptr); } else c = *bptr; if (UCD_GRAPHBREAK(c) != ucp_gbRegional_Indicator) break; ricount++; } if ((ricount & 1) != 0) break; /* Grapheme break required */ } /* If Extend or ZWJ follows Extended_Pictographic, do not update lgb; this allows any number of them before a following Extended_Pictographic. */ if ((rgb != ucp_gbExtend && rgb != ucp_gbZWJ) || lgb != ucp_gbExtended_Pictographic) lgb = rgb; eptr += len; if (xcount != NULL) *xcount += 1; } return eptr; } #endif /* SUPPORT_UNICODE */ /* End of pcre2_extuni.c */
4,819
31.348993
77
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_find_bracket.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2018 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains a single function that scans through a compiled pattern until it finds a capturing bracket with the given number, or, if the number is negative, an instance of OP_REVERSE for a lookbehind. The function is called from pcre2_compile.c and also from pcre2_study.c when finding the minimum matching length. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Scan compiled regex for specific bracket * *************************************************/ /* Arguments: code points to start of expression utf TRUE in UTF mode number the required bracket number or negative to find a lookbehind Returns: pointer to the opcode for the bracket, or NULL if not found */ PCRE2_SPTR PRIV(find_bracket)(PCRE2_SPTR code, BOOL utf, int number) { for (;;) { PCRE2_UCHAR c = *code; if (c == OP_END) return NULL; /* XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. CALLOUT_STR is used for callouts with string arguments. In both cases the length in the table is zero; the actual length is stored in the compiled code. */ if (c == OP_XCLASS) code += GET(code, 1); else if (c == OP_CALLOUT_STR) code += GET(code, 1 + 2*LINK_SIZE); /* Handle lookbehind */ else if (c == OP_REVERSE) { if (number < 0) return (PCRE2_UCHAR *)code; code += PRIV(OP_lengths)[c]; } /* Handle capturing bracket */ else if (c == OP_CBRA || c == OP_SCBRA || c == OP_CBRAPOS || c == OP_SCBRAPOS) { int n = (int)GET2(code, 1+LINK_SIZE); if (n == number) return (PCRE2_UCHAR *)code; code += PRIV(OP_lengths)[c]; } /* Otherwise, we can get the item's length from the table, except that for repeated character types, we have to test for \p and \P, which have an extra two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we must add in its length. */ else { switch(c) { case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; break; case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2; break; case OP_MARK: case OP_COMMIT_ARG: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: code += code[1]; break; } /* Add in the fixed length from the table */ code += PRIV(OP_lengths)[c]; /* In UTF-8 and UTF-16 modes, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to arrange to skip the extra bytes. */ #ifdef MAYBE_UTF_MULTI if (utf) switch(c) { case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: case OP_UPTO: case OP_UPTOI: case OP_NOTUPTO: case OP_NOTUPTOI: case OP_MINUPTO: case OP_MINUPTOI: case OP_NOTMINUPTO: case OP_NOTMINUPTOI: case OP_POSUPTO: case OP_POSUPTOI: case OP_NOTPOSUPTO: case OP_NOTPOSUPTOI: case OP_STAR: case OP_STARI: case OP_NOTSTAR: case OP_NOTSTARI: case OP_MINSTAR: case OP_MINSTARI: case OP_NOTMINSTAR: case OP_NOTMINSTARI: case OP_POSSTAR: case OP_POSSTARI: case OP_NOTPOSSTAR: case OP_NOTPOSSTARI: case OP_PLUS: case OP_PLUSI: case OP_NOTPLUS: case OP_NOTPLUSI: case OP_MINPLUS: case OP_MINPLUSI: case OP_NOTMINPLUS: case OP_NOTMINPLUSI: case OP_POSPLUS: case OP_POSPLUSI: case OP_NOTPOSPLUS: case OP_NOTPOSPLUSI: case OP_QUERY: case OP_QUERYI: case OP_NOTQUERY: case OP_NOTQUERYI: case OP_MINQUERY: case OP_MINQUERYI: case OP_NOTMINQUERY: case OP_NOTMINQUERYI: case OP_POSQUERY: case OP_POSQUERYI: case OP_NOTPOSQUERY: case OP_NOTPOSQUERYI: if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); break; } #else (void)(utf); /* Keep compiler happy by referencing function argument */ #endif /* MAYBE_UTF_MULTI */ } } } /* End of pcre2_find_bracket.c */
6,825
30.027273
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_jit_match.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2018 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifndef INCLUDED_FROM_PCRE2_JIT_COMPILE #error This file must be included from pcre2_jit_compile.c. #endif #ifdef SUPPORT_JIT static SLJIT_NOINLINE int jit_machine_stack_exec(jit_arguments *arguments, jit_function executable_func) { sljit_u8 local_space[MACHINE_STACK_SIZE]; struct sljit_stack local_stack; local_stack.min_start = local_space; local_stack.start = local_space; local_stack.end = local_space + MACHINE_STACK_SIZE; local_stack.top = local_space + MACHINE_STACK_SIZE; arguments->stack = &local_stack; return executable_func(arguments); } #endif /************************************************* * Do a JIT pattern match * *************************************************/ /* This function runs a JIT pattern match. Arguments: code points to the compiled expression subject points to the subject string length length of subject string (may contain binary zeros) start_offset where to start in the subject string options option bits match_data points to a match_data block mcontext points to a match context Returns: > 0 => success; value is the number of ovector pairs filled = 0 => success, but ovector is not big enough -1 => failed to match (PCRE_ERROR_NOMATCH) < -1 => some kind of unexpected problem */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_jit_match(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE start_offset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *mcontext) { #ifndef SUPPORT_JIT (void)code; (void)subject; (void)length; (void)start_offset; (void)options; (void)match_data; (void)mcontext; return PCRE2_ERROR_JIT_BADOPTION; #else /* SUPPORT_JIT */ pcre2_real_code *re = (pcre2_real_code *)code; executable_functions *functions = (executable_functions *)re->executable_jit; pcre2_jit_stack *jit_stack; uint32_t oveccount = match_data->oveccount; uint32_t max_oveccount; union { void *executable_func; jit_function call_executable_func; } convert_executable_func; jit_arguments arguments; int rc; int index = 0; if ((options & PCRE2_PARTIAL_HARD) != 0) index = 2; else if ((options & PCRE2_PARTIAL_SOFT) != 0) index = 1; if (functions == NULL || functions->executable_funcs[index] == NULL) return PCRE2_ERROR_JIT_BADOPTION; /* Sanity checks should be handled by pcre2_match. */ arguments.str = subject + start_offset; arguments.begin = subject; arguments.end = subject + length; arguments.match_data = match_data; arguments.startchar_ptr = subject; arguments.mark_ptr = NULL; arguments.options = options; if (mcontext != NULL) { arguments.callout = mcontext->callout; arguments.callout_data = mcontext->callout_data; arguments.offset_limit = mcontext->offset_limit; arguments.limit_match = (mcontext->match_limit < re->limit_match)? mcontext->match_limit : re->limit_match; if (mcontext->jit_callback != NULL) jit_stack = mcontext->jit_callback(mcontext->jit_callback_data); else jit_stack = (pcre2_jit_stack *)mcontext->jit_callback_data; } else { arguments.callout = NULL; arguments.callout_data = NULL; arguments.offset_limit = PCRE2_UNSET; arguments.limit_match = (MATCH_LIMIT < re->limit_match)? MATCH_LIMIT : re->limit_match; jit_stack = NULL; } max_oveccount = functions->top_bracket; if (oveccount > max_oveccount) oveccount = max_oveccount; arguments.oveccount = oveccount << 1; convert_executable_func.executable_func = functions->executable_funcs[index]; if (jit_stack != NULL) { arguments.stack = (struct sljit_stack *)(jit_stack->stack); rc = convert_executable_func.call_executable_func(&arguments); } else rc = jit_machine_stack_exec(&arguments, convert_executable_func.call_executable_func); if (rc > (int)oveccount) rc = 0; match_data->code = re; match_data->subject = (rc >= 0 || rc == PCRE2_ERROR_PARTIAL)? subject : NULL; match_data->rc = rc; match_data->startchar = arguments.startchar_ptr - subject; match_data->leftchar = 0; match_data->rightchar = 0; match_data->mark = arguments.mark_ptr; match_data->matchedby = PCRE2_MATCHEDBY_JIT; return match_data->rc; #endif /* SUPPORT_JIT */ } /* End of pcre2_jit_match.c */
6,409
33.278075
104
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_jit_misc.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifndef INCLUDED_FROM_PCRE2_JIT_COMPILE #error This file must be included from pcre2_jit_compile.c. #endif /************************************************* * Free JIT read-only data * *************************************************/ void PRIV(jit_free_rodata)(void *current, void *allocator_data) { #ifndef SUPPORT_JIT (void)current; (void)allocator_data; #else /* SUPPORT_JIT */ void *next; SLJIT_UNUSED_ARG(allocator_data); while (current != NULL) { next = *(void**)current; SLJIT_FREE(current, allocator_data); current = next; } #endif /* SUPPORT_JIT */ } /************************************************* * Free JIT compiled code * *************************************************/ void PRIV(jit_free)(void *executable_jit, pcre2_memctl *memctl) { #ifndef SUPPORT_JIT (void)executable_jit; (void)memctl; #else /* SUPPORT_JIT */ executable_functions *functions = (executable_functions *)executable_jit; void *allocator_data = memctl; int i; for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) { if (functions->executable_funcs[i] != NULL) sljit_free_code(functions->executable_funcs[i], NULL); PRIV(jit_free_rodata)(functions->read_only_data_heads[i], allocator_data); } SLJIT_FREE(functions, allocator_data); #endif /* SUPPORT_JIT */ } /************************************************* * Free unused JIT memory * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_jit_free_unused_memory(pcre2_general_context *gcontext) { #ifndef SUPPORT_JIT (void)gcontext; /* Suppress warning */ #else /* SUPPORT_JIT */ SLJIT_UNUSED_ARG(gcontext); sljit_free_unused_memory_exec(); #endif /* SUPPORT_JIT */ } /************************************************* * Allocate a JIT stack * *************************************************/ PCRE2_EXP_DEFN pcre2_jit_stack * PCRE2_CALL_CONVENTION pcre2_jit_stack_create(size_t startsize, size_t maxsize, pcre2_general_context *gcontext) { #ifndef SUPPORT_JIT (void)gcontext; (void)startsize; (void)maxsize; return NULL; #else /* SUPPORT_JIT */ pcre2_jit_stack *jit_stack; if (startsize == 0 || maxsize == 0 || maxsize > SIZE_MAX - STACK_GROWTH_RATE) return NULL; if (startsize > maxsize) startsize = maxsize; startsize = (startsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); maxsize = (maxsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); jit_stack = PRIV(memctl_malloc)(sizeof(pcre2_real_jit_stack), (pcre2_memctl *)gcontext); if (jit_stack == NULL) return NULL; jit_stack->stack = sljit_allocate_stack(startsize, maxsize, &jit_stack->memctl); if (jit_stack->stack == NULL) { jit_stack->memctl.free(jit_stack, jit_stack->memctl.memory_data); return NULL; } return jit_stack; #endif } /************************************************* * Assign a JIT stack to a pattern * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_jit_stack_assign(pcre2_match_context *mcontext, pcre2_jit_callback callback, void *callback_data) { #ifndef SUPPORT_JIT (void)mcontext; (void)callback; (void)callback_data; #else /* SUPPORT_JIT */ if (mcontext == NULL) return; mcontext->jit_callback = callback; mcontext->jit_callback_data = callback_data; #endif /* SUPPORT_JIT */ } /************************************************* * Free a JIT stack * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_jit_stack_free(pcre2_jit_stack *jit_stack) { #ifndef SUPPORT_JIT (void)jit_stack; #else /* SUPPORT_JIT */ if (jit_stack != NULL) { sljit_free_stack((struct sljit_stack *)(jit_stack->stack), &jit_stack->memctl); jit_stack->memctl.free(jit_stack, jit_stack->memctl.memory_data); } #endif /* SUPPORT_JIT */ } /************************************************* * Get target CPU type * *************************************************/ const char* PRIV(jit_get_target)(void) { #ifndef SUPPORT_JIT return "JIT is not supported"; #else /* SUPPORT_JIT */ return sljit_get_platform_name(); #endif /* SUPPORT_JIT */ } /************************************************* * Get size of JIT code * *************************************************/ size_t PRIV(jit_get_size)(void *executable_jit) { #ifndef SUPPORT_JIT (void)executable_jit; return 0; #else /* SUPPORT_JIT */ sljit_uw *executable_sizes = ((executable_functions *)executable_jit)->executable_sizes; SLJIT_COMPILE_ASSERT(JIT_NUMBER_OF_COMPILE_MODES == 3, number_of_compile_modes_changed); return executable_sizes[0] + executable_sizes[1] + executable_sizes[2]; #endif } /* End of pcre2_jit_misc.c */
6,951
28.83691
88
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_jit_neon_inc.h
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel This module by Zoltan Herczeg and Sebastian Pop Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2019 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ # if defined(FFCS) # if defined(FF_UTF) # define FF_FUN ffcs_utf # else # define FF_FUN ffcs # endif # elif defined(FFCS_2) # if defined(FF_UTF) # define FF_FUN ffcs_2_utf # else # define FF_FUN ffcs_2 # endif # elif defined(FFCS_MASK) # if defined(FF_UTF) # define FF_FUN ffcs_mask_utf # else # define FF_FUN ffcs_mask # endif # elif defined(FFCPS_0) # if defined (FF_UTF) # define FF_FUN ffcps_0_utf # else # define FF_FUN ffcps_0 # endif # elif defined (FFCPS_1) # if defined (FF_UTF) # define FF_FUN ffcps_1_utf # else # define FF_FUN ffcps_1 # endif # elif defined (FFCPS_DEFAULT) # if defined (FF_UTF) # define FF_FUN ffcps_default_utf # else # define FF_FUN ffcps_default # endif # endif static sljit_u8* SLJIT_FUNC FF_FUN(sljit_u8 *str_end, sljit_u8 *str_ptr, sljit_uw offs1, sljit_uw offs2, sljit_uw chars) #undef FF_FUN { quad_word qw; int_char ic; SLJIT_UNUSED_ARG(offs1); SLJIT_UNUSED_ARG(offs2); ic.x = chars; #if defined(FFCS) sljit_u8 c1 = ic.c.c1; vect_t vc1 = VDUPQ(c1); #elif defined(FFCS_2) sljit_u8 c1 = ic.c.c1; vect_t vc1 = VDUPQ(c1); sljit_u8 c2 = ic.c.c2; vect_t vc2 = VDUPQ(c2); #elif defined(FFCS_MASK) sljit_u8 c1 = ic.c.c1; vect_t vc1 = VDUPQ(c1); sljit_u8 mask = ic.c.c2; vect_t vmask = VDUPQ(mask); #endif #if defined(FFCPS) compare_type compare1_type = compare_match1; compare_type compare2_type = compare_match1; vect_t cmp1a, cmp1b, cmp2a, cmp2b; const sljit_u32 diff = IN_UCHARS(offs1 - offs2); PCRE2_UCHAR char1a = ic.c.c1; PCRE2_UCHAR char2a = ic.c.c3; # ifdef FFCPS_CHAR1A2A cmp1a = VDUPQ(char1a); cmp2a = VDUPQ(char2a); cmp1b = VDUPQ(0); /* to avoid errors on older compilers -Werror=maybe-uninitialized */ cmp2b = VDUPQ(0); /* to avoid errors on older compilers -Werror=maybe-uninitialized */ # else PCRE2_UCHAR char1b = ic.c.c2; PCRE2_UCHAR char2b = ic.c.c4; if (char1a == char1b) { cmp1a = VDUPQ(char1a); cmp1b = VDUPQ(0); /* to avoid errors on older compilers -Werror=maybe-uninitialized */ } else { sljit_u32 bit1 = char1a ^ char1b; if (is_powerof2(bit1)) { compare1_type = compare_match1i; cmp1a = VDUPQ(char1a | bit1); cmp1b = VDUPQ(bit1); } else { compare1_type = compare_match2; cmp1a = VDUPQ(char1a); cmp1b = VDUPQ(char1b); } } if (char2a == char2b) { cmp2a = VDUPQ(char2a); cmp2b = VDUPQ(0); /* to avoid errors on older compilers -Werror=maybe-uninitialized */ } else { sljit_u32 bit2 = char2a ^ char2b; if (is_powerof2(bit2)) { compare2_type = compare_match1i; cmp2a = VDUPQ(char2a | bit2); cmp2b = VDUPQ(bit2); } else { compare2_type = compare_match2; cmp2a = VDUPQ(char2a); cmp2b = VDUPQ(char2b); } } # endif str_ptr += IN_UCHARS(offs1); #endif #if PCRE2_CODE_UNIT_WIDTH != 8 vect_t char_mask = VDUPQ(0xff); #endif #if defined(FF_UTF) restart:; #endif #if defined(FFCPS) sljit_u8 *p1 = str_ptr - diff; #endif sljit_s32 align_offset = ((uint64_t)str_ptr & 0xf); str_ptr = (sljit_u8 *) ((uint64_t)str_ptr & ~0xf); vect_t data = VLD1Q(str_ptr); #if PCRE2_CODE_UNIT_WIDTH != 8 data = VANDQ(data, char_mask); #endif #if defined(FFCS) vect_t eq = VCEQQ(data, vc1); #elif defined(FFCS_2) vect_t eq1 = VCEQQ(data, vc1); vect_t eq2 = VCEQQ(data, vc2); vect_t eq = VORRQ(eq1, eq2); #elif defined(FFCS_MASK) vect_t eq = VORRQ(data, vmask); eq = VCEQQ(eq, vc1); #elif defined(FFCPS) # if defined(FFCPS_DIFF1) vect_t prev_data = data; # endif vect_t data2; if (p1 < str_ptr) { data2 = VLD1Q(str_ptr - diff); #if PCRE2_CODE_UNIT_WIDTH != 8 data2 = VANDQ(data2, char_mask); #endif } else data2 = shift_left_n_lanes(data, offs1 - offs2); if (compare1_type == compare_match1) data = VCEQQ(data, cmp1a); else data = fast_forward_char_pair_compare(compare1_type, data, cmp1a, cmp1b); if (compare2_type == compare_match1) data2 = VCEQQ(data2, cmp2a); else data2 = fast_forward_char_pair_compare(compare2_type, data2, cmp2a, cmp2b); vect_t eq = VANDQ(data, data2); #endif VST1Q(qw.mem, eq); /* Ignore matches before the first STR_PTR. */ if (align_offset < 8) { qw.dw[0] >>= align_offset * 8; if (qw.dw[0]) { str_ptr += align_offset + __builtin_ctzll(qw.dw[0]) / 8; goto match; } if (qw.dw[1]) { str_ptr += 8 + __builtin_ctzll(qw.dw[1]) / 8; goto match; } } else { qw.dw[1] >>= (align_offset - 8) * 8; if (qw.dw[1]) { str_ptr += align_offset + __builtin_ctzll(qw.dw[1]) / 8; goto match; } } str_ptr += 16; while (str_ptr < str_end) { vect_t orig_data = VLD1Q(str_ptr); #if PCRE2_CODE_UNIT_WIDTH != 8 orig_data = VANDQ(orig_data, char_mask); #endif data = orig_data; #if defined(FFCS) eq = VCEQQ(data, vc1); #elif defined(FFCS_2) eq1 = VCEQQ(data, vc1); eq2 = VCEQQ(data, vc2); eq = VORRQ(eq1, eq2); #elif defined(FFCS_MASK) eq = VORRQ(data, vmask); eq = VCEQQ(eq, vc1); #endif #if defined(FFCPS) # if defined (FFCPS_DIFF1) data2 = VEXTQ(prev_data, data, VECTOR_FACTOR - 1); # else data2 = VLD1Q(str_ptr - diff); # if PCRE2_CODE_UNIT_WIDTH != 8 data2 = VANDQ(data2, char_mask); # endif # endif # ifdef FFCPS_CHAR1A2A data = VCEQQ(data, cmp1a); data2 = VCEQQ(data2, cmp2a); # else if (compare1_type == compare_match1) data = VCEQQ(data, cmp1a); else data = fast_forward_char_pair_compare(compare1_type, data, cmp1a, cmp1b); if (compare2_type == compare_match1) data2 = VCEQQ(data2, cmp2a); else data2 = fast_forward_char_pair_compare(compare2_type, data2, cmp2a, cmp2b); # endif eq = VANDQ(data, data2); #endif VST1Q(qw.mem, eq); if (qw.dw[0]) str_ptr += __builtin_ctzll(qw.dw[0]) / 8; else if (qw.dw[1]) str_ptr += 8 + __builtin_ctzll(qw.dw[1]) / 8; else { str_ptr += 16; #if defined (FFCPS_DIFF1) prev_data = orig_data; #endif continue; } match:; if (str_ptr >= str_end) /* Failed match. */ return NULL; #if defined(FF_UTF) if (utf_continue(str_ptr + IN_UCHARS(-offs1))) { /* Not a match. */ str_ptr += IN_UCHARS(1); goto restart; } #endif /* Match. */ #if defined (FFCPS) str_ptr -= IN_UCHARS(offs1); #endif return str_ptr; } /* Failed match. */ return NULL; }
8,400
23.140805
120
h
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_maketables.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2020 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains the external function pcre2_maketables(), which builds character tables for PCRE2 in the current locale. The file is compiled on its own as part of the PCRE2 library. It is also included in the compilation of pcre2_dftables.c as a freestanding program, in which case the macro PCRE2_DFTABLES is defined. */ #ifndef PCRE2_DFTABLES /* Compiling the library */ # ifdef HAVE_CONFIG_H # include "config.h" # endif # include "pcre2_internal.h" #endif /************************************************* * Create PCRE2 character tables * *************************************************/ /* This function builds a set of character tables for use by PCRE2 and returns a pointer to them. They are build using the ctype functions, and consequently their contents will depend upon the current locale setting. When compiled as part of the library, the store is obtained via a general context malloc, if supplied, but when PCRE2_DFTABLES is defined (when compiling the pcre2_dftables freestanding auxiliary program) malloc() is used, and the function has a different name so as not to clash with the prototype in pcre2.h. Arguments: none when PCRE2_DFTABLES is defined else a PCRE2 general context or NULL Returns: pointer to the contiguous block of data else NULL if memory allocation failed */ #ifdef PCRE2_DFTABLES /* Included in freestanding pcre2_dftables program */ static const uint8_t *maketables(void) { uint8_t *yield = (uint8_t *)malloc(TABLES_LENGTH); #else /* Not PCRE2_DFTABLES, that is, compiling the library */ PCRE2_EXP_DEFN const uint8_t * PCRE2_CALL_CONVENTION pcre2_maketables(pcre2_general_context *gcontext) { uint8_t *yield = (uint8_t *)((gcontext != NULL)? gcontext->memctl.malloc(TABLES_LENGTH, gcontext->memctl.memory_data) : malloc(TABLES_LENGTH)); #endif /* PCRE2_DFTABLES */ int i; uint8_t *p; if (yield == NULL) return NULL; p = yield; /* First comes the lower casing table */ for (i = 0; i < 256; i++) *p++ = tolower(i); /* Next the case-flipping table */ for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); /* Then the character class tables. Don't try to be clever and save effort on exclusive ones - in some locales things may be different. Note that the table for "space" includes everything "isspace" gives, including VT in the default locale. This makes it work for the POSIX class [:space:]. From PCRE1 release 8.34 and for all PCRE2 releases it is also correct for Perl space, because Perl added VT at release 5.18. Note also that it is possible for a character to be alnum or alpha without being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must test for alnum specially. */ memset(p, 0, cbit_length); for (i = 0; i < 256; i++) { if (isdigit(i)) p[cbit_digit + i/8] |= 1u << (i&7); if (isupper(i)) p[cbit_upper + i/8] |= 1u << (i&7); if (islower(i)) p[cbit_lower + i/8] |= 1u << (i&7); if (isalnum(i)) p[cbit_word + i/8] |= 1u << (i&7); if (i == '_') p[cbit_word + i/8] |= 1u << (i&7); if (isspace(i)) p[cbit_space + i/8] |= 1u << (i&7); if (isxdigit(i)) p[cbit_xdigit + i/8] |= 1u << (i&7); if (isgraph(i)) p[cbit_graph + i/8] |= 1u << (i&7); if (isprint(i)) p[cbit_print + i/8] |= 1u << (i&7); if (ispunct(i)) p[cbit_punct + i/8] |= 1u << (i&7); if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1u << (i&7); } p += cbit_length; /* Finally, the character type table. In this, we used to exclude VT from the white space chars, because Perl didn't recognize it as such for \s and for comments within regexes. However, Perl changed at release 5.18, so PCRE1 changed at release 8.34 and it's always been this way for PCRE2. */ for (i = 0; i < 256; i++) { int x = 0; if (isspace(i)) x += ctype_space; if (isalpha(i)) x += ctype_letter; if (islower(i)) x += ctype_lcletter; if (isdigit(i)) x += ctype_digit; if (isalnum(i) || i == '_') x += ctype_word; *p++ = x; } return yield; } #ifndef PCRE2_DFTABLES /* Compiling the library */ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_maketables_free(pcre2_general_context *gcontext, const uint8_t *tables) { if (gcontext) gcontext->memctl.free((void *)tables, gcontext->memctl.memory_data); else free((void *)tables); } #endif /* End of pcre2_maketables.c */
6,563
39.02439
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_match_data.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2019 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Create a match data block given ovector size * *************************************************/ /* A minimum of 1 is imposed on the number of ovector pairs. */ PCRE2_EXP_DEFN pcre2_match_data * PCRE2_CALL_CONVENTION pcre2_match_data_create(uint32_t oveccount, pcre2_general_context *gcontext) { pcre2_match_data *yield; if (oveccount < 1) oveccount = 1; yield = PRIV(memctl_malloc)( offsetof(pcre2_match_data, ovector) + 2*oveccount*sizeof(PCRE2_SIZE), (pcre2_memctl *)gcontext); if (yield == NULL) return NULL; yield->oveccount = oveccount; yield->flags = 0; return yield; } /************************************************* * Create a match data block using pattern data * *************************************************/ /* If no context is supplied, use the memory allocator from the code. */ PCRE2_EXP_DEFN pcre2_match_data * PCRE2_CALL_CONVENTION pcre2_match_data_create_from_pattern(const pcre2_code *code, pcre2_general_context *gcontext) { if (gcontext == NULL) gcontext = (pcre2_general_context *)code; return pcre2_match_data_create(((pcre2_real_code *)code)->top_bracket + 1, gcontext); } /************************************************* * Free a match data block * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_match_data_free(pcre2_match_data *match_data) { if (match_data != NULL) { if ((match_data->flags & PCRE2_MD_COPIED_SUBJECT) != 0) match_data->memctl.free((void *)match_data->subject, match_data->memctl.memory_data); match_data->memctl.free(match_data, match_data->memctl.memory_data); } } /************************************************* * Get last mark in match * *************************************************/ PCRE2_EXP_DEFN PCRE2_SPTR PCRE2_CALL_CONVENTION pcre2_get_mark(pcre2_match_data *match_data) { return match_data->mark; } /************************************************* * Get pointer to ovector * *************************************************/ PCRE2_EXP_DEFN PCRE2_SIZE * PCRE2_CALL_CONVENTION pcre2_get_ovector_pointer(pcre2_match_data *match_data) { return match_data->ovector; } /************************************************* * Get number of ovector slots * *************************************************/ PCRE2_EXP_DEFN uint32_t PCRE2_CALL_CONVENTION pcre2_get_ovector_count(pcre2_match_data *match_data) { return match_data->oveccount; } /************************************************* * Get starting code unit in match * *************************************************/ PCRE2_EXP_DEFN PCRE2_SIZE PCRE2_CALL_CONVENTION pcre2_get_startchar(pcre2_match_data *match_data) { return match_data->startchar; } /************************************************* * Get size of match data block * *************************************************/ PCRE2_EXP_DEFN PCRE2_SIZE PCRE2_CALL_CONVENTION pcre2_get_match_data_size(pcre2_match_data *match_data) { return offsetof(pcre2_match_data, ovector) + 2 * (match_data->oveccount) * sizeof(PCRE2_SIZE); } /* End of pcre2_match_data.c */
5,448
31.628743
77
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_newline.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains internal functions for testing newlines when more than one kind of newline is to be recognized. When a newline is found, its length is returned. In principle, we could implement several newline "types", each referring to a different set of newline characters. At present, PCRE2 supports only NLTYPE_FIXED, which gets handled without these functions, NLTYPE_ANYCRLF, and NLTYPE_ANY. The full list of Unicode newline characters is taken from http://unicode.org/unicode/reports/tr18/. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Check for newline at given position * *************************************************/ /* This function is called only via the IS_NEWLINE macro, which does so only when the newline type is NLTYPE_ANY or NLTYPE_ANYCRLF. The case of a fixed newline (NLTYPE_FIXED) is handled inline. It is guaranteed that the code unit pointed to by ptr is less than the end of the string. Arguments: ptr pointer to possible newline type the newline type endptr pointer to the end of the string lenptr where to return the length utf TRUE if in utf mode Returns: TRUE or FALSE */ BOOL PRIV(is_newline)(PCRE2_SPTR ptr, uint32_t type, PCRE2_SPTR endptr, uint32_t *lenptr, BOOL utf) { uint32_t c; #ifdef SUPPORT_UNICODE if (utf) { GETCHAR(c, ptr); } else c = *ptr; #else (void)utf; c = *ptr; #endif /* SUPPORT_UNICODE */ if (type == NLTYPE_ANYCRLF) switch(c) { case CHAR_LF: *lenptr = 1; return TRUE; case CHAR_CR: *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; return TRUE; default: return FALSE; } /* NLTYPE_ANY */ else switch(c) { #ifdef EBCDIC case CHAR_NEL: #endif case CHAR_LF: case CHAR_VT: case CHAR_FF: *lenptr = 1; return TRUE; case CHAR_CR: *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; return TRUE; #ifndef EBCDIC #if PCRE2_CODE_UNIT_WIDTH == 8 case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; case 0x2028: /* LS */ case 0x2029: /* PS */ *lenptr = 3; return TRUE; #else /* 16-bit or 32-bit code units */ case CHAR_NEL: case 0x2028: /* LS */ case 0x2029: /* PS */ *lenptr = 1; return TRUE; #endif #endif /* Not EBCDIC */ default: return FALSE; } } /************************************************* * Check for newline at previous position * *************************************************/ /* This function is called only via the WAS_NEWLINE macro, which does so only when the newline type is NLTYPE_ANY or NLTYPE_ANYCRLF. The case of a fixed newline (NLTYPE_FIXED) is handled inline. It is guaranteed that the initial value of ptr is greater than the start of the string that is being processed. Arguments: ptr pointer to possible newline type the newline type startptr pointer to the start of the string lenptr where to return the length utf TRUE if in utf mode Returns: TRUE or FALSE */ BOOL PRIV(was_newline)(PCRE2_SPTR ptr, uint32_t type, PCRE2_SPTR startptr, uint32_t *lenptr, BOOL utf) { uint32_t c; ptr--; #ifdef SUPPORT_UNICODE if (utf) { BACKCHAR(ptr); GETCHAR(c, ptr); } else c = *ptr; #else (void)utf; c = *ptr; #endif /* SUPPORT_UNICODE */ if (type == NLTYPE_ANYCRLF) switch(c) { case CHAR_LF: *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; return TRUE; case CHAR_CR: *lenptr = 1; return TRUE; default: return FALSE; } /* NLTYPE_ANY */ else switch(c) { case CHAR_LF: *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; return TRUE; #ifdef EBCDIC case CHAR_NEL: #endif case CHAR_VT: case CHAR_FF: case CHAR_CR: *lenptr = 1; return TRUE; #ifndef EBCDIC #if PCRE2_CODE_UNIT_WIDTH == 8 case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; case 0x2028: /* LS */ case 0x2029: /* PS */ *lenptr = 3; return TRUE; #else /* 16-bit or 32-bit code units */ case CHAR_NEL: case 0x2028: /* LS */ case 0x2029: /* PS */ *lenptr = 1; return TRUE; #endif #endif /* Not EBCDIC */ default: return FALSE; } } /* End of pcre2_newline.c */
6,356
25.053279
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_ord2utf.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This file contains a function that converts a Unicode character code point into a UTF string. The behaviour is different for each code unit width. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /* If SUPPORT_UNICODE is not defined, this function will never be called. Supply a dummy function because some compilers do not like empty source modules. */ #ifndef SUPPORT_UNICODE unsigned int PRIV(ord2utf)(uint32_t cvalue, PCRE2_UCHAR *buffer) { (void)(cvalue); (void)(buffer); return 0; } #else /* SUPPORT_UNICODE */ /************************************************* * Convert code point to UTF * *************************************************/ /* Arguments: cvalue the character value buffer pointer to buffer for result Returns: number of code units placed in the buffer */ unsigned int PRIV(ord2utf)(uint32_t cvalue, PCRE2_UCHAR *buffer) { /* Convert to UTF-8 */ #if PCRE2_CODE_UNIT_WIDTH == 8 int i, j; for (i = 0; i < PRIV(utf8_table1_size); i++) if ((int)cvalue <= PRIV(utf8_table1)[i]) break; buffer += i; for (j = i; j > 0; j--) { *buffer-- = 0x80 | (cvalue & 0x3f); cvalue >>= 6; } *buffer = PRIV(utf8_table2)[i] | cvalue; return i + 1; /* Convert to UTF-16 */ #elif PCRE2_CODE_UNIT_WIDTH == 16 if (cvalue <= 0xffff) { *buffer = (PCRE2_UCHAR)cvalue; return 1; } cvalue -= 0x10000; *buffer++ = 0xd800 | (cvalue >> 10); *buffer = 0xdc00 | (cvalue & 0x3ff); return 2; /* Convert to UTF-32 */ #else *buffer = (PCRE2_UCHAR)cvalue; return 1; #endif } #endif /* SUPPORT_UNICODE */ /* End of pcre_ord2utf.c */
3,741
29.92562
77
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_pattern_info.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2018 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Return info about compiled pattern * *************************************************/ /* Arguments: code points to compiled code what what information is required where where to put the information; if NULL, return length Returns: 0 when data returned > 0 when length requested < 0 on error or unset value */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_pattern_info(const pcre2_code *code, uint32_t what, void *where) { const pcre2_real_code *re = (pcre2_real_code *)code; if (where == NULL) /* Requests field length */ { switch(what) { case PCRE2_INFO_ALLOPTIONS: case PCRE2_INFO_ARGOPTIONS: case PCRE2_INFO_BACKREFMAX: case PCRE2_INFO_BSR: case PCRE2_INFO_CAPTURECOUNT: case PCRE2_INFO_DEPTHLIMIT: case PCRE2_INFO_EXTRAOPTIONS: case PCRE2_INFO_FIRSTCODETYPE: case PCRE2_INFO_FIRSTCODEUNIT: case PCRE2_INFO_HASBACKSLASHC: case PCRE2_INFO_HASCRORLF: case PCRE2_INFO_HEAPLIMIT: case PCRE2_INFO_JCHANGED: case PCRE2_INFO_LASTCODETYPE: case PCRE2_INFO_LASTCODEUNIT: case PCRE2_INFO_MATCHEMPTY: case PCRE2_INFO_MATCHLIMIT: case PCRE2_INFO_MAXLOOKBEHIND: case PCRE2_INFO_MINLENGTH: case PCRE2_INFO_NAMEENTRYSIZE: case PCRE2_INFO_NAMECOUNT: case PCRE2_INFO_NEWLINE: return sizeof(uint32_t); case PCRE2_INFO_FIRSTBITMAP: return sizeof(const uint8_t *); case PCRE2_INFO_JITSIZE: case PCRE2_INFO_SIZE: case PCRE2_INFO_FRAMESIZE: return sizeof(size_t); case PCRE2_INFO_NAMETABLE: return sizeof(PCRE2_SPTR); } } if (re == NULL) return PCRE2_ERROR_NULL; /* Check that the first field in the block is the magic number. If it is not, return with PCRE2_ERROR_BADMAGIC. */ if (re->magic_number != MAGIC_NUMBER) return PCRE2_ERROR_BADMAGIC; /* Check that this pattern was compiled in the correct bit mode */ if ((re->flags & (PCRE2_CODE_UNIT_WIDTH/8)) == 0) return PCRE2_ERROR_BADMODE; switch(what) { case PCRE2_INFO_ALLOPTIONS: *((uint32_t *)where) = re->overall_options; break; case PCRE2_INFO_ARGOPTIONS: *((uint32_t *)where) = re->compile_options; break; case PCRE2_INFO_BACKREFMAX: *((uint32_t *)where) = re->top_backref; break; case PCRE2_INFO_BSR: *((uint32_t *)where) = re->bsr_convention; break; case PCRE2_INFO_CAPTURECOUNT: *((uint32_t *)where) = re->top_bracket; break; case PCRE2_INFO_DEPTHLIMIT: *((uint32_t *)where) = re->limit_depth; if (re->limit_depth == UINT32_MAX) return PCRE2_ERROR_UNSET; break; case PCRE2_INFO_EXTRAOPTIONS: *((uint32_t *)where) = re->extra_options; break; case PCRE2_INFO_FIRSTCODETYPE: *((uint32_t *)where) = ((re->flags & PCRE2_FIRSTSET) != 0)? 1 : ((re->flags & PCRE2_STARTLINE) != 0)? 2 : 0; break; case PCRE2_INFO_FIRSTCODEUNIT: *((uint32_t *)where) = ((re->flags & PCRE2_FIRSTSET) != 0)? re->first_codeunit : 0; break; case PCRE2_INFO_FIRSTBITMAP: *((const uint8_t **)where) = ((re->flags & PCRE2_FIRSTMAPSET) != 0)? &(re->start_bitmap[0]) : NULL; break; case PCRE2_INFO_FRAMESIZE: *((size_t *)where) = offsetof(heapframe, ovector) + re->top_bracket * 2 * sizeof(PCRE2_SIZE); break; case PCRE2_INFO_HASBACKSLASHC: *((uint32_t *)where) = (re->flags & PCRE2_HASBKC) != 0; break; case PCRE2_INFO_HASCRORLF: *((uint32_t *)where) = (re->flags & PCRE2_HASCRORLF) != 0; break; case PCRE2_INFO_HEAPLIMIT: *((uint32_t *)where) = re->limit_heap; if (re->limit_heap == UINT32_MAX) return PCRE2_ERROR_UNSET; break; case PCRE2_INFO_JCHANGED: *((uint32_t *)where) = (re->flags & PCRE2_JCHANGED) != 0; break; case PCRE2_INFO_JITSIZE: #ifdef SUPPORT_JIT *((size_t *)where) = (re->executable_jit != NULL)? PRIV(jit_get_size)(re->executable_jit) : 0; #else *((size_t *)where) = 0; #endif break; case PCRE2_INFO_LASTCODETYPE: *((uint32_t *)where) = ((re->flags & PCRE2_LASTSET) != 0)? 1 : 0; break; case PCRE2_INFO_LASTCODEUNIT: *((uint32_t *)where) = ((re->flags & PCRE2_LASTSET) != 0)? re->last_codeunit : 0; break; case PCRE2_INFO_MATCHEMPTY: *((uint32_t *)where) = (re->flags & PCRE2_MATCH_EMPTY) != 0; break; case PCRE2_INFO_MATCHLIMIT: *((uint32_t *)where) = re->limit_match; if (re->limit_match == UINT32_MAX) return PCRE2_ERROR_UNSET; break; case PCRE2_INFO_MAXLOOKBEHIND: *((uint32_t *)where) = re->max_lookbehind; break; case PCRE2_INFO_MINLENGTH: *((uint32_t *)where) = re->minlength; break; case PCRE2_INFO_NAMEENTRYSIZE: *((uint32_t *)where) = re->name_entry_size; break; case PCRE2_INFO_NAMECOUNT: *((uint32_t *)where) = re->name_count; break; case PCRE2_INFO_NAMETABLE: *((PCRE2_SPTR *)where) = (PCRE2_SPTR)((char *)re + sizeof(pcre2_real_code)); break; case PCRE2_INFO_NEWLINE: *((uint32_t *)where) = re->newline_convention; break; case PCRE2_INFO_SIZE: *((size_t *)where) = re->blocksize; break; default: return PCRE2_ERROR_BADOPTION; } return 0; } /************************************************* * Callout enumerator * *************************************************/ /* Arguments: code points to compiled code callback function called for each callout block callout_data user data passed to the callback Returns: 0 when successfully completed < 0 on local error != 0 for callback error */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_callout_enumerate(const pcre2_code *code, int (*callback)(pcre2_callout_enumerate_block *, void *), void *callout_data) { pcre2_real_code *re = (pcre2_real_code *)code; pcre2_callout_enumerate_block cb; PCRE2_SPTR cc; #ifdef SUPPORT_UNICODE BOOL utf; #endif if (re == NULL) return PCRE2_ERROR_NULL; #ifdef SUPPORT_UNICODE utf = (re->overall_options & PCRE2_UTF) != 0; #endif /* Check that the first field in the block is the magic number. If it is not, return with PCRE2_ERROR_BADMAGIC. */ if (re->magic_number != MAGIC_NUMBER) return PCRE2_ERROR_BADMAGIC; /* Check that this pattern was compiled in the correct bit mode */ if ((re->flags & (PCRE2_CODE_UNIT_WIDTH/8)) == 0) return PCRE2_ERROR_BADMODE; cb.version = 0; cc = (PCRE2_SPTR)((uint8_t *)re + sizeof(pcre2_real_code)) + re->name_count * re->name_entry_size; while (TRUE) { int rc; switch (*cc) { case OP_END: return 0; case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: cc += PRIV(OP_lengths)[*cc]; #ifdef SUPPORT_UNICODE if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSUPTO: cc += PRIV(OP_lengths)[*cc]; #ifdef SUPPORT_UNICODE if (cc[-1] == OP_PROP || cc[-1] == OP_NOTPROP) cc += 2; #endif break; #if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8 case OP_XCLASS: cc += GET(cc, 1); break; #endif case OP_MARK: case OP_COMMIT_ARG: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: cc += PRIV(OP_lengths)[*cc] + cc[1]; break; case OP_CALLOUT: cb.pattern_position = GET(cc, 1); cb.next_item_length = GET(cc, 1 + LINK_SIZE); cb.callout_number = cc[1 + 2*LINK_SIZE]; cb.callout_string_offset = 0; cb.callout_string_length = 0; cb.callout_string = NULL; rc = callback(&cb, callout_data); if (rc != 0) return rc; cc += PRIV(OP_lengths)[*cc]; break; case OP_CALLOUT_STR: cb.pattern_position = GET(cc, 1); cb.next_item_length = GET(cc, 1 + LINK_SIZE); cb.callout_number = 0; cb.callout_string_offset = GET(cc, 1 + 3*LINK_SIZE); cb.callout_string_length = GET(cc, 1 + 2*LINK_SIZE) - (1 + 4*LINK_SIZE) - 2; cb.callout_string = cc + (1 + 4*LINK_SIZE) + 1; rc = callback(&cb, callout_data); if (rc != 0) return rc; cc += GET(cc, 1 + 2*LINK_SIZE); break; default: cc += PRIV(OP_lengths)[*cc]; break; } } } /* End of pcre2_pattern_info.c */
11,738
26.110855
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_printint.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2022 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains a PCRE private debugging function for printing out the internal form of a compiled regular expression, along with some supporting local functions. This source file is #included in pcre2test.c at each supported code unit width, with PCRE2_SUFFIX set appropriately, just like the functions that comprise the library. It can also optionally be included in pcre2_compile.c for detailed debugging in error situations. */ /* Tables of operator names. The same 8-bit table is used for all code unit widths, so it must be defined only once. The list itself is defined in pcre2_internal.h, which is #included by pcre2test before this file. */ #ifndef OP_LISTS_DEFINED static const char *OP_names[] = { OP_NAME_LIST }; #define OP_LISTS_DEFINED #endif /* The functions and tables herein must all have mode-dependent names. */ #define OP_lengths PCRE2_SUFFIX(OP_lengths_) #define get_ucpname PCRE2_SUFFIX(get_ucpname_) #define pcre2_printint PCRE2_SUFFIX(pcre2_printint_) #define print_char PCRE2_SUFFIX(print_char_) #define print_custring PCRE2_SUFFIX(print_custring_) #define print_custring_bylen PCRE2_SUFFIX(print_custring_bylen_) #define print_prop PCRE2_SUFFIX(print_prop_) /* Table of sizes for the fixed-length opcodes. It's defined in a macro so that the definition is next to the definition of the opcodes in pcre2_internal.h. The contents of the table are, however, mode-dependent. */ static const uint8_t OP_lengths[] = { OP_LENGTHS }; /************************************************* * Print one character from a string * *************************************************/ /* In UTF mode the character may occupy more than one code unit. Arguments: f file to write to ptr pointer to first code unit of the character utf TRUE if string is UTF (will be FALSE if UTF is not supported) Returns: number of additional code units used */ static unsigned int print_char(FILE *f, PCRE2_SPTR ptr, BOOL utf) { uint32_t c = *ptr; BOOL one_code_unit = !utf; /* If UTF is supported and requested, check for a valid single code unit. */ #ifdef SUPPORT_UNICODE if (utf) { #if PCRE2_CODE_UNIT_WIDTH == 8 one_code_unit = c < 0x80; #elif PCRE2_CODE_UNIT_WIDTH == 16 one_code_unit = (c & 0xfc00) != 0xd800; #else one_code_unit = (c & 0xfffff800u) != 0xd800u; #endif /* CODE_UNIT_WIDTH */ } #endif /* SUPPORT_UNICODE */ /* Handle a valid one-code-unit character at any width. */ if (one_code_unit) { if (PRINTABLE(c)) fprintf(f, "%c", (char)c); else if (c < 0x80) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%02x}", c); return 0; } /* Code for invalid UTF code units and multi-unit UTF characters is different for each width. If UTF is not supported, control should never get here, but we need a return statement to keep the compiler happy. */ #ifndef SUPPORT_UNICODE return 0; #else /* Malformed UTF-8 should occur only if the sanity check has been turned off. Rather than swallow random bytes, just stop if we hit a bad one. Print it with \X instead of \x as an indication. */ #if PCRE2_CODE_UNIT_WIDTH == 8 if ((c & 0xc0) != 0xc0) { fprintf(f, "\\X{%x}", c); /* Invalid starting byte */ return 0; } else { int i; int a = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes */ int s = 6*a; c = (c & PRIV(utf8_table3)[a]) << s; for (i = 1; i <= a; i++) { if ((ptr[i] & 0xc0) != 0x80) { fprintf(f, "\\X{%x}", c); /* Invalid secondary byte */ return i - 1; } s -= 6; c |= (ptr[i] & 0x3f) << s; } fprintf(f, "\\x{%x}", c); return a; } #endif /* PCRE2_CODE_UNIT_WIDTH == 8 */ /* UTF-16: rather than swallow a low surrogate, just stop if we hit a bad one. Print it with \X instead of \x as an indication. */ #if PCRE2_CODE_UNIT_WIDTH == 16 if ((ptr[1] & 0xfc00) != 0xdc00) { fprintf(f, "\\X{%x}", c); return 0; } c = (((c & 0x3ff) << 10) | (ptr[1] & 0x3ff)) + 0x10000; fprintf(f, "\\x{%x}", c); return 1; #endif /* PCRE2_CODE_UNIT_WIDTH == 16 */ /* For UTF-32 we get here only for a malformed code unit, which should only occur if the sanity check has been turned off. Print it with \X instead of \x as an indication. */ #if PCRE2_CODE_UNIT_WIDTH == 32 fprintf(f, "\\X{%x}", c); return 0; #endif /* PCRE2_CODE_UNIT_WIDTH == 32 */ #endif /* SUPPORT_UNICODE */ } /************************************************* * Print string as a list of code units * *************************************************/ /* These take no account of UTF as they always print each individual code unit. The string is zero-terminated for print_custring(); the length is given for print_custring_bylen(). Arguments: f file to write to ptr point to the string len length for print_custring_bylen() Returns: nothing */ static void print_custring(FILE *f, PCRE2_SPTR ptr) { while (*ptr != '\0') { uint32_t c = *ptr++; if (PRINTABLE(c)) fprintf(f, "%c", c); else fprintf(f, "\\x{%x}", c); } } static void print_custring_bylen(FILE *f, PCRE2_SPTR ptr, PCRE2_UCHAR len) { for (; len > 0; len--) { uint32_t c = *ptr++; if (PRINTABLE(c)) fprintf(f, "%c", c); else fprintf(f, "\\x{%x}", c); } } /************************************************* * Find Unicode property name * *************************************************/ /* When there is no UTF/UCP support, the table of names does not exist. This function should not be called in such configurations, because a pattern that tries to use Unicode properties won't compile. Rather than put lots of #ifdefs into the main code, however, we just put one into this function. Now that the table contains both full names and their abbreviations, we do some fiddling to try to get the full name, which is either the longer of two found names, or a 3-character script name. */ static const char * get_ucpname(unsigned int ptype, unsigned int pvalue) { #ifdef SUPPORT_UNICODE int count = 0; const char *yield = "??"; size_t len = 0; unsigned int ptypex = (ptype == PT_SC)? PT_SCX : ptype; for (int i = PRIV(utt_size) - 1; i >= 0; i--) { const ucp_type_table *u = PRIV(utt) + i; if ((ptype == u->type || ptypex == u->type) && pvalue == u->value) { const char *s = PRIV(utt_names) + u->name_offset; size_t sl = strlen(s); if (sl == 3 && (u->type == PT_SC || u->type == PT_SCX)) { yield = s; break; } if (sl > len) { yield = s; len = sl; } if (++count >= 2) break; } } return yield; #else /* No UTF support */ (void)ptype; (void)pvalue; return "??"; #endif /* SUPPORT_UNICODE */ } /************************************************* * Print Unicode property value * *************************************************/ /* "Normal" properties can be printed from tables. The PT_CLIST property is a pseudo-property that contains a pointer to a list of case-equivalent characters. Arguments: f file to write to code pointer in the compiled code before text to print before after text to print after Returns: nothing */ static void print_prop(FILE *f, PCRE2_SPTR code, const char *before, const char *after) { if (code[1] != PT_CLIST) { const char *sc = (code[1] == PT_SC)? "script:" : ""; const char *s = get_ucpname(code[1], code[2]); fprintf(f, "%s%s %s%c%s%s", before, OP_names[*code], sc, toupper(s[0]), s+1, after); } else { const char *not = (*code == OP_PROP)? "" : "not "; const uint32_t *p = PRIV(ucd_caseless_sets) + code[2]; fprintf (f, "%s%sclist", before, not); while (*p < NOTACHAR) fprintf(f, " %04x", *p++); fprintf(f, "%s", after); } } /************************************************* * Print compiled pattern * *************************************************/ /* The print_lengths flag controls whether offsets and lengths of items are printed. Lenths can be turned off from pcre2test so that automatic tests on bytecode can be written that do not depend on the value of LINK_SIZE. Arguments: re a compiled pattern f the file to write to print_lengths show various lengths Returns: nothing */ static void pcre2_printint(pcre2_code *re, FILE *f, BOOL print_lengths) { PCRE2_SPTR codestart, nametable, code; uint32_t nesize = re->name_entry_size; BOOL utf = (re->overall_options & PCRE2_UTF) != 0; nametable = (PCRE2_SPTR)((uint8_t *)re + sizeof(pcre2_real_code)); code = codestart = nametable + re->name_count * re->name_entry_size; for(;;) { PCRE2_SPTR ccode; uint32_t c; int i; const char *flag = " "; unsigned int extra = 0; if (print_lengths) fprintf(f, "%3d ", (int)(code - codestart)); else fprintf(f, " "); switch(*code) { /* ========================================================================== */ /* These cases are never obeyed. This is a fudge that causes a compile- time error if the vectors OP_names or OP_lengths, which are indexed by opcode, are not the correct length. It seems to be the only way to do such a check at compile time, as the sizeof() operator does not work in the C preprocessor. */ case OP_TABLE_LENGTH: case OP_TABLE_LENGTH + ((sizeof(OP_names)/sizeof(const char *) == OP_TABLE_LENGTH) && (sizeof(OP_lengths) == OP_TABLE_LENGTH)): return; /* ========================================================================== */ case OP_END: fprintf(f, " %s\n", OP_names[*code]); fprintf(f, "------------------------------------------------------------------\n"); return; case OP_CHAR: fprintf(f, " "); do { code++; code += 1 + print_char(f, code, utf); } while (*code == OP_CHAR); fprintf(f, "\n"); continue; case OP_CHARI: fprintf(f, " /i "); do { code++; code += 1 + print_char(f, code, utf); } while (*code == OP_CHARI); fprintf(f, "\n"); continue; case OP_CBRA: case OP_CBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s %d", OP_names[*code], GET2(code, 1+LINK_SIZE)); break; case OP_BRA: case OP_BRAPOS: case OP_SBRA: case OP_SBRAPOS: case OP_KETRMAX: case OP_KETRMIN: case OP_KETRPOS: case OP_ALT: case OP_KET: case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ASSERT_NA: case OP_ASSERTBACK_NA: case OP_ONCE: case OP_SCRIPT_RUN: case OP_COND: case OP_SCOND: case OP_REVERSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", OP_names[*code]); break; case OP_CLOSE: fprintf(f, " %s %d", OP_names[*code], GET2(code, 1)); break; case OP_CREF: fprintf(f, "%3d %s", GET2(code,1), OP_names[*code]); break; case OP_DNCREF: { PCRE2_SPTR entry = nametable + (GET2(code, 1) * nesize) + IMM2_SIZE; fprintf(f, " %s Cond ref <", flag); print_custring(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } break; case OP_RREF: c = GET2(code, 1); if (c == RREF_ANY) fprintf(f, " Cond recurse any"); else fprintf(f, " Cond recurse %d", c); break; case OP_DNRREF: { PCRE2_SPTR entry = nametable + (GET2(code, 1) * nesize) + IMM2_SIZE; fprintf(f, " %s Cond recurse <", flag); print_custring(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } break; case OP_FALSE: fprintf(f, " Cond false"); break; case OP_TRUE: fprintf(f, " Cond true"); break; case OP_STARI: case OP_MINSTARI: case OP_POSSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_POSPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_POSQUERYI: flag = "/i"; /* Fall through */ case OP_STAR: case OP_MINSTAR: case OP_POSSTAR: case OP_PLUS: case OP_MINPLUS: case OP_POSPLUS: case OP_QUERY: case OP_MINQUERY: case OP_POSQUERY: case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPOSSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEPOSPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSQUERY: fprintf(f, " %s ", flag); if (*code >= OP_TYPESTAR) { if (code[1] == OP_PROP || code[1] == OP_NOTPROP) { print_prop(f, code + 1, "", " "); extra = 2; } else fprintf(f, "%s", OP_names[code[1]]); } else extra = print_char(f, code+1, utf); fprintf(f, "%s", OP_names[*code]); break; case OP_EXACTI: case OP_UPTOI: case OP_MINUPTOI: case OP_POSUPTOI: flag = "/i"; /* Fall through */ case OP_EXACT: case OP_UPTO: case OP_MINUPTO: case OP_POSUPTO: fprintf(f, " %s ", flag); extra = print_char(f, code + 1 + IMM2_SIZE, utf); fprintf(f, "{"); if (*code != OP_EXACT && *code != OP_EXACTI) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_MINUPTO || *code == OP_MINUPTOI) fprintf(f, "?"); else if (*code == OP_POSUPTO || *code == OP_POSUPTOI) fprintf(f, "+"); break; case OP_TYPEEXACT: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) { print_prop(f, code + IMM2_SIZE + 1, " ", " "); extra = 2; } else fprintf(f, " %s", OP_names[code[1 + IMM2_SIZE]]); fprintf(f, "{"); if (*code != OP_TYPEEXACT) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_TYPEMINUPTO) fprintf(f, "?"); else if (*code == OP_TYPEPOSUPTO) fprintf(f, "+"); break; case OP_NOTI: flag = "/i"; /* Fall through */ case OP_NOT: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1, utf); fprintf(f, "]"); break; case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPOSSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTPOSPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTPOSQUERYI: flag = "/i"; /* Fall through */ case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPOSSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTPOSPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTPOSQUERY: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1, utf); fprintf(f, "]%s", OP_names[*code]); break; case OP_NOTEXACTI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTPOSUPTOI: flag = "/i"; /* Fall through */ case OP_NOTEXACT: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTPOSUPTO: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1 + IMM2_SIZE, utf); fprintf(f, "]{"); if (*code != OP_NOTEXACT && *code != OP_NOTEXACTI) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_NOTMINUPTO || *code == OP_NOTMINUPTOI) fprintf(f, "?"); else if (*code == OP_NOTPOSUPTO || *code == OP_NOTPOSUPTOI) fprintf(f, "+"); break; case OP_RECURSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", OP_names[*code]); break; case OP_REFI: flag = "/i"; /* Fall through */ case OP_REF: fprintf(f, " %s \\%d", flag, GET2(code,1)); ccode = code + OP_lengths[*code]; goto CLASS_REF_REPEAT; case OP_DNREFI: flag = "/i"; /* Fall through */ case OP_DNREF: { PCRE2_SPTR entry = nametable + (GET2(code, 1) * nesize) + IMM2_SIZE; fprintf(f, " %s \\k<", flag); print_custring(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } ccode = code + OP_lengths[*code]; goto CLASS_REF_REPEAT; case OP_CALLOUT: fprintf(f, " %s %d %d %d", OP_names[*code], code[1 + 2*LINK_SIZE], GET(code, 1), GET(code, 1 + LINK_SIZE)); break; case OP_CALLOUT_STR: c = code[1 + 4*LINK_SIZE]; fprintf(f, " %s %c", OP_names[*code], c); extra = GET(code, 1 + 2*LINK_SIZE); print_custring_bylen(f, code + 2 + 4*LINK_SIZE, extra - 3 - 4*LINK_SIZE); for (i = 0; PRIV(callout_start_delims)[i] != 0; i++) if (c == PRIV(callout_start_delims)[i]) { c = PRIV(callout_end_delims)[i]; break; } fprintf(f, "%c %d %d %d", c, GET(code, 1 + 3*LINK_SIZE), GET(code, 1), GET(code, 1 + LINK_SIZE)); break; case OP_PROP: case OP_NOTPROP: print_prop(f, code, " ", ""); break; /* OP_XCLASS cannot occur in 8-bit, non-UTF mode. However, there's no harm in having this code always here, and it makes it less messy without all those #ifdefs. */ case OP_CLASS: case OP_NCLASS: case OP_XCLASS: { unsigned int min, max; BOOL printmap; BOOL invertmap = FALSE; uint8_t *map; uint8_t inverted_map[32]; fprintf(f, " ["); if (*code == OP_XCLASS) { extra = GET(code, 1); ccode = code + LINK_SIZE + 1; printmap = (*ccode & XCL_MAP) != 0; if ((*ccode & XCL_NOT) != 0) { invertmap = (*ccode & XCL_HASPROP) == 0; fprintf(f, "^"); } ccode++; } else { printmap = TRUE; ccode = code + 1; } /* Print a bit map */ if (printmap) { map = (uint8_t *)ccode; if (invertmap) { /* Using 255 ^ instead of ~ avoids clang sanitize warning. */ for (i = 0; i < 32; i++) inverted_map[i] = 255 ^ map[i]; map = inverted_map; } for (i = 0; i < 256; i++) { if ((map[i/8] & (1u << (i&7))) != 0) { int j; for (j = i+1; j < 256; j++) if ((map[j/8] & (1u << (j&7))) == 0) break; if (i == '-' || i == ']') fprintf(f, "\\"); if (PRINTABLE(i)) fprintf(f, "%c", i); else fprintf(f, "\\x%02x", i); if (--j > i) { if (j != i + 1) fprintf(f, "-"); if (j == '-' || j == ']') fprintf(f, "\\"); if (PRINTABLE(j)) fprintf(f, "%c", j); else fprintf(f, "\\x%02x", j); } i = j; } } ccode += 32 / sizeof(PCRE2_UCHAR); } /* For an XCLASS there is always some additional data */ if (*code == OP_XCLASS) { PCRE2_UCHAR ch; while ((ch = *ccode++) != XCL_END) { BOOL not = FALSE; const char *notch = ""; switch(ch) { case XCL_NOTPROP: not = TRUE; notch = "^"; /* Fall through */ case XCL_PROP: { unsigned int ptype = *ccode++; unsigned int pvalue = *ccode++; const char *s; switch(ptype) { case PT_PXGRAPH: fprintf(f, "[:%sgraph:]", notch); break; case PT_PXPRINT: fprintf(f, "[:%sprint:]", notch); break; case PT_PXPUNCT: fprintf(f, "[:%spunct:]", notch); break; default: s = get_ucpname(ptype, pvalue); fprintf(f, "\\%c{%c%s}", (not? 'P':'p'), toupper(s[0]), s+1); break; } } break; default: ccode += 1 + print_char(f, ccode, utf); if (ch == XCL_RANGE) { fprintf(f, "-"); ccode += 1 + print_char(f, ccode, utf); } break; } } } /* Indicate a non-UTF class which was created by negation */ fprintf(f, "]%s", (*code == OP_NCLASS)? " (neg)" : ""); /* Handle repeats after a class or a back reference */ CLASS_REF_REPEAT: switch(*ccode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSSTAR: case OP_CRPOSPLUS: case OP_CRPOSQUERY: fprintf(f, "%s", OP_names[*ccode]); extra += OP_lengths[*ccode]; break; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: min = GET2(ccode,1); max = GET2(ccode,1 + IMM2_SIZE); if (max == 0) fprintf(f, "{%u,}", min); else fprintf(f, "{%u,%u}", min, max); if (*ccode == OP_CRMINRANGE) fprintf(f, "?"); else if (*ccode == OP_CRPOSRANGE) fprintf(f, "+"); extra += OP_lengths[*ccode]; break; /* Do nothing if it's not a repeat; this code stops picky compilers warning about the lack of a default code path. */ default: break; } } break; case OP_MARK: case OP_COMMIT_ARG: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: fprintf(f, " %s ", OP_names[*code]); print_custring_bylen(f, code + 2, code[1]); extra += code[1]; break; case OP_THEN: fprintf(f, " %s", OP_names[*code]); break; case OP_CIRCM: case OP_DOLLM: flag = "/m"; /* Fall through */ /* Anything else is just an item with no data, but possibly a flag. */ default: fprintf(f, " %s %s", flag, OP_names[*code]); break; } code += OP_lengths[*code] + extra; fprintf(f, "\n"); } } /* End of pcre2_printint.c */
24,151
26.792865
87
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_script_run.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2021 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains the function for checking a script run. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Check script run * *************************************************/ /* A script run is conceptually a sequence of characters all in the same Unicode script. However, it isn't quite that simple. There are special rules for scripts that are commonly used together, and also special rules for digits. This function implements the appropriate checks, which is possible only when PCRE2 is compiled with Unicode support. The function returns TRUE if there is no Unicode support; however, it should never be called in that circumstance because an error is given by pcre2_compile() if a script run is called for in a version of PCRE2 compiled without Unicode support. Arguments: pgr point to the first character endptr point after the last character utf TRUE if in UTF mode Returns: TRUE if this is a valid script run */ /* These are states in the checking process. */ enum { SCRIPT_UNSET, /* Requirement as yet unknown */ SCRIPT_MAP, /* Bitmap contains acceptable scripts */ SCRIPT_HANPENDING, /* Have had only Han characters */ SCRIPT_HANHIRAKATA, /* Expect Han or Hirikata */ SCRIPT_HANBOPOMOFO, /* Expect Han or Bopomofo */ SCRIPT_HANHANGUL /* Expect Han or Hangul */ }; #define UCD_MAPSIZE (ucp_Unknown/32 + 1) #define FULL_MAPSIZE (ucp_Script_Count/32 + 1) BOOL PRIV(script_run)(PCRE2_SPTR ptr, PCRE2_SPTR endptr, BOOL utf) { #ifdef SUPPORT_UNICODE uint32_t require_state = SCRIPT_UNSET; uint32_t require_map[FULL_MAPSIZE]; uint32_t map[FULL_MAPSIZE]; uint32_t require_digitset = 0; uint32_t c; #if PCRE2_CODE_UNIT_WIDTH == 32 (void)utf; /* Avoid compiler warning */ #endif /* Any string containing fewer than 2 characters is a valid script run. */ if (ptr >= endptr) return TRUE; GETCHARINCTEST(c, ptr); if (ptr >= endptr) return TRUE; /* Initialize the require map. This is a full-size bitmap that has a bit for every script, as opposed to the maps in ucd_script_sets, which only have bits for scripts less than ucp_Unknown - those that appear in script extension lists. */ for (int i = 0; i < FULL_MAPSIZE; i++) require_map[i] = 0; /* Scan strings of two or more characters, checking the Unicode characteristics of each code point. There is special code for scripts that can be combined with characters from the Han Chinese script. This may be used in conjunction with four other scripts in these combinations: . Han with Hiragana and Katakana is allowed (for Japanese). . Han with Bopomofo is allowed (for Taiwanese Mandarin). . Han with Hangul is allowed (for Korean). If the first significant character's script is one of the four, the required script type is immediately known. However, if the first significant character's script is Han, we have to keep checking for a non-Han character. Hence the SCRIPT_HANPENDING state. */ for (;;) { const ucd_record *ucd = GET_UCD(c); uint32_t script = ucd->script; /* If the script is Unknown, the string is not a valid script run. Such characters can only form script runs of length one (see test above). */ if (script == ucp_Unknown) return FALSE; /* A character without any script extensions whose script is Inherited or Common is always accepted with any script. If there are extensions, the following processing happens for all scripts. */ if (UCD_SCRIPTX_PROP(ucd) != 0 || (script != ucp_Inherited && script != ucp_Common)) { BOOL OK; /* Set up a full-sized map for this character that can include bits for all scripts. Copy the scriptx map for this character (which covers those scripts that appear in script extension lists), set the remaining values to zero, and then, except for Common or Inherited, add this script's bit to the map. */ memcpy(map, PRIV(ucd_script_sets) + UCD_SCRIPTX_PROP(ucd), UCD_MAPSIZE * sizeof(uint32_t)); memset(map + UCD_MAPSIZE, 0, (FULL_MAPSIZE - UCD_MAPSIZE) * sizeof(uint32_t)); if (script != ucp_Common && script != ucp_Inherited) MAPSET(map, script); /* Handle the different checking states */ switch(require_state) { /* First significant character - it might follow Common or Inherited characters that do not have any script extensions. */ case SCRIPT_UNSET: switch(script) { case ucp_Han: require_state = SCRIPT_HANPENDING; break; case ucp_Hiragana: case ucp_Katakana: require_state = SCRIPT_HANHIRAKATA; break; case ucp_Bopomofo: require_state = SCRIPT_HANBOPOMOFO; break; case ucp_Hangul: require_state = SCRIPT_HANHANGUL; break; default: memcpy(require_map, map, FULL_MAPSIZE * sizeof(uint32_t)); require_state = SCRIPT_MAP; break; } break; /* The first significant character was Han. An inspection of the Unicode 11.0.0 files shows that there are the following types of Script Extension list that involve the Han, Bopomofo, Hiragana, Katakana, and Hangul scripts: . Bopomofo + Han . Han + Hiragana + Katakana . Hiragana + Katakana . Bopopmofo + Hangul + Han + Hiragana + Katakana The following code tries to make sense of this. */ #define FOUND_BOPOMOFO 1 #define FOUND_HIRAGANA 2 #define FOUND_KATAKANA 4 #define FOUND_HANGUL 8 case SCRIPT_HANPENDING: if (script != ucp_Han) /* Another Han does nothing */ { uint32_t chspecial = 0; if (MAPBIT(map, ucp_Bopomofo) != 0) chspecial |= FOUND_BOPOMOFO; if (MAPBIT(map, ucp_Hiragana) != 0) chspecial |= FOUND_HIRAGANA; if (MAPBIT(map, ucp_Katakana) != 0) chspecial |= FOUND_KATAKANA; if (MAPBIT(map, ucp_Hangul) != 0) chspecial |= FOUND_HANGUL; if (chspecial == 0) return FALSE; /* Not allowed with Han */ if (chspecial == FOUND_BOPOMOFO) require_state = SCRIPT_HANBOPOMOFO; else if (chspecial == (FOUND_HIRAGANA|FOUND_KATAKANA)) require_state = SCRIPT_HANHIRAKATA; /* Otherwise this character must be allowed with all of them, so remain in the pending state. */ } break; /* Previously encountered one of the "with Han" scripts. Check that this character is appropriate. */ case SCRIPT_HANHIRAKATA: if (MAPBIT(map, ucp_Han) + MAPBIT(map, ucp_Hiragana) + MAPBIT(map, ucp_Katakana) == 0) return FALSE; break; case SCRIPT_HANBOPOMOFO: if (MAPBIT(map, ucp_Han) + MAPBIT(map, ucp_Bopomofo) == 0) return FALSE; break; case SCRIPT_HANHANGUL: if (MAPBIT(map, ucp_Han) + MAPBIT(map, ucp_Hangul) == 0) return FALSE; break; /* Previously encountered one or more characters that are allowed with a list of scripts. */ case SCRIPT_MAP: OK = FALSE; for (int i = 0; i < FULL_MAPSIZE; i++) { if ((require_map[i] & map[i]) != 0) { OK = TRUE; break; } } if (!OK) return FALSE; /* The rest of the string must be in this script, but we have to allow for the Han complications. */ switch(script) { case ucp_Han: require_state = SCRIPT_HANPENDING; break; case ucp_Hiragana: case ucp_Katakana: require_state = SCRIPT_HANHIRAKATA; break; case ucp_Bopomofo: require_state = SCRIPT_HANBOPOMOFO; break; case ucp_Hangul: require_state = SCRIPT_HANHANGUL; break; /* Compute the intersection of the required list of scripts and the allowed scripts for this character. */ default: for (int i = 0; i < FULL_MAPSIZE; i++) require_map[i] &= map[i]; break; } break; } } /* End checking character's script and extensions. */ /* The character is in an acceptable script. We must now ensure that all decimal digits in the string come from the same set. Some scripts (e.g. Common, Arabic) have more than one set of decimal digits. This code does not allow mixing sets, even within the same script. The vector called PRIV(ucd_digit_sets)[] contains, in its first element, the number of following elements, and then, in ascending order, the code points of the '9' characters in every set of 10 digits. Each set is identified by the offset in the vector of its '9' character. An initial check of the first value picks up ASCII digits quickly. Otherwise, a binary chop is used. */ if (ucd->chartype == ucp_Nd) { uint32_t digitset; if (c <= PRIV(ucd_digit_sets)[1]) digitset = 1; else { int mid; int bot = 1; int top = PRIV(ucd_digit_sets)[0]; for (;;) { if (top <= bot + 1) /* <= rather than == is paranoia */ { digitset = top; break; } mid = (top + bot) / 2; if (c <= PRIV(ucd_digit_sets)[mid]) top = mid; else bot = mid; } } /* A required value of 0 means "unset". */ if (require_digitset == 0) require_digitset = digitset; else if (digitset != require_digitset) return FALSE; } /* End digit handling */ /* If we haven't yet got to the end, pick up the next character. */ if (ptr >= endptr) return TRUE; GETCHARINCTEST(c, ptr); } /* End checking loop */ #else /* NOT SUPPORT_UNICODE */ (void)ptr; (void)endptr; (void)utf; return TRUE; #endif /* SUPPORT_UNICODE */ } /* End of pcre2_script_run.c */
11,928
33.576812
95
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_serialize.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2020 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains functions for serializing and deserializing a sequence of compiled codes. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /* Magic number to provide a small check against being handed junk. */ #define SERIALIZED_DATA_MAGIC 0x50523253u /* Deserialization is limited to the current PCRE version and character width. */ #define SERIALIZED_DATA_VERSION \ ((PCRE2_MAJOR) | ((PCRE2_MINOR) << 16)) #define SERIALIZED_DATA_CONFIG \ (sizeof(PCRE2_UCHAR) | ((sizeof(void*)) << 8) | ((sizeof(PCRE2_SIZE)) << 16)) /************************************************* * Serialize compiled patterns * *************************************************/ PCRE2_EXP_DEFN int32_t PCRE2_CALL_CONVENTION pcre2_serialize_encode(const pcre2_code **codes, int32_t number_of_codes, uint8_t **serialized_bytes, PCRE2_SIZE *serialized_size, pcre2_general_context *gcontext) { uint8_t *bytes; uint8_t *dst_bytes; int32_t i; PCRE2_SIZE total_size; const pcre2_real_code *re; const uint8_t *tables; pcre2_serialized_data *data; const pcre2_memctl *memctl = (gcontext != NULL) ? &gcontext->memctl : &PRIV(default_compile_context).memctl; if (codes == NULL || serialized_bytes == NULL || serialized_size == NULL) return PCRE2_ERROR_NULL; if (number_of_codes <= 0) return PCRE2_ERROR_BADDATA; /* Compute total size. */ total_size = sizeof(pcre2_serialized_data) + TABLES_LENGTH; tables = NULL; for (i = 0; i < number_of_codes; i++) { if (codes[i] == NULL) return PCRE2_ERROR_NULL; re = (const pcre2_real_code *)(codes[i]); if (re->magic_number != MAGIC_NUMBER) return PCRE2_ERROR_BADMAGIC; if (tables == NULL) tables = re->tables; else if (tables != re->tables) return PCRE2_ERROR_MIXEDTABLES; total_size += re->blocksize; } /* Initialize the byte stream. */ bytes = memctl->malloc(total_size + sizeof(pcre2_memctl), memctl->memory_data); if (bytes == NULL) return PCRE2_ERROR_NOMEMORY; /* The controller is stored as a hidden parameter. */ memcpy(bytes, memctl, sizeof(pcre2_memctl)); bytes += sizeof(pcre2_memctl); data = (pcre2_serialized_data *)bytes; data->magic = SERIALIZED_DATA_MAGIC; data->version = SERIALIZED_DATA_VERSION; data->config = SERIALIZED_DATA_CONFIG; data->number_of_codes = number_of_codes; /* Copy all compiled code data. */ dst_bytes = bytes + sizeof(pcre2_serialized_data); memcpy(dst_bytes, tables, TABLES_LENGTH); dst_bytes += TABLES_LENGTH; for (i = 0; i < number_of_codes; i++) { re = (const pcre2_real_code *)(codes[i]); (void)memcpy(dst_bytes, (char *)re, re->blocksize); /* Certain fields in the compiled code block are re-set during deserialization. In order to ensure that the serialized data stream is always the same for the same pattern, set them to zero here. We can't assume the copy of the pattern is correctly aligned for accessing the fields as part of a structure. Note the use of sizeof(void *) in the second of these, to specify the size of a pointer. If sizeof(uint8_t *) is used (tables is a pointer to uint8_t), gcc gives a warning because the first argument is also a pointer to uint8_t. Casting the first argument to (void *) can stop this, but it didn't stop Coverity giving the same complaint. */ (void)memset(dst_bytes + offsetof(pcre2_real_code, memctl), 0, sizeof(pcre2_memctl)); (void)memset(dst_bytes + offsetof(pcre2_real_code, tables), 0, sizeof(void *)); (void)memset(dst_bytes + offsetof(pcre2_real_code, executable_jit), 0, sizeof(void *)); dst_bytes += re->blocksize; } *serialized_bytes = bytes; *serialized_size = total_size; return number_of_codes; } /************************************************* * Deserialize compiled patterns * *************************************************/ PCRE2_EXP_DEFN int32_t PCRE2_CALL_CONVENTION pcre2_serialize_decode(pcre2_code **codes, int32_t number_of_codes, const uint8_t *bytes, pcre2_general_context *gcontext) { const pcre2_serialized_data *data = (const pcre2_serialized_data *)bytes; const pcre2_memctl *memctl = (gcontext != NULL) ? &gcontext->memctl : &PRIV(default_compile_context).memctl; const uint8_t *src_bytes; pcre2_real_code *dst_re; uint8_t *tables; int32_t i, j; /* Sanity checks. */ if (data == NULL || codes == NULL) return PCRE2_ERROR_NULL; if (number_of_codes <= 0) return PCRE2_ERROR_BADDATA; if (data->number_of_codes <= 0) return PCRE2_ERROR_BADSERIALIZEDDATA; if (data->magic != SERIALIZED_DATA_MAGIC) return PCRE2_ERROR_BADMAGIC; if (data->version != SERIALIZED_DATA_VERSION) return PCRE2_ERROR_BADMODE; if (data->config != SERIALIZED_DATA_CONFIG) return PCRE2_ERROR_BADMODE; if (number_of_codes > data->number_of_codes) number_of_codes = data->number_of_codes; src_bytes = bytes + sizeof(pcre2_serialized_data); /* Decode tables. The reference count for the tables is stored immediately following them. */ tables = memctl->malloc(TABLES_LENGTH + sizeof(PCRE2_SIZE), memctl->memory_data); if (tables == NULL) return PCRE2_ERROR_NOMEMORY; memcpy(tables, src_bytes, TABLES_LENGTH); *(PCRE2_SIZE *)(tables + TABLES_LENGTH) = number_of_codes; src_bytes += TABLES_LENGTH; /* Decode the byte stream. We must not try to read the size from the compiled code block in the stream, because it might be unaligned, which causes errors on hardware such as Sparc-64 that doesn't like unaligned memory accesses. The type of the blocksize field is given its own name to ensure that it is the same here as in the block. */ for (i = 0; i < number_of_codes; i++) { CODE_BLOCKSIZE_TYPE blocksize; memcpy(&blocksize, src_bytes + offsetof(pcre2_real_code, blocksize), sizeof(CODE_BLOCKSIZE_TYPE)); if (blocksize <= sizeof(pcre2_real_code)) return PCRE2_ERROR_BADSERIALIZEDDATA; /* The allocator provided by gcontext replaces the original one. */ dst_re = (pcre2_real_code *)PRIV(memctl_malloc)(blocksize, (pcre2_memctl *)gcontext); if (dst_re == NULL) { memctl->free(tables, memctl->memory_data); for (j = 0; j < i; j++) { memctl->free(codes[j], memctl->memory_data); codes[j] = NULL; } return PCRE2_ERROR_NOMEMORY; } /* The new allocator must be preserved. */ memcpy(((uint8_t *)dst_re) + sizeof(pcre2_memctl), src_bytes + sizeof(pcre2_memctl), blocksize - sizeof(pcre2_memctl)); if (dst_re->magic_number != MAGIC_NUMBER || dst_re->name_entry_size > MAX_NAME_SIZE + IMM2_SIZE + 1 || dst_re->name_count > MAX_NAME_COUNT) { memctl->free(dst_re, memctl->memory_data); return PCRE2_ERROR_BADSERIALIZEDDATA; } /* At the moment only one table is supported. */ dst_re->tables = tables; dst_re->executable_jit = NULL; dst_re->flags |= PCRE2_DEREF_TABLES; codes[i] = dst_re; src_bytes += blocksize; } return number_of_codes; } /************************************************* * Get the number of serialized patterns * *************************************************/ PCRE2_EXP_DEFN int32_t PCRE2_CALL_CONVENTION pcre2_serialize_get_number_of_codes(const uint8_t *bytes) { const pcre2_serialized_data *data = (const pcre2_serialized_data *)bytes; if (data == NULL) return PCRE2_ERROR_NULL; if (data->magic != SERIALIZED_DATA_MAGIC) return PCRE2_ERROR_BADMAGIC; if (data->version != SERIALIZED_DATA_VERSION) return PCRE2_ERROR_BADMODE; if (data->config != SERIALIZED_DATA_CONFIG) return PCRE2_ERROR_BADMODE; return data->number_of_codes; } /************************************************* * Free the allocated stream * *************************************************/ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_serialize_free(uint8_t *bytes) { if (bytes != NULL) { pcre2_memctl *memctl = (pcre2_memctl *)(bytes - sizeof(pcre2_memctl)); memctl->free(memctl, memctl->memory_data); } } /* End of pcre2_serialize.c */
10,048
34.013937
81
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_string_utils.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2018-2021 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains internal functions for comparing and finding the length of strings. These are used instead of strcmp() etc because the standard functions work only on 8-bit data. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Emulated memmove() for systems without it * *************************************************/ /* This function can make use of bcopy() if it is available. Otherwise do it by steam, as there some non-Unix environments that lack both memmove() and bcopy(). */ #if !defined(VPCOMPAT) && !defined(HAVE_MEMMOVE) void * PRIV(memmove)(void *d, const void *s, size_t n) { #ifdef HAVE_BCOPY bcopy(s, d, n); return d; #else size_t i; unsigned char *dest = (unsigned char *)d; const unsigned char *src = (const unsigned char *)s; if (dest > src) { dest += n; src += n; for (i = 0; i < n; ++i) *(--dest) = *(--src); return (void *)dest; } else { for (i = 0; i < n; ++i) *dest++ = *src++; return (void *)(dest - n); } #endif /* not HAVE_BCOPY */ } #endif /* not VPCOMPAT && not HAVE_MEMMOVE */ /************************************************* * Compare two zero-terminated PCRE2 strings * *************************************************/ /* Arguments: str1 first string str2 second string Returns: 0, 1, or -1 */ int PRIV(strcmp)(PCRE2_SPTR str1, PCRE2_SPTR str2) { PCRE2_UCHAR c1, c2; while (*str1 != '\0' || *str2 != '\0') { c1 = *str1++; c2 = *str2++; if (c1 != c2) return ((c1 > c2) << 1) - 1; } return 0; } /************************************************* * Compare zero-terminated PCRE2 & 8-bit strings * *************************************************/ /* As the 8-bit string is almost always a literal, its type is specified as const char *. Arguments: str1 first string str2 second string Returns: 0, 1, or -1 */ int PRIV(strcmp_c8)(PCRE2_SPTR str1, const char *str2) { PCRE2_UCHAR c1, c2; while (*str1 != '\0' || *str2 != '\0') { c1 = *str1++; c2 = *str2++; if (c1 != c2) return ((c1 > c2) << 1) - 1; } return 0; } /************************************************* * Compare two PCRE2 strings, given a length * *************************************************/ /* Arguments: str1 first string str2 second string len the length Returns: 0, 1, or -1 */ int PRIV(strncmp)(PCRE2_SPTR str1, PCRE2_SPTR str2, size_t len) { PCRE2_UCHAR c1, c2; for (; len > 0; len--) { c1 = *str1++; c2 = *str2++; if (c1 != c2) return ((c1 > c2) << 1) - 1; } return 0; } /************************************************* * Compare PCRE2 string to 8-bit string by length * *************************************************/ /* As the 8-bit string is almost always a literal, its type is specified as const char *. Arguments: str1 first string str2 second string len the length Returns: 0, 1, or -1 */ int PRIV(strncmp_c8)(PCRE2_SPTR str1, const char *str2, size_t len) { PCRE2_UCHAR c1, c2; for (; len > 0; len--) { c1 = *str1++; c2 = *str2++; if (c1 != c2) return ((c1 > c2) << 1) - 1; } return 0; } /************************************************* * Find the length of a PCRE2 string * *************************************************/ /* Argument: the string Returns: the length */ PCRE2_SIZE PRIV(strlen)(PCRE2_SPTR str) { PCRE2_SIZE c = 0; while (*str++ != 0) c++; return c; } /************************************************* * Copy 8-bit 0-terminated string to PCRE2 string * *************************************************/ /* Arguments: str1 buffer to receive the string str2 8-bit string to be copied Returns: the number of code units used (excluding trailing zero) */ PCRE2_SIZE PRIV(strcpy_c8)(PCRE2_UCHAR *str1, const char *str2) { PCRE2_UCHAR *t = str1; while (*str2 != 0) *t++ = *str2++; *t = 0; return t - str1; } /* End of pcre2_string_utils.c */
6,166
24.911765
79
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_substring.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2018 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Copy named captured string to given buffer * *************************************************/ /* This function copies a single captured substring into a given buffer, identifying it by name. If the regex permits duplicate names, the first substring that is set is chosen. Arguments: match_data points to the match data stringname the name of the required substring buffer where to put the substring sizeptr the size of the buffer, updated to the size of the substring Returns: if successful: zero if not successful, a negative error code: (1) an error from nametable_scan() (2) an error from copy_bynumber() (3) PCRE2_ERROR_UNAVAILABLE: no group is in ovector (4) PCRE2_ERROR_UNSET: all named groups in ovector are unset */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_copy_byname(pcre2_match_data *match_data, PCRE2_SPTR stringname, PCRE2_UCHAR *buffer, PCRE2_SIZE *sizeptr) { PCRE2_SPTR first, last, entry; int failrc, entrysize; if (match_data->matchedby == PCRE2_MATCHEDBY_DFA_INTERPRETER) return PCRE2_ERROR_DFA_UFUNC; entrysize = pcre2_substring_nametable_scan(match_data->code, stringname, &first, &last); if (entrysize < 0) return entrysize; failrc = PCRE2_ERROR_UNAVAILABLE; for (entry = first; entry <= last; entry += entrysize) { uint32_t n = GET2(entry, 0); if (n < match_data->oveccount) { if (match_data->ovector[n*2] != PCRE2_UNSET) return pcre2_substring_copy_bynumber(match_data, n, buffer, sizeptr); failrc = PCRE2_ERROR_UNSET; } } return failrc; } /************************************************* * Copy numbered captured string to given buffer * *************************************************/ /* This function copies a single captured substring into a given buffer, identifying it by number. Arguments: match_data points to the match data stringnumber the number of the required substring buffer where to put the substring sizeptr the size of the buffer, updated to the size of the substring Returns: if successful: 0 if not successful, a negative error code: PCRE2_ERROR_NOMEMORY: buffer too small PCRE2_ERROR_NOSUBSTRING: no such substring PCRE2_ERROR_UNAVAILABLE: ovector too small PCRE2_ERROR_UNSET: substring is not set */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_copy_bynumber(pcre2_match_data *match_data, uint32_t stringnumber, PCRE2_UCHAR *buffer, PCRE2_SIZE *sizeptr) { int rc; PCRE2_SIZE size; rc = pcre2_substring_length_bynumber(match_data, stringnumber, &size); if (rc < 0) return rc; if (size + 1 > *sizeptr) return PCRE2_ERROR_NOMEMORY; memcpy(buffer, match_data->subject + match_data->ovector[stringnumber*2], CU2BYTES(size)); buffer[size] = 0; *sizeptr = size; return 0; } /************************************************* * Extract named captured string * *************************************************/ /* This function copies a single captured substring, identified by name, into new memory. If the regex permits duplicate names, the first substring that is set is chosen. Arguments: match_data pointer to match_data stringname the name of the required substring stringptr where to put the pointer to the new memory sizeptr where to put the length of the substring Returns: if successful: zero if not successful, a negative value: (1) an error from nametable_scan() (2) an error from get_bynumber() (3) PCRE2_ERROR_UNAVAILABLE: no group is in ovector (4) PCRE2_ERROR_UNSET: all named groups in ovector are unset */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_get_byname(pcre2_match_data *match_data, PCRE2_SPTR stringname, PCRE2_UCHAR **stringptr, PCRE2_SIZE *sizeptr) { PCRE2_SPTR first, last, entry; int failrc, entrysize; if (match_data->matchedby == PCRE2_MATCHEDBY_DFA_INTERPRETER) return PCRE2_ERROR_DFA_UFUNC; entrysize = pcre2_substring_nametable_scan(match_data->code, stringname, &first, &last); if (entrysize < 0) return entrysize; failrc = PCRE2_ERROR_UNAVAILABLE; for (entry = first; entry <= last; entry += entrysize) { uint32_t n = GET2(entry, 0); if (n < match_data->oveccount) { if (match_data->ovector[n*2] != PCRE2_UNSET) return pcre2_substring_get_bynumber(match_data, n, stringptr, sizeptr); failrc = PCRE2_ERROR_UNSET; } } return failrc; } /************************************************* * Extract captured string to new memory * *************************************************/ /* This function copies a single captured substring into a piece of new memory. Arguments: match_data points to match data stringnumber the number of the required substring stringptr where to put a pointer to the new memory sizeptr where to put the size of the substring Returns: if successful: 0 if not successful, a negative error code: PCRE2_ERROR_NOMEMORY: failed to get memory PCRE2_ERROR_NOSUBSTRING: no such substring PCRE2_ERROR_UNAVAILABLE: ovector too small PCRE2_ERROR_UNSET: substring is not set */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_get_bynumber(pcre2_match_data *match_data, uint32_t stringnumber, PCRE2_UCHAR **stringptr, PCRE2_SIZE *sizeptr) { int rc; PCRE2_SIZE size; PCRE2_UCHAR *yield; rc = pcre2_substring_length_bynumber(match_data, stringnumber, &size); if (rc < 0) return rc; yield = PRIV(memctl_malloc)(sizeof(pcre2_memctl) + (size + 1)*PCRE2_CODE_UNIT_WIDTH, (pcre2_memctl *)match_data); if (yield == NULL) return PCRE2_ERROR_NOMEMORY; yield = (PCRE2_UCHAR *)(((char *)yield) + sizeof(pcre2_memctl)); memcpy(yield, match_data->subject + match_data->ovector[stringnumber*2], CU2BYTES(size)); yield[size] = 0; *stringptr = yield; *sizeptr = size; return 0; } /************************************************* * Free memory obtained by get_substring * *************************************************/ /* Argument: the result of a previous pcre2_substring_get_byxxx() Returns: nothing */ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_substring_free(PCRE2_UCHAR *string) { if (string != NULL) { pcre2_memctl *memctl = (pcre2_memctl *)((char *)string - sizeof(pcre2_memctl)); memctl->free(memctl, memctl->memory_data); } } /************************************************* * Get length of a named substring * *************************************************/ /* This function returns the length of a named captured substring. If the regex permits duplicate names, the first substring that is set is chosen. Arguments: match_data pointer to match data stringname the name of the required substring sizeptr where to put the length Returns: 0 if successful, else a negative error number */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_length_byname(pcre2_match_data *match_data, PCRE2_SPTR stringname, PCRE2_SIZE *sizeptr) { PCRE2_SPTR first, last, entry; int failrc, entrysize; if (match_data->matchedby == PCRE2_MATCHEDBY_DFA_INTERPRETER) return PCRE2_ERROR_DFA_UFUNC; entrysize = pcre2_substring_nametable_scan(match_data->code, stringname, &first, &last); if (entrysize < 0) return entrysize; failrc = PCRE2_ERROR_UNAVAILABLE; for (entry = first; entry <= last; entry += entrysize) { uint32_t n = GET2(entry, 0); if (n < match_data->oveccount) { if (match_data->ovector[n*2] != PCRE2_UNSET) return pcre2_substring_length_bynumber(match_data, n, sizeptr); failrc = PCRE2_ERROR_UNSET; } } return failrc; } /************************************************* * Get length of a numbered substring * *************************************************/ /* This function returns the length of a captured substring. If the start is beyond the end (which can happen when \K is used in an assertion), it sets the length to zero. Arguments: match_data pointer to match data stringnumber the number of the required substring sizeptr where to put the length, if not NULL Returns: if successful: 0 if not successful, a negative error code: PCRE2_ERROR_NOSUBSTRING: no such substring PCRE2_ERROR_UNAVAILABLE: ovector is too small PCRE2_ERROR_UNSET: substring is not set */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_length_bynumber(pcre2_match_data *match_data, uint32_t stringnumber, PCRE2_SIZE *sizeptr) { PCRE2_SIZE left, right; int count = match_data->rc; if (count == PCRE2_ERROR_PARTIAL) { if (stringnumber > 0) return PCRE2_ERROR_PARTIAL; count = 0; } else if (count < 0) return count; /* Match failed */ if (match_data->matchedby != PCRE2_MATCHEDBY_DFA_INTERPRETER) { if (stringnumber > match_data->code->top_bracket) return PCRE2_ERROR_NOSUBSTRING; if (stringnumber >= match_data->oveccount) return PCRE2_ERROR_UNAVAILABLE; if (match_data->ovector[stringnumber*2] == PCRE2_UNSET) return PCRE2_ERROR_UNSET; } else /* Matched using pcre2_dfa_match() */ { if (stringnumber >= match_data->oveccount) return PCRE2_ERROR_UNAVAILABLE; if (count != 0 && stringnumber >= (uint32_t)count) return PCRE2_ERROR_UNSET; } left = match_data->ovector[stringnumber*2]; right = match_data->ovector[stringnumber*2+1]; if (sizeptr != NULL) *sizeptr = (left > right)? 0 : right - left; return 0; } /************************************************* * Extract all captured strings to new memory * *************************************************/ /* This function gets one chunk of memory and builds a list of pointers and all the captured substrings in it. A NULL pointer is put on the end of the list. The substrings are zero-terminated, but also, if the final argument is non-NULL, a list of lengths is also returned. This allows binary data to be handled. Arguments: match_data points to the match data listptr set to point to the list of pointers lengthsptr set to point to the list of lengths (may be NULL) Returns: if successful: 0 if not successful, a negative error code: PCRE2_ERROR_NOMEMORY: failed to get memory, or a match failure code */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_list_get(pcre2_match_data *match_data, PCRE2_UCHAR ***listptr, PCRE2_SIZE **lengthsptr) { int i, count, count2; PCRE2_SIZE size; PCRE2_SIZE *lensp; pcre2_memctl *memp; PCRE2_UCHAR **listp; PCRE2_UCHAR *sp; PCRE2_SIZE *ovector; if ((count = match_data->rc) < 0) return count; /* Match failed */ if (count == 0) count = match_data->oveccount; /* Ovector too small */ count2 = 2*count; ovector = match_data->ovector; size = sizeof(pcre2_memctl) + sizeof(PCRE2_UCHAR *); /* For final NULL */ if (lengthsptr != NULL) size += sizeof(PCRE2_SIZE) * count; /* For lengths */ for (i = 0; i < count2; i += 2) { size += sizeof(PCRE2_UCHAR *) + CU2BYTES(1); if (ovector[i+1] > ovector[i]) size += CU2BYTES(ovector[i+1] - ovector[i]); } memp = PRIV(memctl_malloc)(size, (pcre2_memctl *)match_data); if (memp == NULL) return PCRE2_ERROR_NOMEMORY; *listptr = listp = (PCRE2_UCHAR **)((char *)memp + sizeof(pcre2_memctl)); lensp = (PCRE2_SIZE *)((char *)listp + sizeof(PCRE2_UCHAR *) * (count + 1)); if (lengthsptr == NULL) { sp = (PCRE2_UCHAR *)lensp; lensp = NULL; } else { *lengthsptr = lensp; sp = (PCRE2_UCHAR *)((char *)lensp + sizeof(PCRE2_SIZE) * count); } for (i = 0; i < count2; i += 2) { size = (ovector[i+1] > ovector[i])? (ovector[i+1] - ovector[i]) : 0; /* Size == 0 includes the case when the capture is unset. Avoid adding PCRE2_UNSET to match_data->subject because it overflows, even though with zero size calling memcpy() is harmless. */ if (size != 0) memcpy(sp, match_data->subject + ovector[i], CU2BYTES(size)); *listp++ = sp; if (lensp != NULL) *lensp++ = size; sp += size; *sp++ = 0; } *listp = NULL; return 0; } /************************************************* * Free memory obtained by substring_list_get * *************************************************/ /* Argument: the result of a previous pcre2_substring_list_get() Returns: nothing */ PCRE2_EXP_DEFN void PCRE2_CALL_CONVENTION pcre2_substring_list_free(PCRE2_SPTR *list) { if (list != NULL) { pcre2_memctl *memctl = (pcre2_memctl *)((char *)list - sizeof(pcre2_memctl)); memctl->free(memctl, memctl->memory_data); } } /************************************************* * Find (multiple) entries for named string * *************************************************/ /* This function scans the nametable for a given name, using binary chop. It returns either two pointers to the entries in the table, or, if no pointers are given, the number of a unique group with the given name. If duplicate names are permitted, and the name is not unique, an error is generated. Arguments: code the compiled regex stringname the name whose entries required firstptr where to put the pointer to the first entry lastptr where to put the pointer to the last entry Returns: PCRE2_ERROR_NOSUBSTRING if the name is not found otherwise, if firstptr and lastptr are NULL: a group number for a unique substring else PCRE2_ERROR_NOUNIQUESUBSTRING otherwise: the length of each entry, having set firstptr and lastptr */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_nametable_scan(const pcre2_code *code, PCRE2_SPTR stringname, PCRE2_SPTR *firstptr, PCRE2_SPTR *lastptr) { uint16_t bot = 0; uint16_t top = code->name_count; uint16_t entrysize = code->name_entry_size; PCRE2_SPTR nametable = (PCRE2_SPTR)((char *)code + sizeof(pcre2_real_code)); while (top > bot) { uint16_t mid = (top + bot) / 2; PCRE2_SPTR entry = nametable + entrysize*mid; int c = PRIV(strcmp)(stringname, entry + IMM2_SIZE); if (c == 0) { PCRE2_SPTR first; PCRE2_SPTR last; PCRE2_SPTR lastentry; lastentry = nametable + entrysize * (code->name_count - 1); first = last = entry; while (first > nametable) { if (PRIV(strcmp)(stringname, (first - entrysize + IMM2_SIZE)) != 0) break; first -= entrysize; } while (last < lastentry) { if (PRIV(strcmp)(stringname, (last + entrysize + IMM2_SIZE)) != 0) break; last += entrysize; } if (firstptr == NULL) return (first == last)? (int)GET2(entry, 0) : PCRE2_ERROR_NOUNIQUESUBSTRING; *firstptr = first; *lastptr = last; return entrysize; } if (c > 0) bot = mid + 1; else top = mid; } return PCRE2_ERROR_NOSUBSTRING; } /************************************************* * Find number for named string * *************************************************/ /* This function is a convenience wrapper for pcre2_substring_nametable_scan() when it is known that names are unique. If there are duplicate names, it is not defined which number is returned. Arguments: code the compiled regex stringname the name whose number is required Returns: the number of the named parenthesis, or a negative number PCRE2_ERROR_NOSUBSTRING if not found PCRE2_ERROR_NOUNIQUESUBSTRING if not unique */ PCRE2_EXP_DEFN int PCRE2_CALL_CONVENTION pcre2_substring_number_from_name(const pcre2_code *code, PCRE2_SPTR stringname) { return pcre2_substring_nametable_scan(code, stringname, NULL, NULL); } /* End of pcre2_substring.c */
18,244
32.293796
81
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_tables.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2021 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains some fixed tables that are used by more than one of the PCRE2 code modules. The tables are also #included by the pcre2test program, which uses macros to change their names from _pcre2_xxx to xxxx, thereby avoiding name clashes with the library. In this case, PCRE2_PCRE2TEST is defined. */ #ifndef PCRE2_PCRE2TEST /* We're compiling the library */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" #endif /* PCRE2_PCRE2TEST */ /* Table of sizes for the fixed-length opcodes. It's defined in a macro so that the definition is next to the definition of the opcodes in pcre2_internal.h. This is mode-dependent, so it is skipped when this file is included by pcre2test. */ #ifndef PCRE2_PCRE2TEST const uint8_t PRIV(OP_lengths)[] = { OP_LENGTHS }; #endif /* Tables of horizontal and vertical whitespace characters, suitable for adding to classes. */ const uint32_t PRIV(hspace_list)[] = { HSPACE_LIST }; const uint32_t PRIV(vspace_list)[] = { VSPACE_LIST }; /* These tables are the pairs of delimiters that are valid for callout string arguments. For each starting delimiter there must be a matching ending delimiter, which in fact is different only for bracket-like delimiters. */ const uint32_t PRIV(callout_start_delims)[] = { CHAR_GRAVE_ACCENT, CHAR_APOSTROPHE, CHAR_QUOTATION_MARK, CHAR_CIRCUMFLEX_ACCENT, CHAR_PERCENT_SIGN, CHAR_NUMBER_SIGN, CHAR_DOLLAR_SIGN, CHAR_LEFT_CURLY_BRACKET, 0 }; const uint32_t PRIV(callout_end_delims[]) = { CHAR_GRAVE_ACCENT, CHAR_APOSTROPHE, CHAR_QUOTATION_MARK, CHAR_CIRCUMFLEX_ACCENT, CHAR_PERCENT_SIGN, CHAR_NUMBER_SIGN, CHAR_DOLLAR_SIGN, CHAR_RIGHT_CURLY_BRACKET, 0 }; /************************************************* * Tables for UTF-8 support * *************************************************/ /* These tables are required by pcre2test in 16- or 32-bit mode, as well as for the library in 8-bit mode, because pcre2test uses UTF-8 internally for handling wide characters. */ #if defined PCRE2_PCRE2TEST || \ (defined SUPPORT_UNICODE && \ defined PCRE2_CODE_UNIT_WIDTH && \ PCRE2_CODE_UNIT_WIDTH == 8) /* These are the breakpoints for different numbers of bytes in a UTF-8 character. */ const int PRIV(utf8_table1)[] = { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; const int PRIV(utf8_table1_size) = sizeof(PRIV(utf8_table1)) / sizeof(int); /* These are the indicator bits and the mask for the data bits to set in the first byte of a character, indexed by the number of additional bytes. */ const int PRIV(utf8_table2)[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; const int PRIV(utf8_table3)[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; /* Table of the number of extra bytes, indexed by the first byte masked with 0x3f. The highest number for a valid UTF-8 first byte is in fact 0x3d. */ const uint8_t PRIV(utf8_table4)[] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; #endif /* UTF-8 support needed */ /* Tables concerned with Unicode properties are relevant only when Unicode support is enabled. See also the pcre2_ucptables.c file, which is generated by a Python script from Unicode data files. */ #ifdef SUPPORT_UNICODE /* Table to translate from particular type value to the general value. */ const uint32_t PRIV(ucp_gentype)[] = { ucp_C, ucp_C, ucp_C, ucp_C, ucp_C, /* Cc, Cf, Cn, Co, Cs */ ucp_L, ucp_L, ucp_L, ucp_L, ucp_L, /* Ll, Lu, Lm, Lo, Lt */ ucp_M, ucp_M, ucp_M, /* Mc, Me, Mn */ ucp_N, ucp_N, ucp_N, /* Nd, Nl, No */ ucp_P, ucp_P, ucp_P, ucp_P, ucp_P, /* Pc, Pd, Pe, Pf, Pi */ ucp_P, ucp_P, /* Ps, Po */ ucp_S, ucp_S, ucp_S, ucp_S, /* Sc, Sk, Sm, So */ ucp_Z, ucp_Z, ucp_Z /* Zl, Zp, Zs */ }; /* This table encodes the rules for finding the end of an extended grapheme cluster. Every code point has a grapheme break property which is one of the ucp_gbXX values defined in pcre2_ucp.h. These changed between Unicode versions 10 and 11. The 2-dimensional table is indexed by the properties of two adjacent code points. The left property selects a word from the table, and the right property selects a bit from that word like this: PRIV(ucp_gbtable)[left-property] & (1u << right-property) The value is non-zero if a grapheme break is NOT permitted between the relevant two code points. The breaking rules are as follows: 1. Break at the start and end of text (pretty obviously). 2. Do not break between a CR and LF; otherwise, break before and after controls. 3. Do not break Hangul syllable sequences, the rules for which are: L may be followed by L, V, LV or LVT LV or V may be followed by V or T LVT or T may be followed by T 4. Do not break before extending characters or zero-width-joiner (ZWJ). The following rules are only for extended grapheme clusters (but that's what we are implementing). 5. Do not break before SpacingMarks. 6. Do not break after Prepend characters. 7. Do not break within emoji modifier sequences or emoji zwj sequences. That is, do not break between characters with the Extended_Pictographic property. Extend and ZWJ characters are allowed between the characters; this cannot be represented in this table, the code has to deal with it. 8. Do not break within emoji flag sequences. That is, do not break between regional indicator (RI) symbols if there are an odd number of RI characters before the break point. This table encodes "join RI characters"; the code has to deal with checking for previous adjoining RIs. 9. Otherwise, break everywhere. */ #define ESZ (1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbZWJ) const uint32_t PRIV(ucp_gbtable)[] = { (1u<<ucp_gbLF), /* 0 CR */ 0, /* 1 LF */ 0, /* 2 Control */ ESZ, /* 3 Extend */ ESZ|(1u<<ucp_gbPrepend)| /* 4 Prepend */ (1u<<ucp_gbL)|(1u<<ucp_gbV)|(1u<<ucp_gbT)| (1u<<ucp_gbLV)|(1u<<ucp_gbLVT)|(1u<<ucp_gbOther)| (1u<<ucp_gbRegional_Indicator), ESZ, /* 5 SpacingMark */ ESZ|(1u<<ucp_gbL)|(1u<<ucp_gbV)|(1u<<ucp_gbLV)| /* 6 L */ (1u<<ucp_gbLVT), ESZ|(1u<<ucp_gbV)|(1u<<ucp_gbT), /* 7 V */ ESZ|(1u<<ucp_gbT), /* 8 T */ ESZ|(1u<<ucp_gbV)|(1u<<ucp_gbT), /* 9 LV */ ESZ|(1u<<ucp_gbT), /* 10 LVT */ (1u<<ucp_gbRegional_Indicator), /* 11 Regional Indicator */ ESZ, /* 12 Other */ ESZ, /* 13 ZWJ */ ESZ|(1u<<ucp_gbExtended_Pictographic) /* 14 Extended Pictographic */ }; #undef ESZ #ifdef SUPPORT_JIT /* This table reverses PRIV(ucp_gentype). We can save the cost of a memory load. */ const int PRIV(ucp_typerange)[] = { ucp_Cc, ucp_Cs, ucp_Ll, ucp_Lu, ucp_Mc, ucp_Mn, ucp_Nd, ucp_No, ucp_Pc, ucp_Ps, ucp_Sc, ucp_So, ucp_Zl, ucp_Zs, }; #endif /* SUPPORT_JIT */ /* Finally, include the tables that are auto-generated from the Unicode data files. */ #include "pcre2_ucptables.c" #endif /* SUPPORT_UNICODE */ /* End of pcre2_tables.c */
9,690
40.238298
86
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_ucp.h
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2022 University of Cambridge This module is auto-generated from Unicode data files. DO NOT EDIT MANUALLY! Instead, modify the maint/GenerateUcpHeader.py script and run it to generate a new version of this code. ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ #ifndef PCRE2_UCP_H_IDEMPOTENT_GUARD #define PCRE2_UCP_H_IDEMPOTENT_GUARD /* This file contains definitions of the Unicode property values that are returned by the UCD access macros and used throughout PCRE2. IMPORTANT: The specific values of the first two enums (general and particular character categories) are assumed by the table called catposstab in the file pcre2_auto_possess.c. They are unlikely to change, but should be checked after an update. */ /* These are the general character categories. */ enum { ucp_C, ucp_L, ucp_M, ucp_N, ucp_P, ucp_S, ucp_Z, }; /* These are the particular character categories. */ enum { ucp_Cc, /* Control */ ucp_Cf, /* Format */ ucp_Cn, /* Unassigned */ ucp_Co, /* Private use */ ucp_Cs, /* Surrogate */ ucp_Ll, /* Lower case letter */ ucp_Lm, /* Modifier letter */ ucp_Lo, /* Other letter */ ucp_Lt, /* Title case letter */ ucp_Lu, /* Upper case letter */ ucp_Mc, /* Spacing mark */ ucp_Me, /* Enclosing mark */ ucp_Mn, /* Non-spacing mark */ ucp_Nd, /* Decimal number */ ucp_Nl, /* Letter number */ ucp_No, /* Other number */ ucp_Pc, /* Connector punctuation */ ucp_Pd, /* Dash punctuation */ ucp_Pe, /* Close punctuation */ ucp_Pf, /* Final punctuation */ ucp_Pi, /* Initial punctuation */ ucp_Po, /* Other punctuation */ ucp_Ps, /* Open punctuation */ ucp_Sc, /* Currency symbol */ ucp_Sk, /* Modifier symbol */ ucp_Sm, /* Mathematical symbol */ ucp_So, /* Other symbol */ ucp_Zl, /* Line separator */ ucp_Zp, /* Paragraph separator */ ucp_Zs, /* Space separator */ }; /* These are Boolean properties. */ enum { ucp_ASCII, ucp_ASCII_Hex_Digit, ucp_Alphabetic, ucp_Bidi_Control, ucp_Bidi_Mirrored, ucp_Case_Ignorable, ucp_Cased, ucp_Changes_When_Casefolded, ucp_Changes_When_Casemapped, ucp_Changes_When_Lowercased, ucp_Changes_When_Titlecased, ucp_Changes_When_Uppercased, ucp_Dash, ucp_Default_Ignorable_Code_Point, ucp_Deprecated, ucp_Diacritic, ucp_Emoji, ucp_Emoji_Component, ucp_Emoji_Modifier, ucp_Emoji_Modifier_Base, ucp_Emoji_Presentation, ucp_Extended_Pictographic, ucp_Extender, ucp_Grapheme_Base, ucp_Grapheme_Extend, ucp_Grapheme_Link, ucp_Hex_Digit, ucp_IDS_Binary_Operator, ucp_IDS_Trinary_Operator, ucp_ID_Continue, ucp_ID_Start, ucp_Ideographic, ucp_Join_Control, ucp_Logical_Order_Exception, ucp_Lowercase, ucp_Math, ucp_Noncharacter_Code_Point, ucp_Pattern_Syntax, ucp_Pattern_White_Space, ucp_Prepended_Concatenation_Mark, ucp_Quotation_Mark, ucp_Radical, ucp_Regional_Indicator, ucp_Sentence_Terminal, ucp_Soft_Dotted, ucp_Terminal_Punctuation, ucp_Unified_Ideograph, ucp_Uppercase, ucp_Variation_Selector, ucp_White_Space, ucp_XID_Continue, ucp_XID_Start, /* This must be last */ ucp_Bprop_Count }; /* Size of entries in ucd_boolprop_sets[] */ #define ucd_boolprop_sets_item_size 2 /* These are the bidi class values. */ enum { ucp_bidiAL, /* Arabic letter */ ucp_bidiAN, /* Arabic number */ ucp_bidiB, /* Paragraph separator */ ucp_bidiBN, /* Boundary neutral */ ucp_bidiCS, /* Common separator */ ucp_bidiEN, /* European number */ ucp_bidiES, /* European separator */ ucp_bidiET, /* European terminator */ ucp_bidiFSI, /* First strong isolate */ ucp_bidiL, /* Left to right */ ucp_bidiLRE, /* Left to right embedding */ ucp_bidiLRI, /* Left to right isolate */ ucp_bidiLRO, /* Left to right override */ ucp_bidiNSM, /* Non-spacing mark */ ucp_bidiON, /* Other neutral */ ucp_bidiPDF, /* Pop directional format */ ucp_bidiPDI, /* Pop directional isolate */ ucp_bidiR, /* Right to left */ ucp_bidiRLE, /* Right to left embedding */ ucp_bidiRLI, /* Right to left isolate */ ucp_bidiRLO, /* Right to left override */ ucp_bidiS, /* Segment separator */ ucp_bidiWS, /* White space */ }; /* These are grapheme break properties. The Extended Pictographic property comes from the emoji-data.txt file. */ enum { ucp_gbCR, /* 0 */ ucp_gbLF, /* 1 */ ucp_gbControl, /* 2 */ ucp_gbExtend, /* 3 */ ucp_gbPrepend, /* 4 */ ucp_gbSpacingMark, /* 5 */ ucp_gbL, /* 6 Hangul syllable type L */ ucp_gbV, /* 7 Hangul syllable type V */ ucp_gbT, /* 8 Hangul syllable type T */ ucp_gbLV, /* 9 Hangul syllable type LV */ ucp_gbLVT, /* 10 Hangul syllable type LVT */ ucp_gbRegional_Indicator, /* 11 */ ucp_gbOther, /* 12 */ ucp_gbZWJ, /* 13 */ ucp_gbExtended_Pictographic, /* 14 */ }; /* These are the script identifications. */ enum { /* Scripts which has characters in other scripts. */ ucp_Latin, ucp_Greek, ucp_Cyrillic, ucp_Arabic, ucp_Syriac, ucp_Thaana, ucp_Devanagari, ucp_Bengali, ucp_Gurmukhi, ucp_Gujarati, ucp_Oriya, ucp_Tamil, ucp_Telugu, ucp_Kannada, ucp_Malayalam, ucp_Sinhala, ucp_Myanmar, ucp_Georgian, ucp_Hangul, ucp_Mongolian, ucp_Hiragana, ucp_Katakana, ucp_Bopomofo, ucp_Han, ucp_Yi, ucp_Tagalog, ucp_Hanunoo, ucp_Buhid, ucp_Tagbanwa, ucp_Limbu, ucp_Tai_Le, ucp_Linear_B, ucp_Cypriot, ucp_Buginese, ucp_Coptic, ucp_Glagolitic, ucp_Syloti_Nagri, ucp_Phags_Pa, ucp_Nko, ucp_Kayah_Li, ucp_Javanese, ucp_Kaithi, ucp_Mandaic, ucp_Chakma, ucp_Sharada, ucp_Takri, ucp_Duployan, ucp_Grantha, ucp_Khojki, ucp_Linear_A, ucp_Mahajani, ucp_Manichaean, ucp_Modi, ucp_Old_Permic, ucp_Psalter_Pahlavi, ucp_Khudawadi, ucp_Tirhuta, ucp_Multani, ucp_Adlam, ucp_Masaram_Gondi, ucp_Dogra, ucp_Gunjala_Gondi, ucp_Hanifi_Rohingya, ucp_Sogdian, ucp_Nandinagari, ucp_Yezidi, ucp_Cypro_Minoan, ucp_Old_Uyghur, /* Scripts which has no characters in other scripts. */ ucp_Unknown, ucp_Common, ucp_Armenian, ucp_Hebrew, ucp_Thai, ucp_Lao, ucp_Tibetan, ucp_Ethiopic, ucp_Cherokee, ucp_Canadian_Aboriginal, ucp_Ogham, ucp_Runic, ucp_Khmer, ucp_Old_Italic, ucp_Gothic, ucp_Deseret, ucp_Inherited, ucp_Ugaritic, ucp_Shavian, ucp_Osmanya, ucp_Braille, ucp_New_Tai_Lue, ucp_Tifinagh, ucp_Old_Persian, ucp_Kharoshthi, ucp_Balinese, ucp_Cuneiform, ucp_Phoenician, ucp_Sundanese, ucp_Lepcha, ucp_Ol_Chiki, ucp_Vai, ucp_Saurashtra, ucp_Rejang, ucp_Lycian, ucp_Carian, ucp_Lydian, ucp_Cham, ucp_Tai_Tham, ucp_Tai_Viet, ucp_Avestan, ucp_Egyptian_Hieroglyphs, ucp_Samaritan, ucp_Lisu, ucp_Bamum, ucp_Meetei_Mayek, ucp_Imperial_Aramaic, ucp_Old_South_Arabian, ucp_Inscriptional_Parthian, ucp_Inscriptional_Pahlavi, ucp_Old_Turkic, ucp_Batak, ucp_Brahmi, ucp_Meroitic_Cursive, ucp_Meroitic_Hieroglyphs, ucp_Miao, ucp_Sora_Sompeng, ucp_Caucasian_Albanian, ucp_Bassa_Vah, ucp_Elbasan, ucp_Pahawh_Hmong, ucp_Mende_Kikakui, ucp_Mro, ucp_Old_North_Arabian, ucp_Nabataean, ucp_Palmyrene, ucp_Pau_Cin_Hau, ucp_Siddham, ucp_Warang_Citi, ucp_Ahom, ucp_Anatolian_Hieroglyphs, ucp_Hatran, ucp_Old_Hungarian, ucp_SignWriting, ucp_Bhaiksuki, ucp_Marchen, ucp_Newa, ucp_Osage, ucp_Tangut, ucp_Nushu, ucp_Soyombo, ucp_Zanabazar_Square, ucp_Makasar, ucp_Medefaidrin, ucp_Old_Sogdian, ucp_Elymaic, ucp_Nyiakeng_Puachue_Hmong, ucp_Wancho, ucp_Chorasmian, ucp_Dives_Akuru, ucp_Khitan_Small_Script, ucp_Tangsa, ucp_Toto, ucp_Vithkuqi, /* This must be last */ ucp_Script_Count }; /* Size of entries in ucd_script_sets[] */ #define ucd_script_sets_item_size 3 #endif /* PCRE2_UCP_H_IDEMPOTENT_GUARD */ /* End of pcre2_ucp.h */
10,214
24.860759
78
h
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_valid_utf.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2020 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains an internal function for validating UTF character strings. This file is also #included by the pcre2test program, which uses macros to change names from _pcre2_xxx to xxxx, thereby avoiding name clashes with the library. In this case, PCRE2_PCRE2TEST is defined. */ #ifndef PCRE2_PCRE2TEST /* We're compiling the library */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" #endif /* PCRE2_PCRE2TEST */ #ifndef SUPPORT_UNICODE /************************************************* * Dummy function when Unicode is not supported * *************************************************/ /* This function should never be called when Unicode is not supported. */ int PRIV(valid_utf)(PCRE2_SPTR string, PCRE2_SIZE length, PCRE2_SIZE *erroroffset) { (void)string; (void)length; (void)erroroffset; return 0; } #else /* UTF is supported */ /************************************************* * Validate a UTF string * *************************************************/ /* This function is called (optionally) at the start of compile or match, to check that a supposed UTF string is actually valid. The early check means that subsequent code can assume it is dealing with a valid string. The check can be turned off for maximum performance, but the consequences of supplying an invalid string are then undefined. Arguments: string points to the string length length of string errp pointer to an error position offset variable Returns: == 0 if the string is a valid UTF string != 0 otherwise, setting the offset of the bad character */ int PRIV(valid_utf)(PCRE2_SPTR string, PCRE2_SIZE length, PCRE2_SIZE *erroroffset) { PCRE2_SPTR p; uint32_t c; /* ----------------- Check a UTF-8 string ----------------- */ #if PCRE2_CODE_UNIT_WIDTH == 8 /* Originally, this function checked according to RFC 2279, allowing for values in the range 0 to 0x7fffffff, up to 6 bytes long, but ensuring that they were in the canonical format. Once somebody had pointed out RFC 3629 to me (it obsoletes 2279), additional restrictions were applied. The values are now limited to be between 0 and 0x0010ffff, no more than 4 bytes long, and the subrange 0xd000 to 0xdfff is excluded. However, the format of 5-byte and 6-byte characters is still checked. Error returns are as follows: PCRE2_ERROR_UTF8_ERR1 Missing 1 byte at the end of the string PCRE2_ERROR_UTF8_ERR2 Missing 2 bytes at the end of the string PCRE2_ERROR_UTF8_ERR3 Missing 3 bytes at the end of the string PCRE2_ERROR_UTF8_ERR4 Missing 4 bytes at the end of the string PCRE2_ERROR_UTF8_ERR5 Missing 5 bytes at the end of the string PCRE2_ERROR_UTF8_ERR6 2nd-byte's two top bits are not 0x80 PCRE2_ERROR_UTF8_ERR7 3rd-byte's two top bits are not 0x80 PCRE2_ERROR_UTF8_ERR8 4th-byte's two top bits are not 0x80 PCRE2_ERROR_UTF8_ERR9 5th-byte's two top bits are not 0x80 PCRE2_ERROR_UTF8_ERR10 6th-byte's two top bits are not 0x80 PCRE2_ERROR_UTF8_ERR11 5-byte character is not permitted by RFC 3629 PCRE2_ERROR_UTF8_ERR12 6-byte character is not permitted by RFC 3629 PCRE2_ERROR_UTF8_ERR13 4-byte character with value > 0x10ffff is not permitted PCRE2_ERROR_UTF8_ERR14 3-byte character with value 0xd800-0xdfff is not permitted PCRE2_ERROR_UTF8_ERR15 Overlong 2-byte sequence PCRE2_ERROR_UTF8_ERR16 Overlong 3-byte sequence PCRE2_ERROR_UTF8_ERR17 Overlong 4-byte sequence PCRE2_ERROR_UTF8_ERR18 Overlong 5-byte sequence (won't ever occur) PCRE2_ERROR_UTF8_ERR19 Overlong 6-byte sequence (won't ever occur) PCRE2_ERROR_UTF8_ERR20 Isolated 0x80 byte (not within UTF-8 character) PCRE2_ERROR_UTF8_ERR21 Byte with the illegal value 0xfe or 0xff */ for (p = string; length > 0; p++) { uint32_t ab, d; c = *p; length--; if (c < 128) continue; /* ASCII character */ if (c < 0xc0) /* Isolated 10xx xxxx byte */ { *erroroffset = (PCRE2_SIZE)(p - string); return PCRE2_ERROR_UTF8_ERR20; } if (c >= 0xfe) /* Invalid 0xfe or 0xff bytes */ { *erroroffset = (PCRE2_SIZE)(p - string); return PCRE2_ERROR_UTF8_ERR21; } ab = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes (1-5) */ if (length < ab) /* Missing bytes */ { *erroroffset = (PCRE2_SIZE)(p - string); switch(ab - length) { case 1: return PCRE2_ERROR_UTF8_ERR1; case 2: return PCRE2_ERROR_UTF8_ERR2; case 3: return PCRE2_ERROR_UTF8_ERR3; case 4: return PCRE2_ERROR_UTF8_ERR4; case 5: return PCRE2_ERROR_UTF8_ERR5; } } length -= ab; /* Length remaining */ /* Check top bits in the second byte */ if (((d = *(++p)) & 0xc0) != 0x80) { *erroroffset = (int)(p - string) - 1; return PCRE2_ERROR_UTF8_ERR6; } /* For each length, check that the remaining bytes start with the 0x80 bit set and not the 0x40 bit. Then check for an overlong sequence, and for the excluded range 0xd800 to 0xdfff. */ switch (ab) { /* 2-byte character. No further bytes to check for 0x80. Check first byte for for xx00 000x (overlong sequence). */ case 1: if ((c & 0x3e) == 0) { *erroroffset = (int)(p - string) - 1; return PCRE2_ERROR_UTF8_ERR15; } break; /* 3-byte character. Check third byte for 0x80. Then check first 2 bytes for 1110 0000, xx0x xxxx (overlong sequence) or 1110 1101, 1010 xxxx (0xd800 - 0xdfff) */ case 2: if ((*(++p) & 0xc0) != 0x80) /* Third byte */ { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR7; } if (c == 0xe0 && (d & 0x20) == 0) { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR16; } if (c == 0xed && d >= 0xa0) { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR14; } break; /* 4-byte character. Check 3rd and 4th bytes for 0x80. Then check first 2 bytes for for 1111 0000, xx00 xxxx (overlong sequence), then check for a character greater than 0x0010ffff (f4 8f bf bf) */ case 3: if ((*(++p) & 0xc0) != 0x80) /* Third byte */ { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR7; } if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ { *erroroffset = (int)(p - string) - 3; return PCRE2_ERROR_UTF8_ERR8; } if (c == 0xf0 && (d & 0x30) == 0) { *erroroffset = (int)(p - string) - 3; return PCRE2_ERROR_UTF8_ERR17; } if (c > 0xf4 || (c == 0xf4 && d > 0x8f)) { *erroroffset = (int)(p - string) - 3; return PCRE2_ERROR_UTF8_ERR13; } break; /* 5-byte and 6-byte characters are not allowed by RFC 3629, and will be rejected by the length test below. However, we do the appropriate tests here so that overlong sequences get diagnosed, and also in case there is ever an option for handling these larger code points. */ /* 5-byte character. Check 3rd, 4th, and 5th bytes for 0x80. Then check for 1111 1000, xx00 0xxx */ case 4: if ((*(++p) & 0xc0) != 0x80) /* Third byte */ { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR7; } if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ { *erroroffset = (int)(p - string) - 3; return PCRE2_ERROR_UTF8_ERR8; } if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ { *erroroffset = (int)(p - string) - 4; return PCRE2_ERROR_UTF8_ERR9; } if (c == 0xf8 && (d & 0x38) == 0) { *erroroffset = (int)(p - string) - 4; return PCRE2_ERROR_UTF8_ERR18; } break; /* 6-byte character. Check 3rd-6th bytes for 0x80. Then check for 1111 1100, xx00 00xx. */ case 5: if ((*(++p) & 0xc0) != 0x80) /* Third byte */ { *erroroffset = (int)(p - string) - 2; return PCRE2_ERROR_UTF8_ERR7; } if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ { *erroroffset = (int)(p - string) - 3; return PCRE2_ERROR_UTF8_ERR8; } if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ { *erroroffset = (int)(p - string) - 4; return PCRE2_ERROR_UTF8_ERR9; } if ((*(++p) & 0xc0) != 0x80) /* Sixth byte */ { *erroroffset = (int)(p - string) - 5; return PCRE2_ERROR_UTF8_ERR10; } if (c == 0xfc && (d & 0x3c) == 0) { *erroroffset = (int)(p - string) - 5; return PCRE2_ERROR_UTF8_ERR19; } break; } /* Character is valid under RFC 2279, but 4-byte and 5-byte characters are excluded by RFC 3629. The pointer p is currently at the last byte of the character. */ if (ab > 3) { *erroroffset = (int)(p - string) - ab; return (ab == 4)? PCRE2_ERROR_UTF8_ERR11 : PCRE2_ERROR_UTF8_ERR12; } } return 0; /* ----------------- Check a UTF-16 string ----------------- */ #elif PCRE2_CODE_UNIT_WIDTH == 16 /* There's not so much work, nor so many errors, for UTF-16. PCRE2_ERROR_UTF16_ERR1 Missing low surrogate at the end of the string PCRE2_ERROR_UTF16_ERR2 Invalid low surrogate PCRE2_ERROR_UTF16_ERR3 Isolated low surrogate */ for (p = string; length > 0; p++) { c = *p; length--; if ((c & 0xf800) != 0xd800) { /* Normal UTF-16 code point. Neither high nor low surrogate. */ } else if ((c & 0x0400) == 0) { /* High surrogate. Must be a followed by a low surrogate. */ if (length == 0) { *erroroffset = p - string; return PCRE2_ERROR_UTF16_ERR1; } p++; length--; if ((*p & 0xfc00) != 0xdc00) { *erroroffset = p - string - 1; return PCRE2_ERROR_UTF16_ERR2; } } else { /* Isolated low surrogate. Always an error. */ *erroroffset = p - string; return PCRE2_ERROR_UTF16_ERR3; } } return 0; /* ----------------- Check a UTF-32 string ----------------- */ #else /* There is very little to do for a UTF-32 string. PCRE2_ERROR_UTF32_ERR1 Surrogate character PCRE2_ERROR_UTF32_ERR2 Character > 0x10ffff */ for (p = string; length > 0; length--, p++) { c = *p; if ((c & 0xfffff800u) != 0xd800u) { /* Normal UTF-32 code point. Neither high nor low surrogate. */ if (c > 0x10ffffu) { *erroroffset = p - string; return PCRE2_ERROR_UTF32_ERR2; } } else { /* A surrogate */ *erroroffset = p - string; return PCRE2_ERROR_UTF32_ERR1; } } return 0; #endif /* CODE_UNIT_WIDTH */ } #endif /* SUPPORT_UNICODE */ /* End of pcre2_valid_utf.c */
12,896
31.323308
82
c
php-src
php-src-master/ext/pcre/pcre2lib/pcre2_xclass.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016-2022 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge 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. ----------------------------------------------------------------------------- */ /* This module contains an internal function that is used to match an extended class. It is used by pcre2_auto_possessify() and by both pcre2_match() and pcre2_def_match(). */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre2_internal.h" /************************************************* * Match character against an XCLASS * *************************************************/ /* This function is called to match a character against an extended class that might contain codepoints above 255 and/or Unicode properties. Arguments: c the character data points to the flag code unit of the XCLASS data utf TRUE if in UTF mode Returns: TRUE if character matches, else FALSE */ BOOL PRIV(xclass)(uint32_t c, PCRE2_SPTR data, BOOL utf) { PCRE2_UCHAR t; BOOL negated = (*data & XCL_NOT) != 0; #if PCRE2_CODE_UNIT_WIDTH == 8 /* In 8 bit mode, this must always be TRUE. Help the compiler to know that. */ utf = TRUE; #endif /* Code points < 256 are matched against a bitmap, if one is present. If not, we still carry on, because there may be ranges that start below 256 in the additional data. */ if (c < 256) { if ((*data & XCL_HASPROP) == 0) { if ((*data & XCL_MAP) == 0) return negated; return (((uint8_t *)(data + 1))[c/8] & (1u << (c&7))) != 0; } if ((*data & XCL_MAP) != 0 && (((uint8_t *)(data + 1))[c/8] & (1u << (c&7))) != 0) return !negated; /* char found */ } /* First skip the bit map if present. Then match against the list of Unicode properties or large chars or ranges that end with a large char. We won't ever encounter XCL_PROP or XCL_NOTPROP when UTF support is not compiled. */ if ((*data++ & XCL_MAP) != 0) data += 32 / sizeof(PCRE2_UCHAR); while ((t = *data++) != XCL_END) { uint32_t x, y; if (t == XCL_SINGLE) { #ifdef SUPPORT_UNICODE if (utf) { GETCHARINC(x, data); /* macro generates multiple statements */ } else #endif x = *data++; if (c == x) return !negated; } else if (t == XCL_RANGE) { #ifdef SUPPORT_UNICODE if (utf) { GETCHARINC(x, data); /* macro generates multiple statements */ GETCHARINC(y, data); /* macro generates multiple statements */ } else #endif { x = *data++; y = *data++; } if (c >= x && c <= y) return !negated; } #ifdef SUPPORT_UNICODE else /* XCL_PROP & XCL_NOTPROP */ { const ucd_record *prop = GET_UCD(c); BOOL isprop = t == XCL_PROP; BOOL ok; switch(*data) { case PT_ANY: if (isprop) return !negated; break; case PT_LAMP: if ((prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || prop->chartype == ucp_Lt) == isprop) return !negated; break; case PT_GC: if ((data[1] == PRIV(ucp_gentype)[prop->chartype]) == isprop) return !negated; break; case PT_PC: if ((data[1] == prop->chartype) == isprop) return !negated; break; case PT_SC: if ((data[1] == prop->script) == isprop) return !negated; break; case PT_SCX: ok = (data[1] == prop->script || MAPBIT(PRIV(ucd_script_sets) + UCD_SCRIPTX_PROP(prop), data[1]) != 0); if (ok == isprop) return !negated; break; case PT_ALNUM: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N) == isprop) return !negated; break; /* Perl space used to exclude VT, but from Perl 5.18 it is included, which means that Perl space and POSIX space are now identical. PCRE was changed at release 8.34. */ case PT_SPACE: /* Perl space */ case PT_PXSPACE: /* POSIX space */ switch(c) { HSPACE_CASES: VSPACE_CASES: if (isprop) return !negated; break; default: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == isprop) return !negated; break; } break; case PT_WORD: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE) == isprop) return !negated; break; case PT_UCNC: if (c < 0xa0) { if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || c == CHAR_GRAVE_ACCENT) == isprop) return !negated; } else { if ((c < 0xd800 || c > 0xdfff) == isprop) return !negated; } break; case PT_BIDICL: if ((UCD_BIDICLASS_PROP(prop) == data[1]) == isprop) return !negated; break; case PT_BOOL: ok = MAPBIT(PRIV(ucd_boolprop_sets) + UCD_BPROPS_PROP(prop), data[1]) != 0; if (ok == isprop) return !negated; break; /* The following three properties can occur only in an XCLASS, as there is no \p or \P coding for them. */ /* Graphic character. Implement this as not Z (space or separator) and not C (other), except for Cf (format) with a few exceptions. This seems to be what Perl does. The exceptional characters are: U+061C Arabic Letter Mark U+180E Mongolian Vowel Separator U+2066 - U+2069 Various "isolate"s */ case PT_PXGRAPH: if ((PRIV(ucp_gentype)[prop->chartype] != ucp_Z && (PRIV(ucp_gentype)[prop->chartype] != ucp_C || (prop->chartype == ucp_Cf && c != 0x061c && c != 0x180e && (c < 0x2066 || c > 0x2069)) )) == isprop) return !negated; break; /* Printable character: same as graphic, with the addition of Zs, i.e. not Zl and not Zp, and U+180E. */ case PT_PXPRINT: if ((prop->chartype != ucp_Zl && prop->chartype != ucp_Zp && (PRIV(ucp_gentype)[prop->chartype] != ucp_C || (prop->chartype == ucp_Cf && c != 0x061c && (c < 0x2066 || c > 0x2069)) )) == isprop) return !negated; break; /* Punctuation: all Unicode punctuation, plus ASCII characters that Unicode treats as symbols rather than punctuation, for Perl compatibility (these are $+<=>^`|~). */ case PT_PXPUNCT: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_P || (c < 128 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop) return !negated; break; /* This should never occur, but compilers may mutter if there is no default. */ default: return FALSE; } data += 2; } #else (void)utf; /* Avoid compiler warning */ #endif /* SUPPORT_UNICODE */ } return negated; /* char did not match */ } /* End of pcre2_xclass.c */
8,933
29.806897
82
c
php-src
php-src-master/ext/pcre/pcre2lib/sljit/sljitConfig.h
/* * Stack-less Just-In-Time compiler * * Copyright Zoltan Herczeg ([email protected]). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) 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. */ #ifndef SLJIT_CONFIG_H_ #define SLJIT_CONFIG_H_ #ifdef __cplusplus extern "C" { #endif /* This file contains the basic configuration options for the SLJIT compiler and their default values. These options can be overridden in the sljitConfigPre.h header file when SLJIT_HAVE_CONFIG_PRE is set to a non-zero value. */ /* --------------------------------------------------------------------- */ /* Architecture */ /* --------------------------------------------------------------------- */ /* Architecture selection. */ /* #define SLJIT_CONFIG_X86_32 1 */ /* #define SLJIT_CONFIG_X86_64 1 */ /* #define SLJIT_CONFIG_ARM_V5 1 */ /* #define SLJIT_CONFIG_ARM_V7 1 */ /* #define SLJIT_CONFIG_ARM_THUMB2 1 */ /* #define SLJIT_CONFIG_ARM_64 1 */ /* #define SLJIT_CONFIG_PPC_32 1 */ /* #define SLJIT_CONFIG_PPC_64 1 */ /* #define SLJIT_CONFIG_MIPS_32 1 */ /* #define SLJIT_CONFIG_MIPS_64 1 */ /* #define SLJIT_CONFIG_SPARC_32 1 */ /* #define SLJIT_CONFIG_S390X 1 */ /* #define SLJIT_CONFIG_AUTO 1 */ /* #define SLJIT_CONFIG_UNSUPPORTED 1 */ /* --------------------------------------------------------------------- */ /* Utilities */ /* --------------------------------------------------------------------- */ /* Implements a stack like data structure (by using mmap / VirtualAlloc */ /* or a custom allocator). */ #ifndef SLJIT_UTIL_STACK /* Enabled by default */ #define SLJIT_UTIL_STACK 1 #endif /* Uses user provided allocator to allocate the stack (see SLJIT_UTIL_STACK) */ #ifndef SLJIT_UTIL_SIMPLE_STACK_ALLOCATION /* Disabled by default */ #define SLJIT_UTIL_SIMPLE_STACK_ALLOCATION 0 #endif /* Single threaded application. Does not require any locks. */ #ifndef SLJIT_SINGLE_THREADED /* Disabled by default. */ #define SLJIT_SINGLE_THREADED 0 #endif /* --------------------------------------------------------------------- */ /* Configuration */ /* --------------------------------------------------------------------- */ /* If SLJIT_STD_MACROS_DEFINED is not defined, the application should define SLJIT_MALLOC, SLJIT_FREE, SLJIT_MEMCPY, and NULL. */ #ifndef SLJIT_STD_MACROS_DEFINED /* Disabled by default. */ #define SLJIT_STD_MACROS_DEFINED 0 #endif /* Executable code allocation: If SLJIT_EXECUTABLE_ALLOCATOR is not defined, the application should define SLJIT_MALLOC_EXEC, SLJIT_FREE_EXEC, and SLJIT_EXEC_OFFSET. */ #ifndef SLJIT_EXECUTABLE_ALLOCATOR /* Enabled by default. */ #define SLJIT_EXECUTABLE_ALLOCATOR 1 /* When SLJIT_PROT_EXECUTABLE_ALLOCATOR is enabled SLJIT uses an allocator which does not set writable and executable permission flags at the same time. Instead, it creates a shared memory segment (usually backed by a file) and maps it twice, with different permissions, depending on the use case. The trade-off is increased use of virtual memory, incompatibility with fork(), and some possible additional security risks by the use of publicly accessible files for the generated code. */ #ifndef SLJIT_PROT_EXECUTABLE_ALLOCATOR /* Disabled by default. */ #define SLJIT_PROT_EXECUTABLE_ALLOCATOR 0 #endif /* When SLJIT_WX_EXECUTABLE_ALLOCATOR is enabled SLJIT uses an allocator which does not set writable and executable permission flags at the same time. Instead, it creates a new independent map on each invocation and switches permissions at the underlying pages as needed. The trade-off is increased memory use and degraded performance. */ #ifndef SLJIT_WX_EXECUTABLE_ALLOCATOR /* Disabled by default. */ #define SLJIT_WX_EXECUTABLE_ALLOCATOR 0 #endif #endif /* !SLJIT_EXECUTABLE_ALLOCATOR */ /* Force cdecl calling convention even if a better calling convention (e.g. fastcall) is supported by the C compiler. If this option is disabled (this is the default), functions called from JIT should be defined with SLJIT_FUNC attribute. Standard C functions can still be called by using the SLJIT_CALL_CDECL jump type. */ #ifndef SLJIT_USE_CDECL_CALLING_CONVENTION /* Disabled by default */ #define SLJIT_USE_CDECL_CALLING_CONVENTION 0 #endif /* Return with error when an invalid argument is passed. */ #ifndef SLJIT_ARGUMENT_CHECKS /* Disabled by default */ #define SLJIT_ARGUMENT_CHECKS 0 #endif /* Debug checks (assertions, etc.). */ #ifndef SLJIT_DEBUG /* Enabled by default */ #define SLJIT_DEBUG 1 #endif /* Verbose operations. */ #ifndef SLJIT_VERBOSE /* Enabled by default */ #define SLJIT_VERBOSE 1 #endif /* SLJIT_IS_FPU_AVAILABLE The availability of the FPU can be controlled by SLJIT_IS_FPU_AVAILABLE. zero value - FPU is NOT present. nonzero value - FPU is present. */ /* For further configurations, see the beginning of sljitConfigInternal.h */ #ifdef __cplusplus } /* extern "C" */ #endif #endif /* SLJIT_CONFIG_H_ */
6,381
35.890173
94
h
php-src
php-src-master/ext/pcre/pcre2lib/sljit/sljitExecAllocator.c
/* * Stack-less Just-In-Time compiler * * Copyright Zoltan Herczeg ([email protected]). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) 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. */ /* This file contains a simple executable memory allocator It is assumed, that executable code blocks are usually medium (or sometimes large) memory blocks, and the allocator is not too frequently called (less optimized than other allocators). Thus, using it as a generic allocator is not suggested. How does it work: Memory is allocated in continuous memory areas called chunks by alloc_chunk() Chunk format: [ block ][ block ] ... [ block ][ block terminator ] All blocks and the block terminator is started with block_header. The block header contains the size of the previous and the next block. These sizes can also contain special values. Block size: 0 - The block is a free_block, with a different size member. 1 - The block is a block terminator. n - The block is used at the moment, and the value contains its size. Previous block size: 0 - This is the first block of the memory chunk. n - The size of the previous block. Using these size values we can go forward or backward on the block chain. The unused blocks are stored in a chain list pointed by free_blocks. This list is useful if we need to find a suitable memory area when the allocator is called. When a block is freed, the new free block is connected to its adjacent free blocks if possible. [ free block ][ used block ][ free block ] and "used block" is freed, the three blocks are connected together: [ one big free block ] */ /* --------------------------------------------------------------------- */ /* System (OS) functions */ /* --------------------------------------------------------------------- */ /* 64 KByte. */ #define CHUNK_SIZE (sljit_uw)0x10000u /* alloc_chunk / free_chunk : * allocate executable system memory chunks * the size is always divisible by CHUNK_SIZE SLJIT_ALLOCATOR_LOCK / SLJIT_ALLOCATOR_UNLOCK : * provided as part of sljitUtils * only the allocator requires this lock, sljit is fully thread safe as it only uses local variables */ #ifdef _WIN32 #define SLJIT_UPDATE_WX_FLAGS(from, to, enable_exec) static SLJIT_INLINE void* alloc_chunk(sljit_uw size) { return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } static SLJIT_INLINE void free_chunk(void *chunk, sljit_uw size) { SLJIT_UNUSED_ARG(size); VirtualFree(chunk, 0, MEM_RELEASE); } #else /* POSIX */ #if defined(__APPLE__) && defined(MAP_JIT) /* On macOS systems, returns MAP_JIT if it is defined _and_ we're running on a version where it's OK to have more than one JIT block or where MAP_JIT is required. On non-macOS systems, returns MAP_JIT if it is defined. */ #include <TargetConditionals.h> #if TARGET_OS_OSX #if defined SLJIT_CONFIG_X86 && SLJIT_CONFIG_X86 #ifdef MAP_ANON #include <sys/utsname.h> #include <stdlib.h> #define SLJIT_MAP_JIT (get_map_jit_flag()) static SLJIT_INLINE int get_map_jit_flag() { size_t page_size; void *ptr; struct utsname name; static int map_jit_flag = -1; if (map_jit_flag < 0) { map_jit_flag = 0; uname(&name); /* Kernel version for 10.14.0 (Mojave) or later */ if (atoi(name.release) >= 18) { page_size = get_page_alignment() + 1; /* Only use MAP_JIT if a hardened runtime is used */ ptr = mmap(NULL, page_size, PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); if (ptr != MAP_FAILED) munmap(ptr, page_size); else map_jit_flag = MAP_JIT; } } return map_jit_flag; } #endif /* MAP_ANON */ #else /* !SLJIT_CONFIG_X86 */ #if !(defined SLJIT_CONFIG_ARM && SLJIT_CONFIG_ARM) #error "Unsupported architecture" #endif /* SLJIT_CONFIG_ARM */ #include <AvailabilityMacros.h> #include <pthread.h> #define SLJIT_MAP_JIT (MAP_JIT) #define SLJIT_UPDATE_WX_FLAGS(from, to, enable_exec) \ apple_update_wx_flags(enable_exec) static SLJIT_INLINE void apple_update_wx_flags(sljit_s32 enable_exec) { #if MAC_OS_X_VERSION_MIN_REQUIRED >= 110000 pthread_jit_write_protect_np(enable_exec); #else #error "Must target Big Sur or newer" #endif /* BigSur */ } #endif /* SLJIT_CONFIG_X86 */ #else /* !TARGET_OS_OSX */ #define SLJIT_MAP_JIT (MAP_JIT) #endif /* TARGET_OS_OSX */ #endif /* __APPLE__ && MAP_JIT */ #ifndef SLJIT_UPDATE_WX_FLAGS #define SLJIT_UPDATE_WX_FLAGS(from, to, enable_exec) #endif /* !SLJIT_UPDATE_WX_FLAGS */ #ifndef SLJIT_MAP_JIT #define SLJIT_MAP_JIT (0) #endif /* !SLJIT_MAP_JIT */ static SLJIT_INLINE void* alloc_chunk(sljit_uw size) { void *retval; int prot = PROT_READ | PROT_WRITE | PROT_EXEC; int flags = MAP_PRIVATE; int fd = -1; #ifdef PROT_MAX prot |= PROT_MAX(prot); #endif #ifdef MAP_ANON flags |= MAP_ANON | SLJIT_MAP_JIT; #else /* !MAP_ANON */ if (SLJIT_UNLIKELY((dev_zero < 0) && open_dev_zero())) return NULL; fd = dev_zero; #endif /* MAP_ANON */ retval = mmap(NULL, size, prot, flags, fd, 0); if (retval == MAP_FAILED) return NULL; #ifdef __FreeBSD__ /* HardenedBSD's mmap lies, so check permissions again */ if (mprotect(retval, size, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { munmap(retval, size); return NULL; } #endif /* FreeBSD */ SLJIT_UPDATE_WX_FLAGS(retval, (uint8_t *)retval + size, 0); return retval; } static SLJIT_INLINE void free_chunk(void *chunk, sljit_uw size) { munmap(chunk, size); } #endif /* windows */ /* --------------------------------------------------------------------- */ /* Common functions */ /* --------------------------------------------------------------------- */ #define CHUNK_MASK (~(CHUNK_SIZE - 1)) struct block_header { sljit_uw size; sljit_uw prev_size; }; struct free_block { struct block_header header; struct free_block *next; struct free_block *prev; sljit_uw size; }; #define AS_BLOCK_HEADER(base, offset) \ ((struct block_header*)(((sljit_u8*)base) + offset)) #define AS_FREE_BLOCK(base, offset) \ ((struct free_block*)(((sljit_u8*)base) + offset)) #define MEM_START(base) ((void*)(((sljit_u8*)base) + sizeof(struct block_header))) #define ALIGN_SIZE(size) (((size) + sizeof(struct block_header) + 7u) & ~(sljit_uw)7) static struct free_block* free_blocks; static sljit_uw allocated_size; static sljit_uw total_size; static SLJIT_INLINE void sljit_insert_free_block(struct free_block *free_block, sljit_uw size) { free_block->header.size = 0; free_block->size = size; free_block->next = free_blocks; free_block->prev = NULL; if (free_blocks) free_blocks->prev = free_block; free_blocks = free_block; } static SLJIT_INLINE void sljit_remove_free_block(struct free_block *free_block) { if (free_block->next) free_block->next->prev = free_block->prev; if (free_block->prev) free_block->prev->next = free_block->next; else { SLJIT_ASSERT(free_blocks == free_block); free_blocks = free_block->next; } } SLJIT_API_FUNC_ATTRIBUTE void* sljit_malloc_exec(sljit_uw size) { struct block_header *header; struct block_header *next_header; struct free_block *free_block; sljit_uw chunk_size; SLJIT_ALLOCATOR_LOCK(); if (size < (64 - sizeof(struct block_header))) size = (64 - sizeof(struct block_header)); size = ALIGN_SIZE(size); free_block = free_blocks; while (free_block) { if (free_block->size >= size) { chunk_size = free_block->size; SLJIT_UPDATE_WX_FLAGS(NULL, NULL, 0); if (chunk_size > size + 64) { /* We just cut a block from the end of the free block. */ chunk_size -= size; free_block->size = chunk_size; header = AS_BLOCK_HEADER(free_block, chunk_size); header->prev_size = chunk_size; AS_BLOCK_HEADER(header, size)->prev_size = size; } else { sljit_remove_free_block(free_block); header = (struct block_header*)free_block; size = chunk_size; } allocated_size += size; header->size = size; SLJIT_ALLOCATOR_UNLOCK(); return MEM_START(header); } free_block = free_block->next; } chunk_size = (size + sizeof(struct block_header) + CHUNK_SIZE - 1) & CHUNK_MASK; header = (struct block_header*)alloc_chunk(chunk_size); if (!header) { SLJIT_ALLOCATOR_UNLOCK(); return NULL; } chunk_size -= sizeof(struct block_header); total_size += chunk_size; header->prev_size = 0; if (chunk_size > size + 64) { /* Cut the allocated space into a free and a used block. */ allocated_size += size; header->size = size; chunk_size -= size; free_block = AS_FREE_BLOCK(header, size); free_block->header.prev_size = size; sljit_insert_free_block(free_block, chunk_size); next_header = AS_BLOCK_HEADER(free_block, chunk_size); } else { /* All space belongs to this allocation. */ allocated_size += chunk_size; header->size = chunk_size; next_header = AS_BLOCK_HEADER(header, chunk_size); } next_header->size = 1; next_header->prev_size = chunk_size; SLJIT_ALLOCATOR_UNLOCK(); return MEM_START(header); } SLJIT_API_FUNC_ATTRIBUTE void sljit_free_exec(void* ptr) { struct block_header *header; struct free_block* free_block; SLJIT_ALLOCATOR_LOCK(); header = AS_BLOCK_HEADER(ptr, -(sljit_sw)sizeof(struct block_header)); allocated_size -= header->size; /* Connecting free blocks together if possible. */ SLJIT_UPDATE_WX_FLAGS(NULL, NULL, 0); /* If header->prev_size == 0, free_block will equal to header. In this case, free_block->header.size will be > 0. */ free_block = AS_FREE_BLOCK(header, -(sljit_sw)header->prev_size); if (SLJIT_UNLIKELY(!free_block->header.size)) { free_block->size += header->size; header = AS_BLOCK_HEADER(free_block, free_block->size); header->prev_size = free_block->size; } else { free_block = (struct free_block*)header; sljit_insert_free_block(free_block, header->size); } header = AS_BLOCK_HEADER(free_block, free_block->size); if (SLJIT_UNLIKELY(!header->size)) { free_block->size += ((struct free_block*)header)->size; sljit_remove_free_block((struct free_block*)header); header = AS_BLOCK_HEADER(free_block, free_block->size); header->prev_size = free_block->size; } /* The whole chunk is free. */ if (SLJIT_UNLIKELY(!free_block->header.prev_size && header->size == 1)) { /* If this block is freed, we still have (allocated_size / 2) free space. */ if (total_size - free_block->size > (allocated_size * 3 / 2)) { total_size -= free_block->size; sljit_remove_free_block(free_block); free_chunk(free_block, free_block->size + sizeof(struct block_header)); } } SLJIT_UPDATE_WX_FLAGS(NULL, NULL, 1); SLJIT_ALLOCATOR_UNLOCK(); } SLJIT_API_FUNC_ATTRIBUTE void sljit_free_unused_memory_exec(void) { struct free_block* free_block; struct free_block* next_free_block; SLJIT_ALLOCATOR_LOCK(); SLJIT_UPDATE_WX_FLAGS(NULL, NULL, 0); free_block = free_blocks; while (free_block) { next_free_block = free_block->next; if (!free_block->header.prev_size && AS_BLOCK_HEADER(free_block, free_block->size)->size == 1) { total_size -= free_block->size; sljit_remove_free_block(free_block); free_chunk(free_block, free_block->size + sizeof(struct block_header)); } free_block = next_free_block; } SLJIT_ASSERT((total_size && free_blocks) || (!total_size && !free_blocks)); SLJIT_UPDATE_WX_FLAGS(NULL, NULL, 1); SLJIT_ALLOCATOR_UNLOCK(); }
12,753
29.956311
94
c
php-src
php-src-master/ext/pcre/pcre2lib/sljit/sljitProtExecAllocator.c
/* * Stack-less Just-In-Time compiler * * Copyright Zoltan Herczeg ([email protected]). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) 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. */ /* This file contains a simple executable memory allocator It is assumed, that executable code blocks are usually medium (or sometimes large) memory blocks, and the allocator is not too frequently called (less optimized than other allocators). Thus, using it as a generic allocator is not suggested. How does it work: Memory is allocated in continuous memory areas called chunks by alloc_chunk() Chunk format: [ block ][ block ] ... [ block ][ block terminator ] All blocks and the block terminator is started with block_header. The block header contains the size of the previous and the next block. These sizes can also contain special values. Block size: 0 - The block is a free_block, with a different size member. 1 - The block is a block terminator. n - The block is used at the moment, and the value contains its size. Previous block size: 0 - This is the first block of the memory chunk. n - The size of the previous block. Using these size values we can go forward or backward on the block chain. The unused blocks are stored in a chain list pointed by free_blocks. This list is useful if we need to find a suitable memory area when the allocator is called. When a block is freed, the new free block is connected to its adjacent free blocks if possible. [ free block ][ used block ][ free block ] and "used block" is freed, the three blocks are connected together: [ one big free block ] */ /* --------------------------------------------------------------------- */ /* System (OS) functions */ /* --------------------------------------------------------------------- */ /* 64 KByte. */ #define CHUNK_SIZE (sljit_uw)0x10000 struct chunk_header { void *executable; }; /* alloc_chunk / free_chunk : * allocate executable system memory chunks * the size is always divisible by CHUNK_SIZE SLJIT_ALLOCATOR_LOCK / SLJIT_ALLOCATOR_UNLOCK : * provided as part of sljitUtils * only the allocator requires this lock, sljit is fully thread safe as it only uses local variables */ #ifndef __NetBSD__ #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #ifndef O_NOATIME #define O_NOATIME 0 #endif /* this is a linux extension available since kernel 3.11 */ #ifndef O_TMPFILE #define O_TMPFILE 020200000 #endif #ifndef _GNU_SOURCE char *secure_getenv(const char *name); int mkostemp(char *template, int flags); #endif static SLJIT_INLINE int create_tempfile(void) { int fd; char tmp_name[256]; size_t tmp_name_len = 0; char *dir; struct stat st; #if defined(SLJIT_SINGLE_THREADED) && SLJIT_SINGLE_THREADED mode_t mode; #endif #ifdef HAVE_MEMFD_CREATE /* this is a GNU extension, make sure to use -D_GNU_SOURCE */ fd = memfd_create("sljit", MFD_CLOEXEC); if (fd != -1) { fchmod(fd, 0); return fd; } #endif dir = secure_getenv("TMPDIR"); if (dir) { tmp_name_len = strlen(dir); if (tmp_name_len > 0 && tmp_name_len < sizeof(tmp_name)) { if ((stat(dir, &st) == 0) && S_ISDIR(st.st_mode)) strcpy(tmp_name, dir); } } #ifdef P_tmpdir if (!tmp_name_len) { tmp_name_len = strlen(P_tmpdir); if (tmp_name_len > 0 && tmp_name_len < sizeof(tmp_name)) strcpy(tmp_name, P_tmpdir); } #endif if (!tmp_name_len) { strcpy(tmp_name, "/tmp"); tmp_name_len = 4; } SLJIT_ASSERT(tmp_name_len > 0 && tmp_name_len < sizeof(tmp_name)); if (tmp_name[tmp_name_len - 1] == '/') tmp_name[--tmp_name_len] = '\0'; #ifdef __linux__ /* * the previous trimming might had left an empty string if TMPDIR="/" * so work around the problem below */ fd = open(tmp_name_len ? tmp_name : "/", O_TMPFILE | O_EXCL | O_RDWR | O_NOATIME | O_CLOEXEC, 0); if (fd != -1) return fd; #endif if (tmp_name_len + 7 >= sizeof(tmp_name)) return -1; strcpy(tmp_name + tmp_name_len, "/XXXXXX"); #if defined(SLJIT_SINGLE_THREADED) && SLJIT_SINGLE_THREADED mode = umask(0777); #endif fd = mkostemp(tmp_name, O_CLOEXEC | O_NOATIME); #if defined(SLJIT_SINGLE_THREADED) && SLJIT_SINGLE_THREADED umask(mode); #else fchmod(fd, 0); #endif if (fd == -1) return -1; if (unlink(tmp_name)) { close(fd); return -1; } return fd; } static SLJIT_INLINE struct chunk_header* alloc_chunk(sljit_uw size) { struct chunk_header *retval; int fd; fd = create_tempfile(); if (fd == -1) return NULL; if (ftruncate(fd, (off_t)size)) { close(fd); return NULL; } retval = (struct chunk_header *)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (retval == MAP_FAILED) { close(fd); return NULL; } retval->executable = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); if (retval->executable == MAP_FAILED) { munmap((void *)retval, size); close(fd); return NULL; } close(fd); return retval; } #else /* * MAP_REMAPDUP is a NetBSD extension available sinde 8.0, make sure to * adjust your feature macros (ex: -D_NETBSD_SOURCE) as needed */ static SLJIT_INLINE struct chunk_header* alloc_chunk(sljit_uw size) { struct chunk_header *retval; retval = (struct chunk_header *)mmap(NULL, size, PROT_READ | PROT_WRITE | PROT_MPROTECT(PROT_EXEC), MAP_ANON | MAP_SHARED, -1, 0); if (retval == MAP_FAILED) return NULL; retval->executable = mremap(retval, size, NULL, size, MAP_REMAPDUP); if (retval->executable == MAP_FAILED) { munmap((void *)retval, size); return NULL; } if (mprotect(retval->executable, size, PROT_READ | PROT_EXEC) == -1) { munmap(retval->executable, size); munmap((void *)retval, size); return NULL; } return retval; } #endif /* NetBSD */ static SLJIT_INLINE void free_chunk(void *chunk, sljit_uw size) { struct chunk_header *header = ((struct chunk_header *)chunk) - 1; munmap(header->executable, size); munmap((void *)header, size); } /* --------------------------------------------------------------------- */ /* Common functions */ /* --------------------------------------------------------------------- */ #define CHUNK_MASK (~(CHUNK_SIZE - 1)) struct block_header { sljit_uw size; sljit_uw prev_size; sljit_sw executable_offset; }; struct free_block { struct block_header header; struct free_block *next; struct free_block *prev; sljit_uw size; }; #define AS_BLOCK_HEADER(base, offset) \ ((struct block_header*)(((sljit_u8*)base) + offset)) #define AS_FREE_BLOCK(base, offset) \ ((struct free_block*)(((sljit_u8*)base) + offset)) #define MEM_START(base) ((void*)((base) + 1)) #define ALIGN_SIZE(size) (((size) + sizeof(struct block_header) + 7u) & ~(sljit_uw)7) static struct free_block* free_blocks; static sljit_uw allocated_size; static sljit_uw total_size; static SLJIT_INLINE void sljit_insert_free_block(struct free_block *free_block, sljit_uw size) { free_block->header.size = 0; free_block->size = size; free_block->next = free_blocks; free_block->prev = NULL; if (free_blocks) free_blocks->prev = free_block; free_blocks = free_block; } static SLJIT_INLINE void sljit_remove_free_block(struct free_block *free_block) { if (free_block->next) free_block->next->prev = free_block->prev; if (free_block->prev) free_block->prev->next = free_block->next; else { SLJIT_ASSERT(free_blocks == free_block); free_blocks = free_block->next; } } SLJIT_API_FUNC_ATTRIBUTE void* sljit_malloc_exec(sljit_uw size) { struct chunk_header *chunk_header; struct block_header *header; struct block_header *next_header; struct free_block *free_block; sljit_uw chunk_size; sljit_sw executable_offset; SLJIT_ALLOCATOR_LOCK(); if (size < (64 - sizeof(struct block_header))) size = (64 - sizeof(struct block_header)); size = ALIGN_SIZE(size); free_block = free_blocks; while (free_block) { if (free_block->size >= size) { chunk_size = free_block->size; if (chunk_size > size + 64) { /* We just cut a block from the end of the free block. */ chunk_size -= size; free_block->size = chunk_size; header = AS_BLOCK_HEADER(free_block, chunk_size); header->prev_size = chunk_size; header->executable_offset = free_block->header.executable_offset; AS_BLOCK_HEADER(header, size)->prev_size = size; } else { sljit_remove_free_block(free_block); header = (struct block_header*)free_block; size = chunk_size; } allocated_size += size; header->size = size; SLJIT_ALLOCATOR_UNLOCK(); return MEM_START(header); } free_block = free_block->next; } chunk_size = sizeof(struct chunk_header) + sizeof(struct block_header); chunk_size = (chunk_size + size + CHUNK_SIZE - 1) & CHUNK_MASK; chunk_header = alloc_chunk(chunk_size); if (!chunk_header) { SLJIT_ALLOCATOR_UNLOCK(); return NULL; } executable_offset = (sljit_sw)((sljit_u8*)chunk_header->executable - (sljit_u8*)chunk_header); chunk_size -= sizeof(struct chunk_header) + sizeof(struct block_header); total_size += chunk_size; header = (struct block_header *)(chunk_header + 1); header->prev_size = 0; header->executable_offset = executable_offset; if (chunk_size > size + 64) { /* Cut the allocated space into a free and a used block. */ allocated_size += size; header->size = size; chunk_size -= size; free_block = AS_FREE_BLOCK(header, size); free_block->header.prev_size = size; free_block->header.executable_offset = executable_offset; sljit_insert_free_block(free_block, chunk_size); next_header = AS_BLOCK_HEADER(free_block, chunk_size); } else { /* All space belongs to this allocation. */ allocated_size += chunk_size; header->size = chunk_size; next_header = AS_BLOCK_HEADER(header, chunk_size); } next_header->size = 1; next_header->prev_size = chunk_size; next_header->executable_offset = executable_offset; SLJIT_ALLOCATOR_UNLOCK(); return MEM_START(header); } SLJIT_API_FUNC_ATTRIBUTE void sljit_free_exec(void* ptr) { struct block_header *header; struct free_block* free_block; SLJIT_ALLOCATOR_LOCK(); header = AS_BLOCK_HEADER(ptr, -(sljit_sw)sizeof(struct block_header)); header = AS_BLOCK_HEADER(header, -header->executable_offset); allocated_size -= header->size; /* Connecting free blocks together if possible. */ /* If header->prev_size == 0, free_block will equal to header. In this case, free_block->header.size will be > 0. */ free_block = AS_FREE_BLOCK(header, -(sljit_sw)header->prev_size); if (SLJIT_UNLIKELY(!free_block->header.size)) { free_block->size += header->size; header = AS_BLOCK_HEADER(free_block, free_block->size); header->prev_size = free_block->size; } else { free_block = (struct free_block*)header; sljit_insert_free_block(free_block, header->size); } header = AS_BLOCK_HEADER(free_block, free_block->size); if (SLJIT_UNLIKELY(!header->size)) { free_block->size += ((struct free_block*)header)->size; sljit_remove_free_block((struct free_block*)header); header = AS_BLOCK_HEADER(free_block, free_block->size); header->prev_size = free_block->size; } /* The whole chunk is free. */ if (SLJIT_UNLIKELY(!free_block->header.prev_size && header->size == 1)) { /* If this block is freed, we still have (allocated_size / 2) free space. */ if (total_size - free_block->size > (allocated_size * 3 / 2)) { total_size -= free_block->size; sljit_remove_free_block(free_block); free_chunk(free_block, free_block->size + sizeof(struct chunk_header) + sizeof(struct block_header)); } } SLJIT_ALLOCATOR_UNLOCK(); } SLJIT_API_FUNC_ATTRIBUTE void sljit_free_unused_memory_exec(void) { struct free_block* free_block; struct free_block* next_free_block; SLJIT_ALLOCATOR_LOCK(); free_block = free_blocks; while (free_block) { next_free_block = free_block->next; if (!free_block->header.prev_size && AS_BLOCK_HEADER(free_block, free_block->size)->size == 1) { total_size -= free_block->size; sljit_remove_free_block(free_block); free_chunk(free_block, free_block->size + sizeof(struct chunk_header) + sizeof(struct block_header)); } free_block = next_free_block; } SLJIT_ASSERT((total_size && free_blocks) || (!total_size && !free_blocks)); SLJIT_ALLOCATOR_UNLOCK(); } SLJIT_API_FUNC_ATTRIBUTE sljit_sw sljit_exec_offset(void* ptr) { return ((struct block_header *)(ptr))[-1].executable_offset; }
13,815
28.086316
95
c
php-src
php-src-master/ext/pcre/pcre2lib/sljit/sljitWXExecAllocator.c
/* * Stack-less Just-In-Time compiler * * Copyright Zoltan Herczeg ([email protected]). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) 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. */ /* This file contains a simple W^X executable memory allocator for POSIX like systems and Windows In *NIX, MAP_ANON is required (that is considered a feature) so make sure to set the right availability macros for your system or the code will fail to build. If your system doesn't support mapping of anonymous pages (ex: IRIX) it is also likely that it doesn't need this allocator and should be using the standard one instead. It allocates a separate map for each code block and may waste a lot of memory, because whatever was requested, will be rounded up to the page size (minimum 4KB, but could be even bigger). It changes the page permissions (RW <-> RX) as needed and therefore, if you will be updating the code after it has been generated, need to make sure to block any concurrent execution, or could result in a SIGBUS, that could even manifest itself at a different address than the one that was being modified. Only use if you are unable to use the regular allocator because of security restrictions and adding exceptions to your application or the system are not possible. */ #define SLJIT_UPDATE_WX_FLAGS(from, to, enable_exec) \ sljit_update_wx_flags((from), (to), (enable_exec)) #ifndef _WIN32 #include <sys/types.h> #include <sys/mman.h> #ifdef __NetBSD__ #if defined(PROT_MPROTECT) #define check_se_protected(ptr, size) (0) #define SLJIT_PROT_WX PROT_MPROTECT(PROT_EXEC) #else /* !PROT_MPROTECT */ #ifdef _NETBSD_SOURCE #include <sys/param.h> #else /* !_NETBSD_SOURCE */ typedef unsigned int u_int; #define devmajor_t sljit_s32 #endif /* _NETBSD_SOURCE */ #include <sys/sysctl.h> #include <unistd.h> #define check_se_protected(ptr, size) netbsd_se_protected() static SLJIT_INLINE int netbsd_se_protected(void) { int mib[3]; int paxflags; size_t len = sizeof(paxflags); mib[0] = CTL_PROC; mib[1] = getpid(); mib[2] = PROC_PID_PAXFLAGS; if (SLJIT_UNLIKELY(sysctl(mib, 3, &paxflags, &len, NULL, 0) < 0)) return -1; return (paxflags & CTL_PROC_PAXFLAGS_MPROTECT) ? -1 : 0; } #endif /* PROT_MPROTECT */ #else /* POSIX */ #define check_se_protected(ptr, size) generic_se_protected(ptr, size) static SLJIT_INLINE int generic_se_protected(void *ptr, sljit_uw size) { if (SLJIT_LIKELY(!mprotect(ptr, size, PROT_EXEC))) return mprotect(ptr, size, PROT_READ | PROT_WRITE); return -1; } #endif /* NetBSD */ #if defined SLJIT_SINGLE_THREADED && SLJIT_SINGLE_THREADED #define SLJIT_SE_LOCK() #define SLJIT_SE_UNLOCK() #else /* !SLJIT_SINGLE_THREADED */ #include <pthread.h> #define SLJIT_SE_LOCK() pthread_mutex_lock(&se_lock) #define SLJIT_SE_UNLOCK() pthread_mutex_unlock(&se_lock) #endif /* SLJIT_SINGLE_THREADED */ #ifndef SLJIT_PROT_WX #define SLJIT_PROT_WX 0 #endif /* !SLJIT_PROT_WX */ SLJIT_API_FUNC_ATTRIBUTE void* sljit_malloc_exec(sljit_uw size) { #if !(defined SLJIT_SINGLE_THREADED && SLJIT_SINGLE_THREADED) static pthread_mutex_t se_lock = PTHREAD_MUTEX_INITIALIZER; #endif static int se_protected = !SLJIT_PROT_WX; int prot = PROT_READ | PROT_WRITE | SLJIT_PROT_WX; sljit_uw* ptr; if (SLJIT_UNLIKELY(se_protected < 0)) return NULL; #ifdef PROT_MAX prot |= PROT_MAX(PROT_READ | PROT_WRITE | PROT_EXEC); #endif size += sizeof(sljit_uw); ptr = (sljit_uw*)mmap(NULL, size, prot, MAP_PRIVATE | MAP_ANON, -1, 0); if (ptr == MAP_FAILED) return NULL; if (SLJIT_UNLIKELY(se_protected > 0)) { SLJIT_SE_LOCK(); se_protected = check_se_protected(ptr, size); SLJIT_SE_UNLOCK(); if (SLJIT_UNLIKELY(se_protected < 0)) { munmap((void *)ptr, size); return NULL; } } *ptr++ = size; return ptr; } #undef SLJIT_PROT_WX #undef SLJIT_SE_UNLOCK #undef SLJIT_SE_LOCK SLJIT_API_FUNC_ATTRIBUTE void sljit_free_exec(void* ptr) { sljit_uw *start_ptr = ((sljit_uw*)ptr) - 1; munmap((void*)start_ptr, *start_ptr); } static void sljit_update_wx_flags(void *from, void *to, sljit_s32 enable_exec) { sljit_uw page_mask = (sljit_uw)get_page_alignment(); sljit_uw start = (sljit_uw)from; sljit_uw end = (sljit_uw)to; int prot = PROT_READ | (enable_exec ? PROT_EXEC : PROT_WRITE); SLJIT_ASSERT(start < end); start &= ~page_mask; end = (end + page_mask) & ~page_mask; mprotect((void*)start, end - start, prot); } #else /* windows */ SLJIT_API_FUNC_ATTRIBUTE void* sljit_malloc_exec(sljit_uw size) { sljit_uw *ptr; size += sizeof(sljit_uw); ptr = (sljit_uw*)VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!ptr) return NULL; *ptr++ = size; return ptr; } SLJIT_API_FUNC_ATTRIBUTE void sljit_free_exec(void* ptr) { sljit_uw start = (sljit_uw)ptr - sizeof(sljit_uw); #if defined(SLJIT_DEBUG) && SLJIT_DEBUG sljit_uw page_mask = (sljit_uw)get_page_alignment(); SLJIT_ASSERT(!(start & page_mask)); #endif VirtualFree((void*)start, 0, MEM_RELEASE); } static void sljit_update_wx_flags(void *from, void *to, sljit_s32 enable_exec) { DWORD oldprot; sljit_uw page_mask = (sljit_uw)get_page_alignment(); sljit_uw start = (sljit_uw)from; sljit_uw end = (sljit_uw)to; DWORD prot = enable_exec ? PAGE_EXECUTE : PAGE_READWRITE; SLJIT_ASSERT(start < end); start &= ~page_mask; end = (end + page_mask) & ~page_mask; VirtualProtect((void*)start, end - start, prot, &oldprot); } #endif /* !windows */ SLJIT_API_FUNC_ATTRIBUTE void sljit_free_unused_memory_exec(void) { /* This allocator does not keep unused memory for future allocations. */ }
6,858
28.821739
94
c
php-src
php-src-master/ext/pdo/pdo_sqlstate.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_pdo.h" #include "php_pdo_driver.h" struct pdo_sqlstate_info { const char state[5]; const char *desc; }; static HashTable err_hash; static const struct pdo_sqlstate_info err_initializer[] = { { "00000", "No error" }, { "01000", "Warning" }, { "01001", "Cursor operation conflict" }, { "01002", "Disconnect error" }, { "01003", "NULL value eliminated in set function" }, { "01004", "String data, right truncated" }, { "01006", "Privilege not revoked" }, { "01007", "Privilege not granted" }, { "01008", "Implicit zero bit padding" }, { "0100C", "Dynamic result sets returned" }, { "01P01", "Deprecated feature" }, { "01S00", "Invalid connection string attribute" }, { "01S01", "Error in row" }, { "01S02", "Option value changed" }, { "01S06", "Attempt to fetch before the result set returned the first rowset" }, { "01S07", "Fractional truncation" }, { "01S08", "Error saving File DSN" }, { "01S09", "Invalid keyword" }, { "02000", "No data" }, { "02001", "No additional dynamic result sets returned" }, { "03000", "Sql statement not yet complete" }, { "07002", "COUNT field incorrect" }, { "07005", "Prepared statement not a cursor-specification" }, { "07006", "Restricted data type attribute violation" }, { "07009", "Invalid descriptor index" }, { "07S01", "Invalid use of default parameter" }, { "08000", "Connection exception" }, { "08001", "Client unable to establish connection" }, { "08002", "Connection name in use" }, { "08003", "Connection does not exist" }, { "08004", "Server rejected the connection" }, { "08006", "Connection failure" }, { "08007", "Connection failure during transaction" }, { "08S01", "Communication link failure" }, { "09000", "Triggered action exception" }, { "0A000", "Feature not supported" }, { "0B000", "Invalid transaction initiation" }, { "0F000", "Locator exception" }, { "0F001", "Invalid locator specification" }, { "0L000", "Invalid grantor" }, { "0LP01", "Invalid grant operation" }, { "0P000", "Invalid role specification" }, { "21000", "Cardinality violation" }, { "21S01", "Insert value list does not match column list" }, { "21S02", "Degree of derived table does not match column list" }, { "22000", "Data exception" }, { "22001", "String data, right truncated" }, { "22002", "Indicator variable required but not supplied" }, { "22003", "Numeric value out of range" }, { "22004", "Null value not allowed" }, { "22005", "Error in assignment" }, { "22007", "Invalid datetime format" }, { "22008", "Datetime field overflow" }, { "22009", "Invalid time zone displacement value" }, { "2200B", "Escape character conflict" }, { "2200C", "Invalid use of escape character" }, { "2200D", "Invalid escape octet" }, { "2200F", "Zero length character string" }, { "2200G", "Most specific type mismatch" }, { "22010", "Invalid indicator parameter value" }, { "22011", "Substring error" }, { "22012", "Division by zero" }, { "22015", "Interval field overflow" }, { "22018", "Invalid character value for cast specification" }, { "22019", "Invalid escape character" }, { "2201B", "Invalid regular expression" }, { "2201E", "Invalid argument for logarithm" }, { "2201F", "Invalid argument for power function" }, { "2201G", "Invalid argument for width bucket function" }, { "22020", "Invalid limit value" }, { "22021", "Character not in repertoire" }, { "22022", "Indicator overflow" }, { "22023", "Invalid parameter value" }, { "22024", "Unterminated c string" }, { "22025", "Invalid escape sequence" }, { "22026", "String data, length mismatch" }, { "22027", "Trim error" }, { "2202E", "Array subscript error" }, { "22P01", "Floating point exception" }, { "22P02", "Invalid text representation" }, { "22P03", "Invalid binary representation" }, { "22P04", "Bad copy file format" }, { "22P05", "Untranslatable character" }, { "23000", "Integrity constraint violation" }, { "23001", "Restrict violation" }, { "23502", "Not null violation" }, { "23503", "Foreign key violation" }, { "23505", "Unique violation" }, { "23514", "Check violation" }, { "24000", "Invalid cursor state" }, { "25000", "Invalid transaction state" }, { "25001", "Active sql transaction" }, { "25002", "Branch transaction already active" }, { "25003", "Inappropriate access mode for branch transaction" }, { "25004", "Inappropriate isolation level for branch transaction" }, { "25005", "No active sql transaction for branch transaction" }, { "25006", "Read only sql transaction" }, { "25007", "Schema and data statement mixing not supported" }, { "25008", "Held cursor requires same isolation level" }, { "25P01", "No active sql transaction" }, { "25P02", "In failed sql transaction" }, { "25S01", "Transaction state" }, { "25S02", "Transaction is still active" }, { "25S03", "Transaction is rolled back" }, { "26000", "Invalid sql statement name" }, { "27000", "Triggered data change violation" }, { "28000", "Invalid authorization specification" }, { "2B000", "Dependent privilege descriptors still exist" }, { "2BP01", "Dependent objects still exist" }, { "2D000", "Invalid transaction termination" }, { "2F000", "Sql routine exception" }, { "2F002", "Modifying sql data not permitted" }, { "2F003", "Prohibited sql statement attempted" }, { "2F004", "Reading sql data not permitted" }, { "2F005", "Function executed no return statement" }, { "34000", "Invalid cursor name" }, { "38000", "External routine exception" }, { "38001", "Containing sql not permitted" }, { "38002", "Modifying sql data not permitted" }, { "38003", "Prohibited sql statement attempted" }, { "38004", "Reading sql data not permitted" }, { "39000", "External routine invocation exception" }, { "39001", "Invalid sqlstate returned" }, { "39004", "Null value not allowed" }, { "39P01", "Trigger protocol violated" }, { "39P02", "Srf protocol violated" }, { "3B000", "Savepoint exception" }, { "3B001", "Invalid savepoint specification" }, { "3C000", "Duplicate cursor name" }, { "3D000", "Invalid catalog name" }, { "3F000", "Invalid schema name" }, { "40000", "Transaction rollback" }, { "40001", "Serialization failure" }, { "40002", "Transaction integrity constraint violation" }, { "40003", "Statement completion unknown" }, { "40P01", "Deadlock detected" }, { "42000", "Syntax error or access violation" }, { "42501", "Insufficient privilege" }, { "42601", "Syntax error" }, { "42602", "Invalid name" }, { "42611", "Invalid column definition" }, { "42622", "Name too long" }, { "42701", "Duplicate column" }, { "42702", "Ambiguous column" }, { "42703", "Undefined column" }, { "42704", "Undefined object" }, { "42710", "Duplicate object" }, { "42712", "Duplicate alias" }, { "42723", "Duplicate function" }, { "42725", "Ambiguous function" }, { "42803", "Grouping error" }, { "42804", "Datatype mismatch" }, { "42809", "Wrong object type" }, { "42830", "Invalid foreign key" }, { "42846", "Cannot coerce" }, { "42883", "Undefined function" }, { "42939", "Reserved name" }, { "42P01", "Undefined table" }, { "42P02", "Undefined parameter" }, { "42P03", "Duplicate cursor" }, { "42P04", "Duplicate database" }, { "42P05", "Duplicate prepared statement" }, { "42P06", "Duplicate schema" }, { "42P07", "Duplicate table" }, { "42P08", "Ambiguous parameter" }, { "42P09", "Ambiguous alias" }, { "42P10", "Invalid column reference" }, { "42P11", "Invalid cursor definition" }, { "42P12", "Invalid database definition" }, { "42P13", "Invalid function definition" }, { "42P14", "Invalid prepared statement definition" }, { "42P15", "Invalid schema definition" }, { "42P16", "Invalid table definition" }, { "42P17", "Invalid object definition" }, { "42P18", "Indeterminate datatype" }, { "42S01", "Base table or view already exists" }, { "42S02", "Base table or view not found" }, { "42S11", "Index already exists" }, { "42S12", "Index not found" }, { "42S21", "Column already exists" }, { "42S22", "Column not found" }, { "44000", "WITH CHECK OPTION violation" }, { "53000", "Insufficient resources" }, { "53100", "Disk full" }, { "53200", "Out of memory" }, { "53300", "Too many connections" }, { "54000", "Program limit exceeded" }, { "54001", "Statement too complex" }, { "54011", "Too many columns" }, { "54023", "Too many arguments" }, { "55000", "Object not in prerequisite state" }, { "55006", "Object in use" }, { "55P02", "Cant change runtime param" }, { "55P03", "Lock not available" }, { "57000", "Operator intervention" }, { "57014", "Query canceled" }, { "57P01", "Admin shutdown" }, { "57P02", "Crash shutdown" }, { "57P03", "Cannot connect now" }, { "58030", "Io error" }, { "58P01", "Undefined file" }, { "58P02", "Duplicate file" }, { "F0000", "Config file error" }, { "F0001", "Lock file exists" }, { "HY000", "General error" }, { "HY001", "Memory allocation error" }, { "HY003", "Invalid application buffer type" }, { "HY004", "Invalid SQL data type" }, { "HY007", "Associated statement is not prepared" }, { "HY008", "Operation canceled" }, { "HY009", "Invalid use of null pointer" }, { "HY010", "Function sequence error" }, { "HY011", "Attribute cannot be set now" }, { "HY012", "Invalid transaction operation code" }, { "HY013", "Memory management error" }, { "HY014", "Limit on the number of handles exceeded" }, { "HY015", "No cursor name available" }, { "HY016", "Cannot modify an implementation row descriptor" }, { "HY017", "Invalid use of an automatically allocated descriptor handle" }, { "HY018", "Server declined cancel request" }, { "HY019", "Non-character and non-binary data sent in pieces" }, { "HY020", "Attempt to concatenate a null value" }, { "HY021", "Inconsistent descriptor information" }, { "HY024", "Invalid attribute value" }, { "HY090", "Invalid string or buffer length" }, { "HY091", "Invalid descriptor field identifier" }, { "HY092", "Invalid attribute/option identifier" }, { "HY093", "Invalid parameter number" }, { "HY095", "Function type out of range" }, { "HY096", "Invalid information type" }, { "HY097", "Column type out of range" }, { "HY098", "Scope type out of range" }, { "HY099", "Nullable type out of range" }, { "HY100", "Uniqueness option type out of range" }, { "HY101", "Accuracy option type out of range" }, { "HY103", "Invalid retrieval code" }, { "HY104", "Invalid precision or scale value" }, { "HY105", "Invalid parameter type" }, { "HY106", "Fetch type out of range" }, { "HY107", "Row value out of range" }, { "HY109", "Invalid cursor position" }, { "HY110", "Invalid driver completion" }, { "HY111", "Invalid bookmark value" }, { "HYC00", "Optional feature not implemented" }, { "HYT00", "Timeout expired" }, { "HYT01", "Connection timeout expired" }, { "IM001", "Driver does not support this function" }, { "IM002", "Data source name not found and no default driver specified" }, { "IM003", "Specified driver could not be loaded" }, { "IM004", "Driver's SQLAllocHandle on SQL_HANDLE_ENV failed" }, { "IM005", "Driver's SQLAllocHandle on SQL_HANDLE_DBC failed" }, { "IM006", "Driver's SQLSetConnectAttr failed" }, { "IM007", "No data source or driver specified; dialog prohibited" }, { "IM008", "Dialog failed" }, { "IM009", "Unable to load translation DLL" }, { "IM010", "Data source name too long" }, { "IM011", "Driver name too long" }, { "IM012", "DRIVER keyword syntax error" }, { "IM013", "Trace file error" }, { "IM014", "Invalid name of File DSN" }, { "IM015", "Corrupt file data source" }, { "P0000", "Plpgsql error" }, { "P0001", "Raise exception" }, { "XX000", "Internal error" }, { "XX001", "Data corrupted" }, { "XX002", "Index corrupted" } }; void pdo_sqlstate_fini_error_table(void) { zend_hash_destroy(&err_hash); } void pdo_sqlstate_init_error_table(void) { size_t i; const struct pdo_sqlstate_info *info; zend_hash_init(&err_hash, sizeof(err_initializer)/sizeof(err_initializer[0]), NULL, NULL, 1); for (i = 0; i < sizeof(err_initializer)/sizeof(err_initializer[0]); i++) { info = &err_initializer[i]; zend_hash_str_add_ptr(&err_hash, info->state, sizeof(info->state), (void *)info); } } const char *pdo_sqlstate_state_to_description(char *state) { const struct pdo_sqlstate_info *info; if ((info = zend_hash_str_find_ptr(&err_hash, state, sizeof(err_initializer[0].state))) != NULL) { return info->desc; } return NULL; }
13,491
39.884848
99
c
php-src
php-src-master/ext/pdo/php_pdo.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_PDO_H #define PHP_PDO_H #include "zend.h" extern zend_module_entry pdo_module_entry; #define phpext_pdo_ptr &pdo_module_entry #include "php_version.h" #define PHP_PDO_VERSION PHP_VERSION #ifdef PHP_WIN32 # if defined(PDO_EXPORTS) || (!defined(COMPILE_DL_PDO)) # define PDO_API __declspec(dllexport) # elif defined(COMPILE_DL_PDO) # define PDO_API __declspec(dllimport) # else # define PDO_API /* nothing special */ # endif #elif defined(__GNUC__) && __GNUC__ >= 4 # define PDO_API __attribute__ ((visibility("default"))) #else # define PDO_API /* nothing special */ #endif #ifdef ZTS # include "TSRM.h" #endif PHP_MINIT_FUNCTION(pdo); PHP_MSHUTDOWN_FUNCTION(pdo); PHP_MINFO_FUNCTION(pdo); #define REGISTER_PDO_CLASS_CONST_LONG(const_name, value) \ zend_declare_class_constant_long(php_pdo_get_dbh_ce(), const_name, sizeof(const_name)-1, (zend_long)value); #define REGISTER_PDO_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(php_pdo_get_dbh_ce(), const_name, sizeof(const_name)-1, value, sizeof(value)-1); #define LONG_CONST(c) (zend_long) c #define PDO_CONSTRUCT_CHECK \ if (!dbh->driver) { \ zend_throw_error(NULL, "PDO object is not initialized, constructor was not called"); \ RETURN_THROWS(); \ } \ #endif /* PHP_PDO_H */
2,272
33.439394
117
h
php-src
php-src-master/ext/pdo/php_pdo_error.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_PDO_ERROR_H #define PHP_PDO_ERROR_H #include "php_pdo_driver.h" PDO_API void pdo_handle_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt); #define PDO_DBH_CLEAR_ERR() do { \ strlcpy(dbh->error_code, PDO_ERR_NONE, sizeof(PDO_ERR_NONE)); \ if (dbh->query_stmt) { \ dbh->query_stmt = NULL; \ zval_ptr_dtor(&dbh->query_stmt_zval); \ } \ } while (0) #define PDO_STMT_CLEAR_ERR() strcpy(stmt->error_code, PDO_ERR_NONE) #define PDO_HANDLE_DBH_ERR() if (strcmp(dbh->error_code, PDO_ERR_NONE)) { pdo_handle_error(dbh, NULL); } #define PDO_HANDLE_STMT_ERR() if (strcmp(stmt->error_code, PDO_ERR_NONE)) { pdo_handle_error(stmt->dbh, stmt); } #endif /* PHP_PDO_ERROR_H */
1,675
45.555556
114
h
php-src
php-src-master/ext/pdo/php_pdo_int.h
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Wez Furlong <[email protected]> | | Marcus Boerger <[email protected]> | | Sterling Hughes <[email protected]> | +----------------------------------------------------------------------+ */ /* Stuff private to the PDO extension and not for consumption by PDO drivers * */ #include "php_pdo_error.h" extern HashTable pdo_driver_hash; extern zend_class_entry *pdo_exception_ce; int php_pdo_list_entry(void); void pdo_dbh_init(int module_number); void pdo_stmt_init(void); extern zend_object *pdo_dbh_new(zend_class_entry *ce); extern const zend_function_entry pdo_dbh_functions[]; extern zend_class_entry *pdo_dbh_ce; extern ZEND_RSRC_DTOR_FUNC(php_pdo_pdbh_dtor); extern zend_object *pdo_dbstmt_new(zend_class_entry *ce); extern const zend_function_entry pdo_dbstmt_functions[]; extern zend_class_entry *pdo_dbstmt_ce; void pdo_dbstmt_free_storage(zend_object *std); zend_object_iterator *pdo_stmt_iter_get(zend_class_entry *ce, zval *object, int by_ref); extern zend_object_handlers pdo_dbstmt_object_handlers; bool pdo_stmt_describe_columns(pdo_stmt_t *stmt); bool pdo_stmt_setup_fetch_mode(pdo_stmt_t *stmt, zend_long mode, uint32_t mode_arg_num, zval *args, uint32_t variadic_num_args); extern zend_object *pdo_row_new(zend_class_entry *ce); extern const zend_function_entry pdo_row_functions[]; extern zend_class_entry *pdo_row_ce; void pdo_row_free_storage(zend_object *std); extern zend_object_handlers pdo_row_object_handlers; zend_object_iterator *php_pdo_dbstmt_iter_get(zend_class_entry *ce, zval *object); extern pdo_driver_t *pdo_find_driver(const char *name, int namelen); void pdo_sqlstate_init_error_table(void); void pdo_sqlstate_fini_error_table(void); const char *pdo_sqlstate_state_to_description(char *state); bool pdo_hash_methods(pdo_dbh_object_t *dbh, int kind);
2,739
44.666667
88
h
php-src
php-src-master/ext/pdo_dblib/dblib_stmt.c
/* +----------------------------------------------------------------------+ | Copyright (c) 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: | | https://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: Wez Furlong <[email protected]> | | Frank M. Kromann <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "pdo/php_pdo.h" #include "pdo/php_pdo_driver.h" #include "php_pdo_dblib.h" #include "php_pdo_dblib_int.h" #include "zend_exceptions.h" /* {{{ pdo_dblib_get_field_name * * Return the data type name for a given TDS number * */ static char *pdo_dblib_get_field_name(int type) { /* * I don't return dbprtype(type) because it does not fully describe the type * (example: varchar is reported as char by dbprtype) * * FIX ME: Cache datatypes from server systypes table in pdo_dblib_handle_factory() * to make this future-proof. */ switch (type) { case 31: return "nvarchar"; case 34: return "image"; case 35: return "text"; case 36: return "uniqueidentifier"; case 37: return "varbinary"; /* & timestamp - Sybase AS12 */ case 38: return "bigint"; /* & bigintn - Sybase AS12 */ case 39: return "varchar"; /* & sysname & nvarchar - Sybase AS12 */ case 40: return "date"; case 41: return "time"; case 42: return "datetime2"; case 43: return "datetimeoffset"; case 45: return "binary"; /* Sybase AS12 */ case 47: return "char"; /* & nchar & uniqueidentifierstr Sybase AS12 */ case 48: return "tinyint"; case 50: return "bit"; /* Sybase AS12 */ case 52: return "smallint"; case 55: return "decimal"; /* Sybase AS12 */ case 56: return "int"; case 58: return "smalldatetime"; case 59: return "real"; case 60: return "money"; case 61: return "datetime"; case 62: return "float"; case 63: return "numeric"; /* or uint, ubigint, usmallint Sybase AS12 */ case 98: return "sql_variant"; case 99: return "ntext"; case 104: return "bit"; case 106: return "decimal"; /* decimal n on sybase */ case 108: return "numeric"; /* numeric n on sybase */ case 122: return "smallmoney"; case 127: return "bigint"; case 165: return "varbinary"; case 167: return "varchar"; case 173: return "binary"; case 175: return "char"; case 189: return "timestamp"; case 231: return "nvarchar"; case 239: return "nchar"; case 240: return "geometry"; case 241: return "xml"; default: return "unknown"; } } /* }}} */ static int pdo_dblib_stmt_cursor_closer(pdo_stmt_t *stmt) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; /* Cancel any pending results */ dbcancel(H->link); pdo_dblib_err_dtor(&H->err); return 1; } static int pdo_dblib_stmt_dtor(pdo_stmt_t *stmt) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_err_dtor(&S->err); efree(S); return 1; } static int pdo_dblib_stmt_next_rowset_no_cancel(pdo_stmt_t *stmt) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; RETCODE ret; int num_fields; do { ret = dbresults(H->link); num_fields = dbnumcols(H->link); } while (H->skip_empty_rowsets && num_fields <= 0 && ret == SUCCEED); if (FAIL == ret) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO_DBLIB: dbresults() returned FAIL"); return 0; } if (NO_MORE_RESULTS == ret) { return 0; } if (H->skip_empty_rowsets && num_fields <= 0) { return 0; } stmt->row_count = DBCOUNT(H->link); stmt->column_count = num_fields; return 1; } static int pdo_dblib_stmt_next_rowset(pdo_stmt_t *stmt) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; RETCODE ret = SUCCESS; /* Ideally use dbcanquery here, but there is a bug in FreeTDS's implementation of dbcanquery * It has been resolved but is currently only available in nightly builds */ while (NO_MORE_ROWS != ret) { ret = dbnextrow(H->link); if (FAIL == ret) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO_DBLIB: dbnextrow() returned FAIL"); return 0; } } return pdo_dblib_stmt_next_rowset_no_cancel(stmt); } static int pdo_dblib_stmt_execute(pdo_stmt_t *stmt) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; dbsetuserdata(H->link, (BYTE*) &S->err); pdo_dblib_stmt_cursor_closer(stmt); if (FAIL == dbcmd(H->link, ZSTR_VAL(stmt->active_query_string))) { return 0; } if (FAIL == dbsqlexec(H->link)) { return 0; } pdo_dblib_stmt_next_rowset_no_cancel(stmt); stmt->row_count = DBCOUNT(H->link); stmt->column_count = dbnumcols(H->link); return 1; } static int pdo_dblib_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, zend_long offset) { RETCODE ret; pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; ret = dbnextrow(H->link); if (FAIL == ret) { pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "PDO_DBLIB: dbnextrow() returned FAIL"); return 0; } if(NO_MORE_ROWS == ret) { return 0; } return 1; } static int pdo_dblib_stmt_describe(pdo_stmt_t *stmt, int colno) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; struct pdo_column_data *col; char *fname; if(colno >= stmt->column_count || colno < 0) { return FAILURE; } if (colno == 0) { S->computed_column_name_count = 0; } col = &stmt->columns[colno]; fname = (char*)dbcolname(H->link, colno+1); if (fname && *fname) { col->name = zend_string_init(fname, strlen(fname), 0); } else { if (S->computed_column_name_count > 0) { char buf[16]; int len; len = snprintf(buf, sizeof(buf), "computed%d", S->computed_column_name_count); col->name = zend_string_init(buf, len, 0); } else { col->name = ZSTR_INIT_LITERAL("computed", 0); } S->computed_column_name_count++; } col->maxlen = dbcollen(H->link, colno+1); return 1; } static int pdo_dblib_stmt_should_stringify_col(pdo_stmt_t *stmt, int coltype) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; switch (coltype) { case SQLDECIMAL: case SQLNUMERIC: case SQLMONEY: case SQLMONEY4: case SQLMONEYN: case SQLFLT4: case SQLFLT8: case SQLINT4: case SQLINT2: case SQLINT1: case SQLBIT: if (stmt->dbh->stringify) { return 1; } break; case SQLINT8: if (stmt->dbh->stringify) { return 1; } /* force stringify if DBBIGINT won't fit in zend_long */ /* this should only be an issue for 32-bit machines */ if (sizeof(zend_long) < sizeof(DBBIGINT)) { return 1; } break; #ifdef SQLMSDATETIME2 case SQLMSDATETIME2: #endif case SQLDATETIME: case SQLDATETIM4: if (H->datetime_convert) { return 1; } break; } return 0; } static void pdo_dblib_stmt_stringify_col(int coltype, LPBYTE data, DBINT data_len, zval *zv) { DBCHAR *tmp_data; /* FIXME: We allocate more than we need here */ DBINT tmp_data_len = 32 + (2 * (data_len)); switch (coltype) { case SQLDATETIME: case SQLDATETIM4: { if (tmp_data_len < DATETIME_MAX_LEN) { tmp_data_len = DATETIME_MAX_LEN; } break; } } tmp_data = emalloc(tmp_data_len); data_len = dbconvert(NULL, coltype, data, data_len, SQLCHAR, (LPBYTE) tmp_data, tmp_data_len); if (data_len > 0) { /* to prevent overflows, tmp_data_len is provided as a dest len for dbconvert() * this code previously passed a dest len of -1 * the FreeTDS impl of dbconvert() does an rtrim with that value, so replicate that behavior */ while (data_len > 0 && tmp_data[data_len - 1] == ' ') { data_len--; } ZVAL_STRINGL(zv, tmp_data, data_len); } else { ZVAL_EMPTY_STRING(zv); } efree(tmp_data); } static int pdo_dblib_stmt_get_col(pdo_stmt_t *stmt, int colno, zval *zv, enum pdo_param_type *type) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; int coltype; LPBYTE data; DBCHAR *tmp_data; DBINT data_len, tmp_data_len; coltype = dbcoltype(H->link, colno+1); data = dbdata(H->link, colno+1); data_len = dbdatlen(H->link, colno+1); if (data_len != 0 || data != NULL) { if (pdo_dblib_stmt_should_stringify_col(stmt, coltype) && dbwillconvert(coltype, SQLCHAR)) { pdo_dblib_stmt_stringify_col(coltype, data, data_len, zv); } else { switch (coltype) { case SQLCHAR: case SQLVARCHAR: case SQLTEXT: { #ifdef ilia_0 while (data_len>0 && data[data_len-1] == ' ') { /* nuke trailing whitespace */ data_len--; } #endif } case SQLVARBINARY: case SQLBINARY: case SQLIMAGE: { ZVAL_STRINGL(zv, (DBCHAR *) data, data_len); break; } #ifdef SQLMSDATETIME2 case SQLMSDATETIME2: #endif case SQLDATETIME: case SQLDATETIM4: { size_t dl; DBDATEREC di; DBDATEREC dt; dbconvert(H->link, coltype, data, -1, SQLDATETIME, (LPBYTE) &dt, -1); dbdatecrack(H->link, &di, (DBDATETIME *) &dt); dl = spprintf(&tmp_data, 20, "%04d-%02d-%02d %02d:%02d:%02d", #if defined(PHP_DBLIB_IS_MSSQL) || defined(MSDBLIB) di.year, di.month, di.day, di.hour, di.minute, di.second #else di.dateyear, di.datemonth+1, di.datedmonth, di.datehour, di.dateminute, di.datesecond #endif ); ZVAL_STRINGL(zv, tmp_data, dl); efree(tmp_data); break; } case SQLFLT4: ZVAL_DOUBLE(zv, *(DBFLT4 *) data); break; case SQLFLT8: ZVAL_DOUBLE(zv, *(DBFLT8 *) data); break; case SQLINT8: ZVAL_LONG(zv, *(DBBIGINT *) data); break; case SQLINT4: ZVAL_LONG(zv, *(DBINT *) data); break; case SQLINT2: ZVAL_LONG(zv, *(DBSMALLINT *) data); break; case SQLINT1: case SQLBIT: ZVAL_LONG(zv, *(DBTINYINT *) data); break; case SQLDECIMAL: case SQLNUMERIC: case SQLMONEY: case SQLMONEY4: case SQLMONEYN: { DBFLT8 float_value; dbconvert(NULL, coltype, data, 8, SQLFLT8, (LPBYTE) &float_value, -1); ZVAL_DOUBLE(zv, float_value); break; } case SQLUNIQUE: { if (H->stringify_uniqueidentifier) { /* 36-char hex string representation */ tmp_data_len = 36; tmp_data = safe_emalloc(tmp_data_len, sizeof(char), 1); data_len = dbconvert(NULL, SQLUNIQUE, data, data_len, SQLCHAR, (LPBYTE) tmp_data, tmp_data_len); zend_str_toupper(tmp_data, data_len); ZVAL_STRINGL(zv, tmp_data, data_len); efree(tmp_data); } else { /* 16-byte binary representation */ ZVAL_STRINGL(zv, (DBCHAR *) data, 16); } break; } default: { if (dbwillconvert(coltype, SQLCHAR)) { pdo_dblib_stmt_stringify_col(coltype, data, data_len, zv); } break; } } } } return 1; } static int pdo_dblib_stmt_get_column_meta(pdo_stmt_t *stmt, zend_long colno, zval *return_value) { pdo_dblib_stmt *S = (pdo_dblib_stmt*)stmt->driver_data; pdo_dblib_db_handle *H = S->H; DBTYPEINFO* dbtypeinfo; int coltype; if(colno >= stmt->column_count || colno < 0) { return FAILURE; } array_init(return_value); dbtypeinfo = dbcoltypeinfo(H->link, colno+1); if(!dbtypeinfo) return FAILURE; coltype = dbcoltype(H->link, colno+1); add_assoc_long(return_value, "max_length", dbcollen(H->link, colno+1) ); add_assoc_long(return_value, "precision", (int) dbtypeinfo->precision ); add_assoc_long(return_value, "scale", (int) dbtypeinfo->scale ); add_assoc_string(return_value, "column_source", dbcolsource(H->link, colno+1)); add_assoc_string(return_value, "native_type", pdo_dblib_get_field_name(coltype)); add_assoc_long(return_value, "native_type_id", coltype); add_assoc_long(return_value, "native_usertype_id", dbcolutype(H->link, colno+1)); switch (coltype) { case SQLBIT: case SQLINT1: case SQLINT2: case SQLINT4: add_assoc_long(return_value, "pdo_type", PDO_PARAM_INT); break; default: add_assoc_long(return_value, "pdo_type", PDO_PARAM_STR); break; } return 1; } const struct pdo_stmt_methods dblib_stmt_methods = { pdo_dblib_stmt_dtor, pdo_dblib_stmt_execute, pdo_dblib_stmt_fetch, pdo_dblib_stmt_describe, pdo_dblib_stmt_get_col, NULL, /* param hook */ NULL, /* set attr */ NULL, /* get attr */ pdo_dblib_stmt_get_column_meta, /* meta */ pdo_dblib_stmt_next_rowset, /* nextrow */ pdo_dblib_stmt_cursor_closer };
13,143
24.276923
102
c