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/Zend/zend_vm.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend 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_VM_H
#define ZEND_VM_H
BEGIN_EXTERN_C()
ZEND_API void ZEND_FASTCALL zend_vm_set_opcode_handler(zend_op* opcode);
ZEND_API void ZEND_FASTCALL zend_vm_set_opcode_handler_ex(zend_op* opcode, uint32_t op1_info, uint32_t op2_info, uint32_t res_info);
ZEND_API void ZEND_FASTCALL zend_serialize_opcode_handler(zend_op *op);
ZEND_API void ZEND_FASTCALL zend_deserialize_opcode_handler(zend_op *op);
ZEND_API const void* ZEND_FASTCALL zend_get_opcode_handler_func(const zend_op *op);
ZEND_API const zend_op *zend_get_halt_op(void);
ZEND_API int ZEND_FASTCALL zend_vm_call_opcode_handler(zend_execute_data *ex);
ZEND_API int zend_vm_kind(void);
ZEND_API bool zend_gcc_global_regs(void);
void zend_vm_init(void);
void zend_vm_dtor(void);
END_EXTERN_C()
#define ZEND_VM_SET_OPCODE_HANDLER(opline) zend_vm_set_opcode_handler(opline)
#endif
| 1,994 | 46.5 | 132 |
h
|
php-src
|
php-src-master/Zend/zend_vm_opcodes.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend 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]> |
| Dmitry Stogov <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef ZEND_VM_OPCODES_H
#define ZEND_VM_OPCODES_H
#define ZEND_VM_SPEC 1
#define ZEND_VM_LINES 0
#define ZEND_VM_KIND_CALL 1
#define ZEND_VM_KIND_SWITCH 2
#define ZEND_VM_KIND_GOTO 3
#define ZEND_VM_KIND_HYBRID 4
/* HYBRID requires support for computed GOTO and global register variables*/
#if (defined(__GNUC__) && defined(HAVE_GCC_GLOBAL_REGS))
# define ZEND_VM_KIND ZEND_VM_KIND_HYBRID
#else
# define ZEND_VM_KIND ZEND_VM_KIND_CALL
#endif
#if (ZEND_VM_KIND == ZEND_VM_KIND_HYBRID) && !defined(__SANITIZE_ADDRESS__)
# if ((defined(i386) && !defined(__PIC__)) || defined(__x86_64__) || defined(_M_X64))
# define ZEND_VM_HYBRID_JIT_RED_ZONE_SIZE 16
# endif
#endif
#define ZEND_VM_OP_SPEC 0x00000001
#define ZEND_VM_OP_CONST 0x00000002
#define ZEND_VM_OP_TMPVAR 0x00000004
#define ZEND_VM_OP_TMPVARCV 0x00000008
#define ZEND_VM_OP_MASK 0x000000f0
#define ZEND_VM_OP_NUM 0x00000010
#define ZEND_VM_OP_JMP_ADDR 0x00000020
#define ZEND_VM_OP_TRY_CATCH 0x00000030
#define ZEND_VM_OP_THIS 0x00000050
#define ZEND_VM_OP_NEXT 0x00000060
#define ZEND_VM_OP_CLASS_FETCH 0x00000070
#define ZEND_VM_OP_CONSTRUCTOR 0x00000080
#define ZEND_VM_OP_CONST_FETCH 0x00000090
#define ZEND_VM_OP_CACHE_SLOT 0x000000a0
#define ZEND_VM_EXT_VAR_FETCH 0x00010000
#define ZEND_VM_EXT_ISSET 0x00020000
#define ZEND_VM_EXT_CACHE_SLOT 0x00040000
#define ZEND_VM_EXT_ARRAY_INIT 0x00080000
#define ZEND_VM_EXT_REF 0x00100000
#define ZEND_VM_EXT_FETCH_REF 0x00200000
#define ZEND_VM_EXT_DIM_WRITE 0x00400000
#define ZEND_VM_EXT_MASK 0x0f000000
#define ZEND_VM_EXT_NUM 0x01000000
#define ZEND_VM_EXT_LAST_CATCH 0x02000000
#define ZEND_VM_EXT_JMP_ADDR 0x03000000
#define ZEND_VM_EXT_OP 0x04000000
#define ZEND_VM_EXT_TYPE 0x07000000
#define ZEND_VM_EXT_EVAL 0x08000000
#define ZEND_VM_EXT_TYPE_MASK 0x09000000
#define ZEND_VM_EXT_SRC 0x0b000000
#define ZEND_VM_NO_CONST_CONST 0x40000000
#define ZEND_VM_COMMUTATIVE 0x80000000
#define ZEND_VM_OP1_FLAGS(flags) (flags & 0xff)
#define ZEND_VM_OP2_FLAGS(flags) ((flags >> 8) & 0xff)
BEGIN_EXTERN_C()
ZEND_API const char* ZEND_FASTCALL zend_get_opcode_name(uint8_t opcode);
ZEND_API uint32_t ZEND_FASTCALL zend_get_opcode_flags(uint8_t opcode);
ZEND_API uint8_t zend_get_opcode_id(const char *name, size_t length);
END_EXTERN_C()
#define ZEND_NOP 0
#define ZEND_ADD 1
#define ZEND_SUB 2
#define ZEND_MUL 3
#define ZEND_DIV 4
#define ZEND_MOD 5
#define ZEND_SL 6
#define ZEND_SR 7
#define ZEND_CONCAT 8
#define ZEND_BW_OR 9
#define ZEND_BW_AND 10
#define ZEND_BW_XOR 11
#define ZEND_POW 12
#define ZEND_BW_NOT 13
#define ZEND_BOOL_NOT 14
#define ZEND_BOOL_XOR 15
#define ZEND_IS_IDENTICAL 16
#define ZEND_IS_NOT_IDENTICAL 17
#define ZEND_IS_EQUAL 18
#define ZEND_IS_NOT_EQUAL 19
#define ZEND_IS_SMALLER 20
#define ZEND_IS_SMALLER_OR_EQUAL 21
#define ZEND_ASSIGN 22
#define ZEND_ASSIGN_DIM 23
#define ZEND_ASSIGN_OBJ 24
#define ZEND_ASSIGN_STATIC_PROP 25
#define ZEND_ASSIGN_OP 26
#define ZEND_ASSIGN_DIM_OP 27
#define ZEND_ASSIGN_OBJ_OP 28
#define ZEND_ASSIGN_STATIC_PROP_OP 29
#define ZEND_ASSIGN_REF 30
#define ZEND_QM_ASSIGN 31
#define ZEND_ASSIGN_OBJ_REF 32
#define ZEND_ASSIGN_STATIC_PROP_REF 33
#define ZEND_PRE_INC 34
#define ZEND_PRE_DEC 35
#define ZEND_POST_INC 36
#define ZEND_POST_DEC 37
#define ZEND_PRE_INC_STATIC_PROP 38
#define ZEND_PRE_DEC_STATIC_PROP 39
#define ZEND_POST_INC_STATIC_PROP 40
#define ZEND_POST_DEC_STATIC_PROP 41
#define ZEND_JMP 42
#define ZEND_JMPZ 43
#define ZEND_JMPNZ 44
#define ZEND_JMPZ_EX 46
#define ZEND_JMPNZ_EX 47
#define ZEND_CASE 48
#define ZEND_CHECK_VAR 49
#define ZEND_SEND_VAR_NO_REF_EX 50
#define ZEND_CAST 51
#define ZEND_BOOL 52
#define ZEND_FAST_CONCAT 53
#define ZEND_ROPE_INIT 54
#define ZEND_ROPE_ADD 55
#define ZEND_ROPE_END 56
#define ZEND_BEGIN_SILENCE 57
#define ZEND_END_SILENCE 58
#define ZEND_INIT_FCALL_BY_NAME 59
#define ZEND_DO_FCALL 60
#define ZEND_INIT_FCALL 61
#define ZEND_RETURN 62
#define ZEND_RECV 63
#define ZEND_RECV_INIT 64
#define ZEND_SEND_VAL 65
#define ZEND_SEND_VAR_EX 66
#define ZEND_SEND_REF 67
#define ZEND_NEW 68
#define ZEND_INIT_NS_FCALL_BY_NAME 69
#define ZEND_FREE 70
#define ZEND_INIT_ARRAY 71
#define ZEND_ADD_ARRAY_ELEMENT 72
#define ZEND_INCLUDE_OR_EVAL 73
#define ZEND_UNSET_VAR 74
#define ZEND_UNSET_DIM 75
#define ZEND_UNSET_OBJ 76
#define ZEND_FE_RESET_R 77
#define ZEND_FE_FETCH_R 78
#define ZEND_EXIT 79
#define ZEND_FETCH_R 80
#define ZEND_FETCH_DIM_R 81
#define ZEND_FETCH_OBJ_R 82
#define ZEND_FETCH_W 83
#define ZEND_FETCH_DIM_W 84
#define ZEND_FETCH_OBJ_W 85
#define ZEND_FETCH_RW 86
#define ZEND_FETCH_DIM_RW 87
#define ZEND_FETCH_OBJ_RW 88
#define ZEND_FETCH_IS 89
#define ZEND_FETCH_DIM_IS 90
#define ZEND_FETCH_OBJ_IS 91
#define ZEND_FETCH_FUNC_ARG 92
#define ZEND_FETCH_DIM_FUNC_ARG 93
#define ZEND_FETCH_OBJ_FUNC_ARG 94
#define ZEND_FETCH_UNSET 95
#define ZEND_FETCH_DIM_UNSET 96
#define ZEND_FETCH_OBJ_UNSET 97
#define ZEND_FETCH_LIST_R 98
#define ZEND_FETCH_CONSTANT 99
#define ZEND_CHECK_FUNC_ARG 100
#define ZEND_EXT_STMT 101
#define ZEND_EXT_FCALL_BEGIN 102
#define ZEND_EXT_FCALL_END 103
#define ZEND_EXT_NOP 104
#define ZEND_TICKS 105
#define ZEND_SEND_VAR_NO_REF 106
#define ZEND_CATCH 107
#define ZEND_THROW 108
#define ZEND_FETCH_CLASS 109
#define ZEND_CLONE 110
#define ZEND_RETURN_BY_REF 111
#define ZEND_INIT_METHOD_CALL 112
#define ZEND_INIT_STATIC_METHOD_CALL 113
#define ZEND_ISSET_ISEMPTY_VAR 114
#define ZEND_ISSET_ISEMPTY_DIM_OBJ 115
#define ZEND_SEND_VAL_EX 116
#define ZEND_SEND_VAR 117
#define ZEND_INIT_USER_CALL 118
#define ZEND_SEND_ARRAY 119
#define ZEND_SEND_USER 120
#define ZEND_STRLEN 121
#define ZEND_DEFINED 122
#define ZEND_TYPE_CHECK 123
#define ZEND_VERIFY_RETURN_TYPE 124
#define ZEND_FE_RESET_RW 125
#define ZEND_FE_FETCH_RW 126
#define ZEND_FE_FREE 127
#define ZEND_INIT_DYNAMIC_CALL 128
#define ZEND_DO_ICALL 129
#define ZEND_DO_UCALL 130
#define ZEND_DO_FCALL_BY_NAME 131
#define ZEND_PRE_INC_OBJ 132
#define ZEND_PRE_DEC_OBJ 133
#define ZEND_POST_INC_OBJ 134
#define ZEND_POST_DEC_OBJ 135
#define ZEND_ECHO 136
#define ZEND_OP_DATA 137
#define ZEND_INSTANCEOF 138
#define ZEND_GENERATOR_CREATE 139
#define ZEND_MAKE_REF 140
#define ZEND_DECLARE_FUNCTION 141
#define ZEND_DECLARE_LAMBDA_FUNCTION 142
#define ZEND_DECLARE_CONST 143
#define ZEND_DECLARE_CLASS 144
#define ZEND_DECLARE_CLASS_DELAYED 145
#define ZEND_DECLARE_ANON_CLASS 146
#define ZEND_ADD_ARRAY_UNPACK 147
#define ZEND_ISSET_ISEMPTY_PROP_OBJ 148
#define ZEND_HANDLE_EXCEPTION 149
#define ZEND_USER_OPCODE 150
#define ZEND_ASSERT_CHECK 151
#define ZEND_JMP_SET 152
#define ZEND_UNSET_CV 153
#define ZEND_ISSET_ISEMPTY_CV 154
#define ZEND_FETCH_LIST_W 155
#define ZEND_SEPARATE 156
#define ZEND_FETCH_CLASS_NAME 157
#define ZEND_CALL_TRAMPOLINE 158
#define ZEND_DISCARD_EXCEPTION 159
#define ZEND_YIELD 160
#define ZEND_GENERATOR_RETURN 161
#define ZEND_FAST_CALL 162
#define ZEND_FAST_RET 163
#define ZEND_RECV_VARIADIC 164
#define ZEND_SEND_UNPACK 165
#define ZEND_YIELD_FROM 166
#define ZEND_COPY_TMP 167
#define ZEND_BIND_GLOBAL 168
#define ZEND_COALESCE 169
#define ZEND_SPACESHIP 170
#define ZEND_FUNC_NUM_ARGS 171
#define ZEND_FUNC_GET_ARGS 172
#define ZEND_FETCH_STATIC_PROP_R 173
#define ZEND_FETCH_STATIC_PROP_W 174
#define ZEND_FETCH_STATIC_PROP_RW 175
#define ZEND_FETCH_STATIC_PROP_IS 176
#define ZEND_FETCH_STATIC_PROP_FUNC_ARG 177
#define ZEND_FETCH_STATIC_PROP_UNSET 178
#define ZEND_UNSET_STATIC_PROP 179
#define ZEND_ISSET_ISEMPTY_STATIC_PROP 180
#define ZEND_FETCH_CLASS_CONSTANT 181
#define ZEND_BIND_LEXICAL 182
#define ZEND_BIND_STATIC 183
#define ZEND_FETCH_THIS 184
#define ZEND_SEND_FUNC_ARG 185
#define ZEND_ISSET_ISEMPTY_THIS 186
#define ZEND_SWITCH_LONG 187
#define ZEND_SWITCH_STRING 188
#define ZEND_IN_ARRAY 189
#define ZEND_COUNT 190
#define ZEND_GET_CLASS 191
#define ZEND_GET_CALLED_CLASS 192
#define ZEND_GET_TYPE 193
#define ZEND_ARRAY_KEY_EXISTS 194
#define ZEND_MATCH 195
#define ZEND_CASE_STRICT 196
#define ZEND_MATCH_ERROR 197
#define ZEND_JMP_NULL 198
#define ZEND_CHECK_UNDEF_ARGS 199
#define ZEND_FETCH_GLOBALS 200
#define ZEND_VERIFY_NEVER_TYPE 201
#define ZEND_CALLABLE_CONVERT 202
#define ZEND_BIND_INIT_STATIC_OR_JMP 203
#define ZEND_VM_LAST_OPCODE 203
#endif
| 12,719 | 42.412969 | 85 |
h
|
php-src
|
php-src-master/Zend/zend_vm_trace_handlers.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend 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]> |
+----------------------------------------------------------------------+
*/
#include "zend_sort.h"
#define VM_TRACE(op) zend_vm_trace(#op, sizeof(#op)-1);
#define VM_TRACE_START() zend_vm_trace_init();
#define VM_TRACE_END() zend_vm_trace_finish();
static HashTable vm_trace_ht;
static void zend_vm_trace(const char *op, size_t op_len)
{
static const char *last = NULL;
static size_t last_len = 0;
char buf[256];
size_t len;
zval tmp, *zv;
if (EXPECTED(last)) {
len = last_len + 1 + op_len;
memcpy(buf, last, last_len);
buf[last_len] = ' ';
memcpy(buf + last_len + 1, op, op_len + 1);
zv = zend_hash_str_find(&vm_trace_ht, buf, len);
if (EXPECTED(zv)) {
if (EXPECTED(Z_LVAL_P(zv) < ZEND_LONG_MAX)) {
Z_LVAL_P(zv)++;
}
} else {
ZVAL_LONG(&tmp, 1);
zend_hash_str_add_new(&vm_trace_ht, buf, len, &tmp);
}
}
last = op;
last_len = op_len;
}
static int zend_vm_trace_compare(const Bucket *p1, const Bucket *p2)
{
if (Z_LVAL(p1->val) < Z_LVAL(p2->val)) {
return 1;
} else if (Z_LVAL(p1->val) > Z_LVAL(p2->val)) {
return -1;
} else {
return 0;
}
}
static void zend_vm_trace_finish(void)
{
zend_string *key;
zval *val;
FILE *f;
f = fopen("zend_vm_trace.log", "w+");
if (f) {
zend_hash_sort(&vm_trace_ht, (compare_func_t)zend_vm_trace_compare, 0);
ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(&vm_trace_ht, key, val) {
fprintf(f, "%s "ZEND_LONG_FMT"\n", ZSTR_VAL(key), Z_LVAL_P(val));
} ZEND_HASH_FOREACH_END();
fclose(f);
}
zend_hash_destroy(&vm_trace_ht);
}
static void zend_vm_trace_init(void)
{
FILE *f;
zend_hash_init(&vm_trace_ht, 0, NULL, NULL, 1);
f = fopen("zend_vm_trace.log", "r");
if (f) {
char buf[256];
size_t len;
zval tmp;
while (!feof(f)) {
if (fgets(buf, sizeof(buf)-1, f)) {
len = strlen(buf);
while (len > 0 && buf[len-1] <= ' ') {
len--;
buf[len] = 0;
}
while (len > 0 && buf[len-1] >= '0' && buf[len-1] <= '9') {
len--;
}
if (len > 1) {
buf[len-1] = 0;
ZVAL_LONG(&tmp, ZEND_STRTOL(buf + len, NULL, 10));
zend_hash_str_add(&vm_trace_ht, buf, len - 1, &tmp);
}
}
}
fclose(f);
}
}
| 3,216 | 27.469027 | 75 |
h
|
php-src
|
php-src-master/Zend/zend_vm_trace_lines.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend 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]> |
+----------------------------------------------------------------------+
*/
#include "zend_sort.h"
#define VM_TRACE(op) zend_vm_trace(execute_data, opline);
#define VM_TRACE_START() zend_vm_trace_init();
#define VM_TRACE_END() zend_vm_trace_finish();
static FILE *vm_trace_file;
static void zend_vm_trace(const zend_execute_data *execute_data, const zend_op *opline)
{
if (EX(func) && EX(func)->op_array.filename) {
fprintf(vm_trace_file, "%s:%d\n", ZSTR_VAL(EX(func)->op_array.filename), opline->lineno);
}
}
static void zend_vm_trace_finish(void)
{
fclose(vm_trace_file);
}
static void zend_vm_trace_init(void)
{
vm_trace_file = fopen("zend_vm_trace.log", "w+");
}
| 1,755 | 39.837209 | 91 |
h
|
php-src
|
php-src-master/Zend/zend_vm_trace_map.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend 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]> |
+----------------------------------------------------------------------+
*/
#include "zend_vm_handlers.h"
#include "zend_sort.h"
#define GEN_MAP(n, name) do { \
ZVAL_LONG(&tmp, (zend_long)(uintptr_t)zend_opcode_handlers[n]); \
zend_hash_str_add(&vm_trace_ht, #name, sizeof(#name) - 1, &tmp); \
} while (0);
#define VM_TRACE_START() do { \
zval tmp; \
zend_hash_init(&vm_trace_ht, 0, NULL, NULL, 1); \
VM_HANDLERS(GEN_MAP) \
zend_vm_trace_init(); \
} while (0)
#ifdef _WIN64
# define ADDR_FMT "%016I64x"
#elif SIZEOF_SIZE_T == 4
# define ADDR_FMT "%08zx"
#elif SIZEOF_SIZE_T == 8
# define ADDR_FMT "%016zx"
#else
# error "Unknown SIZEOF_SIZE_T"
#endif
static HashTable vm_trace_ht;
static int zend_vm_trace_compare(const Bucket *p1, const Bucket *p2)
{
if (Z_LVAL(p1->val) > Z_LVAL(p2->val)) {
return 1;
} else if (Z_LVAL(p1->val) < Z_LVAL(p2->val)) {
return -1;
} else {
return 0;
}
}
static void zend_vm_trace_init(void)
{
FILE *f;
zend_string *key, *prev_key;
zval *val;
zend_long prev_addr;
f = fopen("zend_vm.map", "w+");
if (f) {
zend_hash_sort(&vm_trace_ht, (bucket_compare_func_t)zend_vm_trace_compare, 0);
prev_key = NULL;
ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(&vm_trace_ht, key, val) {
if (prev_key) {
fprintf(f, ADDR_FMT" "ADDR_FMT" t %s\n", prev_addr, Z_LVAL_P(val) - prev_addr, ZSTR_VAL(prev_key));
}
prev_key = key;
prev_addr = Z_LVAL_P(val);
} ZEND_HASH_FOREACH_END();
if (prev_key) {
fprintf(f, ADDR_FMT" "ADDR_FMT" t %s\n", prev_addr, 0, ZSTR_VAL(prev_key));
}
fclose(f);
}
zend_hash_destroy(&vm_trace_ht);
}
| 2,665 | 31.512195 | 103 |
h
|
php-src
|
php-src-master/Zend/Optimizer/compact_vars.c
|
/*
+----------------------------------------------------------------------+
| Zend Engine, Removing unused variables |
+----------------------------------------------------------------------+
| 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: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_bitset.h"
/* This pass removes all CVs and temporaries that are completely unused. It does *not* merge any CVs or TMPs.
* This pass does not operate on SSA form anymore. */
void zend_optimizer_compact_vars(zend_op_array *op_array) {
int i;
ALLOCA_FLAG(use_heap1);
ALLOCA_FLAG(use_heap2);
uint32_t used_vars_len = zend_bitset_len(op_array->last_var + op_array->T);
zend_bitset used_vars = ZEND_BITSET_ALLOCA(used_vars_len, use_heap1);
uint32_t *vars_map = do_alloca((op_array->last_var + op_array->T) * sizeof(uint32_t), use_heap2);
uint32_t num_cvs, num_tmps;
/* Determine which CVs are used */
zend_bitset_clear(used_vars, used_vars_len);
for (i = 0; i < op_array->last; i++) {
zend_op *opline = &op_array->opcodes[i];
if (opline->op1_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
zend_bitset_incl(used_vars, VAR_NUM(opline->op1.var));
}
if (opline->op2_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
zend_bitset_incl(used_vars, VAR_NUM(opline->op2.var));
}
if (opline->result_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
zend_bitset_incl(used_vars, VAR_NUM(opline->result.var));
if (opline->opcode == ZEND_ROPE_INIT) {
uint32_t num = ((opline->extended_value * sizeof(zend_string*)) + (sizeof(zval) - 1)) / sizeof(zval);
while (num > 1) {
num--;
zend_bitset_incl(used_vars, VAR_NUM(opline->result.var) + num);
}
}
}
}
num_cvs = 0;
for (i = 0; i < op_array->last_var; i++) {
if (zend_bitset_in(used_vars, i)) {
vars_map[i] = num_cvs++;
} else {
vars_map[i] = (uint32_t) -1;
}
}
num_tmps = 0;
for (i = op_array->last_var; i < op_array->last_var + op_array->T; i++) {
if (zend_bitset_in(used_vars, i)) {
vars_map[i] = num_cvs + num_tmps++;
} else {
vars_map[i] = (uint32_t) -1;
}
}
free_alloca(used_vars, use_heap1);
if (num_cvs == op_array->last_var && num_tmps == op_array->T) {
free_alloca(vars_map, use_heap2);
return;
}
ZEND_ASSERT(num_cvs <= op_array->last_var);
ZEND_ASSERT(num_tmps <= op_array->T);
/* Update CV and TMP references in opcodes */
for (i = 0; i < op_array->last; i++) {
zend_op *opline = &op_array->opcodes[i];
if (opline->op1_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
opline->op1.var = NUM_VAR(vars_map[VAR_NUM(opline->op1.var)]);
}
if (opline->op2_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
opline->op2.var = NUM_VAR(vars_map[VAR_NUM(opline->op2.var)]);
}
if (opline->result_type & (IS_CV|IS_VAR|IS_TMP_VAR)) {
opline->result.var = NUM_VAR(vars_map[VAR_NUM(opline->result.var)]);
}
}
/* Update CV name table */
if (num_cvs != op_array->last_var) {
if (num_cvs) {
zend_string **names = safe_emalloc(sizeof(zend_string *), num_cvs, 0);
for (i = 0; i < op_array->last_var; i++) {
if (vars_map[i] != (uint32_t) -1) {
names[vars_map[i]] = op_array->vars[i];
} else {
zend_string_release_ex(op_array->vars[i], 0);
}
}
efree(op_array->vars);
op_array->vars = names;
} else {
for (i = 0; i < op_array->last_var; i++) {
zend_string_release_ex(op_array->vars[i], 0);
}
efree(op_array->vars);
op_array->vars = NULL;
}
op_array->last_var = num_cvs;
}
op_array->T = num_tmps;
free_alloca(vars_map, use_heap2);
}
| 4,393 | 34.435484 | 109 |
c
|
php-src
|
php-src-master/Zend/Optimizer/escape_analysis.c
|
/*
+----------------------------------------------------------------------+
| Zend OPcache, Escape Analysis |
+----------------------------------------------------------------------+
| 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]> |
+----------------------------------------------------------------------+
*/
#include "Optimizer/zend_optimizer.h"
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_bitset.h"
#include "zend_cfg.h"
#include "zend_ssa.h"
#include "zend_inference.h"
#include "zend_dump.h"
/*
* T. Kotzmann and H. Mossenbock. Escape analysis in the context of dynamic
* compilation and deoptimization. In Proceedings of the International
* Conference on Virtual Execution Environments, pages 111-120, Chicago,
* June 2005
*/
static zend_always_inline void union_find_init(int *parent, int *size, int count) /* {{{ */
{
int i;
for (i = 0; i < count; i++) {
parent[i] = i;
size[i] = 1;
}
}
/* }}} */
static zend_always_inline int union_find_root(int *parent, int i) /* {{{ */
{
int p = parent[i];
while (i != p) {
p = parent[p];
parent[i] = p;
i = p;
p = parent[i];
}
return i;
}
/* }}} */
static zend_always_inline void union_find_unite(int *parent, int *size, int i, int j) /* {{{ */
{
int r1 = union_find_root(parent, i);
int r2 = union_find_root(parent, j);
if (r1 != r2) {
if (size[r1] < size[r2]) {
parent[r1] = r2;
size[r2] += size[r1];
} else {
parent[r2] = r1;
size[r1] += size[r2];
}
}
}
/* }}} */
static zend_result zend_build_equi_escape_sets(int *parent, zend_op_array *op_array, zend_ssa *ssa) /* {{{ */
{
zend_ssa_var *ssa_vars = ssa->vars;
int ssa_vars_count = ssa->vars_count;
zend_ssa_phi *p;
int i, j;
int *size;
ALLOCA_FLAG(use_heap)
size = do_alloca(sizeof(int) * ssa_vars_count, use_heap);
if (!size) {
return FAILURE;
}
union_find_init(parent, size, ssa_vars_count);
for (i = 0; i < ssa_vars_count; i++) {
if (ssa_vars[i].definition_phi) {
p = ssa_vars[i].definition_phi;
if (p->pi >= 0) {
union_find_unite(parent, size, i, p->sources[0]);
} else {
for (j = 0; j < ssa->cfg.blocks[p->block].predecessors_count; j++) {
union_find_unite(parent, size, i, p->sources[j]);
}
}
} else if (ssa_vars[i].definition >= 0) {
int def = ssa_vars[i].definition;
zend_ssa_op *op = ssa->ops + def;
zend_op *opline = op_array->opcodes + def;
if (op->op1_def >= 0) {
if (op->op1_use >= 0) {
if (opline->opcode != ZEND_ASSIGN) {
union_find_unite(parent, size, op->op1_def, op->op1_use);
}
}
if (opline->opcode == ZEND_ASSIGN && op->op2_use >= 0) {
union_find_unite(parent, size, op->op1_def, op->op2_use);
}
}
if (op->op2_def >= 0) {
if (op->op2_use >= 0) {
union_find_unite(parent, size, op->op2_def, op->op2_use);
}
}
if (op->result_def >= 0) {
if (op->result_use >= 0) {
if (opline->opcode != ZEND_QM_ASSIGN) {
union_find_unite(parent, size, op->result_def, op->result_use);
}
}
if (opline->opcode == ZEND_QM_ASSIGN && op->op1_use >= 0) {
union_find_unite(parent, size, op->result_def, op->op1_use);
}
if (opline->opcode == ZEND_ASSIGN && op->op2_use >= 0) {
union_find_unite(parent, size, op->result_def, op->op2_use);
}
if (opline->opcode == ZEND_ASSIGN && op->op1_def >= 0) {
union_find_unite(parent, size, op->result_def, op->op1_def);
}
}
}
}
for (i = 0; i < ssa_vars_count; i++) {
parent[i] = union_find_root(parent, i);
}
free_alloca(size, use_heap);
return SUCCESS;
}
/* }}} */
static bool is_allocation_def(zend_op_array *op_array, zend_ssa *ssa, int def, int var, const zend_script *script) /* {{{ */
{
zend_ssa_op *ssa_op = ssa->ops + def;
zend_op *opline = op_array->opcodes + def;
if (ssa_op->result_def == var) {
switch (opline->opcode) {
case ZEND_INIT_ARRAY:
return 1;
case ZEND_NEW: {
/* objects with destructors should escape */
zend_class_entry *ce = zend_optimizer_get_class_entry_from_op1(
script, op_array, opline);
uint32_t forbidden_flags =
/* These flags will always cause an exception */
ZEND_ACC_IMPLICIT_ABSTRACT_CLASS | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS
| ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT;
if (ce && !ce->parent && !ce->create_object && !ce->constructor &&
!ce->destructor && !ce->__get && !ce->__set &&
!(ce->ce_flags & forbidden_flags) &&
(ce->ce_flags & ZEND_ACC_CONSTANTS_UPDATED)) {
return 1;
}
break;
}
case ZEND_QM_ASSIGN:
if (opline->op1_type == IS_CONST
&& Z_TYPE_P(CRT_CONSTANT(opline->op1)) == IS_ARRAY) {
return 1;
}
if (opline->op1_type == IS_CV && (OP1_INFO() & MAY_BE_ARRAY)) {
return 1;
}
break;
case ZEND_ASSIGN:
if (opline->op1_type == IS_CV && (OP1_INFO() & MAY_BE_ARRAY)) {
return 1;
}
break;
}
} else if (ssa_op->op1_def == var) {
switch (opline->opcode) {
case ZEND_ASSIGN:
if (opline->op2_type == IS_CONST
&& Z_TYPE_P(CRT_CONSTANT(opline->op2)) == IS_ARRAY) {
return 1;
}
if (opline->op2_type == IS_CV && (OP2_INFO() & MAY_BE_ARRAY)) {
return 1;
}
break;
case ZEND_ASSIGN_DIM:
if (OP1_INFO() & (MAY_BE_UNDEF | MAY_BE_NULL | MAY_BE_FALSE)) {
/* implicit object/array allocation */
return 1;
}
break;
}
}
return 0;
}
/* }}} */
static bool is_local_def(zend_op_array *op_array, zend_ssa *ssa, int def, int var, const zend_script *script) /* {{{ */
{
zend_ssa_op *op = ssa->ops + def;
zend_op *opline = op_array->opcodes + def;
if (op->result_def == var) {
switch (opline->opcode) {
case ZEND_INIT_ARRAY:
case ZEND_ADD_ARRAY_ELEMENT:
case ZEND_QM_ASSIGN:
case ZEND_ASSIGN:
return 1;
case ZEND_NEW: {
/* objects with destructors should escape */
zend_class_entry *ce = zend_optimizer_get_class_entry_from_op1(
script, op_array, opline);
if (ce && !ce->create_object && !ce->constructor &&
!ce->destructor && !ce->__get && !ce->__set && !ce->parent) {
return 1;
}
break;
}
}
} else if (op->op1_def == var) {
switch (opline->opcode) {
case ZEND_ASSIGN:
case ZEND_ASSIGN_DIM:
case ZEND_ASSIGN_OBJ:
case ZEND_ASSIGN_OBJ_REF:
case ZEND_ASSIGN_DIM_OP:
case ZEND_ASSIGN_OBJ_OP:
case ZEND_PRE_INC_OBJ:
case ZEND_PRE_DEC_OBJ:
case ZEND_POST_INC_OBJ:
case ZEND_POST_DEC_OBJ:
return 1;
}
}
return 0;
}
/* }}} */
static bool is_escape_use(zend_op_array *op_array, zend_ssa *ssa, int use, int var) /* {{{ */
{
zend_ssa_op *ssa_op = ssa->ops + use;
zend_op *opline = op_array->opcodes + use;
if (ssa_op->op1_use == var) {
switch (opline->opcode) {
case ZEND_ASSIGN:
/* no_val */
break;
case ZEND_QM_ASSIGN:
if (opline->op1_type == IS_CV) {
if (OP1_INFO() & MAY_BE_OBJECT) {
/* object aliasing */
return 1;
}
}
break;
case ZEND_ISSET_ISEMPTY_DIM_OBJ:
case ZEND_ISSET_ISEMPTY_PROP_OBJ:
case ZEND_FETCH_DIM_R:
case ZEND_FETCH_OBJ_R:
case ZEND_FETCH_DIM_IS:
case ZEND_FETCH_OBJ_IS:
break;
case ZEND_ASSIGN_OP:
return 1;
case ZEND_ASSIGN_DIM_OP:
case ZEND_ASSIGN_OBJ_OP:
case ZEND_ASSIGN_STATIC_PROP_OP:
case ZEND_ASSIGN_DIM:
case ZEND_ASSIGN_OBJ:
case ZEND_ASSIGN_OBJ_REF:
break;
case ZEND_PRE_INC_OBJ:
case ZEND_PRE_DEC_OBJ:
case ZEND_POST_INC_OBJ:
case ZEND_POST_DEC_OBJ:
break;
case ZEND_INIT_ARRAY:
case ZEND_ADD_ARRAY_ELEMENT:
if (opline->extended_value & ZEND_ARRAY_ELEMENT_REF) {
return 1;
}
if (OP1_INFO() & MAY_BE_OBJECT) {
/* object aliasing */
return 1;
}
/* reference dependencies processed separately */
break;
case ZEND_OP_DATA:
if ((opline-1)->opcode != ZEND_ASSIGN_DIM
&& (opline-1)->opcode != ZEND_ASSIGN_OBJ) {
return 1;
}
if (OP1_INFO() & MAY_BE_OBJECT) {
/* object aliasing */
return 1;
}
opline--;
ssa_op--;
if (opline->op1_type != IS_CV
|| (OP1_INFO() & MAY_BE_REF)
|| (ssa_op->op1_def >= 0 && ssa->vars[ssa_op->op1_def].alias)) {
/* assignment into escaping structure */
return 1;
}
/* reference dependencies processed separately */
break;
default:
return 1;
}
}
if (ssa_op->op2_use == var) {
switch (opline->opcode) {
case ZEND_ASSIGN:
if (opline->op1_type != IS_CV
|| (OP1_INFO() & MAY_BE_REF)
|| (ssa_op->op1_def >= 0 && ssa->vars[ssa_op->op1_def].alias)) {
/* assignment into escaping variable */
return 1;
}
if (opline->op2_type == IS_CV || opline->result_type != IS_UNUSED) {
if (OP2_INFO() & MAY_BE_OBJECT) {
/* object aliasing */
return 1;
}
}
break;
default:
return 1;
}
}
if (ssa_op->result_use == var) {
switch (opline->opcode) {
case ZEND_ASSIGN:
case ZEND_QM_ASSIGN:
case ZEND_INIT_ARRAY:
case ZEND_ADD_ARRAY_ELEMENT:
break;
default:
return 1;
}
}
return 0;
}
/* }}} */
zend_result zend_ssa_escape_analysis(const zend_script *script, zend_op_array *op_array, zend_ssa *ssa) /* {{{ */
{
zend_ssa_var *ssa_vars = ssa->vars;
int ssa_vars_count = ssa->vars_count;
int i, root, use;
int *ees;
bool has_allocations;
int num_non_escaped;
ALLOCA_FLAG(use_heap)
if (!ssa_vars) {
return SUCCESS;
}
has_allocations = 0;
for (i = op_array->last_var; i < ssa_vars_count; i++) {
if (ssa_vars[i].definition >= 0
&& (ssa->var_info[i].type & (MAY_BE_ARRAY|MAY_BE_OBJECT))
&& is_allocation_def(op_array, ssa, ssa_vars[i].definition, i, script)) {
has_allocations = 1;
break;
}
}
if (!has_allocations) {
return SUCCESS;
}
/* 1. Build EES (Equi-Escape Sets) */
ees = do_alloca(sizeof(int) * ssa_vars_count, use_heap);
if (!ees) {
return FAILURE;
}
if (zend_build_equi_escape_sets(ees, op_array, ssa) == FAILURE) {
return FAILURE;
}
/* 2. Identify Allocations */
num_non_escaped = 0;
for (i = op_array->last_var; i < ssa_vars_count; i++) {
root = ees[i];
if (ssa_vars[root].escape_state > ESCAPE_STATE_NO_ESCAPE) {
/* already escape. skip */
} else if (ssa_vars[i].alias && (ssa->var_info[i].type & MAY_BE_REF)) {
if (ssa_vars[root].escape_state == ESCAPE_STATE_NO_ESCAPE) {
num_non_escaped--;
}
ssa_vars[root].escape_state = ESCAPE_STATE_GLOBAL_ESCAPE;
} else if (ssa_vars[i].definition >= 0
&& (ssa->var_info[i].type & (MAY_BE_ARRAY|MAY_BE_OBJECT))) {
if (!is_local_def(op_array, ssa, ssa_vars[i].definition, i, script)) {
if (ssa_vars[root].escape_state == ESCAPE_STATE_NO_ESCAPE) {
num_non_escaped--;
}
ssa_vars[root].escape_state = ESCAPE_STATE_GLOBAL_ESCAPE;
} else if (ssa_vars[root].escape_state == ESCAPE_STATE_UNKNOWN
&& is_allocation_def(op_array, ssa, ssa_vars[i].definition, i, script)) {
ssa_vars[root].escape_state = ESCAPE_STATE_NO_ESCAPE;
num_non_escaped++;
}
}
}
/* 3. Mark escaped EES */
if (num_non_escaped) {
for (i = 0; i < ssa_vars_count; i++) {
if (ssa_vars[i].use_chain >= 0) {
root = ees[i];
if (ssa_vars[root].escape_state == ESCAPE_STATE_NO_ESCAPE) {
FOREACH_USE(ssa_vars + i, use) {
if (is_escape_use(op_array, ssa, use, i)) {
ssa_vars[root].escape_state = ESCAPE_STATE_GLOBAL_ESCAPE;
num_non_escaped--;
if (num_non_escaped == 0) {
i = ssa_vars_count;
}
break;
}
} FOREACH_USE_END();
}
}
}
}
/* 4. Process referential dependencies */
if (num_non_escaped) {
bool changed;
do {
changed = 0;
for (i = 0; i < ssa_vars_count; i++) {
if (ssa_vars[i].use_chain >= 0) {
root = ees[i];
if (ssa_vars[root].escape_state == ESCAPE_STATE_NO_ESCAPE) {
FOREACH_USE(ssa_vars + i, use) {
zend_ssa_op *op = ssa->ops + use;
zend_op *opline = op_array->opcodes + use;
int enclosing_root;
if (opline->opcode == ZEND_OP_DATA &&
((opline-1)->opcode == ZEND_ASSIGN_DIM ||
(opline-1)->opcode == ZEND_ASSIGN_OBJ ||
(opline-1)->opcode == ZEND_ASSIGN_OBJ_REF) &&
op->op1_use == i &&
(op-1)->op1_use >= 0) {
enclosing_root = ees[(op-1)->op1_use];
} else if ((opline->opcode == ZEND_INIT_ARRAY ||
opline->opcode == ZEND_ADD_ARRAY_ELEMENT) &&
op->op1_use == i &&
op->result_def >= 0) {
enclosing_root = ees[op->result_def];
} else {
continue;
}
if (ssa_vars[enclosing_root].escape_state == ESCAPE_STATE_UNKNOWN ||
ssa_vars[enclosing_root].escape_state > ssa_vars[root].escape_state) {
if (ssa_vars[enclosing_root].escape_state == ESCAPE_STATE_UNKNOWN) {
ssa_vars[root].escape_state = ESCAPE_STATE_GLOBAL_ESCAPE;
} else {
ssa_vars[root].escape_state = ssa_vars[enclosing_root].escape_state;
}
if (ssa_vars[root].escape_state == ESCAPE_STATE_GLOBAL_ESCAPE) {
num_non_escaped--;
if (num_non_escaped == 0) {
changed = 0;
} else {
changed = 1;
}
break;
} else {
changed = 1;
}
}
} FOREACH_USE_END();
}
}
}
} while (changed);
}
/* 5. Propagate values of escape sets to variables */
for (i = 0; i < ssa_vars_count; i++) {
root = ees[i];
if (i != root) {
ssa_vars[i].escape_state = ssa_vars[root].escape_state;
}
}
free_alloca(ees, use_heap);
return SUCCESS;
}
/* }}} */
| 14,353 | 26.445507 | 124 |
c
|
php-src
|
php-src-master/Zend/Optimizer/nop_removal.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]> |
+----------------------------------------------------------------------+
*/
/* pass 10:
* - remove NOPs
*/
#include "Optimizer/zend_optimizer.h"
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_API.h"
#include "zend_constants.h"
#include "zend_execute.h"
#include "zend_vm.h"
void zend_optimizer_nop_removal(zend_op_array *op_array, zend_optimizer_ctx *ctx)
{
zend_op *end, *opline;
uint32_t new_count, i, shift;
int j;
uint32_t *shiftlist;
ALLOCA_FLAG(use_heap);
shiftlist = (uint32_t *)do_alloca(sizeof(uint32_t) * op_array->last, use_heap);
i = new_count = shift = 0;
end = op_array->opcodes + op_array->last;
for (opline = op_array->opcodes; opline < end; opline++) {
/* Kill JMP-over-NOP-s */
if (opline->opcode == ZEND_JMP && ZEND_OP1_JMP_ADDR(opline) > op_array->opcodes + i) {
/* check if there are only NOPs under the branch */
zend_op *target = ZEND_OP1_JMP_ADDR(opline) - 1;
while (target->opcode == ZEND_NOP) {
target--;
}
if (target == opline) {
/* only NOPs */
opline->opcode = ZEND_NOP;
}
}
shiftlist[i++] = shift;
if (opline->opcode == ZEND_NOP) {
shift++;
} else {
if (shift) {
zend_op *new_opline = op_array->opcodes + new_count;
*new_opline = *opline;
zend_optimizer_migrate_jump(op_array, new_opline, opline);
}
new_count++;
}
}
if (shift) {
op_array->last = new_count;
end = op_array->opcodes + op_array->last;
/* update JMPs */
for (opline = op_array->opcodes; opline<end; opline++) {
zend_optimizer_shift_jump(op_array, opline, shiftlist);
}
/* update try/catch array */
for (j = 0; j < op_array->last_try_catch; j++) {
op_array->try_catch_array[j].try_op -= shiftlist[op_array->try_catch_array[j].try_op];
op_array->try_catch_array[j].catch_op -= shiftlist[op_array->try_catch_array[j].catch_op];
if (op_array->try_catch_array[j].finally_op) {
op_array->try_catch_array[j].finally_op -= shiftlist[op_array->try_catch_array[j].finally_op];
op_array->try_catch_array[j].finally_end -= shiftlist[op_array->try_catch_array[j].finally_end];
}
}
}
free_alloca(shiftlist, use_heap);
}
| 3,446 | 35.284211 | 100 |
c
|
php-src
|
php-src-master/Zend/Optimizer/optimize_func_calls.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: Dmitry Stogov <[email protected]> |
| Xinchen Hui <[email protected]> |
+----------------------------------------------------------------------+
*/
/* pass 4
* - optimize INIT_FCALL_BY_NAME to DO_FCALL
*/
#include "Optimizer/zend_optimizer.h"
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_API.h"
#include "zend_constants.h"
#include "zend_execute.h"
#include "zend_vm.h"
typedef struct _optimizer_call_info {
zend_function *func;
zend_op *opline;
bool is_prototype;
bool try_inline;
uint32_t func_arg_num;
} optimizer_call_info;
static void zend_delete_call_instructions(zend_op_array *op_array, zend_op *opline)
{
int call = 0;
while (1) {
switch (opline->opcode) {
case ZEND_INIT_FCALL_BY_NAME:
case ZEND_INIT_NS_FCALL_BY_NAME:
case ZEND_INIT_STATIC_METHOD_CALL:
case ZEND_INIT_METHOD_CALL:
case ZEND_INIT_FCALL:
if (call == 0) {
MAKE_NOP(opline);
return;
}
ZEND_FALLTHROUGH;
case ZEND_NEW:
case ZEND_INIT_DYNAMIC_CALL:
case ZEND_INIT_USER_CALL:
call--;
break;
case ZEND_DO_FCALL:
case ZEND_DO_ICALL:
case ZEND_DO_UCALL:
case ZEND_DO_FCALL_BY_NAME:
call++;
break;
case ZEND_SEND_VAL:
case ZEND_SEND_VAR:
if (call == 0) {
zend_optimizer_convert_to_free_op1(op_array, opline);
}
break;
}
opline--;
}
}
static void zend_try_inline_call(zend_op_array *op_array, zend_op *fcall, zend_op *opline, zend_function *func)
{
if (func->type == ZEND_USER_FUNCTION
&& !(func->op_array.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_HAS_TYPE_HINTS))
/* TODO: function copied from trait may be inconsistent ??? */
&& !(func->op_array.fn_flags & (ZEND_ACC_TRAIT_CLONE))
&& fcall->extended_value >= func->op_array.required_num_args
&& func->op_array.opcodes[func->op_array.num_args].opcode == ZEND_RETURN) {
zend_op *ret_opline = func->op_array.opcodes + func->op_array.num_args;
if (ret_opline->op1_type == IS_CONST) {
uint32_t i, num_args = func->op_array.num_args;
num_args += (func->op_array.fn_flags & ZEND_ACC_VARIADIC) != 0;
if (fcall->opcode == ZEND_INIT_STATIC_METHOD_CALL
&& !(func->op_array.fn_flags & ZEND_ACC_STATIC)) {
/* Don't inline static call to instance method. */
return;
}
for (i = 0; i < num_args; i++) {
/* Don't inline functions with by-reference arguments. This would require
* correct handling of INDIRECT arguments. */
if (ZEND_ARG_SEND_MODE(&func->op_array.arg_info[i])) {
return;
}
}
if (fcall->extended_value < func->op_array.num_args) {
/* don't inline functions with named constants in default arguments */
i = fcall->extended_value;
do {
if (Z_TYPE_P(CRT_CONSTANT_EX(&func->op_array, &func->op_array.opcodes[i], func->op_array.opcodes[i].op2)) == IS_CONSTANT_AST) {
return;
}
i++;
} while (i < func->op_array.num_args);
}
if (RETURN_VALUE_USED(opline)) {
zval zv;
ZVAL_COPY(&zv, CRT_CONSTANT_EX(&func->op_array, ret_opline, ret_opline->op1));
opline->opcode = ZEND_QM_ASSIGN;
opline->op1_type = IS_CONST;
opline->op1.constant = zend_optimizer_add_literal(op_array, &zv);
SET_UNUSED(opline->op2);
} else {
MAKE_NOP(opline);
}
zend_delete_call_instructions(op_array, opline-1);
}
}
}
/* arg_num is 1-based here, to match SEND encoding. */
static bool has_known_send_mode(const optimizer_call_info *info, uint32_t arg_num)
{
if (!info->func) {
return false;
}
/* For prototype functions we should not make assumptions about arguments that are not part of
* the signature: And inheriting method can add an optional by-ref argument. */
return !info->is_prototype
|| arg_num <= info->func->common.num_args
|| (info->func->common.fn_flags & ZEND_ACC_VARIADIC);
}
void zend_optimize_func_calls(zend_op_array *op_array, zend_optimizer_ctx *ctx)
{
zend_op *opline = op_array->opcodes;
zend_op *end = opline + op_array->last;
int call = 0;
void *checkpoint;
optimizer_call_info *call_stack;
if (op_array->last < 2) {
return;
}
checkpoint = zend_arena_checkpoint(ctx->arena);
call_stack = zend_arena_calloc(&ctx->arena, op_array->last / 2, sizeof(optimizer_call_info));
while (opline < end) {
switch (opline->opcode) {
case ZEND_INIT_FCALL_BY_NAME:
case ZEND_INIT_NS_FCALL_BY_NAME:
case ZEND_INIT_STATIC_METHOD_CALL:
case ZEND_INIT_METHOD_CALL:
case ZEND_INIT_FCALL:
case ZEND_NEW:
/* The argument passing optimizations are valid for prototypes as well,
* as inheritance cannot change between ref <-> non-ref arguments. */
call_stack[call].func = zend_optimizer_get_called_func(
ctx->script, op_array, opline, &call_stack[call].is_prototype);
call_stack[call].try_inline =
!call_stack[call].is_prototype && opline->opcode != ZEND_NEW;
ZEND_FALLTHROUGH;
case ZEND_INIT_DYNAMIC_CALL:
case ZEND_INIT_USER_CALL:
call_stack[call].opline = opline;
call_stack[call].func_arg_num = (uint32_t)-1;
call++;
break;
case ZEND_DO_FCALL:
case ZEND_DO_ICALL:
case ZEND_DO_UCALL:
case ZEND_DO_FCALL_BY_NAME:
case ZEND_CALLABLE_CONVERT:
call--;
if (call_stack[call].func && call_stack[call].opline) {
zend_op *fcall = call_stack[call].opline;
if (fcall->opcode == ZEND_INIT_FCALL) {
/* nothing to do */
} else if (fcall->opcode == ZEND_INIT_FCALL_BY_NAME) {
fcall->opcode = ZEND_INIT_FCALL;
fcall->op1.num = zend_vm_calc_used_stack(fcall->extended_value, call_stack[call].func);
literal_dtor(&ZEND_OP2_LITERAL(fcall));
fcall->op2.constant = fcall->op2.constant + 1;
if (opline->opcode != ZEND_CALLABLE_CONVERT) {
opline->opcode = zend_get_call_op(fcall, call_stack[call].func);
}
} else if (fcall->opcode == ZEND_INIT_NS_FCALL_BY_NAME) {
fcall->opcode = ZEND_INIT_FCALL;
fcall->op1.num = zend_vm_calc_used_stack(fcall->extended_value, call_stack[call].func);
literal_dtor(&op_array->literals[fcall->op2.constant]);
literal_dtor(&op_array->literals[fcall->op2.constant + 2]);
fcall->op2.constant = fcall->op2.constant + 1;
if (opline->opcode != ZEND_CALLABLE_CONVERT) {
opline->opcode = zend_get_call_op(fcall, call_stack[call].func);
}
} else if (fcall->opcode == ZEND_INIT_STATIC_METHOD_CALL
|| fcall->opcode == ZEND_INIT_METHOD_CALL
|| fcall->opcode == ZEND_NEW) {
/* We don't have specialized opcodes for this, do nothing */
} else {
ZEND_UNREACHABLE();
}
if ((ZEND_OPTIMIZER_PASS_16 & ctx->optimization_level)
&& call_stack[call].try_inline
&& opline->opcode != ZEND_CALLABLE_CONVERT) {
zend_try_inline_call(op_array, fcall, opline, call_stack[call].func);
}
}
call_stack[call].func = NULL;
call_stack[call].opline = NULL;
call_stack[call].try_inline = 0;
call_stack[call].func_arg_num = (uint32_t)-1;
break;
case ZEND_FETCH_FUNC_ARG:
case ZEND_FETCH_STATIC_PROP_FUNC_ARG:
case ZEND_FETCH_OBJ_FUNC_ARG:
case ZEND_FETCH_DIM_FUNC_ARG:
if (call_stack[call - 1].func_arg_num != (uint32_t)-1
&& has_known_send_mode(&call_stack[call - 1], call_stack[call - 1].func_arg_num)) {
if (ARG_SHOULD_BE_SENT_BY_REF(call_stack[call - 1].func, call_stack[call - 1].func_arg_num)) {
if (opline->opcode != ZEND_FETCH_STATIC_PROP_FUNC_ARG) {
opline->opcode -= 9;
} else {
opline->opcode = ZEND_FETCH_STATIC_PROP_W;
}
} else {
if (opline->opcode == ZEND_FETCH_DIM_FUNC_ARG
&& opline->op2_type == IS_UNUSED) {
/* FETCH_DIM_FUNC_ARG supports UNUSED op2, while FETCH_DIM_R does not.
* Performing the replacement would create an invalid opcode. */
call_stack[call - 1].try_inline = 0;
break;
}
if (opline->opcode != ZEND_FETCH_STATIC_PROP_FUNC_ARG) {
opline->opcode -= 12;
} else {
opline->opcode = ZEND_FETCH_STATIC_PROP_R;
}
}
}
break;
case ZEND_SEND_VAL_EX:
if (opline->op2_type == IS_CONST) {
call_stack[call - 1].try_inline = 0;
break;
}
if (has_known_send_mode(&call_stack[call - 1], opline->op2.num)) {
if (!ARG_MUST_BE_SENT_BY_REF(call_stack[call - 1].func, opline->op2.num)) {
opline->opcode = ZEND_SEND_VAL;
}
}
break;
case ZEND_CHECK_FUNC_ARG:
if (opline->op2_type == IS_CONST) {
call_stack[call - 1].try_inline = 0;
call_stack[call - 1].func_arg_num = (uint32_t)-1;
break;
}
if (has_known_send_mode(&call_stack[call - 1], opline->op2.num)) {
call_stack[call - 1].func_arg_num = opline->op2.num;
MAKE_NOP(opline);
}
break;
case ZEND_SEND_VAR_EX:
case ZEND_SEND_FUNC_ARG:
if (opline->op2_type == IS_CONST) {
call_stack[call - 1].try_inline = 0;
break;
}
if (has_known_send_mode(&call_stack[call - 1], opline->op2.num)) {
call_stack[call - 1].func_arg_num = (uint32_t)-1;
if (ARG_SHOULD_BE_SENT_BY_REF(call_stack[call - 1].func, opline->op2.num)) {
opline->opcode = ZEND_SEND_REF;
} else {
opline->opcode = ZEND_SEND_VAR;
}
}
break;
case ZEND_SEND_VAR_NO_REF_EX:
if (opline->op2_type == IS_CONST) {
call_stack[call - 1].try_inline = 0;
break;
}
if (has_known_send_mode(&call_stack[call - 1], opline->op2.num)) {
if (ARG_MUST_BE_SENT_BY_REF(call_stack[call - 1].func, opline->op2.num)) {
opline->opcode = ZEND_SEND_VAR_NO_REF;
} else if (ARG_MAY_BE_SENT_BY_REF(call_stack[call - 1].func, opline->op2.num)) {
opline->opcode = ZEND_SEND_VAL;
} else {
opline->opcode = ZEND_SEND_VAR;
}
}
break;
case ZEND_SEND_VAL:
case ZEND_SEND_VAR:
case ZEND_SEND_REF:
if (opline->op2_type == IS_CONST) {
call_stack[call - 1].try_inline = 0;
break;
}
break;
case ZEND_SEND_UNPACK:
case ZEND_SEND_USER:
case ZEND_SEND_ARRAY:
call_stack[call - 1].try_inline = 0;
break;
default:
break;
}
opline++;
}
zend_arena_release(&ctx->arena, checkpoint);
}
| 11,190 | 32.207715 | 132 |
c
|
php-src
|
php-src-master/Zend/Optimizer/optimize_temp_vars_5.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 "Optimizer/zend_optimizer.h"
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_API.h"
#include "zend_constants.h"
#include "zend_execute.h"
#include "zend_vm.h"
#include "zend_bitset.h"
#define INVALID_VAR ((uint32_t)-1)
#define GET_AVAILABLE_T() \
for (i = 0; i < T; i++) { \
if (!zend_bitset_in(taken_T, i)) { \
break; \
} \
} \
zend_bitset_incl(taken_T, i); \
if (i > max) { \
max = i; \
}
void zend_optimize_temporary_variables(zend_op_array *op_array, zend_optimizer_ctx *ctx)
{
uint32_t T = op_array->T;
int offset = op_array->last_var;
uint32_t bitset_len;
zend_bitset taken_T; /* T index in use */
zend_op **start_of_T; /* opline where T is first used */
int *map_T; /* Map's the T to its new index */
zend_op *opline, *end;
int currT;
int i;
int max = -1;
void *checkpoint = zend_arena_checkpoint(ctx->arena);
bitset_len = zend_bitset_len(T);
taken_T = (zend_bitset) zend_arena_alloc(&ctx->arena, bitset_len * ZEND_BITSET_ELM_SIZE);
start_of_T = (zend_op **) zend_arena_alloc(&ctx->arena, T * sizeof(zend_op *));
map_T = (int *) zend_arena_alloc(&ctx->arena, T * sizeof(int));
memset(map_T, 0xff, T * sizeof(int));
end = op_array->opcodes;
opline = &op_array->opcodes[op_array->last - 1];
/* Find T definition points */
while (opline >= end) {
if (opline->result_type & (IS_VAR | IS_TMP_VAR)) {
start_of_T[VAR_NUM(opline->result.var) - offset] = opline;
}
opline--;
}
zend_bitset_clear(taken_T, bitset_len);
end = op_array->opcodes;
opline = &op_array->opcodes[op_array->last - 1];
while (opline >= end) {
if ((opline->op1_type & (IS_VAR | IS_TMP_VAR))) {
currT = VAR_NUM(opline->op1.var) - offset;
if (opline->opcode == ZEND_ROPE_END) {
int num = (((opline->extended_value + 1) * sizeof(zend_string*)) + (sizeof(zval) - 1)) / sizeof(zval);
int var;
var = max;
while (var >= 0 && !zend_bitset_in(taken_T, var)) {
var--;
}
max = MAX(max, var + num);
var = var + 1;
map_T[currT] = var;
zend_bitset_incl(taken_T, var);
opline->op1.var = NUM_VAR(var + offset);
while (num > 1) {
num--;
zend_bitset_incl(taken_T, var + num);
}
} else {
if (map_T[currT] == INVALID_VAR) {
int use_new_var = 0;
/* Code in "finally" blocks may modify temporary variables.
* We allocate new temporaries for values that need to
* relive FAST_CALLs.
*/
if ((op_array->fn_flags & ZEND_ACC_HAS_FINALLY_BLOCK) &&
(opline->opcode == ZEND_RETURN ||
opline->opcode == ZEND_GENERATOR_RETURN ||
opline->opcode == ZEND_RETURN_BY_REF ||
opline->opcode == ZEND_FREE ||
opline->opcode == ZEND_FE_FREE)) {
zend_op *curr = opline;
while (--curr >= end) {
if (curr->opcode == ZEND_FAST_CALL) {
use_new_var = 1;
break;
} else if (curr->opcode != ZEND_FREE &&
curr->opcode != ZEND_FE_FREE &&
curr->opcode != ZEND_VERIFY_RETURN_TYPE &&
curr->opcode != ZEND_DISCARD_EXCEPTION) {
break;
}
}
}
if (use_new_var) {
i = ++max;
zend_bitset_incl(taken_T, i);
} else {
GET_AVAILABLE_T();
}
map_T[currT] = i;
}
opline->op1.var = NUM_VAR(map_T[currT] + offset);
}
}
if ((opline->op2_type & (IS_VAR | IS_TMP_VAR))) {
currT = VAR_NUM(opline->op2.var) - offset;
if (map_T[currT] == INVALID_VAR) {
GET_AVAILABLE_T();
map_T[currT] = i;
}
opline->op2.var = NUM_VAR(map_T[currT] + offset);
}
if (opline->result_type & (IS_VAR | IS_TMP_VAR)) {
currT = VAR_NUM(opline->result.var) - offset;
if (map_T[currT] == INVALID_VAR) {
/* As a result of DCE, an opcode may have an unused result. */
GET_AVAILABLE_T();
map_T[currT] = i;
}
opline->result.var = NUM_VAR(map_T[currT] + offset);
if (start_of_T[currT] == opline) {
/* ZEND_FAST_CALL can not share temporary var with others
* since the fast_var could also be set by ZEND_HANDLE_EXCEPTION
* which could be ahead of it */
if (opline->opcode != ZEND_FAST_CALL) {
zend_bitset_excl(taken_T, map_T[currT]);
}
if (opline->opcode == ZEND_ROPE_INIT) {
uint32_t num = ((opline->extended_value * sizeof(zend_string*)) + (sizeof(zval) - 1)) / sizeof(zval);
while (num > 1) {
num--;
zend_bitset_excl(taken_T, map_T[currT]+num);
}
}
}
}
opline--;
}
zend_arena_release(&ctx->arena, checkpoint);
op_array->T = max + 1;
}
| 5,962 | 32.5 | 106 |
c
|
php-src
|
php-src-master/Zend/Optimizer/pass3.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]> |
+----------------------------------------------------------------------+
*/
/* pass 3: (Jump optimization)
* - optimize series of JMPs
*/
#include "Optimizer/zend_optimizer.h"
#include "Optimizer/zend_optimizer_internal.h"
#include "zend_API.h"
#include "zend_constants.h"
#include "zend_execute.h"
#include "zend_vm.h"
/* we use "jmp_hitlist" to avoid infinity loops during jmp optimization */
static zend_always_inline bool in_hitlist(zend_op *target, zend_op **jmp_hitlist, int jmp_hitlist_count)
{
int i;
for (i = 0; i < jmp_hitlist_count; i++) {
if (jmp_hitlist[i] == target) {
return 1;
}
}
return 0;
}
#define CHECK_LOOP(target) \
if (EXPECTED(!in_hitlist(target, jmp_hitlist, jmp_hitlist_count))) { \
jmp_hitlist[jmp_hitlist_count++] = target; \
} else { \
break; \
}
void zend_optimizer_pass3(zend_op_array *op_array, zend_optimizer_ctx *ctx)
{
zend_op *opline;
zend_op *end;
zend_op *target;
zend_op **jmp_hitlist;
int jmp_hitlist_count;
ALLOCA_FLAG(use_heap);
jmp_hitlist = (zend_op**)do_alloca(sizeof(zend_op*)*op_array->last, use_heap);
opline = op_array->opcodes;
end = opline + op_array->last;
while (opline < end) {
switch (opline->opcode) {
case ZEND_JMP:
jmp_hitlist_count = 0;
target = ZEND_OP1_JMP_ADDR(opline);
while (1) {
if (target->opcode == ZEND_JMP) {
/* convert JMP L1 ... L1: JMP L2 to JMP L2 .. L1: JMP L2 */
target = ZEND_OP1_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == ZEND_NOP) {
target = target + 1;
} else {
break;
}
ZEND_SET_OP_JMP_ADDR(opline, opline->op1, target);
}
if (target == opline + 1) {
/* convert L: JMP L+1 to NOP */
MAKE_NOP(opline);
} else if ((target->opcode == ZEND_RETURN ||
target->opcode == ZEND_RETURN_BY_REF ||
target->opcode == ZEND_GENERATOR_RETURN ||
target->opcode == ZEND_EXIT) &&
!(op_array->fn_flags & ZEND_ACC_HAS_FINALLY_BLOCK)) {
/* JMP L, L: RETURN to immediate RETURN */
*opline = *target;
if (opline->op1_type == IS_CONST) {
zval zv;
ZVAL_COPY(&zv, &ZEND_OP1_LITERAL(opline));
opline->op1.constant = zend_optimizer_add_literal(op_array, &zv);
}
} else if (opline > op_array->opcodes &&
((opline-1)->opcode == ZEND_JMPZ ||
(opline-1)->opcode == ZEND_JMPNZ)) {
if (ZEND_OP2_JMP_ADDR(opline-1) == target) {
/* JMPZ(X,L1), JMP(L1) -> NOP, JMP(L1) */
zend_optimizer_convert_to_free_op1(op_array, opline - 1);
}
}
break;
case ZEND_JMP_SET:
case ZEND_COALESCE:
jmp_hitlist_count = 0;
target = ZEND_OP2_JMP_ADDR(opline);
while (1) {
if (target->opcode == ZEND_JMP) {
target = ZEND_OP1_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == ZEND_NOP) {
target = target + 1;
} else {
break;
}
ZEND_SET_OP_JMP_ADDR(opline, opline->op2, target);
}
break;
case ZEND_JMPZ:
case ZEND_JMPNZ:
jmp_hitlist_count = 0;
target = ZEND_OP2_JMP_ADDR(opline);
while (1) {
if (target->opcode == ZEND_JMP) {
/* plain JMP */
/* JMPZ(X,L1), L1: JMP(L2) => JMPZ(X,L2), L1: JMP(L2) */
target = ZEND_OP1_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == opline->opcode &&
SAME_VAR(opline->op1, target->op1)) {
/* same opcode and same var as this opcode */
/* JMPZ(X,L1), L1: JMPZ(X,L2) => JMPZ(X,L2), L1: JMPZ(X,L2) */
target = ZEND_OP2_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == INV_COND(opline->opcode) &&
SAME_VAR(opline->op1, target->op1)) {
/* convert JMPZ(X,L1), L1: JMPNZ(X,L2) to
JMPZ(X,L1+1) */
target = target + 1;
} else if (target->opcode == ZEND_NOP) {
target = target + 1;
} else {
break;
}
ZEND_SET_OP_JMP_ADDR(opline, opline->op2, target);
}
/* convert L: JMPZ L+1 to NOP */
if (target == opline + 1) {
zend_optimizer_convert_to_free_op1(op_array, opline);
}
break;
case ZEND_JMPZ_EX:
case ZEND_JMPNZ_EX:
jmp_hitlist_count = 0;
target = ZEND_OP2_JMP_ADDR(opline);
while (1) {
if (target->opcode == ZEND_JMP) {
/* plain JMP */
/* JMPZ_EX(X,L1), L1: JMP(L2) => JMPZ_EX(X,L2), L1: JMP(L2) */
target = ZEND_OP1_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == opline->opcode-3 &&
(SAME_VAR(target->op1, opline->result) ||
SAME_VAR(target->op1, opline->op1))) {
/* convert T=JMPZ_EX(X,L1), L1: JMPZ(T,L2) to
JMPZ_EX(X,L2) */
target = ZEND_OP2_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == opline->opcode &&
target->result.var == opline->result.var &&
(SAME_VAR(target->op1, opline->result) ||
SAME_VAR(target->op1, opline->op1))) {
/* convert T=JMPZ_EX(X,L1), L1: T=JMPZ_EX(T,L2) to
JMPZ_EX(X,L2) */
target = ZEND_OP2_JMP_ADDR(target);
CHECK_LOOP(target);
} else if (target->opcode == INV_EX_COND(opline->opcode) &&
(SAME_VAR(target->op1, opline->result) ||
SAME_VAR(target->op1, opline->op1))) {
/* convert T=JMPZ_EX(X,L1), L1: JMPNZ(T,L2) to
JMPZ_EX(X,L1+1) */
target = target + 1;
} else if (target->opcode == INV_EX_COND_EX(opline->opcode) &&
target->result.var == opline->result.var &&
(SAME_VAR(target->op1, opline->result) ||
SAME_VAR(target->op1, opline->op1))) {
/* convert T=JMPZ_EX(X,L1), L1: T=JMPNZ_EX(T,L2) to
JMPZ_EX(X,L1+1) */
target = target + 1;
} else if (target->opcode == ZEND_BOOL &&
(SAME_VAR(target->op1, opline->result) ||
SAME_VAR(target->op1, opline->op1))) {
/* convert Y = JMPZ_EX(X,L1), L1: Z = BOOL(Y) to
Z = JMPZ_EX(X,L1+1) */
/* NOTE: This optimization pattern is not safe, but works, */
/* because result of JMPZ_EX instruction */
/* is not used on the following path and */
/* should be used once on the branch path. */
/* */
/* The pattern works well only if jumps processed in */
/* direct order, otherwise it breaks JMPZ_EX */
/* sequences too early. */
opline->result.var = target->result.var;
target = target + 1;
CHECK_LOOP(target);
} else if (target->opcode == ZEND_NOP) {
target = target + 1;
} else {
break;
}
ZEND_SET_OP_JMP_ADDR(opline, opline->op2, target);
}
/* convert L: T = JMPZ_EX X,L+1 to T = BOOL(X) */
if (target == opline + 1) {
opline->opcode = ZEND_BOOL;
opline->op2.num = 0;
}
break;
}
opline++;
}
free_alloca(jmp_hitlist, use_heap);
}
| 8,418 | 34.079167 | 104 |
c
|
php-src
|
php-src-master/Zend/Optimizer/scdf.c
|
/*
+----------------------------------------------------------------------+
| Zend Engine, Sparse Conditional Data Flow Propagation Framework |
+----------------------------------------------------------------------+
| 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: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "Optimizer/zend_optimizer_internal.h"
#include "Optimizer/scdf.h"
/* This defines a generic framework for sparse conditional dataflow propagation. The algorithm is
* based on "Sparse conditional constant propagation" by Wegman and Zadeck. We're using a
* generalized implementation as described in chapter 8.3 of the SSA book.
*
* Every SSA variable is associated with an element on a finite-height lattice, those value can only
* ever be lowered during the operation of the algorithm. If a value is lowered all instructions and
* phis using that value need to be reconsidered (this is done by adding the variable to a
* worklist). For phi functions the result is computed by applying the meet operation to the
* operands. This continues until a fixed point is reached.
*
* The algorithm is control-flow sensitive: All blocks except the start block are initially assumed
* to be unreachable. When considering a branch instruction, we determine the feasible successors
* based on the current state of the variable lattice. If a new edge becomes feasible we either have
* to mark the successor block executable and consider all instructions in it, or, if the target is
* already executable, we only have to reconsider the phi functions (as we only consider phi
* operands which are associated with a feasible edge).
*
* The generic framework requires the definition of three functions:
* * visit_instr() should recompute the lattice values of all SSA variables defined by an
* instruction.
* * visit_phi() should recompute the lattice value of the SSA variable defined by the phi. While
* doing this it should only consider operands for which scfg_is_edge_feasible() returns true.
* * get_feasible_successors() should determine the feasible successors for a branch instruction.
* Note that this callback only needs to handle conditional branches (with two successors).
*/
#if 0
#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG_PRINT(...)
#endif
void scdf_mark_edge_feasible(scdf_ctx *scdf, int from, int to) {
uint32_t edge = scdf_edge(&scdf->ssa->cfg, from, to);
if (zend_bitset_in(scdf->feasible_edges, edge)) {
/* We already handled this edge */
return;
}
DEBUG_PRINT("Marking edge %d->%d feasible\n", from, to);
zend_bitset_incl(scdf->feasible_edges, edge);
if (!zend_bitset_in(scdf->executable_blocks, to)) {
if (!zend_bitset_in(scdf->block_worklist, to)) {
DEBUG_PRINT("Adding block %d to worklist\n", to);
}
zend_bitset_incl(scdf->block_worklist, to);
} else {
/* Block is already executable, only a new edge became feasible.
* Reevaluate phi nodes to account for changed source operands. */
zend_ssa_block *ssa_block = &scdf->ssa->blocks[to];
zend_ssa_phi *phi;
for (phi = ssa_block->phis; phi; phi = phi->next) {
zend_bitset_excl(scdf->phi_var_worklist, phi->ssa_var);
scdf->handlers.visit_phi(scdf, phi);
}
}
}
void scdf_init(zend_optimizer_ctx *ctx, scdf_ctx *scdf, zend_op_array *op_array, zend_ssa *ssa) {
scdf->op_array = op_array;
scdf->ssa = ssa;
scdf->instr_worklist_len = zend_bitset_len(op_array->last);
scdf->phi_var_worklist_len = zend_bitset_len(ssa->vars_count);
scdf->block_worklist_len = zend_bitset_len(ssa->cfg.blocks_count);
scdf->instr_worklist = zend_arena_calloc(&ctx->arena,
scdf->instr_worklist_len + scdf->phi_var_worklist_len + 2 * scdf->block_worklist_len + zend_bitset_len(ssa->cfg.edges_count),
sizeof(zend_ulong));
scdf->phi_var_worklist = scdf->instr_worklist + scdf->instr_worklist_len;
scdf->block_worklist = scdf->phi_var_worklist + scdf->phi_var_worklist_len;
scdf->executable_blocks = scdf->block_worklist + scdf->block_worklist_len;
scdf->feasible_edges = scdf->executable_blocks + scdf->block_worklist_len;
zend_bitset_incl(scdf->block_worklist, 0);
zend_bitset_incl(scdf->executable_blocks, 0);
}
void scdf_solve(scdf_ctx *scdf, const char *name) {
zend_ssa *ssa = scdf->ssa;
DEBUG_PRINT("Start SCDF solve (%s)\n", name);
while (!zend_bitset_empty(scdf->instr_worklist, scdf->instr_worklist_len)
|| !zend_bitset_empty(scdf->phi_var_worklist, scdf->phi_var_worklist_len)
|| !zend_bitset_empty(scdf->block_worklist, scdf->block_worklist_len)
) {
int i;
while ((i = zend_bitset_pop_first(scdf->phi_var_worklist, scdf->phi_var_worklist_len)) >= 0) {
zend_ssa_phi *phi = ssa->vars[i].definition_phi;
ZEND_ASSERT(phi);
if (zend_bitset_in(scdf->executable_blocks, phi->block)) {
scdf->handlers.visit_phi(scdf, phi);
}
}
while ((i = zend_bitset_pop_first(scdf->instr_worklist, scdf->instr_worklist_len)) >= 0) {
int block_num = ssa->cfg.map[i];
if (zend_bitset_in(scdf->executable_blocks, block_num)) {
zend_basic_block *block = &ssa->cfg.blocks[block_num];
zend_op *opline = &scdf->op_array->opcodes[i];
zend_ssa_op *ssa_op = &ssa->ops[i];
if (opline->opcode == ZEND_OP_DATA) {
opline--;
ssa_op--;
}
scdf->handlers.visit_instr(scdf, opline, ssa_op);
if (i == block->start + block->len - 1) {
if (block->successors_count == 1) {
scdf_mark_edge_feasible(scdf, block_num, block->successors[0]);
} else if (block->successors_count > 1) {
scdf->handlers.mark_feasible_successors(scdf, block_num, block, opline, ssa_op);
}
}
}
}
while ((i = zend_bitset_pop_first(scdf->block_worklist, scdf->block_worklist_len)) >= 0) {
/* This block is now live. Interpret phis and instructions in it. */
zend_basic_block *block = &ssa->cfg.blocks[i];
zend_ssa_block *ssa_block = &ssa->blocks[i];
DEBUG_PRINT("Pop block %d from worklist\n", i);
zend_bitset_incl(scdf->executable_blocks, i);
{
zend_ssa_phi *phi;
for (phi = ssa_block->phis; phi; phi = phi->next) {
zend_bitset_excl(scdf->phi_var_worklist, phi->ssa_var);
scdf->handlers.visit_phi(scdf, phi);
}
}
if (block->len == 0) {
/* Zero length blocks don't have a last instruction that would normally do this */
scdf_mark_edge_feasible(scdf, i, block->successors[0]);
} else {
zend_op *opline = NULL;
int j, end = block->start + block->len;
for (j = block->start; j < end; j++) {
opline = &scdf->op_array->opcodes[j];
zend_bitset_excl(scdf->instr_worklist, j);
if (opline->opcode != ZEND_OP_DATA) {
scdf->handlers.visit_instr(scdf, opline, &ssa->ops[j]);
}
}
if (block->successors_count == 1) {
scdf_mark_edge_feasible(scdf, i, block->successors[0]);
} else if (block->successors_count > 1) {
ZEND_ASSERT(opline && "Should have opline in non-empty block");
if (opline->opcode == ZEND_OP_DATA) {
opline--;
j--;
}
scdf->handlers.mark_feasible_successors(scdf, i, block, opline, &ssa->ops[j-1]);
}
}
}
}
}
/* If a live range starts in a reachable block and ends in an unreachable block, we should
* not eliminate the latter. While it cannot be reached, the FREE opcode of the loop var
* is necessary for the correctness of temporary compaction. */
static bool is_live_loop_var_free(
scdf_ctx *scdf, const zend_op *opline, const zend_ssa_op *ssa_op) {
if (!zend_optimizer_is_loop_var_free(opline)) {
return false;
}
int var = ssa_op->op1_use;
if (var < 0) {
return false;
}
zend_ssa_var *ssa_var = &scdf->ssa->vars[var];
uint32_t def_block;
if (ssa_var->definition >= 0) {
def_block = scdf->ssa->cfg.map[ssa_var->definition];
} else {
def_block = ssa_var->definition_phi->block;
}
return zend_bitset_in(scdf->executable_blocks, def_block);
}
static bool kept_alive_by_loop_var_free(scdf_ctx *scdf, const zend_basic_block *block) {
const zend_op_array *op_array = scdf->op_array;
const zend_cfg *cfg = &scdf->ssa->cfg;
if (!(cfg->flags & ZEND_FUNC_FREE_LOOP_VAR)) {
return false;
}
for (uint32_t i = block->start; i < block->start + block->len; i++) {
if (is_live_loop_var_free(scdf, &op_array->opcodes[i], &scdf->ssa->ops[i])) {
return true;
}
}
return false;
}
static uint32_t cleanup_loop_var_free_block(scdf_ctx *scdf, zend_basic_block *block) {
zend_ssa *ssa = scdf->ssa;
const zend_op_array *op_array = scdf->op_array;
const zend_cfg *cfg = &ssa->cfg;
int block_num = block - cfg->blocks;
uint32_t removed_ops = 0;
/* Removes phi nodes */
for (zend_ssa_phi *phi = ssa->blocks[block_num].phis; phi; phi = phi->next) {
zend_ssa_remove_uses_of_var(ssa, phi->ssa_var);
zend_ssa_remove_phi(ssa, phi);
}
for (uint32_t i = block->start; i < block->start + block->len; i++) {
zend_op *opline = &op_array->opcodes[i];
zend_ssa_op *ssa_op = &scdf->ssa->ops[i];
if (opline->opcode == ZEND_NOP
|| is_live_loop_var_free(scdf, opline, ssa_op)) {
continue;
}
/* While we have to preserve the loop var free, we can still remove other instructions
* in the block. */
zend_ssa_remove_defs_of_instr(ssa, ssa_op);
zend_ssa_remove_instr(ssa, opline, ssa_op);
removed_ops++;
}
zend_ssa_remove_block_from_cfg(ssa, block_num);
return removed_ops;
}
/* Removes unreachable blocks. This will remove both the instructions (and phis) in the
* blocks, as well as remove them from the successor / predecessor lists and mark them
* unreachable. Blocks already marked unreachable are not removed. */
uint32_t scdf_remove_unreachable_blocks(scdf_ctx *scdf) {
zend_ssa *ssa = scdf->ssa;
int i;
uint32_t removed_ops = 0;
for (i = 0; i < ssa->cfg.blocks_count; i++) {
zend_basic_block *block = &ssa->cfg.blocks[i];
if (!zend_bitset_in(scdf->executable_blocks, i) && (block->flags & ZEND_BB_REACHABLE)) {
if (!kept_alive_by_loop_var_free(scdf, block)) {
removed_ops += block->len;
zend_ssa_remove_block(scdf->op_array, ssa, i);
} else {
removed_ops += cleanup_loop_var_free_block(scdf, block);
}
}
}
return removed_ops;
}
| 10,937 | 38.630435 | 127 |
c
|
php-src
|
php-src-master/Zend/Optimizer/scdf.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine, Call Graph |
+----------------------------------------------------------------------+
| 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: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef _SCDF_H
#define _SCDF_H
#include "zend_bitset.h"
typedef struct _scdf_ctx {
zend_op_array *op_array;
zend_ssa *ssa;
zend_bitset instr_worklist;
/* Represent phi-instructions through the defining var */
zend_bitset phi_var_worklist;
zend_bitset block_worklist;
zend_bitset executable_blocks;
/* 1 bit per edge, see scdf_edge(cfg, from, to) */
zend_bitset feasible_edges;
uint32_t instr_worklist_len;
uint32_t phi_var_worklist_len;
uint32_t block_worklist_len;
struct {
void (*visit_instr)(
struct _scdf_ctx *scdf, zend_op *opline, zend_ssa_op *ssa_op);
void (*visit_phi)(
struct _scdf_ctx *scdf, zend_ssa_phi *phi);
void (*mark_feasible_successors)(
struct _scdf_ctx *scdf, int block_num, zend_basic_block *block,
zend_op *opline, zend_ssa_op *ssa_op);
} handlers;
} scdf_ctx;
void scdf_init(zend_optimizer_ctx *ctx, scdf_ctx *scdf, zend_op_array *op_array, zend_ssa *ssa);
void scdf_solve(scdf_ctx *scdf, const char *name);
uint32_t scdf_remove_unreachable_blocks(scdf_ctx *scdf);
/* Add uses to worklist */
static inline void scdf_add_to_worklist(scdf_ctx *scdf, int var_num) {
const zend_ssa *ssa = scdf->ssa;
const zend_ssa_var *var = &ssa->vars[var_num];
int use;
zend_ssa_phi *phi;
FOREACH_USE(var, use) {
zend_bitset_incl(scdf->instr_worklist, use);
} FOREACH_USE_END();
FOREACH_PHI_USE(var, phi) {
zend_bitset_incl(scdf->phi_var_worklist, phi->ssa_var);
} FOREACH_PHI_USE_END();
}
/* This should usually not be necessary, however it's used for type narrowing. */
static inline void scdf_add_def_to_worklist(scdf_ctx *scdf, int var_num) {
const zend_ssa_var *var = &scdf->ssa->vars[var_num];
if (var->definition >= 0) {
zend_bitset_incl(scdf->instr_worklist, var->definition);
} else if (var->definition_phi) {
zend_bitset_incl(scdf->phi_var_worklist, var_num);
}
}
static inline uint32_t scdf_edge(const zend_cfg *cfg, int from, int to) {
const zend_basic_block *to_block = cfg->blocks + to;
int i;
for (i = 0; i < to_block->predecessors_count; i++) {
uint32_t edge = to_block->predecessor_offset + i;
if (cfg->predecessors[edge] == from) {
return edge;
}
}
ZEND_UNREACHABLE();
}
static inline bool scdf_is_edge_feasible(const scdf_ctx *scdf, int from, int to) {
uint32_t edge = scdf_edge(&scdf->ssa->cfg, from, to);
return zend_bitset_in(scdf->feasible_edges, edge);
}
void scdf_mark_edge_feasible(scdf_ctx *scdf, int from, int to);
#endif
| 3,584 | 34.85 | 96 |
h
|
php-src
|
php-src-master/Zend/Optimizer/ssa_integrity.c
|
/*
+----------------------------------------------------------------------+
| Zend Engine, SSA validation |
+----------------------------------------------------------------------+
| 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: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "Optimizer/zend_optimizer_internal.h"
/* The ssa_verify_integrity() function ensures that that certain invariants of the SSA form and
* CFG are upheld and prints messages to stderr if this is not the case. */
static inline bool is_in_use_chain(zend_ssa *ssa, int var, int check) {
int use;
FOREACH_USE(&ssa->vars[var], use) {
if (use == check) {
return 1;
}
} FOREACH_USE_END();
return 0;
}
static inline bool is_in_phi_use_chain(zend_ssa *ssa, int var, zend_ssa_phi *check) {
zend_ssa_phi *phi;
FOREACH_PHI_USE(&ssa->vars[var], phi) {
if (phi == check) {
return 1;
}
} FOREACH_PHI_USE_END();
return 0;
}
static inline bool is_used_by_op(zend_ssa *ssa, int op, int check) {
zend_ssa_op *ssa_op = &ssa->ops[op];
return (ssa_op->op1_use == check)
|| (ssa_op->op2_use == check)
|| (ssa_op->result_use == check);
}
static inline bool is_defined_by_op(zend_ssa *ssa, int op, int check) {
zend_ssa_op *ssa_op = &ssa->ops[op];
return (ssa_op->op1_def == check)
|| (ssa_op->op2_def == check)
|| (ssa_op->result_def == check);
}
static inline bool is_in_phi_sources(zend_ssa *ssa, zend_ssa_phi *phi, int check) {
int source;
FOREACH_PHI_SOURCE(phi, source) {
if (source == check) {
return 1;
}
} FOREACH_PHI_SOURCE_END();
return 0;
}
static inline bool is_in_predecessors(zend_cfg *cfg, zend_basic_block *block, int check) {
int i, *predecessors = &cfg->predecessors[block->predecessor_offset];
for (i = 0; i < block->predecessors_count; i++) {
if (predecessors[i] == check) {
return 1;
}
}
return 0;
}
static inline bool is_in_successors(zend_basic_block *block, int check) {
int s;
for (s = 0; s < block->successors_count; s++) {
if (block->successors[s] == check) {
return 1;
}
}
return 0;
}
static inline bool is_var_type(uint8_t type) {
return (type & (IS_CV|IS_VAR|IS_TMP_VAR)) != 0;
}
static inline bool is_defined(const zend_ssa *ssa, const zend_op_array *op_array, int var) {
const zend_ssa_var *ssa_var = &ssa->vars[var];
return ssa_var->definition >= 0 || ssa_var->definition_phi || var < op_array->last_var;
}
#define FAIL(...) do { \
if (status == SUCCESS) { \
fprintf(stderr, "\nIn function %s::%s (%s):\n", \
op_array->scope ? ZSTR_VAL(op_array->scope->name) : "", \
op_array->function_name ? ZSTR_VAL(op_array->function_name) : "{main}", extra); \
} \
fprintf(stderr, __VA_ARGS__); \
status = FAILURE; \
} while (0)
#define VARFMT "%d (%s%s)"
#define VAR(i) \
(i), (ssa->vars[i].var < op_array->last_var ? "CV $" : "TMP"), \
(ssa->vars[i].var < op_array->last_var ? ZSTR_VAL(op_array->vars[ssa->vars[i].var]) : "")
#define INSTRFMT "%d (%s)"
#define INSTR(i) \
(i), (zend_get_opcode_name(op_array->opcodes[i].opcode))
void ssa_verify_integrity(zend_op_array *op_array, zend_ssa *ssa, const char *extra) {
zend_cfg *cfg = &ssa->cfg;
zend_ssa_phi *phi;
int i;
zend_result status = SUCCESS;
/* Vars */
for (i = 0; i < ssa->vars_count; i++) {
zend_ssa_var *var = &ssa->vars[i];
int use, c;
uint32_t type = ssa->var_info[i].type;
if (var->definition < 0 && !var->definition_phi && i > op_array->last_var) {
if (var->use_chain >= 0) {
FAIL("var " VARFMT " without def has op uses\n", VAR(i));
}
if (var->phi_use_chain) {
FAIL("var " VARFMT " without def has phi uses\n", VAR(i));
}
}
if (var->definition >= 0 && var->definition_phi) {
FAIL("var " VARFMT " has both def and def_phi\n", VAR(i));
}
if (var->definition >= 0) {
if (!is_defined_by_op(ssa, var->definition, i)) {
FAIL("var " VARFMT " not defined by op " INSTRFMT "\n",
VAR(i), INSTR(var->definition));
}
}
if (var->definition_phi) {
if (var->definition_phi->ssa_var != i) {
FAIL("var " VARFMT " not defined by given phi\n", VAR(i));
}
}
c = 0;
FOREACH_USE(var, use) {
if (++c > 10000) {
FAIL("cycle in uses of " VARFMT "\n", VAR(i));
goto finish;
}
if (!is_used_by_op(ssa, use, i)) {
fprintf(stderr, "var " VARFMT " not in uses of op %d\n", VAR(i), use);
}
} FOREACH_USE_END();
c = 0;
FOREACH_PHI_USE(var, phi) {
if (++c > 10000) {
FAIL("cycle in phi uses of " VARFMT "\n", VAR(i));
goto finish;
}
if (!is_in_phi_sources(ssa, phi, i)) {
FAIL("var " VARFMT " not in phi sources of %d\n", VAR(i), phi->ssa_var);
}
} FOREACH_PHI_USE_END();
if ((type & MAY_BE_ARRAY_KEY_ANY) && !(type & MAY_BE_ARRAY_OF_ANY)) {
FAIL("var " VARFMT " has array key type but not value type\n", VAR(i));
}
if ((type & MAY_BE_ARRAY_OF_ANY) && !(type & MAY_BE_ARRAY_KEY_ANY)) {
FAIL("var " VARFMT " has array value type but not key type\n", VAR(i));
}
if ((type & MAY_BE_REF) && ssa->var_info[i].ce) {
FAIL("var " VARFMT " may be ref but has ce\n", VAR(i));
}
}
/* Instructions */
FOREACH_INSTR_NUM(i) {
zend_ssa_op *ssa_op = &ssa->ops[i];
zend_op *opline = &op_array->opcodes[i];
if (is_var_type(opline->op1_type)) {
if (ssa_op->op1_use < 0 && ssa_op->op1_def < 0) {
FAIL("var op1 of " INSTRFMT " does not use/def an ssa var\n", INSTR(i));
}
} else {
if (ssa_op->op1_use >= 0 || ssa_op->op1_def >= 0) {
FAIL("non-var op1 of " INSTRFMT " uses or defs an ssa var\n", INSTR(i));
}
}
if (is_var_type(opline->op2_type)) {
if (ssa_op->op2_use < 0 && ssa_op->op2_def < 0) {
FAIL("var op2 of " INSTRFMT " does not use/def an ssa var\n", INSTR(i));
}
} else {
if (ssa_op->op2_use >= 0 || ssa_op->op2_def >= 0) {
FAIL("non-var op2 of " INSTRFMT " uses or defs an ssa var\n", INSTR(i));
}
}
if (is_var_type(opline->result_type)) {
if (ssa_op->result_use < 0 && ssa_op->result_def < 0) {
FAIL("var result of " INSTRFMT " does not use/def an ssa var\n", INSTR(i));
}
} else {
if (ssa_op->result_use >= 0 || ssa_op->result_def >= 0) {
FAIL("non-var result of " INSTRFMT " uses or defs an ssa var\n", INSTR(i));
}
}
if (ssa_op->op1_use >= 0) {
if (ssa_op->op1_use >= ssa->vars_count) {
FAIL("op1 use %d out of range\n", ssa_op->op1_use);
}
if (!is_defined(ssa, op_array, ssa_op->op1_use)) {
FAIL("op1 use of " VARFMT " in " INSTRFMT " is not defined\n",
VAR(ssa_op->op1_use), INSTR(i));
}
if (!is_in_use_chain(ssa, ssa_op->op1_use, i)) {
FAIL("op1 use of " VARFMT " in " INSTRFMT " not in use chain\n",
VAR(ssa_op->op1_use), INSTR(i));
}
if (VAR_NUM(opline->op1.var) != ssa->vars[ssa_op->op1_use].var) {
FAIL("op1 use of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->op1_use), VAR_NUM(opline->op1.var), INSTR(i));
}
}
if (ssa_op->op2_use >= 0) {
if (ssa_op->op2_use >= ssa->vars_count) {
FAIL("op2 use %d out of range\n", ssa_op->op2_use);
}
if (!is_defined(ssa, op_array, ssa_op->op2_use)) {
FAIL("op2 use of " VARFMT " in " INSTRFMT " is not defined\n",
VAR(ssa_op->op2_use), INSTR(i));
}
if (!is_in_use_chain(ssa, ssa_op->op2_use, i)) {
FAIL("op2 use of " VARFMT " in " INSTRFMT " not in use chain\n",
VAR(ssa_op->op2_use), INSTR(i));
}
if (VAR_NUM(opline->op2.var) != ssa->vars[ssa_op->op2_use].var) {
FAIL("op2 use of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->op2_use), VAR_NUM(opline->op2.var), INSTR(i));
}
}
if (ssa_op->result_use >= 0) {
if (ssa_op->result_use >= ssa->vars_count) {
FAIL("result use %d out of range\n", ssa_op->result_use);
}
if (!is_defined(ssa, op_array, ssa_op->result_use)) {
FAIL("result use of " VARFMT " in " INSTRFMT " is not defined\n",
VAR(ssa_op->result_use), INSTR(i));
}
if (!is_in_use_chain(ssa, ssa_op->result_use, i)) {
FAIL("result use of " VARFMT " in " INSTRFMT " not in use chain\n",
VAR(ssa_op->result_use), INSTR(i));
}
if (VAR_NUM(opline->result.var) != ssa->vars[ssa_op->result_use].var) {
FAIL("result use of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->result_use), VAR_NUM(opline->result.var), INSTR(i));
}
}
if (ssa_op->op1_def >= 0) {
if (ssa_op->op1_def >= ssa->vars_count) {
FAIL("op1 def %d out of range\n", ssa_op->op1_def);
}
if (ssa->vars[ssa_op->op1_def].definition != i) {
FAIL("op1 def of " VARFMT " in " INSTRFMT " invalid\n",
VAR(ssa_op->op1_def), INSTR(i));
}
if (VAR_NUM(opline->op1.var) != ssa->vars[ssa_op->op1_def].var) {
FAIL("op1 def of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->op1_def), VAR_NUM(opline->op1.var), INSTR(i));
}
}
if (ssa_op->op2_def >= 0) {
if (ssa_op->op2_def >= ssa->vars_count) {
FAIL("op2 def %d out of range\n", ssa_op->op2_def);
}
if (ssa->vars[ssa_op->op2_def].definition != i) {
FAIL("op2 def of " VARFMT " in " INSTRFMT " invalid\n",
VAR(ssa_op->op2_def), INSTR(i));
}
if (VAR_NUM(opline->op2.var) != ssa->vars[ssa_op->op2_def].var) {
FAIL("op2 def of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->op2_def), VAR_NUM(opline->op2.var), INSTR(i));
}
}
if (ssa_op->result_def >= 0) {
if (ssa_op->result_def >= ssa->vars_count) {
FAIL("result def %d out of range\n", ssa_op->result_def);
}
if (ssa->vars[ssa_op->result_def].definition != i) {
FAIL("result def of " VARFMT " in " INSTRFMT " invalid\n",
VAR(ssa_op->result_def), INSTR(i));
}
if (VAR_NUM(opline->result.var) != ssa->vars[ssa_op->result_def].var) {
FAIL("result def of " VARFMT " does not match op %d of " INSTRFMT "\n",
VAR(ssa_op->result_def), VAR_NUM(opline->result.var), INSTR(i));
}
}
} FOREACH_INSTR_NUM_END();
/* Phis */
FOREACH_PHI(phi) {
unsigned num_sources = NUM_PHI_SOURCES(phi);
for (i = 0; i < num_sources; i++) {
int source = phi->sources[i];
if (source < 0) {
FAIL(VARFMT " negative source\n", VAR(phi->ssa_var));
}
if (!is_in_phi_use_chain(ssa, source, phi)) {
FAIL(VARFMT " not in phi use chain of %d\n", VAR(phi->ssa_var), source);
}
if (ssa->vars[source].var != ssa->vars[phi->ssa_var].var) {
FAIL(VARFMT " source of phi for " VARFMT "\n", VAR(source), VAR(phi->ssa_var));
}
if (phi->use_chains[i]) {
int j;
for (j = i + 1; j < num_sources; j++) {
if (phi->sources[j] == source && phi->use_chains[j]) {
FAIL("use chain for source " VARFMT " of phi " VARFMT
" at %d despite earlier use\n", VAR(source), VAR(phi->ssa_var), j);
}
}
}
}
if (ssa->vars[phi->ssa_var].definition_phi != phi) {
FAIL(VARFMT " does not define this phi\n", VAR(phi->ssa_var));
}
} FOREACH_PHI_END();
/* Blocks */
for (i = 0; i < cfg->blocks_count; i++) {
zend_basic_block *block = &cfg->blocks[i];
int *predecessors = &cfg->predecessors[block->predecessor_offset];
int s, j;
if (i != 0 && block->start < (block-1)->start + (block-1)->len) {
FAIL("Block %d start %d smaller previous end %d\n",
i, block->start, (block-1)->start + (block-1)->len);
}
if (i != cfg->blocks_count-1 && block->start + block->len > (block+1)->start) {
FAIL("Block %d end %d greater next start %d\n",
i, block->start + block->len, (block+1)->start);
}
for (j = block->start; j < block->start + block->len; j++) {
if (cfg->map[j] != i) {
FAIL("Instr " INSTRFMT " not associated with block %d\n", INSTR(j), i);
}
}
if (!(block->flags & ZEND_BB_REACHABLE)) {
if (ssa->blocks[i].phis) {
FAIL("Unreachable block %d has phis\n", i);
}
continue;
}
for (s = 0; s < block->successors_count; s++) {
zend_basic_block *next_block;
if (block->successors[s] < 0) {
FAIL("Successor number %d of %d negative", s, i);
}
next_block = &cfg->blocks[block->successors[s]];
if (!(next_block->flags & ZEND_BB_REACHABLE)) {
FAIL("Successor %d of %d not reachable\n", block->successors[s], i);
}
if (!is_in_predecessors(cfg, next_block, i)) {
FAIL("Block %d predecessors missing %d\n", block->successors[s], i);
}
}
for (j = 0; j < block->predecessors_count; j++) {
if (predecessors[j] >= 0) {
int k;
zend_basic_block *prev_block = &cfg->blocks[predecessors[j]];
if (!(prev_block->flags & ZEND_BB_REACHABLE)) {
FAIL("Predecessor %d of %d not reachable\n", predecessors[j], i);
}
if (!is_in_successors(prev_block, i)) {
FAIL("Block %d successors missing %d\n", predecessors[j], i);
}
for (k = 0; k < block->predecessors_count; k++) {
if (k != j && predecessors[k] == predecessors[j]) {
FAIL("Block %d has duplicate predecessor %d\n", i, predecessors[j]);
}
}
}
}
}
finish:
if (status == FAILURE) {
zend_dump_op_array(op_array, ZEND_DUMP_SSA, "at SSA integrity verification", ssa);
ZEND_ASSERT(0 && "SSA integrity verification failed");
}
}
| 13,862 | 33.314356 | 95 |
c
|
php-src
|
php-src-master/Zend/Optimizer/zend_func_info.c
|
/*
+----------------------------------------------------------------------+
| Zend Engine, Func Info |
+----------------------------------------------------------------------+
| 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 "zend_compile.h"
#include "zend_extensions.h"
#include "zend_ssa.h"
#include "zend_optimizer_internal.h"
#include "zend_inference.h"
#include "zend_call_graph.h"
#include "zend_func_info.h"
#include "zend_inference.h"
#ifdef _WIN32
#include "win32/ioutil.h"
#endif
typedef uint32_t (*info_func_t)(const zend_call_info *call_info, const zend_ssa *ssa);
typedef struct _func_info_t {
const char *name;
unsigned name_len;
uint32_t info;
info_func_t info_func;
} func_info_t;
#define F0(name, info) \
{name, sizeof(name)-1, (info), NULL}
#define F1(name, info) \
{name, sizeof(name)-1, (MAY_BE_RC1 | (info)), NULL}
#define FN(name, info) \
{name, sizeof(name)-1, (MAY_BE_RC1 | MAY_BE_RCN | (info)), NULL}
#define FC(name, callback) \
{name, sizeof(name)-1, 0, callback}
#include "zend_func_infos.h"
static uint32_t zend_range_info(const zend_call_info *call_info, const zend_ssa *ssa)
{
if (!call_info->send_unpack
&& (call_info->num_args == 2 || call_info->num_args == 3)
&& ssa
&& !(ssa->cfg.flags & ZEND_SSA_TSSA)) {
zend_op_array *op_array = call_info->caller_op_array;
uint32_t t1 = _ssa_op1_info(op_array, ssa, call_info->arg_info[0].opline,
&ssa->ops[call_info->arg_info[0].opline - op_array->opcodes]);
uint32_t t2 = _ssa_op1_info(op_array, ssa, call_info->arg_info[1].opline,
&ssa->ops[call_info->arg_info[1].opline - op_array->opcodes]);
uint32_t t3 = 0;
uint32_t tmp = MAY_BE_RC1 | MAY_BE_ARRAY;
if (call_info->num_args == 3) {
t3 = _ssa_op1_info(op_array, ssa, call_info->arg_info[2].opline,
&ssa->ops[call_info->arg_info[2].opline - op_array->opcodes]);
}
if ((t1 & MAY_BE_STRING) && (t2 & MAY_BE_STRING)) {
tmp |= MAY_BE_ARRAY_OF_LONG | MAY_BE_ARRAY_OF_DOUBLE | MAY_BE_ARRAY_OF_STRING;
}
if ((t1 & (MAY_BE_DOUBLE|MAY_BE_STRING))
|| (t2 & (MAY_BE_DOUBLE|MAY_BE_STRING))
|| (t3 & (MAY_BE_DOUBLE|MAY_BE_STRING))) {
tmp |= MAY_BE_ARRAY_OF_DOUBLE;
}
if ((t1 & ((MAY_BE_ANY|MAY_BE_UNDEF)-MAY_BE_DOUBLE))
&& (t2 & ((MAY_BE_ANY|MAY_BE_UNDEF)-MAY_BE_DOUBLE))) {
if ((t3 & MAY_BE_ANY) != MAY_BE_DOUBLE) {
tmp |= MAY_BE_ARRAY_OF_LONG;
}
}
if (tmp & MAY_BE_ARRAY_OF_ANY) {
tmp |= MAY_BE_ARRAY_PACKED;
}
return tmp;
} else {
/* May throw */
return MAY_BE_RC1 | MAY_BE_ARRAY | MAY_BE_ARRAY_PACKED | MAY_BE_ARRAY_OF_LONG | MAY_BE_ARRAY_OF_DOUBLE | MAY_BE_ARRAY_OF_STRING;
}
}
static const func_info_t old_func_infos[] = {
FC("range", zend_range_info),
};
static HashTable func_info;
ZEND_API int zend_func_info_rid = -1;
uint32_t zend_get_internal_func_info(
const zend_function *callee_func, const zend_call_info *call_info, const zend_ssa *ssa) {
if (callee_func->common.scope) {
/* This is a method, not a function. */
return 0;
}
zend_string *name = callee_func->common.function_name;
if (!name) {
/* zend_pass_function has no name. */
return 0;
}
zval *zv = zend_hash_find_known_hash(&func_info, name);
if (!zv) {
return 0;
}
func_info_t *info = Z_PTR_P(zv);
if (info->info_func) {
return call_info ? info->info_func(call_info, ssa) : 0;
} else {
return info->info;
}
}
ZEND_API uint32_t zend_get_func_info(
const zend_call_info *call_info, const zend_ssa *ssa,
zend_class_entry **ce, bool *ce_is_instanceof)
{
uint32_t ret = 0;
const zend_function *callee_func = call_info->callee_func;
*ce = NULL;
*ce_is_instanceof = 0;
if (callee_func->type == ZEND_INTERNAL_FUNCTION) {
uint32_t internal_ret = zend_get_internal_func_info(callee_func, call_info, ssa);
#if !ZEND_DEBUG
if (internal_ret) {
return internal_ret;
}
#endif
ret = zend_get_return_info_from_signature_only(
callee_func, /* script */ NULL, ce, ce_is_instanceof, /* use_tentative_return_info */ !call_info->is_prototype);
#if ZEND_DEBUG
if (internal_ret) {
zend_string *name = callee_func->common.function_name;
/* Check whether the func_info information is a subset of the information we can
* compute from the specified return type, otherwise it contains redundant types. */
if (internal_ret & ~ret) {
fprintf(stderr, "Inaccurate func info for %s()\n", ZSTR_VAL(name));
}
/* Check whether the func info is completely redundant with arginfo. */
if (internal_ret == ret) {
fprintf(stderr, "Useless func info for %s()\n", ZSTR_VAL(name));
}
/* If the return type is not mixed, check that the types match exactly if we exclude
* RC and array information. */
uint32_t ret_any = ret & MAY_BE_ANY, internal_ret_any = internal_ret & MAY_BE_ANY;
if (ret_any != MAY_BE_ANY) {
uint32_t diff = internal_ret_any ^ ret_any;
/* Func info may contain "true" types as well as isolated "null" and "false". */
if (diff && !(diff == MAY_BE_FALSE && (ret & MAY_BE_FALSE))
&& (internal_ret_any & ~(MAY_BE_NULL|MAY_BE_FALSE))) {
fprintf(stderr, "Incorrect func info for %s()\n", ZSTR_VAL(name));
}
}
return internal_ret;
}
#endif
} else {
if (!call_info->is_prototype) {
// FIXME: the order of functions matters!!!
zend_func_info *info = ZEND_FUNC_INFO((zend_op_array*)callee_func);
if (info) {
ret = info->return_info.type;
*ce = info->return_info.ce;
*ce_is_instanceof = info->return_info.is_instanceof;
}
}
if (!ret) {
ret = zend_get_return_info_from_signature_only(
callee_func, /* TODO: script */ NULL, ce, ce_is_instanceof, /* use_tentative_return_info */ !call_info->is_prototype);
/* It's allowed to override a method that return non-reference with a method that returns a reference */
if (call_info->is_prototype && (ret & ~MAY_BE_REF)) {
ret |= MAY_BE_REF;
*ce = NULL;
}
}
}
return ret;
}
static void zend_func_info_add(const func_info_t *func_infos, size_t n)
{
for (size_t i = 0; i < n; i++) {
zend_string *key = zend_string_init_interned(func_infos[i].name, func_infos[i].name_len, 1);
if (zend_hash_add_ptr(&func_info, key, (void**)&func_infos[i]) == NULL) {
fprintf(stderr, "ERROR: Duplicate function info for \"%s\"\n", func_infos[i].name);
}
zend_string_release_ex(key, 1);
}
}
zend_result zend_func_info_startup(void)
{
if (zend_func_info_rid == -1) {
zend_func_info_rid = zend_get_resource_handle("Zend Optimizer");
if (zend_func_info_rid < 0) {
return FAILURE;
}
zend_hash_init(&func_info, sizeof(old_func_infos)/sizeof(func_info_t) + sizeof(func_infos)/sizeof(func_info_t), NULL, NULL, 1);
zend_func_info_add(old_func_infos, sizeof(old_func_infos)/sizeof(func_info_t));
zend_func_info_add(func_infos, sizeof(func_infos)/sizeof(func_info_t));
}
return SUCCESS;
}
zend_result zend_func_info_shutdown(void)
{
if (zend_func_info_rid != -1) {
zend_hash_destroy(&func_info);
zend_func_info_rid = -1;
}
return SUCCESS;
}
| 7,989 | 33.145299 | 130 |
c
|
php-src
|
php-src-master/Zend/Optimizer/zend_func_info.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine, Func Info |
+----------------------------------------------------------------------+
| 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_FUNC_INFO_H
#define ZEND_FUNC_INFO_H
#include "zend_ssa.h"
/* func/cfg flags */
#define ZEND_FUNC_INDIRECT_VAR_ACCESS (1<<0) /* accesses variables by name */
#define ZEND_FUNC_HAS_CALLS (1<<1)
#define ZEND_FUNC_VARARG (1<<2) /* uses func_get_args() */
#define ZEND_FUNC_NO_LOOPS (1<<3)
#define ZEND_FUNC_IRREDUCIBLE (1<<4)
#define ZEND_FUNC_FREE_LOOP_VAR (1<<5)
#define ZEND_FUNC_RECURSIVE (1<<7)
#define ZEND_FUNC_RECURSIVE_DIRECTLY (1<<8)
#define ZEND_FUNC_RECURSIVE_INDIRECTLY (1<<9)
#define ZEND_FUNC_HAS_EXTENDED_FCALL (1<<10)
#define ZEND_FUNC_HAS_EXTENDED_STMT (1<<11)
#define ZEND_SSA_TSSA (1<<12) /* used by tracing JIT */
#define ZEND_FUNC_JIT_ON_FIRST_EXEC (1<<13) /* used by JIT */
#define ZEND_FUNC_JIT_ON_PROF_REQUEST (1<<14) /* used by JIT */
#define ZEND_FUNC_JIT_ON_HOT_COUNTERS (1<<15) /* used by JIT */
#define ZEND_FUNC_JIT_ON_HOT_TRACE (1<<16) /* used by JIT */
typedef struct _zend_func_info zend_func_info;
typedef struct _zend_call_info zend_call_info;
#define ZEND_FUNC_INFO(op_array) \
((zend_func_info*)((op_array)->reserved[zend_func_info_rid]))
#define ZEND_SET_FUNC_INFO(op_array, info) do { \
zend_func_info** pinfo = (zend_func_info**)&(op_array)->reserved[zend_func_info_rid]; \
*pinfo = info; \
} while (0)
BEGIN_EXTERN_C()
extern ZEND_API int zend_func_info_rid;
uint32_t zend_get_internal_func_info(
const zend_function *callee_func, const zend_call_info *call_info, const zend_ssa *ssa);
ZEND_API uint32_t zend_get_func_info(
const zend_call_info *call_info, const zend_ssa *ssa,
zend_class_entry **ce, bool *ce_is_instanceof);
zend_result zend_func_info_startup(void);
zend_result zend_func_info_shutdown(void);
END_EXTERN_C()
#endif /* ZEND_FUNC_INFO_H */
| 3,049 | 41.957746 | 89 |
h
|
php-src
|
php-src-master/Zend/Optimizer/zend_optimizer.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_OPTIMIZER_H
#define ZEND_OPTIMIZER_H
#include "zend.h"
#include "zend_compile.h"
#define ZEND_OPTIMIZER_PASS_1 (1<<0) /* Simple local optimizations */
#define ZEND_OPTIMIZER_PASS_2 (1<<1) /* */
#define ZEND_OPTIMIZER_PASS_3 (1<<2) /* Jump optimization */
#define ZEND_OPTIMIZER_PASS_4 (1<<3) /* INIT_FCALL_BY_NAME -> DO_FCALL */
#define ZEND_OPTIMIZER_PASS_5 (1<<4) /* CFG based optimization */
#define ZEND_OPTIMIZER_PASS_6 (1<<5) /* DFA based optimization */
#define ZEND_OPTIMIZER_PASS_7 (1<<6) /* CALL GRAPH optimization */
#define ZEND_OPTIMIZER_PASS_8 (1<<7) /* SCCP (constant propagation) */
#define ZEND_OPTIMIZER_PASS_9 (1<<8) /* TMP VAR usage */
#define ZEND_OPTIMIZER_PASS_10 (1<<9) /* NOP removal */
#define ZEND_OPTIMIZER_PASS_11 (1<<10) /* Merge equal constants */
#define ZEND_OPTIMIZER_PASS_12 (1<<11) /* Adjust used stack */
#define ZEND_OPTIMIZER_PASS_13 (1<<12) /* Remove unused variables */
#define ZEND_OPTIMIZER_PASS_14 (1<<13) /* DCE (dead code elimination) */
#define ZEND_OPTIMIZER_PASS_15 (1<<14) /* (unsafe) Collect constants */
#define ZEND_OPTIMIZER_PASS_16 (1<<15) /* Inline functions */
#define ZEND_OPTIMIZER_IGNORE_OVERLOADING (1<<16) /* (unsafe) Ignore possibility of operator overloading */
#define ZEND_OPTIMIZER_NARROW_TO_DOUBLE (1<<17) /* try to narrow long constant assignments to double */
#define ZEND_OPTIMIZER_ALL_PASSES 0x7FFFFFFF
#define DEFAULT_OPTIMIZATION_LEVEL "0x7FFEBFFF"
#define ZEND_DUMP_AFTER_PASS_1 ZEND_OPTIMIZER_PASS_1
#define ZEND_DUMP_AFTER_PASS_2 ZEND_OPTIMIZER_PASS_2
#define ZEND_DUMP_AFTER_PASS_3 ZEND_OPTIMIZER_PASS_3
#define ZEND_DUMP_AFTER_PASS_4 ZEND_OPTIMIZER_PASS_4
#define ZEND_DUMP_AFTER_PASS_5 ZEND_OPTIMIZER_PASS_5
#define ZEND_DUMP_AFTER_PASS_6 ZEND_OPTIMIZER_PASS_6
#define ZEND_DUMP_AFTER_PASS_7 ZEND_OPTIMIZER_PASS_7
#define ZEND_DUMP_AFTER_PASS_8 ZEND_OPTIMIZER_PASS_8
#define ZEND_DUMP_AFTER_PASS_9 ZEND_OPTIMIZER_PASS_9
#define ZEND_DUMP_AFTER_PASS_10 ZEND_OPTIMIZER_PASS_10
#define ZEND_DUMP_AFTER_PASS_11 ZEND_OPTIMIZER_PASS_11
#define ZEND_DUMP_AFTER_PASS_12 ZEND_OPTIMIZER_PASS_12
#define ZEND_DUMP_AFTER_PASS_13 ZEND_OPTIMIZER_PASS_13
#define ZEND_DUMP_AFTER_PASS_14 ZEND_OPTIMIZER_PASS_14
#define ZEND_DUMP_BEFORE_OPTIMIZER (1<<16)
#define ZEND_DUMP_AFTER_OPTIMIZER (1<<17)
#define ZEND_DUMP_BEFORE_BLOCK_PASS (1<<18)
#define ZEND_DUMP_AFTER_BLOCK_PASS (1<<19)
#define ZEND_DUMP_BLOCK_PASS_VARS (1<<20)
#define ZEND_DUMP_BEFORE_DFA_PASS (1<<21)
#define ZEND_DUMP_AFTER_DFA_PASS (1<<22)
#define ZEND_DUMP_DFA_CFG (1<<23)
#define ZEND_DUMP_DFA_DOMINATORS (1<<24)
#define ZEND_DUMP_DFA_LIVENESS (1<<25)
#define ZEND_DUMP_DFA_PHI (1<<26)
#define ZEND_DUMP_DFA_SSA (1<<27)
#define ZEND_DUMP_DFA_SSA_VARS (1<<28)
#define ZEND_DUMP_SCCP (1<<29)
typedef struct _zend_script {
zend_string *filename;
zend_op_array main_op_array;
HashTable function_table;
HashTable class_table;
} zend_script;
typedef void (*zend_optimizer_pass_t)(zend_script *, void *context);
BEGIN_EXTERN_C()
ZEND_API void zend_optimize_script(zend_script *script, zend_long optimization_level, zend_long debug_level);
ZEND_API int zend_optimizer_register_pass(zend_optimizer_pass_t pass);
ZEND_API void zend_optimizer_unregister_pass(int idx);
zend_result zend_optimizer_startup(void);
zend_result zend_optimizer_shutdown(void);
END_EXTERN_C()
#endif
| 4,957 | 46.673077 | 109 |
h
|
php-src
|
php-src-master/Zend/Optimizer/zend_optimizer_internal.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_OPTIMIZER_INTERNAL_H
#define ZEND_OPTIMIZER_INTERNAL_H
#include "zend_ssa.h"
#include "zend_func_info.h"
#include <stdint.h>
#define ZEND_OP1_LITERAL(opline) (op_array)->literals[(opline)->op1.constant]
#define ZEND_OP1_JMP_ADDR(opline) OP_JMP_ADDR(opline, (opline)->op1)
#define ZEND_OP2_LITERAL(opline) (op_array)->literals[(opline)->op2.constant]
#define ZEND_OP2_JMP_ADDR(opline) OP_JMP_ADDR(opline, (opline)->op2)
#define VAR_NUM(v) EX_VAR_TO_NUM(v)
#define NUM_VAR(v) EX_NUM_TO_VAR(v)
#define INV_COND(op) ((op) == ZEND_JMPZ ? ZEND_JMPNZ : ZEND_JMPZ)
#define INV_EX_COND(op) ((op) == ZEND_JMPZ_EX ? ZEND_JMPNZ : ZEND_JMPZ)
#define INV_COND_EX(op) ((op) == ZEND_JMPZ ? ZEND_JMPNZ_EX : ZEND_JMPZ_EX)
#define INV_EX_COND_EX(op) ((op) == ZEND_JMPZ_EX ? ZEND_JMPNZ_EX : ZEND_JMPZ_EX)
#define RESULT_UNUSED(op) (op->result_type == IS_UNUSED)
#define SAME_VAR(op1, op2) (op1 ## _type == op2 ## _type && op1.var == op2.var)
typedef struct _zend_optimizer_ctx {
zend_arena *arena;
zend_script *script;
HashTable *constants;
zend_long optimization_level;
zend_long debug_level;
} zend_optimizer_ctx;
#define LITERAL_LONG(op, val) do { \
zval _c; \
ZVAL_LONG(&_c, val); \
op.constant = zend_optimizer_add_literal(op_array, &_c); \
} while (0)
#define LITERAL_BOOL(op, val) do { \
zval _c; \
ZVAL_BOOL(&_c, val); \
op.constant = zend_optimizer_add_literal(op_array, &_c); \
} while (0)
#define literal_dtor(zv) do { \
zval_ptr_dtor_nogc(zv); \
ZVAL_NULL(zv); \
} while (0)
#define COPY_NODE(target, src) do { \
target ## _type = src ## _type; \
target = src; \
} while (0)
static inline bool zend_optimizer_is_loop_var_free(const zend_op *opline) {
return (opline->opcode == ZEND_FE_FREE && opline->extended_value != ZEND_FREE_ON_RETURN)
|| (opline->opcode == ZEND_FREE && opline->extended_value == ZEND_FREE_SWITCH);
}
void zend_optimizer_convert_to_free_op1(zend_op_array *op_array, zend_op *opline);
int zend_optimizer_add_literal(zend_op_array *op_array, const zval *zv);
bool zend_optimizer_get_persistent_constant(zend_string *name, zval *result, int copy);
void zend_optimizer_collect_constant(zend_optimizer_ctx *ctx, zval *name, zval* value);
bool zend_optimizer_get_collected_constant(HashTable *constants, zval *name, zval* value);
zend_result zend_optimizer_eval_binary_op(zval *result, uint8_t opcode, zval *op1, zval *op2);
zend_result zend_optimizer_eval_unary_op(zval *result, uint8_t opcode, zval *op1);
zend_result zend_optimizer_eval_cast(zval *result, uint32_t type, zval *op1);
zend_result zend_optimizer_eval_strlen(zval *result, const zval *op1);
zend_result zend_optimizer_eval_special_func_call(
zval *result, zend_string *name, zend_string *arg);
bool zend_optimizer_update_op1_const(zend_op_array *op_array,
zend_op *opline,
zval *val);
bool zend_optimizer_update_op2_const(zend_op_array *op_array,
zend_op *opline,
zval *val);
bool zend_optimizer_replace_by_const(zend_op_array *op_array,
zend_op *opline,
uint8_t type,
uint32_t var,
zval *val);
zend_op *zend_optimizer_get_loop_var_def(const zend_op_array *op_array, zend_op *free_opline);
zend_class_entry *zend_optimizer_get_class_entry(
const zend_script *script, const zend_op_array *op_array, zend_string *lcname);
zend_class_entry *zend_optimizer_get_class_entry_from_op1(
const zend_script *script, const zend_op_array *op_array, const zend_op *opline);
void zend_optimizer_pass1(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimizer_pass3(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimize_func_calls(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimize_cfg(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimize_dfa(zend_op_array *op_array, zend_optimizer_ctx *ctx);
zend_result zend_dfa_analyze_op_array(zend_op_array *op_array, zend_optimizer_ctx *ctx, zend_ssa *ssa);
void zend_dfa_optimize_op_array(zend_op_array *op_array, zend_optimizer_ctx *ctx, zend_ssa *ssa, zend_call_info **call_map);
void zend_optimize_temporary_variables(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimizer_nop_removal(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimizer_compact_literals(zend_op_array *op_array, zend_optimizer_ctx *ctx);
void zend_optimizer_compact_vars(zend_op_array *op_array);
zend_function *zend_optimizer_get_called_func(
zend_script *script, zend_op_array *op_array, zend_op *opline, bool *is_prototype);
uint32_t zend_optimizer_classify_function(zend_string *name, uint32_t num_args);
void zend_optimizer_migrate_jump(zend_op_array *op_array, zend_op *new_opline, zend_op *opline);
void zend_optimizer_shift_jump(zend_op_array *op_array, zend_op *opline, uint32_t *shiftlist);
int sccp_optimize_op_array(zend_optimizer_ctx *ctx, zend_op_array *op_array, zend_ssa *ssa, zend_call_info **call_map);
int dce_optimize_op_array(zend_op_array *op_array, zend_optimizer_ctx *optimizer_ctx, zend_ssa *ssa, bool reorder_dtor_effects);
zend_result zend_ssa_escape_analysis(const zend_script *script, zend_op_array *op_array, zend_ssa *ssa);
typedef void (*zend_op_array_func_t)(zend_op_array *, void *context);
void zend_foreach_op_array(zend_script *script, zend_op_array_func_t func, void *context);
#endif
| 7,077 | 52.218045 | 128 |
h
|
php-src
|
php-src-master/Zend/Optimizer/zend_worklist.h
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| 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: Andy Wingo <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef _ZEND_WORKLIST_H_
#define _ZEND_WORKLIST_H_
#include "zend_arena.h"
#include "zend_bitset.h"
typedef struct _zend_worklist_stack {
int *buf;
int len;
int capacity;
} zend_worklist_stack;
#define ZEND_WORKLIST_STACK_ALLOCA(s, _len, use_heap) do { \
(s)->buf = (int*)do_alloca(sizeof(int) * _len, use_heap); \
(s)->len = 0; \
(s)->capacity = _len; \
} while (0)
#define ZEND_WORKLIST_STACK_FREE_ALLOCA(s, use_heap) \
free_alloca((s)->buf, use_heap)
static inline void zend_worklist_stack_prepare(zend_arena **arena, zend_worklist_stack *stack, int len)
{
ZEND_ASSERT(len >= 0);
stack->buf = (int*)zend_arena_calloc(arena, sizeof(*stack->buf), len);
stack->len = 0;
stack->capacity = len;
}
static inline void zend_worklist_stack_push(zend_worklist_stack *stack, int i)
{
ZEND_ASSERT(stack->len < stack->capacity);
stack->buf[stack->len++] = i;
}
static inline int zend_worklist_stack_peek(const zend_worklist_stack *stack)
{
ZEND_ASSERT(stack->len);
return stack->buf[stack->len - 1];
}
static inline int zend_worklist_stack_pop(zend_worklist_stack *stack)
{
ZEND_ASSERT(stack->len);
return stack->buf[--stack->len];
}
typedef struct _zend_worklist {
zend_bitset visited;
zend_worklist_stack stack;
} zend_worklist;
#define ZEND_WORKLIST_ALLOCA(w, _len, use_heap) do { \
(w)->stack.buf = (int*)do_alloca(ZEND_MM_ALIGNED_SIZE(sizeof(int) * _len) + sizeof(zend_ulong) * zend_bitset_len(_len), use_heap); \
(w)->stack.len = 0; \
(w)->stack.capacity = _len; \
(w)->visited = (zend_bitset)((char*)(w)->stack.buf + ZEND_MM_ALIGNED_SIZE(sizeof(int) * _len)); \
memset((w)->visited, 0, sizeof(zend_ulong) * zend_bitset_len(_len)); \
} while (0)
#define ZEND_WORKLIST_FREE_ALLOCA(w, use_heap) \
free_alloca((w)->stack.buf, use_heap)
static inline void zend_worklist_prepare(zend_arena **arena, zend_worklist *worklist, int len)
{
ZEND_ASSERT(len >= 0);
worklist->visited = (zend_bitset)zend_arena_calloc(arena, sizeof(zend_ulong), zend_bitset_len(len));
zend_worklist_stack_prepare(arena, &worklist->stack, len);
}
static inline int zend_worklist_len(const zend_worklist *worklist)
{
return worklist->stack.len;
}
static inline bool zend_worklist_push(zend_worklist *worklist, int i)
{
ZEND_ASSERT(i >= 0 && i < worklist->stack.capacity);
if (zend_bitset_in(worklist->visited, i)) {
return 0;
}
zend_bitset_incl(worklist->visited, i);
zend_worklist_stack_push(&worklist->stack, i);
return 1;
}
static inline int zend_worklist_peek(const zend_worklist *worklist)
{
return zend_worklist_stack_peek(&worklist->stack);
}
static inline int zend_worklist_pop(zend_worklist *worklist)
{
/* Does not clear visited flag */
return zend_worklist_stack_pop(&worklist->stack);
}
#endif /* _ZEND_WORKLIST_H_ */
| 3,911 | 31.6 | 134 |
h
|
php-src
|
php-src-master/ext/bcmath/bcmath.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: Andi Gutmans <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef HAVE_BCMATH
#include "php_ini.h"
#include "zend_exceptions.h"
#include "bcmath_arginfo.h"
#include "ext/standard/info.h"
#include "php_bcmath.h"
#include "libbcmath/src/bcmath.h"
ZEND_DECLARE_MODULE_GLOBALS(bcmath)
static PHP_GINIT_FUNCTION(bcmath);
static PHP_GSHUTDOWN_FUNCTION(bcmath);
zend_module_entry bcmath_module_entry = {
STANDARD_MODULE_HEADER,
"bcmath",
ext_functions,
PHP_MINIT(bcmath),
PHP_MSHUTDOWN(bcmath),
NULL,
NULL,
PHP_MINFO(bcmath),
PHP_BCMATH_VERSION,
PHP_MODULE_GLOBALS(bcmath),
PHP_GINIT(bcmath),
PHP_GSHUTDOWN(bcmath),
NULL,
STANDARD_MODULE_PROPERTIES_EX
};
#ifdef COMPILE_DL_BCMATH
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(bcmath)
#endif
ZEND_INI_MH(OnUpdateScale)
{
int *p;
zend_long tmp;
tmp = zend_ini_parse_quantity_warn(new_value, entry->name);
if (tmp < 0 || tmp > INT_MAX) {
return FAILURE;
}
p = (int *) ZEND_INI_GET_ADDR();
*p = (int) tmp;
return SUCCESS;
}
/* {{{ PHP_INI */
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("bcmath.scale", "0", PHP_INI_ALL, OnUpdateScale, bc_precision, zend_bcmath_globals, bcmath_globals)
PHP_INI_END()
/* }}} */
/* {{{ PHP_GINIT_FUNCTION */
static PHP_GINIT_FUNCTION(bcmath)
{
#if defined(COMPILE_DL_BCMATH) && defined(ZTS)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
bcmath_globals->bc_precision = 0;
bc_init_numbers();
}
/* }}} */
/* {{{ PHP_GSHUTDOWN_FUNCTION */
static PHP_GSHUTDOWN_FUNCTION(bcmath)
{
_bc_free_num_ex(&bcmath_globals->_zero_, 1);
_bc_free_num_ex(&bcmath_globals->_one_, 1);
_bc_free_num_ex(&bcmath_globals->_two_, 1);
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(bcmath)
{
REGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(bcmath)
{
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(bcmath)
{
php_info_print_table_start();
php_info_print_table_row(2, "BCMath support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ php_str2num
Convert to bc_num detecting scale */
static zend_result php_str2num(bc_num *num, char *str)
{
char *p;
if (!(p = strchr(str, '.'))) {
if (!bc_str2num(num, str, 0)) {
return FAILURE;
}
return SUCCESS;
}
if (!bc_str2num(num, str, strlen(p+1))) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* {{{ Returns the sum of two arbitrary precision numbers */
PHP_FUNCTION(bcadd)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
bc_add (first, second, &result, scale);
RETVAL_STR(bc_num2str_ex(result, scale));
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the difference between two arbitrary precision numbers */
PHP_FUNCTION(bcsub)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
bc_sub (first, second, &result, scale);
RETVAL_STR(bc_num2str_ex(result, scale));
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the multiplication of two arbitrary precision numbers */
PHP_FUNCTION(bcmul)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
bc_multiply (first, second, &result, scale);
RETVAL_STR(bc_num2str_ex(result, scale));
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the quotient of two arbitrary precision numbers (division) */
PHP_FUNCTION(bcdiv)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
switch (bc_divide(first, second, &result, scale)) {
case 0: /* OK */
RETVAL_STR(bc_num2str_ex(result, scale));
break;
case -1: /* division by zero */
zend_throw_exception_ex(zend_ce_division_by_zero_error, 0, "Division by zero");
break;
}
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the modulus of the two arbitrary precision operands */
PHP_FUNCTION(bcmod)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
switch (bc_modulo(first, second, &result, scale)) {
case 0:
RETVAL_STR(bc_num2str_ex(result, scale));
break;
case -1:
zend_throw_exception_ex(zend_ce_division_by_zero_error, 0, "Modulo by zero");
break;
}
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the value of an arbitrary precision number raised to the power of another reduced by a modulus */
PHP_FUNCTION(bcpowmod)
{
zend_string *left, *right, *modulus;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, mod, result;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(3, 4)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_STR(modulus)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(4, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&mod);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
if (php_str2num(&mod, ZSTR_VAL(modulus)) == FAILURE) {
zend_argument_value_error(3, "is not well-formed");
goto cleanup;
}
if (bc_raisemod(first, second, mod, &result, scale) == SUCCESS) {
RETVAL_STR(bc_num2str_ex(result, scale));
}
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&mod);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the value of an arbitrary precision number raised to the power of another */
PHP_FUNCTION(bcpow)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second, result;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
if (php_str2num(&first, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (php_str2num(&second, ZSTR_VAL(right)) == FAILURE) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
bc_raise (first, second, &result, scale);
RETVAL_STR(bc_num2str_ex(result, scale));
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Returns the square root of an arbitrary precision number */
PHP_FUNCTION(bcsqrt)
{
zend_string *left;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num result;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STR(left)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(2, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&result);
if (php_str2num(&result, ZSTR_VAL(left)) == FAILURE) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (bc_sqrt (&result, scale) != 0) {
RETVAL_STR(bc_num2str_ex(result, scale));
} else {
zend_argument_value_error(1, "must be greater than or equal to 0");
}
cleanup: {
bc_free_num(&result);
};
}
/* }}} */
/* {{{ Compares two arbitrary precision numbers */
PHP_FUNCTION(bccomp)
{
zend_string *left, *right;
zend_long scale_param;
bool scale_param_is_null = 1;
bc_num first, second;
int scale = BCG(bc_precision);
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(left)
Z_PARAM_STR(right)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(scale_param, scale_param_is_null)
ZEND_PARSE_PARAMETERS_END();
if (scale_param_is_null) {
scale = BCG(bc_precision);
} else if (scale_param < 0 || scale_param > INT_MAX) {
zend_argument_value_error(3, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
} else {
scale = (int) scale_param;
}
bc_init_num(&first);
bc_init_num(&second);
if (!bc_str2num(&first, ZSTR_VAL(left), scale)) {
zend_argument_value_error(1, "is not well-formed");
goto cleanup;
}
if (!bc_str2num(&second, ZSTR_VAL(right), scale)) {
zend_argument_value_error(2, "is not well-formed");
goto cleanup;
}
RETVAL_LONG(bc_compare(first, second));
cleanup: {
bc_free_num(&first);
bc_free_num(&second);
};
}
/* }}} */
/* {{{ Sets default scale parameter for all bc math functions */
PHP_FUNCTION(bcscale)
{
zend_long old_scale, new_scale;
bool new_scale_is_null = 1;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_LONG_OR_NULL(new_scale, new_scale_is_null)
ZEND_PARSE_PARAMETERS_END();
old_scale = BCG(bc_precision);
if (!new_scale_is_null) {
if (new_scale < 0 || new_scale > INT_MAX) {
zend_argument_value_error(1, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
}
zend_string *ini_name = ZSTR_INIT_LITERAL("bcmath.scale", 0);
zend_string *new_scale_str = zend_long_to_str(new_scale);
zend_alter_ini_entry(ini_name, new_scale_str, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release(new_scale_str);
zend_string_release(ini_name);
}
RETURN_LONG(old_scale);
}
/* }}} */
#endif
| 15,120 | 22.298921 | 118 |
c
|
php-src
|
php-src-master/ext/bcmath/bcmath_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: f28dafc2a279f5421cd0d0e668fde0032e996ebc */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bcadd, 0, 2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_bcsub arginfo_bcadd
#define arginfo_bcmul arginfo_bcadd
#define arginfo_bcdiv arginfo_bcadd
#define arginfo_bcmod arginfo_bcadd
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bcpowmod, 0, 3, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, exponent, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, modulus, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bcpow, 0, 2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, exponent, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bcsqrt, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bccomp, 0, 2, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, num1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, num2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bcscale, 0, 0, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, scale, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_FUNCTION(bcadd);
ZEND_FUNCTION(bcsub);
ZEND_FUNCTION(bcmul);
ZEND_FUNCTION(bcdiv);
ZEND_FUNCTION(bcmod);
ZEND_FUNCTION(bcpowmod);
ZEND_FUNCTION(bcpow);
ZEND_FUNCTION(bcsqrt);
ZEND_FUNCTION(bccomp);
ZEND_FUNCTION(bcscale);
static const zend_function_entry ext_functions[] = {
ZEND_FE(bcadd, arginfo_bcadd)
ZEND_FE(bcsub, arginfo_bcsub)
ZEND_FE(bcmul, arginfo_bcmul)
ZEND_FE(bcdiv, arginfo_bcdiv)
ZEND_FE(bcmod, arginfo_bcmod)
ZEND_FE(bcpowmod, arginfo_bcpowmod)
ZEND_FE(bcpow, arginfo_bcpow)
ZEND_FE(bcsqrt, arginfo_bcsqrt)
ZEND_FE(bccomp, arginfo_bccomp)
ZEND_FE(bcscale, arginfo_bcscale)
ZEND_FE_END
};
| 2,323 | 31.277778 | 77 |
h
|
php-src
|
php-src-master/ext/bcmath/php_bcmath.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: Andi Gutmans <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_BCMATH_H
#define PHP_BCMATH_H
#include "libbcmath/src/bcmath.h"
extern zend_module_entry bcmath_module_entry;
#define phpext_bcmath_ptr &bcmath_module_entry
#include "php_version.h"
#define PHP_BCMATH_VERSION PHP_VERSION
PHP_MINIT_FUNCTION(bcmath);
PHP_MSHUTDOWN_FUNCTION(bcmath);
PHP_MINFO_FUNCTION(bcmath);
ZEND_BEGIN_MODULE_GLOBALS(bcmath)
bc_num _zero_;
bc_num _one_;
bc_num _two_;
int bc_precision;
ZEND_END_MODULE_GLOBALS(bcmath)
#if defined(ZTS) && defined(COMPILE_DL_BCMATH)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
ZEND_EXTERN_MODULE_GLOBALS(bcmath)
#define BCG(v) ZEND_MODULE_GLOBALS_ACCESSOR(bcmath, v)
#endif /* PHP_BCMATH_H */
| 1,652 | 34.170213 | 75 |
h
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/add.c
|
/* add.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Here is the full add routine that takes care of negative numbers.
N1 is added to N2 and the result placed into RESULT. SCALE_MIN
is the minimum scale for the result. */
void bc_add (bc_num n1, bc_num n2, bc_num *result, int scale_min)
{
bc_num sum = NULL;
int cmp_res;
int res_scale;
if (n1->n_sign == n2->n_sign)
{
sum = _bc_do_add (n1, n2, scale_min);
sum->n_sign = n1->n_sign;
}
else
{
/* subtraction must be done. */
cmp_res = _bc_do_compare (n1, n2, FALSE, FALSE); /* Compare magnitudes. */
switch (cmp_res)
{
case -1:
/* n1 is less than n2, subtract n1 from n2. */
sum = _bc_do_sub (n2, n1, scale_min);
sum->n_sign = n2->n_sign;
break;
case 0:
/* They are equal! return zero with the correct scale! */
res_scale = MAX (scale_min, MAX(n1->n_scale, n2->n_scale));
sum = bc_new_num (1, res_scale);
memset (sum->n_value, 0, res_scale+1);
break;
case 1:
/* n2 is less than n1, subtract n2 from n1. */
sum = _bc_do_sub (n1, n2, scale_min);
sum->n_sign = n1->n_sign;
}
}
/* Clean up and return. */
bc_free_num (result);
*result = sum;
}
| 2,536 | 29.202381 | 81 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/bcmath.h
|
/* bcmath.h: bcmath library header. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#ifndef _BCMATH_H_
#define _BCMATH_H_
typedef enum {PLUS, MINUS} sign;
typedef struct bc_struct *bc_num;
typedef struct bc_struct
{
sign n_sign;
int n_len; /* The number of digits before the decimal point. */
int n_scale; /* The number of digits after the decimal point. */
int n_refs; /* The number of pointers to this number. */
char *n_ptr; /* The pointer to the actual storage.
If NULL, n_value points to the inside of
another number (bc_multiply...) and should
not be "freed." */
char *n_value; /* The number. Not zero char terminated.
May not point to the same place as n_ptr as
in the case of leading zeros generated. */
} bc_struct;
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdbool.h>
#include "php.h" /* Needed for safe_pemalloc() in init.c */
#include "../../php_bcmath.h"
/* The base used in storing the numbers in n_value above.
Currently this MUST be 10. */
#define BASE 10
/* Some useful macros and constants. */
#define CH_VAL(c) (c - '0')
#define BCD_CHAR(d) (d + '0')
#ifdef MIN
#undef MIN
#undef MAX
#endif
#define MAX(a, b) ((a)>(b)?(a):(b))
#define MIN(a, b) ((a)>(b)?(b):(a))
#define ODD(a) ((a)&1)
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#ifndef LONG_MAX
#define LONG_MAX 0x7ffffff
#endif
/* Function Prototypes */
void bc_init_numbers(void);
bc_num _bc_new_num_ex(int length, int scale, int persistent);
void _bc_free_num_ex(bc_num *num, int persistent);
bc_num bc_copy_num(bc_num num);
void bc_init_num(bc_num *num);
int bc_str2num(bc_num *num, char *str, int scale);
zend_string *bc_num2str_ex(bc_num num, int scale);
void bc_int2num(bc_num *num, int val);
long bc_num2long(bc_num num);
int bc_compare(bc_num n1, bc_num n2);
char bc_is_zero(bc_num num);
char bc_is_zero_for_scale(bc_num num, int scale);
bool bc_is_near_zero(bc_num num, int scale);
bool bc_is_neg(bc_num num);
void bc_add(bc_num n1, bc_num n2, bc_num *result, int scale_min);
void bc_sub(bc_num n1, bc_num n2, bc_num *result, int scale_min);
void bc_multiply(bc_num n1, bc_num n2, bc_num *prod, int scale);
int bc_divide(bc_num n1, bc_num n2, bc_num *quot, int scale);
int bc_modulo(bc_num num1, bc_num num2, bc_num *resul, int scale);
int bc_divmod(bc_num num1, bc_num num2, bc_num *quo, bc_num *rem, int scale);
zend_result bc_raisemod(bc_num base, bc_num expo, bc_num mo, bc_num *result, int scale);
void bc_raise(bc_num num1, bc_num num2, bc_num *resul, int scale);
bool bc_sqrt(bc_num *num, int scale);
void bc_out_num(bc_num num, int o_base, void (* out_char)(char), int leading_zero);
/* Prototypes needed for external utility routines. */
#define bc_new_num(length, scale) _bc_new_num_ex((length), (scale), 0)
#define bc_free_num(num) _bc_free_num_ex((num), 0)
#define bc_num2str(num) bc_num2str_ex((num), (num->n_scale))
#endif
| 4,163 | 27.520548 | 88 |
h
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/compare.c
|
/* compare.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include "bcmath.h"
#include "private.h"
/* Compare two bc numbers. Return value is 0 if equal, -1 if N1 is less
than N2 and +1 if N1 is greater than N2. If USE_SIGN is false, just
compare the magnitudes. */
int _bc_do_compare(bc_num n1, bc_num n2, bool use_sign, bool ignore_last)
{
char *n1ptr, *n2ptr;
int count;
/* First, compare signs. */
if (use_sign && n1->n_sign != n2->n_sign)
{
if (n1->n_sign == PLUS)
return (1); /* Positive N1 > Negative N2 */
else
return (-1); /* Negative N1 < Positive N1 */
}
/* Now compare the magnitude. */
if (n1->n_len != n2->n_len)
{
if (n1->n_len > n2->n_len)
{
/* Magnitude of n1 > n2. */
if (!use_sign || n1->n_sign == PLUS)
return (1);
else
return (-1);
}
else
{
/* Magnitude of n1 < n2. */
if (!use_sign || n1->n_sign == PLUS)
return (-1);
else
return (1);
}
}
/* If we get here, they have the same number of integer digits.
check the integer part and the equal length part of the fraction. */
count = n1->n_len + MIN (n1->n_scale, n2->n_scale);
n1ptr = n1->n_value;
n2ptr = n2->n_value;
while ((count > 0) && (*n1ptr == *n2ptr))
{
n1ptr++;
n2ptr++;
count--;
}
if (ignore_last && count == 1 && n1->n_scale == n2->n_scale)
return (0);
if (count != 0)
{
if (*n1ptr > *n2ptr)
{
/* Magnitude of n1 > n2. */
if (!use_sign || n1->n_sign == PLUS)
return (1);
else
return (-1);
}
else
{
/* Magnitude of n1 < n2. */
if (!use_sign || n1->n_sign == PLUS)
return (-1);
else
return (1);
}
}
/* They are equal up to the last part of the equal part of the fraction. */
if (n1->n_scale != n2->n_scale)
{
if (n1->n_scale > n2->n_scale)
{
for (count = n1->n_scale-n2->n_scale; count>0; count--)
if (*n1ptr++ != 0)
{
/* Magnitude of n1 > n2. */
if (!use_sign || n1->n_sign == PLUS)
return (1);
else
return (-1);
}
}
else
{
for (count = n2->n_scale-n1->n_scale; count>0; count--)
if (*n2ptr++ != 0)
{
/* Magnitude of n1 < n2. */
if (!use_sign || n1->n_sign == PLUS)
return (-1);
else
return (1);
}
}
}
/* They must be equal! */
return (0);
}
/* This is the "user callable" routine to compare numbers N1 and N2. */
int bc_compare(bc_num n1, bc_num n2)
{
return _bc_do_compare (n1, n2, true, false);
}
| 3,819 | 23.645161 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/debug.c
|
/* debug.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* pn prints the number NUM in base 10. */
static void out_char (char c)
{
putchar(c);
}
void pn (bc_num num)
{
bc_out_num(num, 10, out_char, 0);
out_char ('\n');
}
/* pv prints a character array as if it was a string of bcd digits. */
void pv (char *name, unsigned char *num, int len)
{
int i;
printf ("%s=", name);
for (i=0; i<len; i++) printf ("%c",BCD_CHAR(num[i]));
printf ("\n");
}
| 1,789 | 27.412698 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/div.c
|
/* div.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Some utility routines for the divide: First a one digit multiply.
NUM (with SIZE digits) is multiplied by DIGIT and the result is
placed into RESULT. It is written so that NUM and RESULT can be
the same pointers. */
static void _one_mult (unsigned char *num, int size, int digit, unsigned char *result)
{
int carry, value;
unsigned char *nptr, *rptr;
if (digit == 0)
memset (result, 0, size);
else
{
if (digit == 1)
memcpy (result, num, size);
else
{
/* Initialize */
nptr = (unsigned char *) (num+size-1);
rptr = (unsigned char *) (result+size-1);
carry = 0;
while (size-- > 0)
{
value = *nptr-- * digit + carry;
*rptr-- = value % BASE;
carry = value / BASE;
}
if (carry != 0) *rptr = carry;
}
}
}
/* The full division routine. This computes N1 / N2. It returns
0 if the division is ok and the result is in QUOT. The number of
digits after the decimal point is SCALE. It returns -1 if division
by zero is tried. The algorithm is found in Knuth Vol 2. p237. */
int bc_divide (bc_num n1, bc_num n2, bc_num *quot, int scale)
{
bc_num qval;
unsigned char *num1, *num2;
unsigned char *ptr1, *ptr2, *n2ptr, *qptr;
int scale1, val;
unsigned int len1, len2, scale2, qdigits, extra, count;
unsigned int qdig, qguess, borrow, carry;
unsigned char *mval;
char zero;
unsigned int norm;
/* Test for divide by zero. */
if (bc_is_zero (n2)) return -1;
/* Test for divide by 1. If it is we must truncate. */
if (n2->n_scale == 0)
{
if (n2->n_len == 1 && *n2->n_value == 1)
{
qval = bc_new_num (n1->n_len, scale);
qval->n_sign = (n1->n_sign == n2->n_sign ? PLUS : MINUS);
memset (&qval->n_value[n1->n_len],0,scale);
memcpy (qval->n_value, n1->n_value,
n1->n_len + MIN(n1->n_scale,scale));
bc_free_num (quot);
*quot = qval;
}
}
/* Set up the divide. Move the decimal point on n1 by n2's scale.
Remember, zeros on the end of num2 are wasted effort for dividing. */
scale2 = n2->n_scale;
n2ptr = (unsigned char *) n2->n_value+n2->n_len+scale2-1;
while ((scale2 > 0) && (*n2ptr-- == 0)) scale2--;
len1 = n1->n_len + scale2;
scale1 = n1->n_scale - scale2;
if (scale1 < scale)
extra = scale - scale1;
else
extra = 0;
num1 = (unsigned char *) safe_emalloc (1, n1->n_len+n1->n_scale, extra+2);
memset (num1, 0, n1->n_len+n1->n_scale+extra+2);
memcpy (num1+1, n1->n_value, n1->n_len+n1->n_scale);
len2 = n2->n_len + scale2;
num2 = (unsigned char *) safe_emalloc (1, len2, 1);
memcpy (num2, n2->n_value, len2);
*(num2+len2) = 0;
n2ptr = num2;
while (*n2ptr == 0)
{
n2ptr++;
len2--;
}
/* Calculate the number of quotient digits. */
if (len2 > len1+scale)
{
qdigits = scale+1;
zero = TRUE;
}
else
{
zero = FALSE;
if (len2>len1)
qdigits = scale+1; /* One for the zero integer part. */
else
qdigits = len1-len2+scale+1;
}
/* Allocate and zero the storage for the quotient. */
qval = bc_new_num (qdigits-scale,scale);
memset (qval->n_value, 0, qdigits);
/* Allocate storage for the temporary storage mval. */
mval = (unsigned char *) safe_emalloc (1, len2, 1);
/* Now for the full divide algorithm. */
if (!zero)
{
/* Normalize */
norm = 10 / ((int)*n2ptr + 1);
if (norm != 1)
{
_one_mult (num1, len1+scale1+extra+1, norm, num1);
_one_mult (n2ptr, len2, norm, n2ptr);
}
/* Initialize divide loop. */
qdig = 0;
if (len2 > len1)
qptr = (unsigned char *) qval->n_value+len2-len1;
else
qptr = (unsigned char *) qval->n_value;
/* Loop */
while (qdig <= len1+scale-len2)
{
/* Calculate the quotient digit guess. */
if (*n2ptr == num1[qdig])
qguess = 9;
else
qguess = (num1[qdig]*10 + num1[qdig+1]) / *n2ptr;
/* Test qguess. */
if (n2ptr[1]*qguess >
(num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10
+ num1[qdig+2])
{
qguess--;
/* And again. */
if (n2ptr[1]*qguess >
(num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10
+ num1[qdig+2])
qguess--;
}
/* Multiply and subtract. */
borrow = 0;
if (qguess != 0)
{
*mval = 0;
_one_mult (n2ptr, len2, qguess, mval+1);
ptr1 = (unsigned char *) num1+qdig+len2;
ptr2 = (unsigned char *) mval+len2;
for (count = 0; count < len2+1; count++)
{
val = (int) *ptr1 - (int) *ptr2-- - borrow;
if (val < 0)
{
val += 10;
borrow = 1;
}
else
borrow = 0;
*ptr1-- = val;
}
}
/* Test for negative result. */
if (borrow == 1)
{
qguess--;
ptr1 = (unsigned char *) num1+qdig+len2;
ptr2 = (unsigned char *) n2ptr+len2-1;
carry = 0;
for (count = 0; count < len2; count++)
{
val = (int) *ptr1 + (int) *ptr2-- + carry;
if (val > 9)
{
val -= 10;
carry = 1;
}
else
carry = 0;
*ptr1-- = val;
}
if (carry == 1) *ptr1 = (*ptr1 + 1) % 10;
}
/* We now know the quotient digit. */
*qptr++ = qguess;
qdig++;
}
}
/* Clean up and return the number. */
qval->n_sign = ( n1->n_sign == n2->n_sign ? PLUS : MINUS );
if (bc_is_zero (qval)) qval->n_sign = PLUS;
_bc_rm_leading_zeros (qval);
bc_free_num (quot);
*quot = qval;
/* Clean up temporary storage. */
efree (mval);
efree (num1);
efree (num2);
return 0; /* Everything is OK. */
}
| 6,928 | 25.14717 | 86 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/divmod.c
|
/* divmod.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Division *and* modulo for numbers. This computes both NUM1 / NUM2 and
NUM1 % NUM2 and puts the results in QUOT and REM, except that if QUOT
is NULL then that store will be omitted.
*/
int bc_divmod (bc_num num1, bc_num num2, bc_num *quot, bc_num *rem, int scale)
{
bc_num quotient = NULL;
bc_num temp;
int rscale;
/* Check for correct numbers. */
if (bc_is_zero (num2)) return -1;
/* Calculate final scale. */
rscale = MAX (num1->n_scale, num2->n_scale+scale);
bc_init_num(&temp);
/* Calculate it. */
bc_divide (num1, num2, &temp, 0);
if (quot)
quotient = bc_copy_num (temp);
bc_multiply (temp, num2, &temp, rscale);
bc_sub (num1, temp, rem, rscale);
bc_free_num (&temp);
if (quot)
{
bc_free_num (quot);
*quot = quotient;
}
return 0; /* Everything is OK. */
}
/* Modulo for numbers. This computes NUM1 % NUM2 and puts the
result in RESULT. */
int bc_modulo (bc_num num1, bc_num num2, bc_num *result, int scale)
{
return bc_divmod (num1, num2, NULL, result, scale);
}
| 2,437 | 28.02381 | 78 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/doaddsub.c
|
/* doaddsub.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Perform addition: N1 is added to N2 and the value is
returned. The signs of N1 and N2 are ignored.
SCALE_MIN is to set the minimum scale of the result. */
bc_num _bc_do_add(bc_num n1, bc_num n2, int scale_min)
{
bc_num sum;
int sum_scale, sum_digits;
char *n1ptr, *n2ptr, *sumptr;
int carry, n1bytes, n2bytes;
int count;
/* Prepare sum. */
sum_scale = MAX (n1->n_scale, n2->n_scale);
sum_digits = MAX (n1->n_len, n2->n_len) + 1;
sum = bc_new_num (sum_digits, MAX(sum_scale, scale_min));
/* Zero extra digits made by scale_min. */
if (scale_min > sum_scale)
{
sumptr = (char *) (sum->n_value + sum_scale + sum_digits);
for (count = scale_min - sum_scale; count > 0; count--)
*sumptr++ = 0;
}
/* Start with the fraction part. Initialize the pointers. */
n1bytes = n1->n_scale;
n2bytes = n2->n_scale;
n1ptr = (char *) (n1->n_value + n1->n_len + n1bytes - 1);
n2ptr = (char *) (n2->n_value + n2->n_len + n2bytes - 1);
sumptr = (char *) (sum->n_value + sum_scale + sum_digits - 1);
/* Add the fraction part. First copy the longer fraction.*/
if (n1bytes != n2bytes)
{
if (n1bytes > n2bytes)
while (n1bytes>n2bytes)
{ *sumptr-- = *n1ptr--; n1bytes--;}
else
while (n2bytes>n1bytes)
{ *sumptr-- = *n2ptr--; n2bytes--;}
}
/* Now add the remaining fraction part and equal size integer parts. */
n1bytes += n1->n_len;
n2bytes += n2->n_len;
carry = 0;
while ((n1bytes > 0) && (n2bytes > 0))
{
*sumptr = *n1ptr-- + *n2ptr-- + carry;
if (*sumptr > (BASE-1))
{
carry = 1;
*sumptr -= BASE;
}
else
carry = 0;
sumptr--;
n1bytes--;
n2bytes--;
}
/* Now add carry the longer integer part. */
if (n1bytes == 0)
{ n1bytes = n2bytes; n1ptr = n2ptr; }
while (n1bytes-- > 0)
{
*sumptr = *n1ptr-- + carry;
if (*sumptr > (BASE-1))
{
carry = 1;
*sumptr -= BASE;
}
else
carry = 0;
sumptr--;
}
/* Set final carry. */
if (carry == 1)
*sumptr += 1;
/* Adjust sum and return. */
_bc_rm_leading_zeros (sum);
return sum;
}
/* Perform subtraction: N2 is subtracted from N1 and the value is
returned. The signs of N1 and N2 are ignored. Also, N1 is
assumed to be larger than N2. SCALE_MIN is the minimum scale
of the result. */
bc_num _bc_do_sub(bc_num n1, bc_num n2, int scale_min)
{
bc_num diff;
int diff_scale, diff_len;
int min_scale, min_len;
char *n1ptr, *n2ptr, *diffptr;
int borrow, count, val;
/* Allocate temporary storage. */
diff_len = MAX (n1->n_len, n2->n_len);
diff_scale = MAX (n1->n_scale, n2->n_scale);
min_len = MIN (n1->n_len, n2->n_len);
min_scale = MIN (n1->n_scale, n2->n_scale);
diff = bc_new_num (diff_len, MAX(diff_scale, scale_min));
/* Zero extra digits made by scale_min. */
if (scale_min > diff_scale)
{
diffptr = (char *) (diff->n_value + diff_len + diff_scale);
for (count = scale_min - diff_scale; count > 0; count--)
*diffptr++ = 0;
}
/* Initialize the subtract. */
n1ptr = (char *) (n1->n_value + n1->n_len + n1->n_scale -1);
n2ptr = (char *) (n2->n_value + n2->n_len + n2->n_scale -1);
diffptr = (char *) (diff->n_value + diff_len + diff_scale -1);
/* Subtract the numbers. */
borrow = 0;
/* Take care of the longer scaled number. */
if (n1->n_scale != min_scale)
{
/* n1 has the longer scale */
for (count = n1->n_scale - min_scale; count > 0; count--)
*diffptr-- = *n1ptr--;
}
else
{
/* n2 has the longer scale */
for (count = n2->n_scale - min_scale; count > 0; count--)
{
val = - *n2ptr-- - borrow;
if (val < 0)
{
val += BASE;
borrow = 1;
}
else
borrow = 0;
*diffptr-- = val;
}
}
/* Now do the equal length scale and integer parts. */
for (count = 0; count < min_len + min_scale; count++)
{
val = *n1ptr-- - *n2ptr-- - borrow;
if (val < 0)
{
val += BASE;
borrow = 1;
}
else
borrow = 0;
*diffptr-- = val;
}
/* If n1 has more digits then n2, we now do that subtract. */
if (diff_len != min_len)
{
for (count = diff_len - min_len; count > 0; count--)
{
val = *n1ptr-- - borrow;
if (val < 0)
{
val += BASE;
borrow = 1;
}
else
borrow = 0;
*diffptr-- = val;
}
}
/* Clean up and return. */
_bc_rm_leading_zeros (diff);
return diff;
}
| 5,842 | 24.968889 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/init.c
|
/* init.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* new_num allocates a number and sets fields to known values. */
bc_num _bc_new_num_ex (int length, int scale, int persistent)
{
bc_num temp;
/* PHP Change: malloc() -> pemalloc(), removed free_list code */
temp = (bc_num) safe_pemalloc (1, sizeof(bc_struct)+length, scale, persistent);
temp->n_sign = PLUS;
temp->n_len = length;
temp->n_scale = scale;
temp->n_refs = 1;
/* PHP Change: malloc() -> pemalloc() */
temp->n_ptr = (char *) safe_pemalloc (1, length, scale, persistent);
temp->n_value = temp->n_ptr;
memset (temp->n_ptr, 0, length+scale);
return temp;
}
/* "Frees" a bc_num NUM. Actually decreases reference count and only
frees the storage if reference count is zero. */
void _bc_free_num_ex(bc_num *num, int persistent)
{
if (*num == NULL) return;
(*num)->n_refs--;
if ((*num)->n_refs == 0) {
if ((*num)->n_ptr)
/* PHP Change: free() -> pefree(), removed free_list code */
pefree ((*num)->n_ptr, persistent);
pefree(*num, persistent);
}
*num = NULL;
}
/* Initialize the number package! */
void bc_init_numbers(void)
{
BCG(_zero_) = _bc_new_num_ex (1,0,1);
BCG(_one_) = _bc_new_num_ex (1,0,1);
BCG(_one_)->n_value[0] = 1;
BCG(_two_) = _bc_new_num_ex (1,0,1);
BCG(_two_)->n_value[0] = 2;
}
/* Make a copy of a number! Just increments the reference count! */
bc_num bc_copy_num(bc_num num)
{
num->n_refs++;
return num;
}
/* Initialize a number NUM by making it a copy of zero. */
void bc_init_num(bc_num *num)
{
*num = bc_copy_num (BCG(_zero_));
}
| 2,925 | 27.407767 | 81 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/int2num.c
|
/* int2num.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include "bcmath.h"
/* Convert an integer VAL to a bc number NUM. */
void bc_int2num(bc_num *num, int val)
{
char buffer[30];
char *bptr, *vptr;
int ix = 1;
char neg = 0;
/* Sign. */
if (val < 0)
{
neg = 1;
val = -val;
}
/* Get things going. */
bptr = buffer;
*bptr++ = val % BASE;
val = val / BASE;
/* Extract remaining digits. */
while (val != 0)
{
*bptr++ = val % BASE;
val = val / BASE;
ix++; /* Count the digits. */
}
/* Make the number. */
bc_free_num (num);
*num = bc_new_num (ix, 0);
if (neg) (*num)->n_sign = MINUS;
/* Assign the digits. */
vptr = (*num)->n_value;
while (ix-- > 0)
*vptr++ = *--bptr;
}
| 1,975 | 25.346667 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/nearzero.c
|
/* nearzero.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <stdbool.h>
#include "bcmath.h"
/* In some places we need to check if the number NUM is almost zero.
Specifically, all but the last digit is 0 and the last digit is 1.
Last digit is defined by scale. */
bool bc_is_near_zero(bc_num num, int scale)
{
int count;
char *nptr;
/* Error checking */
if (scale > num->n_scale)
scale = num->n_scale;
/* Initialize */
count = num->n_len + scale;
nptr = num->n_value;
/* The check */
while ((count > 0) && (*nptr++ == 0)) count--;
if (count != 0 && (count != 1 || *--nptr != 1))
return false;
else
return true;
}
| 1,853 | 29.9 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/neg.c
|
/* neg.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <stdbool.h>
#include "bcmath.h"
/* In some places we need to check if the number is negative. */
bool bc_is_neg(bc_num num)
{
return num->n_sign == MINUS;
}
| 1,409 | 34.25 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/num2long.c
|
/* num2long.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include "bcmath.h"
/* Convert a number NUM to a long. The function returns only the integer
part of the number. For numbers that are too large to represent as
a long, this function returns a zero. This can be detected by checking
the NUM for zero after having a zero returned. */
long bc_num2long(bc_num num)
{
long val;
char *nptr;
int index;
/* Extract the int value, ignore the fraction. */
val = 0;
nptr = num->n_value;
for (index = num->n_len; index > 0; index--) {
char n = *nptr++;
if (val > LONG_MAX/BASE) {
return 0;
}
val *= BASE;
if (val > LONG_MAX - n) {
return 0;
}
val += n;
}
/* Return the value. */
if (num->n_sign == PLUS)
return (val);
else
return (-val);
}
| 2,031 | 28.449275 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/num2str.c
|
/* num2str.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Convert a numbers to a string. Base 10 only.*/
zend_string *bc_num2str_ex(bc_num num, int scale)
{
zend_string *str;
char *sptr;
char *nptr;
int index, signch;
/* Allocate the string memory. */
signch = num->n_sign != PLUS && !bc_is_zero_for_scale(num, MIN(num->n_scale, scale)); /* Number of sign chars. */
if (scale > 0)
str = zend_string_alloc(num->n_len + scale + signch + 1, 0);
else
str = zend_string_alloc(num->n_len + signch, 0);
/* The negative sign if needed. */
sptr = ZSTR_VAL(str);
if (signch) *sptr++ = '-';
/* Load the whole number. */
nptr = num->n_value;
for (index=num->n_len; index>0; index--)
*sptr++ = BCD_CHAR(*nptr++);
/* Now the fraction. */
if (scale > 0)
{
*sptr++ = '.';
for (index=0; index<scale && index<num->n_scale; index++)
*sptr++ = BCD_CHAR(*nptr++);
for (index = num->n_scale; index<scale; index++)
*sptr++ = BCD_CHAR(0);
}
/* Terminate the string and return it! */
*sptr = '\0';
ZSTR_LEN(str) = sptr - (char *)ZSTR_VAL(str);
return str;
}
| 2,411 | 29.15 | 115 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/output.c
|
/* output.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* The following routines provide output for bcd numbers package
using the rules of POSIX bc for output. */
/* This structure is used for saving digits in the conversion process. */
typedef struct stk_rec {
long digit;
struct stk_rec *next;
} stk_rec;
/* The reference string for digits. */
static const char ref_str[] = "0123456789ABCDEF";
/* A special output routine for "multi-character digits." Exactly
SIZE characters must be output for the value VAL. If SPACE is
non-zero, we must output one space before the number. OUT_CHAR
is the actual routine for writing the characters. */
void bc_out_long (long val, size_t size, bool space, void (*out_char)(char) )
{
char digits[40];
size_t len, ix;
if (space) (*out_char) (' ');
snprintf(digits, sizeof(digits), "%ld", val);
len = strlen (digits);
while (size > len)
{
(*out_char) ('0');
size--;
}
for (ix=0; ix < len; ix++)
(*out_char) (digits[ix]);
}
/* Output of a bcd number. NUM is written in base O_BASE using OUT_CHAR
as the routine to do the actual output of the characters. */
void bc_out_num (bc_num num, int o_base, void (*out_char)(char), int leading_zero)
{
char *nptr;
int index, fdigit;
bool pre_space;
stk_rec *digits, *temp;
bc_num int_part, frac_part, base, cur_dig, t_num, max_o_digit;
/* The negative sign if needed. */
if (num->n_sign == MINUS) (*out_char) ('-');
/* Output the number. */
if (bc_is_zero (num))
(*out_char) ('0');
else
if (o_base == 10)
{
/* The number is in base 10, do it the fast way. */
nptr = num->n_value;
if (num->n_len > 1 || *nptr != 0)
for (index=num->n_len; index>0; index--)
(*out_char) (BCD_CHAR(*nptr++));
else
nptr++;
if (leading_zero && bc_is_zero (num))
(*out_char) ('0');
/* Now the fraction. */
if (num->n_scale > 0)
{
(*out_char) ('.');
for (index=0; index<num->n_scale; index++)
(*out_char) (BCD_CHAR(*nptr++));
}
}
else
{
/* special case ... */
if (leading_zero && bc_is_zero (num))
(*out_char) ('0');
/* The number is some other base. */
digits = NULL;
bc_init_num (&int_part);
bc_divide (num, BCG(_one_), &int_part, 0);
bc_init_num (&frac_part);
bc_init_num (&cur_dig);
bc_init_num (&base);
bc_sub (num, int_part, &frac_part, 0);
/* Make the INT_PART and FRAC_PART positive. */
int_part->n_sign = PLUS;
frac_part->n_sign = PLUS;
bc_int2num (&base, o_base);
bc_init_num (&max_o_digit);
bc_int2num (&max_o_digit, o_base-1);
/* Get the digits of the integer part and push them on a stack. */
while (!bc_is_zero (int_part))
{
bc_modulo (int_part, base, &cur_dig, 0);
/* PHP Change: malloc() -> emalloc() */
temp = (stk_rec *) emalloc (sizeof(stk_rec));
temp->digit = bc_num2long (cur_dig);
temp->next = digits;
digits = temp;
bc_divide (int_part, base, &int_part, 0);
}
/* Print the digits on the stack. */
if (digits != NULL)
{
/* Output the digits. */
while (digits != NULL)
{
temp = digits;
digits = digits->next;
if (o_base <= 16)
(*out_char) (ref_str[ (int) temp->digit]);
else
bc_out_long (temp->digit, max_o_digit->n_len, 1, out_char);
efree (temp);
}
}
/* Get and print the digits of the fraction part. */
if (num->n_scale > 0)
{
(*out_char) ('.');
pre_space = false;
t_num = bc_copy_num (BCG(_one_));
while (t_num->n_len <= num->n_scale) {
bc_multiply (frac_part, base, &frac_part, num->n_scale);
fdigit = bc_num2long (frac_part);
bc_int2num (&int_part, fdigit);
bc_sub (frac_part, int_part, &frac_part, 0);
if (o_base <= 16)
(*out_char) (ref_str[fdigit]);
else {
bc_out_long (fdigit, max_o_digit->n_len, pre_space, out_char);
pre_space = true;
}
bc_multiply (t_num, base, &t_num, 0);
}
bc_free_num (&t_num);
}
/* Clean up. */
bc_free_num (&int_part);
bc_free_num (&frac_part);
bc_free_num (&base);
bc_free_num (&cur_dig);
bc_free_num (&max_o_digit);
}
}
| 5,449 | 26.948718 | 82 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/private.h
|
/* private.h: bcmath library header. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
/* "Private" routines to bcmath. */
#include <stdbool.h>
/* routines */
int _bc_do_compare (bc_num n1, bc_num n2, bool use_sign, bool ignore_last);
bc_num _bc_do_add (bc_num n1, bc_num n2, int scale_min);
bc_num _bc_do_sub (bc_num n1, bc_num n2, int scale_min);
void _bc_rm_leading_zeros (bc_num num);
| 1,554 | 36.926829 | 77 |
h
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/raise.c
|
/* raise.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Raise NUM1 to the NUM2 power. The result is placed in RESULT.
Maximum exponent is LONG_MAX. If a NUM2 is not an integer,
only the integer part is used. */
void
bc_raise (bc_num num1, bc_num num2, bc_num *result, int scale)
{
bc_num temp, power;
long exponent;
int rscale;
int pwrscale;
int calcscale;
char neg;
/* Check the exponent for scale digits and convert to a long. */
if (num2->n_scale != 0) {
/* 2nd argument from PHP_FUNCTION(bcpow) */
zend_argument_value_error(2, "cannot have a fractional part");
return;
}
exponent = bc_num2long (num2);
if (exponent == 0 && (num2->n_len > 1 || num2->n_value[0] != 0)) {
/* 2nd argument from PHP_FUNCTION(bcpow) */
zend_argument_value_error(2, "is too large");
return;
}
/* Special case if exponent is a zero. */
if (exponent == 0)
{
bc_free_num (result);
*result = bc_copy_num (BCG(_one_));
return;
}
/* Other initializations. */
if (exponent < 0)
{
neg = TRUE;
exponent = -exponent;
rscale = scale;
}
else
{
neg = FALSE;
rscale = MIN (num1->n_scale*exponent, MAX(scale, num1->n_scale));
}
/* Set initial value of temp. */
power = bc_copy_num (num1);
pwrscale = num1->n_scale;
while ((exponent & 1) == 0)
{
pwrscale = 2*pwrscale;
bc_multiply (power, power, &power, pwrscale);
exponent = exponent >> 1;
}
temp = bc_copy_num (power);
calcscale = pwrscale;
exponent = exponent >> 1;
/* Do the calculation. */
while (exponent > 0)
{
pwrscale = 2*pwrscale;
bc_multiply (power, power, &power, pwrscale);
if ((exponent & 1) == 1) {
calcscale = pwrscale + calcscale;
bc_multiply (temp, power, &temp, calcscale);
}
exponent = exponent >> 1;
}
/* Assign the value. */
if (neg)
{
bc_divide (BCG(_one_), temp, result, rscale);
bc_free_num (&temp);
}
else
{
bc_free_num (result);
*result = temp;
if ((*result)->n_scale > rscale)
(*result)->n_scale = rscale;
}
bc_free_num (&power);
}
| 3,534 | 26.403101 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/raisemod.c
|
/* raisemod.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
#include "zend_exceptions.h"
/* Raise BASE to the EXPO power, reduced modulo MOD. The result is placed in RESULT. */
zend_result bc_raisemod (bc_num base, bc_num expo, bc_num mod, bc_num *result, int scale)
{
bc_num power, exponent, modulus, parity, temp;
int rscale;
/* Check the base for scale digits. */
if (base->n_scale != 0) {
/* 1st argument from PHP_FUNCTION(bcpowmod) */
zend_argument_value_error(1, "cannot have a fractional part");
return FAILURE;
}
/* Check the exponent for scale digits. */
if (expo->n_scale != 0) {
/* 2nd argument from PHP_FUNCTION(bcpowmod) */
zend_argument_value_error(2, "cannot have a fractional part");
return FAILURE;
}
if (bc_is_neg(expo)) {
zend_argument_value_error(2, "must be greater than or equal to 0");
return FAILURE;
}
/* Check the modulus for scale digits. */
if (mod->n_scale != 0) {
/* 3rd argument from PHP_FUNCTION(bcpowmod) */
zend_argument_value_error(3, "cannot have a fractional part");
return FAILURE;
}
/* Modulus cannot be 0 */
if (bc_is_zero(mod)) {
zend_throw_exception_ex(zend_ce_division_by_zero_error, 0, "Modulo by zero");
return FAILURE;
}
/* Set initial values. */
power = bc_copy_num (base);
exponent = bc_copy_num (expo);
modulus = bc_copy_num (mod);
temp = bc_copy_num (BCG(_one_));
bc_init_num(&parity);
/* Do the calculation. */
rscale = MAX(scale, power->n_scale);
if ( !bc_compare(modulus, BCG(_one_)) )
{
bc_free_num (&temp);
temp = bc_new_num (1, scale);
}
else
{
while ( !bc_is_zero(exponent) )
{
(void) bc_divmod (exponent, BCG(_two_), &exponent, &parity, 0);
if ( !bc_is_zero(parity) )
{
bc_multiply (temp, power, &temp, rscale);
(void) bc_modulo (temp, modulus, &temp, scale);
}
bc_multiply (power, power, &power, rscale);
(void) bc_modulo (power, modulus, &power, scale);
}
}
/* Assign the value. */
bc_free_num (&power);
bc_free_num (&exponent);
bc_free_num (&modulus);
bc_free_num (result);
bc_free_num (&parity);
*result = temp;
return SUCCESS; /* Everything is OK. */
}
| 3,512 | 29.815789 | 89 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/recmul.c
|
/* recmul.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <assert.h>
#include "bcmath.h"
#include "private.h"
/* Recursive vs non-recursive multiply crossover ranges. */
#if defined(MULDIGITS)
#include "muldigits.h"
#else
#define MUL_BASE_DIGITS 80
#endif
int mul_base_digits = MUL_BASE_DIGITS;
#define MUL_SMALL_DIGITS mul_base_digits/4
/* Multiply utility routines */
static bc_num new_sub_num(int length, int scale, char *value)
{
bc_num temp;
temp = (bc_num) emalloc (sizeof(bc_struct));
temp->n_sign = PLUS;
temp->n_len = length;
temp->n_scale = scale;
temp->n_refs = 1;
temp->n_ptr = NULL;
temp->n_value = value;
return temp;
}
static void
_bc_simp_mul (bc_num n1, int n1len, bc_num n2, int n2len, bc_num *prod,
int full_scale)
{
char *n1ptr, *n2ptr, *pvptr;
char *n1end, *n2end; /* To the end of n1 and n2. */
int indx, sum, prodlen;
prodlen = n1len+n2len+1;
*prod = bc_new_num (prodlen, 0);
n1end = (char *) (n1->n_value + n1len - 1);
n2end = (char *) (n2->n_value + n2len - 1);
pvptr = (char *) ((*prod)->n_value + prodlen - 1);
sum = 0;
/* Here is the loop... */
for (indx = 0; indx < prodlen-1; indx++)
{
n1ptr = (char *) (n1end - MAX(0, indx-n2len+1));
n2ptr = (char *) (n2end - MIN(indx, n2len-1));
while ((n1ptr >= n1->n_value) && (n2ptr <= n2end))
sum += *n1ptr-- * *n2ptr++;
*pvptr-- = sum % BASE;
sum = sum / BASE;
}
*pvptr = sum;
}
/* A special adder/subtractor for the recursive divide and conquer
multiply algorithm. Note: if sub is called, accum must
be larger that what is being subtracted. Also, accum and val
must have n_scale = 0. (e.g. they must look like integers. *) */
static void
_bc_shift_addsub (bc_num accum, bc_num val, int shift, int sub)
{
signed char *accp, *valp;
int count, carry;
count = val->n_len;
if (val->n_value[0] == 0)
count--;
assert (accum->n_len+accum->n_scale >= shift+count);
/* Set up pointers and others */
accp = (signed char *)(accum->n_value +
accum->n_len + accum->n_scale - shift - 1);
valp = (signed char *)(val->n_value + val->n_len - 1);
carry = 0;
if (sub) {
/* Subtraction, carry is really borrow. */
while (count--) {
*accp -= *valp-- + carry;
if (*accp < 0) {
carry = 1;
*accp-- += BASE;
} else {
carry = 0;
accp--;
}
}
while (carry) {
*accp -= carry;
if (*accp < 0)
*accp-- += BASE;
else
carry = 0;
}
} else {
/* Addition */
while (count--) {
*accp += *valp-- + carry;
if (*accp > (BASE-1)) {
carry = 1;
*accp-- -= BASE;
} else {
carry = 0;
accp--;
}
}
while (carry) {
*accp += carry;
if (*accp > (BASE-1))
*accp-- -= BASE;
else
carry = 0;
}
}
}
/* Recursive divide and conquer multiply algorithm.
Based on
Let u = u0 + u1*(b^n)
Let v = v0 + v1*(b^n)
Then uv = (B^2n+B^n)*u1*v1 + B^n*(u1-u0)*(v0-v1) + (B^n+1)*u0*v0
B is the base of storage, number of digits in u1,u0 close to equal.
*/
static void
_bc_rec_mul (bc_num u, int ulen, bc_num v, int vlen, bc_num *prod,
int full_scale)
{
bc_num u0, u1, v0, v1;
bc_num m1, m2, m3, d1, d2;
int n, prodlen, m1zero;
int d1len, d2len;
/* Base case? */
if ((ulen+vlen) < mul_base_digits
|| ulen < MUL_SMALL_DIGITS
|| vlen < MUL_SMALL_DIGITS ) {
_bc_simp_mul (u, ulen, v, vlen, prod, full_scale);
return;
}
/* Calculate n -- the u and v split point in digits. */
n = (MAX(ulen, vlen)+1) / 2;
/* Split u and v. */
if (ulen < n) {
u1 = bc_copy_num (BCG(_zero_));
u0 = new_sub_num (ulen,0, u->n_value);
} else {
u1 = new_sub_num (ulen-n, 0, u->n_value);
u0 = new_sub_num (n, 0, u->n_value+ulen-n);
}
if (vlen < n) {
v1 = bc_copy_num (BCG(_zero_));
v0 = new_sub_num (vlen,0, v->n_value);
} else {
v1 = new_sub_num (vlen-n, 0, v->n_value);
v0 = new_sub_num (n, 0, v->n_value+vlen-n);
}
_bc_rm_leading_zeros (u1);
_bc_rm_leading_zeros (u0);
_bc_rm_leading_zeros (v1);
_bc_rm_leading_zeros (v0);
m1zero = bc_is_zero(u1) || bc_is_zero(v1);
/* Calculate sub results ... */
bc_init_num(&d1);
bc_init_num(&d2);
bc_sub (u1, u0, &d1, 0);
d1len = d1->n_len;
bc_sub (v0, v1, &d2, 0);
d2len = d2->n_len;
/* Do recursive multiplies and shifted adds. */
if (m1zero)
m1 = bc_copy_num (BCG(_zero_));
else
_bc_rec_mul (u1, u1->n_len, v1, v1->n_len, &m1, 0);
if (bc_is_zero(d1) || bc_is_zero(d2))
m2 = bc_copy_num (BCG(_zero_));
else
_bc_rec_mul (d1, d1len, d2, d2len, &m2, 0);
if (bc_is_zero(u0) || bc_is_zero(v0))
m3 = bc_copy_num (BCG(_zero_));
else
_bc_rec_mul (u0, u0->n_len, v0, v0->n_len, &m3, 0);
/* Initialize product */
prodlen = ulen+vlen+1;
*prod = bc_new_num(prodlen, 0);
if (!m1zero) {
_bc_shift_addsub (*prod, m1, 2*n, 0);
_bc_shift_addsub (*prod, m1, n, 0);
}
_bc_shift_addsub (*prod, m3, n, 0);
_bc_shift_addsub (*prod, m3, 0, 0);
_bc_shift_addsub (*prod, m2, n, d1->n_sign != d2->n_sign);
/* Now clean up! */
bc_free_num (&u1);
bc_free_num (&u0);
bc_free_num (&v1);
bc_free_num (&m1);
bc_free_num (&v0);
bc_free_num (&m2);
bc_free_num (&m3);
bc_free_num (&d1);
bc_free_num (&d2);
}
/* The multiply routine. N2 times N1 is put int PROD with the scale of
the result being MIN(N2 scale+N1 scale, MAX (SCALE, N2 scale, N1 scale)).
*/
void
bc_multiply (bc_num n1, bc_num n2, bc_num *prod, int scale)
{
bc_num pval;
int len1, len2;
int full_scale, prod_scale;
/* Initialize things. */
len1 = n1->n_len + n1->n_scale;
len2 = n2->n_len + n2->n_scale;
full_scale = n1->n_scale + n2->n_scale;
prod_scale = MIN(full_scale,MAX(scale,MAX(n1->n_scale,n2->n_scale)));
/* Do the multiply */
_bc_rec_mul (n1, len1, n2, len2, &pval, full_scale);
/* Assign to prod and clean up the number. */
pval->n_sign = ( n1->n_sign == n2->n_sign ? PLUS : MINUS );
pval->n_value = pval->n_ptr;
pval->n_len = len2 + len1 + 1 - full_scale;
pval->n_scale = prod_scale;
_bc_rm_leading_zeros (pval);
if (bc_is_zero (pval))
pval->n_sign = PLUS;
bc_free_num (prod);
*prod = pval;
}
| 7,442 | 24.84375 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/rmzero.c
|
/* rmzero.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include "bcmath.h"
#include "private.h"
/* For many things, we may have leading zeros in a number NUM.
_bc_rm_leading_zeros just moves the data "value" pointer to the
correct place and adjusts the length. */
void _bc_rm_leading_zeros(bc_num num)
{
/* We can move n_value to point to the first non zero digit! */
while (*num->n_value == 0 && num->n_len > 1) {
num->n_value++;
num->n_len--;
}
}
| 1,679 | 34 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/sqrt.c
|
/* sqrt.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdbool.h>
#include "bcmath.h"
#include "private.h"
/* Take the square root NUM and return it in NUM with SCALE digits
after the decimal place. */
bool bc_sqrt(bc_num *num, int scale)
{
int rscale, cmp_res;
int cscale;
bc_num guess, guess1, point5, diff;
/* Initial checks. */
cmp_res = bc_compare (*num, BCG(_zero_));
if (cmp_res < 0) {
return false; /* error */
} else {
if (cmp_res == 0) {
bc_free_num (num);
*num = bc_copy_num (BCG(_zero_));
return true;
}
}
cmp_res = bc_compare (*num, BCG(_one_));
if (cmp_res == 0)
{
bc_free_num (num);
*num = bc_copy_num (BCG(_one_));
return true;
}
/* Initialize the variables. */
rscale = MAX (scale, (*num)->n_scale);
bc_init_num(&guess1);
bc_init_num(&diff);
point5 = bc_new_num (1,1);
point5->n_value[1] = 5;
/* Calculate the initial guess. */
if (cmp_res < 0) {
/* The number is between 0 and 1. Guess should start at 1. */
guess = bc_copy_num (BCG(_one_));
cscale = (*num)->n_scale;
} else {
/* The number is greater than 1. Guess should start at 10^(exp/2). */
bc_init_num(&guess);
bc_int2num (&guess,10);
bc_int2num (&guess1,(*num)->n_len);
bc_multiply (guess1, point5, &guess1, 0);
guess1->n_scale = 0;
bc_raise (guess, guess1, &guess, 0);
bc_free_num (&guess1);
cscale = 3;
}
/* Find the square root using Newton's algorithm. */
bool done = false;
while (!done) {
bc_free_num (&guess1);
guess1 = bc_copy_num (guess);
bc_divide (*num, guess, &guess, cscale);
bc_add (guess, guess1, &guess, 0);
bc_multiply (guess, point5, &guess, cscale);
bc_sub (guess, guess1, &diff, cscale+1);
if (bc_is_near_zero (diff, cscale)) {
if (cscale < rscale+1) {
cscale = MIN (cscale*3, rscale+1);
} else {
done = true;
}
}
}
/* Assign the number and clean up. */
bc_free_num (num);
bc_divide (guess,BCG(_one_),num,rscale);
bc_free_num (&guess);
bc_free_num (&guess1);
bc_free_num (&point5);
bc_free_num (&diff);
return true;
}
| 3,398 | 27.805085 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/str2num.c
|
/* str2num.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* Convert strings to bc numbers. Base 10 only.*/
int
bc_str2num (bc_num *num, char *str, int scale)
{
int digits, strscale;
char *ptr, *nptr;
char zero_int;
/* Prepare num. */
bc_free_num (num);
/* Check for valid number and count digits. */
ptr = str;
digits = 0;
strscale = 0;
zero_int = FALSE;
if ( (*ptr == '+') || (*ptr == '-')) ptr++; /* Sign */
while (*ptr == '0') ptr++; /* Skip leading zeros. */
while (*ptr >= '0' && *ptr <= '9') ptr++, digits++; /* digits */
if (*ptr == '.') ptr++; /* decimal point */
while (*ptr >= '0' && *ptr <= '9') ptr++, strscale++; /* digits */
if ((*ptr != '\0') || (digits+strscale == 0))
{
*num = bc_copy_num (BCG(_zero_));
return *ptr == '\0';
}
/* Adjust numbers and allocate storage and initialize fields. */
strscale = MIN(strscale, scale);
if (digits == 0)
{
zero_int = TRUE;
digits = 1;
}
*num = bc_new_num (digits, strscale);
/* Build the whole number. */
ptr = str;
if (*ptr == '-')
{
(*num)->n_sign = MINUS;
ptr++;
}
else
{
(*num)->n_sign = PLUS;
if (*ptr == '+') ptr++;
}
while (*ptr == '0') ptr++; /* Skip leading zeros. */
nptr = (*num)->n_value;
if (zero_int)
{
*nptr++ = 0;
digits = 0;
}
for (;digits > 0; digits--)
*nptr++ = CH_VAL(*ptr++);
/* Build the fractional part. */
if (strscale > 0)
{
ptr++; /* skip the decimal point! */
for (;strscale > 0; strscale--)
*nptr++ = CH_VAL(*ptr++);
}
if (bc_is_zero (*num))
(*num)->n_sign = PLUS;
return 1;
}
| 3,000 | 25.557522 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/sub.c
|
/* sub.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include "bcmath.h"
#include "private.h"
/* Here is the full subtract routine that takes care of negative numbers.
N2 is subtracted from N1 and the result placed in RESULT. SCALE_MIN
is the minimum scale for the result. */
void bc_sub(bc_num n1, bc_num n2, bc_num *result, int scale_min)
{
bc_num diff = NULL;
int cmp_res;
int res_scale;
if (n1->n_sign != n2->n_sign)
{
diff = _bc_do_add (n1, n2, scale_min);
diff->n_sign = n1->n_sign;
}
else
{
/* subtraction must be done. */
/* Compare magnitudes. */
cmp_res = _bc_do_compare (n1, n2, FALSE, FALSE);
switch (cmp_res)
{
case -1:
/* n1 is less than n2, subtract n1 from n2. */
diff = _bc_do_sub (n2, n1, scale_min);
diff->n_sign = (n2->n_sign == PLUS ? MINUS : PLUS);
break;
case 0:
/* They are equal! return zero! */
res_scale = MAX (scale_min, MAX(n1->n_scale, n2->n_scale));
diff = bc_new_num (1, res_scale);
memset (diff->n_value, 0, res_scale+1);
break;
case 1:
/* n2 is less than n1, subtract n2 from n1. */
diff = _bc_do_sub (n1, n2, scale_min);
diff->n_sign = n1->n_sign;
break;
}
}
/* Clean up and return. */
bc_free_num (result);
*result = diff;
}
| 2,493 | 29.790123 | 77 |
c
|
php-src
|
php-src-master/ext/bcmath/libbcmath/src/zero.c
|
/* zero.c: bcmath library file. */
/*
Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
Copyright (C) 2000 Philip A. Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. (LICENSE)
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include "bcmath.h"
#include "private.h"
/* In some places we need to check if the number NUM is zero. */
char
bc_is_zero_for_scale (bc_num num, int scale)
{
int count;
char *nptr;
/* Quick check. */
if (num == BCG(_zero_)) return TRUE;
/* Initialize */
count = num->n_len + scale;
nptr = num->n_value;
/* The check */
while ((count > 0) && (*nptr++ == 0)) count--;
if (count != 0)
return FALSE;
else
return TRUE;
}
char
bc_is_zero (bc_num num)
{
return bc_is_zero_for_scale(num, num->n_scale);
}
| 1,876 | 26.202899 | 77 |
c
|
php-src
|
php-src-master/ext/bz2/bz2_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: ebd3dc9902075c276828c17dc7a1c3bdc5401f8e */
ZEND_BEGIN_ARG_INFO_EX(arginfo_bzopen, 0, 0, 2)
ZEND_ARG_INFO(0, file)
ZEND_ARG_TYPE_INFO(0, mode, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bzread, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_INFO(0, bz)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "1024")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bzwrite, 0, 2, MAY_BE_LONG|MAY_BE_FALSE)
ZEND_ARG_INFO(0, bz)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bzflush, 0, 1, _IS_BOOL, 0)
ZEND_ARG_INFO(0, bz)
ZEND_END_ARG_INFO()
#define arginfo_bzclose arginfo_bzflush
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bzerrno, 0, 1, IS_LONG, 0)
ZEND_ARG_INFO(0, bz)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bzerrstr, 0, 1, IS_STRING, 0)
ZEND_ARG_INFO(0, bz)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_bzerror, 0, 1, IS_ARRAY, 0)
ZEND_ARG_INFO(0, bz)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bzcompress, 0, 1, MAY_BE_STRING|MAY_BE_LONG)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, block_size, IS_LONG, 0, "4")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, work_factor, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bzdecompress, 0, 1, MAY_BE_STRING|MAY_BE_LONG|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, use_less_memory, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_FUNCTION(bzopen);
ZEND_FUNCTION(bzread);
ZEND_FUNCTION(fwrite);
ZEND_FUNCTION(fflush);
ZEND_FUNCTION(fclose);
ZEND_FUNCTION(bzerrno);
ZEND_FUNCTION(bzerrstr);
ZEND_FUNCTION(bzerror);
ZEND_FUNCTION(bzcompress);
ZEND_FUNCTION(bzdecompress);
static const zend_function_entry ext_functions[] = {
ZEND_FE(bzopen, arginfo_bzopen)
ZEND_FE(bzread, arginfo_bzread)
ZEND_FALIAS(bzwrite, fwrite, arginfo_bzwrite)
ZEND_FALIAS(bzflush, fflush, arginfo_bzflush)
ZEND_FALIAS(bzclose, fclose, arginfo_bzclose)
ZEND_FE(bzerrno, arginfo_bzerrno)
ZEND_FE(bzerrstr, arginfo_bzerrstr)
ZEND_FE(bzerror, arginfo_bzerror)
ZEND_FE(bzcompress, arginfo_bzcompress)
ZEND_FE(bzdecompress, arginfo_bzdecompress)
ZEND_FE_END
};
| 2,492 | 32.24 | 107 |
h
|
php-src
|
php-src-master/ext/bz2/bz2_filter.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: Sara Golemon ([email protected]) |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_bz2.h"
/* {{{ data structure */
enum strm_status {
PHP_BZ2_UNINITIALIZED,
PHP_BZ2_RUNNING,
PHP_BZ2_FINISHED
};
typedef struct _php_bz2_filter_data {
bz_stream strm;
char *inbuf;
char *outbuf;
size_t inbuf_len;
size_t outbuf_len;
enum strm_status status; /* Decompress option */
unsigned int small_footprint : 1; /* Decompress option */
unsigned int expect_concatenated : 1; /* Decompress option */
unsigned int is_flushed : 1; /* only for compression */
int persistent;
} php_bz2_filter_data;
/* }}} */
/* {{{ Memory management wrappers */
static void *php_bz2_alloc(void *opaque, int items, int size)
{
return (void *)safe_pemalloc(items, size, 0, ((php_bz2_filter_data*)opaque)->persistent);
}
static void php_bz2_free(void *opaque, void *address)
{
pefree((void *)address, ((php_bz2_filter_data*)opaque)->persistent);
}
/* }}} */
/* {{{ bzip2.decompress filter implementation */
static php_stream_filter_status_t php_bz2_decompress_filter(
php_stream *stream,
php_stream_filter *thisfilter,
php_stream_bucket_brigade *buckets_in,
php_stream_bucket_brigade *buckets_out,
size_t *bytes_consumed,
int flags
)
{
php_bz2_filter_data *data;
php_stream_bucket *bucket;
size_t consumed = 0;
int status;
php_stream_filter_status_t exit_status = PSFS_FEED_ME;
bz_stream *streamp;
if (!Z_PTR(thisfilter->abstract)) {
/* Should never happen */
return PSFS_ERR_FATAL;
}
data = (php_bz2_filter_data *)Z_PTR(thisfilter->abstract);
streamp = &(data->strm);
while (buckets_in->head) {
size_t bin = 0, desired;
bucket = php_stream_bucket_make_writeable(buckets_in->head);
while (bin < bucket->buflen) {
if (data->status == PHP_BZ2_UNINITIALIZED) {
status = BZ2_bzDecompressInit(streamp, 0, data->small_footprint);
if (BZ_OK != status) {
php_stream_bucket_delref(bucket);
return PSFS_ERR_FATAL;
}
data->status = PHP_BZ2_RUNNING;
}
if (data->status != PHP_BZ2_RUNNING) {
consumed += bucket->buflen;
break;
}
desired = bucket->buflen - bin;
if (desired > data->inbuf_len) {
desired = data->inbuf_len;
}
memcpy(data->strm.next_in, bucket->buf + bin, desired);
data->strm.avail_in = desired;
status = BZ2_bzDecompress(&(data->strm));
if (status == BZ_STREAM_END) {
BZ2_bzDecompressEnd(&(data->strm));
if (data->expect_concatenated) {
data->status = PHP_BZ2_UNINITIALIZED;
} else {
data->status = PHP_BZ2_FINISHED;
}
} else if (status != BZ_OK) {
/* Something bad happened */
php_error_docref(NULL, E_NOTICE, "bzip2 decompression failed");
php_stream_bucket_delref(bucket);
return PSFS_ERR_FATAL;
}
desired -= data->strm.avail_in; /* desired becomes what we consumed this round through */
data->strm.next_in = data->inbuf;
data->strm.avail_in = 0;
consumed += desired;
bin += desired;
if (data->strm.avail_out < data->outbuf_len) {
php_stream_bucket *out_bucket;
size_t bucketlen = data->outbuf_len - data->strm.avail_out;
out_bucket = php_stream_bucket_new(stream, estrndup(data->outbuf, bucketlen), bucketlen, 1, 0);
php_stream_bucket_append(buckets_out, out_bucket);
data->strm.avail_out = data->outbuf_len;
data->strm.next_out = data->outbuf;
exit_status = PSFS_PASS_ON;
} else if (status == BZ_STREAM_END && data->strm.avail_out >= data->outbuf_len) {
/* no more data to decompress, and nothing was spat out */
php_stream_bucket_delref(bucket);
return PSFS_PASS_ON;
}
}
php_stream_bucket_delref(bucket);
}
if ((data->status == PHP_BZ2_RUNNING) && (flags & PSFS_FLAG_FLUSH_CLOSE)) {
/* Spit it out! */
status = BZ_OK;
while (status == BZ_OK) {
status = BZ2_bzDecompress(&(data->strm));
if (data->strm.avail_out < data->outbuf_len) {
size_t bucketlen = data->outbuf_len - data->strm.avail_out;
bucket = php_stream_bucket_new(stream, estrndup(data->outbuf, bucketlen), bucketlen, 1, 0);
php_stream_bucket_append(buckets_out, bucket);
data->strm.avail_out = data->outbuf_len;
data->strm.next_out = data->outbuf;
exit_status = PSFS_PASS_ON;
} else if (status == BZ_OK) {
break;
}
}
}
if (bytes_consumed) {
*bytes_consumed = consumed;
}
return exit_status;
}
static void php_bz2_decompress_dtor(php_stream_filter *thisfilter)
{
if (thisfilter && Z_PTR(thisfilter->abstract)) {
php_bz2_filter_data *data = Z_PTR(thisfilter->abstract);
if (data->status == PHP_BZ2_RUNNING) {
BZ2_bzDecompressEnd(&(data->strm));
}
pefree(data->inbuf, data->persistent);
pefree(data->outbuf, data->persistent);
pefree(data, data->persistent);
}
}
static const php_stream_filter_ops php_bz2_decompress_ops = {
php_bz2_decompress_filter,
php_bz2_decompress_dtor,
"bzip2.decompress"
};
/* }}} */
/* {{{ bzip2.compress filter implementation */
static php_stream_filter_status_t php_bz2_compress_filter(
php_stream *stream,
php_stream_filter *thisfilter,
php_stream_bucket_brigade *buckets_in,
php_stream_bucket_brigade *buckets_out,
size_t *bytes_consumed,
int flags
)
{
php_bz2_filter_data *data;
php_stream_bucket *bucket;
size_t consumed = 0;
int status;
php_stream_filter_status_t exit_status = PSFS_FEED_ME;
if (!Z_PTR(thisfilter->abstract)) {
/* Should never happen */
return PSFS_ERR_FATAL;
}
data = (php_bz2_filter_data *)Z_PTR(thisfilter->abstract);
while (buckets_in->head) {
size_t bin = 0, desired;
bucket = php_stream_bucket_make_writeable(buckets_in->head);
while (bin < bucket->buflen) {
int flush_mode;
desired = bucket->buflen - bin;
if (desired > data->inbuf_len) {
desired = data->inbuf_len;
}
memcpy(data->strm.next_in, bucket->buf + bin, desired);
data->strm.avail_in = desired;
flush_mode = flags & PSFS_FLAG_FLUSH_CLOSE ? BZ_FINISH : (flags & PSFS_FLAG_FLUSH_INC ? BZ_FLUSH : BZ_RUN);
data->is_flushed = flush_mode != BZ_RUN;
status = BZ2_bzCompress(&(data->strm), flush_mode);
if (status != BZ_RUN_OK && status != BZ_FLUSH_OK && status != BZ_FINISH_OK) {
/* Something bad happened */
php_stream_bucket_delref(bucket);
return PSFS_ERR_FATAL;
}
desired -= data->strm.avail_in; /* desired becomes what we consumed this round through */
data->strm.next_in = data->inbuf;
data->strm.avail_in = 0;
consumed += desired;
bin += desired;
if (data->strm.avail_out < data->outbuf_len) {
php_stream_bucket *out_bucket;
size_t bucketlen = data->outbuf_len - data->strm.avail_out;
out_bucket = php_stream_bucket_new(stream, estrndup(data->outbuf, bucketlen), bucketlen, 1, 0);
php_stream_bucket_append(buckets_out, out_bucket);
data->strm.avail_out = data->outbuf_len;
data->strm.next_out = data->outbuf;
exit_status = PSFS_PASS_ON;
}
}
php_stream_bucket_delref(bucket);
}
if (flags & PSFS_FLAG_FLUSH_CLOSE || ((flags & PSFS_FLAG_FLUSH_INC) && !data->is_flushed)) {
/* Spit it out! */
do {
status = BZ2_bzCompress(&(data->strm), (flags & PSFS_FLAG_FLUSH_CLOSE ? BZ_FINISH : BZ_FLUSH));
data->is_flushed = 1;
if (data->strm.avail_out < data->outbuf_len) {
size_t bucketlen = data->outbuf_len - data->strm.avail_out;
bucket = php_stream_bucket_new(stream, estrndup(data->outbuf, bucketlen), bucketlen, 1, 0);
php_stream_bucket_append(buckets_out, bucket);
data->strm.avail_out = data->outbuf_len;
data->strm.next_out = data->outbuf;
exit_status = PSFS_PASS_ON;
}
} while (status == (flags & PSFS_FLAG_FLUSH_CLOSE ? BZ_FINISH_OK : BZ_FLUSH_OK));
}
if (bytes_consumed) {
*bytes_consumed = consumed;
}
return exit_status;
}
static void php_bz2_compress_dtor(php_stream_filter *thisfilter)
{
if (Z_PTR(thisfilter->abstract)) {
php_bz2_filter_data *data = Z_PTR(thisfilter->abstract);
BZ2_bzCompressEnd(&(data->strm));
pefree(data->inbuf, data->persistent);
pefree(data->outbuf, data->persistent);
pefree(data, data->persistent);
}
}
static const php_stream_filter_ops php_bz2_compress_ops = {
php_bz2_compress_filter,
php_bz2_compress_dtor,
"bzip2.compress"
};
/* }}} */
/* {{{ bzip2.* common factory */
static php_stream_filter *php_bz2_filter_create(const char *filtername, zval *filterparams, uint8_t persistent)
{
const php_stream_filter_ops *fops = NULL;
php_bz2_filter_data *data;
int status = BZ_OK;
/* Create this filter */
data = pecalloc(1, sizeof(php_bz2_filter_data), persistent);
/* Circular reference */
data->strm.opaque = (void *) data;
data->strm.bzalloc = php_bz2_alloc;
data->strm.bzfree = php_bz2_free;
data->persistent = persistent;
data->strm.avail_out = data->outbuf_len = data->inbuf_len = 2048;
data->strm.next_in = data->inbuf = (char *) pemalloc(data->inbuf_len, persistent);
data->strm.avail_in = 0;
data->strm.next_out = data->outbuf = (char *) pemalloc(data->outbuf_len, persistent);
if (strcasecmp(filtername, "bzip2.decompress") == 0) {
data->small_footprint = 0;
data->expect_concatenated = 0;
if (filterparams) {
zval *tmpzval = NULL;
if (Z_TYPE_P(filterparams) == IS_ARRAY || Z_TYPE_P(filterparams) == IS_OBJECT) {
if ((tmpzval = zend_hash_str_find(HASH_OF(filterparams), "concatenated", sizeof("concatenated")-1))) {
data->expect_concatenated = zend_is_true(tmpzval);
tmpzval = NULL;
}
tmpzval = zend_hash_str_find(HASH_OF(filterparams), "small", sizeof("small")-1);
} else {
tmpzval = filterparams;
}
if (tmpzval) {
data->small_footprint = zend_is_true(tmpzval);
}
}
data->status = PHP_BZ2_UNINITIALIZED;
fops = &php_bz2_decompress_ops;
} else if (strcasecmp(filtername, "bzip2.compress") == 0) {
int blockSize100k = PHP_BZ2_FILTER_DEFAULT_BLOCKSIZE;
int workFactor = PHP_BZ2_FILTER_DEFAULT_WORKFACTOR;
if (filterparams) {
zval *tmpzval;
if (Z_TYPE_P(filterparams) == IS_ARRAY || Z_TYPE_P(filterparams) == IS_OBJECT) {
if ((tmpzval = zend_hash_str_find(HASH_OF(filterparams), "blocks", sizeof("blocks")-1))) {
/* How much memory to allocate (1 - 9) x 100kb */
zend_long blocks = zval_get_long(tmpzval);
if (blocks < 1 || blocks > 9) {
php_error_docref(NULL, E_WARNING, "Invalid parameter given for number of blocks to allocate (" ZEND_LONG_FMT ")", blocks);
} else {
blockSize100k = (int) blocks;
}
}
if ((tmpzval = zend_hash_str_find(HASH_OF(filterparams), "work", sizeof("work")-1))) {
/* Work Factor (0 - 250) */
zend_long work = zval_get_long(tmpzval);
if (work < 0 || work > 250) {
php_error_docref(NULL, E_WARNING, "Invalid parameter given for work factor (" ZEND_LONG_FMT ")", work);
} else {
workFactor = (int) work;
}
}
}
}
status = BZ2_bzCompressInit(&(data->strm), blockSize100k, 0, workFactor);
data->is_flushed = 1;
fops = &php_bz2_compress_ops;
} else {
status = BZ_DATA_ERROR;
}
if (status != BZ_OK) {
/* Unspecified (probably strm) error, let stream-filter error do its own whining */
pefree(data->strm.next_in, persistent);
pefree(data->strm.next_out, persistent);
pefree(data, persistent);
return NULL;
}
return php_stream_filter_alloc(fops, data, persistent);
}
const php_stream_filter_factory php_bz2_filter_factory = {
php_bz2_filter_create
};
/* }}} */
| 12,341 | 29.176039 | 128 |
c
|
php-src
|
php-src-master/ext/calendar/cal_unix.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: Shane Caraveo <[email protected]> |
| Colin Viebrock <[email protected]> |
| Hartmut Holzgraefe <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_calendar.h"
#include "sdncal.h"
#include <time.h>
#define SECS_PER_DAY (24 * 3600)
/* {{{ Convert UNIX timestamp to Julian Day */
PHP_FUNCTION(unixtojd)
{
time_t ts;
zend_long tl = 0;
bool tl_is_null = 1;
struct tm *ta, tmbuf;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &tl, &tl_is_null) == FAILURE) {
RETURN_THROWS();
}
if (tl_is_null) {
ts = time(NULL);
} else if (tl >= 0) {
ts = (time_t) tl;
} else {
zend_argument_value_error(1, "must be greater than or equal to 0");
RETURN_THROWS();
}
if (!(ta = php_localtime_r(&ts, &tmbuf))) {
RETURN_FALSE;
}
RETURN_LONG(GregorianToSdn(ta->tm_year+1900, ta->tm_mon+1, ta->tm_mday));
}
/* }}} */
/* {{{ Convert Julian Day to UNIX timestamp */
PHP_FUNCTION(jdtounix)
{
zend_long uday;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &uday) == FAILURE) {
RETURN_THROWS();
}
uday -= 2440588 /* J.D. of 1.1.1970 */;
if (uday < 0 || uday > ZEND_LONG_MAX / SECS_PER_DAY) { /* before beginning of unix epoch or greater than representable */
zend_value_error("jday must be between 2440588 and " ZEND_LONG_FMT, ZEND_LONG_MAX / SECS_PER_DAY + 2440588);
RETURN_THROWS();
}
RETURN_LONG(uday * SECS_PER_DAY);
}
/* }}} */
| 2,384 | 31.671233 | 122 |
c
|
php-src
|
php-src-master/ext/calendar/calendar_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: f45116785b01842f56ff923a54f65ab839b3dd61 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_cal_days_in_month, 0, 3, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, calendar, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, month, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, year, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_cal_from_jd, 0, 2, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, calendar, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_cal_info, 0, 0, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, calendar, IS_LONG, 0, "-1")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_cal_to_jd, 0, 4, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, calendar, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, month, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, year, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_easter_date, 0, 0, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, year, IS_LONG, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, mode, IS_LONG, 0, "CAL_EASTER_DEFAULT")
ZEND_END_ARG_INFO()
#define arginfo_easter_days arginfo_easter_date
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frenchtojd, 0, 3, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, month, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, year, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_gregoriantojd arginfo_frenchtojd
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_jddayofweek, 0, 1, MAY_BE_LONG|MAY_BE_STRING)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, mode, IS_LONG, 0, "CAL_DOW_DAYNO")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_jdmonthname, 0, 2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, mode, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_jdtofrench, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_jdtogregorian arginfo_jdtofrench
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_jdtojewish, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, hebrew, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
#define arginfo_jdtojulian arginfo_jdtofrench
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_jdtounix, 0, 1, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, julian_day, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_jewishtojd arginfo_frenchtojd
#define arginfo_juliantojd arginfo_frenchtojd
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_unixtojd, 0, 0, MAY_BE_LONG|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timestamp, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_FUNCTION(cal_days_in_month);
ZEND_FUNCTION(cal_from_jd);
ZEND_FUNCTION(cal_info);
ZEND_FUNCTION(cal_to_jd);
ZEND_FUNCTION(easter_date);
ZEND_FUNCTION(easter_days);
ZEND_FUNCTION(frenchtojd);
ZEND_FUNCTION(gregoriantojd);
ZEND_FUNCTION(jddayofweek);
ZEND_FUNCTION(jdmonthname);
ZEND_FUNCTION(jdtofrench);
ZEND_FUNCTION(jdtogregorian);
ZEND_FUNCTION(jdtojewish);
ZEND_FUNCTION(jdtojulian);
ZEND_FUNCTION(jdtounix);
ZEND_FUNCTION(jewishtojd);
ZEND_FUNCTION(juliantojd);
ZEND_FUNCTION(unixtojd);
static const zend_function_entry ext_functions[] = {
ZEND_FE(cal_days_in_month, arginfo_cal_days_in_month)
ZEND_FE(cal_from_jd, arginfo_cal_from_jd)
ZEND_FE(cal_info, arginfo_cal_info)
ZEND_FE(cal_to_jd, arginfo_cal_to_jd)
ZEND_FE(easter_date, arginfo_easter_date)
ZEND_FE(easter_days, arginfo_easter_days)
ZEND_FE(frenchtojd, arginfo_frenchtojd)
ZEND_FE(gregoriantojd, arginfo_gregoriantojd)
ZEND_FE(jddayofweek, arginfo_jddayofweek)
ZEND_FE(jdmonthname, arginfo_jdmonthname)
ZEND_FE(jdtofrench, arginfo_jdtofrench)
ZEND_FE(jdtogregorian, arginfo_jdtogregorian)
ZEND_FE(jdtojewish, arginfo_jdtojewish)
ZEND_FE(jdtojulian, arginfo_jdtojulian)
ZEND_FE(jdtounix, arginfo_jdtounix)
ZEND_FE(jewishtojd, arginfo_jewishtojd)
ZEND_FE(juliantojd, arginfo_juliantojd)
ZEND_FE(unixtojd, arginfo_unixtojd)
ZEND_FE_END
};
static void register_calendar_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("CAL_GREGORIAN", CAL_GREGORIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_JULIAN", CAL_JULIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_JEWISH", CAL_JEWISH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_FRENCH", CAL_FRENCH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_NUM_CALS", CAL_NUM_CALS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_DOW_DAYNO", CAL_DOW_DAYNO, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_DOW_SHORT", CAL_DOW_SHORT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_DOW_LONG", CAL_DOW_LONG, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_GREGORIAN_SHORT", CAL_MONTH_GREGORIAN_SHORT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_GREGORIAN_LONG", CAL_MONTH_GREGORIAN_LONG, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_JULIAN_SHORT", CAL_MONTH_JULIAN_SHORT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_JULIAN_LONG", CAL_MONTH_JULIAN_LONG, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_JEWISH", CAL_MONTH_JEWISH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_MONTH_FRENCH", CAL_MONTH_FRENCH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_EASTER_DEFAULT", CAL_EASTER_DEFAULT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_EASTER_ROMAN", CAL_EASTER_ROMAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_EASTER_ALWAYS_GREGORIAN", CAL_EASTER_ALWAYS_GREGORIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_EASTER_ALWAYS_JULIAN", CAL_EASTER_ALWAYS_JULIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_JEWISH_ADD_ALAFIM_GERESH", CAL_JEWISH_ADD_ALAFIM_GERESH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_JEWISH_ADD_ALAFIM", CAL_JEWISH_ADD_ALAFIM, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CAL_JEWISH_ADD_GERESHAYIM", CAL_JEWISH_ADD_GERESHAYIM, CONST_PERSISTENT);
}
| 6,107 | 41.416667 | 104 |
h
|
php-src
|
php-src-master/ext/calendar/dow.c
|
/* $selId: dow.c,v 2.0 1995/10/24 01:13:06 lees Exp $
* Copyright 1993-1995, Scott E. Lee, all rights reserved.
* Permission granted to use, copy, modify, distribute and sell so long as
* the above copyright and this permission statement are retained in all
* copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
*/
/**************************************************************************
*
* These are the externally visible components of this file:
*
* int
* DayOfWeek(
* long int sdn);
*
* Convert a SDN to a day-of-week number (0 to 6). Where 0 stands for
* Sunday, 1 for Monday, etc. and 6 stands for Saturday.
*
* char *DayNameShort[7];
*
* Convert a day-of-week number (0 to 6), as returned from DayOfWeek(), to
* the abbreviated (three character) name of the day.
*
* char *DayNameLong[7];
*
* Convert a day-of-week number (0 to 6), as returned from DayOfWeek(), to
* the name of the day.
*
**************************************************************************/
#include "sdncal.h"
int DayOfWeek(
zend_long sdn)
{
int dow;
dow = (sdn + 1) % 7;
if (dow >= 0) {
return (dow);
} else {
return (dow + 7);
}
}
const char * const DayNameShort[7] =
{
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
};
const char * const DayNameLong[7] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
| 1,415 | 20.134328 | 76 |
c
|
php-src
|
php-src-master/ext/calendar/easter.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: Shane Caraveo <[email protected]> |
| Colin Viebrock <[email protected]> |
| Hartmut Holzgraefe <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_calendar.h"
#include "sdncal.h"
#include <time.h>
static void _cal_easter(INTERNAL_FUNCTION_PARAMETERS, bool gm)
{
/* based on code by Simon Kershaw, <[email protected]> */
struct tm te;
zend_long year, golden, solar, lunar, pfm, dom, tmp, easter, result;
zend_long method = CAL_EASTER_DEFAULT;
bool year_is_null = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS(),
"|l!l", &year, &year_is_null, &method) == FAILURE) {
RETURN_THROWS();
}
/* Default to the current year if year parameter is not given */
if (year_is_null) {
time_t a;
struct tm b, *res;
time(&a);
res = php_localtime_r(&a, &b);
if (!res) {
year = 1900;
} else {
year = 1900 + b.tm_year;
}
}
if (gm && (year<1970 || year>2037)) { /* out of range for timestamps */
zend_argument_value_error(1, "must be between 1970 and 2037 (inclusive)");
RETURN_THROWS();
}
golden = (year % 19) + 1; /* the Golden number */
if ((year <= 1582 && method != CAL_EASTER_ALWAYS_GREGORIAN) ||
(year >= 1583 && year <= 1752 && method != CAL_EASTER_ROMAN && method != CAL_EASTER_ALWAYS_GREGORIAN) ||
method == CAL_EASTER_ALWAYS_JULIAN) { /* JULIAN CALENDAR */
dom = (year + (year/4) + 5) % 7; /* the "Dominical number" - finding a Sunday */
if (dom < 0) {
dom += 7;
}
pfm = (3 - (11*golden) - 7) % 30; /* uncorrected date of the Paschal full moon */
if (pfm < 0) {
pfm += 30;
}
} else { /* GREGORIAN CALENDAR */
dom = (year + (year/4) - (year/100) + (year/400)) % 7; /* the "Domincal number" */
if (dom < 0) {
dom += 7;
}
solar = (year-1600)/100 - (year-1600)/400; /* the solar and lunar corrections */
lunar = (((year-1400) / 100) * 8) / 25;
pfm = (3 - (11*golden) + solar - lunar) % 30; /* uncorrected date of the Paschal full moon */
if (pfm < 0) {
pfm += 30;
}
}
if ((pfm == 29) || (pfm == 28 && golden > 11)) { /* corrected date of the Paschal full moon */
pfm--; /* - days after 21st March */
}
tmp = (4-pfm-dom) % 7;
if (tmp < 0) {
tmp += 7;
}
easter = pfm + tmp + 1; /* Easter as the number of days after 21st March */
if (gm) { /* return a timestamp */
te.tm_isdst = -1;
te.tm_year = year-1900;
te.tm_sec = 0;
te.tm_min = 0;
te.tm_hour = 0;
if (easter < 11) {
te.tm_mon = 2; /* March */
te.tm_mday = easter+21;
} else {
te.tm_mon = 3; /* April */
te.tm_mday = easter-10;
}
result = mktime(&te);
} else { /* return the days after March 21 */
result = easter;
}
ZVAL_LONG(return_value, result);
}
/* {{{ Return the timestamp of midnight on Easter of a given year (defaults to current year) */
PHP_FUNCTION(easter_date)
{
_cal_easter(INTERNAL_FUNCTION_PARAM_PASSTHRU, true);
}
/* }}} */
/* {{{ Return the number of days after March 21 that Easter falls on for a given year (defaults to current year) */
PHP_FUNCTION(easter_days)
{
_cal_easter(INTERNAL_FUNCTION_PARAM_PASSTHRU, false);
}
/* }}} */
| 4,162 | 30.778626 | 115 |
c
|
php-src
|
php-src-master/ext/calendar/french.c
|
/* $selId: french.c,v 2.0 1995/10/24 01:13:06 lees Exp $
* Copyright 1993-1995, Scott E. Lee, all rights reserved.
* Permission granted to use, copy, modify, distribute and sell so long as
* the above copyright and this permission statement are retained in all
* copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
*/
/**************************************************************************
*
* These are the externally visible components of this file:
*
* void
* SdnToFrench(
* long int sdn,
* int *pYear,
* int *pMonth,
* int *pDay);
*
* Convert a SDN to a French republican calendar date. If the input SDN is
* before the first day of year 1 or after the last day of year 14, the
* three output values will all be set to zero, otherwise *pYear will be in
* the range 1 to 14 inclusive; *pMonth will be in the range 1 to 13
* inclusive; *pDay will be in the range 1 to 30 inclusive. If *pMonth is
* 13, the SDN represents one of the holidays at the end of the year and
* *pDay will be in the range 1 to 6 inclusive.
*
* long int
* FrenchToSdn(
* int year,
* int month,
* int day);
*
* Convert a French republican calendar date to a SDN. Zero is returned
* when the input date is detected as invalid or out of the supported
* range. The return value will be > 0 for all valid, supported dates, but
* there are some invalid dates that will return a positive value. To
* verify that a date is valid, convert it to SDN and then back and compare
* with the original.
*
* char *FrenchMonthName[14];
*
* Convert a French republican month number (1 to 13) to the name of the
* French republican month (null terminated). An index of 13 (for the
* "extra" days at the end of the year) will return the string "Extra". An
* index of zero will return a zero length string.
*
* VALID RANGE
*
* These routines only convert dates in years 1 through 14 (Gregorian
* dates 22 September 1792 through 22 September 1806). This more than
* covers the period when the calendar was in use.
*
* I would support a wider range of dates, but I have not been able to
* find an authoritative definition of when leap years were to have
* occurred. There are suggestions that it was to skip a leap year ever
* 100 years like the Gregorian calendar.
*
* CALENDAR OVERVIEW
*
* The French republican calendar was adopted in October 1793 during
* the French Revolution and was abandoned in January 1806. The intent
* was to create a new calendar system that was based on scientific
* principals, not religious traditions.
*
* The year is divided into 12 months of 30 days each. The remaining 5
* to 6 days in the year are grouped at the end and are holidays. Each
* month is divided into three decades (instead of weeks) of 10 days
* each.
*
* The epoch (first day of the first year) is 22 September 1792 in the
* Gregorian calendar. Leap years are every fourth year (year 3, 7,
* 11, etc.)
*
* TESTING
*
* This algorithm has been tested from the year 1 to 14. The source
* code of the verification program is included in this package.
*
* REFERENCES
*
* I have found no detailed, authoritative reference on this calendar.
* The algorithms are based on a preponderance of less authoritative
* sources.
*
**************************************************************************/
#include "sdncal.h"
#define FRENCH_SDN_OFFSET 2375474
#define DAYS_PER_4_YEARS 1461
#define DAYS_PER_MONTH 30
#define FIRST_VALID 2375840
#define LAST_VALID 2380952
void SdnToFrench(
zend_long sdn,
int *pYear,
int *pMonth,
int *pDay)
{
zend_long temp;
int dayOfYear;
if (sdn < FIRST_VALID || sdn > LAST_VALID) {
*pYear = 0;
*pMonth = 0;
*pDay = 0;
return;
}
temp = (sdn - FRENCH_SDN_OFFSET) * 4 - 1;
*pYear = temp / DAYS_PER_4_YEARS;
dayOfYear = (temp % DAYS_PER_4_YEARS) / 4;
*pMonth = dayOfYear / DAYS_PER_MONTH + 1;
*pDay = dayOfYear % DAYS_PER_MONTH + 1;
}
zend_long FrenchToSdn(
int year,
int month,
int day)
{
/* check for invalid dates */
if (year < 1 || year > 14 ||
month < 1 || month > 13 ||
day < 1 || day > 30) {
return (0);
}
return ((year * DAYS_PER_4_YEARS) / 4
+ (month - 1) * DAYS_PER_MONTH
+ day
+ FRENCH_SDN_OFFSET);
}
const char * const FrenchMonthName[14] =
{
"",
"Vendemiaire",
"Brumaire",
"Frimaire",
"Nivose",
"Pluviose",
"Ventose",
"Germinal",
"Floreal",
"Prairial",
"Messidor",
"Thermidor",
"Fructidor",
"Extra"
};
| 4,696 | 30.10596 | 76 |
c
|
php-src
|
php-src-master/ext/calendar/gregor.c
|
/* $selId: gregor.c,v 2.0 1995/10/24 01:13:06 lees Exp $
* Copyright 1993-1995, Scott E. Lee, all rights reserved.
* Permission granted to use, copy, modify, distribute and sell so long as
* the above copyright and this permission statement are retained in all
* copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
*/
/**************************************************************************
*
* These are the externally visible components of this file:
*
* void
* SdnToGregorian(
* long int sdn,
* int *pYear,
* int *pMonth,
* int *pDay);
*
* Convert a SDN to a Gregorian calendar date. If the input SDN is less
* than 1, the three output values will all be set to zero, otherwise
* *pYear will be >= -4714 and != 0; *pMonth will be in the range 1 to 12
* inclusive; *pDay will be in the range 1 to 31 inclusive.
*
* long int
* GregorianToSdn(
* int inputYear,
* int inputMonth,
* int inputDay);
*
* Convert a Gregorian calendar date to a SDN. Zero is returned when the
* input date is detected as invalid or out of the supported range. The
* return value will be > 0 for all valid, supported dates, but there are
* some invalid dates that will return a positive value. To verify that a
* date is valid, convert it to SDN and then back and compare with the
* original.
*
* char *MonthNameShort[13];
*
* Convert a Gregorian month number (1 to 12) to the abbreviated (three
* character) name of the Gregorian month (null terminated). An index of
* zero will return a zero length string.
*
* char *MonthNameLong[13];
*
* Convert a Gregorian month number (1 to 12) to the name of the Gregorian
* month (null terminated). An index of zero will return a zero length
* string.
*
* VALID RANGE
*
* 4714 B.C. to at least 10000 A.D.
*
* Although this software can handle dates all the way back to 4714
* B.C., such use may not be meaningful. The Gregorian calendar was
* not instituted until October 15, 1582 (or October 5, 1582 in the
* Julian calendar). Some countries did not accept it until much
* later. For example, Britain converted in 1752, The USSR in 1918 and
* Greece in 1923. Most European countries used the Julian calendar
* prior to the Gregorian.
*
* CALENDAR OVERVIEW
*
* The Gregorian calendar is a modified version of the Julian calendar.
* The only difference being the specification of leap years. The
* Julian calendar specifies that every year that is a multiple of 4
* will be a leap year. This leads to a year that is 365.25 days long,
* but the current accepted value for the tropical year is 365.242199
* days.
*
* To correct this error in the length of the year and to bring the
* vernal equinox back to March 21, Pope Gregory XIII issued a papal
* bull declaring that Thursday October 4, 1582 would be followed by
* Friday October 15, 1582 and that centennial years would only be a
* leap year if they were a multiple of 400. This shortened the year
* by 3 days per 400 years, giving a year of 365.2425 days.
*
* Another recently proposed change in the leap year rule is to make
* years that are multiples of 4000 not a leap year, but this has never
* been officially accepted and this rule is not implemented in these
* algorithms.
*
* ALGORITHMS
*
* The calculations are based on three different cycles: a 400 year
* cycle of leap years, a 4 year cycle of leap years and a 5 month
* cycle of month lengths.
*
* The 5 month cycle is used to account for the varying lengths of
* months. You will notice that the lengths alternate between 30
* and 31 days, except for three anomalies: both July and August
* have 31 days, both December and January have 31, and February
* is less than 30. Starting with March, the lengths are in a
* cycle of 5 months (31, 30, 31, 30, 31):
*
* Mar 31 days \
* Apr 30 days |
* May 31 days > First cycle
* Jun 30 days |
* Jul 31 days /
*
* Aug 31 days \
* Sep 30 days |
* Oct 31 days > Second cycle
* Nov 30 days |
* Dec 31 days /
*
* Jan 31 days \
* Feb 28/9 days |
* > Third cycle (incomplete)
*
* For this reason the calculations (internally) assume that the
* year starts with March 1.
*
* TESTING
*
* This algorithm has been tested from the year 4714 B.C. to 10000
* A.D. The source code of the verification program is included in
* this package.
*
* REFERENCES
*
* Conversions Between Calendar Date and Julian Day Number by Robert J.
* Tantzen, Communications of the Association for Computing Machinery
* August 1963. (Also published in Collected Algorithms from CACM,
* algorithm number 199).
*
**************************************************************************/
#include "sdncal.h"
#include <limits.h>
#define GREGOR_SDN_OFFSET 32045
#define DAYS_PER_5_MONTHS 153
#define DAYS_PER_4_YEARS 1461
#define DAYS_PER_400_YEARS 146097
void SdnToGregorian(
zend_long sdn,
int *pYear,
int *pMonth,
int *pDay)
{
int century;
int year;
int month;
int day;
zend_long temp;
int dayOfYear;
if (sdn <= 0 ||
sdn > (LONG_MAX - 4 * GREGOR_SDN_OFFSET) / 4) {
goto fail;
}
temp = (sdn + GREGOR_SDN_OFFSET) * 4 - 1;
/* Calculate the century (year/100). */
century = temp / DAYS_PER_400_YEARS;
/* Calculate the year and day of year (1 <= dayOfYear <= 366). */
temp = ((temp % DAYS_PER_400_YEARS) / 4) * 4 + 3;
year = (century * 100) + (temp / DAYS_PER_4_YEARS);
dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
/* Calculate the month and day of month. */
temp = dayOfYear * 5 - 3;
month = temp / DAYS_PER_5_MONTHS;
day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
/* Convert to the normal beginning of the year. */
if (month < 10) {
month += 3;
} else {
year += 1;
month -= 9;
}
/* Adjust to the B.C./A.D. type numbering. */
year -= 4800;
if (year <= 0)
year--;
*pYear = year;
*pMonth = month;
*pDay = day;
return;
fail:
*pYear = 0;
*pMonth = 0;
*pDay = 0;
}
zend_long GregorianToSdn(
int inputYear,
int inputMonth,
int inputDay)
{
zend_long year;
int month;
/* check for invalid dates */
if (inputYear == 0 || inputYear < -4714 ||
inputMonth <= 0 || inputMonth > 12 ||
inputDay <= 0 || inputDay > 31) {
return (0);
}
/* check for dates before SDN 1 (Nov 25, 4714 B.C.) */
if (inputYear == -4714) {
if (inputMonth < 11) {
return (0);
}
if (inputMonth == 11 && inputDay < 25) {
return (0);
}
}
/* Make year always a positive number. */
if (inputYear < 0) {
year = inputYear + 4801;
} else {
year = inputYear + 4800;
}
/* Adjust the start of the year. */
if (inputMonth > 2) {
month = inputMonth - 3;
} else {
month = inputMonth + 9;
year--;
}
return (((year / 100) * DAYS_PER_400_YEARS) / 4
+ ((year % 100) * DAYS_PER_4_YEARS) / 4
+ (month * DAYS_PER_5_MONTHS + 2) / 5
+ inputDay
- GREGOR_SDN_OFFSET);
}
const char * const MonthNameShort[13] =
{
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
const char * const MonthNameLong[13] =
{
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
| 7,631 | 27.162362 | 76 |
c
|
php-src
|
php-src-master/ext/calendar/julian.c
|
/* $selId: julian.c,v 2.0 1995/10/24 01:13:06 lees Exp $
* Copyright 1993-1995, Scott E. Lee, all rights reserved.
* Permission granted to use, copy, modify, distribute and sell so long as
* the above copyright and this permission statement are retained in all
* copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
*/
/**************************************************************************
*
* These are the externally visible components of this file:
*
* void
* SdnToJulian(
* zend_long sdn,
* int *pYear,
* int *pMonth,
* int *pDay);
*
* Convert a SDN to a Julian calendar date. If the input SDN is less than
* 1, the three output values will all be set to zero, otherwise *pYear
* will be >= -4713 and != 0; *pMonth will be in the range 1 to 12
* inclusive; *pDay will be in the range 1 to 31 inclusive.
*
* zend_long
* JulianToSdn(
* int inputYear,
* int inputMonth,
* int inputDay);
*
* Convert a Julian calendar date to a SDN. Zero is returned when the
* input date is detected as invalid or out of the supported range. The
* return value will be > 0 for all valid, supported dates, but there are
* some invalid dates that will return a positive value. To verify that a
* date is valid, convert it to SDN and then back and compare with the
* original.
*
* VALID RANGE
*
* 4713 B.C. to at least 10000 A.D.
*
* Although this software can handle dates all the way back to 4713
* B.C., such use may not be meaningful. The calendar was created in
* 46 B.C., but the details did not stabilize until at least 8 A.D.,
* and perhaps as late at the 4th century. Also, the beginning of a
* year varied from one culture to another - not all accepted January
* as the first month.
*
* CALENDAR OVERVIEW
*
* Julius Caesar created the calendar in 46 B.C. as a modified form of
* the old Roman republican calendar which was based on lunar cycles.
* The new Julian calendar set fixed lengths for the months, abandoning
* the lunar cycle. It also specified that there would be exactly 12
* months per year and 365.25 days per year with every 4th year being a
* leap year.
*
* Note that the current accepted value for the tropical year is
* 365.242199 days, not 365.25. This lead to an 11 day shift in the
* calendar with respect to the seasons by the 16th century when the
* Gregorian calendar was created to replace the Julian calendar.
*
* The difference between the Julian and today's Gregorian calendar is
* that the Gregorian does not make centennial years leap years unless
* they are a multiple of 400, which leads to a year of 365.2425 days.
* In other words, in the Gregorian calendar, 1700, 1800 and 1900 are
* not leap years, but 2000 is. All centennial years are leap years in
* the Julian calendar.
*
* The details are unknown, but the lengths of the months were adjusted
* until they finally stablized in 8 A.D. with their current lengths:
*
* January 31
* February 28/29
* March 31
* April 30
* May 31
* June 30
* Quintilis/July 31
* Sextilis/August 31
* September 30
* October 31
* November 30
* December 31
*
* In the early days of the calendar, the days of the month were not
* numbered as we do today. The numbers ran backwards (decreasing) and
* were counted from the Ides (15th of the month - which in the old
* Roman republican lunar calendar would have been the full moon) or
* from the Nonae (9th day before the Ides) or from the beginning of
* the next month.
*
* In the early years, the beginning of the year varied, sometimes
* based on the ascension of rulers. It was not always the first of
* January.
*
* Also, today's epoch, 1 A.D. or the birth of Jesus Christ, did not
* come into use until several centuries later when Christianity became
* a dominant religion.
*
* ALGORITHMS
*
* The calculations are based on two different cycles: a 4 year cycle
* of leap years and a 5 month cycle of month lengths.
*
* The 5 month cycle is used to account for the varying lengths of
* months. You will notice that the lengths alternate between 30 and
* 31 days, except for three anomalies: both July and August have 31
* days, both December and January have 31, and February is less than
* 30. Starting with March, the lengths are in a cycle of 5 months
* (31, 30, 31, 30, 31):
*
* Mar 31 days \
* Apr 30 days |
* May 31 days > First cycle
* Jun 30 days |
* Jul 31 days /
*
* Aug 31 days \
* Sep 30 days |
* Oct 31 days > Second cycle
* Nov 30 days |
* Dec 31 days /
*
* Jan 31 days \
* Feb 28/9 days |
* > Third cycle (incomplete)
*
* For this reason the calculations (internally) assume that the year
* starts with March 1.
*
* TESTING
*
* This algorithm has been tested from the year 4713 B.C. to 10000 A.D.
* The source code of the verification program is included in this
* package.
*
* REFERENCES
*
* Conversions Between Calendar Date and Julian Day Number by Robert J.
* Tantzen, Communications of the Association for Computing Machinery
* August 1963. (Also published in Collected Algorithms from CACM,
* algorithm number 199). [Note: the published algorithm is for the
* Gregorian calendar, but was adjusted to use the Julian calendar's
* simpler leap year rule.]
*
**************************************************************************/
#include "sdncal.h"
#include <limits.h>
#define JULIAN_SDN_OFFSET 32083
#define DAYS_PER_5_MONTHS 153
#define DAYS_PER_4_YEARS 1461
void SdnToJulian(
zend_long sdn,
int *pYear,
int *pMonth,
int *pDay)
{
int year;
int month;
int day;
zend_long temp;
int dayOfYear;
if (sdn <= 0) {
goto fail;
}
/* Check for overflow */
if (sdn > (LONG_MAX - JULIAN_SDN_OFFSET * 4 + 1) / 4 || sdn < LONG_MIN / 4) {
goto fail;
}
temp = sdn * 4 + (JULIAN_SDN_OFFSET * 4 - 1);
/* Calculate the year and day of year (1 <= dayOfYear <= 366). */
{
long yearl = temp / DAYS_PER_4_YEARS;
if (yearl > INT_MAX || yearl < INT_MIN) {
goto fail;
}
year = (int) yearl;
}
dayOfYear = (temp % DAYS_PER_4_YEARS) / 4 + 1;
/* Calculate the month and day of month. */
temp = dayOfYear * 5 - 3;
month = temp / DAYS_PER_5_MONTHS;
day = (temp % DAYS_PER_5_MONTHS) / 5 + 1;
/* Convert to the normal beginning of the year. */
if (month < 10) {
month += 3;
} else {
year += 1;
month -= 9;
}
/* Adjust to the B.C./A.D. type numbering. */
year -= 4800;
if (year <= 0)
year--;
*pYear = year;
*pMonth = month;
*pDay = day;
return;
fail:
*pYear = 0;
*pMonth = 0;
*pDay = 0;
}
zend_long JulianToSdn(
int inputYear,
int inputMonth,
int inputDay)
{
zend_long year;
int month;
/* check for invalid dates */
if (inputYear == 0 || inputYear < -4713 ||
inputMonth <= 0 || inputMonth > 12 ||
inputDay <= 0 || inputDay > 31) {
return (0);
}
/* check for dates before SDN 1 (Jan 2, 4713 B.C.) */
if (inputYear == -4713) {
if (inputMonth == 1 && inputDay == 1) {
return (0);
}
}
/* Make year always a positive number. */
if (inputYear < 0) {
year = inputYear + 4801;
} else {
year = inputYear + 4800;
}
/* Adjust the start of the year. */
if (inputMonth > 2) {
month = inputMonth - 3;
} else {
month = inputMonth + 9;
year--;
}
return ((year * DAYS_PER_4_YEARS) / 4
+ (month * DAYS_PER_5_MONTHS + 2) / 5
+ inputDay
- JULIAN_SDN_OFFSET);
}
| 8,041 | 30.537255 | 78 |
c
|
php-src
|
php-src-master/ext/calendar/php_calendar.h
|
#ifndef PHP_CALENDAR_H
#define PHP_CALENDAR_H
extern zend_module_entry calendar_module_entry;
#define calendar_module_ptr &calendar_module_entry
#include "php_version.h"
#define PHP_CALENDAR_VERSION PHP_VERSION
/* Functions */
PHP_MINIT_FUNCTION(calendar);
PHP_MINFO_FUNCTION(calendar);
#define phpext_calendar_ptr calendar_module_ptr
/*
* Specifying the easter calculation method
*
* DEFAULT is Anglican, ie. use Julian calendar before 1753
* and Gregorian after that. With ROMAN, the cutoff year is 1582.
* ALWAYS_GREGORIAN and ALWAYS_JULIAN force the calendar
* regardless of date.
*
*/
#define CAL_EASTER_DEFAULT 0
#define CAL_EASTER_ROMAN 1
#define CAL_EASTER_ALWAYS_GREGORIAN 2
#define CAL_EASTER_ALWAYS_JULIAN 3
#endif
| 746 | 21.636364 | 65 |
h
|
php-src
|
php-src-master/ext/calendar/sdncal.h
|
#ifndef SDNCAL_H
#define SDNCAL_H
/*
* This code has been modified for use with PHP
* by Shane Caraveo [email protected]
* see below for more details
*
*/
/* $selId: sdncal.h,v 2.0 1995/10/24 01:13:06 lees Exp $
* Copyright 1993-1995, Scott E. Lee, all rights reserved.
* Permission granted to use, copy, modify, distribute and sell so long as
* the above copyright and this permission statement are retained in all
* copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
*/
/**************************************************************************
*
* This package defines a set of routines that convert calendar dates to
* and from a serial day number (SDN). The SDN is a serial numbering of
* days where SDN 1 is November 25, 4714 BC in the Gregorian calendar and
* SDN 2447893 is January 1, 1990. This system of day numbering is
* sometimes referred to as Julian days, but to avoid confusion with the
* Julian calendar, it is referred to as serial day numbers here. The term
* Julian days is also used to mean the number of days since the beginning
* of the current year.
*
* The SDN can be used as an intermediate step in converting from one
* calendar system to another (such as Gregorian to Jewish). It can also
* be used for date computations such as easily comparing two dates,
* determining the day of the week, finding the date of yesterday or
* calculating the number of days between two dates.
*
* When using this software on 16 bit systems, be careful to store SDNs in
* a long int, because it will not fit in the 16 bits that some systems
* allocate to an int.
*
* For each calendar, there are two routines provided. One converts dates
* in that calendar to SDN and the other converts SDN to calendar dates.
* The routines are named SdnTo<CALENDAR>() and <CALENDAR>ToSdn(), where
* <CALENDAR> is the name of the calendar system.
*
* SDN values less than one are not supported. If a conversion routine
* returns an SDN of zero, this means that the date given is either invalid
* or is outside the supported range for that calendar.
*
* At least some validity checks are performed on input dates. For
* example, a negative month number will result in the return of zero for
* the SDN. A returned SDN greater than one does not necessarily mean that
* the input date was valid. To determine if the date is valid, convert it
* to SDN, and if the SDN is greater than zero, convert it back to a date
* and compare to the original. For example:
*
* int y1, m1, d1;
* int y2, m2, d2;
* zend_long sdn;
* ...
* sdn = GregorianToSdn(y1, m1, d1);
* if (sdn > 0) {
* SdnToGregorian(sdn, &y2, &m2, &d2);
* if (y1 == y2 && m1 == m2 && d1 == d2) {
* ... date is valid ...
* }
* }
*
**************************************************************************/
#include "php.h"
/* Gregorian calendar conversions. */
void SdnToGregorian(zend_long sdn, int *pYear, int *pMonth, int *pDay);
zend_long GregorianToSdn(int year, int month, int day);
extern const char * const MonthNameShort[13];
extern const char * const MonthNameLong[13];
/* Julian calendar conversions. */
void SdnToJulian(zend_long sdn, int *pYear, int *pMonth, int *pDay);
zend_long JulianToSdn(int year, int month, int day);
/* Jewish calendar conversions. */
void SdnToJewish(zend_long sdn, int *pYear, int *pMonth, int *pDay);
zend_long JewishToSdn(int year, int month, int day);
extern const char * const JewishMonthName[14];
extern const char * const JewishMonthNameLeap[14];
extern const char * const JewishMonthHebName[14];
extern const char * const JewishMonthHebNameLeap[14];
extern const int monthsPerYear[19];
/* French republic calendar conversions. */
void SdnToFrench(zend_long sdn, int *pYear, int *pMonth, int *pDay);
zend_long FrenchToSdn(int inputYear, int inputMonth, int inputDay);
extern const char * const FrenchMonthName[14];
/* Islamic calendar conversions. */
/* Not implemented yet. */
/* Day of week conversion. 0=Sunday, 6=Saturday */
int DayOfWeek(zend_long sdn);
extern const char * const DayNameShort[7];
extern const char * const DayNameLong[7];
#endif /* SDNCAL_H */
| 4,196 | 39.747573 | 76 |
h
|
php-src
|
php-src-master/ext/com_dotnet/com_extension_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: b91206482b5119ce6d7c899e9599acfa2e06ec2a */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_variant_set, 0, 2, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_variant_add, 0, 2, variant, 0)
ZEND_ARG_TYPE_INFO(0, left, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, right, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_variant_cat arginfo_variant_add
#define arginfo_variant_sub arginfo_variant_add
#define arginfo_variant_mul arginfo_variant_add
#define arginfo_variant_and arginfo_variant_add
#define arginfo_variant_div arginfo_variant_add
#define arginfo_variant_eqv arginfo_variant_add
#define arginfo_variant_idiv arginfo_variant_add
#define arginfo_variant_imp arginfo_variant_add
#define arginfo_variant_mod arginfo_variant_add
#define arginfo_variant_or arginfo_variant_add
#define arginfo_variant_pow arginfo_variant_add
#define arginfo_variant_xor arginfo_variant_add
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_variant_abs, 0, 1, variant, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_variant_fix arginfo_variant_abs
#define arginfo_variant_int arginfo_variant_abs
#define arginfo_variant_neg arginfo_variant_abs
#define arginfo_variant_not arginfo_variant_abs
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_variant_round, 0, 2, variant, 1)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, decimals, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_variant_cmp, 0, 2, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, left, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, right, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, locale_id, IS_LONG, 0, "LOCALE_SYSTEM_DEFAULT")
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_variant_date_to_timestamp, 0, 1, IS_LONG, 1)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_variant_date_from_timestamp, 0, 1, variant, 0)
ZEND_ARG_TYPE_INFO(0, timestamp, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_variant_get_type, 0, 1, IS_LONG, 0)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_variant_set_type, 0, 2, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_variant_cast, 0, 2, variant, 0)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_com_get_active_object, 0, 1, variant, 0)
ZEND_ARG_TYPE_INFO(0, prog_id, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, codepage, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_com_create_guid, 0, 0, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_com_event_sink, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, variant, variant, 0)
ZEND_ARG_TYPE_INFO(0, sink_object, IS_OBJECT, 0)
ZEND_ARG_TYPE_MASK(0, sink_interface, MAY_BE_ARRAY|MAY_BE_STRING|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_com_print_typeinfo, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, variant, variant, MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, dispatch_interface, IS_STRING, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, display_sink, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_com_message_pump, 0, 0, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout_milliseconds, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_com_load_typelib, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, typelib, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, case_insensitive, _IS_BOOL, 0, "true")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_variant___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, value, IS_MIXED, 0, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, type, IS_LONG, 0, "VT_EMPTY")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, codepage, IS_LONG, 0, "CP_ACP")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_com___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, module_name, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, server_name, MAY_BE_ARRAY|MAY_BE_STRING|MAY_BE_NULL, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, codepage, IS_LONG, 0, "CP_ACP")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, typelib, IS_STRING, 0, "\"\"")
ZEND_END_ARG_INFO()
#if HAVE_MSCOREE_H
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_dotnet___construct, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, assembly_name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, datatype_name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, codepage, IS_LONG, 0, "CP_ACP")
ZEND_END_ARG_INFO()
#endif
ZEND_FUNCTION(variant_set);
ZEND_FUNCTION(variant_add);
ZEND_FUNCTION(variant_cat);
ZEND_FUNCTION(variant_sub);
ZEND_FUNCTION(variant_mul);
ZEND_FUNCTION(variant_and);
ZEND_FUNCTION(variant_div);
ZEND_FUNCTION(variant_eqv);
ZEND_FUNCTION(variant_idiv);
ZEND_FUNCTION(variant_imp);
ZEND_FUNCTION(variant_mod);
ZEND_FUNCTION(variant_or);
ZEND_FUNCTION(variant_pow);
ZEND_FUNCTION(variant_xor);
ZEND_FUNCTION(variant_abs);
ZEND_FUNCTION(variant_fix);
ZEND_FUNCTION(variant_int);
ZEND_FUNCTION(variant_neg);
ZEND_FUNCTION(variant_not);
ZEND_FUNCTION(variant_round);
ZEND_FUNCTION(variant_cmp);
ZEND_FUNCTION(variant_date_to_timestamp);
ZEND_FUNCTION(variant_date_from_timestamp);
ZEND_FUNCTION(variant_get_type);
ZEND_FUNCTION(variant_set_type);
ZEND_FUNCTION(variant_cast);
ZEND_FUNCTION(com_get_active_object);
ZEND_FUNCTION(com_create_guid);
ZEND_FUNCTION(com_event_sink);
ZEND_FUNCTION(com_print_typeinfo);
ZEND_FUNCTION(com_message_pump);
ZEND_FUNCTION(com_load_typelib);
ZEND_METHOD(variant, __construct);
ZEND_METHOD(com, __construct);
#if HAVE_MSCOREE_H
ZEND_METHOD(dotnet, __construct);
#endif
static const zend_function_entry ext_functions[] = {
ZEND_FE(variant_set, arginfo_variant_set)
ZEND_FE(variant_add, arginfo_variant_add)
ZEND_FE(variant_cat, arginfo_variant_cat)
ZEND_FE(variant_sub, arginfo_variant_sub)
ZEND_FE(variant_mul, arginfo_variant_mul)
ZEND_FE(variant_and, arginfo_variant_and)
ZEND_FE(variant_div, arginfo_variant_div)
ZEND_FE(variant_eqv, arginfo_variant_eqv)
ZEND_FE(variant_idiv, arginfo_variant_idiv)
ZEND_FE(variant_imp, arginfo_variant_imp)
ZEND_FE(variant_mod, arginfo_variant_mod)
ZEND_FE(variant_or, arginfo_variant_or)
ZEND_FE(variant_pow, arginfo_variant_pow)
ZEND_FE(variant_xor, arginfo_variant_xor)
ZEND_FE(variant_abs, arginfo_variant_abs)
ZEND_FE(variant_fix, arginfo_variant_fix)
ZEND_FE(variant_int, arginfo_variant_int)
ZEND_FE(variant_neg, arginfo_variant_neg)
ZEND_FE(variant_not, arginfo_variant_not)
ZEND_FE(variant_round, arginfo_variant_round)
ZEND_FE(variant_cmp, arginfo_variant_cmp)
ZEND_FE(variant_date_to_timestamp, arginfo_variant_date_to_timestamp)
ZEND_FE(variant_date_from_timestamp, arginfo_variant_date_from_timestamp)
ZEND_FE(variant_get_type, arginfo_variant_get_type)
ZEND_FE(variant_set_type, arginfo_variant_set_type)
ZEND_FE(variant_cast, arginfo_variant_cast)
ZEND_FE(com_get_active_object, arginfo_com_get_active_object)
ZEND_FE(com_create_guid, arginfo_com_create_guid)
ZEND_FE(com_event_sink, arginfo_com_event_sink)
ZEND_FE(com_print_typeinfo, arginfo_com_print_typeinfo)
ZEND_FE(com_message_pump, arginfo_com_message_pump)
ZEND_FE(com_load_typelib, arginfo_com_load_typelib)
ZEND_FE_END
};
static const zend_function_entry class_variant_methods[] = {
ZEND_ME(variant, __construct, arginfo_class_variant___construct, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_com_methods[] = {
ZEND_ME(com, __construct, arginfo_class_com___construct, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
#if HAVE_MSCOREE_H
static const zend_function_entry class_dotnet_methods[] = {
ZEND_ME(dotnet, __construct, arginfo_class_dotnet___construct, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
#endif
static const zend_function_entry class_com_safearray_proxy_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_com_exception_methods[] = {
ZEND_FE_END
};
static void register_com_extension_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("CLSCTX_INPROC_SERVER", CLSCTX_INPROC_SERVER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CLSCTX_INPROC_HANDLER", CLSCTX_INPROC_HANDLER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CLSCTX_LOCAL_SERVER", CLSCTX_LOCAL_SERVER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CLSCTX_REMOTE_SERVER", CLSCTX_REMOTE_SERVER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CLSCTX_SERVER", CLSCTX_SERVER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CLSCTX_ALL", CLSCTX_ALL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_NULL", VT_NULL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_EMPTY", VT_EMPTY, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_UI1", VT_UI1, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_I1", VT_I1, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_UI2", VT_UI2, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_I2", VT_I2, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_UI4", VT_UI4, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_I4", VT_I4, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_R4", VT_R4, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_R8", VT_R8, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_BOOL", VT_BOOL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_ERROR", VT_ERROR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_CY", VT_CY, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_DATE", VT_DATE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_BSTR", VT_BSTR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_DECIMAL", VT_DECIMAL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_UNKNOWN", VT_UNKNOWN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_DISPATCH", VT_DISPATCH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_VARIANT", VT_VARIANT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_INT", VT_INT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_UINT", VT_UINT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_ARRAY", VT_ARRAY, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VT_BYREF", VT_BYREF, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_ACP", CP_ACP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_MACCP", CP_MACCP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_OEMCP", CP_OEMCP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_UTF7", CP_UTF7, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_UTF8", CP_UTF8, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_SYMBOL", CP_SYMBOL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CP_THREAD_ACP", CP_THREAD_ACP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VARCMP_LT", VARCMP_LT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VARCMP_EQ", VARCMP_EQ, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VARCMP_GT", VARCMP_GT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("VARCMP_NULL", VARCMP_NULL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("LOCALE_SYSTEM_DEFAULT", LOCALE_SYSTEM_DEFAULT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("LOCALE_NEUTRAL", LOCALE_NEUTRAL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("NORM_IGNORECASE", NORM_IGNORECASE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("NORM_IGNORENONSPACE", NORM_IGNORENONSPACE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("NORM_IGNORESYMBOLS", NORM_IGNORESYMBOLS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("NORM_IGNOREWIDTH", NORM_IGNOREWIDTH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("NORM_IGNOREKANATYPE", NORM_IGNOREKANATYPE, CONST_PERSISTENT);
#if defined(NORM_IGNOREKASHIDA)
REGISTER_LONG_CONSTANT("NORM_IGNOREKASHIDA", NORM_IGNOREKASHIDA, CONST_PERSISTENT);
#endif
REGISTER_LONG_CONSTANT("DISP_E_DIVBYZERO", PHP_DISP_E_DIVBYZERO, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DISP_E_OVERFLOW", PHP_DISP_E_OVERFLOW, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DISP_E_BADINDEX", PHP_DISP_E_BADINDEX, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DISP_E_PARAMNOTFOUND", PHP_DISP_E_PARAMNOTFOUND, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("MK_E_UNAVAILABLE", PHP_MK_E_UNAVAILABLE, CONST_PERSISTENT);
#if SIZEOF_ZEND_LONG == 8
REGISTER_LONG_CONSTANT("VT_UI8", VT_UI8, CONST_PERSISTENT);
#endif
#if SIZEOF_ZEND_LONG == 8
REGISTER_LONG_CONSTANT("VT_I8", VT_I8, CONST_PERSISTENT);
#endif
}
static zend_class_entry *register_class_variant(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "variant", class_variant_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
static zend_class_entry *register_class_com(zend_class_entry *class_entry_variant)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "com", class_com_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_variant);
return class_entry;
}
#if HAVE_MSCOREE_H
static zend_class_entry *register_class_dotnet(zend_class_entry *class_entry_variant)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "dotnet", class_dotnet_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_variant);
return class_entry;
}
#endif
static zend_class_entry *register_class_com_safearray_proxy(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "com_safearray_proxy", class_com_safearray_proxy_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
return class_entry;
}
static zend_class_entry *register_class_com_exception(zend_class_entry *class_entry_Exception)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "com_exception", class_com_exception_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_Exception);
class_entry->ce_flags |= ZEND_ACC_FINAL;
return class_entry;
}
| 14,102 | 38.284123 | 98 |
h
|
php-src
|
php-src-master/ext/com_dotnet/com_iterator.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_com_dotnet.h"
#include "php_com_dotnet_internal.h"
#include "Zend/zend_exceptions.h"
struct php_com_iterator {
zend_object_iterator iter;
IEnumVARIANT *ev;
zend_ulong key;
VARIANT v; /* cached element */
int code_page;
VARIANT safe_array;
VARTYPE sa_type;
LONG sa_max;
zval zdata;
};
static void com_iter_dtor(zend_object_iterator *iter)
{
struct php_com_iterator *I = (struct php_com_iterator*)Z_PTR(iter->data);
if (I->ev) {
IEnumVARIANT_Release(I->ev);
}
VariantClear(&I->v);
VariantClear(&I->safe_array);
zval_ptr_dtor(&I->zdata);
}
static int com_iter_valid(zend_object_iterator *iter)
{
struct php_com_iterator *I = (struct php_com_iterator*)Z_PTR(iter->data);
if (Z_TYPE(I->zdata) != IS_UNDEF) {
return SUCCESS;
}
return FAILURE;
}
static zval* com_iter_get_data(zend_object_iterator *iter)
{
struct php_com_iterator *I = (struct php_com_iterator*)Z_PTR(iter->data);
return &I->zdata;
}
static void com_iter_get_key(zend_object_iterator *iter, zval *key)
{
struct php_com_iterator *I = (struct php_com_iterator*)Z_PTR(iter->data);
if (I->key == (zend_ulong)-1) {
ZVAL_NULL(key);
} else {
ZVAL_LONG(key, I->key);
}
}
static void com_iter_move_forwards(zend_object_iterator *iter)
{
struct php_com_iterator *I = (struct php_com_iterator*)Z_PTR(iter->data);
unsigned long n_fetched;
zval ptr;
/* release current cached element */
VariantClear(&I->v);
if (Z_TYPE(I->zdata) != IS_UNDEF) {
zval_ptr_dtor(&I->zdata);
ZVAL_UNDEF(&I->zdata);
}
if (I->ev) {
/* Get the next element */
if (SUCCEEDED(IEnumVARIANT_Next(I->ev, 1, &I->v, &n_fetched)) && n_fetched > 0) {
I->key++;
} else {
/* indicate that there are no more items */
I->key = (zend_ulong)-1;
return;
}
} else {
/* safe array */
if (I->key >= (ULONG) I->sa_max) {
I->key = (zend_ulong)-1;
return;
}
I->key++;
if (!php_com_safearray_get_elem(&I->safe_array, &I->v, (LONG)I->key)) {
I->key = (zend_ulong)-1;
return;
}
}
ZVAL_NULL(&ptr);
php_com_zval_from_variant(&ptr, &I->v, I->code_page);
/* php_com_wrap_variant(ptr, &I->v, I->code_page); */
ZVAL_COPY_VALUE(&I->zdata, &ptr);
}
static const zend_object_iterator_funcs com_iter_funcs = {
com_iter_dtor,
com_iter_valid,
com_iter_get_data,
com_iter_get_key,
com_iter_move_forwards,
NULL,
NULL, /* get_gc */
};
zend_object_iterator *php_com_iter_get(zend_class_entry *ce, zval *object, int by_ref)
{
php_com_dotnet_object *obj;
struct php_com_iterator *I;
IEnumVARIANT *iev = NULL;
DISPPARAMS dp;
VARIANT v;
unsigned long n_fetched;
zval ptr;
if (by_ref) {
zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
return NULL;
}
obj = CDNO_FETCH(object);
if (V_VT(&obj->v) != VT_DISPATCH && !V_ISARRAY(&obj->v)) {
/* TODO Promote to TypeError? */
php_error_docref(NULL, E_WARNING, "Variant is not an object or array VT=%d", V_VT(&obj->v));
return NULL;
}
memset(&dp, 0, sizeof(dp));
VariantInit(&v);
I = (struct php_com_iterator*)ecalloc(1, sizeof(*I));
zend_iterator_init(&I->iter);
I->iter.funcs = &com_iter_funcs;
Z_PTR(I->iter.data) = I;
I->code_page = obj->code_page;
ZVAL_UNDEF(&I->zdata);
VariantInit(&I->safe_array);
VariantInit(&I->v);
if (V_ISARRAY(&obj->v)) {
LONG bound;
UINT dims;
dims = SafeArrayGetDim(V_ARRAY(&obj->v));
if (dims != 1) {
/* TODO Promote to ValueError? */
php_error_docref(NULL, E_WARNING,
"Can only handle single dimension variant arrays (this array has %d)", dims);
goto fail;
}
/* same semantics as foreach on a PHP array;
* make a copy and enumerate that copy */
VariantCopy(&I->safe_array, &obj->v);
/* determine the key value for the array */
SafeArrayGetLBound(V_ARRAY(&I->safe_array), 1, &bound);
SafeArrayGetUBound(V_ARRAY(&I->safe_array), 1, &I->sa_max);
/* pre-fetch the element */
if (I->sa_max >= bound && php_com_safearray_get_elem(&I->safe_array, &I->v, bound)) {
I->key = bound;
ZVAL_NULL(&ptr);
php_com_zval_from_variant(&ptr, &I->v, I->code_page);
ZVAL_COPY_VALUE(&I->zdata, &ptr);
} else {
I->key = (zend_ulong)-1;
}
} else {
/* can we enumerate it? */
if (FAILED(IDispatch_Invoke(V_DISPATCH(&obj->v), DISPID_NEWENUM,
&IID_NULL, LOCALE_NEUTRAL, DISPATCH_METHOD|DISPATCH_PROPERTYGET,
&dp, &v, NULL, NULL))) {
goto fail;
}
/* get something useful out of it */
if (V_VT(&v) == VT_UNKNOWN) {
IUnknown_QueryInterface(V_UNKNOWN(&v), &IID_IEnumVARIANT, (void**)&iev);
} else if (V_VT(&v) == VT_DISPATCH) {
IDispatch_QueryInterface(V_DISPATCH(&v), &IID_IEnumVARIANT, (void**)&iev);
}
VariantClear(&v);
if (iev == NULL) {
goto fail;
}
I->ev = iev;
/* Get the first element now */
if (SUCCEEDED(IEnumVARIANT_Next(I->ev, 1, &I->v, &n_fetched)) && n_fetched > 0) {
/* indicate that we have element 0 */
I->key = 0;
ZVAL_NULL(&ptr);
php_com_zval_from_variant(&ptr, &I->v, I->code_page);
ZVAL_COPY_VALUE(&I->zdata, &ptr);
} else {
/* indicate that there are no more items */
I->key = (zend_ulong)-1;
}
}
return &I->iter;
fail:
if (I) {
VariantClear(&I->safe_array);
VariantClear(&I->v);
efree(I);
}
return NULL;
}
| 6,328 | 24.727642 | 94 |
c
|
php-src
|
php-src-master/ext/com_dotnet/com_misc.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_com_dotnet.h"
#include "php_com_dotnet_internal.h"
#include "Zend/zend_exceptions.h"
void php_com_throw_exception(HRESULT code, char *message)
{
int free_msg = 0;
if (message == NULL) {
message = php_win32_error_to_msg(code);
free_msg = 1;
}
#if SIZEOF_ZEND_LONG == 8
zend_throw_exception(php_com_exception_class_entry, message, (zend_long)(uint32_t)code);
#else
zend_throw_exception(php_com_exception_class_entry, message, (zend_long)code);
#endif
if (free_msg) {
php_win32_error_msg_free(message);
}
}
PHP_COM_DOTNET_API void php_com_wrap_dispatch(zval *z, IDispatch *disp,
int codepage)
{
php_com_dotnet_object *obj;
obj = emalloc(sizeof(*obj));
memset(obj, 0, sizeof(*obj));
obj->code_page = codepage;
obj->ce = php_com_variant_class_entry;
obj->zo.ce = php_com_variant_class_entry;
VariantInit(&obj->v);
V_VT(&obj->v) = VT_DISPATCH;
V_DISPATCH(&obj->v) = disp;
IDispatch_AddRef(V_DISPATCH(&obj->v));
IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &obj->typeinfo);
zend_object_std_init(&obj->zo, php_com_variant_class_entry);
ZVAL_OBJ(z, &obj->zo);
}
PHP_COM_DOTNET_API void php_com_wrap_variant(zval *z, VARIANT *v,
int codepage)
{
php_com_dotnet_object *obj;
obj = emalloc(sizeof(*obj));
memset(obj, 0, sizeof(*obj));
obj->code_page = codepage;
obj->ce = php_com_variant_class_entry;
obj->zo.ce = php_com_variant_class_entry;
VariantInit(&obj->v);
VariantCopyInd(&obj->v, v);
obj->modified = 0;
if ((V_VT(&obj->v) == VT_DISPATCH) && (V_DISPATCH(&obj->v) != NULL)) {
IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &obj->typeinfo);
}
zend_object_std_init(&obj->zo, php_com_variant_class_entry);
ZVAL_OBJ(z, &obj->zo);
}
/* this is a convenience function for fetching a particular
* element from a (possibly multi-dimensional) safe array */
PHP_COM_DOTNET_API bool php_com_safearray_get_elem(VARIANT *array, VARIANT *dest, LONG dim1)
{
UINT dims;
LONG lbound, ubound;
LONG indices[1];
VARTYPE vt;
if (!V_ISARRAY(array)) {
return 0;
}
dims = SafeArrayGetDim(V_ARRAY(array));
if (dims != 1) {
/* TODO Promote to ValueError? */
php_error_docref(NULL, E_WARNING,
"Can only handle single dimension variant arrays (this array has %d)", dims);
return 0;
}
if (FAILED(SafeArrayGetVartype(V_ARRAY(array), &vt)) || vt == VT_EMPTY) {
vt = V_VT(array) & ~VT_ARRAY;
}
/* determine the bounds */
SafeArrayGetLBound(V_ARRAY(array), 1, &lbound);
SafeArrayGetUBound(V_ARRAY(array), 1, &ubound);
/* check bounds */
if (dim1 < lbound || dim1 > ubound) {
php_com_throw_exception(DISP_E_BADINDEX, "index out of bounds");
return 0;
}
/* now fetch that element */
VariantInit(dest);
indices[0] = dim1;
if (vt == VT_VARIANT) {
SafeArrayGetElement(V_ARRAY(array), indices, dest);
} else {
V_VT(dest) = vt;
/* store the value into "lVal" member of the variant.
* This works because it is a union; since we know the variant
* type, we end up with a working variant */
SafeArrayGetElement(V_ARRAY(array), indices, &dest->lVal);
}
return 1;
}
| 4,197 | 28.356643 | 92 |
c
|
php-src
|
php-src-master/ext/com_dotnet/com_olechar.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]> |
| Harald Radi <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_com_dotnet.h"
#include "php_com_dotnet_internal.h"
PHP_COM_DOTNET_API OLECHAR *php_com_string_to_olestring(const char *string, size_t string_len, int codepage)
{
OLECHAR *olestring = NULL;
DWORD flags = codepage == CP_UTF8 ? 0 : MB_PRECOMPOSED | MB_ERR_INVALID_CHARS;
BOOL ok;
if (string_len == -1) {
/* determine required length for the buffer (includes NUL terminator) */
string_len = MultiByteToWideChar(codepage, flags, string, -1, NULL, 0);
} else {
/* allow room for NUL terminator */
string_len++;
}
if (string_len > 0) {
olestring = (OLECHAR*)safe_emalloc(string_len, sizeof(OLECHAR), 0);
/* XXX if that's a real multibyte string, olestring is obviously allocated excessively.
This should be fixed by reallocating the olestring, but as emalloc is used, that doesn't
matter much. */
ok = MultiByteToWideChar(codepage, flags, string, (int)string_len, olestring, (int)string_len);
if (ok > 0 && (size_t)ok < string_len) {
olestring[ok] = '\0';
}
} else {
ok = FALSE;
olestring = (OLECHAR*)emalloc(sizeof(OLECHAR));
*olestring = 0;
}
if (!ok) {
char *msg = php_win32_error_to_msg(GetLastError());
php_error_docref(NULL, E_WARNING,
"Could not convert string to unicode: `%s'", msg);
php_win32_error_msg_free(msg);
}
return olestring;
}
PHP_COM_DOTNET_API zend_string *php_com_olestring_to_string(OLECHAR *olestring, int codepage)
{
zend_string *string;
uint32_t length = 0;
length = WideCharToMultiByte(codepage, 0, olestring, -1, NULL, 0, NULL, NULL);
if (length) {
/* We remove 1 from the length as it takes into account the terminating null byte
* which zend_string alloc already takes into consideration */
/* TODO Should use safe alloc? */
string = zend_string_alloc(length - 1, /* persistent */ false);
length = WideCharToMultiByte(codepage, 0, olestring, -1, ZSTR_VAL(string), length, NULL, NULL);
} else {
string = ZSTR_EMPTY_ALLOC();
}
/* Failure to determine length of WideChar */
if (length == 0) {
char *msg = php_win32_error_to_msg(GetLastError());
php_error_docref(NULL, E_WARNING,
"Could not convert string from unicode: `%s'", msg);
php_win32_error_msg_free(msg);
}
return string;
}
BSTR php_com_string_to_bstr(zend_string *string, int codepage)
{
BSTR bstr = NULL;
DWORD flags = codepage == CP_UTF8 ? 0 : MB_PRECOMPOSED | MB_ERR_INVALID_CHARS;
size_t mb_len = ZSTR_LEN(string);
int wc_len;
if ((wc_len = MultiByteToWideChar(codepage, flags, ZSTR_VAL(string), (int)mb_len + 1, NULL, 0)) <= 0) {
goto fail;
}
if ((bstr = SysAllocStringLen(NULL, (UINT)(wc_len - 1))) == NULL) {
goto fail;
}
if ((wc_len = MultiByteToWideChar(codepage, flags, ZSTR_VAL(string), (int)mb_len + 1, bstr, wc_len)) <= 0) {
goto fail;
}
return bstr;
fail:
char *msg = php_win32_error_to_msg(GetLastError());
php_error_docref(NULL, E_WARNING,
"Could not convert string to unicode: `%s'", msg);
LocalFree(msg);
SysFreeString(bstr);
return SysAllocString(L"");
}
zend_string *php_com_bstr_to_string(BSTR bstr, int codepage)
{
zend_string *string = NULL;
UINT wc_len = SysStringLen(bstr);
int mb_len;
mb_len = WideCharToMultiByte(codepage, 0, bstr, wc_len + 1, NULL, 0, NULL, NULL);
if (mb_len > 0) {
string = zend_string_alloc(mb_len - 1, 0);
mb_len = WideCharToMultiByte(codepage, 0, bstr, wc_len + 1, ZSTR_VAL(string), mb_len, NULL, NULL);
}
if (mb_len <= 0) {
char *msg = php_win32_error_to_msg(GetLastError());
php_error_docref(NULL, E_WARNING,
"Could not convert string from unicode: `%s'", msg);
LocalFree(msg);
if (string != NULL) {
zend_string_release(string);
}
string = ZSTR_EMPTY_ALLOC();
}
return string;
}
| 4,876 | 30.668831 | 109 |
c
|
php-src
|
php-src-master/ext/com_dotnet/com_persist_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: d14d30fb232f08da37ba0df0b9186eb8bac5e1a4 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_COMPersistHelper___construct, 0, 0, 0)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, variant, variant, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_COMPersistHelper_GetCurFileName, 0, 0, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_COMPersistHelper_SaveToFile, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 1)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, remember, _IS_BOOL, 0, "true")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_COMPersistHelper_LoadFromFile, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 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_class_COMPersistHelper_GetMaxStreamSize, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_COMPersistHelper_InitNew, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_COMPersistHelper_LoadFromStream, 0, 1, _IS_BOOL, 0)
ZEND_ARG_INFO(0, stream)
ZEND_END_ARG_INFO()
#define arginfo_class_COMPersistHelper_SaveToStream arginfo_class_COMPersistHelper_LoadFromStream
ZEND_METHOD(COMPersistHelper, __construct);
ZEND_METHOD(COMPersistHelper, GetCurFileName);
ZEND_METHOD(COMPersistHelper, SaveToFile);
ZEND_METHOD(COMPersistHelper, LoadFromFile);
ZEND_METHOD(COMPersistHelper, GetMaxStreamSize);
ZEND_METHOD(COMPersistHelper, InitNew);
ZEND_METHOD(COMPersistHelper, LoadFromStream);
ZEND_METHOD(COMPersistHelper, SaveToStream);
static const zend_function_entry class_COMPersistHelper_methods[] = {
ZEND_ME(COMPersistHelper, __construct, arginfo_class_COMPersistHelper___construct, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, GetCurFileName, arginfo_class_COMPersistHelper_GetCurFileName, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, SaveToFile, arginfo_class_COMPersistHelper_SaveToFile, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, LoadFromFile, arginfo_class_COMPersistHelper_LoadFromFile, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, GetMaxStreamSize, arginfo_class_COMPersistHelper_GetMaxStreamSize, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, InitNew, arginfo_class_COMPersistHelper_InitNew, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, LoadFromStream, arginfo_class_COMPersistHelper_LoadFromStream, ZEND_ACC_PUBLIC)
ZEND_ME(COMPersistHelper, SaveToStream, arginfo_class_COMPersistHelper_SaveToStream, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static zend_class_entry *register_class_COMPersistHelper(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "COMPersistHelper", class_COMPersistHelper_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
return class_entry;
}
| 2,987 | 44.272727 | 120 |
h
|
php-src
|
php-src-master/ext/com_dotnet/com_saproxy.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]> |
+----------------------------------------------------------------------+
*/
/* This module implements a SafeArray proxy which is used internally
* by the engine when resolving multi-dimensional array accesses on
* SafeArray types.
* In addition, the proxy is now able to handle properties of COM objects
* that smell like PHP arrays.
* */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_com_dotnet.h"
#include "php_com_dotnet_internal.h"
#include "Zend/zend_exceptions.h"
typedef struct {
zend_object std;
/* the object we a proxying for; we hold a refcount to it */
php_com_dotnet_object *obj;
/* how many dimensions we are indirecting to get into this element */
LONG dimensions;
/* this is an array whose size_is(dimensions) */
zval *indices;
} php_com_saproxy;
typedef struct {
zend_object_iterator iter;
zval proxy_obj;
zval data;
php_com_saproxy *proxy;
LONG key;
LONG imin, imax;
LONG *indices;
} php_com_saproxy_iter;
#define SA_FETCH(zv) (php_com_saproxy*)Z_OBJ_P(zv)
static inline void clone_indices(php_com_saproxy *dest, php_com_saproxy *src, int ndims)
{
int i;
for (i = 0; i < ndims; i++) {
ZVAL_DUP(&dest->indices[i], &src->indices[i]);
}
}
static zval *saproxy_property_read(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv)
{
ZVAL_NULL(rv);
php_com_throw_exception(E_INVALIDARG, "safearray has no properties");
return rv;
}
static zval *saproxy_property_write(zend_object *object, zend_string *member, zval *value, void **cache_slot)
{
php_com_throw_exception(E_INVALIDARG, "safearray has no properties");
return value;
}
static zval *saproxy_read_dimension(zend_object *object, zval *offset, int type, zval *rv)
{
php_com_saproxy *proxy = (php_com_saproxy*) object;
UINT dims, i;
SAFEARRAY *sa;
LONG ubound, lbound;
HRESULT res;
ZVAL_NULL(rv);
if (V_VT(&proxy->obj->v) == VT_DISPATCH) {
VARIANT v;
zval *args;
/* prop-get using first dimension as the property name,
* all subsequent dimensions and the offset as parameters */
args = safe_emalloc(proxy->dimensions + 1, sizeof(zval), 0);
for (i = 1; i < (UINT) proxy->dimensions; i++) {
args[i-1] = proxy->indices[i];
}
ZVAL_COPY_VALUE(&args[i-1], offset);
if (!try_convert_to_string(&proxy->indices[0])) {
efree(args);
return rv;
}
VariantInit(&v);
res = php_com_do_invoke(proxy->obj, Z_STR(proxy->indices[0]),
DISPATCH_METHOD|DISPATCH_PROPERTYGET, &v,
proxy->dimensions, args, 0);
efree(args);
if (res == SUCCESS) {
php_com_zval_from_variant(rv, &v, proxy->obj->code_page);
VariantClear(&v);
} else if (res == DISP_E_BADPARAMCOUNT) {
/* return another proxy */
php_com_saproxy_create(object, rv, offset);
}
return rv;
} else if (!V_ISARRAY(&proxy->obj->v)) {
php_com_throw_exception(E_INVALIDARG, "invalid read from com proxy object");
return rv;
}
/* the SafeArray case */
/* offset/index must be an integer */
convert_to_long(offset);
sa = V_ARRAY(&proxy->obj->v);
dims = SafeArrayGetDim(sa);
if ((UINT) proxy->dimensions >= dims) {
/* too many dimensions */
php_com_throw_exception(E_INVALIDARG, "too many dimensions!");
return rv;
}
/* bounds check */
SafeArrayGetLBound(sa, proxy->dimensions, &lbound);
SafeArrayGetUBound(sa, proxy->dimensions, &ubound);
if (Z_LVAL_P(offset) < lbound || Z_LVAL_P(offset) > ubound) {
php_com_throw_exception(DISP_E_BADINDEX, "index out of bounds");
return rv;
}
if (dims - 1 == proxy->dimensions) {
LONG *indices;
VARTYPE vt;
VARIANT v;
VariantInit(&v);
/* we can return a real value */
indices = safe_emalloc(dims, sizeof(LONG), 0);
/* copy indices from proxy */
for (i = 0; i < dims; i++) {
convert_to_long(&proxy->indices[i]);
indices[i] = (LONG)Z_LVAL(proxy->indices[i]);
}
/* add user-supplied index */
indices[dims-1] = (LONG)Z_LVAL_P(offset);
/* now fetch the value */
if (FAILED(SafeArrayGetVartype(sa, &vt)) || vt == VT_EMPTY) {
vt = V_VT(&proxy->obj->v) & ~VT_ARRAY;
}
if (vt == VT_VARIANT) {
res = SafeArrayGetElement(sa, indices, &v);
} else {
V_VT(&v) = vt;
res = SafeArrayGetElement(sa, indices, &v.lVal);
}
efree(indices);
if (SUCCEEDED(res)) {
php_com_wrap_variant(rv, &v, proxy->obj->code_page);
} else {
php_com_throw_exception(res, NULL);
}
VariantClear(&v);
} else {
/* return another proxy */
php_com_saproxy_create(object, rv, offset);
}
return rv;
}
static void saproxy_write_dimension(zend_object *object, zval *offset, zval *value)
{
php_com_saproxy *proxy = (php_com_saproxy*) object;
UINT dims, i;
HRESULT res;
VARIANT v;
if (V_VT(&proxy->obj->v) == VT_DISPATCH) {
/* We do a prop-set using the first dimension as the property name,
* all subsequent dimensions and offset as parameters, with value as
* the final value */
zval *args = safe_emalloc(proxy->dimensions + 2, sizeof(zval), 0);
for (i = 1; i < (UINT) proxy->dimensions; i++) {
ZVAL_COPY_VALUE(&args[i-1], &proxy->indices[i]);
}
ZVAL_COPY_VALUE(&args[i-1], offset);
ZVAL_COPY_VALUE(&args[i], value);
if (!try_convert_to_string(&proxy->indices[0])) {
efree(args);
return;
}
VariantInit(&v);
if (SUCCESS == php_com_do_invoke(proxy->obj, Z_STR(proxy->indices[0]),
DISPATCH_PROPERTYPUT, &v, proxy->dimensions + 1,
args, 0)) {
VariantClear(&v);
}
efree(args);
} else if (V_ISARRAY(&proxy->obj->v)) {
LONG *indices;
VARTYPE vt;
dims = SafeArrayGetDim(V_ARRAY(&proxy->obj->v));
indices = safe_emalloc(dims, sizeof(LONG), 0);
/* copy indices from proxy */
for (i = 0; i < dims; i++) {
convert_to_long(&proxy->indices[i]);
indices[i] = (LONG)Z_LVAL(proxy->indices[i]);
}
/* add user-supplied index */
convert_to_long(offset);
indices[dims-1] = (LONG)Z_LVAL_P(offset);
if (FAILED(SafeArrayGetVartype(V_ARRAY(&proxy->obj->v), &vt)) || vt == VT_EMPTY) {
vt = V_VT(&proxy->obj->v) & ~VT_ARRAY;
}
VariantInit(&v);
php_com_variant_from_zval(&v, value, proxy->obj->code_page);
if (V_VT(&v) != vt) {
VariantChangeType(&v, &v, 0, vt);
}
if (vt == VT_VARIANT) {
res = SafeArrayPutElement(V_ARRAY(&proxy->obj->v), indices, &v);
} else {
res = SafeArrayPutElement(V_ARRAY(&proxy->obj->v), indices, &v.lVal);
}
efree(indices);
VariantClear(&v);
if (FAILED(res)) {
php_com_throw_exception(res, NULL);
}
} else {
php_com_throw_exception(E_NOTIMPL, "invalid write to com proxy object");
}
}
static int saproxy_property_exists(zend_object *object, zend_string *member, int check_empty, void **cache_slot)
{
/* no properties */
return 0;
}
static int saproxy_dimension_exists(zend_object *object, zval *member, int check_empty)
{
/* TODO Add support */
zend_throw_error(NULL, "Cannot check dimension on a COM object");
return 0;
}
static void saproxy_property_delete(zend_object *object, zend_string *member, void **cache_slot)
{
zend_throw_error(NULL, "Cannot delete properties from a COM object");
}
static void saproxy_dimension_delete(zend_object *object, zval *offset)
{
zend_throw_error(NULL, "Cannot delete dimension from a COM object");
}
static HashTable *saproxy_properties_get(zend_object *object)
{
/* no properties */
return NULL;
}
static zend_function *saproxy_method_get(zend_object **object, zend_string *name, const zval *key)
{
/* no methods */
return NULL;
}
static zend_function *saproxy_constructor_get(zend_object *object)
{
/* user cannot instantiate */
return NULL;
}
static zend_string* saproxy_class_name_get(const zend_object *object)
{
return zend_string_copy(php_com_saproxy_class_entry->name);
}
static int saproxy_objects_compare(zval *object1, zval *object2)
{
ZEND_COMPARE_OBJECTS_FALLBACK(object1, object2);
return -1;
}
static zend_result saproxy_object_cast(zend_object *readobj, zval *writeobj, int type)
{
return FAILURE;
}
static zend_result saproxy_count_elements(zend_object *object, zend_long *count)
{
php_com_saproxy *proxy = (php_com_saproxy*) object;
LONG ubound, lbound;
if (!V_ISARRAY(&proxy->obj->v)) {
return FAILURE;
}
SafeArrayGetLBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &lbound);
SafeArrayGetUBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &ubound);
*count = ubound - lbound + 1;
return SUCCESS;
}
static void saproxy_free_storage(zend_object *object)
{
php_com_saproxy *proxy = (php_com_saproxy *)object;
//??? int i;
//???
//??? for (i = 0; i < proxy->dimensions; i++) {
//??? if (proxy->indices) {
//??? FREE_ZVAL(proxy->indices[i]);
//??? }
//??? }
OBJ_RELEASE(&proxy->obj->zo);
zend_object_std_dtor(object);
efree(proxy->indices);
}
static zend_object* saproxy_clone(zend_object *object)
{
php_com_saproxy *proxy = (php_com_saproxy *) object;
php_com_saproxy *cloneproxy;
cloneproxy = emalloc(sizeof(*cloneproxy));
memcpy(cloneproxy, proxy, sizeof(*cloneproxy));
GC_ADDREF(&cloneproxy->obj->zo);
cloneproxy->indices = safe_emalloc(cloneproxy->dimensions, sizeof(zval), 0);
clone_indices(cloneproxy, proxy, proxy->dimensions);
return &cloneproxy->std;
}
zend_object_handlers php_com_saproxy_handlers = {
0,
saproxy_free_storage,
zend_objects_destroy_object,
saproxy_clone,
saproxy_property_read,
saproxy_property_write,
saproxy_read_dimension,
saproxy_write_dimension,
NULL,
saproxy_property_exists,
saproxy_property_delete,
saproxy_dimension_exists,
saproxy_dimension_delete,
saproxy_properties_get,
saproxy_method_get,
saproxy_constructor_get,
saproxy_class_name_get,
saproxy_object_cast,
saproxy_count_elements,
NULL, /* get_debug_info */
NULL, /* get_closure */
NULL, /* get_gc */
NULL, /* do_operation */
saproxy_objects_compare, /* compare */
NULL, /* get_properties_for */
};
void php_com_saproxy_create(zend_object *com_object, zval *proxy_out, zval *index)
{
php_com_saproxy *proxy, *rel = NULL;
proxy = ecalloc(1, sizeof(*proxy));
proxy->dimensions = 1;
if (com_object->ce == php_com_saproxy_class_entry) {
rel = (php_com_saproxy*) com_object;
proxy->obj = rel->obj;
proxy->dimensions += rel->dimensions;
} else {
proxy->obj = (php_com_dotnet_object*) com_object;
}
GC_ADDREF(&proxy->obj->zo);
proxy->indices = safe_emalloc(proxy->dimensions, sizeof(zval), 0);
if (rel) {
clone_indices(proxy, rel, rel->dimensions);
}
ZVAL_DUP(&proxy->indices[proxy->dimensions-1], index);
zend_object_std_init(&proxy->std, php_com_saproxy_class_entry);
ZVAL_OBJ(proxy_out, &proxy->std);
}
/* iterator */
static void saproxy_iter_dtor(zend_object_iterator *iter)
{
php_com_saproxy_iter *I = (php_com_saproxy_iter*)Z_PTR(iter->data);
zval_ptr_dtor(&I->proxy_obj);
efree(I->indices);
efree(I);
}
static int saproxy_iter_valid(zend_object_iterator *iter)
{
php_com_saproxy_iter *I = (php_com_saproxy_iter*)Z_PTR(iter->data);
return (I->key < I->imax) ? SUCCESS : FAILURE;
}
static zval* saproxy_iter_get_data(zend_object_iterator *iter)
{
php_com_saproxy_iter *I = (php_com_saproxy_iter*)Z_PTR(iter->data);
VARIANT v;
VARTYPE vt;
SAFEARRAY *sa;
I->indices[I->proxy->dimensions-1] = I->key;
sa = V_ARRAY(&I->proxy->obj->v);
if (FAILED(SafeArrayGetVartype(sa, &vt)) || vt == VT_EMPTY) {
vt = V_VT(&I->proxy->obj->v) & ~VT_ARRAY;
}
VariantInit(&v);
if (vt == VT_VARIANT) {
SafeArrayGetElement(sa, I->indices, &v);
} else {
V_VT(&v) = vt;
SafeArrayGetElement(sa, I->indices, &v.lVal);
}
ZVAL_NULL(&I->data);
php_com_wrap_variant(&I->data, &v, I->proxy->obj->code_page);
VariantClear(&v);
return &I->data;
}
static void saproxy_iter_get_key(zend_object_iterator *iter, zval *key)
{
php_com_saproxy_iter *I = (php_com_saproxy_iter*)Z_PTR(iter->data);
if (I->key == -1) {
ZVAL_NULL(key);
} else {
ZVAL_LONG(key, I->key);
}
}
static void saproxy_iter_move_forwards(zend_object_iterator *iter)
{
php_com_saproxy_iter *I = (php_com_saproxy_iter*)Z_PTR(iter->data);
if (++I->key >= I->imax) {
I->key = -1;
}
}
static const zend_object_iterator_funcs saproxy_iter_funcs = {
saproxy_iter_dtor,
saproxy_iter_valid,
saproxy_iter_get_data,
saproxy_iter_get_key,
saproxy_iter_move_forwards,
NULL,
NULL, /* get_gc */
};
zend_object_iterator *php_com_saproxy_iter_get(zend_class_entry *ce, zval *object, int by_ref)
{
php_com_saproxy *proxy = SA_FETCH(object);
php_com_saproxy_iter *I;
int i;
if (by_ref) {
zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
return NULL;
}
I = ecalloc(1, sizeof(*I));
I->iter.funcs = &saproxy_iter_funcs;
Z_PTR(I->iter.data) = I;
I->proxy = proxy;
Z_ADDREF_P(object);
ZVAL_OBJ(&I->proxy_obj, Z_OBJ_P(object));
I->indices = safe_emalloc(proxy->dimensions + 1, sizeof(LONG), 0);
for (i = 0; i < proxy->dimensions; i++) {
convert_to_long(&proxy->indices[i]);
I->indices[i] = (LONG)Z_LVAL(proxy->indices[i]);
}
SafeArrayGetLBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &I->imin);
SafeArrayGetUBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &I->imax);
I->key = I->imin;
return &I->iter;
}
| 14,062 | 24.202509 | 115 |
c
|
php-src
|
php-src-master/ext/com_dotnet/com_typeinfo.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]> |
| Harald Radi <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_com_dotnet.h"
#include "php_com_dotnet_internal.h"
static HashTable php_com_typelibraries;
#ifdef ZTS
static MUTEX_T php_com_typelibraries_mutex;
#endif
PHP_MINIT_FUNCTION(com_typeinfo)
{
zend_hash_init(&php_com_typelibraries, 0, NULL, php_com_typelibrary_dtor, 1);
#ifdef ZTS
php_com_typelibraries_mutex = tsrm_mutex_alloc();
#endif
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(com_typeinfo)
{
zend_hash_destroy(&php_com_typelibraries);
#ifdef ZTS
tsrm_mutex_free(php_com_typelibraries_mutex);
#endif
return SUCCESS;
}
/* The search string can be either:
* a) a file name
* b) a CLSID, major, minor e.g. "{00000200-0000-0010-8000-00AA006D2EA4},2,0"
* c) a Type Library name e.g. "Microsoft OLE DB ActiveX Data Objects 1.0 Library"
*/
PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib(char *search_string, int codepage)
{
ITypeLib *TL = NULL;
char *strtok_buf, *major, *minor;
CLSID clsid;
OLECHAR *p;
HRESULT hr;
search_string = php_strtok_r(search_string, ",", &strtok_buf);
if (search_string == NULL) {
return NULL;
}
major = php_strtok_r(NULL, ",", &strtok_buf);
minor = php_strtok_r(NULL, ",", &strtok_buf);
p = php_com_string_to_olestring(search_string, strlen(search_string), codepage);
if (SUCCEEDED(CLSIDFromString(p, &clsid))) {
WORD major_i = 1, minor_i = 0;
/* pick up the major/minor numbers; if none specified, default to 1,0 */
if (major && minor) {
major_i = (WORD)atoi(major);
minor_i = (WORD)atoi(minor);
}
/* Load the TypeLib by GUID */
hr = LoadRegTypeLib((REFGUID)&clsid, major_i, minor_i, LANG_NEUTRAL, &TL);
/* if that failed, assumed that the GUID is actually a CLSID and
* attempt to get the library via an instance of that class */
if (FAILED(hr) && (major == NULL || minor == NULL)) {
IDispatch *disp = NULL;
ITypeInfo *info = NULL;
UINT idx;
if (SUCCEEDED(hr = CoCreateInstance(&clsid, NULL, CLSCTX_SERVER, &IID_IDispatch, (LPVOID*)&disp)) &&
SUCCEEDED(hr = IDispatch_GetTypeInfo(disp, 0, LANG_NEUTRAL, &info))) {
hr = ITypeInfo_GetContainingTypeLib(info, &TL, &idx);
}
if (info) {
ITypeInfo_Release(info);
}
if (disp) {
IDispatch_Release(disp);
}
}
} else {
/* Try to load it from a file; if it fails, do a really painful search of
* the registry */
if (FAILED(LoadTypeLib(p, &TL))) {
HKEY hkey, hsubkey;
DWORD SubKeys, MaxSubKeyLength;
char *keyname;
unsigned int i, j;
DWORD VersionCount;
char version[20];
char *libname;
long libnamelen;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, "TypeLib", 0, KEY_READ, &hkey) &&
ERROR_SUCCESS == RegQueryInfoKey(hkey, NULL, NULL, NULL, &SubKeys,
&MaxSubKeyLength, NULL, NULL, NULL, NULL, NULL, NULL)) {
MaxSubKeyLength++; /* make room for NUL */
keyname = emalloc(MaxSubKeyLength);
libname = emalloc(strlen(search_string) + 1);
for (i = 0; i < SubKeys && TL == NULL; i++) {
if (ERROR_SUCCESS == RegEnumKey(hkey, i, keyname, MaxSubKeyLength) &&
ERROR_SUCCESS == RegOpenKeyEx(hkey, keyname, 0, KEY_READ, &hsubkey)) {
if (ERROR_SUCCESS == RegQueryInfoKey(hsubkey, NULL, NULL, NULL, &VersionCount,
NULL, NULL, NULL, NULL, NULL, NULL, NULL)) {
for (j = 0; j < VersionCount; j++) {
if (ERROR_SUCCESS != RegEnumKey(hsubkey, j, version, sizeof(version))) {
continue;
}
/* get the default value for this key and compare */
libnamelen = (long)strlen(search_string)+1;
if (ERROR_SUCCESS == RegQueryValue(hsubkey, version, libname, &libnamelen)) {
if (0 == stricmp(libname, search_string)) {
char *str = NULL;
int major_tmp, minor_tmp;
/* fetch the GUID and add the version numbers */
if (2 != sscanf(version, "%d.%d", &major_tmp, &minor_tmp)) {
major_tmp = 1;
minor_tmp = 0;
}
spprintf(&str, 0, "%s,%d,%d", keyname, major_tmp, minor_tmp);
/* recurse */
TL = php_com_load_typelib(str, codepage);
efree(str);
break;
}
}
}
}
RegCloseKey(hsubkey);
}
}
RegCloseKey(hkey);
efree(keyname);
efree(libname);
}
}
}
efree(p);
return TL;
}
/* Given a type-library, merge it into the current engine state */
PHP_COM_DOTNET_API zend_result php_com_import_typelib(ITypeLib *TL, int mode, int codepage)
{
int i, j, interfaces;
TYPEKIND pTKind;
ITypeInfo *TypeInfo;
VARDESC *pVarDesc;
UINT NameCount;
BSTR bstr_ids;
zend_constant c;
zval *exists, results, value;
if (TL == NULL) {
return FAILURE;
}
interfaces = ITypeLib_GetTypeInfoCount(TL);
for (i = 0; i < interfaces; i++) {
ITypeLib_GetTypeInfoType(TL, i, &pTKind);
if (pTKind == TKIND_ENUM) {
ITypeLib_GetTypeInfo(TL, i, &TypeInfo);
for (j = 0; ; j++) {
zend_string *const_name;
if (FAILED(ITypeInfo_GetVarDesc(TypeInfo, j, &pVarDesc))) {
break;
}
ITypeInfo_GetNames(TypeInfo, pVarDesc->memid, &bstr_ids, 1, &NameCount);
if (NameCount != 1) {
ITypeInfo_ReleaseVarDesc(TypeInfo, pVarDesc);
continue;
}
const_name = php_com_olestring_to_string(bstr_ids, codepage);
SysFreeString(bstr_ids);
/* sanity check for the case where the constant is already defined */
php_com_zval_from_variant(&value, pVarDesc->lpvarValue, codepage);
if ((exists = zend_get_constant(const_name)) != NULL) {
if (COMG(autoreg_verbose) && !compare_function(&results, &value, exists)) {
php_error_docref(NULL, E_WARNING, "Type library constant %s is already defined", ZSTR_VAL(const_name));
}
zend_string_release_ex(const_name, /* persistent */ false);
ITypeInfo_ReleaseVarDesc(TypeInfo, pVarDesc);
continue;
}
/* register the constant */
if (Z_TYPE(value) == IS_LONG) {
ZEND_CONSTANT_SET_FLAGS(&c, mode, 0);
ZVAL_LONG(&c.value, Z_LVAL(value));
if (mode & CONST_PERSISTENT) {
/* duplicate string in a persistent manner */
c.name = zend_string_dup(const_name, /* persistent */ true);
zend_string_release_ex(const_name, /* persistent */ false);
} else {
c.name = const_name;
}
zend_register_constant(&c);
}
ITypeInfo_ReleaseVarDesc(TypeInfo, pVarDesc);
}
ITypeInfo_Release(TypeInfo);
}
}
return SUCCESS;
}
/* Type-library stuff */
void php_com_typelibrary_dtor(zval *pDest)
{
ITypeLib *Lib = (ITypeLib*)Z_PTR_P(pDest);
ITypeLib_Release(Lib);
}
ITypeLib *php_com_cache_typelib(ITypeLib* TL, char *cache_key, zend_long cache_key_len) {
ITypeLib* result;
#ifdef ZTS
tsrm_mutex_lock(php_com_typelibraries_mutex);
#endif
result = zend_hash_str_add_ptr(&php_com_typelibraries, cache_key, cache_key_len, TL);
#ifdef ZTS
tsrm_mutex_unlock(php_com_typelibraries_mutex);
#endif
return result;
}
PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib_via_cache(const char *search_string, int codepage)
{
ITypeLib *TL;
char *name_dup;
zend_string *key = zend_string_init(search_string, strlen(search_string), 1);
#ifdef ZTS
tsrm_mutex_lock(php_com_typelibraries_mutex);
#endif
if ((TL = zend_hash_find_ptr(&php_com_typelibraries, key)) != NULL) {
/* add a reference for the caller */
ITypeLib_AddRef(TL);
goto php_com_load_typelib_via_cache_return;
}
name_dup = estrndup(ZSTR_VAL(key), ZSTR_LEN(key));
TL = php_com_load_typelib(name_dup, codepage);
efree(name_dup);
if (TL) {
if (NULL != zend_hash_add_ptr(&php_com_typelibraries, key, TL)) {
/* add a reference for the hash table */
ITypeLib_AddRef(TL);
}
}
php_com_load_typelib_via_cache_return:
#ifdef ZTS
tsrm_mutex_unlock(php_com_typelibraries_mutex);
#endif
zend_string_release(key);
return TL;
}
ITypeInfo *php_com_locate_typeinfo(zend_string *type_lib_name, php_com_dotnet_object *obj,
zend_string *dispatch_name, bool sink)
{
ITypeInfo *typeinfo = NULL;
ITypeLib *typelib = NULL;
int gotguid = 0;
GUID iid;
if (obj) {
if (dispatch_name == NULL && sink) {
if (V_VT(&obj->v) == VT_DISPATCH) {
IProvideClassInfo2 *pci2;
IProvideClassInfo *pci;
if (SUCCEEDED(IDispatch_QueryInterface(V_DISPATCH(&obj->v), &IID_IProvideClassInfo2, (void**)&pci2))) {
gotguid = SUCCEEDED(IProvideClassInfo2_GetGUID(pci2, GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid));
IProvideClassInfo2_Release(pci2);
}
if (!gotguid && SUCCEEDED(IDispatch_QueryInterface(V_DISPATCH(&obj->v), &IID_IProvideClassInfo, (void**)&pci))) {
/* examine the available interfaces */
/* TODO: write some code here */
php_error_docref(NULL, E_WARNING, "IProvideClassInfo: this code not yet written!");
IProvideClassInfo_Release(pci);
}
}
} else if (dispatch_name == NULL) {
if (obj->typeinfo) {
ITypeInfo_AddRef(obj->typeinfo);
return obj->typeinfo;
} else {
IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &typeinfo);
if (typeinfo) {
return typeinfo;
}
}
} else if (dispatch_name && obj->typeinfo) {
unsigned int idx;
/* get the library from the object; the rest will be dealt with later */
ITypeInfo_GetContainingTypeLib(obj->typeinfo, &typelib, &idx);
} else if (type_lib_name == NULL) {
if (V_VT(&obj->v) == VT_DISPATCH) {
IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &typeinfo);
if (dispatch_name) {
unsigned int idx;
/* get the library from the object; the rest will be dealt with later */
ITypeInfo_GetContainingTypeLib(typeinfo, &typelib, &idx);
if (typelib) {
ITypeInfo_Release(typeinfo);
typeinfo = NULL;
}
}
}
}
} else if (type_lib_name) {
/* Fetch the typelibrary and use that to look things up */
typelib = php_com_load_typelib(ZSTR_VAL(type_lib_name), CP_THREAD_ACP);
}
if (!gotguid && dispatch_name && typelib) {
unsigned short cfound;
MEMBERID memid;
OLECHAR *olename = php_com_string_to_olestring(ZSTR_VAL(dispatch_name), ZSTR_LEN(dispatch_name), CP_ACP);
cfound = 1;
if (FAILED(ITypeLib_FindName(typelib, olename, 0, &typeinfo, &memid, &cfound)) || cfound == 0) {
CLSID coclass;
ITypeInfo *coinfo;
/* assume that it might be a progid instead */
if (SUCCEEDED(CLSIDFromProgID(olename, &coclass)) &&
SUCCEEDED(ITypeLib_GetTypeInfoOfGuid(typelib, &coclass, &coinfo))) {
/* enumerate implemented interfaces and pick the one as indicated by sink */
TYPEATTR *attr;
int i;
ITypeInfo_GetTypeAttr(coinfo, &attr);
for (i = 0; i < attr->cImplTypes; i++) {
HREFTYPE rt;
int tf;
if (FAILED(ITypeInfo_GetImplTypeFlags(coinfo, i, &tf))) {
continue;
}
if ((sink && tf == (IMPLTYPEFLAG_FSOURCE|IMPLTYPEFLAG_FDEFAULT)) ||
(!sink && (tf & IMPLTYPEFLAG_FSOURCE) == 0)) {
/* flags match what we are looking for */
if (SUCCEEDED(ITypeInfo_GetRefTypeOfImplType(coinfo, i, &rt)))
if (SUCCEEDED(ITypeInfo_GetRefTypeInfo(coinfo, rt, &typeinfo)))
break;
}
}
ITypeInfo_ReleaseTypeAttr(coinfo, attr);
ITypeInfo_Release(coinfo);
}
}
efree(olename);
} else if (gotguid) {
ITypeLib_GetTypeInfoOfGuid(typelib, &iid, &typeinfo);
}
if (typelib) {
ITypeLib_Release(typelib);
}
return typeinfo;
}
static const struct {
VARTYPE vt;
const char *name;
} vt_names[] = {
{ VT_NULL, "VT_NULL" },
{ VT_EMPTY, "VT_EMPTY" },
{ VT_UI1, "VT_UI1" },
{ VT_I2, "VT_I2" },
{ VT_I4, "VT_I4" },
{ VT_R4, "VT_R4" },
{ VT_R8, "VT_R8" },
{ VT_BOOL, "VT_BOOL" },
{ VT_ERROR, "VT_ERROR" },
{ VT_CY, "VT_CY" },
{ VT_DATE, "VT_DATE" },
{ VT_BSTR, "VT_BSTR" },
{ VT_DECIMAL, "VT_DECIMAL" },
{ VT_UNKNOWN, "VT_UNKNOWN" },
{ VT_DISPATCH, "VT_DISPATCH" },
{ VT_VARIANT, "VT_VARIANT" },
{ VT_I1, "VT_I1" },
{ VT_UI2, "VT_UI2" },
{ VT_UI4, "VT_UI4" },
{ VT_INT, "VT_INT" },
{ VT_UINT, "VT_UINT" },
{ VT_ARRAY, "VT_ARRAY" },
{ VT_BYREF, "VT_BYREF" },
{ VT_VOID, "VT_VOID" },
{ VT_PTR, "VT_PTR" },
{ VT_HRESULT, "VT_HRESULT" },
{ VT_SAFEARRAY, "VT_SAFEARRAY" },
{ 0, NULL }
};
static inline const char *vt_to_string(VARTYPE vt)
{
int i;
for (i = 0; vt_names[i].name != NULL; i++) {
if (vt_names[i].vt == vt)
return vt_names[i].name;
}
return "?";
}
static zend_string *php_com_string_from_clsid(const CLSID *clsid, int codepage)
{
LPOLESTR ole_clsid;
zend_string *clsid_str;
StringFromCLSID(clsid, &ole_clsid);
clsid_str = php_com_olestring_to_string(ole_clsid, codepage);
LocalFree(ole_clsid);
return clsid_str;
}
bool php_com_process_typeinfo(ITypeInfo *typeinfo, HashTable *id_to_name, bool printdef, GUID *guid, int codepage)
{
TYPEATTR *attr;
FUNCDESC *func;
int i;
OLECHAR *olename;
zend_string *ansi_name = NULL;
DISPID lastid = 0; /* for props */
if (FAILED(ITypeInfo_GetTypeAttr(typeinfo, &attr))) {
return false;
}
/* verify that it is suitable */
if (id_to_name == NULL || attr->typekind == TKIND_DISPATCH) {
if (guid) {
memcpy(guid, &attr->guid, sizeof(GUID));
}
if (printdef) {
zend_string *guid_str;
ITypeInfo_GetDocumentation(typeinfo, MEMBERID_NIL, &olename, NULL, NULL, NULL);
ansi_name = php_com_olestring_to_string(olename, codepage);
SysFreeString(olename);
guid_str = php_com_string_from_clsid(&attr->guid, codepage);
php_printf("class %s { /* GUID=%s */\n", ZSTR_VAL(ansi_name), ZSTR_VAL(guid_str));
zend_string_release_ex(guid_str, /* persistent */ false);
zend_string_release_ex(ansi_name, /* persistent */ false);
}
if (id_to_name) {
zend_hash_init(id_to_name, 0, NULL, ZVAL_PTR_DTOR, 0);
}
/* So we've got the dispatch interface; lets list the event methods */
for (i = 0; i < attr->cFuncs; i++) {
zval tmp;
int isprop;
if (FAILED(ITypeInfo_GetFuncDesc(typeinfo, i, &func)))
break;
isprop = (func->invkind & DISPATCH_PROPERTYGET || func->invkind & DISPATCH_PROPERTYPUT);
if (!isprop || lastid != func->memid) {
lastid = func->memid;
ITypeInfo_GetDocumentation(typeinfo, func->memid, &olename, NULL, NULL, NULL);
ansi_name = php_com_olestring_to_string(olename, codepage);
SysFreeString(olename);
if (printdef) {
int j;
zend_string *func_desc;
unsigned int cnames = 0;
BSTR *names;
names = (BSTR*)safe_emalloc((func->cParams + 1), sizeof(BSTR), 0);
ITypeInfo_GetNames(typeinfo, func->memid, names, func->cParams + 1, &cnames);
/* first element is the function name */
SysFreeString(names[0]);
php_printf("\t/* DISPID=%d */\n", func->memid);
if (func->elemdescFunc.tdesc.vt != VT_VOID) {
php_printf("\t/* %s [%d] */\n",
vt_to_string(func->elemdescFunc.tdesc.vt),
func->elemdescFunc.tdesc.vt
);
}
if (isprop) {
ITypeInfo_GetDocumentation(typeinfo, func->memid, NULL, &olename, NULL, NULL);
if (olename) {
func_desc = php_com_olestring_to_string(olename, codepage);
SysFreeString(olename);
php_printf("\t/* %s */\n", ZSTR_VAL(func_desc));
zend_string_release_ex(func_desc, /* persistent */ false);
}
php_printf("\tvar $%s;\n\n", ZSTR_VAL(ansi_name));
} else {
/* a function */
php_printf("\tfunction %s(\n", ZSTR_VAL(ansi_name));
for (j = 0; j < func->cParams; j++) {
ELEMDESC *elem = &func->lprgelemdescParam[j];
php_printf("\t\t/* %s [%d] ", vt_to_string(elem->tdesc.vt), elem->tdesc.vt);
if (elem->paramdesc.wParamFlags & PARAMFLAG_FIN)
php_printf("[in]");
if (elem->paramdesc.wParamFlags & PARAMFLAG_FOUT)
php_printf("[out]");
if (elem->tdesc.vt == VT_PTR) {
/* what does it point to ? */
php_printf(" --> %s [%d] ",
vt_to_string(elem->tdesc.lptdesc->vt),
elem->tdesc.lptdesc->vt
);
}
/* when we handle prop put and get, this will look nicer */
if (j+1 < (int)cnames) {
func_desc = php_com_olestring_to_string(names[j+1], codepage);
SysFreeString(names[j+1]);
php_printf(" */ %s%s%c\n",
elem->tdesc.vt == VT_PTR ? "&$" : "$",
ZSTR_VAL(func_desc),
j == func->cParams - 1 ? ' ' : ','
);
} else {
php_printf(" */ %s???%c\n",
elem->tdesc.vt == VT_PTR ? "&$" : "$",
j == func->cParams - 1 ? ' ' : ','
);
}
if (j+1 < (int)cnames) {
zend_string_release_ex(func_desc, /* persistent */ false);
}
}
php_printf("\t\t)\n\t{\n");
ITypeInfo_GetDocumentation(typeinfo, func->memid, NULL, &olename, NULL, NULL);
if (olename) {
func_desc = php_com_olestring_to_string(olename, codepage);
SysFreeString(olename);
php_printf("\t\t/* %s */\n", ZSTR_VAL(func_desc));
zend_string_release_ex(func_desc, /* persistent */ false);
}
php_printf("\t}\n");
}
efree(names);
}
if (id_to_name) {
zend_string *lc_ansi_name = zend_string_tolower(ansi_name);
ZVAL_STR(&tmp, lc_ansi_name);
zend_hash_index_update(id_to_name, func->memid, &tmp);
}
zend_string_release_ex(ansi_name, /* persistent */ false);
}
ITypeInfo_ReleaseFuncDesc(typeinfo, func);
}
if (printdef) {
php_printf("}\n");
}
} else {
zend_throw_error(NULL, "Type kind must be dispatchable, %08x given", attr->typekind);
}
ITypeInfo_ReleaseTypeAttr(typeinfo, attr);
return true;
}
| 18,575 | 27.666667 | 117 |
c
|
php-src
|
php-src-master/ext/com_dotnet/com_wrapper.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]> |
+----------------------------------------------------------------------+
*/
/* This module exports a PHP object as a COM object by wrapping it
* using IDispatchEx */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_com_dotnet.h"
#include "php_com_dotnet_internal.h"
typedef struct {
/* This first part MUST match the declaration
* of interface IDispatchEx */
CONST_VTBL struct IDispatchExVtbl *lpVtbl;
/* now the PHP stuff */
DWORD engine_thread; /* for sanity checking */
zval object; /* the object exported */
LONG refcount; /* COM reference count */
HashTable *dispid_to_name; /* keep track of dispid -> name mappings */
HashTable *name_to_dispid; /* keep track of name -> dispid mappings */
GUID sinkid; /* iid that we "implement" for event sinking */
zend_resource *res;
} php_dispatchex;
static int le_dispatch;
static void disp_destructor(php_dispatchex *disp);
static void dispatch_dtor(zend_resource *rsrc)
{
php_dispatchex *disp = (php_dispatchex *)rsrc->ptr;
disp_destructor(disp);
}
int php_com_wrapper_minit(INIT_FUNC_ARGS)
{
le_dispatch = zend_register_list_destructors_ex(dispatch_dtor,
NULL, "com_dotnet_dispatch_wrapper", module_number);
return le_dispatch;
}
/* {{{ trace */
static inline void trace(char *fmt, ...)
{
va_list ap;
char buf[4096];
snprintf(buf, sizeof(buf), "T=%08x ", GetCurrentThreadId());
OutputDebugString(buf);
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
OutputDebugString(buf);
va_end(ap);
}
/* }}} */
#define FETCH_DISP(methname) \
php_dispatchex *disp = (php_dispatchex*)This; \
if (COMG(rshutdown_started)) { \
trace(" PHP Object:%p (name:unknown) %s\n", Z_OBJ(disp->object), methname); \
} else { \
trace(" PHP Object:%p (name:%s) %s\n", Z_OBJ(disp->object), Z_OBJCE(disp->object)->name->val, methname); \
} \
if (GetCurrentThreadId() != disp->engine_thread) { \
return RPC_E_WRONG_THREAD; \
}
static HRESULT STDMETHODCALLTYPE disp_queryinterface(
IDispatchEx *This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject)
{
FETCH_DISP("QueryInterface");
if (IsEqualGUID(&IID_IUnknown, riid) ||
IsEqualGUID(&IID_IDispatch, riid) ||
IsEqualGUID(&IID_IDispatchEx, riid) ||
IsEqualGUID(&disp->sinkid, riid)) {
*ppvObject = This;
InterlockedIncrement(&disp->refcount);
return S_OK;
}
*ppvObject = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE disp_addref(IDispatchEx *This)
{
FETCH_DISP("AddRef");
return InterlockedIncrement(&disp->refcount);
}
static ULONG STDMETHODCALLTYPE disp_release(IDispatchEx *This)
{
ULONG ret;
FETCH_DISP("Release");
ret = InterlockedDecrement(&disp->refcount);
trace("-- refcount now %d\n", ret);
if (ret == 0) {
/* destroy it */
if (disp->res)
zend_list_delete(disp->res);
}
return ret;
}
static HRESULT STDMETHODCALLTYPE disp_gettypeinfocount(
IDispatchEx *This,
/* [out] */ UINT *pctinfo)
{
FETCH_DISP("GetTypeInfoCount");
*pctinfo = 0;
return S_OK;
}
static HRESULT STDMETHODCALLTYPE disp_gettypeinfo(
IDispatchEx *This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo)
{
FETCH_DISP("GetTypeInfo");
*ppTInfo = NULL;
return DISP_E_BADINDEX;
}
static HRESULT STDMETHODCALLTYPE disp_getidsofnames(
IDispatchEx *This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId)
{
UINT i;
HRESULT ret = S_OK;
FETCH_DISP("GetIDsOfNames");
for (i = 0; i < cNames; i++) {
zend_string *name;
zval *tmp;
name = php_com_olestring_to_string(rgszNames[i], COMG(code_page));
/* Lookup the name in the hash */
if ((tmp = zend_hash_find(disp->name_to_dispid, name)) == NULL) {
ret = DISP_E_UNKNOWNNAME;
rgDispId[i] = 0;
} else {
rgDispId[i] = (DISPID)Z_LVAL_P(tmp);
}
zend_string_release_ex(name, /* persistent */ false);
}
return ret;
}
static HRESULT STDMETHODCALLTYPE disp_invoke(
IDispatchEx *This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr)
{
return This->lpVtbl->InvokeEx(This, dispIdMember,
lcid, wFlags, pDispParams,
pVarResult, pExcepInfo, NULL);
}
static HRESULT STDMETHODCALLTYPE disp_getdispid(
IDispatchEx *This,
/* [in] */ BSTR bstrName,
/* [in] */ DWORD grfdex,
/* [out] */ DISPID *pid)
{
HRESULT ret = DISP_E_UNKNOWNNAME;
zend_string *name;
zval *tmp;
FETCH_DISP("GetDispID");
name = php_com_olestring_to_string(bstrName, COMG(code_page));
trace("Looking for %s, namelen=%d in %p\n", ZSTR_VAL(name), ZSTR_LEN(name), disp->name_to_dispid);
/* Lookup the name in the hash */
if ((tmp = zend_hash_find(disp->name_to_dispid, name)) != NULL) {
trace("found it\n");
*pid = (DISPID)Z_LVAL_P(tmp);
ret = S_OK;
}
zend_string_release_ex(name, /* persistent */ false);
return ret;
}
static HRESULT STDMETHODCALLTYPE disp_invokeex(
IDispatchEx *This,
/* [in] */ DISPID id,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [in] */ DISPPARAMS *pdp,
/* [out] */ VARIANT *pvarRes,
/* [out] */ EXCEPINFO *pei,
/* [unique][in] */ IServiceProvider *pspCaller)
{
zval *name;
UINT i;
zval rv, *retval = NULL;
zval *params = NULL;
HRESULT ret = DISP_E_MEMBERNOTFOUND;
FETCH_DISP("InvokeEx");
if (NULL != (name = zend_hash_index_find(disp->dispid_to_name, id))) {
/* TODO: add support for overloaded objects */
trace("-- Invoke: %d %20s [%d] flags=%08x args=%d\n", id, Z_STRVAL_P(name), Z_STRLEN_P(name), wFlags, pdp->cArgs);
/* convert args into zvals.
* Args are in reverse order */
if (pdp->cArgs) {
params = (zval *)safe_emalloc(sizeof(zval), pdp->cArgs, 0);
for (i = 0; i < pdp->cArgs; i++) {
VARIANT *arg;
arg = &pdp->rgvarg[ pdp->cArgs - 1 - i];
trace("alloc zval for arg %d VT=%08x\n", i, V_VT(arg));
php_com_wrap_variant(¶ms[i], arg, COMG(code_page));
}
}
trace("arguments processed, prepare to do some work\n");
/* TODO: if PHP raises an exception here, we should catch it
* and expose it as a COM exception */
if (wFlags & DISPATCH_PROPERTYGET) {
retval = zend_read_property(Z_OBJCE(disp->object), Z_OBJ(disp->object), Z_STRVAL_P(name), Z_STRLEN_P(name)+1, 1, &rv);
} else if (wFlags & DISPATCH_PROPERTYPUT) {
zend_update_property(Z_OBJCE(disp->object), Z_OBJ(disp->object), Z_STRVAL_P(name), Z_STRLEN_P(name), ¶ms[0]);
} else if (wFlags & DISPATCH_METHOD) {
zend_try {
retval = &rv;
if (SUCCESS == call_user_function(NULL, &disp->object, name,
retval, pdp->cArgs, params)) {
ret = S_OK;
trace("function called ok\n");
/* Copy any modified values to callers copy of variant*/
for (i = 0; i < pdp->cArgs; i++) {
php_com_dotnet_object *obj = CDNO_FETCH(¶ms[i]);
VARIANT *srcvar = &obj->v;
VARIANT *dstvar = &pdp->rgvarg[ pdp->cArgs - 1 - i];
if ((V_VT(dstvar) & VT_BYREF) && obj->modified ) {
trace("percolate modified value for arg %d VT=%08x\n", i, V_VT(dstvar));
php_com_copy_variant(dstvar, srcvar);
}
}
} else {
trace("failed to call func\n");
ret = DISP_E_EXCEPTION;
}
} zend_catch {
trace("something blew up\n");
ret = DISP_E_EXCEPTION;
} zend_end_try();
} else {
trace("Don't know how to handle this invocation %08x\n", wFlags);
}
/* release arguments */
if (params) {
for (i = 0; i < pdp->cArgs; i++) {
zval_ptr_dtor(¶ms[i]);
}
efree(params);
}
/* return value */
if (retval) {
if (pvarRes) {
VariantInit(pvarRes);
php_com_variant_from_zval(pvarRes, retval, COMG(code_page));
}
zval_ptr_dtor(retval);
} else if (pvarRes) {
VariantInit(pvarRes);
}
} else {
trace("InvokeEx: I don't support DISPID=%d\n", id);
}
return ret;
}
static HRESULT STDMETHODCALLTYPE disp_deletememberbyname(
IDispatchEx *This,
/* [in] */ BSTR bstrName,
/* [in] */ DWORD grfdex)
{
FETCH_DISP("DeleteMemberByName");
/* TODO: unset */
return S_FALSE;
}
static HRESULT STDMETHODCALLTYPE disp_deletememberbydispid(
IDispatchEx *This,
/* [in] */ DISPID id)
{
FETCH_DISP("DeleteMemberByDispID");
/* TODO: unset */
return S_FALSE;
}
static HRESULT STDMETHODCALLTYPE disp_getmemberproperties(
IDispatchEx *This,
/* [in] */ DISPID id,
/* [in] */ DWORD grfdexFetch,
/* [out] */ DWORD *pgrfdex)
{
FETCH_DISP("GetMemberProperties");
return DISP_E_UNKNOWNNAME;
}
static HRESULT STDMETHODCALLTYPE disp_getmembername(
IDispatchEx *This,
/* [in] */ DISPID id,
/* [out] */ BSTR *pbstrName)
{
zval *name;
FETCH_DISP("GetMemberName");
if (NULL != (name = zend_hash_index_find(disp->dispid_to_name, id))) {
OLECHAR *olestr = php_com_string_to_olestring(Z_STRVAL_P(name), Z_STRLEN_P(name), COMG(code_page));
*pbstrName = SysAllocString(olestr);
efree(olestr);
return S_OK;
} else {
return DISP_E_UNKNOWNNAME;
}
}
static HRESULT STDMETHODCALLTYPE disp_getnextdispid(
IDispatchEx *This,
/* [in] */ DWORD grfdex,
/* [in] */ DISPID id,
/* [out] */ DISPID *pid)
{
zend_ulong next = id+1;
FETCH_DISP("GetNextDispID");
while(!zend_hash_index_exists(disp->dispid_to_name, next))
next++;
if (zend_hash_index_exists(disp->dispid_to_name, next)) {
*pid = next;
return S_OK;
}
return S_FALSE;
}
static HRESULT STDMETHODCALLTYPE disp_getnamespaceparent(
IDispatchEx *This,
/* [out] */ IUnknown **ppunk)
{
FETCH_DISP("GetNameSpaceParent");
*ppunk = NULL;
return E_NOTIMPL;
}
static struct IDispatchExVtbl php_dispatch_vtbl = {
disp_queryinterface,
disp_addref,
disp_release,
disp_gettypeinfocount,
disp_gettypeinfo,
disp_getidsofnames,
disp_invoke,
disp_getdispid,
disp_invokeex,
disp_deletememberbyname,
disp_deletememberbydispid,
disp_getmemberproperties,
disp_getmembername,
disp_getnextdispid,
disp_getnamespaceparent
};
/* enumerate functions and properties of the object and assign
* dispatch ids */
static void generate_dispids(php_dispatchex *disp)
{
HashPosition pos;
zend_string *name = NULL;
zval *tmp, tmp2;
int keytype;
zend_ulong pid;
if (disp->dispid_to_name == NULL) {
ALLOC_HASHTABLE(disp->dispid_to_name);
ALLOC_HASHTABLE(disp->name_to_dispid);
zend_hash_init(disp->name_to_dispid, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_init(disp->dispid_to_name, 0, NULL, ZVAL_PTR_DTOR, 0);
}
/* properties */
if (Z_OBJPROP(disp->object)) {
zend_hash_internal_pointer_reset_ex(Z_OBJPROP(disp->object), &pos);
while (HASH_KEY_NON_EXISTENT != (keytype =
zend_hash_get_current_key_ex(Z_OBJPROP(disp->object), &name,
&pid, &pos))) {
char namebuf[32];
if (keytype == HASH_KEY_IS_LONG) {
snprintf(namebuf, sizeof(namebuf), ZEND_ULONG_FMT, pid);
name = zend_string_init(namebuf, strlen(namebuf), 0);
} else {
zend_string_addref(name);
}
zend_hash_move_forward_ex(Z_OBJPROP(disp->object), &pos);
/* Find the existing id */
if ((tmp = zend_hash_find(disp->name_to_dispid, name)) != NULL) {
zend_string_release_ex(name, 0);
continue;
}
/* add the mappings */
ZVAL_STR_COPY(&tmp2, name);
pid = zend_hash_next_free_element(disp->dispid_to_name);
zend_hash_index_update(disp->dispid_to_name, pid, &tmp2);
ZVAL_LONG(&tmp2, pid);
zend_hash_update(disp->name_to_dispid, name, &tmp2);
zend_string_release_ex(name, 0);
}
}
/* functions */
if (Z_OBJCE(disp->object)) {
zend_hash_internal_pointer_reset_ex(&Z_OBJCE(disp->object)->function_table, &pos);
while (HASH_KEY_NON_EXISTENT != (keytype =
zend_hash_get_current_key_ex(&Z_OBJCE(disp->object)->function_table,
&name, &pid, &pos))) {
char namebuf[32];
if (keytype == HASH_KEY_IS_LONG) {
snprintf(namebuf, sizeof(namebuf), ZEND_ULONG_FMT, pid);
name = zend_string_init(namebuf, strlen(namebuf), 0);
} else {
zend_string_addref(name);
}
zend_hash_move_forward_ex(&Z_OBJCE(disp->object)->function_table, &pos);
/* Find the existing id */
if ((tmp = zend_hash_find(disp->name_to_dispid, name)) != NULL) {
zend_string_release_ex(name, 0);
continue;
}
/* add the mappings */
ZVAL_STR_COPY(&tmp2, name);
pid = zend_hash_next_free_element(disp->dispid_to_name);
zend_hash_index_update(disp->dispid_to_name, pid, &tmp2);
ZVAL_LONG(&tmp2, pid);
zend_hash_update(disp->name_to_dispid, name, &tmp2);
zend_string_release_ex(name, 0);
}
}
}
static php_dispatchex *disp_constructor(zval *object)
{
php_dispatchex *disp = (php_dispatchex*)CoTaskMemAlloc(sizeof(php_dispatchex));
zval *tmp;
trace("constructing a COM wrapper for PHP object %p (%s)\n", object, Z_OBJCE_P(object)->name);
if (disp == NULL)
return NULL;
memset(disp, 0, sizeof(php_dispatchex));
disp->engine_thread = GetCurrentThreadId();
disp->lpVtbl = &php_dispatch_vtbl;
disp->refcount = 1;
if (object) {
ZVAL_COPY(&disp->object, object);
} else {
ZVAL_UNDEF(&disp->object);
}
tmp = zend_list_insert(disp, le_dispatch);
disp->res = Z_RES_P(tmp);
return disp;
}
static void disp_destructor(php_dispatchex *disp)
{
/* Object store not available during request shutdown */
if (COMG(rshutdown_started)) {
trace("destroying COM wrapper for PHP object %p (name:unknown)\n", Z_OBJ(disp->object));
} else {
trace("destroying COM wrapper for PHP object %p (name:%s)\n", Z_OBJ(disp->object), Z_OBJCE(disp->object)->name->val);
}
disp->res = NULL;
if (disp->refcount > 0)
CoDisconnectObject((IUnknown*)disp, 0);
zend_hash_destroy(disp->dispid_to_name);
zend_hash_destroy(disp->name_to_dispid);
FREE_HASHTABLE(disp->dispid_to_name);
FREE_HASHTABLE(disp->name_to_dispid);
zval_ptr_dtor(&disp->object);
CoTaskMemFree(disp);
}
PHP_COM_DOTNET_API IDispatch *php_com_wrapper_export_as_sink(zval *val, GUID *sinkid,
HashTable *id_to_name)
{
php_dispatchex *disp = disp_constructor(val);
HashPosition pos;
zend_string *name = NULL;
zval tmp, *ntmp;
int keytype;
zend_ulong pid;
disp->dispid_to_name = id_to_name;
memcpy(&disp->sinkid, sinkid, sizeof(disp->sinkid));
/* build up the reverse mapping */
ALLOC_HASHTABLE(disp->name_to_dispid);
zend_hash_init(disp->name_to_dispid, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_internal_pointer_reset_ex(id_to_name, &pos);
while (HASH_KEY_NON_EXISTENT != (keytype =
zend_hash_get_current_key_ex(id_to_name, &name, &pid, &pos))) {
if (keytype == HASH_KEY_IS_LONG) {
ntmp = zend_hash_get_current_data_ex(id_to_name, &pos);
ZVAL_LONG(&tmp, pid);
zend_hash_update(disp->name_to_dispid, Z_STR_P(ntmp), &tmp);
}
zend_hash_move_forward_ex(id_to_name, &pos);
}
return (IDispatch*)disp;
}
PHP_COM_DOTNET_API IDispatch *php_com_wrapper_export(zval *val)
{
php_dispatchex *disp = NULL;
if (Z_TYPE_P(val) != IS_OBJECT) {
return NULL;
}
if (php_com_is_valid_object(val)) {
/* pass back its IDispatch directly */
php_com_dotnet_object *obj = CDNO_FETCH(val);
if (obj == NULL)
return NULL;
if (V_VT(&obj->v) == VT_DISPATCH && V_DISPATCH(&obj->v)) {
IDispatch_AddRef(V_DISPATCH(&obj->v));
return V_DISPATCH(&obj->v);
}
return NULL;
}
disp = disp_constructor(val);
generate_dispids(disp);
return (IDispatch*)disp;
}
| 16,409 | 24.560748 | 121 |
c
|
php-src
|
php-src-master/ext/com_dotnet/php_com_dotnet.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_COM_DOTNET_H
#define PHP_COM_DOTNET_H
extern zend_module_entry com_dotnet_module_entry;
#define phpext_com_dotnet_ptr &com_dotnet_module_entry
#ifdef ZTS
#include "TSRM.h"
#endif
#define PHP_COM_DOTNET_API __declspec(dllexport)
#include "php_version.h"
#define PHP_COM_DOTNET_VERSION PHP_VERSION
PHP_MINIT_FUNCTION(com_dotnet);
PHP_MSHUTDOWN_FUNCTION(com_dotnet);
PHP_RINIT_FUNCTION(com_dotnet);
PHP_RSHUTDOWN_FUNCTION(com_dotnet);
PHP_MINFO_FUNCTION(com_dotnet);
ZEND_BEGIN_MODULE_GLOBALS(com_dotnet)
bool allow_dcom;
bool autoreg_verbose;
bool autoreg_on;
bool autoreg_case_sensitive;
void *dotnet_runtime_stuff; /* opaque to avoid cluttering up other modules */
int code_page; /* default code_page if left unspecified */
bool rshutdown_started;
ZEND_END_MODULE_GLOBALS(com_dotnet)
#if defined(ZTS) && defined(COMPILE_DL_COM_DOTNET)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
ZEND_EXTERN_MODULE_GLOBALS(com_dotnet)
#define COMG(v) ZEND_MODULE_GLOBALS_ACCESSOR(com_dotnet, v)
#endif /* PHP_COM_DOTNET_H */
| 2,022 | 35.125 | 78 |
h
|
php-src
|
php-src-master/ext/com_dotnet/php_com_dotnet_internal.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_COM_DOTNET_INTERNAL_H
#define PHP_COM_DOTNET_INTERNAL_H
#define _WIN32_DCOM
#define COBJMACROS
#include <ocidl.h>
#include <oleauto.h>
#include <unknwn.h>
#include <dispex.h>
#include "win32/winutil.h"
typedef struct _php_com_dotnet_object {
zend_object zo;
VARIANT v;
bool modified;
int code_page;
ITypeInfo *typeinfo;
zend_class_entry *ce;
/* associated event sink */
IDispatch *sink_dispatch;
GUID sink_id;
DWORD sink_cookie;
/* cache for method signatures */
HashTable *method_cache;
/* cache for name -> DISPID */
HashTable *id_of_name_cache;
} php_com_dotnet_object;
static inline bool php_com_is_valid_object(zval *zv)
{
zend_class_entry *ce = Z_OBJCE_P(zv);
return zend_string_equals_literal(ce->name, "com") ||
zend_string_equals_literal(ce->name, "dotnet") ||
zend_string_equals_literal(ce->name, "variant");
}
#define CDNO_FETCH(zv) (php_com_dotnet_object*)Z_OBJ_P(zv)
#define CDNO_FETCH_VERIFY(obj, zv) do { \
if (!php_com_is_valid_object(zv)) { \
php_com_throw_exception(E_UNEXPECTED, "expected a variant object"); \
return; \
} \
obj = (php_com_dotnet_object*)Z_OBJ_P(zv); \
} while(0)
/* com_extension.c */
zend_class_entry *php_com_variant_class_entry, *php_com_exception_class_entry, *php_com_saproxy_class_entry;
/* com_handlers.c */
zend_object* php_com_object_new(zend_class_entry *ce);
zend_object* php_com_object_clone(zend_object *object);
void php_com_object_free_storage(zend_object *object);
extern zend_object_handlers php_com_object_handlers;
void php_com_object_enable_event_sink(php_com_dotnet_object *obj, bool enable);
/* com_saproxy.c */
zend_object_iterator *php_com_saproxy_iter_get(zend_class_entry *ce, zval *object, int by_ref);
void php_com_saproxy_create(zend_object *com_object, zval *proxy_out, zval *index);
extern zend_object_handlers php_com_saproxy_handlers;
/* com_olechar.c */
PHP_COM_DOTNET_API zend_string *php_com_olestring_to_string(OLECHAR *olestring, int codepage);
PHP_COM_DOTNET_API OLECHAR *php_com_string_to_olestring(const char *string,
size_t string_len, int codepage);
BSTR php_com_string_to_bstr(zend_string *string, int codepage);
zend_string *php_com_bstr_to_string(BSTR bstr, int codepage);
/* com_com.c */
PHP_METHOD(com, __construct);
HRESULT php_com_invoke_helper(php_com_dotnet_object *obj, DISPID id_member,
WORD flags, DISPPARAMS *disp_params, VARIANT *v, bool silent, bool allow_noarg);
HRESULT php_com_get_id_of_name(php_com_dotnet_object *obj, zend_string *name,
DISPID *dispid);
zend_result php_com_do_invoke_by_id(php_com_dotnet_object *obj, DISPID dispid,
WORD flags, VARIANT *v, int nargs, zval *args, bool silent, bool allow_noarg);
zend_result php_com_do_invoke(php_com_dotnet_object *obj, zend_string *name,
WORD flags, VARIANT *v, int nargs, zval *args, bool allow_noarg);
zend_result php_com_do_invoke_byref(php_com_dotnet_object *obj, zend_internal_function *f,
WORD flags, VARIANT *v, int nargs, zval *args);
/* com_wrapper.c */
int php_com_wrapper_minit(INIT_FUNC_ARGS);
PHP_COM_DOTNET_API IDispatch *php_com_wrapper_export_as_sink(zval *val, GUID *sinkid, HashTable *id_to_name);
PHP_COM_DOTNET_API IDispatch *php_com_wrapper_export(zval *val);
/* com_persist.c */
void php_com_persist_minit(INIT_FUNC_ARGS);
/* com_variant.c */
PHP_METHOD(variant, __construct);
PHP_COM_DOTNET_API void php_com_variant_from_zval_with_type(VARIANT *v, zval *z, VARTYPE type, int codepage);
PHP_COM_DOTNET_API void php_com_variant_from_zval(VARIANT *v, zval *z, int codepage);
PHP_COM_DOTNET_API zend_result php_com_zval_from_variant(zval *z, VARIANT *v, int codepage);
PHP_COM_DOTNET_API zend_result php_com_copy_variant(VARIANT *dst, VARIANT *src);
/* com_dotnet.c */
PHP_METHOD(dotnet, __construct);
void php_com_dotnet_rshutdown(void);
void php_com_dotnet_mshutdown(void);
/* com_misc.c */
void php_com_throw_exception(HRESULT code, char *message);
PHP_COM_DOTNET_API void php_com_wrap_dispatch(zval *z, IDispatch *disp,
int codepage);
PHP_COM_DOTNET_API void php_com_wrap_variant(zval *z, VARIANT *v,
int codepage);
PHP_COM_DOTNET_API bool php_com_safearray_get_elem(VARIANT *array, VARIANT *dest, LONG dim1);
/* com_typeinfo.c */
PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib_via_cache(const char *search_string, int codepage);
PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib(char *search_string, int codepage);
PHP_COM_DOTNET_API zend_result php_com_import_typelib(ITypeLib *TL, int mode, int codepage);
void php_com_typelibrary_dtor(zval *pDest);
ITypeInfo *php_com_locate_typeinfo(zend_string *type_lib_name, php_com_dotnet_object *obj,
zend_string *dispatch_name, bool sink);
bool php_com_process_typeinfo(ITypeInfo *typeinfo, HashTable *id_to_name, bool printdef, GUID *guid, int codepage);
ITypeLib *php_com_cache_typelib(ITypeLib* TL, char *cache_key, zend_long cache_key_len);
PHP_MINIT_FUNCTION(com_typeinfo);
PHP_MSHUTDOWN_FUNCTION(com_typeinfo);
/* com_iterator.c */
zend_object_iterator *php_com_iter_get(zend_class_entry *ce, zval *object, int by_ref);
#endif
| 6,039 | 39 | 115 |
h
|
php-src
|
php-src-master/ext/ctype/ctype.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: Hartmut Holzgraefe <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "php_ctype.h"
#include "ctype_arginfo.h"
#include "SAPI.h"
#include "ext/standard/info.h"
#include <ctype.h>
#ifdef HAVE_CTYPE
static PHP_MINFO_FUNCTION(ctype);
/* }}} */
/* {{{ ctype_module_entry */
zend_module_entry ctype_module_entry = {
STANDARD_MODULE_HEADER,
"ctype",
ext_functions,
NULL,
NULL,
NULL,
NULL,
PHP_MINFO(ctype),
PHP_CTYPE_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_CTYPE
ZEND_GET_MODULE(ctype)
#endif
/* {{{ PHP_MINFO_FUNCTION */
static PHP_MINFO_FUNCTION(ctype)
{
php_info_print_table_start();
php_info_print_table_row(2, "ctype functions", "enabled");
php_info_print_table_end();
}
/* }}} */
static void ctype_impl(
INTERNAL_FUNCTION_PARAMETERS, int (*iswhat)(int), bool allow_digits, bool allow_minus) {
zval *c;
ZEND_PARSE_PARAMETERS_START(1, 1);
Z_PARAM_ZVAL(c)
ZEND_PARSE_PARAMETERS_END();
if (Z_TYPE_P(c) == IS_STRING) {
char *p = Z_STRVAL_P(c), *e = Z_STRVAL_P(c) + Z_STRLEN_P(c);
if (e == p) {
RETURN_FALSE;
}
while (p < e) {
if (!iswhat((int)*(unsigned char *)(p++))) {
RETURN_FALSE;
}
}
RETURN_TRUE;
}
php_error_docref(NULL, E_DEPRECATED,
"Argument of type %s will be interpreted as string in the future", zend_zval_type_name(c));
if (Z_TYPE_P(c) == IS_LONG) {
if (Z_LVAL_P(c) <= 255 && Z_LVAL_P(c) >= 0) {
RETURN_BOOL(iswhat((int)Z_LVAL_P(c)));
} else if (Z_LVAL_P(c) >= -128 && Z_LVAL_P(c) < 0) {
RETURN_BOOL(iswhat((int)Z_LVAL_P(c) + 256));
} else if (Z_LVAL_P(c) >= 0) {
RETURN_BOOL(allow_digits);
} else {
RETURN_BOOL(allow_minus);
}
} else {
RETURN_FALSE;
}
}
/* {{{ Checks for alphanumeric character(s) */
PHP_FUNCTION(ctype_alnum)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isalnum, 1, 0);
}
/* }}} */
/* {{{ Checks for alphabetic character(s) */
PHP_FUNCTION(ctype_alpha)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isalpha, 0, 0);
}
/* }}} */
/* {{{ Checks for control character(s) */
PHP_FUNCTION(ctype_cntrl)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, iscntrl, 0, 0);
}
/* }}} */
/* {{{ Checks for numeric character(s) */
PHP_FUNCTION(ctype_digit)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isdigit, 1, 0);
}
/* }}} */
/* {{{ Checks for lowercase character(s) */
PHP_FUNCTION(ctype_lower)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, islower, 0, 0);
}
/* }}} */
/* {{{ Checks for any printable character(s) except space */
PHP_FUNCTION(ctype_graph)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isgraph, 1, 1);
}
/* }}} */
/* {{{ Checks for printable character(s) */
PHP_FUNCTION(ctype_print)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isprint, 1, 1);
}
/* }}} */
/* {{{ Checks for any printable character which is not whitespace or an alphanumeric character */
PHP_FUNCTION(ctype_punct)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, ispunct, 0, 0);
}
/* }}} */
/* {{{ Checks for whitespace character(s)*/
PHP_FUNCTION(ctype_space)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isspace, 0, 0);
}
/* }}} */
/* {{{ Checks for uppercase character(s) */
PHP_FUNCTION(ctype_upper)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isupper, 0, 0);
}
/* }}} */
/* {{{ Checks for character(s) representing a hexadecimal digit */
PHP_FUNCTION(ctype_xdigit)
{
ctype_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, isxdigit, 1, 0);
}
/* }}} */
#endif /* HAVE_CTYPE */
| 4,439 | 23.666667 | 97 |
c
|
php-src
|
php-src-master/ext/ctype/ctype_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 155783e1858a7f24dbc1c3e810d5cffee5468bf7 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ctype_alnum, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, text, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_ctype_alpha arginfo_ctype_alnum
#define arginfo_ctype_cntrl arginfo_ctype_alnum
#define arginfo_ctype_digit arginfo_ctype_alnum
#define arginfo_ctype_lower arginfo_ctype_alnum
#define arginfo_ctype_graph arginfo_ctype_alnum
#define arginfo_ctype_print arginfo_ctype_alnum
#define arginfo_ctype_punct arginfo_ctype_alnum
#define arginfo_ctype_space arginfo_ctype_alnum
#define arginfo_ctype_upper arginfo_ctype_alnum
#define arginfo_ctype_xdigit arginfo_ctype_alnum
ZEND_FUNCTION(ctype_alnum);
ZEND_FUNCTION(ctype_alpha);
ZEND_FUNCTION(ctype_cntrl);
ZEND_FUNCTION(ctype_digit);
ZEND_FUNCTION(ctype_lower);
ZEND_FUNCTION(ctype_graph);
ZEND_FUNCTION(ctype_print);
ZEND_FUNCTION(ctype_punct);
ZEND_FUNCTION(ctype_space);
ZEND_FUNCTION(ctype_upper);
ZEND_FUNCTION(ctype_xdigit);
static const zend_function_entry ext_functions[] = {
ZEND_FE(ctype_alnum, arginfo_ctype_alnum)
ZEND_FE(ctype_alpha, arginfo_ctype_alpha)
ZEND_FE(ctype_cntrl, arginfo_ctype_cntrl)
ZEND_FE(ctype_digit, arginfo_ctype_digit)
ZEND_FE(ctype_lower, arginfo_ctype_lower)
ZEND_FE(ctype_graph, arginfo_ctype_graph)
ZEND_FE(ctype_print, arginfo_ctype_print)
ZEND_FE(ctype_punct, arginfo_ctype_punct)
ZEND_FE(ctype_space, arginfo_ctype_space)
ZEND_FE(ctype_upper, arginfo_ctype_upper)
ZEND_FE(ctype_xdigit, arginfo_ctype_xdigit)
ZEND_FE_END
};
| 1,611 | 27.785714 | 79 |
h
|
php-src
|
php-src-master/ext/ctype/php_ctype.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: Hartmut Holzgraefe <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_CTYPE_H
#define PHP_CTYPE_H
#include "php_version.h"
#define PHP_CTYPE_VERSION PHP_VERSION
#ifdef HAVE_CTYPE
extern zend_module_entry ctype_module_entry;
#define phpext_ctype_ptr &ctype_module_entry
#else
#define phpext_ctype_ptr NULL
#endif
#endif /* PHP_CTYPE_H */
| 1,282 | 35.657143 | 75 |
h
|
php-src
|
php-src-master/ext/curl/curl_file.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: Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "Zend/zend_exceptions.h"
#include "curl_private.h"
#include "curl_file_arginfo.h"
PHP_CURL_API zend_class_entry *curl_CURLFile_class;
PHP_CURL_API zend_class_entry *curl_CURLStringFile_class;
static void curlfile_ctor(INTERNAL_FUNCTION_PARAMETERS)
{
zend_string *fname, *mime = NULL, *postname = NULL;
zval *cf = return_value;
ZEND_PARSE_PARAMETERS_START(1,3)
Z_PARAM_PATH_STR(fname)
Z_PARAM_OPTIONAL
Z_PARAM_STR_OR_NULL(mime)
Z_PARAM_STR_OR_NULL(postname)
ZEND_PARSE_PARAMETERS_END();
zend_update_property_str(curl_CURLFile_class, Z_OBJ_P(cf), "name", sizeof("name")-1, fname);
if (mime) {
zend_update_property_str(curl_CURLFile_class, Z_OBJ_P(cf), "mime", sizeof("mime")-1, mime);
}
if (postname) {
zend_update_property_str(curl_CURLFile_class, Z_OBJ_P(cf), "postname", sizeof("postname")-1, postname);
}
}
/* {{{ Create the CURLFile object */
ZEND_METHOD(CURLFile, __construct)
{
return_value = ZEND_THIS;
curlfile_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/* {{{ Create the CURLFile object */
PHP_FUNCTION(curl_file_create)
{
object_init_ex( return_value, curl_CURLFile_class );
curlfile_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
static void curlfile_get_property(const char *name, size_t name_len, INTERNAL_FUNCTION_PARAMETERS)
{
zval *res, rv;
ZEND_PARSE_PARAMETERS_NONE();
res = zend_read_property(curl_CURLFile_class, Z_OBJ_P(ZEND_THIS), name, name_len, 1, &rv);
RETURN_COPY_DEREF(res);
}
static void curlfile_set_property(const char *name, size_t name_len, INTERNAL_FUNCTION_PARAMETERS)
{
zend_string *arg;
ZEND_PARSE_PARAMETERS_START(1,1)
Z_PARAM_STR(arg)
ZEND_PARSE_PARAMETERS_END();
zend_update_property_str(curl_CURLFile_class, Z_OBJ_P(ZEND_THIS), name, name_len, arg);
}
/* {{{ Get file name */
ZEND_METHOD(CURLFile, getFilename)
{
curlfile_get_property("name", sizeof("name")-1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/* {{{ Get MIME type */
ZEND_METHOD(CURLFile, getMimeType)
{
curlfile_get_property("mime", sizeof("mime")-1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/* {{{ Get file name for POST */
ZEND_METHOD(CURLFile, getPostFilename)
{
curlfile_get_property("postname", sizeof("postname")-1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/* {{{ Set MIME type */
ZEND_METHOD(CURLFile, setMimeType)
{
curlfile_set_property("mime", sizeof("mime")-1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/* {{{ Set file name for POST */
ZEND_METHOD(CURLFile, setPostFilename)
{
curlfile_set_property("postname", sizeof("postname")-1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
ZEND_METHOD(CURLStringFile, __construct)
{
zend_string *data, *postname, *mime = NULL;
zval *object;
object = ZEND_THIS;
ZEND_PARSE_PARAMETERS_START(2,3)
Z_PARAM_STR(data)
Z_PARAM_STR(postname)
Z_PARAM_OPTIONAL
Z_PARAM_STR(mime)
ZEND_PARSE_PARAMETERS_END();
zend_update_property_str(curl_CURLStringFile_class, Z_OBJ_P(object), "data", sizeof("data") - 1, data);
zend_update_property_str(curl_CURLStringFile_class, Z_OBJ_P(object), "postname", sizeof("postname")-1, postname);
if (mime) {
zend_update_property_str(curl_CURLStringFile_class, Z_OBJ_P(object), "mime", sizeof("mime")-1, mime);
} else {
zend_update_property_string(curl_CURLStringFile_class, Z_OBJ_P(object), "mime", sizeof("mime")-1, "application/octet-stream");
}
}
void curlfile_register_class(void)
{
curl_CURLFile_class = register_class_CURLFile();
curl_CURLStringFile_class = register_class_CURLStringFile();
}
| 4,566 | 29.046053 | 128 |
c
|
php-src
|
php-src-master/ext/curl/curl_private.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: Sterling Hughes <[email protected]> |
| Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef _PHP_CURL_PRIVATE_H
#define _PHP_CURL_PRIVATE_H
#include "php_curl.h"
#define PHP_CURL_DEBUG 0
#include "php_version.h"
#define PHP_CURL_VERSION PHP_VERSION
#include <curl/curl.h>
#include <curl/multi.h>
#define CURLOPT_RETURNTRANSFER 19913
#define CURLOPT_BINARYTRANSFER 19914 /* For Backward compatibility */
#define PHP_CURL_STDOUT 0
#define PHP_CURL_FILE 1
#define PHP_CURL_USER 2
#define PHP_CURL_DIRECT 3
#define PHP_CURL_RETURN 4
#define PHP_CURL_IGNORE 7
#define SAVE_CURL_ERROR(__handle, __err) \
do { (__handle)->err.no = (int) __err; } while (0)
PHP_MINIT_FUNCTION(curl);
PHP_MSHUTDOWN_FUNCTION(curl);
PHP_MINFO_FUNCTION(curl);
typedef struct {
zval func_name;
zend_fcall_info_cache fci_cache;
FILE *fp;
smart_str buf;
int method;
zval stream;
} php_curl_write;
typedef struct {
zval func_name;
zend_fcall_info_cache fci_cache;
FILE *fp;
zend_resource *res;
int method;
zval stream;
} php_curl_read;
typedef struct {
zval func_name;
zend_fcall_info_cache fci_cache;
} php_curl_callback;
typedef struct {
php_curl_write *write;
php_curl_write *write_header;
php_curl_read *read;
zval std_err;
php_curl_callback *progress;
#if LIBCURL_VERSION_NUM >= 0x072000
php_curl_callback *xferinfo;
#endif
php_curl_callback *fnmatch;
#if LIBCURL_VERSION_NUM >= 0x075400
php_curl_callback *sshhostkey;
#endif
} php_curl_handlers;
struct _php_curl_error {
char str[CURL_ERROR_SIZE + 1];
int no;
};
struct _php_curl_send_headers {
zend_string *str;
};
struct _php_curl_free {
zend_llist post;
zend_llist stream;
#if LIBCURL_VERSION_NUM < 0x073800 /* 7.56.0 */
zend_llist buffers;
#endif
HashTable *slist;
};
typedef struct {
CURL *cp;
php_curl_handlers handlers;
struct _php_curl_free *to_free;
struct _php_curl_send_headers header;
struct _php_curl_error err;
bool in_callback;
uint32_t* clone;
zval postfields;
/* For CURLOPT_PRIVATE */
zval private_data;
/* CurlShareHandle object set using CURLOPT_SHARE. */
struct _php_curlsh *share;
zend_object std;
} php_curl;
#define CURLOPT_SAFE_UPLOAD -1
typedef struct {
php_curl_callback *server_push;
} php_curlm_handlers;
typedef struct {
CURLM *multi;
zend_llist easyh;
php_curlm_handlers handlers;
struct {
int no;
} err;
zend_object std;
} php_curlm;
typedef struct _php_curlsh {
CURLSH *share;
struct {
int no;
} err;
zend_object std;
} php_curlsh;
php_curl *init_curl_handle_into_zval(zval *curl);
void init_curl_handle(php_curl *ch);
void _php_curl_cleanup_handle(php_curl *);
void _php_curl_multi_cleanup_list(void *data);
void _php_curl_verify_handlers(php_curl *ch, bool reporterror);
void _php_setup_easy_copy_handlers(php_curl *ch, php_curl *source);
static inline php_curl *curl_from_obj(zend_object *obj) {
return (php_curl *)((char *)(obj) - XtOffsetOf(php_curl, std));
}
#define Z_CURL_P(zv) curl_from_obj(Z_OBJ_P(zv))
static inline php_curlsh *curl_share_from_obj(zend_object *obj) {
return (php_curlsh *)((char *)(obj) - XtOffsetOf(php_curlsh, std));
}
#define Z_CURL_SHARE_P(zv) curl_share_from_obj(Z_OBJ_P(zv))
void curl_multi_register_handlers(void);
void curl_share_register_handlers(void);
void curlfile_register_class(void);
zend_result curl_cast_object(zend_object *obj, zval *result, int type);
#endif /* _PHP_CURL_PRIVATE_H */
| 4,714 | 27.065476 | 75 |
h
|
php-src
|
php-src-master/ext/curl/php_curl.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: Sterling Hughes <[email protected]> |
| Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef _PHP_CURL_H
#define _PHP_CURL_H
#include "php.h"
#ifdef PHP_WIN32
# ifdef PHP_CURL_EXPORTS
# define PHP_CURL_API __declspec(dllexport)
# else
# define PHP_CURL_API __declspec(dllimport)
# endif
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_CURL_API __attribute__ ((visibility("default")))
#else
# define PHP_CURL_API
#endif
extern zend_module_entry curl_module_entry;
#define phpext_curl_ptr &curl_module_entry
PHP_CURL_API extern zend_class_entry *curl_ce;
PHP_CURL_API extern zend_class_entry *curl_share_ce;
PHP_CURL_API extern zend_class_entry *curl_multi_ce;
PHP_CURL_API extern zend_class_entry *curl_CURLFile_class;
PHP_CURL_API extern zend_class_entry *curl_CURLStringFile_class;
#endif /* _PHP_CURL_H */
| 1,808 | 39.2 | 75 |
h
|
php-src
|
php-src-master/ext/curl/share.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: Pierrick Charron <[email protected]> |
+----------------------------------------------------------------------+
*/
#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "curl_private.h"
#include <curl/curl.h>
#define SAVE_CURLSH_ERROR(__handle, __err) (__handle)->err.no = (int) __err;
/* {{{ Initialize a share curl handle */
PHP_FUNCTION(curl_share_init)
{
php_curlsh *sh;
ZEND_PARSE_PARAMETERS_NONE();
object_init_ex(return_value, curl_share_ce);
sh = Z_CURL_SHARE_P(return_value);
sh->share = curl_share_init();
}
/* }}} */
/* {{{ Close a set of cURL handles */
PHP_FUNCTION(curl_share_close)
{
zval *z_sh;
ZEND_PARSE_PARAMETERS_START(1,1)
Z_PARAM_OBJECT_OF_CLASS(z_sh, curl_share_ce)
ZEND_PARSE_PARAMETERS_END();
}
/* }}} */
static bool _php_curl_share_setopt(php_curlsh *sh, zend_long option, zval *zvalue, zval *return_value) /* {{{ */
{
CURLSHcode error = CURLSHE_OK;
switch (option) {
case CURLSHOPT_SHARE:
case CURLSHOPT_UNSHARE:
error = curl_share_setopt(sh->share, option, zval_get_long(zvalue));
break;
default:
zend_argument_value_error(2, "is not a valid cURL share option");
error = CURLSHE_BAD_OPTION;
break;
}
SAVE_CURLSH_ERROR(sh, error);
return error == CURLSHE_OK;
}
/* }}} */
/* {{{ Set an option for a cURL transfer */
PHP_FUNCTION(curl_share_setopt)
{
zval *z_sh, *zvalue;
zend_long options;
php_curlsh *sh;
ZEND_PARSE_PARAMETERS_START(3,3)
Z_PARAM_OBJECT_OF_CLASS(z_sh, curl_share_ce)
Z_PARAM_LONG(options)
Z_PARAM_ZVAL(zvalue)
ZEND_PARSE_PARAMETERS_END();
sh = Z_CURL_SHARE_P(z_sh);
if (_php_curl_share_setopt(sh, options, zvalue, return_value)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ Return an integer containing the last share curl error number */
PHP_FUNCTION(curl_share_errno)
{
zval *z_sh;
php_curlsh *sh;
ZEND_PARSE_PARAMETERS_START(1,1)
Z_PARAM_OBJECT_OF_CLASS(z_sh, curl_share_ce)
ZEND_PARSE_PARAMETERS_END();
sh = Z_CURL_SHARE_P(z_sh);
RETURN_LONG(sh->err.no);
}
/* }}} */
/* {{{ return string describing error code */
PHP_FUNCTION(curl_share_strerror)
{
zend_long code;
const char *str;
ZEND_PARSE_PARAMETERS_START(1,1)
Z_PARAM_LONG(code)
ZEND_PARSE_PARAMETERS_END();
str = curl_share_strerror(code);
if (str) {
RETURN_STRING(str);
} else {
RETURN_NULL();
}
}
/* }}} */
/* CurlShareHandle class */
static zend_object *curl_share_create_object(zend_class_entry *class_type) {
php_curlsh *intern = zend_object_alloc(sizeof(php_curlsh), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
return &intern->std;
}
static zend_function *curl_share_get_constructor(zend_object *object) {
zend_throw_error(NULL, "Cannot directly construct CurlShareHandle, use curl_share_init() instead");
return NULL;
}
void curl_share_free_obj(zend_object *object)
{
php_curlsh *sh = curl_share_from_obj(object);
curl_share_cleanup(sh->share);
zend_object_std_dtor(&sh->std);
}
static zend_object_handlers curl_share_handlers;
void curl_share_register_handlers(void) {
curl_share_ce->create_object = curl_share_create_object;
curl_share_ce->default_object_handlers = &curl_share_handlers;
memcpy(&curl_share_handlers, &std_object_handlers, sizeof(zend_object_handlers));
curl_share_handlers.offset = XtOffsetOf(php_curlsh, std);
curl_share_handlers.free_obj = curl_share_free_obj;
curl_share_handlers.get_constructor = curl_share_get_constructor;
curl_share_handlers.clone_obj = NULL;
curl_share_handlers.compare = zend_objects_not_comparable;
}
| 4,533 | 25.057471 | 112 |
c
|
php-src
|
php-src-master/ext/date/lib/astro.h
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2019 Derick Rethans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* This macro computes the length of the day, from sunrise to sunset. */
/* Sunrise/set is considered to occur when the Sun's upper limb is */
/* 35 arc minutes below the horizon (this accounts for the refraction */
/* of the Earth's atmosphere). */
#define day_length(year,month,day,lon,lat) \
__daylen__( year, month, day, lon, lat, -35.0/60.0, 1 )
/* This macro computes the length of the day, including civil twilight. */
/* Civil twilight starts/ends when the Sun's center is 6 degrees below */
/* the horizon. */
#define day_civil_twilight_length(year,month,day,lon,lat) \
__daylen__( year, month, day, lon, lat, -6.0, 0 )
/* This macro computes the length of the day, incl. nautical twilight. */
/* Nautical twilight starts/ends when the Sun's center is 12 degrees */
/* below the horizon. */
#define day_nautical_twilight_length(year,month,day,lon,lat) \
__daylen__( year, month, day, lon, lat, -12.0, 0 )
/* This macro computes the length of the day, incl. astronomical twilight. */
/* Astronomical twilight starts/ends when the Sun's center is 18 degrees */
/* below the horizon. */
#define day_astronomical_twilight_length(year,month,day,lon,lat) \
__daylen__( year, month, day, lon, lat, -18.0, 0 )
/* This macro computes times for sunrise/sunset. */
/* Sunrise/set is considered to occur when the Sun's upper limb is */
/* 35 arc minutes below the horizon (this accounts for the refraction */
/* of the Earth's atmosphere). */
#define timelib_astro_sun_rise_set(ts,lon,lat,hrise,hset,rise,set) \
timelib_astro_rise_set_altitude( ts, lon, lat, -35.0/60.0, 1, hrise, hset, rise, set )
/* This macro computes the start and end times of civil twilight. */
/* Civil twilight starts/ends when the Sun's center is 6 degrees below */
/* the horizon. */
#define civil_twilight(ts,lon,lat,start,end) \
timelib_astro_rise_set_altitude( ts, lon, lat, -6.0, 0, start, end )
/* This macro computes the start and end times of nautical twilight. */
/* Nautical twilight starts/ends when the Sun's center is 12 degrees */
/* below the horizon. */
#define nautical_twilight(ts,lon,lat,start,end) \
timelib_astro_rise_set_altitude( ts, lon, lat, -12.0, 0, start, end )
/* This macro computes the start and end times of astronomical twilight. */
/* Astronomical twilight starts/ends when the Sun's center is 18 degrees */
/* below the horizon. */
#define astronomical_twilight(ts,lon,lat,start,end) \
timelib_astro_rise_set_altitude( ts, lon, lat, -18.0, 0, start, end )
| 4,144 | 54.266667 | 94 |
h
|
php-src
|
php-src-master/ext/date/lib/dow.c
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2019 Derick Rethans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "timelib.h"
#include "timelib_private.h"
static int m_table_common[13] = { -1, 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }; /* 1 = jan */
static int m_table_leap[13] = { -1, 6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }; /* 1 = jan */
static timelib_sll positive_mod(timelib_sll x, timelib_sll y)
{
timelib_sll tmp;
tmp = x % y;
if (tmp < 0) {
tmp += y;
}
return tmp;
}
static timelib_sll century_value(timelib_sll j)
{
return 6 - positive_mod(j, 4) * 2;
}
static timelib_sll timelib_day_of_week_ex(timelib_sll y, timelib_sll m, timelib_sll d, int iso)
{
timelib_sll c1, y1, m1, dow;
/* Only valid for Gregorian calendar, commented out as we don't handle
* Julian calendar. We just return the 'wrong' day of week to be
* consistent. */
c1 = century_value(positive_mod(y, 400) / 100);
y1 = positive_mod(y, 100);
m1 = timelib_is_leap(y) ? m_table_leap[m] : m_table_common[m];
dow = positive_mod((c1 + y1 + m1 + (y1 / 4) + d), 7);
if (iso) {
if (dow == 0) {
dow = 7;
}
}
return dow;
}
timelib_sll timelib_day_of_week(timelib_sll y, timelib_sll m, timelib_sll d)
{
return timelib_day_of_week_ex(y, m, d, 0);
}
timelib_sll timelib_iso_day_of_week(timelib_sll y, timelib_sll m, timelib_sll d)
{
return timelib_day_of_week_ex(y, m, d, 1);
}
/* jan feb mar apr may jun jul aug sep oct nov dec */
static int d_table_common[13] = { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
static int d_table_leap[13] = { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
static int ml_table_common[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static int ml_table_leap[13] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
timelib_sll timelib_day_of_year(timelib_sll y, timelib_sll m, timelib_sll d)
{
return (timelib_is_leap(y) ? d_table_leap[m] : d_table_common[m]) + d - 1;
}
timelib_sll timelib_days_in_month(timelib_sll y, timelib_sll m)
{
return timelib_is_leap(y) ? ml_table_leap[m] : ml_table_common[m];
}
void timelib_isoweek_from_date(timelib_sll y, timelib_sll m, timelib_sll d, timelib_sll *iw, timelib_sll *iy)
{
int y_leap, prev_y_leap, doy, jan1weekday, weekday;
y_leap = timelib_is_leap(y);
prev_y_leap = timelib_is_leap(y-1);
doy = timelib_day_of_year(y, m, d) + 1;
if (y_leap && m > 2) {
doy++;
}
jan1weekday = timelib_day_of_week(y, 1, 1);
weekday = timelib_day_of_week(y, m, d);
if (weekday == 0) weekday = 7;
if (jan1weekday == 0) jan1weekday = 7;
/* Find if Y M D falls in YearNumber Y-1, WeekNumber 52 or 53 */
if (doy <= (8 - jan1weekday) && jan1weekday > 4) {
*iy = y - 1;
if (jan1weekday == 5 || (jan1weekday == 6 && prev_y_leap)) {
*iw = 53;
} else {
*iw = 52;
}
} else {
*iy = y;
}
/* 8. Find if Y M D falls in YearNumber Y+1, WeekNumber 1 */
if (*iy == y) {
int i;
i = y_leap ? 366 : 365;
if ((i - (doy - y_leap)) < (4 - weekday)) {
*iy = y + 1;
*iw = 1;
return;
}
}
/* 9. Find if Y M D falls in YearNumber Y, WeekNumber 1 through 53 */
if (*iy == y) {
int j;
j = doy + (7 - weekday) + (jan1weekday - 1);
*iw = j / 7;
if (jan1weekday > 4) {
*iw -= 1;
}
}
}
void timelib_isodate_from_date(timelib_sll y, timelib_sll m, timelib_sll d, timelib_sll *iy, timelib_sll *iw, timelib_sll *id)
{
timelib_isoweek_from_date(y, m, d, iw, iy);
*id = timelib_day_of_week_ex(y, m, d, 1);
}
timelib_sll timelib_daynr_from_weeknr(timelib_sll iy, timelib_sll iw, timelib_sll id)
{
timelib_sll dow, day;
/* Figure out the dayofweek for y-1-1 */
dow = timelib_day_of_week(iy, 1, 1);
/* then use that to figure out the offset for day 1 of week 1 */
day = 0 - (dow > 4 ? dow - 7 : dow);
/* Add weeks and days */
return day + ((iw - 1) * 7) + id;
}
void timelib_date_from_isodate(timelib_sll iy, timelib_sll iw, timelib_sll id, timelib_sll *y, timelib_sll *m, timelib_sll *d)
{
timelib_sll daynr = timelib_daynr_from_weeknr(iy, iw, id) + 1;
int *table;
bool is_leap_year;
// Invariant: is_leap_year == timelib_is_leap(*y)
*y = iy;
is_leap_year = timelib_is_leap(*y);
// Establish invariant that daynr >= 0
while (daynr <= 0) {
*y -= 1;
daynr += (is_leap_year = timelib_is_leap(*y)) ? 366 : 365;
}
// Establish invariant that daynr <= number of days in *yr
while (daynr > (is_leap_year ? 366 : 365)) {
daynr -= is_leap_year ? 366 : 365;
*y += 1;
is_leap_year = timelib_is_leap(*y);
}
table = is_leap_year ? ml_table_leap : ml_table_common;
// Establish invariant that daynr <= number of days in *m
*m = 1;
while (daynr > table[*m]) {
daynr -= table[*m];
*m += 1;
}
*d = daynr;
}
int timelib_valid_time(timelib_sll h, timelib_sll i, timelib_sll s)
{
if (h < 0 || h > 23 || i < 0 || i > 59 || s < 0 || s > 59) {
return 0;
}
return 1;
}
int timelib_valid_date(timelib_sll y, timelib_sll m, timelib_sll d)
{
if (m < 1 || m > 12 || d < 1 || d > timelib_days_in_month(y, m)) {
return 0;
}
return 1;
}
#if 0
int main(void)
{
printf("dow = %d\n", timelib_day_of_week(1978, 12, 22)); /* 5 */
printf("dow = %d\n", timelib_day_of_week(2005, 2, 19)); /* 6 */
}
#endif
| 6,307 | 28.069124 | 126 |
c
|
php-src
|
php-src-master/ext/date/lib/fallbackmap.h
|
{ "sst", 0, -660 * 60, "Pacific/Apia" },
{ "hst", 0, -600 * 60, "Pacific/Honolulu" },
{ "akst", 0, -540 * 60, "America/Anchorage" },
{ "akdt", 1, -480 * 60, "America/Anchorage" },
{ "pst", 0, -480 * 60, "America/Los_Angeles" },
{ "pdt", 1, -420 * 60, "America/Los_Angeles" },
{ "mst", 0, -420 * 60, "America/Denver" },
{ "mdt", 1, -360 * 60, "America/Denver" },
{ "cst", 0, -360 * 60, "America/Chicago" },
{ "cdt", 1, -300 * 60, "America/Chicago" },
{ "est", 0, -300 * 60, "America/New_York" },
{ "vet", 0, -270 * 60, "America/Caracas" },
{ "edt", 1, -240 * 60, "America/New_York" },
{ "ast", 0, -240 * 60, "America/Halifax" },
{ "adt", 1, -180 * 60, "America/Halifax" },
{ "brt", 0, -180 * 60, "America/Sao_Paulo" },
{ "brst", 1, -120 * 60, "America/Sao_Paulo" },
{ "azost", 0, -60 * 60, "Atlantic/Azores" },
{ "azodt", 1, 0 * 60, "Atlantic/Azores" },
{ "gmt", 0, 0 * 60, "Europe/London" },
{ "bst", 1, 60 * 60, "Europe/London" },
{ "cet", 0, 60 * 60, "Europe/Paris" },
{ "cest", 1, 120 * 60, "Europe/Paris" },
{ "eet", 0, 120 * 60, "Europe/Helsinki" },
{ "eest", 1, 180 * 60, "Europe/Helsinki" },
{ "msk", 0, 180 * 60, "Europe/Moscow" },
{ "msd", 1, 240 * 60, "Europe/Moscow" },
{ "gst", 0, 240 * 60, "Asia/Dubai" },
{ "pkt", 0, 300 * 60, "Asia/Karachi" },
{ "ist", 0, 330 * 60, "Asia/Kolkata" },
{ "npt", 0, 345 * 60, "Asia/Katmandu" },
{ "yekt", 1, 360 * 60, "Asia/Yekaterinburg" },
{ "novst", 1, 420 * 60, "Asia/Novosibirsk" },
{ "krat", 0, 420 * 60, "Asia/Krasnoyarsk" },
{ "cst", 0, 480 * 60, "Asia/Shanghai" },
{ "krast", 1, 480 * 60, "Asia/Krasnoyarsk" },
{ "jst", 0, 540 * 60, "Asia/Tokyo" },
{ "est", 0, 600 * 60, "Australia/Melbourne" },
{ "cst", 1, 630 * 60, "Australia/Adelaide" },
{ "est", 1, 660 * 60, "Australia/Melbourne" },
{ "nzst", 0, 720 * 60, "Pacific/Auckland" },
{ "nzdt", 1, 780 * 60, "Pacific/Auckland" },
| 1,973 | 44.906977 | 50 |
h
|
php-src
|
php-src-master/ext/date/lib/parse_iso_intervals.c
|
/* Generated by re2c 0.15.3 on Wed Sep 14 16:32:05 2022 */
#line 1 "ext/date/lib/parse_iso_intervals.re"
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2019 Derick Rethans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "timelib.h"
#include "timelib_private.h"
#include <ctype.h>
#if defined(_MSC_VER)
# define strtoll(s, f, b) _atoi64(s)
#elif !defined(HAVE_STRTOLL)
# if defined(HAVE_ATOLL)
# define strtoll(s, f, b) atoll(s)
# else
# define strtoll(s, f, b) strtol(s, f, b)
# endif
#endif
#define EOI 257
#define TIMELIB_PERIOD 260
#define TIMELIB_ISO_DATE 261
#define TIMELIB_ERROR 999
typedef unsigned char uchar;
#define BSIZE 8192
#define YYCTYPE uchar
#define YYCURSOR cursor
#define YYLIMIT s->lim
#define YYMARKER s->ptr
#define YYFILL(n) return EOI;
#define RET(i) {s->cur = cursor; return i;}
#define timelib_string_free timelib_free
#define TIMELIB_INIT s->cur = cursor; str = timelib_string(s); ptr = str
#define TIMELIB_DEINIT timelib_string_free(str)
#ifdef DEBUG_PARSER
#define DEBUG_OUTPUT(s) printf("%s\n", s);
#define YYDEBUG(s,c) { if (s != -1) { printf("state: %d ", s); printf("[%c]\n", c); } }
#else
#define DEBUG_OUTPUT(s)
#define YYDEBUG(s,c)
#endif
typedef struct _Scanner {
int fd;
uchar *lim, *str, *ptr, *cur, *tok, *pos;
unsigned int line, len;
timelib_error_container *errors;
timelib_time *begin;
timelib_time *end;
timelib_rel_time *period;
int recurrences;
int have_period;
int have_recurrences;
int have_date;
int have_begin_date;
int have_end_date;
} Scanner;
static void add_error(Scanner *s, const char *error)
{
s->errors->error_count++;
s->errors->error_messages = timelib_realloc(s->errors->error_messages, s->errors->error_count * sizeof(timelib_error_message));
s->errors->error_messages[s->errors->error_count - 1].position = s->tok ? s->tok - s->str : 0;
s->errors->error_messages[s->errors->error_count - 1].character = s->tok ? *s->tok : 0;
s->errors->error_messages[s->errors->error_count - 1].message = timelib_strdup(error);
}
static char *timelib_string(Scanner *s)
{
char *tmp = timelib_calloc(1, s->cur - s->tok + 1);
memcpy(tmp, s->tok, s->cur - s->tok);
return tmp;
}
static timelib_sll timelib_get_nr(const char **ptr, int max_length)
{
const char *begin, *end;
char *str;
timelib_sll tmp_nr = TIMELIB_UNSET;
int len = 0;
while ((**ptr < '0') || (**ptr > '9')) {
if (**ptr == '\0') {
return TIMELIB_UNSET;
}
++*ptr;
}
begin = *ptr;
while ((**ptr >= '0') && (**ptr <= '9') && len < max_length) {
++*ptr;
++len;
}
end = *ptr;
str = timelib_calloc(1, end - begin + 1);
memcpy(str, begin, end - begin);
tmp_nr = strtoll(str, NULL, 10);
timelib_free(str);
return tmp_nr;
}
static timelib_ull timelib_get_unsigned_nr(const char **ptr, int max_length)
{
timelib_ull dir = 1;
while (((**ptr < '0') || (**ptr > '9')) && (**ptr != '+') && (**ptr != '-')) {
if (**ptr == '\0') {
return TIMELIB_UNSET;
}
++*ptr;
}
while (**ptr == '+' || **ptr == '-')
{
if (**ptr == '-') {
dir *= -1;
}
++*ptr;
}
return dir * timelib_get_nr(ptr, max_length);
}
#define timelib_split_free(arg) { \
int i; \
for (i = 0; i < arg.c; i++) { \
timelib_free(arg.v[i]); \
} \
if (arg.v) { \
timelib_free(arg.v); \
} \
}
/* date parser's scan function too large for VC6 - VC7.x
drop the optimization solves the problem */
#ifdef PHP_WIN32
#pragma optimize( "", off )
#endif
static int scan(Scanner *s)
{
uchar *cursor = s->cur;
char *str;
const char *ptr = NULL;
std:
s->tok = cursor;
s->len = 0;
#line 204 "ext/date/lib/parse_iso_intervals.re"
#line 184 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept = 0;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
YYDEBUG(0, *YYCURSOR);
if ((YYLIMIT - YYCURSOR) < 20) YYFILL(20);
yych = *YYCURSOR;
if (yych <= ',') {
if (yych <= '\n') {
if (yych <= 0x00) goto yy9;
if (yych <= 0x08) goto yy11;
if (yych <= '\t') goto yy7;
goto yy9;
} else {
if (yych == ' ') goto yy7;
if (yych <= '+') goto yy11;
goto yy7;
}
} else {
if (yych <= 'O') {
if (yych <= '-') goto yy11;
if (yych <= '/') goto yy7;
if (yych <= '9') goto yy4;
goto yy11;
} else {
if (yych <= 'P') goto yy5;
if (yych != 'R') goto yy11;
}
}
YYDEBUG(2, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '/') goto yy3;
if (yych <= '9') goto yy98;
yy3:
YYDEBUG(3, *YYCURSOR);
#line 317 "ext/date/lib/parse_iso_intervals.re"
{
add_error(s, "Unexpected character");
goto std;
}
#line 258 "<stdout>"
yy4:
YYDEBUG(4, *YYCURSOR);
yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy3;
if (yych <= '9') goto yy59;
goto yy3;
yy5:
YYDEBUG(5, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy12;
if (yych == 'T') goto yy14;
yy6:
YYDEBUG(6, *YYCURSOR);
#line 244 "ext/date/lib/parse_iso_intervals.re"
{
timelib_sll nr;
int in_time = 0;
DEBUG_OUTPUT("period");
TIMELIB_INIT;
ptr++;
do {
if ( *ptr == 'T' ) {
in_time = 1;
ptr++;
}
if ( *ptr == '\0' ) {
add_error(s, "Missing expected time part");
break;
}
nr = timelib_get_unsigned_nr(&ptr, 12);
switch (*ptr) {
case 'Y': s->period->y = nr; break;
case 'W': s->period->d += nr * 7; break;
case 'D': s->period->d += nr; break;
case 'H': s->period->h = nr; break;
case 'S': s->period->s = nr; break;
case 'M':
if (in_time) {
s->period->i = nr;
} else {
s->period->m = nr;
}
break;
default:
add_error(s, "Undefined period specifier");
break;
}
ptr++;
} while (!s->errors->error_count && *ptr);
s->have_period = 1;
TIMELIB_DEINIT;
return TIMELIB_PERIOD;
}
#line 316 "<stdout>"
yy7:
YYDEBUG(7, *YYCURSOR);
++YYCURSOR;
YYDEBUG(8, *YYCURSOR);
#line 306 "ext/date/lib/parse_iso_intervals.re"
{
goto std;
}
#line 325 "<stdout>"
yy9:
YYDEBUG(9, *YYCURSOR);
++YYCURSOR;
YYDEBUG(10, *YYCURSOR);
#line 311 "ext/date/lib/parse_iso_intervals.re"
{
s->pos = cursor; s->line++;
goto std;
}
#line 335 "<stdout>"
yy11:
YYDEBUG(11, *YYCURSOR);
yych = *++YYCURSOR;
goto yy3;
yy12:
YYDEBUG(12, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych >= '0') goto yy25;
} else {
if (yych == 'D') goto yy24;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych >= 'W') goto yy26;
} else {
if (yych == 'Y') goto yy28;
}
}
yy13:
YYDEBUG(13, *YYCURSOR);
YYCURSOR = YYMARKER;
if (yyaccept == 0) {
goto yy3;
} else {
goto yy6;
}
yy14:
YYDEBUG(14, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy15;
}
goto yy6;
yy15:
YYDEBUG(15, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(16, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy15;
}
if (yych <= 'L') {
if (yych == 'H') goto yy19;
goto yy13;
} else {
if (yych <= 'M') goto yy18;
if (yych != 'S') goto yy13;
}
yy17:
YYDEBUG(17, *YYCURSOR);
yych = *++YYCURSOR;
goto yy6;
yy18:
YYDEBUG(18, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy22;
goto yy6;
yy19:
YYDEBUG(19, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych >= ':') goto yy6;
yy20:
YYDEBUG(20, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(21, *YYCURSOR);
if (yych <= 'L') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy20;
goto yy13;
} else {
if (yych <= 'M') goto yy18;
if (yych == 'S') goto yy17;
goto yy13;
}
yy22:
YYDEBUG(22, *YYCURSOR);
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(23, *YYCURSOR);
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy22;
if (yych == 'S') goto yy17;
goto yy13;
yy24:
YYDEBUG(24, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy14;
goto yy6;
yy25:
YYDEBUG(25, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
goto yy35;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
yy26:
YYDEBUG(26, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy33;
if (yych == 'T') goto yy14;
goto yy6;
yy27:
YYDEBUG(27, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy31;
if (yych == 'T') goto yy14;
goto yy6;
yy28:
YYDEBUG(28, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy29;
if (yych == 'T') goto yy14;
goto yy6;
yy29:
YYDEBUG(29, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(30, *YYCURSOR);
if (yych <= 'D') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy29;
if (yych <= 'C') goto yy13;
goto yy24;
} else {
if (yych <= 'M') {
if (yych <= 'L') goto yy13;
goto yy27;
} else {
if (yych == 'W') goto yy26;
goto yy13;
}
}
yy31:
YYDEBUG(31, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(32, *YYCURSOR);
if (yych <= 'C') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy31;
goto yy13;
} else {
if (yych <= 'D') goto yy24;
if (yych == 'W') goto yy26;
goto yy13;
}
yy33:
YYDEBUG(33, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(34, *YYCURSOR);
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy33;
if (yych == 'D') goto yy24;
goto yy13;
yy35:
YYDEBUG(35, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
goto yy26;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
YYDEBUG(36, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy39;
YYDEBUG(37, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy40;
if (yych <= '1') goto yy41;
goto yy13;
yy38:
YYDEBUG(38, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
yy39:
YYDEBUG(39, *YYCURSOR);
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
goto yy38;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
goto yy26;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
yy40:
YYDEBUG(40, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy42;
goto yy13;
yy41:
YYDEBUG(41, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '3') goto yy13;
yy42:
YYDEBUG(42, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy13;
YYDEBUG(43, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy44;
if (yych <= '2') goto yy45;
if (yych <= '3') goto yy46;
goto yy13;
yy44:
YYDEBUG(44, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy47;
goto yy13;
yy45:
YYDEBUG(45, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy47;
goto yy13;
yy46:
YYDEBUG(46, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy47:
YYDEBUG(47, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(48, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy49;
if (yych <= '2') goto yy50;
goto yy13;
yy49:
YYDEBUG(49, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy51;
goto yy13;
yy50:
YYDEBUG(50, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy51:
YYDEBUG(51, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(52, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(53, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(54, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(55, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(56, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(57, *YYCURSOR);
++YYCURSOR;
YYDEBUG(58, *YYCURSOR);
#line 286 "ext/date/lib/parse_iso_intervals.re"
{
DEBUG_OUTPUT("combinedrep");
TIMELIB_INIT;
s->period->y = timelib_get_unsigned_nr(&ptr, 4);
ptr++;
s->period->m = timelib_get_unsigned_nr(&ptr, 2);
ptr++;
s->period->d = timelib_get_unsigned_nr(&ptr, 2);
ptr++;
s->period->h = timelib_get_unsigned_nr(&ptr, 2);
ptr++;
s->period->i = timelib_get_unsigned_nr(&ptr, 2);
ptr++;
s->period->s = timelib_get_unsigned_nr(&ptr, 2);
s->have_period = 1;
TIMELIB_DEINIT;
return TIMELIB_PERIOD;
}
#line 684 "<stdout>"
yy59:
YYDEBUG(59, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(60, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(61, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '-') goto yy64;
goto yy13;
} else {
if (yych <= '0') goto yy62;
if (yych <= '1') goto yy63;
goto yy13;
}
yy62:
YYDEBUG(62, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy85;
goto yy13;
yy63:
YYDEBUG(63, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '2') goto yy85;
goto yy13;
yy64:
YYDEBUG(64, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy65;
if (yych <= '1') goto yy66;
goto yy13;
yy65:
YYDEBUG(65, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy67;
goto yy13;
yy66:
YYDEBUG(66, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '3') goto yy13;
yy67:
YYDEBUG(67, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy13;
YYDEBUG(68, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy69;
if (yych <= '2') goto yy70;
if (yych <= '3') goto yy71;
goto yy13;
yy69:
YYDEBUG(69, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy72;
goto yy13;
yy70:
YYDEBUG(70, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy72;
goto yy13;
yy71:
YYDEBUG(71, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy72:
YYDEBUG(72, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(73, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy74;
if (yych <= '2') goto yy75;
goto yy13;
yy74:
YYDEBUG(74, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy76;
goto yy13;
yy75:
YYDEBUG(75, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy76:
YYDEBUG(76, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(77, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(78, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(79, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(80, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(81, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(82, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'Z') goto yy13;
yy83:
YYDEBUG(83, *YYCURSOR);
++YYCURSOR;
YYDEBUG(84, *YYCURSOR);
#line 220 "ext/date/lib/parse_iso_intervals.re"
{
timelib_time *current;
if (s->have_date || s->have_period) {
current = s->end;
s->have_end_date = 1;
} else {
current = s->begin;
s->have_begin_date = 1;
}
DEBUG_OUTPUT("datetimebasic | datetimeextended");
TIMELIB_INIT;
current->y = timelib_get_nr(&ptr, 4);
current->m = timelib_get_nr(&ptr, 2);
current->d = timelib_get_nr(&ptr, 2);
current->h = timelib_get_nr(&ptr, 2);
current->i = timelib_get_nr(&ptr, 2);
current->s = timelib_get_nr(&ptr, 2);
s->have_date = 1;
TIMELIB_DEINIT;
return TIMELIB_ISO_DATE;
}
#line 836 "<stdout>"
yy85:
YYDEBUG(85, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy86;
if (yych <= '2') goto yy87;
if (yych <= '3') goto yy88;
goto yy13;
yy86:
YYDEBUG(86, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy89;
goto yy13;
yy87:
YYDEBUG(87, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy89;
goto yy13;
yy88:
YYDEBUG(88, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy89:
YYDEBUG(89, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(90, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy91;
if (yych <= '2') goto yy92;
goto yy13;
yy91:
YYDEBUG(91, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy93;
goto yy13;
yy92:
YYDEBUG(92, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy93:
YYDEBUG(93, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(94, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(95, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(96, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(97, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Z') goto yy83;
goto yy13;
yy98:
YYDEBUG(98, *YYCURSOR);
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(99, *YYCURSOR);
if (yych <= '/') goto yy100;
if (yych <= '9') goto yy98;
yy100:
YYDEBUG(100, *YYCURSOR);
#line 209 "ext/date/lib/parse_iso_intervals.re"
{
DEBUG_OUTPUT("recurrences");
TIMELIB_INIT;
ptr++;
s->recurrences = timelib_get_unsigned_nr(&ptr, 9);
TIMELIB_DEINIT;
s->have_recurrences = 1;
return TIMELIB_PERIOD;
}
#line 924 "<stdout>"
}
#line 321 "ext/date/lib/parse_iso_intervals.re"
}
#ifdef PHP_WIN32
#pragma optimize( "", on )
#endif
#define YYMAXFILL 20
void timelib_strtointerval(const char *s, size_t len,
timelib_time **begin, timelib_time **end,
timelib_rel_time **period, int *recurrences,
timelib_error_container **errors)
{
Scanner in;
int t;
const char *e = s + len - 1;
memset(&in, 0, sizeof(in));
in.errors = timelib_malloc(sizeof(timelib_error_container));
in.errors->warning_count = 0;
in.errors->warning_messages = NULL;
in.errors->error_count = 0;
in.errors->error_messages = NULL;
if (len > 0) {
while (isspace(*s) && s < e) {
s++;
}
while (isspace(*e) && e > s) {
e--;
}
}
if (e - s < 0) {
add_error(&in, "Empty string");
if (errors) {
*errors = in.errors;
} else {
timelib_error_container_dtor(in.errors);
}
return;
}
e++;
/* init cursor */
in.str = timelib_malloc((e - s) + YYMAXFILL);
memset(in.str, 0, (e - s) + YYMAXFILL);
memcpy(in.str, s, (e - s));
in.lim = in.str + (e - s) + YYMAXFILL;
in.cur = in.str;
/* init value containers */
in.begin = timelib_time_ctor();
in.begin->y = TIMELIB_UNSET;
in.begin->d = TIMELIB_UNSET;
in.begin->m = TIMELIB_UNSET;
in.begin->h = TIMELIB_UNSET;
in.begin->i = TIMELIB_UNSET;
in.begin->s = TIMELIB_UNSET;
in.begin->us = 0;
in.begin->z = 0;
in.begin->dst = 0;
in.begin->is_localtime = 0;
in.begin->zone_type = TIMELIB_ZONETYPE_OFFSET;
in.end = timelib_time_ctor();
in.end->y = TIMELIB_UNSET;
in.end->d = TIMELIB_UNSET;
in.end->m = TIMELIB_UNSET;
in.end->h = TIMELIB_UNSET;
in.end->i = TIMELIB_UNSET;
in.end->s = TIMELIB_UNSET;
in.end->us = 0;
in.end->z = 0;
in.end->dst = 0;
in.end->is_localtime = 0;
in.end->zone_type = TIMELIB_ZONETYPE_OFFSET;
in.period = timelib_rel_time_ctor();
in.period->y = 0;
in.period->d = 0;
in.period->m = 0;
in.period->h = 0;
in.period->i = 0;
in.period->s = 0;
in.period->weekday = 0;
in.period->weekday_behavior = 0;
in.period->first_last_day_of = 0;
in.period->days = TIMELIB_UNSET;
in.recurrences = 1;
do {
t = scan(&in);
#ifdef DEBUG_PARSER
printf("%d\n", t);
#endif
} while(t != EOI);
timelib_free(in.str);
if (errors) {
*errors = in.errors;
} else {
timelib_error_container_dtor(in.errors);
}
if (in.have_begin_date) {
*begin = in.begin;
} else {
timelib_time_dtor(in.begin);
}
if (in.have_end_date) {
*end = in.end;
} else {
timelib_time_dtor(in.end);
}
if (in.have_period) {
*period = in.period;
} else {
timelib_rel_time_dtor(in.period);
}
if (in.have_recurrences) {
*recurrences = in.recurrences;
}
}
/*
* vim: syntax=c
*/
| 24,024 | 21.794118 | 128 |
c
|
php-src
|
php-src-master/ext/date/lib/parse_posix.c
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 MongoDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "timelib.h"
#include "timelib_private.h"
// This section adds the missing 'strndup' implementation on Windows.
#if TIMELIB_USE_BUILTIN_STRNDUP == 1
# include <stdlib.h>
# include <string.h>
/**
* char* timelib_strndup(const char* s, size_t n)
*
* Returns a pointer to a copy of 's' with at most 'n' characters
* in memory obtained from 'malloc', or 'NULL' if insufficient
* memory was available. The result is always 'NULL' terminated.
*/
static char* timelib_strndup(const char* s, size_t n)
{
char* result;
size_t len = strlen(s);
if (n < len) {
len = n;
}
result = (char*)malloc(len + 1);
if (!result) {
return 0;
}
result[len] = '\0';
return (char*)memcpy(result, s, len);
}
#endif
/* Forwards declrations */
static timelib_posix_trans_info *timelib_posix_trans_info_ctor(void);
static void timelib_posix_trans_info_dtor(timelib_posix_trans_info* ts);
/* "<" [+-]? .+? ">" */
static char *read_description_numeric_abbr(char **ptr)
{
const char *begin = *ptr + 1;
// skip '<'
(*ptr)++;
while (**ptr != '\0' && **ptr != '>') {
(*ptr)++;
}
if (**ptr == '\0') {
return NULL;
}
if (**ptr == '>') {
(*ptr)++;
}
// Abbreviation may not be empty
if (*ptr - begin - 1 < 1) {
return NULL;
}
return timelib_strndup(begin, *ptr - begin - 1);
}
/* [A-Z]+ */
static char *read_description_abbr(char **ptr)
{
const char *begin = *ptr;
// Find the end
while ((**ptr >= 'A' && **ptr <= 'Z') || (**ptr >= 'a' && **ptr <= 'z')) {
(*ptr)++;
}
// Abbreviation may not be empty
if (*ptr - begin < 1) {
return NULL;
}
return timelib_strndup(begin, *ptr - begin);
}
/* "<" [+-]? .+? ">" | [A-Z]+ */
static char *read_description(char **ptr)
{
if (**ptr == '<') {
return read_description_numeric_abbr(ptr);
} else {
return read_description_abbr(ptr);
}
}
/* [+-]? */
static int read_sign(char **ptr)
{
int bias = 1;
if (**ptr == '+') {
(*ptr)++;
} else if (**ptr == '-') {
bias = -1;
(*ptr)++;
}
return bias;
}
/* [0-9]+ */
static timelib_sll read_number(char **ptr)
{
const char *begin = *ptr;
int acc = 0;
// skip leading 0's
while (**ptr == '0') {
(*ptr)++;
}
while (**ptr >= '0' && **ptr <= '9') {
acc = acc * 10;
acc += (**ptr) - '0';
(*ptr)++;
}
if (begin == *ptr) {
return TIMELIB_UNSET;
}
return acc;
}
/* [+-]? [0-9]+ ( ":" [0-9]+ ( ":" [0-9]+ )? )? */
static timelib_sll read_offset(char **ptr)
{
const char *begin;
int bias = read_sign(ptr);
int hours = 0;
int minutes = 0;
int seconds = 0;
begin = *ptr;
// read through to : or non-digit for hours
hours = read_number(ptr);
if (hours == TIMELIB_UNSET) {
return hours;
}
// check for optional minutes
if (**ptr == ':') {
(*ptr)++; // skip ':'
minutes = read_number(ptr);
if (minutes == TIMELIB_UNSET) {
return minutes;
}
}
// check for optional seconds
if (**ptr == ':') {
(*ptr)++; // skip ':'
seconds = read_number(ptr);
if (seconds == TIMELIB_UNSET) {
return seconds;
}
}
if (begin == *ptr) {
return TIMELIB_UNSET;
}
// multiplication with -1, because the offset in the identifier is the
// 'wrong' way around as for example EST5 is UTC-5 (and not +5)
return -1 * bias * (hours * 3600 + minutes * 60 + seconds);
}
// Mw.m.d
static timelib_posix_trans_info* read_trans_spec_mwd(char **ptr)
{
timelib_posix_trans_info *tmp = timelib_posix_trans_info_ctor();
tmp->type = TIMELIB_POSIX_TRANS_TYPE_MWD;
// Skip 'M'
(*ptr)++;
tmp->mwd.month = read_number(ptr);
if (tmp->mwd.month == TIMELIB_UNSET) {
goto fail;
}
// check for '.' and skip it
if (**ptr != '.') {
goto fail;
}
(*ptr)++;
tmp->mwd.week = read_number(ptr);
if (tmp->mwd.week == TIMELIB_UNSET) {
goto fail;
}
// check for '.' and skip it
if (**ptr != '.') {
goto fail;
}
(*ptr)++;
tmp->mwd.dow = read_number(ptr);
if (tmp->mwd.dow == TIMELIB_UNSET) {
goto fail;
}
return tmp;
fail:
timelib_posix_trans_info_dtor(tmp);
return NULL;
}
// (Jn | n | Mw.m.d) ( /time )?
static timelib_posix_trans_info* read_transition_spec(char **ptr)
{
timelib_posix_trans_info *tmp;
if (**ptr == 'M') {
tmp = read_trans_spec_mwd(ptr);
if (!tmp) {
return NULL;
}
} else {
tmp = timelib_posix_trans_info_ctor();
if (**ptr == 'J') {
tmp->type = TIMELIB_POSIX_TRANS_TYPE_JULIAN_NO_FEB29;
(*ptr)++;
}
tmp->days = read_number(ptr);
if (tmp->days == TIMELIB_UNSET) {
goto fail;
}
}
// Check for the optional hour
if (**ptr == '/') {
(*ptr)++;
tmp->hour = read_offset(ptr);
if (tmp->hour == TIMELIB_UNSET) {
goto fail;
}
// as the bias for normal offsets = -1, we need to reverse it here
tmp->hour = -tmp->hour;
}
return tmp;
fail:
timelib_posix_trans_info_dtor(tmp);
return NULL;
}
static timelib_posix_trans_info* timelib_posix_trans_info_ctor(void)
{
timelib_posix_trans_info *tmp;
tmp = timelib_calloc(1, sizeof(timelib_posix_trans_info));
tmp->type = TIMELIB_POSIX_TRANS_TYPE_JULIAN_FEB29;
tmp->hour = 2 * 3600;
return tmp;
}
static void timelib_posix_trans_info_dtor(timelib_posix_trans_info* ts)
{
timelib_free(ts);
}
void timelib_posix_str_dtor(timelib_posix_str *ps)
{
if (ps->std) {
timelib_free(ps->std);
}
if (ps->dst) {
timelib_free(ps->dst);
}
if (ps->dst_begin) {
timelib_posix_trans_info_dtor(ps->dst_begin);
}
if (ps->dst_end) {
timelib_posix_trans_info_dtor(ps->dst_end);
}
timelib_free(ps);
}
timelib_posix_str* timelib_parse_posix_str(const char *posix)
{
timelib_posix_str *tmp = timelib_calloc(1, sizeof(timelib_posix_str));
char *ptr = (char*) posix;
// read standard description (ie. EST or <-03>)
tmp->std = read_description(&ptr);
if (!tmp->std) {
timelib_posix_str_dtor(tmp);
return NULL;
}
// read required offset
tmp->std_offset = read_offset(&ptr);
if (tmp->std_offset == TIMELIB_UNSET) {
timelib_posix_str_dtor(tmp);
return NULL;
}
// if we're at the end return, otherwise we'll continue to try to parse
// the dst abbreviation and spec
if (*ptr == '\0') {
return tmp;
}
// assume dst is there, and initialise offset
tmp->dst_offset = tmp->std_offset + 3600;
tmp->dst = read_description(&ptr);
if (!tmp->dst) {
timelib_posix_str_dtor(tmp);
return NULL;
}
// if we have a "," here, then the dst offset is the standard offset +
// 3600 seconds, otherwise, try to parse the dst offset
if (*ptr != ',' && *ptr != '\0') {
tmp->dst_offset = read_offset(&ptr);
if (tmp->dst_offset == TIMELIB_UNSET) {
timelib_posix_str_dtor(tmp);
return NULL;
}
}
// if we *don't* have a "," here, we're missing the dst transitions
// ,start[/time],end[/time]
if (*ptr != ',') {
timelib_posix_str_dtor(tmp);
return NULL;
}
ptr++; // skip ','
// start[/time]
tmp->dst_begin = read_transition_spec(&ptr);
if (!tmp->dst_begin) {
timelib_posix_str_dtor(tmp);
return NULL;
}
// if we *don't* have a "," here, we're missing the dst end transition
// ,end[/time]
if (*ptr != ',') {
timelib_posix_str_dtor(tmp);
return NULL;
}
ptr++; // skip ','
// end[/time]
tmp->dst_end = read_transition_spec(&ptr);
if (!tmp->dst_end) {
timelib_posix_str_dtor(tmp);
return NULL;
}
// make sure there is no trailing data
if (*ptr != '\0') {
timelib_posix_str_dtor(tmp);
return NULL;
}
return tmp;
}
static const int month_lengths[2][MONTHS_PER_YEAR] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // normal year
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // leap year
};
/* This function is adapted from the 'localtime.c' function 'transtime' as bundled with the 'tzcode' project
* from IANA, and is public domain licensed. */
static timelib_sll calc_transition(timelib_posix_trans_info *psi, timelib_sll year)
{
int leap_year = timelib_is_leap(year);
switch (psi->type) {
case TIMELIB_POSIX_TRANS_TYPE_JULIAN_NO_FEB29: {
timelib_sll value = (psi->days - 1);
if (leap_year && psi->days >= 60) {
value++;
}
return value * SECS_PER_DAY;
}
case TIMELIB_POSIX_TRANS_TYPE_JULIAN_FEB29: {
return psi->days * SECS_PER_DAY;
}
case TIMELIB_POSIX_TRANS_TYPE_MWD: {
/*
* Mm.n.d - nth "dth day" of month m.
*/
int i, d, m1, yy0, yy1, yy2, dow;
timelib_sll value = 0;
/* Use Zeller's Congruence to get day-of-week of first day of
* month. */
m1 = (psi->mwd.month + 9) % 12 + 1;
yy0 = (psi->mwd.month <= 2) ? (year - 1) : year;
yy1 = yy0 / 100;
yy2 = yy0 % 100;
dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
if (dow < 0) {
dow += DAYS_PER_WEEK;
}
/* "dow" is the day-of-week of the first day of the month. Get the
* day-of-month (zero-origin) of the first "dow" day of the month. */
d = psi->mwd.dow - dow;
if (d < 0) {
d += DAYS_PER_WEEK;
}
for (i = 1; i < psi->mwd.week; ++i) {
if (d + DAYS_PER_WEEK >= month_lengths[leap_year][psi->mwd.month - 1]) {
break;
}
d += DAYS_PER_WEEK;
}
/* "d" is the day-of-month (zero-origin) of the day we want. */
value = d * SECS_PER_DAY;
for (i = 0; i < psi->mwd.month - 1; ++i) {
value += month_lengths[leap_year][i] * SECS_PER_DAY;
}
return value;
} break;
}
return 0;
}
static timelib_sll count_leap_years(timelib_sll y)
{
/* Because we want this for Jan 1, the leap day hasn't happend yet, so
* subtract one of year before we calculate */
y--;
return (y/4) - (y/100) + (y/400);
}
timelib_sll timelib_ts_at_start_of_year(timelib_sll year)
{
timelib_sll epoch_leap_years = count_leap_years(1970);
timelib_sll current_leap_years = count_leap_years(year);
return SECS_PER_DAY * (
((year-1970) * DAYS_PER_YEAR)
+ current_leap_years
- epoch_leap_years
);
}
void timelib_get_transitions_for_year(timelib_tzinfo *tz, timelib_sll year, timelib_posix_transitions *transitions)
{
timelib_sll trans_begin; /* Since start of the year */
timelib_sll trans_end;
timelib_sll year_begin_ts = timelib_ts_at_start_of_year(year);
trans_begin = year_begin_ts;
trans_begin += calc_transition(tz->posix_info->dst_begin, year);
trans_begin += tz->posix_info->dst_begin->hour;
trans_begin -= tz->posix_info->std_offset;
trans_end = year_begin_ts;
trans_end += calc_transition(tz->posix_info->dst_end, year);
trans_end += tz->posix_info->dst_end->hour;
trans_end -= tz->posix_info->dst_offset;
if (trans_begin < trans_end) {
transitions->times[transitions->count ] = trans_begin;
transitions->times[transitions->count+1] = trans_end;
transitions->types[transitions->count ] = tz->posix_info->type_index_dst_type;
transitions->types[transitions->count+1] = tz->posix_info->type_index_std_type;
} else {
transitions->times[transitions->count+1] = trans_begin;
transitions->times[transitions->count ] = trans_end;
transitions->types[transitions->count+1] = tz->posix_info->type_index_dst_type;
transitions->types[transitions->count ] = tz->posix_info->type_index_std_type;
}
transitions->count += 2;
}
ttinfo* timelib_fetch_posix_timezone_offset(timelib_tzinfo *tz, timelib_sll ts, timelib_sll *transition_time)
{
timelib_sll year;
timelib_time dummy;
timelib_posix_transitions transitions = { 0 };
size_t i;
/* If there is no second (dst_end) information, the UTC offset is valid for the whole year, so no need to
* do clever logic */
if (!tz->posix_info->dst_end) {
if (transition_time) {
*transition_time = tz->trans[tz->bit64.timecnt - 1];
}
return &(tz->type[tz->posix_info->type_index_std_type]);
}
/* Find 'year' (UTC) for 'ts' */
timelib_unixtime2gmt(&dummy, ts);
year = dummy.y;
/* Calculate transition times for 'year-1', 'year', and 'year+1' */
timelib_get_transitions_for_year(tz, year - 1, &transitions);
timelib_get_transitions_for_year(tz, year, &transitions);
timelib_get_transitions_for_year(tz, year + 1, &transitions);
/* Check where the 'ts' falls in the 4 transitions */
for (i = 1; i < transitions.count; i++) {
if (ts < transitions.times[i]) {
if (transition_time) {
*transition_time = transitions.times[i - 1];
}
return &(tz->type[transitions.types[i - 1]]);
}
}
return NULL;
}
| 13,283 | 22.387324 | 115 |
c
|
php-src
|
php-src-master/ext/date/lib/timelib.c
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2019 Derick Rethans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Portions copyright (c) 1998-2017 Zend Technologies Ltd.
*
* The timelib_strcasecmp and timelib_strncasecmp are taken from PHP's
* Zend/zend_operators.[hc] source files.
*
*/
#include "timelib.h"
#include "timelib_private.h"
#include <ctype.h>
#include <math.h>
#define TIMELIB_LLABS(y) (y < 0 ? (y * -1) : y)
const char *timelib_error_messages[10] = {
"No error",
"Cannot allocate buffer for parsing",
"Corrupt tzfile: The transitions in the file don't always increase",
"Corrupt tzfile: The expected 64-bit preamble is missing",
"Corrupt tzfile: No abbreviation could be found for a transition",
"The version used in this timezone identifier is unsupported",
"No timezone with this name could be found",
"A 'slim' timezone file has been detected",
"The embedded POSIX string is not valid",
"The embedded POSIX string is empty"
};
const char *timelib_get_error_message(int error_code)
{
int entries = sizeof(timelib_error_messages) / sizeof(char*);
if (error_code >= 0 && error_code < entries) {
return timelib_error_messages[error_code];
}
return "Unknown error code";
}
timelib_time* timelib_time_ctor(void)
{
timelib_time *t;
t = timelib_calloc(1, sizeof(timelib_time));
return t;
}
void timelib_time_dtor(timelib_time* t)
{
TIMELIB_TIME_FREE(t->tz_abbr);
TIMELIB_TIME_FREE(t);
}
int timelib_time_compare(timelib_time *t1, timelib_time *t2)
{
if (t1->sse == t2->sse) {
if (t1->us == t2->us) {
return 0;
}
return (t1->us < t2->us) ? -1 : 1;
}
return (t1->sse < t2->sse) ? -1 : 1;
}
timelib_time* timelib_time_clone(timelib_time *orig)
{
timelib_time *tmp = timelib_time_ctor();
memcpy(tmp, orig, sizeof(timelib_time));
if (orig->tz_abbr) {
tmp->tz_abbr = timelib_strdup(orig->tz_abbr);
}
if (orig->tz_info) {
tmp->tz_info = orig->tz_info;
}
return tmp;
}
timelib_rel_time* timelib_rel_time_ctor(void)
{
timelib_rel_time *t;
t = timelib_calloc(1, sizeof(timelib_rel_time));
return t;
}
void timelib_rel_time_dtor(timelib_rel_time* t)
{
TIMELIB_TIME_FREE(t);
}
timelib_rel_time* timelib_rel_time_clone(timelib_rel_time *rel)
{
timelib_rel_time *tmp = timelib_rel_time_ctor();
memcpy(tmp, rel, sizeof(timelib_rel_time));
return tmp;
}
void timelib_time_tz_abbr_update(timelib_time* tm, const char* tz_abbr)
{
unsigned int i;
size_t tz_abbr_len = strlen(tz_abbr);
TIMELIB_TIME_FREE(tm->tz_abbr);
tm->tz_abbr = timelib_strdup(tz_abbr);
for (i = 0; i < tz_abbr_len; i++) {
tm->tz_abbr[i] = toupper(tz_abbr[i]);
}
}
timelib_time_offset* timelib_time_offset_ctor(void)
{
timelib_time_offset *t;
t = timelib_calloc(1, sizeof(timelib_time_offset));
return t;
}
void timelib_time_offset_dtor(timelib_time_offset* t)
{
TIMELIB_TIME_FREE(t->abbr);
TIMELIB_TIME_FREE(t);
}
char *timelib_get_tz_abbr_ptr(timelib_time *t)
{
if (!t->sse_uptodate) {
timelib_update_ts(t, NULL);
};
return t->tz_abbr;
}
void timelib_error_container_dtor(timelib_error_container *errors)
{
int i;
for (i = 0; i < errors->warning_count; i++) {
timelib_free(errors->warning_messages[i].message);
}
timelib_free(errors->warning_messages);
for (i = 0; i < errors->error_count; i++) {
timelib_free(errors->error_messages[i].message);
}
timelib_free(errors->error_messages);
timelib_free(errors);
}
timelib_long timelib_date_to_int(timelib_time *d, int *error)
{
timelib_sll ts;
ts = d->sse;
if (ts < TIMELIB_LONG_MIN || ts > TIMELIB_LONG_MAX) {
if (error) {
*error = 1;
}
return 0;
}
if (error) {
*error = 0;
}
return (timelib_long) d->sse;
}
void timelib_decimal_hour_to_hms(double h, int *hour, int *min, int *sec)
{
if (h > 0) {
*hour = floor(h);
*min = floor((h - *hour) * 60);
*sec = (h - *hour - ((float) *min / 60)) * 3600;
} else {
*hour = ceil(h);
*min = 0 - ceil((h - *hour) * 60);
*sec = 0 - (h - *hour - ((float) *min / -60)) * 3600;
}
}
void timelib_hms_to_decimal_hour(int hour, int min, int sec, double *h)
{
if (hour >= 0) {
*h = ((double)hour + (double)min / 60 + (double)sec / 3600);
} else {
*h = ((double)hour - (double)min / 60 - (double)sec / 3600);
}
}
void timelib_hmsf_to_decimal_hour(int hour, int min, int sec, int us, double *h)
{
if (hour >= 0) {
*h = ((double)hour + (double)min / MINS_PER_HOUR + (double)sec / SECS_PER_HOUR) + (double)us / USECS_PER_HOUR;
} else {
*h = ((double)hour - (double)min / MINS_PER_HOUR - (double)sec / SECS_PER_HOUR) - (double)us / USECS_PER_HOUR;
}
}
timelib_sll timelib_hms_to_seconds(timelib_sll h, timelib_sll m, timelib_sll s)
{
return (h * SECS_PER_HOUR) + (m * 60) + s;
}
static const unsigned char timelib_tolower_map[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
#define timelib_tolower(c) (timelib_tolower_map[(unsigned char)(c)])
#undef MIN
#undef MAX
#define MAX(a, b) (((a)>(b))?(a):(b))
#define MIN(a, b) (((a)<(b))?(a):(b))
int timelib_strcasecmp(const char *s1, const char *s2)
{
size_t len;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
int c1, c2;
if (s1 == s2) {
return 0;
}
len = MIN(len1, len2);
while (len--) {
c1 = timelib_tolower(*(unsigned char *)s1++);
c2 = timelib_tolower(*(unsigned char *)s2++);
if (c1 != c2) {
return c1 - c2;
}
}
return (int)(len1 - len2);
}
int timelib_strncasecmp(const char *s1, const char *s2, size_t length)
{
size_t len;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
int c1, c2;
if (s1 == s2) {
return 0;
}
len = MIN(length, MIN(len1, len2));
while (len--) {
c1 = timelib_tolower(*(unsigned char *)s1++);
c2 = timelib_tolower(*(unsigned char *)s2++);
if (c1 != c2) {
return c1 - c2;
}
}
return (int)(MIN(length, len1) - MIN(length, len2));
}
#undef MIN
#undef MAX
void timelib_dump_date(timelib_time *d, int options)
{
if ((options & 2) == 2) {
printf("TYPE: %d ", d->zone_type);
}
printf("TS: %lld | %s%04lld-%02lld-%02lld %02lld:%02lld:%02lld",
d->sse, d->y < 0 ? "-" : "", TIMELIB_LLABS(d->y), d->m, d->d, d->h, d->i, d->s);
if (d->us > 0) {
printf(" 0.%06lld", d->us);
}
if (d->is_localtime) {
switch (d->zone_type) {
case TIMELIB_ZONETYPE_OFFSET: /* Only offset */
printf(" GMT %05d%s", d->z, d->dst == 1 ? " (DST)" : "");
break;
case TIMELIB_ZONETYPE_ID: /* Timezone struct */
/* Show abbreviation if wanted */
if (d->tz_abbr) {
printf(" %s", d->tz_abbr);
}
/* Do we have a TimeZone struct? */
if (d->tz_info) {
printf(" %s", d->tz_info->name);
}
break;
case TIMELIB_ZONETYPE_ABBR:
printf(" %s", d->tz_abbr);
printf(" %05d%s", d->z, d->dst == 1 ? " (DST)" : "");
break;
}
}
if ((options & 1) == 1) {
if (d->have_relative) {
printf("%3lldY %3lldM %3lldD / %3lldH %3lldM %3lldS",
d->relative.y, d->relative.m, d->relative.d, d->relative.h, d->relative.i, d->relative.s);
if (d->relative.us) {
printf(" 0.%06lld", d->relative.us);
}
if (d->relative.first_last_day_of != 0) {
switch (d->relative.first_last_day_of) {
case 1:
printf(" / first day of");
break;
case 2:
printf(" / last day of");
break;
}
}
if (d->relative.have_weekday_relative) {
printf(" / %d.%d", d->relative.weekday, d->relative.weekday_behavior);
}
if (d->relative.have_special_relative) {
switch (d->relative.special.type) {
case TIMELIB_SPECIAL_WEEKDAY:
printf(" / %lld weekday", d->relative.special.amount);
break;
case TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH:
printf(" / x y of z month");
break;
case TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH:
printf(" / last y of z month");
break;
}
}
}
}
printf("\n");
}
void timelib_dump_rel_time(timelib_rel_time *d)
{
printf("%3lldY %3lldM %3lldD / %3lldH %3lldM %3lldS (days: %lld)%s",
d->y, d->m, d->d, d->h, d->i, d->s, d->days, d->invert ? " inverted" : "");
if (d->first_last_day_of != 0) {
switch (d->first_last_day_of) {
case 1:
printf(" / first day of");
break;
case 2:
printf(" / last day of");
break;
}
}
printf("\n");
}
| 10,688 | 26.835938 | 112 |
c
|
php-src
|
php-src-master/ext/date/lib/timelib_private.h
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2019 Derick Rethans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __TIMELIB_PRIVATE_H__
#define __TIMELIB_PRIVATE_H__
#ifdef HAVE_TIMELIB_CONFIG_H
# include "timelib_config.h"
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef _WIN32
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
#include <string.h>
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if defined(HAVE_STDINT_H)
# include <stdint.h>
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#if HAVE_IO_H
# include <io.h>
#endif
#if HAVE_DIRENT_H
# include <dirent.h>
#endif
#include <stdio.h>
#include <limits.h>
#define TIMELIB_SECOND 1
#define TIMELIB_MINUTE 2
#define TIMELIB_HOUR 3
#define TIMELIB_DAY 4
#define TIMELIB_MONTH 5
#define TIMELIB_YEAR 6
#define TIMELIB_WEEKDAY 7
#define TIMELIB_SPECIAL 8
#define TIMELIB_MICROSEC 9
#define TIMELIB_SPECIAL_WEEKDAY 0x01
#define TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH 0x02
#define TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH 0x03
#define TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH 0x01
#define TIMELIB_SPECIAL_LAST_DAY_OF_MONTH 0x02
#define TIMELIB_TIME_PART_DONT_KEEP 0x00
#define TIMELIB_TIME_PART_KEEP 0x01
#define MINS_PER_HOUR 60
#define SECS_PER_ERA TIMELIB_LL_CONST(12622780800)
#define SECS_PER_DAY 86400
#define SECS_PER_HOUR 3600
#define USECS_PER_HOUR TIMELIB_LL_CONST(3600000000)
#define DAYS_PER_WEEK 7
#define DAYS_PER_YEAR 365
#define DAYS_PER_LYEAR 366
#define MONTHS_PER_YEAR 12
/* 400*365 days + 97 leap days */
#define DAYS_PER_ERA 146097
#define YEARS_PER_ERA 400
#define HINNANT_EPOCH_SHIFT 719468 /* 0000-03-01 instead of 1970-01-01 */
#define TIMELIB_TZINFO_PHP 0x01
#define TIMELIB_TZINFO_ZONEINFO 0x02
#define timelib_is_leap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
#define TIMELIB_DEBUG(s) if (0) { s }
#define TIMELIB_TIME_FREE(m) \
if (m) { \
timelib_free(m); \
m = NULL; \
}
#if defined (__GNUC__)
# define TIMELIB_GNUC_CHECK_VERSION(major, minor) \
((__GNUC__ > (major)) || \
((__GNUC__ == (major)) && (__GNUC_MINOR__ >= (minor))))
#else
# define TIMELIB_GNUC_CHECK_VERSION(major, minor) 0
#endif
#if TIMELIB_GNUC_CHECK_VERSION(7, 0)
# define TIMELIB_BREAK_INTENTIONALLY_MISSING __attribute__ ((fallthrough));
#else
# define TIMELIB_BREAK_INTENTIONALLY_MISSING
#endif
struct _ttinfo
{
int32_t offset;
int isdst;
unsigned int abbr_idx;
unsigned int isstdcnt;
unsigned int isgmtcnt;
};
struct _tlinfo
{
int64_t trans;
int32_t offset;
};
#ifndef LONG_MAX
#define LONG_MAX 2147483647L
#endif
#ifndef LONG_MIN
#define LONG_MIN (- LONG_MAX - 1)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* From unixtime2tm.c */
int timelib_apply_localtime(timelib_time *t, unsigned int localtime);
/* From parse_posix.c */
timelib_sll timelib_ts_at_start_of_year(timelib_sll year);
ttinfo* timelib_fetch_posix_timezone_offset(timelib_tzinfo *tz, timelib_sll ts, timelib_sll *transition_time);
/* From parse_tz.c */
void timelib_time_tz_abbr_update(timelib_time* tm, const char* tz_abbr);
ttinfo* timelib_fetch_timezone_offset(timelib_tzinfo *tz, timelib_sll ts, timelib_sll *transition_time);
/* From timelib.c */
int timelib_strcasecmp(const char *s1, const char *s2);
int timelib_strncasecmp(const char *s1, const char *s2, size_t n);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| 4,584 | 24.758427 | 110 |
h
|
php-src
|
php-src-master/ext/date/lib/unixtime2tm.c
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 Derick Rethans
* Copyright (c) 2021 MongoDB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "timelib.h"
#include "timelib_private.h"
void timelib_unixtime2date(timelib_sll ts, timelib_sll *y, timelib_sll *m, timelib_sll *d)
{
timelib_sll days, era, t;
timelib_ull day_of_era, year_of_era, day_of_year, month_portion;
/* Calculate days since algorithm's epoch (0000-03-01) */
days = ts / SECS_PER_DAY + HINNANT_EPOCH_SHIFT;
/* Adjustment for a negative time portion */
t = ts % SECS_PER_DAY;
days += (t < 0) ? -1 : 0;
/* Calculate year, month, and day. Algorithm from:
* http://howardhinnant.github.io/date_algorithms.html#civil_from_days */
era = (days >= 0 ? days : days - DAYS_PER_ERA + 1) / DAYS_PER_ERA;
day_of_era = days - era * DAYS_PER_ERA;
year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / DAYS_PER_YEAR;
*y = year_of_era + era * YEARS_PER_ERA;
day_of_year = day_of_era - (DAYS_PER_YEAR * year_of_era + year_of_era / 4 - year_of_era / 100);
month_portion = (5 * day_of_year + 2) / 153;
*d = day_of_year - (153 * month_portion + 2) / 5 + 1;
*m = month_portion + (month_portion < 10 ? 3 : -9);
*y += (*m <= 2);
TIMELIB_DEBUG(printf("A: ts=%lld, year=%lld, month=%lld, day=%lld,", ts, *y, *m, *d););
}
/* Converts a Unix timestamp value into broken down time, in GMT */
void timelib_unixtime2gmt(timelib_time* tm, timelib_sll ts)
{
timelib_sll remainder;
timelib_sll hours, minutes, seconds;
timelib_unixtime2date(ts, &tm->y, &tm->m, &tm->d);
remainder = ts % SECS_PER_DAY;
remainder += (remainder < 0) * SECS_PER_DAY;
/* That was the date, now we do the time */
hours = remainder / 3600;
minutes = (remainder - hours * 3600) / 60;
seconds = remainder % 60;
TIMELIB_DEBUG(printf(" hour=%lld, minute=%lld, second=%lld\n", hours, minutes, seconds););
tm->h = hours;
tm->i = minutes;
tm->s = seconds;
tm->z = 0;
tm->dst = 0;
tm->sse = ts;
tm->sse_uptodate = 1;
tm->tim_uptodate = 1;
tm->is_localtime = 0;
}
void timelib_update_from_sse(timelib_time *tm)
{
timelib_sll sse;
int z = tm->z;
signed int dst = tm->dst;
sse = tm->sse;
switch (tm->zone_type) {
case TIMELIB_ZONETYPE_ABBR:
case TIMELIB_ZONETYPE_OFFSET: {
timelib_unixtime2gmt(tm, tm->sse + tm->z + (tm->dst * 3600));
goto cleanup;
}
case TIMELIB_ZONETYPE_ID: {
int32_t offset = 0;
timelib_get_time_zone_offset_info(tm->sse, tm->tz_info, &offset, NULL, NULL);
timelib_unixtime2gmt(tm, tm->sse + offset);
goto cleanup;
}
default:
timelib_unixtime2gmt(tm, tm->sse);
goto cleanup;
}
cleanup:
tm->sse = sse;
tm->is_localtime = 1;
tm->have_zone = 1;
tm->z = z;
tm->dst = dst;
}
void timelib_unixtime2local(timelib_time *tm, timelib_sll ts)
{
timelib_time_offset *gmt_offset;
timelib_tzinfo *tz = tm->tz_info;
switch (tm->zone_type) {
case TIMELIB_ZONETYPE_ABBR:
case TIMELIB_ZONETYPE_OFFSET: {
int z = tm->z;
signed int dst = tm->dst;
timelib_unixtime2gmt(tm, ts + tm->z + (tm->dst * 3600));
tm->sse = ts;
tm->z = z;
tm->dst = dst;
break;
}
case TIMELIB_ZONETYPE_ID:
gmt_offset = timelib_get_time_zone_info(ts, tz);
timelib_unixtime2gmt(tm, ts + gmt_offset->offset);
/* we need to reset the sse here as unixtime2gmt modifies it */
tm->sse = ts;
tm->dst = gmt_offset->is_dst;
tm->z = gmt_offset->offset;
tm->tz_info = tz;
timelib_time_tz_abbr_update(tm, gmt_offset->abbr);
timelib_time_offset_dtor(gmt_offset);
break;
default:
tm->is_localtime = 0;
tm->have_zone = 0;
return;
}
tm->is_localtime = 1;
tm->have_zone = 1;
}
void timelib_set_timezone_from_offset(timelib_time *t, timelib_sll utc_offset)
{
if (t->tz_abbr) {
timelib_free(t->tz_abbr);
}
t->tz_abbr = NULL;
t->z = utc_offset;
t->have_zone = 1;
t->zone_type = TIMELIB_ZONETYPE_OFFSET;
t->dst = 0;
t->tz_info = NULL;
}
void timelib_set_timezone_from_abbr(timelib_time *t, timelib_abbr_info abbr_info)
{
if (t->tz_abbr) {
timelib_free(t->tz_abbr);
}
t->tz_abbr = timelib_strdup(abbr_info.abbr);
t->z = abbr_info.utc_offset;
t->have_zone = 1;
t->zone_type = TIMELIB_ZONETYPE_ABBR;
t->dst = abbr_info.dst;
t->tz_info = NULL;
}
void timelib_set_timezone(timelib_time *t, timelib_tzinfo *tz)
{
timelib_time_offset *gmt_offset;
gmt_offset = timelib_get_time_zone_info(t->sse, tz);
t->z = gmt_offset->offset;
/*
if (t->dst != gmt_offset->is_dst) {
printf("ERROR (%d, %d)\n", t->dst, gmt_offset->is_dst);
exit(1);
}
*/
t->dst = gmt_offset->is_dst;
t->tz_info = tz;
if (t->tz_abbr) {
timelib_free(t->tz_abbr);
}
t->tz_abbr = timelib_strdup(gmt_offset->abbr);
timelib_time_offset_dtor(gmt_offset);
t->have_zone = 1;
t->zone_type = TIMELIB_ZONETYPE_ID;
}
/* Converts the time stored in the struct to localtime if localtime = true,
* otherwise it converts it to gmttime. This is only done when necessary
* of course. */
int timelib_apply_localtime(timelib_time *t, unsigned int localtime)
{
if (localtime) {
/* Converting from GMT time to local time */
TIMELIB_DEBUG(printf("Converting from GMT time to local time\n"););
/* Check if TZ is set */
if (!t->tz_info) {
TIMELIB_DEBUG(printf("E: No timezone configured, can't switch to local time\n"););
return -1;
}
timelib_unixtime2local(t, t->sse);
} else {
/* Converting from local time to GMT time */
TIMELIB_DEBUG(printf("Converting from local time to GMT time\n"););
timelib_unixtime2gmt(t, t->sse);
}
return 0;
}
| 6,581 | 26.539749 | 107 |
c
|
php-src
|
php-src-master/ext/dba/dba_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1a02eaf9da45edb40720620e3beef43fd19dd520 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_dba_popen, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, path, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, mode, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, handler, IS_STRING, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, permission, IS_LONG, 0, "0644")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, map_size, IS_LONG, 0, "0")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_dba_open arginfo_dba_popen
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_close, 0, 1, IS_VOID, 0)
ZEND_ARG_INFO(0, dba)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_exists, 0, 2, _IS_BOOL, 0)
ZEND_ARG_TYPE_MASK(0, key, MAY_BE_STRING|MAY_BE_ARRAY, NULL)
ZEND_ARG_INFO(0, dba)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_dba_fetch, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_MASK(0, key, MAY_BE_STRING|MAY_BE_ARRAY, NULL)
ZEND_ARG_INFO(0, dba)
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(0, skip, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_dba_key_split, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE)
ZEND_ARG_TYPE_MASK(0, key, MAY_BE_STRING|MAY_BE_FALSE|MAY_BE_NULL, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_dba_firstkey, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_INFO(0, dba)
ZEND_END_ARG_INFO()
#define arginfo_dba_nextkey arginfo_dba_firstkey
#define arginfo_dba_delete arginfo_dba_exists
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_insert, 0, 3, _IS_BOOL, 0)
ZEND_ARG_TYPE_MASK(0, key, MAY_BE_STRING|MAY_BE_ARRAY, NULL)
ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_ARG_INFO(0, dba)
ZEND_END_ARG_INFO()
#define arginfo_dba_replace arginfo_dba_insert
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_optimize, 0, 1, _IS_BOOL, 0)
ZEND_ARG_INFO(0, dba)
ZEND_END_ARG_INFO()
#define arginfo_dba_sync arginfo_dba_optimize
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_handlers, 0, 0, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, full_info, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dba_list, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(dba_popen);
ZEND_FUNCTION(dba_open);
ZEND_FUNCTION(dba_close);
ZEND_FUNCTION(dba_exists);
ZEND_FUNCTION(dba_fetch);
ZEND_FUNCTION(dba_key_split);
ZEND_FUNCTION(dba_firstkey);
ZEND_FUNCTION(dba_nextkey);
ZEND_FUNCTION(dba_delete);
ZEND_FUNCTION(dba_insert);
ZEND_FUNCTION(dba_replace);
ZEND_FUNCTION(dba_optimize);
ZEND_FUNCTION(dba_sync);
ZEND_FUNCTION(dba_handlers);
ZEND_FUNCTION(dba_list);
static const zend_function_entry ext_functions[] = {
ZEND_FE(dba_popen, arginfo_dba_popen)
ZEND_FE(dba_open, arginfo_dba_open)
ZEND_FE(dba_close, arginfo_dba_close)
ZEND_FE(dba_exists, arginfo_dba_exists)
ZEND_FE(dba_fetch, arginfo_dba_fetch)
ZEND_FE(dba_key_split, arginfo_dba_key_split)
ZEND_FE(dba_firstkey, arginfo_dba_firstkey)
ZEND_FE(dba_nextkey, arginfo_dba_nextkey)
ZEND_FE(dba_delete, arginfo_dba_delete)
ZEND_FE(dba_insert, arginfo_dba_insert)
ZEND_FE(dba_replace, arginfo_dba_replace)
ZEND_FE(dba_optimize, arginfo_dba_optimize)
ZEND_FE(dba_sync, arginfo_dba_sync)
ZEND_FE(dba_handlers, arginfo_dba_handlers)
ZEND_FE(dba_list, arginfo_dba_list)
ZEND_FE_END
};
static void register_dba_symbols(int module_number)
{
#if defined(DBA_LMDB)
REGISTER_LONG_CONSTANT("DBA_LMDB_USE_SUB_DIR", 0, CONST_PERSISTENT);
#endif
#if defined(DBA_LMDB)
REGISTER_LONG_CONSTANT("DBA_LMDB_NO_SUB_DIR", MDB_NOSUBDIR, CONST_PERSISTENT);
#endif
}
| 3,676 | 32.733945 | 95 |
h
|
php-src
|
php-src-master/ext/dba/dba_cdb.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: Sascha Schumann <[email protected]> |
| Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_CDB
#include "php_cdb.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#if DBA_CDB_BUILTIN
# include "libcdb/cdb.h"
# include "libcdb/cdb_make.h"
# include "libcdb/uint32.h"
#else
# ifdef CDB_INCLUDE_FILE
# include CDB_INCLUDE_FILE
# endif
#endif
#define CDB_INFO \
dba_cdb *cdb = (dba_cdb *) info->dbf
typedef struct {
struct cdb c;
#if DBA_CDB_BUILTIN
struct cdb_make m;
php_stream *file;
int make;
#else
int file;
#endif
uint32 eod; /* size of constant database */
uint32 pos; /* current position for traversing */
} dba_cdb;
DBA_OPEN_FUNC(cdb)
{
#if DBA_CDB_BUILTIN
php_stream* file = 0;
int make;
#else
int file = 0;
#endif
dba_cdb *cdb;
dba_info *pinfo = (dba_info *) info;
switch (info->mode) {
case DBA_READER:
#if DBA_CDB_BUILTIN
make = 0;
file = info->fp;
#else
file = VCWD_OPEN(ZSTR_VAL(info->path), O_RDONLY);
if (file < 0) {
*error = "Unable to open file";
return FAILURE;
}
#endif
break;
#if DBA_CDB_BUILTIN
case DBA_TRUNC:
make = 1;
file = info->fp;
break;
case DBA_CREAT:
case DBA_WRITER:
*error = "Update operations are not supported";
return FAILURE; /* not supported */
#endif
default:
*error = "Currently not supported";
return FAILURE;
}
cdb = pemalloc(sizeof(dba_cdb), info->flags&DBA_PERSISTENT);
memset(cdb, 0, sizeof(dba_cdb));
#if DBA_CDB_BUILTIN
if (make) {
cdb_make_start(&cdb->m, file);
} else {
cdb_init(&cdb->c, file);
}
cdb->make = make;
#else
cdb_init(&cdb->c, file);
#endif
cdb->file = file;
pinfo->dbf = cdb;
return SUCCESS;
}
DBA_CLOSE_FUNC(cdb)
{
CDB_INFO;
/* cdb_free does not close associated file */
#if DBA_CDB_BUILTIN
if (cdb->make) {
cdb_make_finish(&cdb->m);
} else {
cdb_free(&cdb->c);
}
#else
cdb_free(&cdb->c);
close(cdb->file);
#endif
pefree(cdb, info->flags&DBA_PERSISTENT);
}
#if DBA_CDB_BUILTIN
# define php_cdb_read(cdb, buf, len, pos) cdb_read(cdb, buf, len, pos)
# define php_cdb_findnext(cdb, key, len) cdb_findnext(cdb, key, len)
# define php_cdb_find(cdb, key, len) cdb_find(cdb, key, len)
#else
# define php_cdb_read(cdb, buf, len, pos) cdb_read(cdb, buf, len, pos)
# define php_cdb_findnext(cdb, key, len) cdb_findnext(cdb, key, len)
# define php_cdb_find(cdb, key, len) cdb_find(cdb, key, len)
#endif
DBA_FETCH_FUNC(cdb)
{
CDB_INFO;
zend_string *fetched_val = NULL;
unsigned int len;
#if DBA_CDB_BUILTIN
if (cdb->make)
return NULL; /* database was opened writeonly */
#endif
if (php_cdb_find(&cdb->c, ZSTR_VAL(key), ZSTR_LEN(key)) == 1) {
while(skip--) {
if (php_cdb_findnext(&cdb->c, ZSTR_VAL(key), ZSTR_LEN(key)) != 1) {
return NULL;
}
}
len = cdb_datalen(&cdb->c);
fetched_val = zend_string_alloc(len, /* persistent */ false);
if (php_cdb_read(&cdb->c, ZSTR_VAL(fetched_val), len, cdb_datapos(&cdb->c)) == -1) {
zend_string_release_ex(fetched_val, /* persistent */ false);
return NULL;
}
ZSTR_VAL(fetched_val)[len] = 0;
}
return fetched_val;
}
DBA_UPDATE_FUNC(cdb)
{
#if DBA_CDB_BUILTIN
CDB_INFO;
if (!cdb->make)
return FAILURE; /* database was opened readonly */
if (!mode)
return FAILURE; /* cdb_make doesn't know replace */
if (cdb_make_add(&cdb->m, ZSTR_VAL(key), ZSTR_LEN(key), ZSTR_VAL(val), ZSTR_LEN(val)) != -1)
return SUCCESS;
#endif
return FAILURE;
}
DBA_EXISTS_FUNC(cdb)
{
CDB_INFO;
#if DBA_CDB_BUILTIN
if (cdb->make)
return FAILURE; /* database was opened writeonly */
#endif
if (php_cdb_find(&cdb->c, ZSTR_VAL(key), ZSTR_LEN(key)) == 1)
return SUCCESS;
return FAILURE;
}
DBA_DELETE_FUNC(cdb)
{
return FAILURE; /* cdb doesn't support delete */
}
/* {{{ cdb_file_read */
#if DBA_CDB_BUILTIN
# define cdb_file_read(fildes, buf, size) php_stream_read(fildes, buf, size)
#else
# define cdb_file_read(fildes, buf, size) read(fildes, buf, size)
#endif
/* }}} */
#define CREAD(n) do { \
if (cdb_file_read(cdb->file, buf, n) < n) return NULL; \
} while (0)
/* {{{ cdb_file_lseek
php_stream_seek does not return actual position */
#if DBA_CDB_BUILTIN
zend_off_t cdb_file_lseek(php_stream *fp, zend_off_t offset, int whence) {
php_stream_seek(fp, offset, whence);
return php_stream_tell(fp);
}
#else
zend_off_t cdb_file_lseek(int fd, zend_off_t offset, int whence) {
return lseek(fd, offset, whence);
}
#endif
/* }}} */
#define CSEEK(n) do { \
if (n >= cdb->eod) return NULL; \
if (cdb_file_lseek(cdb->file, (zend_off_t)n, SEEK_SET) != (zend_off_t) n) return NULL; \
} while (0)
DBA_FIRSTKEY_FUNC(cdb)
{
CDB_INFO;
uint32 klen, dlen;
char buf[8];
zend_string *key;
#if DBA_CDB_BUILTIN
if (cdb->make)
return NULL; /* database was opened writeonly */
#endif
cdb->eod = -1;
CSEEK(0);
CREAD(4);
/* Total length of file in bytes */
uint32_unpack(buf, &cdb->eod);
CSEEK(2048);
CREAD(8);
/* The first four bytes contain the length of the key */
uint32_unpack(buf, &klen);
uint32_unpack(buf + 4, &dlen);
key = zend_string_alloc(klen, /* persistent */ false);
if (cdb_file_read(cdb->file, ZSTR_VAL(key), klen) < klen) {
zend_string_release_ex(key, /* persistent */ false);
key = NULL;
} else {
ZSTR_VAL(key)[klen] = 0;
}
/* header + klenlen + dlenlen + klen + dlen */
cdb->pos = 2048 + 4 + 4 + klen + dlen;
return key;
}
DBA_NEXTKEY_FUNC(cdb)
{
CDB_INFO;
uint32 klen, dlen;
char buf[8];
zend_string *key;
#if DBA_CDB_BUILTIN
if (cdb->make)
return NULL; /* database was opened writeonly */
#endif
CSEEK(cdb->pos);
CREAD(8);
uint32_unpack(buf, &klen);
uint32_unpack(buf + 4, &dlen);
key = zend_string_alloc(klen, /* persistent */ false);
if (cdb_file_read(cdb->file, ZSTR_VAL(key), klen) < klen) {
zend_string_release_ex(key, /* persistent */ false);
key = NULL;
} else {
ZSTR_VAL(key)[klen] = 0;
}
cdb->pos += 8 + klen + dlen;
return key;
}
DBA_OPTIMIZE_FUNC(cdb)
{
return SUCCESS;
}
DBA_SYNC_FUNC(cdb)
{
/* this is read-only */
return SUCCESS;
}
DBA_INFO_FUNC(cdb)
{
#if DBA_CDB_BUILTIN
if (!strcmp(hnd->name, "cdb")) {
return estrdup(cdb_version());
} else {
return estrdup(cdb_make_version());
}
#else
return estrdup("External");
#endif
}
#endif
| 7,289 | 20.826347 | 93 |
c
|
php-src
|
php-src-master/ext/dba/dba_db3.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: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_DB3
#include "php_db3.h"
#include <sys/stat.h>
#include <string.h>
#ifdef DB3_INCLUDE_FILE
#include DB3_INCLUDE_FILE
#else
#include <db.h>
#endif
static void php_dba_db3_errcall_fcn(
#if (DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3))
const DB_ENV *dbenv,
#endif
const char *errpfx, const char *msg)
{
php_error_docref(NULL, E_NOTICE, "%s%s", errpfx?errpfx:"", msg);
}
typedef struct {
DB *dbp;
DBC *cursor;
} dba_db3_data;
DBA_OPEN_FUNC(db3)
{
DB *dbp = NULL;
DBTYPE type;
int gmode = 0, err;
int filemode = info->file_permission;
struct stat check_stat;
int s = VCWD_STAT(ZSTR_VAL(info->path), &check_stat);
if (!s && !check_stat.st_size) {
info->mode = DBA_TRUNC; /* force truncate */
}
type = info->mode == DBA_READER ? DB_UNKNOWN :
info->mode == DBA_TRUNC ? DB_BTREE :
s ? DB_BTREE : DB_UNKNOWN;
gmode = info->mode == DBA_READER ? DB_RDONLY :
(info->mode == DBA_CREAT && s) ? DB_CREATE :
(info->mode == DBA_CREAT && !s) ? 0 :
info->mode == DBA_WRITER ? 0 :
info->mode == DBA_TRUNC ? DB_CREATE | DB_TRUNCATE : -1;
if (gmode == -1) {
return FAILURE; /* not possible */
}
#ifdef DB_FCNTL_LOCKING
gmode |= DB_FCNTL_LOCKING;
#endif
if ((err=db_create(&dbp, NULL, 0)) == 0) {
dbp->set_errcall(dbp, php_dba_db3_errcall_fcn);
if(
#if (DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 1))
(err=dbp->open(dbp, 0, ZSTR_VAL(info->path), NULL, type, gmode, filemode)) == 0) {
#else
(err=dbp->open(dbp, ZSTR_VAL(info->path), NULL, type, gmode, filemode)) == 0) {
#endif
dba_db3_data *data;
data = pemalloc(sizeof(*data), info->flags&DBA_PERSISTENT);
data->dbp = dbp;
data->cursor = NULL;
info->dbf = data;
return SUCCESS;
} else {
dbp->close(dbp, 0);
*error = db_strerror(err);
}
} else {
*error = db_strerror(err);
}
return FAILURE;
}
DBA_CLOSE_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
if (dba->cursor) dba->cursor->c_close(dba->cursor);
dba->dbp->close(dba->dbp, 0);
pefree(dba, info->flags&DBA_PERSISTENT);
}
DBA_FETCH_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
DBT gval;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
if (!dba->dbp->get(dba->dbp, NULL, &gkey, &gval, 0)) {
return zend_string_init(gval.data, gval.size, /* persistent */ false);
}
return NULL;
}
DBA_UPDATE_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
DBT gval;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
gval.data = ZSTR_VAL(val);
gval.size = ZSTR_LEN(val);
if (!dba->dbp->put(dba->dbp, NULL, &gkey, &gval,
mode == 1 ? DB_NOOVERWRITE : 0)) {
return SUCCESS;
}
return FAILURE;
}
DBA_EXISTS_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
DBT gval;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
if (!dba->dbp->get(dba->dbp, NULL, &gkey, &gval, 0)) {
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
return dba->dbp->del(dba->dbp, NULL, &gkey, 0) ? FAILURE : SUCCESS;
}
DBA_FIRSTKEY_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
if (dba->cursor) {
dba->cursor->c_close(dba->cursor);
}
dba->cursor = NULL;
if (dba->dbp->cursor(dba->dbp, NULL, &dba->cursor, 0) != 0) {
return NULL;
}
return dba_nextkey_db3(info);
}
DBA_NEXTKEY_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
DBT gkey, gval;
memset(&gkey, 0, sizeof(gkey));
memset(&gval, 0, sizeof(gval));
if (dba->cursor->c_get(dba->cursor, &gkey, &gval, DB_NEXT) == 0) {
if (gkey.data) {
return zend_string_init(gkey.data, gkey.size, /* persistent */ false);
}
}
return NULL;
}
DBA_OPTIMIZE_FUNC(db3)
{
return SUCCESS;
}
DBA_SYNC_FUNC(db3)
{
dba_db3_data *dba = info->dbf;
return dba->dbp->sync(dba->dbp, 0) ? FAILURE : SUCCESS;
}
DBA_INFO_FUNC(db3)
{
return estrdup(DB_VERSION_STRING);
}
#endif
| 5,210 | 21.269231 | 85 |
c
|
php-src
|
php-src-master/ext/dba/dba_db4.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: Marcus Boerger <[email protected]> |
| Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_DB4
#include "php_db4.h"
#include <sys/stat.h>
#include <string.h>
#ifdef DB4_INCLUDE_FILE
#include DB4_INCLUDE_FILE
#else
#include <db.h>
#endif
static void php_dba_db4_errcall_fcn(
#if (DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3))
const DB_ENV *dbenv,
#endif
const char *errpfx, const char *msg)
{
#if (DB_VERSION_MAJOR == 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 8))
/* Bug 51086, Berkeley DB 4.8.26 */
/* This code suppresses a BDB 4.8+ error message, thus keeping PHP test compatibility */
{
const char *function = get_active_function_name();
if (function && (!strcmp(function,"dba_popen") || !strcmp(function,"dba_open"))
&& (!strncmp(msg, "fop_read_meta", sizeof("fop_read_meta")-1)
|| !strncmp(msg, "BDB0004 fop_read_meta", sizeof("BDB0004 fop_read_meta")-1))) {
return;
}
}
#endif
php_error_docref(NULL, E_NOTICE, "%s%s", errpfx?errpfx:"", msg);
}
typedef struct {
DB *dbp;
DBC *cursor;
} dba_db4_data;
DBA_OPEN_FUNC(db4)
{
DB *dbp = NULL;
DBTYPE type;
int gmode = 0, err;
int filemode = info->file_permission;
struct stat check_stat;
int s = VCWD_STAT(ZSTR_VAL(info->path), &check_stat);
#if (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 7) /* Bug 51086 */
if (!s && !check_stat.st_size) {
info->mode = DBA_TRUNC; /* force truncate */
}
type = info->mode == DBA_READER ? DB_UNKNOWN :
info->mode == DBA_TRUNC ? DB_BTREE :
s ? DB_BTREE : DB_UNKNOWN;
gmode = info->mode == DBA_READER ? DB_RDONLY :
(info->mode == DBA_CREAT && s) ? DB_CREATE :
(info->mode == DBA_CREAT && !s) ? 0 :
info->mode == DBA_WRITER ? 0 :
info->mode == DBA_TRUNC ? DB_CREATE | DB_TRUNCATE : -1;
#else
if (!s && !check_stat.st_size) {
info->mode = DBA_CREAT; /* force creation */
}
type = info->mode == DBA_READER ? DB_UNKNOWN :
(info->mode == DBA_TRUNC || info->mode == DBA_CREAT) ? DB_BTREE :
s ? DB_BTREE : DB_UNKNOWN;
gmode = info->mode == DBA_READER ? DB_RDONLY :
info->mode == DBA_CREAT ? DB_CREATE :
info->mode == DBA_WRITER ? 0 :
info->mode == DBA_TRUNC ? DB_CREATE | DB_TRUNCATE : -1;
#endif
if (gmode == -1) {
return FAILURE; /* not possible */
}
if (info->flags & DBA_PERSISTENT) {
gmode |= DB_THREAD;
}
if ((err=db_create(&dbp, NULL, 0)) == 0) {
dbp->set_errcall(dbp, php_dba_db4_errcall_fcn);
if (
#if (DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 1))
(err=dbp->open(dbp, 0, ZSTR_VAL(info->path), NULL, type, gmode, filemode)) == 0) {
#else
(err=dbp->open(dbp, ZSTR_VAL(info->path), NULL, type, gmode, filemode)) == 0) {
#endif
dba_db4_data *data;
data = pemalloc(sizeof(*data), info->flags&DBA_PERSISTENT);
data->dbp = dbp;
data->cursor = NULL;
info->dbf = data;
return SUCCESS;
} else {
dbp->close(dbp, 0);
*error = db_strerror(err);
}
} else {
*error = db_strerror(err);
}
return FAILURE;
}
DBA_CLOSE_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
if (dba->cursor) dba->cursor->c_close(dba->cursor);
dba->dbp->close(dba->dbp, 0);
pefree(dba, info->flags&DBA_PERSISTENT);
}
DBA_FETCH_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
DBT gval;
DBT gkey;
zend_string *fetched_value = NULL;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
if (info->flags & DBA_PERSISTENT) {
gval.flags |= DB_DBT_MALLOC;
}
if (!dba->dbp->get(dba->dbp, NULL, &gkey, &gval, 0)) {
fetched_value = zend_string_init(gval.data, gval.size, /* persistent */ false);
if (info->flags & DBA_PERSISTENT) {
free(gval.data);
}
}
return fetched_value;
}
DBA_UPDATE_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
DBT gval;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
gval.data = ZSTR_VAL(val);
gval.size = ZSTR_LEN(val);
if (!dba->dbp->put(dba->dbp, NULL, &gkey, &gval,
mode == 1 ? DB_NOOVERWRITE : 0)) {
return SUCCESS;
}
return FAILURE;
}
DBA_EXISTS_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
DBT gval;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
memset(&gval, 0, sizeof(gval));
if (info->flags & DBA_PERSISTENT) {
gval.flags |= DB_DBT_MALLOC;
}
if (!dba->dbp->get(dba->dbp, NULL, &gkey, &gval, 0)) {
if (info->flags & DBA_PERSISTENT) {
free(gval.data);
}
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
DBT gkey;
memset(&gkey, 0, sizeof(gkey));
gkey.data = ZSTR_VAL(key);
gkey.size = ZSTR_LEN(key);
return dba->dbp->del(dba->dbp, NULL, &gkey, 0) ? FAILURE : SUCCESS;
}
DBA_FIRSTKEY_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
if (dba->cursor) {
dba->cursor->c_close(dba->cursor);
}
dba->cursor = NULL;
if (dba->dbp->cursor(dba->dbp, NULL, &dba->cursor, 0) != 0) {
return NULL;
}
return dba_nextkey_db4(info);
}
DBA_NEXTKEY_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
DBT gkey, gval;
zend_string *key = NULL;
memset(&gkey, 0, sizeof(gkey));
memset(&gval, 0, sizeof(gval));
if (info->flags & DBA_PERSISTENT) {
gkey.flags |= DB_DBT_MALLOC;
gval.flags |= DB_DBT_MALLOC;
}
if (dba->cursor && dba->cursor->c_get(dba->cursor, &gkey, &gval, DB_NEXT) == 0) {
if (gkey.data) {
key = zend_string_init(gkey.data, gkey.size, /* persistent */ false);
}
if (info->flags & DBA_PERSISTENT) {
if (gkey.data) {
free(gkey.data);
}
if (gval.data) {
free(gval.data);
}
}
}
return key;
}
DBA_OPTIMIZE_FUNC(db4)
{
return SUCCESS;
}
DBA_SYNC_FUNC(db4)
{
dba_db4_data *dba = info->dbf;
return dba->dbp->sync(dba->dbp, 0) ? FAILURE : SUCCESS;
}
DBA_INFO_FUNC(db4)
{
return estrdup(DB_VERSION_STRING);
}
#endif
| 6,910 | 22.749141 | 88 |
c
|
php-src
|
php-src-master/ext/dba/dba_flatfile.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_FLATFILE
#include "php_flatfile.h"
#include "libflatfile/flatfile.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
DBA_OPEN_FUNC(flatfile)
{
info->dbf = pemalloc(sizeof(flatfile), info->flags&DBA_PERSISTENT);
memset(info->dbf, 0, sizeof(flatfile));
((flatfile*)info->dbf)->fp = info->fp;
return SUCCESS;
}
DBA_CLOSE_FUNC(flatfile)
{
flatfile *dba = info->dbf;
if (dba->nextkey.dptr) {
efree(dba->nextkey.dptr);
}
pefree(dba, info->flags&DBA_PERSISTENT);
}
DBA_FETCH_FUNC(flatfile)
{
flatfile *dba = info->dbf;
datum gval;
datum gkey;
zend_string *fetched_val = NULL;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
gval = flatfile_fetch(dba, gkey);
if (gval.dptr) {
fetched_val = zend_string_init(gval.dptr, gval.dsize, /* persistent */ false);
efree(gval.dptr);
}
return fetched_val;
}
DBA_UPDATE_FUNC(flatfile)
{
flatfile *dba = info->dbf;
datum gval;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
gval.dptr = ZSTR_VAL(val);
gval.dsize = ZSTR_LEN(val);
switch(flatfile_store(dba, gkey, gval, mode==1 ? FLATFILE_INSERT : FLATFILE_REPLACE)) {
case 0:
return SUCCESS;
case 1:
return FAILURE;
case -1:
// TODO Check when this happens and confirm this can even happen
php_error_docref(NULL, E_WARNING, "Operation not possible");
return FAILURE;
default:
// TODO Convert this to an assertion failure
php_error_docref(NULL, E_WARNING, "Unknown return value");
return FAILURE;
}
}
DBA_EXISTS_FUNC(flatfile)
{
flatfile *dba = info->dbf;
datum gval;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
gval = flatfile_fetch(dba, gkey);
if (gval.dptr) {
efree(gval.dptr);
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(flatfile)
{
flatfile *dba = info->dbf;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
return(flatfile_delete(dba, gkey) == -1 ? FAILURE : SUCCESS);
}
DBA_FIRSTKEY_FUNC(flatfile)
{
flatfile *dba = info->dbf;
if (dba->nextkey.dptr) {
efree(dba->nextkey.dptr);
}
dba->nextkey = flatfile_firstkey(dba);
if (dba->nextkey.dptr) {
return zend_string_init(dba->nextkey.dptr, dba->nextkey.dsize, /* persistent */ false);
}
return NULL;
}
DBA_NEXTKEY_FUNC(flatfile)
{
flatfile *dba = info->dbf;
if (!dba->nextkey.dptr) {
return NULL;
}
if (dba->nextkey.dptr) {
efree(dba->nextkey.dptr);
}
dba->nextkey = flatfile_nextkey(dba);
if (dba->nextkey.dptr) {
return zend_string_init(dba->nextkey.dptr, dba->nextkey.dsize, /* persistent */ false);
}
return NULL;
}
DBA_OPTIMIZE_FUNC(flatfile)
{
/* dummy */
return SUCCESS;
}
DBA_SYNC_FUNC(flatfile)
{
/* dummy */
return SUCCESS;
}
DBA_INFO_FUNC(flatfile)
{
return estrdup(flatfile_version());
}
#endif
| 3,892 | 21.119318 | 89 |
c
|
php-src
|
php-src-master/ext/dba/dba_gdbm.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: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_GDBM
#include "php_gdbm.h"
#ifdef GDBM_INCLUDE_FILE
#include GDBM_INCLUDE_FILE
#endif
typedef struct {
GDBM_FILE dbf;
datum nextkey;
} dba_gdbm_data;
DBA_OPEN_FUNC(gdbm)
{
GDBM_FILE dbf;
int gmode = 0;
int filemode = info->file_permission;
gmode = info->mode == DBA_READER ? GDBM_READER :
info->mode == DBA_WRITER ? GDBM_WRITER :
info->mode == DBA_CREAT ? GDBM_WRCREAT :
info->mode == DBA_TRUNC ? GDBM_NEWDB : -1;
if(gmode == -1)
return FAILURE; /* not possible */
dbf = gdbm_open(ZSTR_VAL(info->path), /* int block_size */ 0, gmode, filemode, NULL);
if(dbf) {
info->dbf = pemalloc(sizeof(dba_gdbm_data), info->flags&DBA_PERSISTENT);
memset(info->dbf, 0, sizeof(dba_gdbm_data));
((dba_gdbm_data *) info->dbf)->dbf = dbf;
return SUCCESS;
}
*error = (char *)gdbm_strerror(gdbm_errno);
return FAILURE;
}
DBA_CLOSE_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
if(dba->nextkey.dptr) free(dba->nextkey.dptr);
gdbm_close(dba->dbf);
pefree(dba, info->flags&DBA_PERSISTENT);
}
DBA_FETCH_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
datum gval;
datum gkey;
zend_string *fetched_val = NULL;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
gval = gdbm_fetch(dba->dbf, gkey);
if (gval.dptr) {
fetched_val = zend_string_init(gval.dptr, gval.dsize, /* persistent */ false);
free(gval.dptr);
}
return fetched_val;
}
DBA_UPDATE_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
datum gval;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
gval.dptr = ZSTR_VAL(val);
gval.dsize = ZSTR_LEN(val);
switch (gdbm_store(dba->dbf, gkey, gval, mode == 1 ? GDBM_INSERT : GDBM_REPLACE)) {
case 0:
return SUCCESS;
case 1:
return FAILURE;
case -1:
// TODO Check when this happens and confirm this can even happen
php_error_docref(NULL, E_WARNING, "%s", gdbm_strerror(gdbm_errno));
return FAILURE;
default:
// TODO Convert this to an assertion failure
php_error_docref(NULL, E_WARNING, "Unknown return value");
return FAILURE;
}
}
DBA_EXISTS_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
return gdbm_exists(dba->dbf, gkey) ? SUCCESS : FAILURE;
}
DBA_DELETE_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
datum gkey;
gkey.dptr = ZSTR_VAL(key);
gkey.dsize = ZSTR_LEN(key);
return gdbm_delete(dba->dbf, gkey) == -1 ? FAILURE : SUCCESS;
}
DBA_FIRSTKEY_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
datum gkey;
zend_string *key = NULL;
if (dba->nextkey.dptr) {
free(dba->nextkey.dptr);
}
gkey = gdbm_firstkey(dba->dbf);
if (gkey.dptr) {
key = zend_string_init(gkey.dptr, gkey.dsize, /* persistent */ false);
dba->nextkey = gkey;
} else {
dba->nextkey.dptr = NULL;
}
return key;
}
DBA_NEXTKEY_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
zend_string *key = NULL;
datum gkey;
if(!dba->nextkey.dptr) { return NULL; }
gkey = gdbm_nextkey(dba->dbf, dba->nextkey);
free(dba->nextkey.dptr);
if (gkey.dptr) {
key = zend_string_init(gkey.dptr, gkey.dsize, /* persistent */ false);
dba->nextkey = gkey;
} else {
dba->nextkey.dptr = NULL;
}
return key;
}
DBA_OPTIMIZE_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
gdbm_reorganize(dba->dbf);
return SUCCESS;
}
DBA_SYNC_FUNC(gdbm)
{
dba_gdbm_data *dba = info->dbf;
gdbm_sync(dba->dbf);
return SUCCESS;
}
DBA_INFO_FUNC(gdbm)
{
return estrdup(gdbm_version);
}
#endif
| 4,494 | 21.70202 | 86 |
c
|
php-src
|
php-src-master/ext/dba/dba_inifile.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_INIFILE
#include "php_inifile.h"
#include "libinifile/inifile.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
DBA_OPEN_FUNC(inifile)
{
info->dbf = inifile_alloc(info->fp, info->mode == DBA_READER, info->flags&DBA_PERSISTENT);
return info->dbf ? SUCCESS : FAILURE;
}
DBA_CLOSE_FUNC(inifile)
{
inifile *dba = info->dbf;
inifile_free(dba, info->flags&DBA_PERSISTENT);
}
DBA_FETCH_FUNC(inifile)
{
inifile *dba = info->dbf;
val_type ini_val;
key_type ini_key;
zend_string *fetched_val = NULL;
if (!key) {
php_error_docref(NULL, E_WARNING, "No key specified");
return 0;
}
ini_key = inifile_key_split(ZSTR_VAL(key)); /* keylen not needed here */
ini_val = inifile_fetch(dba, &ini_key, skip);
inifile_key_free(&ini_key);
if (ini_val.value) {
fetched_val = zend_string_init(ini_val.value, strlen(ini_val.value), /* persistent */ false);
inifile_val_free(&ini_val);
}
return fetched_val;
}
DBA_UPDATE_FUNC(inifile)
{
inifile *dba = info->dbf;
val_type ini_val;
int res;
key_type ini_key;
if (!key) {
php_error_docref(NULL, E_WARNING, "No key specified");
return 0;
}
ini_key = inifile_key_split(ZSTR_VAL(key)); /* keylen not needed here */
ini_val.value = ZSTR_VAL(val);
if (mode == 1) {
res = inifile_append(dba, &ini_key, &ini_val);
} else {
res = inifile_replace(dba, &ini_key, &ini_val);
}
inifile_key_free(&ini_key);
switch(res) {
case -1:
// TODO Check when this happens and confirm this can even happen
php_error_docref(NULL, E_WARNING, "Operation not possible");
return FAILURE;
default:
case 0:
return SUCCESS;
case 1:
return FAILURE;
}
}
DBA_EXISTS_FUNC(inifile)
{
inifile *dba = info->dbf;
val_type ini_val;
key_type ini_key;
if (!key) {
php_error_docref(NULL, E_WARNING, "No key specified");
return 0;
}
ini_key = inifile_key_split(ZSTR_VAL(key)); /* keylen not needed here */
ini_val = inifile_fetch(dba, &ini_key, 0);
inifile_key_free(&ini_key);
if (ini_val.value) {
inifile_val_free(&ini_val);
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(inifile)
{
inifile *dba = info->dbf;
int res;
bool found = 0;
key_type ini_key;
if (!key) {
php_error_docref(NULL, E_WARNING, "No key specified");
return 0;
}
ini_key = inifile_key_split(ZSTR_VAL(key)); /* keylen not needed here */
res = inifile_delete_ex(dba, &ini_key, &found);
inifile_key_free(&ini_key);
return (res == -1 || !found ? FAILURE : SUCCESS);
}
DBA_FIRSTKEY_FUNC(inifile)
{
inifile *dba = info->dbf;
if (inifile_firstkey(dba)) {
char *result = inifile_key_string(&dba->curr.key);
zend_string *key = zend_string_init(result, strlen(result), /* persistent */ false);
efree(result);
return key;
} else {
return NULL;
}
}
DBA_NEXTKEY_FUNC(inifile)
{
inifile *dba = info->dbf;
if (!dba->curr.key.group && !dba->curr.key.name) {
return NULL;
}
if (inifile_nextkey(dba)) {
char *result = inifile_key_string(&dba->curr.key);
zend_string *key = zend_string_init(result, strlen(result), /* persistent */ false);
efree(result);
return key;
} else {
return NULL;
}
}
DBA_OPTIMIZE_FUNC(inifile)
{
/* dummy */
return SUCCESS;
}
DBA_SYNC_FUNC(inifile)
{
/* dummy */
return SUCCESS;
}
DBA_INFO_FUNC(inifile)
{
return estrdup(inifile_version());
}
#endif
| 4,406 | 21.6 | 95 |
c
|
php-src
|
php-src-master/ext/dba/dba_lmdb.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: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_LMDB
#include "php_lmdb.h"
#ifdef LMDB_INCLUDE_FILE
#include LMDB_INCLUDE_FILE
#endif
struct php_lmdb_info {
MDB_env *env;
MDB_txn *txn;
MDB_dbi dbi;
MDB_cursor *cur;
};
#define LMDB_IT(it) (((struct php_lmdb_info *)info->dbf)->it)
DBA_OPEN_FUNC(lmdb)
{
MDB_env *env;
MDB_txn *txn;
int rc;
int mode = info->file_permission;
zend_long map_size = info->map_size;
ZEND_ASSERT(map_size >= 0);
/* By default use the MDB_NOSUBDIR flag */
int flags = MDB_NOSUBDIR;
/* Use flags passed by the user for driver flags */
if (info->driver_flags != DBA_DEFAULT_DRIVER_FLAGS) {
ZEND_ASSERT(info->driver_flags >= 0);
switch (info->driver_flags) {
case 0:
case MDB_NOSUBDIR:
flags = info->driver_flags;
break;
default:
zend_argument_value_error(6, "must be either DBA_LMDB_USE_SUB_DIR or DBA_LMDB_NO_SUB_DIR for LMDB driver");
return FAILURE;
}
}
/* Add readonly flag if DB is opened in read only mode */
if (info->mode == DBA_READER) {
flags |= MDB_RDONLY;
}
rc = mdb_env_create(&env);
if (rc) {
*error = mdb_strerror(rc);
return FAILURE;
}
if (map_size > 0) {
rc = mdb_env_set_mapsize(env, (size_t) map_size);
if (rc) {
*error = mdb_strerror(rc);
return FAILURE;
}
}
rc = mdb_env_open(env, ZSTR_VAL(info->path), flags, mode);
if (rc) {
/* If this function [mdb_env_open()] fails, mdb_env_close() must be called to discard the MDB_env handle.
* http://www.lmdb.tech/doc/group__mdb.html#ga32a193c6bf4d7d5c5d579e71f22e9340 */
mdb_env_close(env);
*error = mdb_strerror(rc);
return FAILURE;
}
rc = mdb_txn_begin(env, NULL, /* flags */ MDB_RDONLY, &txn);
if (rc) {
mdb_env_close(env);
*error = mdb_strerror(rc);
return FAILURE;
}
info->dbf = pemalloc(sizeof(struct php_lmdb_info), info->flags & DBA_PERSISTENT);
if (!info->dbf) {
*error = "Failed to allocate php_lmdb_info.";
return FAILURE;
}
memset(info->dbf, 0, sizeof(struct php_lmdb_info));
rc = mdb_dbi_open(txn, NULL, 0, &LMDB_IT(dbi));
if (rc) {
mdb_env_close(env);
pefree(info->dbf, info->flags & DBA_PERSISTENT);
*error = mdb_strerror(rc);
return FAILURE;
}
LMDB_IT(env) = env;
LMDB_IT(txn) = txn;
mdb_txn_abort(LMDB_IT(txn));
return SUCCESS;
}
DBA_CLOSE_FUNC(lmdb)
{
mdb_dbi_close(LMDB_IT(env), LMDB_IT(dbi));
mdb_env_close(LMDB_IT(env));
pefree(info->dbf, info->flags & DBA_PERSISTENT);
}
DBA_FETCH_FUNC(lmdb)
{
int rc;
MDB_val k, v;
zend_string *ret = NULL;
if (LMDB_IT(cur)) {
rc = mdb_txn_renew(LMDB_IT(txn));
} else {
rc = mdb_txn_begin(LMDB_IT(env), NULL, MDB_RDONLY, &LMDB_IT(txn));
}
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return NULL;
}
k.mv_size = ZSTR_LEN(key);
k.mv_data = ZSTR_VAL(key);
rc = mdb_get(LMDB_IT(txn), LMDB_IT(dbi), &k, &v);
if (rc) {
if (MDB_NOTFOUND != rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
}
mdb_txn_abort(LMDB_IT(txn));
return NULL;
}
if (v.mv_data) {
ret = zend_string_init(v.mv_data, v.mv_size, /* persistent */ false);
}
if (LMDB_IT(cur)) {
mdb_txn_reset(LMDB_IT(txn));
} else {
mdb_txn_abort(LMDB_IT(txn));
}
return ret;
}
DBA_UPDATE_FUNC(lmdb)
{
int rc;
MDB_val k, v;
rc = mdb_txn_begin(LMDB_IT(env), NULL, 0, &LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return FAILURE;
}
k.mv_size = ZSTR_LEN(key);
k.mv_data = ZSTR_VAL(key);
v.mv_size = ZSTR_LEN(val);
v.mv_data = ZSTR_VAL(val);
rc = mdb_put(LMDB_IT(txn), LMDB_IT(dbi), &k, &v, mode == 1 ? MDB_NOOVERWRITE : 0);
if (rc) {
if (MDB_KEYEXIST != rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
}
mdb_txn_abort(LMDB_IT(txn));
return FAILURE;
}
rc = mdb_txn_commit(LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
mdb_txn_abort(LMDB_IT(txn));
return FAILURE;
}
return SUCCESS;
}
DBA_EXISTS_FUNC(lmdb)
{
int rc;
MDB_val k, v;
if (LMDB_IT(cur)) {
rc = mdb_txn_renew(LMDB_IT(txn));
} else {
rc = mdb_txn_begin(LMDB_IT(env), NULL, MDB_RDONLY, &LMDB_IT(txn));
}
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return FAILURE;
}
k.mv_size = ZSTR_LEN(key);
k.mv_data = ZSTR_VAL(key);
rc = mdb_get(LMDB_IT(txn), LMDB_IT(dbi), &k, &v);
if (rc) {
if (MDB_NOTFOUND != rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
}
mdb_txn_abort(LMDB_IT(txn));
return FAILURE;
}
if (LMDB_IT(cur)) {
mdb_txn_reset(LMDB_IT(txn));
} else {
mdb_txn_abort(LMDB_IT(txn));
}
return SUCCESS;
}
DBA_DELETE_FUNC(lmdb)
{
int rc;
MDB_val k;
rc = mdb_txn_begin(LMDB_IT(env), NULL, 0, &LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return FAILURE;
}
k.mv_size = ZSTR_LEN(key);
k.mv_data = ZSTR_VAL(key);
rc = mdb_del(LMDB_IT(txn), LMDB_IT(dbi), &k, NULL);
if (!rc) {
rc = mdb_txn_commit(LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
mdb_txn_abort(LMDB_IT(txn));
return FAILURE;
}
return SUCCESS;
}
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
mdb_txn_abort(LMDB_IT(txn));
return FAILURE;
}
DBA_FIRSTKEY_FUNC(lmdb)
{
int rc;
MDB_val k, v;
zend_string *ret = NULL;
rc = mdb_txn_begin(LMDB_IT(env), NULL, MDB_RDONLY, &LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return NULL;
}
rc = mdb_cursor_open(LMDB_IT(txn), LMDB_IT(dbi), &LMDB_IT(cur));
if (rc) {
mdb_txn_abort(LMDB_IT(txn));
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return NULL;
}
rc = mdb_cursor_get(LMDB_IT(cur), &k, &v, MDB_FIRST);
if (rc) {
mdb_txn_abort(LMDB_IT(txn));
mdb_cursor_close(LMDB_IT(cur));
LMDB_IT(cur) = NULL;
if (MDB_NOTFOUND != rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
}
return NULL;
}
if (k.mv_data) {
ret = zend_string_init(k.mv_data, k.mv_size, /* persistent */ false);
}
mdb_txn_reset(LMDB_IT(txn));
return ret;
}
DBA_NEXTKEY_FUNC(lmdb)
{
int rc;
MDB_val k, v;
zend_string *ret = NULL;
rc = mdb_txn_renew(LMDB_IT(txn));
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return NULL;
}
rc = mdb_cursor_get(LMDB_IT(cur), &k, &v, MDB_NEXT);
if (rc) {
mdb_txn_abort(LMDB_IT(txn));
mdb_cursor_close(LMDB_IT(cur));
LMDB_IT(cur) = NULL;
if (MDB_NOTFOUND != rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
}
return NULL;
}
if (k.mv_data) {
ret = zend_string_init(k.mv_data, k.mv_size, /* persistent */ false);
}
mdb_txn_reset(LMDB_IT(txn));
return ret;
}
DBA_OPTIMIZE_FUNC(lmdb)
{
return SUCCESS;
}
DBA_SYNC_FUNC(lmdb)
{
int rc;
rc = mdb_env_sync(LMDB_IT(env), 1);
if (rc) {
php_error_docref(NULL, E_WARNING, "%s", mdb_strerror(rc));
return FAILURE;
}
return SUCCESS;
}
DBA_INFO_FUNC(lmdb)
{
return estrdup(MDB_VERSION_STRING);
}
#endif
| 7,969 | 20.598916 | 111 |
c
|
php-src
|
php-src-master/ext/dba/dba_qdbm.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: Marcin Gibula <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_QDBM
#include "php_qdbm.h"
#ifdef QDBM_INCLUDE_FILE
#include QDBM_INCLUDE_FILE
#endif
typedef struct {
DEPOT *dbf;
} dba_qdbm_data;
DBA_OPEN_FUNC(qdbm)
{
DEPOT *dbf;
switch(info->mode) {
case DBA_READER:
dbf = dpopen(ZSTR_VAL(info->path), DP_OREADER, 0);
break;
case DBA_WRITER:
dbf = dpopen(ZSTR_VAL(info->path), DP_OWRITER, 0);
break;
case DBA_CREAT:
dbf = dpopen(ZSTR_VAL(info->path), DP_OWRITER | DP_OCREAT, 0);
break;
case DBA_TRUNC:
dbf = dpopen(ZSTR_VAL(info->path), DP_OWRITER | DP_OCREAT | DP_OTRUNC, 0);
break;
default:
return FAILURE;
}
if (dbf) {
info->dbf = pemalloc(sizeof(dba_qdbm_data), info->flags & DBA_PERSISTENT);
memset(info->dbf, 0, sizeof(dba_qdbm_data));
((dba_qdbm_data *) info->dbf)->dbf = dbf;
return SUCCESS;
}
*error = (char *) dperrmsg(dpecode);
return FAILURE;
}
DBA_CLOSE_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
dpclose(dba->dbf);
pefree(dba, info->flags & DBA_PERSISTENT);
}
DBA_FETCH_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
char *value;
int value_size;
zend_string *fetched_val = NULL;
value = dpget(dba->dbf, ZSTR_VAL(key), ZSTR_LEN(key), 0, -1, &value_size);
if (value) {
fetched_val = zend_string_init(value, value_size, /* persistent */ false);
free(value);
}
return fetched_val;
}
DBA_UPDATE_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
if (dpput(dba->dbf, ZSTR_VAL(key), ZSTR_LEN(key), ZSTR_VAL(val), ZSTR_LEN(val), mode == 1 ? DP_DKEEP : DP_DOVER)) {
return SUCCESS;
}
if (dpecode != DP_EKEEP) {
php_error_docref(NULL, E_WARNING, "%s", dperrmsg(dpecode));
}
return FAILURE;
}
DBA_EXISTS_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
char *value;
value = dpget(dba->dbf, ZSTR_VAL(key), ZSTR_LEN(key), 0, -1, NULL);
if (value) {
free(value);
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
return dpout(dba->dbf, ZSTR_VAL(key), ZSTR_LEN(key)) ? SUCCESS : FAILURE;
}
DBA_FIRSTKEY_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
int value_size;
char *value;
zend_string *key = NULL;
dpiterinit(dba->dbf);
value = dpiternext(dba->dbf, &value_size);
if (value) {
key = zend_string_init(value, value_size, /* persistent */ false);
free(value);
}
return key;
}
DBA_NEXTKEY_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
int value_size;
char *value;
zend_string *key = NULL;
value = dpiternext(dba->dbf, &value_size);
if (value) {
key = zend_string_init(value, value_size, /* persistent */ false);
free(value);
}
return key;
}
DBA_OPTIMIZE_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
dpoptimize(dba->dbf, 0);
return SUCCESS;
}
DBA_SYNC_FUNC(qdbm)
{
dba_qdbm_data *dba = info->dbf;
dpsync(dba->dbf);
return SUCCESS;
}
DBA_INFO_FUNC(qdbm)
{
return estrdup(dpversion);
}
#endif
| 3,871 | 20.274725 | 116 |
c
|
php-src
|
php-src-master/ext/dba/dba_tcadb.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: Michael Maclean <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef DBA_TCADB
#include "php_tcadb.h"
#ifdef TCADB_INCLUDE_FILE
#include TCADB_INCLUDE_FILE
#endif
typedef struct {
TCADB *tcadb;
} dba_tcadb_data;
DBA_OPEN_FUNC(tcadb)
{
char *path_string;
TCADB *tcadb = tcadbnew();
if (tcadb) {
switch(info->mode) {
case DBA_READER:
spprintf(&path_string, 0, "%s#mode=r", ZSTR_VAL(info->path));
break;
case DBA_WRITER:
spprintf(&path_string, 0, "%s#mode=w", ZSTR_VAL(info->path));
break;
case DBA_CREAT:
spprintf(&path_string, 0, "%s#mode=wc", ZSTR_VAL(info->path));
break;
case DBA_TRUNC:
spprintf(&path_string, 0, "%s#mode=wct", ZSTR_VAL(info->path));
break;
default:
tcadbdel(tcadb);
return FAILURE;
}
if (!tcadbopen(tcadb, path_string)) {
efree(path_string);
tcadbdel(tcadb);
return FAILURE;
}
efree(path_string);
info->dbf = pemalloc(sizeof(dba_tcadb_data), info->flags & DBA_PERSISTENT);
memset(info->dbf, 0, sizeof(dba_tcadb_data));
((dba_tcadb_data *) info->dbf)->tcadb = tcadb;
return SUCCESS;
}
return FAILURE;
}
DBA_CLOSE_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
tcadbclose(dba->tcadb);
tcadbdel(dba->tcadb);
pefree(dba, info->flags & DBA_PERSISTENT);
}
DBA_FETCH_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
char *value;
int value_size;
zend_string *fetched_val = NULL;
value = tcadbget(dba->tcadb, ZSTR_VAL(key), ZSTR_LEN(key), &value_size);
if (value) {
fetched_val = zend_string_init(value, value_size, /* persistent */ false);
tcfree(value);
}
return fetched_val;
}
DBA_UPDATE_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
int result;
if (mode == 1) {
/* Insert */
if (tcadbvsiz(dba->tcadb, ZSTR_VAL(key), ZSTR_LEN(key)) > -1) {
return FAILURE;
}
}
result = tcadbput(dba->tcadb, ZSTR_VAL(key), ZSTR_LEN(key), ZSTR_VAL(val), ZSTR_LEN(val));
if (result) {
return SUCCESS;
}
php_error_docref(NULL, E_WARNING, "Error updating data");
return FAILURE;
}
DBA_EXISTS_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
char *value;
int value_len;
value = tcadbget(dba->tcadb, ZSTR_VAL(key), ZSTR_LEN(key), &value_len);
if (value) {
tcfree(value);
return SUCCESS;
}
return FAILURE;
}
DBA_DELETE_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
return tcadbout(dba->tcadb, ZSTR_VAL(key), ZSTR_LEN(key)) ? SUCCESS : FAILURE;
}
DBA_FIRSTKEY_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
int value_size;
char *value;
zend_string *key = NULL;
tcadbiterinit(dba->tcadb);
value = tcadbiternext(dba->tcadb, &value_size);
if (value) {
key = zend_string_init(value, value_size, /* persistent */ false);
tcfree(value);
}
return key;
}
DBA_NEXTKEY_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
int value_size;
char *value;
zend_string *key = NULL;
value = tcadbiternext(dba->tcadb, &value_size);
if (value) {
key = zend_string_init(value, value_size, /* persistent */ false);
tcfree(value);
}
return key;
}
DBA_OPTIMIZE_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
#if _TC_LIBVER >= 811
return tcadboptimize(dba->tcadb, NULL) ? SUCCESS : FAILURE;
#else
return FAILURE;
#endif
}
DBA_SYNC_FUNC(tcadb)
{
dba_tcadb_data *dba = info->dbf;
return tcadbsync(dba->tcadb) ? SUCCESS : FAILURE;
}
DBA_INFO_FUNC(tcadb)
{
return estrdup(tcversion);
}
#endif
| 4,350 | 20.539604 | 91 |
c
|
php-src
|
php-src-master/ext/dba/php_dba.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: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_DBA_H
#define PHP_DBA_H
#include "php_version.h"
#define PHP_DBA_VERSION PHP_VERSION
#ifdef HAVE_DBA
typedef enum {
/* do not allow 0 here */
DBA_READER = 1,
DBA_WRITER,
DBA_TRUNC,
DBA_CREAT
} dba_mode_t;
typedef struct dba_lock {
php_stream *fp;
int mode; /* LOCK_EX,LOCK_SH */
} dba_lock;
typedef struct dba_info {
/* public */
void *dbf; /* ptr to private data or whatever */
zend_string *path;
dba_mode_t mode;
php_stream *fp; /* this is the database stream for builtin handlers */
int fd;
int file_permission;
zend_long map_size;
/* -1 for default driver flags */
zend_long driver_flags;
/* private */
int flags; /* whether and how dba did locking and other flags*/
const struct dba_handler *hnd;
dba_lock lock;
} dba_info;
#define DBA_DEFAULT_DRIVER_FLAGS -1
#define DBA_LOCK_READER (0x0001)
#define DBA_LOCK_WRITER (0x0002)
#define DBA_LOCK_CREAT (0x0004)
#define DBA_LOCK_TRUNC (0x0008)
#define DBA_LOCK_EXT (0)
#define DBA_LOCK_ALL (DBA_LOCK_READER|DBA_LOCK_WRITER|DBA_LOCK_CREAT|DBA_LOCK_TRUNC)
#define DBA_LOCK_WCT (DBA_LOCK_WRITER|DBA_LOCK_CREAT|DBA_LOCK_TRUNC)
#define DBA_STREAM_OPEN (0x0010)
#define DBA_PERSISTENT (0x0020)
#define DBA_CAST_AS_FD (0x0050)
#define DBA_NO_APPEND (0x00D0)
extern zend_module_entry dba_module_entry;
#define dba_module_ptr &dba_module_entry
typedef struct dba_handler {
const char *name; /* handler name */
int flags; /* whether and how dba does locking and other flags*/
zend_result (*open)(dba_info *, const char **error);
void (*close)(dba_info *);
zend_string* (*fetch)(dba_info *, zend_string *, int);
zend_result (*update)(dba_info *, zend_string *, zend_string *, int);
zend_result (*exists)(dba_info *, zend_string *);
zend_result (*delete)(dba_info *, zend_string *);
zend_string* (*firstkey)(dba_info *);
zend_string* (*nextkey)(dba_info *);
zend_result (*optimize)(dba_info *);
zend_result (*sync)(dba_info *);
char* (*info)(const struct dba_handler *hnd, dba_info *);
/* dba_info==NULL: Handler info, dba_info!=NULL: Database info */
} dba_handler;
/* common prototypes which must be supplied by modules */
#define DBA_OPEN_FUNC(x) \
zend_result dba_open_##x(dba_info *info, const char **error)
#define DBA_CLOSE_FUNC(x) \
void dba_close_##x(dba_info *info)
#define DBA_FETCH_FUNC(x) \
zend_string *dba_fetch_##x(dba_info *info, zend_string *key, int skip)
#define DBA_UPDATE_FUNC(x) \
zend_result dba_update_##x(dba_info *info, zend_string *key, zend_string *val, int mode)
#define DBA_EXISTS_FUNC(x) \
zend_result dba_exists_##x(dba_info *info, zend_string *key)
#define DBA_DELETE_FUNC(x) \
zend_result dba_delete_##x(dba_info *info, zend_string *key)
#define DBA_FIRSTKEY_FUNC(x) \
zend_string *dba_firstkey_##x(dba_info *info)
#define DBA_NEXTKEY_FUNC(x) \
zend_string *dba_nextkey_##x(dba_info *info)
#define DBA_OPTIMIZE_FUNC(x) \
zend_result dba_optimize_##x(dba_info *info)
#define DBA_SYNC_FUNC(x) \
zend_result dba_sync_##x(dba_info *info)
#define DBA_INFO_FUNC(x) \
char *dba_info_##x(const dba_handler *hnd, dba_info *info)
#define DBA_FUNCS(x) \
DBA_OPEN_FUNC(x); \
DBA_CLOSE_FUNC(x); \
DBA_FETCH_FUNC(x); \
DBA_UPDATE_FUNC(x); \
DBA_DELETE_FUNC(x); \
DBA_EXISTS_FUNC(x); \
DBA_FIRSTKEY_FUNC(x); \
DBA_NEXTKEY_FUNC(x); \
DBA_OPTIMIZE_FUNC(x); \
DBA_SYNC_FUNC(x); \
DBA_INFO_FUNC(x)
#else
#define dba_module_ptr NULL
#endif
#define phpext_dba_ptr dba_module_ptr
#endif
| 4,464 | 31.591241 | 89 |
h
|
php-src
|
php-src-master/ext/dba/php_tcadb.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: Michael Maclean <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_TCADB_H
#define PHP_TCADB_H
#ifdef DBA_TCADB
#include "php_dba.h"
DBA_FUNCS(tcadb);
#endif
#endif
| 1,111 | 37.344828 | 75 |
h
|
php-src
|
php-src-master/ext/dba/libcdb/cdb.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* incorporated from D.J.Bernstein's cdb-0.75 (http://cr.yp.to/cdb.html)*/
#ifndef CDB_H
#define CDB_H
#include "uint32.h"
#define CDB_HASHSTART 5381
struct cdb {
php_stream *fp;
uint32 loop; /* number of hash slots searched under this key */
uint32 khash; /* initialized if loop is nonzero */
uint32 kpos; /* initialized if loop is nonzero */
uint32 hpos; /* initialized if loop is nonzero */
uint32 hslots; /* initialized if loop is nonzero */
uint32 dpos; /* initialized if cdb_findnext() returns 1 */
uint32 dlen; /* initialized if cdb_findnext() returns 1 */
};
uint32 cdb_hash(char *, unsigned int);
void cdb_free(struct cdb *);
void cdb_init(struct cdb *, php_stream *fp);
int cdb_read(struct cdb *, char *, unsigned int, uint32);
void cdb_findstart(struct cdb *);
int cdb_findnext(struct cdb *, char *, unsigned int);
int cdb_find(struct cdb *, char *, unsigned int);
#define cdb_datapos(c) ((c)->dpos)
#define cdb_datalen(c) ((c)->dlen)
const char *cdb_version(void);
#endif
| 1,999 | 36.037037 | 75 |
h
|
php-src
|
php-src-master/ext/dba/libcdb/cdb_make.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id: 570e3625b0cea5c29455cecf40fdfd491c0eb3c6 $ */
/* incorporated from D.J.Bernstein's cdb-0.75 (http://cr.yp.to/cdb.html)*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include "cdb.h"
#include "cdb_make.h"
#include "uint32.h"
/* {{{ cdb_make_write */
static int cdb_make_write(struct cdb_make *c, char *buf, uint32 sz) {
return php_stream_write(c->fp, buf, sz) == sz ? 0 : -1;
}
/* {{{ cdb_posplus */
static int cdb_posplus(struct cdb_make *c, uint32 len)
{
uint32 newpos = c->pos + len;
if (newpos < len) {
errno = ENOMEM;
return -1;
}
c->pos = newpos;
return 0;
}
/* }}} */
/* {{{ cdb_make_start */
int cdb_make_start(struct cdb_make *c, php_stream * f)
{
c->head = 0;
c->split = 0;
c->hash = 0;
c->numentries = 0;
c->fp = f;
c->pos = sizeof(c->final);
if (php_stream_seek(f, c->pos, SEEK_SET) == -1) {
php_error_docref(NULL, E_NOTICE, "Fseek failed");
return -1;
}
return php_stream_tell(c->fp);
}
/* }}} */
/* {{{ cdb_make_addend */
int cdb_make_addend(struct cdb_make *c, unsigned int keylen, unsigned int datalen, uint32 h)
{
struct cdb_hplist *head;
head = c->head;
if (!head || (head->num >= CDB_HPLIST)) {
head = (struct cdb_hplist *) emalloc(sizeof(struct cdb_hplist));
if (!head)
return -1;
head->num = 0;
head->next = c->head;
c->head = head;
}
head->hp[head->num].h = h;
head->hp[head->num].p = c->pos;
++head->num;
++c->numentries;
if (cdb_posplus(c,8) == -1)
return -1;
if (cdb_posplus(c, keylen) == -1)
return -1;
if (cdb_posplus(c, datalen) == -1)
return -1;
return 0;
}
/* }}} */
/* {{{ cdb_make_addbegin */
int cdb_make_addbegin(struct cdb_make *c, unsigned int keylen, unsigned int datalen)
{
char buf[8];
if (keylen > 0xffffffff) {
errno = ENOMEM;
return -1;
}
if (datalen > 0xffffffff) {
errno = ENOMEM;
return -1;
}
uint32_pack(buf, keylen);
uint32_pack(buf + 4, datalen);
if (cdb_make_write(c, buf, 8) != 0)
return -1;
return 0;
}
/* {{{ cdb_make_add */
int cdb_make_add(struct cdb_make *c,char *key,unsigned int keylen,char *data,unsigned int datalen)
{
if (cdb_make_addbegin(c, keylen, datalen) == -1)
return -1;
if (cdb_make_write(c, key, keylen) != 0)
return -1;
if (cdb_make_write(c, data, datalen) != 0)
return -1;
return cdb_make_addend(c, keylen, datalen, cdb_hash(key, keylen));
}
/* }}} */
/* {{{ cdb_make_finish */
int cdb_make_finish(struct cdb_make *c)
{
char buf[8];
int i;
uint32 len;
uint32 u;
uint32 memsize;
uint32 count;
uint32 where;
struct cdb_hplist *x;
struct cdb_hp *hp;
for (i = 0;i < 256;++i)
c->count[i] = 0;
for (x = c->head; x; x = x->next) {
i = x->num;
while (i--)
++c->count[255 & x->hp[i].h];
}
memsize = 1;
for (i = 0;i < 256;++i) {
u = c->count[i] * 2;
if (u > memsize)
memsize = u;
}
memsize += c->numentries; /* no overflow possible up to now */
u = (uint32) 0 - (uint32) 1;
u /= sizeof(struct cdb_hp);
if (memsize > u) {
errno = ENOMEM;
return -1;
}
c->split = (struct cdb_hp *) safe_emalloc(memsize, sizeof(struct cdb_hp), 0);
if (!c->split)
return -1;
c->hash = c->split + c->numentries;
u = 0;
for (i = 0;i < 256;++i) {
u += c->count[i]; /* bounded by numentries, so no overflow */
c->start[i] = u;
}
for (x = c->head; x; x = x->next) {
i = x->num;
while (i--)
c->split[--c->start[255 & x->hp[i].h]] = x->hp[i];
}
for (i = 0;i < 256;++i) {
count = c->count[i];
len = count + count; /* no overflow possible */
uint32_pack(c->final + 8 * i,c->pos);
uint32_pack(c->final + 8 * i + 4,len);
for (u = 0;u < len;++u)
c->hash[u].h = c->hash[u].p = 0;
hp = c->split + c->start[i];
for (u = 0;u < count;++u) {
where = (hp->h >> 8) % len;
while (c->hash[where].p)
if (++where == len)
where = 0;
c->hash[where] = *hp++;
}
for (u = 0;u < len;++u) {
uint32_pack(buf, c->hash[u].h);
uint32_pack(buf + 4, c->hash[u].p);
if (cdb_make_write(c, buf, 8) != 0)
return -1;
if (cdb_posplus(c, 8) == -1)
return -1;
}
}
if (c->split)
efree(c->split);
for (x = c->head; x; c->head = x) {
x = x->next;
efree(c->head);
}
if (php_stream_flush(c->fp) != 0)
return -1;
php_stream_rewind(c->fp);
if (php_stream_tell(c->fp) != 0)
return -1;
if (cdb_make_write(c, c->final, sizeof(c->final)) != 0)
return -1;
return php_stream_flush(c->fp);
}
/* }}} */
/* {{{ cdb_make_version */
const char *cdb_make_version(void)
{
return "0.75, $Id: 570e3625b0cea5c29455cecf40fdfd491c0eb3c6 $";
}
| 5,621 | 22.135802 | 98 |
c
|
php-src
|
php-src-master/ext/dba/libcdb/cdb_make.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* incorporated from D.J.Bernstein's cdb-0.75 (http://cr.yp.to/cdb.html)*/
#ifndef CDB_MAKE_H
#define CDB_MAKE_H
#include <stdio.h>
#include "uint32.h"
#define CDB_HPLIST 1000
struct cdb_hp {
uint32 h;
uint32 p;
};
struct cdb_hplist {
struct cdb_hp hp[CDB_HPLIST];
struct cdb_hplist *next;
int num;
} ;
struct cdb_make {
/* char bspace[8192]; */
char final[2048];
uint32 count[256];
uint32 start[256];
struct cdb_hplist *head;
struct cdb_hp *split; /* includes space for hash */
struct cdb_hp *hash;
uint32 numentries;
/* buffer b; */
uint32 pos;
/* int fd; */
php_stream * fp;
};
int cdb_make_start(struct cdb_make *, php_stream *);
int cdb_make_addbegin(struct cdb_make *, unsigned int, unsigned int);
int cdb_make_addend(struct cdb_make *, unsigned int, unsigned int, uint32);
int cdb_make_add(struct cdb_make *, char *, unsigned int, char *, unsigned int);
int cdb_make_finish(struct cdb_make *);
const char *cdb_make_version(void);
#endif
| 1,965 | 31.229508 | 80 |
h
|
php-src
|
php-src-master/ext/dba/libcdb/uint32.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* incorporated from D.J.Bernstein's cdb-0.75 (http://cr.yp.to/cdb.html)*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "uint32.h"
/* {{{ uint32_pack */
void uint32_pack(char *out, uint32 in)
{
out[0] = in&0xff; in>>=8;
out[1] = in&0xff; in>>=8;
out[2] = in&0xff; in>>=8;
out[3] = in&0xff;
}
/* }}} */
/* {{{ uint32_unpack */
void uint32_unpack(const char *in, uint32 *out)
{
*out = (((uint32)(unsigned char)in[3])<<24) |
(((uint32)(unsigned char)in[2])<<16) |
(((uint32)(unsigned char)in[1])<<8) |
(((uint32)(unsigned char)in[0]));
}
/* }}} */
| 1,604 | 33.891304 | 75 |
c
|
php-src
|
php-src-master/ext/dba/libcdb/uint32.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* incorporated from D.J.Bernstein's cdb-0.75 (http://cr.yp.to/cdb.html)*/
#ifndef UINT32_H
#define UINT32_H
#if SIZEOF_INT == 4
/* Most 32-bit and 64-bit systems have 32-bit ints */
typedef unsigned int uint32;
#elif SIZEOF_LONG == 4
/* 16-bit systems? */
typedef unsigned long uint32;
#else
#error Need type which holds 32 bits
#endif
void uint32_pack(char *out, uint32 in);
void uint32_unpack(const char *in, uint32 *out);
#endif
| 1,433 | 38.833333 | 75 |
h
|
php-src
|
php-src-master/ext/dba/libflatfile/flatfile.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: Marcus Boerger <[email protected]> |
| based on ext/db/db.c by: |
| Rasmus Lerdorf <[email protected]> |
| Jim Winstead <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id: 7fa995b7bd21d527a78003f309ad0190b8e6fd95 $ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_globals.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "flatfile.h"
#define FLATFILE_BLOCK_SIZE 1024
/*
* ret = -1 means that database was opened for read-only
* ret = 0 success
* ret = 1 key already exists - nothing done
*/
/* {{{ flatfile_store */
int flatfile_store(flatfile *dba, datum key_datum, datum value_datum, int mode) {
if (mode == FLATFILE_INSERT) {
if (flatfile_findkey(dba, key_datum)) {
return 1;
}
php_stream_seek(dba->fp, 0L, SEEK_END);
php_stream_printf(dba->fp, "%zu\n", key_datum.dsize);
php_stream_flush(dba->fp);
if (php_stream_write(dba->fp, key_datum.dptr, key_datum.dsize) < key_datum.dsize) {
return -1;
}
php_stream_printf(dba->fp, "%zu\n", value_datum.dsize);
php_stream_flush(dba->fp);
if (php_stream_write(dba->fp, value_datum.dptr, value_datum.dsize) < value_datum.dsize) {
return -1;
}
} else { /* FLATFILE_REPLACE */
flatfile_delete(dba, key_datum);
php_stream_printf(dba->fp, "%zu\n", key_datum.dsize);
php_stream_flush(dba->fp);
if (php_stream_write(dba->fp, key_datum.dptr, key_datum.dsize) < key_datum.dsize) {
return -1;
}
php_stream_printf(dba->fp, "%zu\n", value_datum.dsize);
if (php_stream_write(dba->fp, value_datum.dptr, value_datum.dsize) < value_datum.dsize) {
return -1;
}
}
php_stream_flush(dba->fp);
return 0;
}
/* }}} */
/* {{{ flatfile_fetch */
datum flatfile_fetch(flatfile *dba, datum key_datum) {
datum value_datum = {NULL, 0};
char buf[16];
if (flatfile_findkey(dba, key_datum)) {
if (php_stream_gets(dba->fp, buf, sizeof(buf))) {
value_datum.dsize = atoi(buf);
value_datum.dptr = safe_emalloc(value_datum.dsize, 1, 1);
value_datum.dsize = php_stream_read(dba->fp, value_datum.dptr, value_datum.dsize);
} else {
value_datum.dptr = NULL;
value_datum.dsize = 0;
}
}
return value_datum;
}
/* }}} */
/* {{{ flatfile_delete */
int flatfile_delete(flatfile *dba, datum key_datum) {
char *key = key_datum.dptr;
size_t size = key_datum.dsize;
size_t buf_size = FLATFILE_BLOCK_SIZE;
char *buf = emalloc(buf_size);
size_t num;
size_t pos;
php_stream_rewind(dba->fp);
while(!php_stream_eof(dba->fp)) {
/* read in the length of the key name */
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
pos = php_stream_tell(dba->fp);
/* read in the key name */
num = php_stream_read(dba->fp, buf, num);
if (size == num && !memcmp(buf, key, size)) {
php_stream_seek(dba->fp, pos, SEEK_SET);
php_stream_putc(dba->fp, 0);
php_stream_flush(dba->fp);
php_stream_seek(dba->fp, 0L, SEEK_END);
efree(buf);
return SUCCESS;
}
/* read in the length of the value */
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
/* read in the value */
num = php_stream_read(dba->fp, buf, num);
}
efree(buf);
return FAILURE;
}
/* }}} */
/* {{{ flatfile_findkey */
int flatfile_findkey(flatfile *dba, datum key_datum) {
size_t buf_size = FLATFILE_BLOCK_SIZE;
char *buf = emalloc(buf_size);
size_t num;
int ret=0;
void *key = key_datum.dptr;
size_t size = key_datum.dsize;
php_stream_rewind(dba->fp);
while (!php_stream_eof(dba->fp)) {
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
if (size == num) {
if (!memcmp(buf, key, size)) {
ret = 1;
break;
}
}
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
}
efree(buf);
return ret;
}
/* }}} */
/* {{{ flatfile_firstkey */
datum flatfile_firstkey(flatfile *dba) {
datum res;
size_t num;
size_t buf_size = FLATFILE_BLOCK_SIZE;
char *buf = emalloc(buf_size);
php_stream_rewind(dba->fp);
while(!php_stream_eof(dba->fp)) {
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
if (*(buf) != 0) {
dba->CurrentFlatFilePos = php_stream_tell(dba->fp);
res.dptr = buf;
res.dsize = num;
return res;
}
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
}
efree(buf);
res.dptr = NULL;
res.dsize = 0;
return res;
}
/* }}} */
/* {{{ flatfile_nextkey */
datum flatfile_nextkey(flatfile *dba) {
datum res;
size_t num;
size_t buf_size = FLATFILE_BLOCK_SIZE;
char *buf = emalloc(buf_size);
php_stream_seek(dba->fp, dba->CurrentFlatFilePos, SEEK_SET);
while(!php_stream_eof(dba->fp)) {
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
if (!php_stream_gets(dba->fp, buf, 15)) {
break;
}
num = atoi(buf);
if (num >= buf_size) {
buf_size = num + FLATFILE_BLOCK_SIZE;
buf = erealloc(buf, buf_size);
}
num = php_stream_read(dba->fp, buf, num);
if (*(buf)!=0) {
dba->CurrentFlatFilePos = php_stream_tell(dba->fp);
res.dptr = buf;
res.dsize = num;
return res;
}
}
efree(buf);
res.dptr = NULL;
res.dsize = 0;
return res;
}
/* }}} */
/* {{{ flatfile_version */
const char *flatfile_version(void)
{
return "1.0, $Id: 7fa995b7bd21d527a78003f309ad0190b8e6fd95 $";
}
/* }}} */
| 7,330 | 24.81338 | 91 |
c
|
php-src
|
php-src-master/ext/dba/libflatfile/flatfile.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: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_LIB_FLATFILE_H
#define PHP_LIB_FLATFILE_H
typedef struct {
char *dptr;
size_t dsize;
} datum;
typedef struct {
char *lockfn;
int lockfd;
php_stream *fp;
size_t CurrentFlatFilePos;
datum nextkey;
} flatfile;
#define FLATFILE_INSERT 1
#define FLATFILE_REPLACE 0
int flatfile_store(flatfile *dba, datum key_datum, datum value_datum, int mode);
datum flatfile_fetch(flatfile *dba, datum key_datum);
int flatfile_delete(flatfile *dba, datum key_datum);
int flatfile_findkey(flatfile *dba, datum key_datum);
datum flatfile_firstkey(flatfile *dba);
datum flatfile_nextkey(flatfile *dba);
const char *flatfile_version(void);
#endif
| 1,644 | 35.555556 | 80 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.