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/sapi/phpdbg/phpdbg_lexer.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_LEXER_H
#define PHPDBG_LEXER_H
#include "phpdbg_cmd.h"
typedef struct {
unsigned int len;
unsigned char *text;
unsigned char *cursor;
unsigned char *marker;
unsigned char *ctxmarker;
int state;
} phpdbg_lexer_data;
#define yyparse phpdbg_parse
#define yylex phpdbg_lex
void phpdbg_init_lexer (phpdbg_param_t *stack, char *input);
int phpdbg_lex (phpdbg_param_t* yylval);
#endif
| 1,594 | 37.902439 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_list.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_LIST_H
#define PHPDBG_LIST_H
#include "TSRM.h"
#include "phpdbg_cmd.h"
#define PHPDBG_LIST(name) PHPDBG_COMMAND(list_##name)
#define PHPDBG_LIST_HANDLER(name) PHPDBG_COMMAND_HANDLER(list_##name)
PHPDBG_LIST(lines);
PHPDBG_LIST(class);
PHPDBG_LIST(method);
PHPDBG_LIST(func);
void phpdbg_list_function_byname(const char *, size_t);
void phpdbg_list_function(const zend_function *);
void phpdbg_list_file(zend_string *, uint32_t, int, uint32_t);
extern const phpdbg_command_t phpdbg_list_commands[];
void phpdbg_init_list(void);
void phpdbg_list_update(void);
typedef struct {
char *buf;
size_t len;
zend_op_array op_array;
uint32_t lines;
uint32_t line[1];
} phpdbg_file_source;
#endif /* PHPDBG_LIST_H */
| 1,888 | 36.039216 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_out.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: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "zend.h"
#include "php.h"
#include "spprintf.h"
#include "phpdbg.h"
#include "phpdbg_io.h"
#include "ext/standard/html.h"
#ifdef _WIN32
# include "win32/time.h"
#endif
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
PHPDBG_API int _phpdbg_asprintf(char **buf, const char *format, ...) {
int ret;
va_list va;
va_start(va, format);
ret = vasprintf(buf, format, va);
va_end(va);
return ret;
}
static int phpdbg_process_print(int fd, int type, const char *msg, int msglen) {
char *msgout = NULL;
int msgoutlen = FAILURE;
switch (type) {
case P_ERROR:
if (!PHPDBG_G(last_was_newline)) {
phpdbg_mixed_write(fd, ZEND_STRL("\n"));
PHPDBG_G(last_was_newline) = 1;
}
if (PHPDBG_G(flags) & PHPDBG_IS_COLOURED) {
msgoutlen = phpdbg_asprintf(&msgout, "\033[%sm[%.*s]\033[0m\n", PHPDBG_G(colors)[PHPDBG_COLOR_ERROR]->code, msglen, msg);
} else {
msgoutlen = phpdbg_asprintf(&msgout, "[%.*s]\n", msglen, msg);
}
break;
case P_NOTICE:
if (!PHPDBG_G(last_was_newline)) {
phpdbg_mixed_write(fd, ZEND_STRL("\n"));
PHPDBG_G(last_was_newline) = 1;
}
if (PHPDBG_G(flags) & PHPDBG_IS_COLOURED) {
msgoutlen = phpdbg_asprintf(&msgout, "\033[%sm[%.*s]\033[0m\n", PHPDBG_G(colors)[PHPDBG_COLOR_NOTICE]->code, msglen, msg);
} else {
msgoutlen = phpdbg_asprintf(&msgout, "[%.*s]\n", msglen, msg);
}
break;
case P_WRITELN:
if (msg) {
msgoutlen = phpdbg_asprintf(&msgout, "%.*s\n", msglen, msg);
} else {
msgoutlen = 1;
msgout = strdup("\n");
}
PHPDBG_G(last_was_newline) = 1;
break;
case P_WRITE:
if (msg) {
msgout = pestrndup(msg, msglen, 1);
msgoutlen = msglen;
PHPDBG_G(last_was_newline) = msg[msglen - 1] == '\n';
} else {
msgoutlen = 0;
msgout = strdup("");
}
break;
case P_STDOUT:
case P_STDERR:
if (msg) {
PHPDBG_G(last_was_newline) = msg[msglen - 1] == '\n';
phpdbg_mixed_write(fd, msg, msglen);
}
return msglen;
/* no formatting on logging output */
case P_LOG:
if (msg) {
struct timeval tp;
if (gettimeofday(&tp, NULL) == SUCCESS) {
msgoutlen = phpdbg_asprintf(&msgout, "[%ld %.8F]: %.*s\n", tp.tv_sec, tp.tv_usec / 1000000., msglen, msg);
} else {
msgoutlen = FAILURE;
}
}
break;
EMPTY_SWITCH_DEFAULT_CASE()
}
if (msgoutlen != FAILURE) {
phpdbg_mixed_write(fd, msgout, msgoutlen);
free(msgout);
}
return msgoutlen;
} /* }}} */
PHPDBG_API int phpdbg_vprint(int type, int fd, const char *strfmt, va_list args) {
char *msg = NULL;
int msglen = 0;
int len;
va_list argcpy;
if (strfmt != NULL && strlen(strfmt) > 0L) {
va_copy(argcpy, args);
msglen = vasprintf(&msg, strfmt, argcpy);
va_end(argcpy);
}
if (PHPDBG_G(err_buf).active && type != P_STDOUT && type != P_STDERR) {
phpdbg_free_err_buf();
PHPDBG_G(err_buf).type = type;
PHPDBG_G(err_buf).fd = fd;
PHPDBG_G(err_buf).msg = msg;
PHPDBG_G(err_buf).msglen = msglen;
return msglen;
}
if (UNEXPECTED(msglen == 0)) {
len = 0;
} else {
len = phpdbg_process_print(fd, type, msg, msglen);
}
if (msg) {
free(msg);
}
return len;
}
PHPDBG_API void phpdbg_free_err_buf(void) {
if (PHPDBG_G(err_buf).type == 0) {
return;
}
free(PHPDBG_G(err_buf).msg);
PHPDBG_G(err_buf).type = 0;
}
PHPDBG_API void phpdbg_activate_err_buf(bool active) {
PHPDBG_G(err_buf).active = active;
}
PHPDBG_API int phpdbg_output_err_buf(const char *strfmt, ...) {
int len;
va_list args;
int errbuf_active = PHPDBG_G(err_buf).active;
if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
return 0;
}
PHPDBG_G(err_buf).active = 0;
va_start(args, strfmt);
len = phpdbg_vprint(PHPDBG_G(err_buf).type, PHPDBG_G(err_buf).fd, strfmt, args);
va_end(args);
PHPDBG_G(err_buf).active = errbuf_active;
phpdbg_free_err_buf();
return len;
}
PHPDBG_API int phpdbg_print(int type, int fd, const char *strfmt, ...) {
va_list args;
int len;
if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
return 0;
}
va_start(args, strfmt);
len = phpdbg_vprint(type, fd, strfmt, args);
va_end(args);
return len;
}
PHPDBG_API int phpdbg_log_internal(int fd, const char *fmt, ...) {
va_list args;
char *buffer;
int buflen;
int len = 0;
va_start(args, fmt);
buflen = vasprintf(&buffer, fmt, args);
va_end(args);
len = phpdbg_mixed_write(fd, buffer, buflen);
free(buffer);
return len;
}
PHPDBG_API int phpdbg_out_internal(int fd, const char *fmt, ...) {
va_list args;
char *buffer;
int buflen;
int len = 0;
if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
return 0;
}
va_start(args, fmt);
buflen = vasprintf(&buffer, fmt, args);
va_end(args);
len = phpdbg_mixed_write(fd, buffer, buflen);
free(buffer);
return len;
}
| 5,856 | 23.004098 | 126 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_out.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_OUT_H
#define PHPDBG_OUT_H
/**
* Error/notice/formatting helpers
*/
enum {
P_ERROR = 1,
P_NOTICE,
P_WRITELN,
P_WRITE,
P_STDOUT,
P_STDERR,
P_LOG
};
PHPDBG_API int phpdbg_print(int severity, int fd, const char *strfmt, ...) PHP_ATTRIBUTE_FORMAT(printf, 3, 4);
PHPDBG_API int phpdbg_log_internal(int fd, const char *fmt, ...) PHP_ATTRIBUTE_FORMAT(printf, 2, 3);
PHPDBG_API int phpdbg_out_internal(int fd, const char *fmt, ...) PHP_ATTRIBUTE_FORMAT(printf, 2, 3);
#define phpdbg_error(strfmt, ...) phpdbg_print(P_ERROR , PHPDBG_G(io)[PHPDBG_STDOUT].fd, strfmt, ##__VA_ARGS__)
#define phpdbg_notice(strfmt, ...) phpdbg_print(P_NOTICE , PHPDBG_G(io)[PHPDBG_STDOUT].fd, strfmt, ##__VA_ARGS__)
#define phpdbg_writeln(strfmt, ...) phpdbg_print(P_WRITELN, PHPDBG_G(io)[PHPDBG_STDOUT].fd, strfmt, ##__VA_ARGS__)
#define phpdbg_write(strfmt, ...) phpdbg_print(P_WRITE , PHPDBG_G(io)[PHPDBG_STDOUT].fd, strfmt, ##__VA_ARGS__)
#define phpdbg_log(fmt, ...) phpdbg_log_internal(PHPDBG_G(io)[PHPDBG_STDOUT].fd, fmt, ##__VA_ARGS__)
#define phpdbg_out(fmt, ...) phpdbg_out_internal(PHPDBG_G(io)[PHPDBG_STDOUT].fd, fmt, ##__VA_ARGS__)
#define phpdbg_script(type, strfmt, ...) phpdbg_print(type, PHPDBG_G(io)[PHPDBG_STDOUT].fd, strfmt, ##__VA_ARGS__)
#define phpdbg_asprintf(buf, ...) _phpdbg_asprintf(buf, ##__VA_ARGS__)
PHPDBG_API int _phpdbg_asprintf(char **buf, const char *format, ...);
#if PHPDBG_DEBUG
# define phpdbg_debug(strfmt, ...) phpdbg_log_internal(PHPDBG_G(io)[PHPDBG_STDERR].fd, strfmt, ##__VA_ARGS__)
#else
# define phpdbg_debug(strfmt, ...)
#endif
PHPDBG_API void phpdbg_free_err_buf(void);
PHPDBG_API void phpdbg_activate_err_buf(bool active);
PHPDBG_API int phpdbg_output_err_buf(const char *strfmt, ...);
/* {{{ For separation */
#define SEPARATE "------------------------------------------------" /* }}} */
#endif /* PHPDBG_OUT_H */
| 3,116 | 45.522388 | 125 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_print.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_PRINT_H
#define PHPDBG_PRINT_H
#include "phpdbg_cmd.h"
#define PHPDBG_PRINT(name) PHPDBG_COMMAND(print_##name)
/**
* Printer Forward Declarations
*/
PHPDBG_PRINT(exec);
PHPDBG_PRINT(opline);
PHPDBG_PRINT(class);
PHPDBG_PRINT(method);
PHPDBG_PRINT(func);
PHPDBG_PRINT(stack);
extern const phpdbg_command_t phpdbg_print_commands[];
void phpdbg_print_opcodes(const char *function);
void phpdbg_print_opline(zend_execute_data *execute_data, bool ignore_flags);
#endif /* PHPDBG_PRINT_H */
| 1,655 | 38.428571 | 77 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_prompt.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_PROMPT_H
#define PHPDBG_PROMPT_H
/* {{{ */
void phpdbg_string_init(char *buffer);
void phpdbg_init(char *init_file, size_t init_file_len, bool use_default);
void phpdbg_try_file_init(char *init_file, size_t init_file_len, bool free_init);
int phpdbg_interactive(bool allow_async_unsafe, char *input);
int phpdbg_compile(void);
int phpdbg_compile_stdin(zend_string *code);
void phpdbg_force_interruption(void);
/* }}} */
/* {{{ phpdbg command handlers */
PHPDBG_COMMAND(exec);
PHPDBG_COMMAND(stdin);
PHPDBG_COMMAND(step);
PHPDBG_COMMAND(continue);
PHPDBG_COMMAND(run);
PHPDBG_COMMAND(ev);
PHPDBG_COMMAND(until);
PHPDBG_COMMAND(finish);
PHPDBG_COMMAND(leave);
PHPDBG_COMMAND(frame);
PHPDBG_COMMAND(print);
PHPDBG_COMMAND(break);
PHPDBG_COMMAND(back);
PHPDBG_COMMAND(list);
PHPDBG_COMMAND(info);
PHPDBG_COMMAND(clean);
PHPDBG_COMMAND(clear);
PHPDBG_COMMAND(help);
PHPDBG_COMMAND(sh);
PHPDBG_COMMAND(dl);
PHPDBG_COMMAND(generator);
PHPDBG_COMMAND(set);
PHPDBG_COMMAND(source);
PHPDBG_COMMAND(export);
PHPDBG_COMMAND(register);
PHPDBG_COMMAND(quit);
PHPDBG_COMMAND(watch);
PHPDBG_COMMAND(next);
PHPDBG_COMMAND(eol); /* }}} */
/* {{{ prompt commands */
extern const phpdbg_command_t phpdbg_prompt_commands[]; /* }}} */
void phpdbg_execute_ex(zend_execute_data *execute_data);
#endif /* PHPDBG_PROMPT_H */
| 2,466 | 34.753623 | 81 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_set.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: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "phpdbg.h"
#include "phpdbg_cmd.h"
#include "phpdbg_set.h"
#include "phpdbg_utils.h"
#include "phpdbg_bp.h"
#include "phpdbg_prompt.h"
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
#define PHPDBG_SET_COMMAND_D(f, h, a, m, l, s, flags) \
PHPDBG_COMMAND_D_EXP(f, h, a, m, l, s, &phpdbg_prompt_commands[17], flags)
const phpdbg_command_t phpdbg_set_commands[] = {
PHPDBG_SET_COMMAND_D(prompt, "usage: set prompt [<string>]", 'p', set_prompt, NULL, "|s", 0),
PHPDBG_SET_COMMAND_D(pagination, "usage: set pagination [<on|off>]", 'P', set_pagination, NULL, "|b", PHPDBG_ASYNC_SAFE),
#ifndef _WIN32
PHPDBG_SET_COMMAND_D(color, "usage: set color <element> <color>", 'c', set_color, NULL, "ss", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(colors, "usage: set colors [<on|off>]", 'C', set_colors, NULL, "|b", PHPDBG_ASYNC_SAFE),
#endif
PHPDBG_SET_COMMAND_D(break, "usage: set break id [<on|off>]", 'b', set_break, NULL, "l|b", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(breaks, "usage: set breaks [<on|off>]", 'B', set_breaks, NULL, "|b", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(quiet, "usage: set quiet [<on|off>]", 'q', set_quiet, NULL, "|b", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(stepping, "usage: set stepping [<line|op>]", 's', set_stepping, NULL, "|s", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(refcount, "usage: set refcount [<on|off>]", 'r', set_refcount, NULL, "|b", PHPDBG_ASYNC_SAFE),
PHPDBG_SET_COMMAND_D(lines, "usage: set lines [<number>]", 'l', set_lines, NULL, "|l", PHPDBG_ASYNC_SAFE),
PHPDBG_END_COMMAND
};
PHPDBG_SET(prompt) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Current prompt: %s", phpdbg_get_prompt());
} else {
phpdbg_set_prompt(param->str);
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(pagination) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Pagination %s", PHPDBG_G(flags) & PHPDBG_HAS_PAGINATION ? "on" : "off");
} else switch (param->type) {
case NUMERIC_PARAM: {
if (param->num) {
PHPDBG_G(flags) |= PHPDBG_HAS_PAGINATION;
} else {
PHPDBG_G(flags) &= ~PHPDBG_HAS_PAGINATION;
}
} break;
default:
phpdbg_error("set pagination used incorrectly: set pagination <on|off>");
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(lines) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Lines "ZEND_ULONG_FMT, PHPDBG_G(lines));
} else switch (param->type) {
case NUMERIC_PARAM: {
PHPDBG_G(lines) = param->num;
} break;
default:
phpdbg_error("set lines used incorrectly: set lines <number>");
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(break) /* {{{ */
{
switch (param->type) {
case NUMERIC_PARAM: {
if (param->next) {
if (param->next->num) {
phpdbg_enable_breakpoint(param->num);
} else {
phpdbg_disable_breakpoint(param->num);
}
} else {
phpdbg_breakbase_t *brake = phpdbg_find_breakbase(param->num);
if (brake) {
phpdbg_writeln("Breakpoint #"ZEND_LONG_FMT" %s", param->num, brake->disabled ? "off" : "on");
} else {
phpdbg_error("Failed to find breakpoint #"ZEND_LONG_FMT, param->num);
}
}
} break;
default:
phpdbg_error("set break used incorrectly: set break [id] <on|off>");
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(breaks) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Breakpoints %s",PHPDBG_G(flags) & PHPDBG_IS_BP_ENABLED ? "on" : "off");
} else switch (param->type) {
case NUMERIC_PARAM: {
if (param->num) {
phpdbg_enable_breakpoints();
} else {
phpdbg_disable_breakpoints();
}
} break;
default:
phpdbg_error("set breaks used incorrectly: set breaks <on|off>");
}
return SUCCESS;
} /* }}} */
#ifndef _WIN32
PHPDBG_SET(color) /* {{{ */
{
const phpdbg_color_t *color = phpdbg_get_color(param->next->str, param->next->len);
if (!color) {
phpdbg_error("Failed to find the requested color (%s)", param->next->str);
return SUCCESS;
}
switch (phpdbg_get_element(param->str, param->len)) {
case PHPDBG_COLOR_PROMPT:
phpdbg_notice("setting prompt color to %s (%s)", color->name, color->code);
if (PHPDBG_G(prompt)[1]) {
free(PHPDBG_G(prompt)[1]);
PHPDBG_G(prompt)[1]=NULL;
}
phpdbg_set_color(PHPDBG_COLOR_PROMPT, color);
break;
case PHPDBG_COLOR_ERROR:
phpdbg_notice("setting error color to %s (%s)", color->name, color->code);
phpdbg_set_color(PHPDBG_COLOR_ERROR, color);
break;
case PHPDBG_COLOR_NOTICE:
phpdbg_notice("setting notice color to %s (%s)", color->name, color->code);
phpdbg_set_color(PHPDBG_COLOR_NOTICE, color);
break;
default:
phpdbg_error("Failed to find the requested element (%s)", param->str);
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(colors) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Colors %s", PHPDBG_G(flags) & PHPDBG_IS_COLOURED ? "on" : "off");
} else switch (param->type) {
case NUMERIC_PARAM: {
if (param->num) {
PHPDBG_G(flags) |= PHPDBG_IS_COLOURED;
} else {
PHPDBG_G(flags) &= ~PHPDBG_IS_COLOURED;
}
} break;
default:
phpdbg_error("set colors used incorrectly: set colors <on|off>");
}
return SUCCESS;
} /* }}} */
#endif
PHPDBG_SET(quiet) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Quietness %s", PHPDBG_G(flags) & PHPDBG_IS_QUIET ? "on" : "off");
} else switch (param->type) {
case NUMERIC_PARAM: {
if (param->num) {
PHPDBG_G(flags) |= PHPDBG_IS_QUIET;
} else {
PHPDBG_G(flags) &= ~PHPDBG_IS_QUIET;
}
} break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(stepping) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Stepping %s", PHPDBG_G(flags) & PHPDBG_STEP_OPCODE ? "opcode" : "line");
} else switch (param->type) {
case STR_PARAM: {
if (param->len == sizeof("opcode") - 1 && !memcmp(param->str, "opcode", sizeof("opcode"))) {
PHPDBG_G(flags) |= PHPDBG_STEP_OPCODE;
} else if (param->len == sizeof("line") - 1 && !memcmp(param->str, "line", sizeof("line"))) {
PHPDBG_G(flags) &= ~PHPDBG_STEP_OPCODE;
} else {
phpdbg_error("usage set stepping [<opcode|line>]");
}
} break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
PHPDBG_SET(refcount) /* {{{ */
{
if (!param || param->type == EMPTY_PARAM) {
phpdbg_writeln("Showing refcounts %s", PHPDBG_G(flags) & PHPDBG_IS_QUIET ? "on" : "off");
} else switch (param->type) {
case NUMERIC_PARAM: {
if (param->num) {
PHPDBG_G(flags) |= PHPDBG_SHOW_REFCOUNTS;
} else {
PHPDBG_G(flags) &= ~PHPDBG_SHOW_REFCOUNTS;
}
} break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
| 8,019 | 30.206226 | 134 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_set.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_SET_H
#define PHPDBG_SET_H
#include "phpdbg_cmd.h"
#define PHPDBG_SET(name) PHPDBG_COMMAND(set_##name)
PHPDBG_SET(prompt);
#ifndef _WIN32
PHPDBG_SET(color);
PHPDBG_SET(colors);
#endif
PHPDBG_SET(break);
PHPDBG_SET(breaks);
PHPDBG_SET(quiet);
PHPDBG_SET(stepping);
PHPDBG_SET(refcount);
PHPDBG_SET(pagination);
PHPDBG_SET(lines);
extern const phpdbg_command_t phpdbg_set_commands[];
#endif /* PHPDBG_SET_H */
| 1,575 | 36.52381 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_win.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: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "zend.h"
#include "phpdbg.h"
int mprotect(void *addr, size_t size, int protection) {
int var;
return (int)VirtualProtect(addr, size, protection == (PROT_READ | PROT_WRITE) ? PAGE_READWRITE : PAGE_READONLY, &var);
}
int phpdbg_exception_handler_win32(EXCEPTION_POINTERS *xp) {
EXCEPTION_RECORD *xr = xp->ExceptionRecord;
CONTEXT *xc = xp->ContextRecord;
if(xr->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
if (phpdbg_watchpoint_segfault_handler((void *)xr->ExceptionInformation[1]) == SUCCESS) {
return EXCEPTION_CONTINUE_EXECUTION;
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
| 1,749 | 42.75 | 119 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_win.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_WIN_H
#define PHPDBG_WIN_H
#include "winbase.h"
#include "windows.h"
#include "excpt.h"
#define PROT_READ 1
#define PROT_WRITE 2
int mprotect(void *addr, size_t size, int protection);
void phpdbg_win_set_mm_heap(zend_mm_heap *heap);
int phpdbg_exception_handler_win32(EXCEPTION_POINTERS *xp);
#endif
| 1,468 | 39.805556 | 75 |
h
|
php-src
|
php-src-master/win32/codepage.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]> |
+----------------------------------------------------------------------+
*/
#include <assert.h>
#include "php.h"
#include "SAPI.h"
#ifdef _M_ARM64
# include <arm_neon.h>
#else
# include <emmintrin.h>
#endif // _M_ARM64
#include "win32/console.h"
ZEND_TLS const struct php_win32_cp *cur_cp = NULL;
ZEND_TLS const struct php_win32_cp *orig_cp = NULL;
ZEND_TLS const struct php_win32_cp *cur_out_cp = NULL;
ZEND_TLS const struct php_win32_cp *orig_out_cp = NULL;
ZEND_TLS const struct php_win32_cp *cur_in_cp = NULL;
ZEND_TLS const struct php_win32_cp *orig_in_cp = NULL;
#include "cp_enc_map.c"
__forceinline static wchar_t *php_win32_cp_to_w_int(const char* in, size_t in_len, size_t *out_len, UINT cp, DWORD flags)
{/*{{{*/
wchar_t *ret;
int ret_len, tmp_len;
if (!in || in_len > (size_t)INT_MAX) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER);
return NULL;
}
assert(in_len ? (in[in_len] == L'\0') : 1);
tmp_len = !in_len ? -1 : (int)in_len + 1;
ret_len = MultiByteToWideChar(cp, flags, in, tmp_len, NULL, 0);
if (ret_len == 0) {
SET_ERRNO_FROM_WIN32_CODE(GetLastError());
return NULL;
}
ret = malloc(ret_len * sizeof(wchar_t));
if (!ret) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_OUTOFMEMORY);
return NULL;
}
tmp_len = MultiByteToWideChar(cp, flags, in, tmp_len, ret, ret_len);
if (tmp_len == 0) {
free(ret);
SET_ERRNO_FROM_WIN32_CODE(GetLastError());
return NULL;
}
assert(ret ? tmp_len == ret_len : 1);
assert(ret && !in_len ? wcslen(ret) == ret_len - 1 : 1);
ret[ret_len-1] = L'\0';
if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) {
*out_len = ret_len - 1;
}
return ret;
}/*}}}*/
PW32CP wchar_t *php_win32_cp_conv_utf8_to_w(const char* in, size_t in_len, size_t *out_len)
{/*{{{*/
return php_win32_cp_to_w_int(in, in_len, out_len, CP_UTF8, MB_ERR_INVALID_CHARS);
}/*}}}*/
PW32CP wchar_t *php_win32_cp_conv_cur_to_w(const char* in, size_t in_len, size_t *out_len)
{/*{{{*/
wchar_t *ret;
ret = php_win32_cp_to_w_int(in, in_len, out_len, cur_cp->id, cur_cp->from_w_fl);
return ret;
}/*}}}*/
PW32CP wchar_t *php_win32_cp_conv_to_w(DWORD cp, DWORD flags, const char* in, size_t in_len, size_t *out_len)
{/*{{{*/
return php_win32_cp_to_w_int(in, in_len, out_len, cp, flags);
}/*}}}*/
#define ASCII_FAIL_RETURN() \
if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) { \
*out_len = 0; \
} \
return NULL;
PW32CP wchar_t *php_win32_cp_conv_ascii_to_w(const char* in, size_t in_len, size_t *out_len)
{/*{{{*/
wchar_t *ret, *ret_idx;
const char *idx = in, *end;
char ch_err = 0;
#if PHP_DEBUG
size_t save_in_len = in_len;
#endif
assert(in && in_len ? in[in_len] == '\0' : 1);
if (!in) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER);
return NULL;
} else if (0 == in_len) {
/* Not binary safe. */
in_len = strlen(in);
}
end = in + in_len;
if (in_len > 15) {
const char *aidx = (const char *)ZEND_SLIDE_TO_ALIGNED16(in);
/* Process unaligned chunk. */
while (idx < aidx) {
ch_err |= *idx;
idx++;
}
if (ch_err & 0x80) {
ASCII_FAIL_RETURN()
}
/* Process aligned chunk. */
#ifdef _M_ARM64
uint8x16_t ver_err = {0};
while (end - idx > 15) {
const uint8x16_t block = vld1q_u8((const void*)idx);
ver_err = vorrq_u8(ver_err, block);
idx += 16;
}
ver_err = vshrq_n_u8(ver_err, 7);
if (vmaxvq_u8(ver_err)) {
ASCII_FAIL_RETURN()
}
#else
__m128i vec_err = _mm_setzero_si128();
while (end - idx > 15) {
const __m128i block = _mm_load_si128((__m128i *)idx);
vec_err = _mm_or_si128(vec_err, block);
idx += 16;
}
if (_mm_movemask_epi8(vec_err)) {
ASCII_FAIL_RETURN()
}
#endif // _M_ARM64
}
/* Process the trailing part, or otherwise process string < 16 bytes. */
while (idx < end) {
ch_err |= *idx;
idx++;
}
if (ch_err & 0x80) {
ASCII_FAIL_RETURN()
}
ret = malloc((in_len+1)*sizeof(wchar_t));
if (!ret) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_OUTOFMEMORY);
return NULL;
}
ret_idx = ret;
idx = in;
if (in_len > 15) {
const char *aidx = (const char *)ZEND_SLIDE_TO_ALIGNED16(in);
/* Process unaligned chunk. */
while (idx < aidx) {
*ret_idx++ = (wchar_t)*idx++;
}
/* Process aligned chunk. */
if (end - idx > 15) {
#ifdef _M_ARM64
while (end - idx > 15) {
/*
vst2q_u8 below will store interlaced vector by 8bits, so this will be little endian wchar
at wrote time all windows arm64 is little endian
*/
uint8x16x2_t vec = {/* .val = */{
vld1q_u8((const void*)idx),
{0},
}};
vst2q_u8((void*)ret_idx, vec);
idx += 16;
ret_idx += 16;
}
#else
const __m128i mask = _mm_set1_epi32(0);
while (end - idx > 15) {
const __m128i block = _mm_load_si128((__m128i *)idx);
const __m128i lo = _mm_unpacklo_epi8(block, mask);
_mm_storeu_si128((__m128i *)ret_idx, lo);
ret_idx += 8;
const __m128i hi = _mm_unpackhi_epi8(block, mask);
_mm_storeu_si128((__m128i *)ret_idx, hi);
idx += 16;
ret_idx += 8;
}
#endif // _M_ARM64
}
}
/* Process the trailing part, or otherwise process string < 16 bytes. */
while (idx < end) {
*ret_idx++ = (wchar_t)*idx++;
}
ret[in_len] = L'\0';
assert(ret && !save_in_len ? wcslen(ret) == in_len : 1);
if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) {
*out_len = in_len;
}
return ret;
}/*}}}*/
#undef ASCII_FAIL_RETURN
__forceinline static char *php_win32_cp_from_w_int(const wchar_t* in, size_t in_len, size_t *out_len, UINT cp, DWORD flags)
{/*{{{*/
int r;
int target_len, tmp_len;
char* target;
if (!in || in_len > INT_MAX) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER);
return NULL;
}
assert(in_len ? in[in_len] == '\0' : 1);
tmp_len = !in_len ? -1 : (int)in_len + 1;
target_len = WideCharToMultiByte(cp, flags, in, tmp_len, NULL, 0, NULL, NULL);
if (target_len == 0) {
SET_ERRNO_FROM_WIN32_CODE(GetLastError());
return NULL;
}
target = malloc(target_len);
if (target == NULL) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_OUTOFMEMORY);
return NULL;
}
r = WideCharToMultiByte(cp, flags, in, tmp_len, target, target_len, NULL, NULL);
if (r == 0) {
free(target);
SET_ERRNO_FROM_WIN32_CODE(GetLastError());
return NULL;
}
assert(target ? r == target_len : 1);
assert(target && !in_len ? strlen(target) == target_len - 1 : 1);
target[target_len-1] = '\0';
if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) {
*out_len = target_len - 1;
}
return target;
}/*}}}*/
PW32CP char *php_win32_cp_conv_w_to_utf8(const wchar_t* in, size_t in_len, size_t *out_len)
{/*{{{*/
return php_win32_cp_from_w_int(in, in_len, out_len, CP_UTF8, WC_ERR_INVALID_CHARS);
}/*}}}*/
PW32CP char *php_win32_cp_conv_w_to_cur(const wchar_t* in, size_t in_len, size_t *out_len)
{/*{{{*/
char *ret;
ret = php_win32_cp_from_w_int(in, in_len, out_len, cur_cp->id, cur_cp->from_w_fl);
return ret;
}/*}}}*/
PW32CP char *php_win32_cp_conv_from_w(DWORD cp, DWORD flags, const wchar_t* in, size_t in_len, size_t *out_len)
{/*{{{*/
return php_win32_cp_from_w_int(in, in_len, out_len, cp, flags);
}/*}}}*/
/* This is only usable after the startup phase*/
__forceinline static char *php_win32_cp_get_enc(void)
{/*{{{*/
char *enc = NULL;
const zend_encoding *zenc;
if (PG(internal_encoding) && PG(internal_encoding)[0]) {
enc = PG(internal_encoding);
} else if (SG(default_charset) && SG(default_charset)[0] ) {
enc = SG(default_charset);
} else {
zenc = zend_multibyte_get_internal_encoding();
if (zenc) {
enc = (char *)zend_multibyte_get_encoding_name(zenc);
}
}
return enc;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_get_current(void)
{/*{{{*/
return cur_cp;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_get_orig(void)
{/*{{{*/
return orig_cp;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_get_by_id(DWORD id)
{/*{{{*/
size_t i;
if (id < php_win32_cp_map[0].id) {
switch (id) {
case CP_ACP:
id = GetACP();
break;
case CP_OEMCP:
id = GetOEMCP();
break;
}
}
for (i = 0; i < sizeof(php_win32_cp_map)/sizeof(struct php_win32_cp); i++) {
if (php_win32_cp_map[i].id == id) {
return &php_win32_cp_map[i];
}
}
SET_ERRNO_FROM_WIN32_CODE(ERROR_NOT_FOUND);
return NULL;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_get_by_enc(const char *enc)
{/*{{{*/
size_t enc_len = 0, i;
if (!enc || !enc[0]) {
return php_win32_cp_get_by_id(65001U);
}
enc_len = strlen(enc);
for (i = 0; i < sizeof(php_win32_cp_map)/sizeof(struct php_win32_cp); i++) {
const struct php_win32_cp *cp = &php_win32_cp_map[i];
if (!cp->name || !cp->name[0]) {
continue;
}
if (0 == zend_binary_strcasecmp(enc, enc_len, cp->name, strlen(cp->name))) {
return cp;
}
if (cp->enc) {
char *start = cp->enc, *idx;
idx = strpbrk(start, "|");
while (NULL != idx) {
if (0 == zend_binary_strcasecmp(enc, enc_len, start, idx - start)) {
return cp;
}
start = idx + 1;
idx = strpbrk(start, "|");
}
/* Last in the list, or single charset specified. */
if (0 == zend_binary_strcasecmp(enc, enc_len, start, strlen(start))) {
return cp;
}
}
}
return php_win32_cp_get_by_id(GetACP());
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_set_by_id(DWORD id)
{/*{{{*/
const struct php_win32_cp *tmp;
if (!IsValidCodePage(id)) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER);
return NULL;
}
tmp = php_win32_cp_get_by_id(id);
if (tmp) {
cur_cp = tmp;
}
return cur_cp;
}/*}}}*/
PW32CP BOOL php_win32_cp_use_unicode(void)
{/*{{{*/
return 65001 == cur_cp->id;
}/*}}}*/
PW32CP wchar_t *php_win32_cp_env_any_to_w(const char* env)
{/*{{{*/
wchar_t *envw = NULL, ew[32760];
char *cur = (char *)env, *prev;
size_t bin_len = 0;
if (!env) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER);
return NULL;
}
do {
wchar_t *tmp;
tmp = php_win32_cp_any_to_w(cur);
if (tmp) {
size_t tmp_len = wcslen(tmp) + 1;
memmove(ew + bin_len, tmp, tmp_len * sizeof(wchar_t));
free(tmp);
bin_len += tmp_len;
}
prev = cur;
} while (NULL != (cur = strchr(prev, '\0')) && cur++ && *cur && bin_len + (cur - prev) < 32760);
envw = (wchar_t *) malloc((bin_len + 3) * sizeof(wchar_t));
if (!envw) {
SET_ERRNO_FROM_WIN32_CODE(ERROR_OUTOFMEMORY);
return NULL;
}
memmove(envw, ew, bin_len * sizeof(wchar_t));
envw[bin_len] = L'\0';
envw[bin_len + 1] = L'\0';
envw[bin_len + 2] = L'\0';
return envw;
}/*}}}*/
static BOOL php_win32_cp_cli_io_setup(void)
{/*{{{*/
BOOL ret = TRUE;
if (PG(input_encoding) && PG(input_encoding)[0]) {
cur_in_cp = php_win32_cp_get_by_enc(PG(input_encoding));
if (!cur_in_cp) {
cur_in_cp = cur_cp;
}
} else {
cur_in_cp = cur_cp;
}
if (PG(output_encoding) && PG(output_encoding)[0]) {
cur_out_cp = php_win32_cp_get_by_enc(PG(output_encoding));
if (!cur_out_cp) {
cur_out_cp = cur_cp;
}
} else {
cur_out_cp = cur_cp;
}
if(php_get_module_initialized()) {
ret = SetConsoleCP(cur_in_cp->id) && SetConsoleOutputCP(cur_out_cp->id);
}
return ret;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_do_setup(const char *enc)
{/*{{{*/
if (!enc) {
enc = php_win32_cp_get_enc();
}
cur_cp = php_win32_cp_get_by_enc(enc);
if (!orig_cp) {
orig_cp = php_win32_cp_get_by_id(GetACP());
}
if (php_win32_console_is_cli_sapi()) {
if (!orig_in_cp) {
orig_in_cp = php_win32_cp_get_by_id(GetConsoleCP());
if (!orig_in_cp) {
orig_in_cp = orig_cp;
}
}
if (!orig_out_cp) {
orig_out_cp = php_win32_cp_get_by_id(GetConsoleOutputCP());
if (!orig_out_cp) {
orig_out_cp = orig_cp;
}
}
php_win32_cp_cli_io_setup();
}
return cur_cp;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_do_update(const char *enc)
{/*{{{*/
if (!enc) {
enc = php_win32_cp_get_enc();
}
cur_cp = php_win32_cp_get_by_enc(enc);
if (php_win32_console_is_cli_sapi()) {
php_win32_cp_cli_do_setup(cur_cp->id);
}
return cur_cp;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_shutdown(void)
{/*{{{*/
return orig_cp;
}/*}}}*/
/* php_win32_cp_setup() needs to have run before! */
PW32CP const struct php_win32_cp *php_win32_cp_cli_do_setup(DWORD id)
{/*{{{*/
const struct php_win32_cp *cp;
if (!orig_cp) {
php_win32_cp_setup();
}
if (id) {
cp = php_win32_cp_set_by_id(id);
} else {
cp = cur_cp;
}
if (!cp) {
return NULL;
}
if (php_win32_cp_cli_io_setup()) {
return cp;
}
return cp;
}/*}}}*/
PW32CP const struct php_win32_cp *php_win32_cp_cli_do_restore(DWORD id)
{/*{{{*/
BOOL cli_io_restored = TRUE;
if (orig_in_cp) {
cli_io_restored = cli_io_restored && SetConsoleCP(orig_in_cp->id);
}
if (orig_out_cp) {
cli_io_restored = cli_io_restored && SetConsoleOutputCP(orig_out_cp->id);
}
if (cli_io_restored && id) {
return php_win32_cp_set_by_id(id);
}
return NULL;
}/*}}}*/
/* Userspace functions, see basic_functions.* for arginfo and decls. */
/* {{{ Set process codepage. */
PHP_FUNCTION(sapi_windows_cp_set)
{
zend_long id;
const struct php_win32_cp *cp;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &id) == FAILURE) {
RETURN_THROWS();
}
if (ZEND_LONG_UINT_OVFL(id)) {
zend_argument_value_error(1, "must be between 0 and %u", UINT_MAX);
RETURN_THROWS();
}
if (php_win32_console_is_cli_sapi()) {
cp = php_win32_cp_cli_do_setup((DWORD)id);
} else {
cp = php_win32_cp_set_by_id((DWORD)id);
}
if (!cp) {
php_error_docref(NULL, E_WARNING, "Failed to switch to codepage %d", id);
RETURN_FALSE;
}
RETURN_BOOL(cp->id == id);
}
/* }}} */
/* {{{ Get process codepage. */
PHP_FUNCTION(sapi_windows_cp_get)
{
zend_string *kind = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &kind) == FAILURE) {
RETURN_THROWS();
}
if (!kind) {
const struct php_win32_cp *cp = php_win32_cp_get_current();
RETURN_LONG(cp->id);
} else if (zend_string_equals_literal_ci(kind, "ansi")) {
RETURN_LONG(GetACP());
} else if (zend_string_equals_literal_ci(kind, "oem")) {
RETURN_LONG(GetOEMCP());
} else {
/* TODO Warn/ValueError for invalid kind? */
const struct php_win32_cp *cp = php_win32_cp_get_current();
RETURN_LONG(cp->id);
}
}
/* }}} */
/* {{{ Indicates whether the codepage is UTF-8 compatible. */
PHP_FUNCTION(sapi_windows_cp_is_utf8)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
RETURN_BOOL(php_win32_cp_use_unicode());
}
/* }}} */
/* {{{ Convert string from one codepage to another. */
PHP_FUNCTION(sapi_windows_cp_conv)
{
char *ret;
size_t ret_len, tmpw_len;
wchar_t *tmpw;
const struct php_win32_cp *in_cp, *out_cp;
zend_string *string_in_codepage = NULL;
zend_long int_in_codepage = 0;
zend_string *string_out_codepage = NULL;
zend_long int_out_codepage = 0;
zend_string *subject;
ZEND_PARSE_PARAMETERS_START(3, 3)
Z_PARAM_STR_OR_LONG(string_in_codepage, int_in_codepage)
Z_PARAM_STR_OR_LONG(string_out_codepage, int_out_codepage)
Z_PARAM_STR(subject)
ZEND_PARSE_PARAMETERS_END();
if (ZEND_SIZE_T_INT_OVFL(ZSTR_LEN(subject))) {
zend_argument_value_error(1, "is too long");
RETURN_THROWS();
}
if (string_in_codepage != NULL) {
in_cp = php_win32_cp_get_by_enc(ZSTR_VAL(string_in_codepage));
if (!in_cp) {
zend_argument_value_error(1, "must be a valid charset");
RETURN_THROWS();
}
} else {
if (ZEND_LONG_UINT_OVFL(int_in_codepage)) {
zend_argument_value_error(1, "must be between 0 and %u", UINT_MAX);
RETURN_THROWS();
}
in_cp = php_win32_cp_get_by_id((DWORD)int_in_codepage);
if (!in_cp) {
zend_argument_value_error(1, "must be a valid codepage");
RETURN_THROWS();
}
}
if (string_out_codepage != NULL) {
out_cp = php_win32_cp_get_by_enc(ZSTR_VAL(string_out_codepage));
if (!out_cp) {
zend_argument_value_error(2, "must be a valid charset");
RETURN_THROWS();
}
} else {
if (ZEND_LONG_UINT_OVFL(int_out_codepage)) {
zend_argument_value_error(2, "must be between 0 and %u", UINT_MAX);
RETURN_THROWS();
}
out_cp = php_win32_cp_get_by_id((DWORD)int_out_codepage);
if (!out_cp) {
zend_argument_value_error(2, "must be a valid codepage");
RETURN_THROWS();
}
}
tmpw = php_win32_cp_conv_to_w(in_cp->id, in_cp->to_w_fl, ZSTR_VAL(subject), ZSTR_LEN(subject), &tmpw_len);
if (!tmpw) {
php_error_docref(NULL, E_WARNING, "Wide char conversion failed");
RETURN_NULL();
}
ret = php_win32_cp_conv_from_w(out_cp->id, out_cp->from_w_fl, tmpw, tmpw_len, &ret_len);
if (!ret) {
free(tmpw);
php_error_docref(NULL, E_WARNING, "Wide char conversion failed");
RETURN_NULL();
}
RETVAL_STRINGL(ret, ret_len);
free(tmpw);
free(ret);
}
/* }}} */
/* }}} */
| 17,452 | 22.585135 | 123 |
c
|
php-src
|
php-src-master/win32/codepage.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: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_WIN32_CODEPAGE_H
#define PHP_WIN32_CODEPAGE_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef PHP_EXPORTS
# define PW32CP __declspec(dllexport)
#else
# define PW32CP __declspec(dllimport)
#endif
#define PHP_WIN32_CP_IGNORE_LEN (0)
#define PHP_WIN32_CP_IGNORE_LEN_P ((size_t *)-1)
struct php_win32_cp {
DWORD id;
DWORD to_w_fl;
DWORD from_w_fl;
DWORD char_size;
char *name;
char *enc;
char *desc;
};
PW32CP BOOL php_win32_cp_use_unicode(void);
PW32CP const struct php_win32_cp *php_win32_cp_do_setup(const char *);
#define php_win32_cp_setup() php_win32_cp_do_setup(NULL)
PW32CP const struct php_win32_cp *php_win32_cp_do_update(const char *);
#define php_win32_cp_update() php_win32_cp_do_update(NULL)
PW32CP const struct php_win32_cp *php_win32_cp_shutdown(void);
PW32CP const struct php_win32_cp *php_win32_cp_get_current(void);
PW32CP const struct php_win32_cp *php_win32_cp_get_orig(void);
PW32CP const struct php_win32_cp *php_win32_cp_get_by_id(DWORD id);
PW32CP const struct php_win32_cp *php_win32_cp_set_by_id(DWORD id);
PW32CP const struct php_win32_cp *php_win32_cp_get_by_enc(const char *enc);
PW32CP const struct php_win32_cp *php_win32_cp_cli_do_setup(DWORD);
#define php_win32_cp_cli_setup() php_win32_cp_cli_do_setup(0)
#define php_win32_cp_cli_update() php_win32_cp_cli_do_setup(0)
PW32CP const struct php_win32_cp *php_win32_cp_cli_do_restore(DWORD);
#define php_win32_cp_cli_restore() php_win32_cp_cli_do_restore(0)
/* This API is binary safe and expects a \0 terminated input.
The returned out is \0 terminated, but the length doesn't count \0. */
PW32CP wchar_t *php_win32_cp_conv_to_w(DWORD in_cp, DWORD flags, const char* in, size_t in_len, size_t *out_len);
PW32CP wchar_t *php_win32_cp_conv_utf8_to_w(const char* in, size_t in_len, size_t *out_len);
#define php_win32_cp_utf8_to_w(in) php_win32_cp_conv_utf8_to_w(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
PW32CP wchar_t *php_win32_cp_conv_cur_to_w(const char* in, size_t in_len, size_t *out_len);
#define php_win32_cp_cur_to_w(in) php_win32_cp_conv_cur_to_w(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
PW32CP wchar_t *php_win32_cp_conv_ascii_to_w(const char* in, size_t in_len, size_t *out_len);
#define php_win32_cp_ascii_to_w(in) php_win32_cp_conv_ascii_to_w(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
PW32CP char *php_win32_cp_conv_from_w(DWORD out_cp, DWORD flags, const wchar_t* in, size_t in_len, size_t *out_len);
PW32CP char *php_win32_cp_conv_w_to_utf8(const wchar_t* in, size_t in_len, size_t *out_len);
#define php_win32_cp_w_to_utf8(in) php_win32_cp_conv_w_to_utf8(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
PW32CP char *php_win32_cp_conv_w_to_cur(const wchar_t* in, size_t in_len, size_t *out_len);
#define php_win32_cp_w_to_cur(in) php_win32_cp_conv_w_to_cur(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
PW32CP wchar_t *php_win32_cp_env_any_to_w(const char* env);
/* This function tries to make the best guess to convert any
given string to a wide char, also preferring the fastest code
path to unicode. It returns NULL on fail. */
__forceinline static wchar_t *php_win32_cp_conv_any_to_w(const char* in, size_t in_len, size_t *out_len)
{/*{{{*/
wchar_t *ret = NULL;
if (php_win32_cp_use_unicode()) {
/* First try the pure ascii conversion. This is the fastest way to do the
thing. Only applicable if the source string is UTF-8 in general.
While it could possibly be ok with European encodings, usage with
Asian encodings can cause unintended side effects. Lookup the term
"mojibake" if need more. */
ret = php_win32_cp_conv_ascii_to_w(in, in_len, out_len);
/* If that failed, try to convert to multibyte. */
if (!ret) {
ret = php_win32_cp_conv_utf8_to_w(in, in_len, out_len);
/* Still need this fallback with regard to possible broken data
in the existing scripts. Broken data might be hardcoded in
the user scripts, as UTF-8 settings was de facto ignored in
older PHP versions. The fallback can be removed later for
the sake of purity, keep now for BC reasons. */
if (!ret) {
const struct php_win32_cp *acp = php_win32_cp_get_by_id(GetACP());
if (acp) {
ret = php_win32_cp_conv_to_w(acp->id, acp->to_w_fl, in, in_len, out_len);
}
}
}
} else {
/* No unicode, convert from the current thread cp. */
ret = php_win32_cp_conv_cur_to_w(in, in_len, out_len);
}
return ret;
}/*}}}*/
#define php_win32_cp_any_to_w(in) php_win32_cp_conv_any_to_w(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
/* This function converts from unicode function output back to PHP. If
the PHP's current charset is not compatible with unicode, so the currently
configured CP will be used. */
__forceinline static char *php_win32_cp_conv_w_to_any(const wchar_t* in, size_t in_len, size_t *out_len)
{/*{{{*/
return php_win32_cp_conv_w_to_cur(in, in_len, out_len);
}/*}}}*/
#define php_win32_cp_w_to_any(in) php_win32_cp_conv_w_to_any(in, PHP_WIN32_CP_IGNORE_LEN, PHP_WIN32_CP_IGNORE_LEN_P)
#define PHP_WIN32_CP_W_TO_ANY_ARRAY(aw, aw_len, aa, aa_len) do { \
int i; \
aa_len = aw_len; \
aa = (char **) malloc(aw_len * sizeof(char *)); \
if (!aa) { \
break; \
} \
for (i = 0; i < aw_len; i++) { \
aa[i] = php_win32_cp_w_to_any(aw[i]); \
} \
} while (0);
#define PHP_WIN32_CP_FREE_ARRAY(a, a_len) do { \
int i; \
for (i = 0; i < a_len; i++) { \
free(a[i]); \
} \
free(a); \
} while (0);
#ifdef __cplusplus
}
#endif
#endif /* PHP_WIN32_CODEPAGE_H */
| 6,509 | 41.828947 | 120 |
h
|
php-src
|
php-src-master/win32/console.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: Michele Locati <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "SAPI.h"
#include "win32/console.h"
PHP_WINUTIL_API BOOL php_win32_console_fileno_is_console(zend_long fileno)
{/*{{{*/
BOOL result = FALSE;
HANDLE handle = (HANDLE) _get_osfhandle(fileno);
if (handle != INVALID_HANDLE_VALUE) {
DWORD mode;
if (GetConsoleMode(handle, &mode)) {
result = TRUE;
}
}
return result;
}/*}}}*/
PHP_WINUTIL_API BOOL php_win32_console_fileno_has_vt100(zend_long fileno)
{/*{{{*/
BOOL result = FALSE;
HANDLE handle = (HANDLE) _get_osfhandle(fileno);
if (handle != INVALID_HANDLE_VALUE) {
DWORD events;
if (fileno != 0 && !GetNumberOfConsoleInputEvents(handle, &events)) {
// Not STDIN
DWORD mode;
if (GetConsoleMode(handle, &mode)) {
if (mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
result = TRUE;
}
}
}
}
return result;
}/*}}}*/
PHP_WINUTIL_API BOOL php_win32_console_fileno_set_vt100(zend_long fileno, BOOL enable)
{/*{{{*/
BOOL result = FALSE;
HANDLE handle = (HANDLE) _get_osfhandle(fileno);
if (handle != INVALID_HANDLE_VALUE) {
DWORD events;
if (fileno != 0 && !GetNumberOfConsoleInputEvents(handle, &events)) {
// Not STDIN
DWORD mode;
if (GetConsoleMode(handle, &mode)) {
DWORD newMode;
if (enable) {
newMode = mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
}
else {
newMode = mode & ~ENABLE_VIRTUAL_TERMINAL_PROCESSING;
}
if (newMode == mode) {
result = TRUE;
}
else {
if (SetConsoleMode(handle, newMode)) {
result = TRUE;
}
}
}
}
}
return result;
}/*}}}*/
PHP_WINUTIL_API BOOL php_win32_console_is_own(void)
{/*{{{*/
if (!IsDebuggerPresent()) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD pl[1];
BOOL ret0 = FALSE, ret1 = FALSE;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
ret0 = !csbi.dwCursorPosition.X && !csbi.dwCursorPosition.Y;
}
ret1 = GetConsoleProcessList(pl, 1) == 1;
return ret0 && ret1;
}
return FALSE;
}/*}}}*/
PHP_WINUTIL_API BOOL php_win32_console_is_cli_sapi(void)
{/*{{{*/
return strlen(sapi_module.name) >= sizeof("cli") - 1 && !strncmp(sapi_module.name, "cli", sizeof("cli") - 1);
}/*}}}*/
| 3,165 | 26.059829 | 110 |
c
|
php-src
|
php-src-master/win32/console.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: Michele Locati <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_WIN32_CONSOLE_H
#define PHP_WIN32_CONSOLE_H
#ifndef PHP_WINUTIL_API
#ifdef PHP_EXPORTS
# define PHP_WINUTIL_API __declspec(dllexport)
#else
# define PHP_WINUTIL_API __declspec(dllimport)
#endif
#endif
#include "php.h"
#include "php_streams.h"
#include <windows.h>
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
/*
Check if a file descriptor associated to a stream is a console
(valid fileno, neither redirected nor piped)
*/
PHP_WINUTIL_API BOOL php_win32_console_fileno_is_console(zend_long fileno);
/*
Check if the console attached to a file descriptor (screen buffer, not STDIN)
has the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag set
*/
PHP_WINUTIL_API BOOL php_win32_console_fileno_has_vt100(zend_long fileno);
/*
Set/unset the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag for the screen buffer (STDOUT/STDERR)
associated to a file descriptor
*/
PHP_WINUTIL_API BOOL php_win32_console_fileno_set_vt100(zend_long fileno, BOOL enable);
/* Check, whether the program has its own console. If a process was launched
through a GUI, it will have it's own console. For more info see
http://support.microsoft.com/kb/99115 */
PHP_WINUTIL_API BOOL php_win32_console_is_own(void);
/* Check whether the current SAPI is run on console. */
PHP_WINUTIL_API BOOL php_win32_console_is_cli_sapi(void);
#endif
| 2,345 | 35.65625 | 91 |
h
|
php-src
|
php-src-master/win32/dllmain.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: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <config.w32.h>
#include <win32/time.h>
#include <win32/ioutil.h>
#include <php.h>
#ifdef HAVE_LIBXML
#include <libxml/threads.h>
#endif
/* TODO this file, or part of it, could be machine generated, to
allow extensions and SAPIs adding their own init stuff.
However expected is that MINIT is enough in most cases.
This file is only useful for some really internal stuff,
eq. initializing something before the DLL even is
available to be called. */
BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID dummy)
{
BOOL ret = TRUE;
switch (reason)
{
case DLL_PROCESS_ATTACH:
/*
* We do not need to check the return value of php_win32_init_gettimeofday()
* because the symbol bare minimum symbol we need is always available on our
* lowest supported platform.
*
* On Windows 8 or greater, we use a more precise symbol to obtain the system
* time, which is dynamically. The fallback allows us to proper support
* Vista/7/Server 2003 R2/Server 2008/Server 2008 R2.
*
* Instead simply initialize the global in win32/time.c for gettimeofday()
* use later on
*/
php_win32_init_gettimeofday();
ret = ret && php_win32_ioutil_init();
if (!ret) {
fprintf(stderr, "ioutil initialization failed");
return ret;
}
break;
#if 0 /* prepared */
case DLL_PROCESS_DETACH:
/* pass */
break;
case DLL_THREAD_ATTACH:
/* pass */
break;
case DLL_THREAD_DETACH:
/* pass */
break;
#endif
}
#ifdef HAVE_LIBXML
/* This imply that only LIBXML_STATIC_FOR_DLL is supported ATM.
If that changes, this place will need some rework.
TODO Also this should be revisited as no initialization
might be needed for TS build (libxml build with TLS
support. */
ret = ret && xmlDllMain(inst, reason, dummy);
#endif
return ret;
}
| 2,816 | 31.37931 | 80 |
c
|
php-src
|
php-src-master/win32/fnmatch.c
|
/*
* Copyright (c) 1989, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Guido van Rossum.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* From FreeBSD fnmatch.c 1.11
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)fnmatch.c 8.2 (Berkeley) 4/16/94";
#endif /* LIBC_SCCS and not lint */
/*
* Function fnmatch() as specified in POSIX 1003.2-1992, section B.6.
* Compares a filename or pathname to a pattern.
*/
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "fnmatch.h"
#define EOS '\0'
static const char *rangematch(const char *, char, int);
PHPAPI int fnmatch(const char *pattern, const char *string, int flags)
{
const char *stringstart;
char c, test;
for (stringstart = string;;)
switch (c = *pattern++) {
case EOS:
if ((flags & FNM_LEADING_DIR) && *string == '/')
return (0);
return (*string == EOS ? 0 : FNM_NOMATCH);
case '?':
if (*string == EOS)
return (FNM_NOMATCH);
if (*string == '/' && (flags & FNM_PATHNAME))
return (FNM_NOMATCH);
if (*string == '.' && (flags & FNM_PERIOD) &&
(string == stringstart ||
((flags & FNM_PATHNAME) && *(string - 1) == '/')))
return (FNM_NOMATCH);
++string;
break;
case '*':
c = *pattern;
/* Collapse multiple stars. */
while (c == '*')
c = *++pattern;
if (*string == '.' && (flags & FNM_PERIOD) &&
(string == stringstart ||
((flags & FNM_PATHNAME) && *(string - 1) == '/')))
return (FNM_NOMATCH);
/* Optimize for pattern with * at end or before /. */
if (c == EOS)
if (flags & FNM_PATHNAME)
return ((flags & FNM_LEADING_DIR) ||
strchr(string, '/') == NULL ?
0 : FNM_NOMATCH);
else
return (0);
else if (c == '/' && flags & FNM_PATHNAME) {
if ((string = strchr(string, '/')) == NULL)
return (FNM_NOMATCH);
break;
}
/* General case, use recursion. */
while ((test = *string) != EOS) {
if (!fnmatch(pattern, string, flags & ~FNM_PERIOD))
return (0);
if (test == '/' && flags & FNM_PATHNAME)
break;
++string;
}
return (FNM_NOMATCH);
case '[':
if (*string == EOS)
return (FNM_NOMATCH);
if (*string == '/' && flags & FNM_PATHNAME)
return (FNM_NOMATCH);
if ((pattern =
rangematch(pattern, *string, flags)) == NULL)
return (FNM_NOMATCH);
++string;
break;
case '\\':
if (!(flags & FNM_NOESCAPE)) {
if ((c = *pattern++) == EOS) {
c = '\\';
--pattern;
}
}
/* FALLTHROUGH */
default:
if (c == *string)
;
else if ((flags & FNM_CASEFOLD) &&
(tolower((unsigned char)c) ==
tolower((unsigned char)*string)))
;
else if ((flags & FNM_PREFIX_DIRS) && *string == EOS &&
(c == '/' && string != stringstart ||
string == stringstart+1 && *stringstart == '/') )
return (0);
else
return (FNM_NOMATCH);
string++;
break;
}
/* NOTREACHED */
}
static const char *
rangematch(const char *pattern, char test, int flags)
{
int negate, ok;
char c, c2;
/*
* A bracket expression starting with an unquoted circumflex
* character produces unspecified results (IEEE 1003.2-1992,
* 3.13.2). This implementation treats it like '!', for
* consistency with the regular expression syntax.
* J.T. Conklin ([email protected])
*/
if ( (negate = (*pattern == '!' || *pattern == '^')) )
++pattern;
if (flags & FNM_CASEFOLD)
test = tolower((unsigned char)test);
for (ok = 0; (c = *pattern++) != ']';) {
if (c == '\\' && !(flags & FNM_NOESCAPE))
c = *pattern++;
if (c == EOS)
return (NULL);
if (flags & FNM_CASEFOLD)
c = tolower((unsigned char)c);
if (*pattern == '-'
&& (c2 = *(pattern+1)) != EOS && c2 != ']') {
pattern += 2;
if (c2 == '\\' && !(flags & FNM_NOESCAPE))
c2 = *pattern++;
if (c2 == EOS)
return (NULL);
if (flags & FNM_CASEFOLD)
c2 = tolower((unsigned char)c2);
if ((unsigned char)c <= (unsigned char)test &&
(unsigned char)test <= (unsigned char)c2)
ok = 1;
} else if (c == test)
ok = 1;
}
return (ok == negate ? NULL : pattern);
}
| 5,913 | 28.868687 | 77 |
c
|
php-src
|
php-src-master/win32/fnmatch.h
|
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)fnmatch.h 8.1 (Berkeley) 6/2/93
*
* From FreeBSD fnmatch.h 1.7
*/
#ifndef _FNMATCH_H_
#define _FNMATCH_H_
#include "php.h"
#define FNM_NOMATCH 1 /* Match failed. */
#define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */
#define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */
#define FNM_PERIOD 0x04 /* Period must be matched by period. */
#define FNM_LEADING_DIR 0x08 /* Ignore /<tail> after Imatch. */
#define FNM_CASEFOLD 0x10 /* Case insensitive search. */
#define FNM_PREFIX_DIRS 0x20 /* Directory prefixes of pattern match too. */
PHPAPI int fnmatch(const char *pattern, const char *string, int flags);
#endif /* !_FNMATCH_H_ */
| 2,494 | 45.203704 | 77 |
h
|
php-src
|
php-src-master/win32/getrusage.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: Kalle Sommer Nielsen <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <php.h>
#include <psapi.h>
#include "getrusage.h"
/*
* Parts of this file is based on code from the OpenVSwitch project, that
* is released under the Apache 2.0 license and is copyright 2014 Nicira, Inc.
* and have been modified to work with PHP.
*/
static zend_always_inline void usage_to_timeval(FILETIME *ft, struct timeval *tv)
{
ULARGE_INTEGER time;
time.LowPart = ft->dwLowDateTime;
time.HighPart = ft->dwHighDateTime;
tv->tv_sec = (zend_long) (time.QuadPart / 10000000);
tv->tv_usec = (zend_long) ((time.QuadPart % 10000000) / 10);
}
PHPAPI int getrusage(int who, struct rusage *usage)
{
FILETIME ctime, etime, stime, utime;
memset(usage, 0, sizeof(struct rusage));
if (who == RUSAGE_SELF) {
PROCESS_MEMORY_COUNTERS pmc;
HANDLE proc = GetCurrentProcess();
if (!GetProcessTimes(proc, &ctime, &etime, &stime, &utime)) {
return -1;
} else if(!GetProcessMemoryInfo(proc, &pmc, sizeof(pmc))) {
return -1;
}
usage_to_timeval(&stime, &usage->ru_stime);
usage_to_timeval(&utime, &usage->ru_utime);
usage->ru_majflt = pmc.PageFaultCount;
usage->ru_maxrss = pmc.PeakWorkingSetSize / 1024;
return 0;
} else if (who == RUSAGE_THREAD) {
if (!GetThreadTimes(GetCurrentThread(), &ctime, &etime, &stime, &utime)) {
return -1;
}
usage_to_timeval(&stime, &usage->ru_stime);
usage_to_timeval(&utime, &usage->ru_utime);
return 0;
} else {
return -1;
}
}
| 2,415 | 31.648649 | 81 |
c
|
php-src
|
php-src-master/win32/getrusage.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Kalle Sommer Nielsen <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef HAVE_GETRUSAGE_H
# define HAVE_GETRUSAGE_H
/*
* Note
*
* RUSAGE_CHILDREN is not implemented, and the RUSAGE_THREAD will
* therefore instead be used instead to emulate the behavior.
*/
# define RUSAGE_SELF 0
# define RUSAGE_CHILDREN 1
# define RUSAGE_THREAD RUSAGE_CHILDREN
/*
* Implementation support
*
* RUSAGE_SELF
* ru_utime
* ru_stime
* ru_majflt
* ru_maxrss
*
* RUSAGE_THREAD
* ru_utime
* ru_stime
*
* Not implemented:
* ru_ixrss (unused)
* ru_idrss (unused)
* ru_isrss (unused)
* ru_minflt
* ru_nswap (unused)
* ru_inblock
* ru_oublock
* ru_msgsnd (unused)
* ru_msgrcv (unused)
* ru_nsignals (unused)
* ru_nvcsw
* ru_nivcsw
*/
struct rusage
{
/* User time used */
struct timeval ru_utime;
/* System time used */
struct timeval ru_stime;
/* Integral max resident set size */
zend_long ru_maxrss;
/* Page faults */
zend_long ru_majflt;
#if 0
/* Integral shared text memory size */
zend_long ru_ixrss;
/* Integral unshared data size */
zend_long ru_idrss;
/* Integral unshared stack size */
zend_long ru_isrss;
/* Page reclaims */
zend_long ru_minflt;
/* Swaps */
zend_long ru_nswap;
/* Block input operations */
zend_long ru_inblock;
/* Block output operations */
zend_long ru_oublock;
/* Messages sent */
zend_long ru_msgsnd;
/* Messages received */
zend_long ru_msgrcv;
/* Signals received */
zend_long ru_nsignals;
/* Voluntary context switches */
zend_long ru_nvcsw;
/* Involuntary context switches */
zend_long ru_nivcsw;
#endif
};
PHPAPI int getrusage(int who, struct rusage *usage);
#endif
| 2,618 | 21.773913 | 75 |
h
|
php-src
|
php-src-master/win32/glob.c
|
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Guido van Rossum.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* glob(3) -- a superset of the one defined in POSIX 1003.2.
*
* The [!...] convention to negate a range is supported (SysV, Posix, ksh).
*
* Optional extra services, controlled by flags not defined by POSIX:
*
* GLOB_QUOTE:
* Escaping convention: \ inhibits any special meaning the following
* character might have (except \ at end of string is retained).
* GLOB_MAGCHAR:
* Set in gl_flags if pattern contained a globbing character.
* GLOB_NOMAGIC:
* Same as GLOB_NOCHECK, but it will only append pattern if it did
* not contain any magic characters. [Used in csh style globbing]
* GLOB_ALTDIRFUNC:
* Use alternately specified directory access functions.
* GLOB_TILDE:
* expand ~user/foo to the /home/dir/of/user/foo
* GLOB_BRACE:
* expand {1,2}{a,b} to 1a 1b 2a 2b
* gl_matchc:
* Number of matches in the current invocation of glob.
*/
#ifdef PHP_WIN32
#if _MSC_VER < 1800
# define _POSIX_
# include <limits.h>
# undef _POSIX_
#else
/* Visual Studio 2013 removed all the _POSIX_ defines, but we depend on some */
# ifndef ARG_MAX
# define ARG_MAX 14500
# endif
#endif
#endif
#include "php.h"
#include <sys/stat.h>
#include <ctype.h>
#ifndef PHP_WIN32
#include <sys/param.h>
#include <dirent.h>
#include <pwd.h>
#include <unistd.h>
#endif
#include <errno.h>
#include "glob.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DOLLAR '$'
#define DOT '.'
#define EOS '\0'
#define LBRACKET '['
#define NOT '!'
#define QUESTION '?'
#define QUOTE '\\'
#define RANGE '-'
#define RBRACKET ']'
#define SEP DEFAULT_SLASH
#define STAR '*'
#define TILDE '~'
#define UNDERSCORE '_'
#define LBRACE '{'
#define RBRACE '}'
#define SLASH '/'
#define COMMA ','
#ifndef DEBUG
#define M_QUOTE 0x8000
#define M_PROTECT 0x4000
#define M_MASK 0xffff
#define M_ASCII 0x00ff
typedef u_short Char;
#else
#define M_QUOTE 0x80
#define M_PROTECT 0x40
#define M_MASK 0xff
#define M_ASCII 0x7f
typedef char Char;
#endif
#define CHAR(c) ((Char)((c)&M_ASCII))
#define META(c) ((Char)((c)|M_QUOTE))
#define M_ALL META('*')
#define M_END META(']')
#define M_NOT META('!')
#define M_ONE META('?')
#define M_RNG META('-')
#define M_SET META('[')
#define ismeta(c) (((c)&M_QUOTE) != 0)
static int compare(const void *, const void *);
static int g_Ctoc(const Char *, char *, u_int);
static int g_lstat(Char *, zend_stat_t *, glob_t *);
static DIR *g_opendir(Char *, glob_t *);
static Char *g_strchr(Char *, int);
static int g_stat(Char *, zend_stat_t *, glob_t *);
static int glob0(const Char *, glob_t *);
static int glob1(Char *, Char *, glob_t *, size_t *);
static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
glob_t *, size_t *);
static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
Char *, Char *, glob_t *, size_t *);
static int globextend(const Char *, glob_t *, size_t *);
static const Char *globtilde(const Char *, Char *, size_t, glob_t *);
static int globexp1(const Char *, glob_t *);
static int globexp2(const Char *, const Char *, glob_t *, int *);
static int match(Char *, Char *, Char *);
#ifdef DEBUG
static void qprintf(const char *, Char *);
#endif
PHPAPI int glob(const char *pattern, int flags, int (*errfunc)(const char *, int), glob_t *pglob)
{
const uint8_t *patnext;
int c;
Char *bufnext, *bufend, patbuf[MAXPATHLEN];
#ifdef PHP_WIN32
/* Force skipping escape sequences on windows
* due to the ambiguity with path backslashes
*/
flags |= GLOB_NOESCAPE;
#endif
patnext = (uint8_t *) pattern;
if (!(flags & GLOB_APPEND)) {
pglob->gl_pathc = 0;
pglob->gl_pathv = NULL;
if (!(flags & GLOB_DOOFFS))
pglob->gl_offs = 0;
}
pglob->gl_flags = flags & ~GLOB_MAGCHAR;
pglob->gl_errfunc = errfunc;
pglob->gl_matchc = 0;
bufnext = patbuf;
bufend = bufnext + MAXPATHLEN - 1;
if (flags & GLOB_NOESCAPE)
while (bufnext < bufend && (c = *patnext++) != EOS)
*bufnext++ = c;
else {
/* Protect the quoted characters. */
while (bufnext < bufend && (c = *patnext++) != EOS)
if (c == QUOTE) {
if ((c = *patnext++) == EOS) {
c = QUOTE;
--patnext;
}
*bufnext++ = c | M_PROTECT;
} else
*bufnext++ = c;
}
*bufnext = EOS;
if (flags & GLOB_BRACE)
return globexp1(patbuf, pglob);
else
return glob0(patbuf, pglob);
}
/*
* Expand recursively a glob {} pattern. When there is no more expansion
* invoke the standard globbing routine to glob the rest of the magic
* characters
*/
static int globexp1(const Char *pattern,glob_t *pglob)
{
const Char* ptr = pattern;
int rv;
/* Protect a single {}, for find(1), like csh */
if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
return glob0(pattern, pglob);
while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
if (!globexp2(ptr, pattern, pglob, &rv))
return rv;
return glob0(pattern, pglob);
}
/*
* Recursive brace globbing helper. Tries to expand a single brace.
* If it succeeds then it invokes globexp1 with the new pattern.
* If it fails then it tries to glob the rest of the pattern and returns.
*/
static int globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv)
{
int i;
Char *lm, *ls;
const Char *pe, *pm, *pl;
Char patbuf[MAXPATHLEN];
/* copy part up to the brace */
for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
;
*lm = EOS;
ls = lm;
/* Find the balanced brace */
for (i = 0, pe = ++ptr; *pe; pe++)
if (*pe == LBRACKET) {
/* Ignore everything between [] */
for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
;
if (*pe == EOS) {
/*
* We could not find a matching RBRACKET.
* Ignore and just look for RBRACE
*/
pe = pm;
}
} else if (*pe == LBRACE)
i++;
else if (*pe == RBRACE) {
if (i == 0)
break;
i--;
}
/* Non matching braces; just glob the pattern */
if (i != 0 || *pe == EOS) {
*rv = glob0(patbuf, pglob);
return 0;
}
for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
const Char *pb;
switch (*pm) {
case LBRACKET:
/* Ignore everything between [] */
for (pb = pm++; *pm != RBRACKET && *pm != EOS; pm++)
;
if (*pm == EOS) {
/*
* We could not find a matching RBRACKET.
* Ignore and just look for RBRACE
*/
pm = pb;
}
break;
case LBRACE:
i++;
break;
case RBRACE:
if (i) {
i--;
break;
}
/* FALLTHROUGH */
case COMMA:
if (i && *pm == COMMA)
break;
else {
/* Append the current string */
for (lm = ls; (pl < pm); *lm++ = *pl++)
;
/*
* Append the rest of the pattern after the
* closing brace
*/
for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
;
/* Expand the current pattern */
#ifdef DEBUG
qprintf("globexp2:", patbuf);
#endif
*rv = globexp1(patbuf, pglob);
/* move after the comma, to the next string */
pl = pm + 1;
}
break;
default:
break;
}
}
*rv = 0;
return 0;
}
/*
* expand tilde from the passwd file.
*/
static const Char *globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
{
#ifndef PHP_WIN32
struct passwd *pwd;
#endif
char *h;
const Char *p;
Char *b, *eb;
if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
return pattern;
/* Copy up to the end of the string or / */
eb = &patbuf[patbuf_len - 1];
for (p = pattern + 1, h = (char *) patbuf;
h < (char *)eb && *p && *p != SLASH; *h++ = (char) *p++)
;
*h = EOS;
#if 0
if (h == (char *)eb)
return what;
#endif
if (((char *) patbuf)[0] == EOS) {
/*
* handle a plain ~ or ~/ by expanding $HOME
* first and then trying the password file
*/
if ((h = getenv("HOME")) == NULL) {
#ifndef PHP_WIN32
if ((pwd = getpwuid(getuid())) == NULL)
return pattern;
else
h = pwd->pw_dir;
#else
return pattern;
#endif
}
} else {
/*
* Expand a ~user
*/
#ifndef PHP_WIN32
if ((pwd = getpwnam((char*) patbuf)) == NULL)
return pattern;
else
h = pwd->pw_dir;
#else
return pattern;
#endif
}
/* Copy the home directory */
for (b = patbuf; b < eb && *h; *b++ = *h++)
;
/* Append the rest of the pattern */
while (b < eb && (*b++ = *p++) != EOS)
;
*b = EOS;
return patbuf;
}
/*
* The main glob() routine: compiles the pattern (optionally processing
* quotes), calls glob1() to do the real pattern matching, and finally
* sorts the list (unless unsorted operation is requested). Returns 0
* if things went well, nonzero if errors occurred. It is not an error
* to find no matches.
*/
static int glob0( const Char *pattern, glob_t *pglob)
{
const Char *qpatnext;
int c, err, oldpathc;
Char *bufnext, patbuf[MAXPATHLEN];
size_t limit = 0;
qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
oldpathc = pglob->gl_pathc;
bufnext = patbuf;
/* We don't need to check for buffer overflow any more. */
while ((c = *qpatnext++) != EOS) {
switch (c) {
case LBRACKET:
c = *qpatnext;
if (c == NOT)
++qpatnext;
if (*qpatnext == EOS ||
g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
*bufnext++ = LBRACKET;
if (c == NOT)
--qpatnext;
break;
}
*bufnext++ = M_SET;
if (c == NOT)
*bufnext++ = M_NOT;
c = *qpatnext++;
do {
*bufnext++ = CHAR(c);
if (*qpatnext == RANGE &&
(c = qpatnext[1]) != RBRACKET) {
*bufnext++ = M_RNG;
*bufnext++ = CHAR(c);
qpatnext += 2;
}
} while ((c = *qpatnext++) != RBRACKET);
pglob->gl_flags |= GLOB_MAGCHAR;
*bufnext++ = M_END;
break;
case QUESTION:
pglob->gl_flags |= GLOB_MAGCHAR;
*bufnext++ = M_ONE;
break;
case STAR:
pglob->gl_flags |= GLOB_MAGCHAR;
/* collapse adjacent stars to one,
* to avoid exponential behavior
*/
if (bufnext == patbuf || bufnext[-1] != M_ALL)
*bufnext++ = M_ALL;
break;
default:
*bufnext++ = CHAR(c);
break;
}
}
*bufnext = EOS;
#ifdef DEBUG
qprintf("glob0:", patbuf);
#endif
if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
return(err);
/*
* If there was no match we are going to append the pattern
* if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
* and the pattern did not contain any magic characters
* GLOB_NOMAGIC is there just for compatibility with csh.
*/
if (pglob->gl_pathc == oldpathc) {
if ((pglob->gl_flags & GLOB_NOCHECK) ||
((pglob->gl_flags & GLOB_NOMAGIC) &&
!(pglob->gl_flags & GLOB_MAGCHAR)))
return(globextend(pattern, pglob, &limit));
else
return(GLOB_NOMATCH);
}
if (!(pglob->gl_flags & GLOB_NOSORT))
qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
pglob->gl_pathc - oldpathc, sizeof(char *), compare);
return(0);
}
static int compare(const void *p, const void *q)
{
return(strcmp(*(char **)p, *(char **)q));
}
static int
glob1(pattern, pattern_last, pglob, limitp)
Char *pattern, *pattern_last;
glob_t *pglob;
size_t *limitp;
{
Char pathbuf[MAXPATHLEN];
/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
if (*pattern == EOS)
return(0);
return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
pathbuf, pathbuf+MAXPATHLEN-1,
pattern, pattern_last, pglob, limitp));
}
/*
* The functions glob2 and glob3 are mutually recursive; there is one level
* of recursion for each segment in the pattern that contains one or more
* meta characters.
*/
static int glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last, Char *pattern,
Char *pattern_last, glob_t *pglob, size_t *limitp)
{
zend_stat_t sb = {0};
Char *p, *q;
int anymeta;
/*
* Loop over pattern segments until end of pattern or until
* segment with meta character found.
*/
for (anymeta = 0;;) {
if (*pattern == EOS) { /* End of pattern? */
*pathend = EOS;
if (g_lstat(pathbuf, &sb, pglob))
return(0);
if (((pglob->gl_flags & GLOB_MARK) &&
!IS_SLASH(pathend[-1])) && (S_ISDIR(sb.st_mode) ||
(S_ISLNK(sb.st_mode) &&
(g_stat(pathbuf, &sb, pglob) == 0) &&
S_ISDIR(sb.st_mode)))) {
if (pathend+1 > pathend_last)
return (1);
*pathend++ = SEP;
*pathend = EOS;
}
++pglob->gl_matchc;
return(globextend(pathbuf, pglob, limitp));
}
/* Find end of next segment, copy tentatively to pathend. */
q = pathend;
p = pattern;
while (*p != EOS && !IS_SLASH(*p)) {
if (ismeta(*p))
anymeta = 1;
if (q+1 > pathend_last)
return (1);
*q++ = *p++;
}
if (!anymeta) { /* No expansion, do next segment. */
pathend = q;
pattern = p;
while (IS_SLASH(*pattern)) {
if (pathend+1 > pathend_last)
return (1);
*pathend++ = *pattern++;
}
} else
/* Need expansion, recurse. */
return(glob3(pathbuf, pathbuf_last, pathend,
pathend_last, pattern, pattern_last,
p, pattern_last, pglob, limitp));
}
/* NOTREACHED */
}
static int glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last, Char *pattern, Char *pattern_last,
Char *restpattern, Char *restpattern_last, glob_t *pglob, size_t *limitp)
{
register struct dirent *dp;
DIR *dirp;
int err;
/*
* The readdirfunc declaration can't be prototyped, because it is
* assigned, below, to two functions which are prototyped in glob.h
* and dirent.h as taking pointers to differently typed opaque
* structures.
*/
struct dirent *(*readdirfunc)();
if (pathend > pathend_last)
return (1);
*pathend = EOS;
errno = 0;
if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
/* TODO: don't call for ENOENT or ENOTDIR? */
if (pglob->gl_errfunc) {
char buf[MAXPATHLEN];
if (g_Ctoc(pathbuf, buf, sizeof(buf)))
return(GLOB_ABORTED);
if (pglob->gl_errfunc(buf, errno) ||
pglob->gl_flags & GLOB_ERR)
return(GLOB_ABORTED);
}
return(0);
}
err = 0;
/* Search directory for matching names. */
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
readdirfunc = pglob->gl_readdir;
else
readdirfunc = readdir;
while ((dp = (*readdirfunc)(dirp))) {
register uint8_t *sc;
register Char *dc;
/* Initial DOT must be matched literally. */
if (dp->d_name[0] == DOT && *pattern != DOT)
continue;
dc = pathend;
sc = (uint8_t *) dp->d_name;
while (dc < pathend_last && (*dc++ = *sc++) != EOS)
;
if (dc >= pathend_last) {
*dc = EOS;
err = 1;
break;
}
if (!match(pathend, pattern, restpattern)) {
*pathend = EOS;
continue;
}
err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
restpattern, restpattern_last, pglob, limitp);
if (err)
break;
}
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
(*pglob->gl_closedir)(dirp);
else
closedir(dirp);
return(err);
}
/*
* Extend the gl_pathv member of a glob_t structure to accommodate a new item,
* add the new item, and update gl_pathc.
*
* This assumes the BSD realloc, which only copies the block when its size
* crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
* behavior.
*
* Return 0 if new item added, error code if memory couldn't be allocated.
*
* Invariant of the glob_t structure:
* Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
* gl_pathv points to (gl_offs + gl_pathc + 1) items.
*/
static int globextend(const Char *path, glob_t *pglob, size_t *limitp)
{
register char **pathv;
u_int newsize, len;
char *copy;
const Char *p;
newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
malloc(newsize);
if (pathv == NULL) {
if (pglob->gl_pathv) {
free(pglob->gl_pathv);
pglob->gl_pathv = NULL;
}
return(GLOB_NOSPACE);
}
if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
register int i;
/* first time around -- clear initial gl_offs items */
pathv += pglob->gl_offs;
for (i = pglob->gl_offs; --i >= 0; )
*--pathv = NULL;
}
pglob->gl_pathv = pathv;
for (p = path; *p++;)
;
len = (u_int)(p - path);
*limitp += len;
if ((copy = malloc(len)) != NULL) {
if (g_Ctoc(path, copy, len)) {
free(copy);
return(GLOB_NOSPACE);
}
pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
}
pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
if ((pglob->gl_flags & GLOB_LIMIT) &&
newsize + *limitp >= ARG_MAX) {
errno = 0;
return(GLOB_NOSPACE);
}
return(copy == NULL ? GLOB_NOSPACE : 0);
}
/*
* pattern matching function for filenames. Each occurrence of the *
* pattern causes a recursion level.
*/
static int match(Char *name, Char *pat, Char *patend)
{
int ok, negate_range;
Char c, k;
while (pat < patend) {
c = *pat++;
switch (c & M_MASK) {
case M_ALL:
if (pat == patend)
return(1);
do
if (match(name, pat, patend))
return(1);
while (*name++ != EOS)
;
return(0);
case M_ONE:
if (*name++ == EOS)
return(0);
break;
case M_SET:
ok = 0;
if ((k = *name++) == EOS)
return(0);
if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
++pat;
while (((c = *pat++) & M_MASK) != M_END)
if ((*pat & M_MASK) == M_RNG) {
if (c <= k && k <= pat[1])
ok = 1;
pat += 2;
} else if (c == k)
ok = 1;
if (ok == negate_range)
return(0);
break;
default:
if (*name++ != c)
return(0);
break;
}
}
return(*name == EOS);
}
/* Free allocated data belonging to a glob_t structure. */
PHPAPI void globfree(glob_t *pglob)
{
register int i;
register char **pp;
if (pglob->gl_pathv != NULL) {
pp = pglob->gl_pathv + pglob->gl_offs;
for (i = pglob->gl_pathc; i--; ++pp)
if (*pp)
free(*pp);
free(pglob->gl_pathv);
pglob->gl_pathv = NULL;
}
}
static DIR * g_opendir(Char *str, glob_t *pglob)
{
char buf[MAXPATHLEN];
if (!*str)
strlcpy(buf, ".", sizeof(buf));
else {
if (g_Ctoc(str, buf, sizeof(buf)))
return(NULL);
}
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
return((*pglob->gl_opendir)(buf));
return(opendir(buf));
}
static int g_lstat(Char *fn, zend_stat_t *sb, glob_t *pglob)
{
char buf[MAXPATHLEN];
if (g_Ctoc(fn, buf, sizeof(buf)))
return(-1);
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
return((*pglob->gl_lstat)(buf, sb));
return(php_sys_lstat(buf, sb));
}
static int g_stat(Char *fn, zend_stat_t *sb, glob_t *pglob)
{
char buf[MAXPATHLEN];
if (g_Ctoc(fn, buf, sizeof(buf)))
return(-1);
if (pglob->gl_flags & GLOB_ALTDIRFUNC)
return((*pglob->gl_stat)(buf, sb));
return(php_sys_stat(buf, sb));
}
static Char *g_strchr(Char *str, int ch)
{
do {
if (*str == ch)
return (str);
} while (*str++);
return (NULL);
}
static int g_Ctoc(const Char *str, char *buf, u_int len)
{
while (len--) {
if ((*buf++ = (char) *str++) == EOS)
return (0);
}
return (1);
}
#ifdef DEBUG
static void
qprintf(char *str, Char *s)
{
register Char *p;
(void)printf("%s:\n", str);
for (p = s; *p; p++)
(void)printf("%c", CHAR(*p));
(void)printf("\n");
for (p = s; *p; p++)
(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
(void)printf("\n");
for (p = s; *p; p++)
(void)printf("%c", ismeta(*p) ? '_' : ' ');
(void)printf("\n");
}
#endif
| 20,837 | 23.006912 | 121 |
c
|
php-src
|
php-src-master/win32/glob.h
|
/* OpenBSD: glob.h,v 1.7 2002/02/17 19:42:21 millert Exp */
/* NetBSD: glob.h,v 1.5 1994/10/26 00:55:56 cgd Exp */
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Guido van Rossum.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)glob.h 8.1 (Berkeley) 6/2/93
*/
#ifndef _GLOB_H_
#define _GLOB_H_
#ifndef PHP_WIN32
# include <sys/cdefs.h>
#endif
#include "Zend/zend_stream.h"
typedef struct {
int gl_pathc; /* Count of total paths so far. */
int gl_matchc; /* Count of paths matching pattern. */
int gl_offs; /* Reserved at beginning of gl_pathv. */
int gl_flags; /* Copy of flags parameter to glob. */
char **gl_pathv; /* List of paths matching pattern. */
/* Copy of errfunc parameter to glob. */
int (*gl_errfunc)(const char *, int);
/*
* Alternate filesystem access methods for glob; replacement
* versions of closedir(3), readdir(3), opendir(3), stat(2)
* and lstat(2).
*/
void (*gl_closedir)(void *);
struct dirent *(*gl_readdir)(void *);
void *(*gl_opendir)(const char *);
int (*gl_lstat)(const char *, zend_stat_t *);
int (*gl_stat)(const char *, zend_stat_t *);
} glob_t;
/* Flags */
#define GLOB_APPEND 0x0001 /* Append to output from previous call. */
#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */
#define GLOB_ERR 0x0004 /* Return on error. */
#define GLOB_MARK 0x0008 /* Append / to matching directories. */
#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */
#define GLOB_NOSORT 0x0020 /* Don't sort. */
#ifndef _POSIX_SOURCE
#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */
#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */
#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */
#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */
#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */
#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */
#define GLOB_NOESCAPE 0x1000 /* Disable backslash escaping. */
#define GLOB_LIMIT 0x2000 /* Limit pattern match output to ARG_MAX */
#endif
/* Error values returned by glob(3) */
#define GLOB_NOSPACE (-1) /* Malloc call failed. */
#define GLOB_ABORTED (-2) /* Unignored error. */
#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK not set. */
#define GLOB_NOSYS (-4) /* Function not supported. */
#define GLOB_ABEND GLOB_ABORTED
BEGIN_EXTERN_C()
PHPAPI int glob(const char *, int, int (*)(const char *, int), glob_t *);
PHPAPI void globfree(glob_t *);
END_EXTERN_C()
#endif /* !_GLOB_H_ */
| 4,318 | 40.932039 | 79 |
h
|
php-src
|
php-src-master/win32/globals.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]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_win32_globals.h"
#include "syslog.h"
#ifdef ZTS
PHPAPI int php_win32_core_globals_id;
#else
php_win32_core_globals the_php_win32_core_globals;
#endif
void php_win32_core_globals_ctor(void *vg)
{/*{{{*/
php_win32_core_globals *wg = (php_win32_core_globals*)vg;
memset(wg, 0, sizeof(*wg));
wg->mail_socket = INVALID_SOCKET;
wg->log_source = INVALID_HANDLE_VALUE;
}/*}}}*/
void php_win32_core_globals_dtor(void *vg)
{/*{{{*/
php_win32_core_globals *wg = (php_win32_core_globals*)vg;
if (wg->registry_key) {
RegCloseKey(wg->registry_key);
wg->registry_key = NULL;
}
if (wg->registry_event) {
CloseHandle(wg->registry_event);
wg->registry_event = NULL;
}
if (wg->registry_directories) {
zend_hash_destroy(wg->registry_directories);
free(wg->registry_directories);
wg->registry_directories = NULL;
}
if (INVALID_SOCKET != wg->mail_socket) {
closesocket(wg->mail_socket);
wg->mail_socket = INVALID_SOCKET;
}
}/*}}}*/
PHP_RSHUTDOWN_FUNCTION(win32_core_globals)
{/*{{{*/
closelog();
return SUCCESS;
}/*}}}*/
| 2,068 | 29.426471 | 75 |
c
|
php-src
|
php-src-master/win32/inet.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: Pierre Joye <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "inet.h"
int inet_aton(const char *cp, struct in_addr *inp) {
inp->s_addr = inet_addr(cp);
if (inp->s_addr == INADDR_NONE) {
return 0;
}
return 1;
}
| 1,165 | 40.642857 | 75 |
c
|
php-src
|
php-src-master/win32/inet.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: Pierre Joye <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_WIN32_INET_H
#define PHP_WIN32_INET_H
#include <php.h>
#include <Winsock2.h>
PHPAPI int inet_aton(const char *cp, struct in_addr *inp);
#endif
| 1,154 | 43.423077 | 75 |
h
|
php-src
|
php-src-master/win32/ipc.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: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_WIN32_IPC_H
#define PHP_WIN32_IPC_H 1
#ifdef PHP_EXPORTS
# define PHP_WIN32_IPC_API __declspec(dllexport)
#else
# define PHP_WIN32_IPC_API __declspec(dllimport)
#endif
typedef int key_t;
PHP_WIN32_IPC_API key_t ftok(const char *path, int id);
#endif /* PHP_WIN32_IPC_H */
| 1,285 | 39.1875 | 75 |
h
|
php-src
|
php-src-master/win32/nice.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: Kalle Sommer Nielsen <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <php.h>
#include "nice.h"
/*
* Basic Windows implementation for the nice() function.
*
* This implementation uses SetPriorityClass() as a backend for defining
* a process priority.
*
* The following values of inc, defines the value sent to SetPriorityClass():
*
* +-----------------------+-----------------------------+
* | Expression | Priority type |
* +-----------------------+-----------------------------+
* | priority < -9 | HIGH_PRIORITY_CLASS |
* +-----------------------+-----------------------------+
* | priority < -4 | ABOVE_NORMAL_PRIORITY_CLASS |
* +-----------------------+-----------------------------+
* | priority > 4 | BELOW_NORMAL_PRIORITY_CLASS |
* +-----------------------+-----------------------------+
* | priority > 9 | IDLE_PRIORITY_CLASS |
* +-----------------------+-----------------------------+
*
* If a value is between -4 and 4 (inclusive), then the priority will be set
* to NORMAL_PRIORITY_CLASS.
*
* These values tries to mimic that of the UNIX version of nice().
*
* This is applied to the main process, not per thread, although this could
* be implemented using SetThreadPriority() at one point.
*
* Note, the following priority classes are left out with intention:
*
* . REALTIME_PRIORITY_CLASS
* Realtime priority class requires special system permissions to set, and
* can be dangerous in certain cases.
*
* . PROCESS_MODE_BACKGROUND_BEGIN
* . PROCESS_MODE_BACKGROUND_END
* Process mode is not covered because it can easily forgotten to be changed
* back and can cause unforeseen side effects that is hard to debug. Besides
* that, these do generally not really fit into making a Windows somewhat
* compatible nice() function.
*/
PHPAPI int nice(zend_long p)
{
DWORD dwFlag = NORMAL_PRIORITY_CLASS;
if (p < -9) {
dwFlag = HIGH_PRIORITY_CLASS;
} else if (p < -4) {
dwFlag = ABOVE_NORMAL_PRIORITY_CLASS;
} else if (p > 9) {
dwFlag = IDLE_PRIORITY_CLASS;
} else if (p > 4) {
dwFlag = BELOW_NORMAL_PRIORITY_CLASS;
}
if (!SetPriorityClass(GetCurrentProcess(), dwFlag)) {
return -1;
}
return 0;
}
| 3,221 | 38.292683 | 80 |
c
|
php-src
|
php-src-master/win32/nice.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Kalle Sommer Nielsen <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef HAVE_NICE_H
# define HAVE_NICE_H
PHPAPI int nice(zend_long);
#endif
| 1,074 | 45.73913 | 75 |
h
|
php-src
|
php-src-master/win32/param.h
|
/*****************************************************************************
* *
* sys/param.c *
* *
* Freely redistributable and modifiable. Use at your own risk. *
* *
* Copyright 1994 The Downhill Project *
* *
*****************************************************************************/
#ifndef PHP_WIN32_PARAM_H
#define PHP_WIN32_PARAM_H
#ifndef MAXPATHLEN
#include "win32/ioutil.h"
#define MAXPATHLEN PHP_WIN32_IOUTIL_MAXPATHLEN
#endif
#define MAXHOSTNAMELEN 64
#define howmany(x,y) (((x)+((y)-1))/(y))
#define roundup(x,y) ((((x)+((y)-1))/(y))*(y))
#endif
| 990 | 44.045455 | 79 |
h
|
php-src
|
php-src-master/win32/php_registry.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: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_REGISTRY_H
#define PHP_REGISTRY_H
void UpdateIniFromRegistry(char *path);
char *GetIniPathFromRegistry();
#endif /* PHP_REGISTRY_H */
| 1,145 | 44.84 | 75 |
h
|
php-src
|
php-src-master/win32/php_win32_globals.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_WIN32_GLOBALS_H
#define PHP_WIN32_GLOBALS_H
/* misc globals for thread-safety under win32 */
#include "win32/sendmail.h"
typedef struct _php_win32_core_globals php_win32_core_globals;
#ifdef ZTS
# define PW32G(v) ZEND_TSRMG(php_win32_core_globals_id, php_win32_core_globals*, v)
extern PHPAPI int php_win32_core_globals_id;
#else
# define PW32G(v) (the_php_win32_core_globals.v)
extern PHPAPI struct _php_win32_core_globals the_php_win32_core_globals;
#endif
struct _php_win32_core_globals {
/* syslog */
char *log_header;
HANDLE log_source;
HKEY registry_key;
HANDLE registry_event;
HashTable *registry_directories;
char mail_buffer[MAIL_BUFFER_SIZE];
SOCKET mail_socket;
char mail_host[HOST_NAME_LEN];
char mail_local_host[HOST_NAME_LEN];
};
void php_win32_core_globals_ctor(void *vg);
void php_win32_core_globals_dtor(void *vg);
PHP_RSHUTDOWN_FUNCTION(win32_core_globals);
#endif
| 1,927 | 34.703704 | 84 |
h
|
php-src
|
php-src-master/win32/readdir.h
|
#ifndef READDIR_H
#define READDIR_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Structures and types used to implement opendir/readdir/closedir
* on Windows.
*/
#include <config.w32.h>
#include "ioutil.h"
#define _DIRENT_HAVE_D_TYPE
#define DT_UNKNOWN 0
#define DT_DIR 4
#define DT_REG 8
/* struct dirent - same as Unix */
struct dirent {
long d_ino; /* inode (always 1 in WIN32) */
off_t d_off; /* offset to this dirent */
unsigned short d_reclen; /* length of d_name */
unsigned char d_type;
char d_name[1]; /* null terminated filename in the current encoding, glyph number <= 255 wchar_t's + \0 byte */
};
/* typedef DIR - not the same as Unix */
struct DIR_W32 {
HANDLE handle; /* _findfirst/_findnext handle */
uint32_t offset; /* offset into directory */
uint8_t finished; /* 1 if there are not more files */
WIN32_FIND_DATAW fileinfo; /* from _findfirst/_findnext */
wchar_t *dirw; /* the dir we are reading */
struct dirent dent; /* the dirent to return */
};
typedef struct DIR_W32 DIR;
/* Function prototypes */
DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int closedir(DIR *);
int rewinddir(DIR *);
#ifdef __cplusplus
}
#endif
#endif /* READDIR_H */
| 1,217 | 21.555556 | 112 |
h
|
php-src
|
php-src-master/win32/registry.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: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_ini.h"
#include "php_win32_globals.h"
#define PHP_REGISTRY_KEY "SOFTWARE\\PHP"
#define PHP_VER1(V1) #V1
#define PHP_VER2(V1,V2) #V1"."#V2
#define PHP_VER3(V1,V2,V3) #V1"."#V2"."#V3
#define PHP_REGISTRY_KEYV(VER) PHP_REGISTRY_KEY"\\"VER
#define PHP_REGISTRY_KEY1(V1) PHP_REGISTRY_KEY"\\"PHP_VER1(V1)
#define PHP_REGISTRY_KEY2(V1,V2) PHP_REGISTRY_KEY"\\"PHP_VER2(V1,V2)
#define PHP_REGISTRY_KEY3(V1,V2,V3) PHP_REGISTRY_KEY"\\"PHP_VER3(V1,V2,V3)
static const char* registry_keys[] = {
PHP_REGISTRY_KEYV(PHP_VERSION),
PHP_REGISTRY_KEY3(PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION),
PHP_REGISTRY_KEY2(PHP_MAJOR_VERSION, PHP_MINOR_VERSION),
PHP_REGISTRY_KEY1(PHP_MAJOR_VERSION),
PHP_REGISTRY_KEY,
NULL
};
static int OpenPhpRegistryKey(char* sub_key, HKEY *hKey)
{/*{{{*/
const char **key_name = registry_keys;
if (sub_key) {
size_t main_key_len;
size_t sub_key_len = strlen(sub_key);
char *reg_key;
while (*key_name) {
LONG ret;
main_key_len = strlen(*key_name);
reg_key = emalloc(main_key_len + sub_key_len + 1);
memcpy(reg_key, *key_name, main_key_len);
memcpy(reg_key + main_key_len, sub_key, sub_key_len + 1);
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg_key, 0, KEY_READ, hKey);
efree(reg_key);
if (ret == ERROR_SUCCESS) {
return 1;
}
++key_name;
}
} else {
while (*key_name) {
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, *key_name, 0, KEY_READ, hKey) == ERROR_SUCCESS) {
return 1;
}
++key_name;
}
}
return 0;
}/*}}}*/
static int LoadDirectory(HashTable *directories, HKEY key, char *path, int path_len, HashTable *parent_ht)
{/*{{{*/
DWORD keys, values, max_key, max_name, max_value;
int ret = 0;
HashTable *ht = NULL;
if (RegQueryInfoKey(key, NULL, NULL, NULL, &keys, &max_key, NULL, &values, &max_name, &max_value, NULL, NULL) == ERROR_SUCCESS) {
if (values) {
DWORD i;
char *name = (char*)emalloc(max_name+1);
char *value = (char*)emalloc(max_value+1);
DWORD name_len, type, value_len;
for (i = 0; i < values; i++) {
name_len = max_name+1;
value_len = max_value+1;
memset(name, '\0', max_name+1);
memset(value, '\0', max_value+1);
if (RegEnumValue(key, i, name, &name_len, NULL, &type, value, &value_len) == ERROR_SUCCESS) {
if ((type == REG_SZ) || (type == REG_EXPAND_SZ)) {
zval data;
if (!ht) {
ht = (HashTable*)malloc(sizeof(HashTable));
if (!ht) {
return ret;
}
zend_hash_init(ht, 0, NULL, ZVAL_INTERNAL_PTR_DTOR, 1);
}
ZVAL_PSTRINGL(&data, value, value_len-1);
zend_hash_str_update(ht, name, name_len, &data);
}
}
}
if (ht) {
if (parent_ht) {
zend_string *index;
zend_ulong num;
zval *tmpdata;
ZEND_HASH_MAP_FOREACH_KEY_VAL(parent_ht, num, index, tmpdata) {
zend_hash_add(ht, index, tmpdata);
} ZEND_HASH_FOREACH_END();
}
zend_hash_str_update_mem(directories, path, path_len, ht, sizeof(HashTable));
ret = 1;
}
efree(name);
efree(value);
}
if (ht == NULL) {
ht = parent_ht;
}
if (keys) {
DWORD i;
char *name = (char*)emalloc(max_key+1);
char *new_path = (char*)emalloc(path_len+max_key+2);
DWORD name_len;
FILETIME t;
HKEY subkey;
for (i = 0; i < keys; i++) {
name_len = max_key+1;
if (RegEnumKeyEx(key, i, name, &name_len, NULL, NULL, NULL, &t) == ERROR_SUCCESS) {
if (RegOpenKeyEx(key, name, 0, KEY_READ, &subkey) == ERROR_SUCCESS) {
if (path_len) {
memcpy(new_path, path, path_len);
new_path[path_len] = '/';
memcpy(new_path+path_len+1, name, name_len+1);
zend_str_tolower(new_path, path_len+name_len+1);
name_len += path_len+1;
} else {
memcpy(new_path, name, name_len+1);
zend_str_tolower(new_path, name_len);
}
if (LoadDirectory(directories, subkey, new_path, name_len, ht)) {
ret = 1;
}
RegCloseKey(subkey);
}
}
}
efree(new_path);
efree(name);
}
}
return ret;
}/*}}}*/
static void delete_internal_hashtable(zval *zv)
{/*{{{*/
HashTable *ht = (HashTable *)Z_PTR_P(zv);
zend_hash_destroy(ht);
free(ht);
}/*}}}*/
#define RegNotifyFlags (REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_ATTRIBUTES | REG_NOTIFY_CHANGE_LAST_SET)
void UpdateIniFromRegistry(char *path)
{/*{{{*/
char *p, *orig_path;
int path_len;
if(!path) {
return;
}
if (!PW32G(registry_directories)) {
PW32G(registry_directories) = (HashTable*)malloc(sizeof(HashTable));
if (!PW32G(registry_directories)) {
return;
}
zend_hash_init(PW32G(registry_directories), 0, NULL, delete_internal_hashtable, 1);
if (!OpenPhpRegistryKey("\\Per Directory Values", &PW32G(registry_key))) {
PW32G(registry_key) = NULL;
return;
}
PW32G(registry_event) = CreateEvent(NULL, TRUE, FALSE, NULL);
if (PW32G(registry_event)) {
RegNotifyChangeKeyValue(PW32G(registry_key), TRUE, RegNotifyFlags, PW32G(registry_event), TRUE);
}
if (!LoadDirectory(PW32G(registry_directories), PW32G(registry_key), "", 0, NULL)) {
return;
}
} else if (PW32G(registry_event) && WaitForSingleObject(PW32G(registry_event), 0) == WAIT_OBJECT_0) {
RegNotifyChangeKeyValue(PW32G(registry_key), TRUE, RegNotifyFlags, PW32G(registry_event), TRUE);
zend_hash_clean(PW32G(registry_directories));
if (!LoadDirectory(PW32G(registry_directories), PW32G(registry_key), "", 0, NULL)) {
return;
}
} else if (zend_hash_num_elements(PW32G(registry_directories)) == 0) {
return;
}
orig_path = path = estrdup(path);
/* Get rid of C:, if exists */
p = strchr(path, ':');
if (p) {
*p = path[0]; /* replace the colon with the drive letter */
path = p; /* make path point to the drive letter */
} else {
if (path[0] != '\\' && path[0] != '/') {
char tmp_buf[MAXPATHLEN], *cwd;
char drive_letter;
/* get current working directory and prepend it to the path */
if (!VCWD_GETCWD(tmp_buf, MAXPATHLEN)) {
efree(orig_path);
return;
}
cwd = strchr(tmp_buf, ':');
if (!cwd) {
drive_letter = 'C';
cwd = tmp_buf;
} else {
drive_letter = tmp_buf[0];
cwd++;
}
while (*cwd == '\\' || *cwd == '/') {
cwd++;
}
spprintf(&path, 0, "%c\\%s\\%s", drive_letter, cwd, orig_path);
efree(orig_path);
orig_path = path;
}
}
path_len = 0;
while (path[path_len] != 0) {
if (path[path_len] == '\\') {
path[path_len] = '/';
}
path_len++;
}
zend_str_tolower(path, path_len);
while (path_len > 0) {
HashTable *ht = (HashTable *)zend_hash_str_find_ptr(PW32G(registry_directories), path, path_len);
if (ht != NULL) {
zend_string *index;
zval *data;
ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(ht, index, data) {
zend_alter_ini_entry(index, Z_STR_P(data), PHP_INI_USER, PHP_INI_STAGE_ACTIVATE);
} ZEND_HASH_FOREACH_END();
}
do {
path_len--;
} while (path_len > 0 && path[path_len] != '/');
path[path_len] = 0;
}
efree(orig_path);
}/*}}}*/
#define PHPRC_REGISTRY_NAME "IniFilePath"
char *GetIniPathFromRegistry()
{/*{{{*/
char *reg_location = NULL;
HKEY hKey;
if (OpenPhpRegistryKey(NULL, &hKey)) {
DWORD buflen = MAXPATHLEN;
reg_location = emalloc(MAXPATHLEN+1);
if(RegQueryValueEx(hKey, PHPRC_REGISTRY_NAME, 0, NULL, reg_location, &buflen) != ERROR_SUCCESS) {
RegCloseKey(hKey);
efree(reg_location);
reg_location = NULL;
return reg_location;
}
RegCloseKey(hKey);
}
return reg_location;
}/*}}}*/
| 8,542 | 27.476667 | 130 |
c
|
php-src
|
php-src-master/win32/select.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]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_network.h"
/* Win32 select() will only work with sockets, so we roll our own implementation here.
* - If you supply only sockets, this simply passes through to winsock select().
* - If you supply file handles, there is no way to distinguish between
* ready for read/write or OOB, so any set in which the handle is found will
* be marked as ready.
* - If you supply a mixture of handles and sockets, the system will interleave
* calls between select() and WaitForMultipleObjects(). The time slicing may
* cause this function call to take up to 100 ms longer than you specified.
* - Calling this with NULL sets as a portable way to sleep with sub-second
* accuracy is not supported.
* */
PHPAPI int php_select(php_socket_t max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tv)
{
ULONGLONG ms_total, limit;
HANDLE handles[MAXIMUM_WAIT_OBJECTS];
int handle_slot_to_fd[MAXIMUM_WAIT_OBJECTS];
int n_handles = 0, i;
fd_set sock_read, sock_write, sock_except;
fd_set aread, awrite, aexcept;
int sock_max_fd = -1;
struct timeval tvslice;
int retcode;
/* As max_fd is unsigned, non socket might overflow. */
if (max_fd > (php_socket_t)INT_MAX) {
return -1;
}
#define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
/* calculate how long we need to wait in milliseconds */
if (tv == NULL) {
ms_total = INFINITE;
} else {
ms_total = tv->tv_sec * 1000;
ms_total += tv->tv_usec / 1000;
}
FD_ZERO(&sock_read);
FD_ZERO(&sock_write);
FD_ZERO(&sock_except);
/* build an array of handles for non-sockets */
for (i = 0; (uint32_t)i < max_fd; i++) {
if (SAFE_FD_ISSET(i, rfds) || SAFE_FD_ISSET(i, wfds) || SAFE_FD_ISSET(i, efds)) {
handles[n_handles] = (HANDLE)(uintptr_t)_get_osfhandle(i);
if (handles[n_handles] == INVALID_HANDLE_VALUE) {
/* socket */
if (SAFE_FD_ISSET(i, rfds)) {
FD_SET((uint32_t)i, &sock_read);
}
if (SAFE_FD_ISSET(i, wfds)) {
FD_SET((uint32_t)i, &sock_write);
}
if (SAFE_FD_ISSET(i, efds)) {
FD_SET((uint32_t)i, &sock_except);
}
if (i > sock_max_fd) {
sock_max_fd = i;
}
} else {
handle_slot_to_fd[n_handles] = i;
n_handles++;
}
}
}
if (n_handles == 0) {
/* plain sockets only - let winsock handle the whole thing */
return select(-1, rfds, wfds, efds, tv);
}
/* mixture of handles and sockets; lets multiplex between
* winsock and waiting on the handles */
FD_ZERO(&aread);
FD_ZERO(&awrite);
FD_ZERO(&aexcept);
limit = GetTickCount64() + ms_total;
do {
retcode = 0;
if (sock_max_fd >= 0) {
/* overwrite the zero'd sets here; the select call
* will clear those that are not active */
aread = sock_read;
awrite = sock_write;
aexcept = sock_except;
tvslice.tv_sec = 0;
tvslice.tv_usec = 100000;
retcode = select(-1, &aread, &awrite, &aexcept, &tvslice);
}
if (n_handles > 0) {
/* check handles */
DWORD wret;
wret = WaitForMultipleObjects(n_handles, handles, FALSE, retcode > 0 ? 0 : 100);
if (wret == WAIT_TIMEOUT) {
/* set retcode to 0; this is the default.
* select() may have set it to something else,
* in which case we leave it alone, so this branch
* does nothing */
;
} else if (wret == WAIT_FAILED) {
if (retcode == 0) {
retcode = -1;
}
} else {
if (retcode < 0) {
retcode = 0;
}
for (i = 0; i < n_handles; i++) {
if (WAIT_OBJECT_0 == WaitForSingleObject(handles[i], 0)) {
if (SAFE_FD_ISSET(handle_slot_to_fd[i], rfds)) {
FD_SET((uint32_t)handle_slot_to_fd[i], &aread);
}
if (SAFE_FD_ISSET(handle_slot_to_fd[i], wfds)) {
FD_SET((uint32_t)handle_slot_to_fd[i], &awrite);
}
if (SAFE_FD_ISSET(handle_slot_to_fd[i], efds)) {
FD_SET((uint32_t)handle_slot_to_fd[i], &aexcept);
}
retcode++;
}
}
}
}
} while (retcode == 0 && (ms_total == INFINITE || GetTickCount64() < limit));
if (rfds) {
*rfds = aread;
}
if (wfds) {
*wfds = awrite;
}
if (efds) {
*efds = aexcept;
}
return retcode;
}
| 5,087 | 29.836364 | 104 |
c
|
php-src
|
php-src-master/win32/select.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_WIN32_SELECT_H
#define PHP_WIN32_SELECT_H
#include "php_network.h"
PHPAPI int php_select(php_socket_t max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tv);
#endif
| 1,177 | 46.12 | 105 |
h
|
php-src
|
php-src-master/win32/sendmail.h
|
#if !defined(sendmail_h) /* Sentry, use file only if it's not already included. */
#define sendmail_h
#include <windows.h>
#define HOST_NAME_LEN 256
#define MAX_APPNAME_LENGTH 100
#define MAIL_BUFFER_SIZE (1024*4) /* 4k buffer */
/* Return values */
#define MIN_ERROR_INDEX 0 /* Always 0 like SUCCESS */
#define SUCCESS 0
#define FAILED_TO_PARSE_ARGUMENTS 1
#define FAILED_TO_OPEN_MAILFILE 2
#define FAILED_TO_START_SOCKETS 3
#define FAILED_TO_RESOLVE_HOST 4
#define FAILED_TO_OBTAIN_SOCKET_HANDLE 5
#define FAILED_TO_CONNECT 6
#define FAILED_TO_SEND 7
#define FAILED_TO_RECEIVE 8
#define SMTP_SERVER_ERROR 9
#define FAILED_TO_GET_HOSTNAME 10
#define OUT_OF_MEMORY 11
#define UNKNOWN_ERROR 12
#define BAD_MSG_CONTENTS 13
#define BAD_MSG_SUBJECT 14
#define BAD_MSG_DESTINATION 15
#define BAD_MSG_RPATH 16
#define BAD_MAIL_HOST 17
#define BAD_MSG_FILE 18
#define W32_SM_SENDMAIL_FROM_NOT_SET 19
#define W32_SM_SENDMAIL_FROM_MALFORMED 20
#define W32_SM_PCRE_ERROR 21
#define MAX_ERROR_INDEX 22 /* Always last error message + 1 */
PHPAPI int TSendMail(const char *host, int *error, char **error_message,
const char *headers, const char *Subject, const char *mailTo, const char *data,
char *mailCc, char *mailBcc, char *mailRPath);
PHPAPI void TSMClose(void);
static int SendText(char *RPath, const char *Subject, const char *mailTo, char *mailCc, char *mailBcc, const char *data,
const char *headers, char *headers_lc, char **error_message);
PHPAPI char *GetSMErrorText(int index);
static int MailConnect();
static int PostHeader(char *RPath, const char *Subject, const char *mailTo, char *xheaders);
static int Post(LPCSTR msg);
static int Ack(char **server_response);
static unsigned long GetAddr(LPSTR szHost);
static int FormatEmailAddress(char* Buf, char* EmailAddress, char* FormatString);
#endif /* sendmail_h */
| 1,911 | 37.24 | 120 |
h
|
php-src
|
php-src-master/win32/signal.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "SAPI.h"
#include "win32/console.h"
/* true globals; only used from main thread and from kernel callback */
static zval ctrl_handler;
static DWORD ctrl_evt = (DWORD)-1;
static zend_atomic_bool *vm_interrupt_flag = NULL;
static void (*orig_interrupt_function)(zend_execute_data *execute_data);
static void php_win32_signal_ctrl_interrupt_function(zend_execute_data *execute_data)
{/*{{{*/
if (IS_UNDEF != Z_TYPE(ctrl_handler)) {
zval retval, params[1];
ZVAL_LONG(¶ms[0], ctrl_evt);
/* If the function returns, */
call_user_function(NULL, NULL, &ctrl_handler, &retval, 1, params);
zval_ptr_dtor(&retval);
}
if (orig_interrupt_function) {
orig_interrupt_function(execute_data);
}
}/*}}}*/
PHP_WINUTIL_API void php_win32_signal_ctrl_handler_init(void)
{/*{{{*/
/* We are in the main thread! */
if (!php_win32_console_is_cli_sapi()) {
return;
}
orig_interrupt_function = zend_interrupt_function;
zend_interrupt_function = php_win32_signal_ctrl_interrupt_function;
vm_interrupt_flag = &EG(vm_interrupt);
ZVAL_UNDEF(&ctrl_handler);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_EVENT_CTRL_C", CTRL_C_EVENT, CONST_PERSISTENT);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_EVENT_CTRL_BREAK", CTRL_BREAK_EVENT, CONST_PERSISTENT);
}/*}}}*/
PHP_WINUTIL_API void php_win32_signal_ctrl_handler_shutdown(void)
{/*{{{*/
if (!php_win32_console_is_cli_sapi()) {
return;
}
zend_interrupt_function = orig_interrupt_function;
orig_interrupt_function = NULL;
vm_interrupt_flag = NULL;
ZVAL_UNDEF(&ctrl_handler);
}/*}}}*/
static BOOL WINAPI php_win32_signal_system_ctrl_handler(DWORD evt)
{/*{{{*/
if (CTRL_C_EVENT != evt && CTRL_BREAK_EVENT != evt) {
return FALSE;
}
zend_atomic_bool_store_ex(vm_interrupt_flag, true);
ctrl_evt = evt;
return TRUE;
}/*}}}*/
/* {{{ Assigns a CTRL signal handler to a PHP function */
PHP_FUNCTION(sapi_windows_set_ctrl_handler)
{
zend_fcall_info fci;
zend_fcall_info_cache fcc;
bool add = 1;
/* callable argument corresponds to the CTRL handler */
if (zend_parse_parameters(ZEND_NUM_ARGS(), "f!|b", &fci, &fcc, &add) == FAILURE) {
RETURN_THROWS();
}
#if ZTS
if (!tsrm_is_main_thread()) {
zend_throw_error(NULL, "CTRL events can only be received on the main thread");
RETURN_THROWS();
}
#endif
if (!php_win32_console_is_cli_sapi()) {
zend_throw_error(NULL, "CTRL events trapping is only supported on console");
RETURN_THROWS();
}
if (!ZEND_FCI_INITIALIZED(fci)) {
zval_ptr_dtor(&ctrl_handler);
ZVAL_UNDEF(&ctrl_handler);
if (!SetConsoleCtrlHandler(NULL, add)) {
RETURN_FALSE;
}
RETURN_TRUE;
}
if (!SetConsoleCtrlHandler(NULL, FALSE) || !SetConsoleCtrlHandler(php_win32_signal_system_ctrl_handler, add)) {
zend_string *func_name = zend_get_callable_name(&fci.function_name);
php_error_docref(NULL, E_WARNING, "Unable to attach %s as a CTRL handler", ZSTR_VAL(func_name));
zend_string_release_ex(func_name, 0);
RETURN_FALSE;
}
zval_ptr_dtor_nogc(&ctrl_handler);
ZVAL_COPY(&ctrl_handler, &fci.function_name);
RETURN_TRUE;
}/*}}}*/
PHP_FUNCTION(sapi_windows_generate_ctrl_event)
{/*{{{*/
zend_long evt, pid = 0;
bool ret = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l", &evt, &pid) == FAILURE) {
RETURN_THROWS();
}
if (!php_win32_console_is_cli_sapi()) {
zend_throw_error(NULL, "CTRL events trapping is only supported on console");
return;
}
SetConsoleCtrlHandler(NULL, TRUE);
ret = (GenerateConsoleCtrlEvent(evt, pid) != 0);
if (IS_UNDEF != Z_TYPE(ctrl_handler)) {
ret = ret && SetConsoleCtrlHandler(php_win32_signal_system_ctrl_handler, TRUE);
}
RETURN_BOOL(ret);
}/*}}}*/
| 4,642 | 28.386076 | 112 |
c
|
php-src
|
php-src-master/win32/sockets.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: Chris Vandomelen <[email protected]> |
| Sterling Hughes <[email protected]> |
| |
| WinSock: Daniel Beulshausen <[email protected]> |
+----------------------------------------------------------------------+
*/
/* Code originally from ext/sockets */
#include <stdio.h>
#include <fcntl.h>
#include "php.h"
PHPAPI int socketpair_win32(int domain, int type, int protocol, SOCKET sock[2], int overlapped)
{
struct sockaddr_in address;
SOCKET redirect;
int size = sizeof(address);
if (domain != AF_INET) {
WSASetLastError(WSAENOPROTOOPT);
return -1;
}
sock[1] = redirect = INVALID_SOCKET;
sock[0] = socket(domain, type, protocol);
if (INVALID_SOCKET == sock[0]) {
goto error;
}
address.sin_addr.s_addr = INADDR_ANY;
address.sin_family = AF_INET;
address.sin_port = 0;
if (bind(sock[0], (struct sockaddr *) &address, sizeof(address)) != 0) {
goto error;
}
if (getsockname(sock[0], (struct sockaddr *) &address, &size) != 0) {
goto error;
}
if (listen(sock[0], 2) != 0) {
goto error;
}
if (overlapped) {
sock[1] = socket(domain, type, protocol);
} else {
sock[1] = WSASocket(domain, type, protocol, NULL, 0, 0);
}
if (INVALID_SOCKET == sock[1]) {
goto error;
}
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(sock[1], (struct sockaddr *) &address, sizeof(address)) != 0) {
goto error;
}
redirect = accept(sock[0], (struct sockaddr *) &address, &size);
if (INVALID_SOCKET == redirect) {
goto error;
}
closesocket(sock[0]);
sock[0] = redirect;
return 0;
error:
closesocket(redirect);
closesocket(sock[0]);
closesocket(sock[1]);
WSASetLastError(WSAECONNABORTED);
return -1;
}
PHPAPI int socketpair(int domain, int type, int protocol, SOCKET sock[2])
{
return socketpair_win32(domain, type, protocol, sock, 1);
}
| 2,807 | 27.653061 | 95 |
c
|
php-src
|
php-src-master/win32/sockets.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Chris Vandomelen <[email protected]> |
| Sterling Hughes <[email protected]> |
| |
| WinSock: Daniel Beulshausen <[email protected]> |
+----------------------------------------------------------------------+
*/
/* Code originally from ext/sockets */
#ifndef PHP_WIN32_SOCKETS_H
#define PHP_WIN32_SOCKETS_H
PHPAPI int socketpair_win32(int domain, int type, int protocol, SOCKET sock[2], int overlapped);
PHPAPI int socketpair(int domain, int type, int protocol, SOCKET sock[2]);
#endif
| 1,501 | 50.793103 | 96 |
h
|
php-src
|
php-src-master/win32/syslog.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]> |
+----------------------------------------------------------------------+
*/
#ifndef SYSLOG_H
#define SYSLOG_H
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define LOG_EMERG 1
#define LOG_ALERT 1
#define LOG_CRIT 1
#define LOG_ERR 4
#define LOG_WARNING 5
#define LOG_NOTICE 6
#define LOG_INFO 6
#define LOG_DEBUG 6
#define LOG_PRIMASK 0x07
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
#define LOG_KERN (0<<3)
#define LOG_USER (1<<3)
#define LOG_MAIL (2<<3)
#define LOG_DAEMON (3<<3)
#define LOG_AUTH (4<<3)
#define LOG_SYSLOG (5<<3)
#define LOG_LPR (6<<3)
#define LOG_NEWS (7<<3)
#define LOG_UUCP (8<<3)
#define LOG_CRON (9<<3)
#define LOG_AUTHPRIV (10<<3)
#define LOG_NFACILITIES 10
#define LOG_FACMASK 0x03f8
#define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3)
#define LOG_MASK(pri) (1 << (pri))
#define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1)
/*
* Option flags for openlog.
*
* LOG_ODELAY no longer does anything.
* LOG_NDELAY is the inverse of what it used to be.
*/
#define LOG_PID 0x01 /* log the pid with each message */
#define LOG_CONS 0x02 /* log on the console if errors in sending */
#define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
#define LOG_NDELAY 0x08 /* don't delay open */
#define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
#define LOG_PERROR 0x20 /* log to stderr as well */
extern void closelog(void);
extern void openlog(const char *, int, int);
extern void syslog(int, const char *, ...);
extern void vsyslog(int, const char *, va_list ap);
#endif /* SYSLOG_H */
| 2,548 | 32.539474 | 76 |
h
|
php-src
|
php-src-master/win32/time.c
|
/*****************************************************************************
* *
* DH_TIME.C *
* *
* Freely redistributable and modifiable. Use at your own risk. *
* *
* Copyright 1994 The Downhill Project *
*
* Modified by Shane Caraveo for use with PHP
*
*****************************************************************************/
/* Include stuff ************************************************************ */
#include <config.w32.h>
#include "time.h"
#include "unistd.h"
#include "signal.h"
#include <windows.h>
#include <winbase.h>
#include <mmsystem.h>
#include <errno.h>
#include "php_win32_globals.h"
typedef VOID (WINAPI *MyGetSystemTimeAsFileTime)(LPFILETIME lpSystemTimeAsFileTime);
static MyGetSystemTimeAsFileTime timefunc = NULL;
#ifdef PHP_EXPORTS
static zend_always_inline MyGetSystemTimeAsFileTime get_time_func(void)
{/*{{{*/
MyGetSystemTimeAsFileTime timefunc = NULL;
HMODULE hMod = GetModuleHandle("kernel32.dll");
if (hMod) {
/* Max possible resolution <1us, win8/server2012 */
timefunc = (MyGetSystemTimeAsFileTime)GetProcAddress(hMod, "GetSystemTimePreciseAsFileTime");
}
if(!timefunc) {
/* 100ns blocks since 01-Jan-1641 */
timefunc = (MyGetSystemTimeAsFileTime) GetSystemTimeAsFileTime;
}
return timefunc;
}/*}}}*/
void php_win32_init_gettimeofday(void)
{/*{{{*/
timefunc = get_time_func();
}/*}}}*/
#endif
static zend_always_inline int getfilesystemtime(struct timeval *tv)
{/*{{{*/
FILETIME ft;
unsigned __int64 ff = 0;
ULARGE_INTEGER fft;
timefunc(&ft);
/*
* Do not cast a pointer to a FILETIME structure to either a
* ULARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows.
* via http://technet.microsoft.com/en-us/library/ms724284(v=vs.85).aspx
*/
fft.HighPart = ft.dwHighDateTime;
fft.LowPart = ft.dwLowDateTime;
ff = fft.QuadPart;
ff /= 10Ui64; /* convert to microseconds */
ff -= 11644473600000000Ui64; /* convert to unix epoch */
tv->tv_sec = (long)(ff / 1000000Ui64);
tv->tv_usec = (long)(ff % 1000000Ui64);
return 0;
}/*}}}*/
PHPAPI int gettimeofday(struct timeval *time_Info, struct timezone *timezone_Info)
{/*{{{*/
/* Get the time, if they want it */
if (time_Info != NULL) {
getfilesystemtime(time_Info);
}
/* Get the timezone, if they want it */
if (timezone_Info != NULL) {
_tzset();
timezone_Info->tz_minuteswest = _timezone;
timezone_Info->tz_dsttime = _daylight;
}
/* And return */
return 0;
}/*}}}*/
PHPAPI int usleep(unsigned int useconds)
{/*{{{*/
HANDLE timer;
LARGE_INTEGER due;
due.QuadPart = -(10 * (__int64)useconds);
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &due, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
return 0;
}/*}}}*/
PHPAPI int nanosleep( const struct timespec * rqtp, struct timespec * rmtp )
{/*{{{*/
if (rqtp->tv_nsec > 999999999) {
/* The time interval specified 1,000,000 or more microseconds. */
errno = EINVAL;
return -1;
}
return usleep( rqtp->tv_sec * 1000000 + rqtp->tv_nsec / 1000 );
}/*}}}*/
| 3,419 | 27.5 | 95 |
c
|
php-src
|
php-src-master/win32/time.h
|
/*****************************************************************************
* *
* sys/time.h *
* *
* Freely redistributable and modifiable. Use at your own risk. *
* *
* Copyright 1994 The Downhill Project *
*
* Modified by Shane Caraveo for PHP
*
*****************************************************************************/
#ifndef TIME_H
#define TIME_H
/* Include stuff ************************************************************ */
#include <time.h>
#include "php.h"
/* Struct stuff ************************************************************* */
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};
#if !defined(timespec) && _MSC_VER < 1900
struct timespec
{
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#endif
#define ITIMER_REAL 0 /*generates sigalrm */
#define ITIMER_VIRTUAL 1 /*generates sigvtalrm */
#define ITIMER_VIRT 1 /*generates sigvtalrm */
#define ITIMER_PROF 2 /*generates sigprof */
typedef long suseconds_t;
/* Prototype stuff ********************************************************** */
PHPAPI extern int gettimeofday(struct timeval *time_Info, struct timezone *timezone_Info);
/* setitimer operates at 100 millisecond resolution */
PHPAPI extern int setitimer(int which, const struct itimerval *value,
struct itimerval *ovalue);
PHPAPI int nanosleep( const struct timespec * rqtp, struct timespec * rmtp );
PHPAPI int usleep(unsigned int useconds);
#ifdef PHP_EXPORTS
/* This symbols are needed only for the DllMain, but should not be exported
or be available when used with PHP binaries. */
void php_win32_init_gettimeofday(void);
#endif
#endif
| 2,105 | 31.90625 | 90 |
h
|
php-src
|
php-src-master/win32/winutil.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: Zeev Suraski <[email protected]> |
* Pierre Joye <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "winutil.h"
#include "codepage.h"
#include <bcrypt.h>
#include <lmcons.h>
PHP_WINUTIL_API char *php_win32_error_to_msg(HRESULT error)
{/*{{{*/
wchar_t *bufw = NULL, *pw;
char *buf;
DWORD ret = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPWSTR)&bufw, 0, NULL
);
if (!ret || !bufw) {
return "";
}
/* strip trailing line breaks and periods */
for (pw = bufw + wcslen(bufw) - 1; pw >= bufw && (*pw == L'\r' || *pw == L'\n' || *pw == L'.'); pw--);
pw[1] = L'\0';
buf = php_win32_cp_conv_w_to_any(bufw, ret, PHP_WIN32_CP_IGNORE_LEN_P);
LocalFree(bufw);
return (buf ? buf : "");
}/*}}}*/
PHP_WINUTIL_API void php_win32_error_msg_free(char *msg)
{/*{{{*/
if (msg && msg[0]) {
free(msg);
}
}/*}}}*/
int php_win32_check_trailing_space(const char * path, const size_t path_len)
{/*{{{*/
if (path_len > MAXPATHLEN - 1) {
return 1;
}
if (path) {
if (path[0] == ' ' || path[path_len - 1] == ' ') {
return 0;
} else {
return 1;
}
} else {
return 0;
}
}/*}}}*/
static BCRYPT_ALG_HANDLE bcrypt_algo;
static BOOL has_bcrypt_algo = 0;
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#ifdef PHP_EXPORTS
BOOL php_win32_shutdown_random_bytes(void)
{/*{{{*/
BOOL ret = TRUE;
if (has_bcrypt_algo) {
ret = NT_SUCCESS(BCryptCloseAlgorithmProvider(bcrypt_algo, 0));
has_bcrypt_algo = 0;
}
return ret;
}/*}}}*/
BOOL php_win32_init_random_bytes(void)
{/*{{{*/
if (has_bcrypt_algo) {
return TRUE;
}
has_bcrypt_algo = NT_SUCCESS(BCryptOpenAlgorithmProvider(&bcrypt_algo, BCRYPT_RNG_ALGORITHM, NULL, 0));
return has_bcrypt_algo;
}/*}}}*/
#endif
PHP_WINUTIL_API int php_win32_get_random_bytes(unsigned char *buf, size_t size)
{ /* {{{ */
BOOL ret;
#if 0
/* Currently we fail on startup, with CNG API it shows no regressions so far and is secure.
Should switch on and try to reinit, if it fails too often on startup. This means also
bringing locks back. */
if (has_bcrypt_algo == 0) {
return FAILURE;
}
#endif
/* No sense to loop here, the limit is huge enough. */
ret = NT_SUCCESS(BCryptGenRandom(bcrypt_algo, buf, (ULONG)size, 0));
return ret ? SUCCESS : FAILURE;
}
/* }}} */
/*
* This functions based on the code from the UNIXem project under
* the BSD like license. Modified for PHP by [email protected]
*
* Home: http://synesis.com.au/software/
*
* Copyright (c) 2005-2010, Matthew Wilson and Synesis Software
*/
PHP_WINUTIL_API int php_win32_code_to_errno(unsigned long w32Err)
{/*{{{*/
size_t i;
struct code_to_errno_map
{
unsigned long w32Err;
int eerrno;
};
static const struct code_to_errno_map errmap[] =
{
/* 1 */ { ERROR_INVALID_FUNCTION , EINVAL }
/* 2 */ , { ERROR_FILE_NOT_FOUND , ENOENT }
/* 3 */ , { ERROR_PATH_NOT_FOUND , ENOENT }
/* 4 */ , { ERROR_TOO_MANY_OPEN_FILES , EMFILE }
/* 5 */ , { ERROR_ACCESS_DENIED , EACCES }
/* 6 */ , { ERROR_INVALID_HANDLE , EBADF }
/* 7 */ , { ERROR_ARENA_TRASHED , ENOMEM }
/* 8 */ , { ERROR_NOT_ENOUGH_MEMORY , ENOMEM }
/* 9 */ , { ERROR_INVALID_BLOCK , ENOMEM }
/* 10 */ , { ERROR_BAD_ENVIRONMENT , E2BIG }
/* 11 */ , { ERROR_BAD_FORMAT , ENOEXEC }
/* 12 */ , { ERROR_INVALID_ACCESS , EINVAL }
/* 13 */ , { ERROR_INVALID_DATA , EINVAL }
/* 14 */ , { ERROR_OUTOFMEMORY , ENOMEM }
/* 15 */ , { ERROR_INVALID_DRIVE , ENOENT }
/* 16 */ , { ERROR_CURRENT_DIRECTORY , ECURDIR }
/* 17 */ , { ERROR_NOT_SAME_DEVICE , EXDEV }
/* 18 */ , { ERROR_NO_MORE_FILES , ENOENT }
/* 19 */ , { ERROR_WRITE_PROTECT , EROFS }
/* 20 */ , { ERROR_BAD_UNIT , ENXIO }
/* 21 */ , { ERROR_NOT_READY , EBUSY }
/* 22 */ , { ERROR_BAD_COMMAND , EIO }
/* 23 */ , { ERROR_CRC , EIO }
/* 24 */ , { ERROR_BAD_LENGTH , EIO }
/* 25 */ , { ERROR_SEEK , EIO }
/* 26 */ , { ERROR_NOT_DOS_DISK , EIO }
/* 27 */ , { ERROR_SECTOR_NOT_FOUND , ENXIO }
/* 28 */ , { ERROR_OUT_OF_PAPER , EBUSY }
/* 29 */ , { ERROR_WRITE_FAULT , EIO }
/* 30 */ , { ERROR_READ_FAULT , EIO }
/* 31 */ , { ERROR_GEN_FAILURE , EIO }
/* 32 */ , { ERROR_SHARING_VIOLATION , EAGAIN }
/* 33 */ , { ERROR_LOCK_VIOLATION , EACCES }
/* 34 */ , { ERROR_WRONG_DISK , ENXIO }
/* 35 */ , { 35 , ENFILE }
/* 36 */ , { ERROR_SHARING_BUFFER_EXCEEDED , ENFILE }
/* 37 */ , { ERROR_HANDLE_EOF , EINVAL }
/* 38 */ , { ERROR_HANDLE_DISK_FULL , ENOSPC }
#if 0
/* 39 */ , { 0 , 0 }
/* 40 */ , { 0 , 0 }
/* 41 */ , { 0 , 0 }
/* 42 */ , { 0 , 0 }
/* 43 */ , { 0 , 0 }
/* 44 */ , { 0 , 0 }
/* 45 */ , { 0 , 0 }
/* 46 */ , { 0 , 0 }
/* 47 */ , { 0 , 0 }
/* 48 */ , { 0 , 0 }
/* 49 */ , { 0 , 0 }
#endif
/* 50 */ , { ERROR_NOT_SUPPORTED , ENOSYS }
#if 0
/* 51 */ , { 0 , 0 }
/* 52 */ , { 0 , 0 }
#endif
/* 53 */ , { ERROR_BAD_NETPATH , ENOENT }
#if 0
/* 54 */ , { 0 , 0 }
/* 55 */ , { 0 , 0 }
/* 56 */ , { 0 , 0 }
/* 57 */ , { 0 , 0 }
/* 58 */ , { 0 , 0 }
/* 59 */ , { 0 , 0 }
/* 60 */ , { 0 , 0 }
/* 61 */ , { 0 , 0 }
/* 62 */ , { 0 , 0 }
/* 63 */ , { 0 , 0 }
/* 64 */ , { 0 , 0 }
#endif
/* 65 */ , { ERROR_NETWORK_ACCESS_DENIED , EACCES }
#if 0
/* 66 */ , { 0 , 0 }
#endif
/* 67 */ , { ERROR_BAD_NET_NAME , ENOENT }
#if 0
/* 68 */ , { 0 , 0 }
/* 69 */ , { 0 , 0 }
/* 70 */ , { 0 , 0 }
/* 71 */ , { 0 , 0 }
/* 72 */ , { 0 , 0 }
/* 73 */ , { 0 , 0 }
/* 74 */ , { 0 , 0 }
/* 75 */ , { 0 , 0 }
/* 76 */ , { 0 , 0 }
/* 77 */ , { 0 , 0 }
/* 78 */ , { 0 , 0 }
/* 79 */ , { 0 , 0 }
#endif
/* 80 */ , { ERROR_FILE_EXISTS , EEXIST }
#if 0
/* 81 */ , { 0 , 0 }
#endif
/* 82 */ , { ERROR_CANNOT_MAKE , EACCES }
/* 83 */ , { ERROR_FAIL_I24 , EACCES }
#if 0
/* 84 */ , { 0 , 0 }
/* 85 */ , { 0 , 0 }
/* 86 */ , { 0 , 0 }
#endif
/* 87 */ , { ERROR_INVALID_PARAMETER , EINVAL }
#if 0
/* 88 */ , { 0 , 0 }
#endif
/* 89 */ , { ERROR_NO_PROC_SLOTS , EAGAIN }
#if 0
/* 90 */ , { 0 , 0 }
/* 91 */ , { 0 , 0 }
/* 92 */ , { 0 , 0 }
/* 93 */ , { 0 , 0 }
/* 94 */ , { 0 , 0 }
/* 95 */ , { 0 , 0 }
/* 96 */ , { 0 , 0 }
/* 97 */ , { 0 , 0 }
/* 98 */ , { 0 , 0 }
/* 99 */ , { 0 , 0 }
/* 100 */ , { 0 , 0 }
/* 101 */ , { 0 , 0 }
/* 102 */ , { 0 , 0 }
/* 103 */ , { 0 , 0 }
/* 104 */ , { 0 , 0 }
/* 105 */ , { 0 , 0 }
/* 106 */ , { 0 , 0 }
/* 107 */ , { 0 , 0 }
#endif
/* 108 */ , { ERROR_DRIVE_LOCKED , EACCES }
/* 109 */ , { ERROR_BROKEN_PIPE , EPIPE }
#if 0
/* 110 */ , { 0 , 0 }
#endif
/* 111 */ , { ERROR_BUFFER_OVERFLOW , ENAMETOOLONG }
/* 112 */ , { ERROR_DISK_FULL , ENOSPC }
#if 0
/* 113 */ , { 0 , 0 }
#endif
/* 114 */ , { ERROR_INVALID_TARGET_HANDLE , EBADF }
#if 0
/* 115 */ , { 0 , 0 }
/* 116 */ , { 0 , 0 }
/* 117 */ , { 0 , 0 }
/* 118 */ , { 0 , 0 }
/* 119 */ , { 0 , 0 }
/* 120 */ , { 0 , 0 }
/* 121 */ , { 0 , 0 }
#endif
/* 122 */ , { ERROR_INSUFFICIENT_BUFFER , ERANGE }
/* 123 */ , { ERROR_INVALID_NAME , ENOENT }
/* 124 */ , { ERROR_INVALID_HANDLE , EINVAL }
#if 0
/* 125 */ , { 0 , 0 }
#endif
/* 126 */ , { ERROR_MOD_NOT_FOUND , ENOENT }
/* 127 */ , { ERROR_PROC_NOT_FOUND , ENOENT }
/* 128 */ , { ERROR_WAIT_NO_CHILDREN , ECHILD }
/* 129 */ , { ERROR_CHILD_NOT_COMPLETE , ECHILD }
/* 130 */ , { ERROR_DIRECT_ACCESS_HANDLE , EBADF }
/* 131 */ , { ERROR_NEGATIVE_SEEK , EINVAL }
/* 132 */ , { ERROR_SEEK_ON_DEVICE , EACCES }
#if 0
/* 133 */ , { 0 , 0 }
/* 134 */ , { 0 , 0 }
/* 135 */ , { 0 , 0 }
/* 136 */ , { 0 , 0 }
/* 137 */ , { 0 , 0 }
/* 138 */ , { 0 , 0 }
/* 139 */ , { 0 , 0 }
/* 140 */ , { 0 , 0 }
/* 141 */ , { 0 , 0 }
/* 142 */ , { 0 , 0 }
/* 143 */ , { 0 , 0 }
/* 144 */ , { 0 , 0 }
#endif
/* 145 */ , { ERROR_DIR_NOT_EMPTY , ENOTEMPTY }
#if 0
/* 146 */ , { 0 , 0 }
/* 147 */ , { 0 , 0 }
/* 148 */ , { 0 , 0 }
/* 149 */ , { 0 , 0 }
/* 150 */ , { 0 , 0 }
/* 151 */ , { 0 , 0 }
/* 152 */ , { 0 , 0 }
/* 153 */ , { 0 , 0 }
/* 154 */ , { 0 , 0 }
/* 155 */ , { 0 , 0 }
/* 156 */ , { 0 , 0 }
/* 157 */ , { 0 , 0 }
#endif
/* 158 */ , { ERROR_NOT_LOCKED , EACCES }
#if 0
/* 159 */ , { 0 , 0 }
/* 160 */ , { 0 , 0 }
#endif
/* 161 */ , { ERROR_BAD_PATHNAME , ENOENT }
#if 0
/* 162 */ , { 0 , 0 }
/* 163 */ , { 0 , 0 }
#endif
/* 164 */ , { ERROR_MAX_THRDS_REACHED , EAGAIN }
#if 0
/* 165 */ , { 0 , 0 }
/* 166 */ , { 0 , 0 }
#endif
/* 167 */ , { ERROR_LOCK_FAILED , EACCES }
#if 0
/* 168 */ , { 0 , 0 }
/* 169 */ , { 0 , 0 }
/* 170 */ , { 0 , 0 }
/* 171 */ , { 0 , 0 }
/* 172 */ , { 0 , 0 }
/* 173 */ , { 0 , 0 }
/* 174 */ , { 0 , 0 }
/* 175 */ , { 0 , 0 }
/* 176 */ , { 0 , 0 }
/* 177 */ , { 0 , 0 }
/* 178 */ , { 0 , 0 }
/* 179 */ , { 0 , 0 }
/* 180 */ , { 0 , 0 }
/* 181 */ , { 0 , 0 }
/* 182 */ , { 0 , 0 }
#endif
/* 183 */ , { ERROR_ALREADY_EXISTS , EEXIST }
#if 0
/* 184 */ , { 0 , 0 }
/* 185 */ , { 0 , 0 }
/* 186 */ , { 0 , 0 }
/* 187 */ , { 0 , 0 }
/* 188 */ , { 0 , 0 }
/* 189 */ , { 0 , 0 }
/* 190 */ , { 0 , 0 }
/* 191 */ , { 0 , 0 }
/* 192 */ , { 0 , 0 }
/* 193 */ , { 0 , 0 }
/* 194 */ , { 0 , 0 }
/* 195 */ , { 0 , 0 }
/* 196 */ , { 0 , 0 }
/* 197 */ , { 0 , 0 }
/* 198 */ , { 0 , 0 }
/* 199 */ , { 0 , 0 }
#endif
/* 206 */ , { ERROR_FILENAME_EXCED_RANGE , ENAMETOOLONG }
/* 215 */ , { ERROR_NESTING_NOT_ALLOWED , EAGAIN }
/* 258 */ , { WAIT_TIMEOUT, ETIME}
/* 267 */ , { ERROR_DIRECTORY , ENOTDIR }
/* 336 */ , { ERROR_DIRECTORY_NOT_SUPPORTED , EISDIR }
/* 996 */ , { ERROR_IO_INCOMPLETE , EAGAIN }
/* 997 */ , { ERROR_IO_PENDING , EAGAIN }
/* 1004 */ , { ERROR_INVALID_FLAGS , EINVAL }
/* 1113 */ , { ERROR_NO_UNICODE_TRANSLATION , EINVAL }
/* 1168 */ , { ERROR_NOT_FOUND , ENOENT }
/* 1224 */ , { ERROR_USER_MAPPED_FILE , EACCES }
/* 1314 */ , { ERROR_PRIVILEGE_NOT_HELD , EACCES }
/* 1816 */ , { ERROR_NOT_ENOUGH_QUOTA , ENOMEM }
, { ERROR_ABANDONED_WAIT_0 , EIO }
/* 1464 */ , { ERROR_SYMLINK_NOT_SUPPORTED , EINVAL }
/* 4390 */ , { ERROR_NOT_A_REPARSE_POINT , EINVAL }
};
for(i = 0; i < sizeof(errmap)/sizeof(struct code_to_errno_map); ++i)
{
if(w32Err == errmap[i].w32Err)
{
return errmap[i].eerrno;
}
}
assert(!"Unrecognised value");
return EINVAL;
}/*}}}*/
PHP_WINUTIL_API char *php_win32_get_username(void)
{/*{{{*/
wchar_t unamew[UNLEN + 1];
size_t uname_len;
char *uname;
DWORD unsize = UNLEN;
GetUserNameW(unamew, &unsize);
uname = php_win32_cp_conv_w_to_any(unamew, unsize - 1, &uname_len);
if (!uname) {
return NULL;
}
/* Ensure the length doesn't overflow. */
if (uname_len > UNLEN) {
uname[uname_len] = '\0';
}
return uname;
}/*}}}*/
static zend_always_inline BOOL is_compatible(HMODULE handle, BOOL is_smaller, char *format, char **err)
{/*{{{*/
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) handle;
PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((char *) dosHeader + dosHeader->e_lfanew);
DWORD major = pNTHeader->OptionalHeader.MajorLinkerVersion;
DWORD minor = pNTHeader->OptionalHeader.MinorLinkerVersion;
#if PHP_LINKER_MAJOR == 14
/* VS 2015, 2017, 2019 and 2022 are binary compatible, but only forward compatible.
It should be fine, if we load a module linked with an older one into
the core linked with the newer one, but not the otherway round.
Analogously, it should be fine, if a PHP build linked with an older version
is used with a newer CRT, but not the other way round.
Otherwise, if the linker major version is not same, it is an error, as
per the current knowledge.
This check is to be extended as new VS versions come out. */
DWORD core_minor = (DWORD)(PHP_LINKER_MINOR/10);
DWORD comp_minor = (DWORD)(minor/10);
if (14 == major && (is_smaller ? core_minor < comp_minor : core_minor > comp_minor) || PHP_LINKER_MAJOR != major)
#else
if (PHP_LINKER_MAJOR != major)
#endif
{
char buf[MAX_PATH];
if (GetModuleFileName(handle, buf, sizeof(buf)) != 0) {
spprintf(err, 0, format, buf, major, minor, PHP_LINKER_MAJOR, PHP_LINKER_MINOR);
} else {
spprintf(err, 0, "Can't retrieve the module name (error %u)", GetLastError());
}
return FALSE;
}
return TRUE;
}/*}}}*/
PHP_WINUTIL_API BOOL php_win32_image_compatible(HMODULE handle, char **err)
{/*{{{*/
return is_compatible(handle, TRUE, "Can't load module '%s' as it's linked with %u.%u, but the core is linked with %d.%d", err);
}/*}}}*/
/* Expect a CRT module handle */
PHP_WINUTIL_API BOOL php_win32_crt_compatible(char **err)
{/*{{{*/
#if PHP_LINKER_MAJOR == 14
/* Extend for other CRT if needed. */
# if PHP_DEBUG
const char *crt_name = "vcruntime140d.dll";
# else
const char *crt_name = "vcruntime140.dll";
# endif
HMODULE handle = GetModuleHandle(crt_name);
if (handle == NULL) {
spprintf(err, 0, "Can't get handle of module %s (error %u)", crt_name, GetLastError());
return FALSE;
}
return is_compatible(handle, FALSE, "'%s' %u.%u is not compatible with this PHP build linked with %d.%d", err);
#endif
return TRUE;
}/*}}}*/
| 24,621 | 47.950298 | 128 |
c
|
php-src
|
php-src-master/win32/winutil.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: |
+----------------------------------------------------------------------+
*/
#ifndef PHP_WIN32_WINUTIL_H
#define PHP_WIN32_WINUTIL_H
#ifdef PHP_EXPORTS
# define PHP_WINUTIL_API __declspec(dllexport)
#else
# define PHP_WINUTIL_API __declspec(dllimport)
#endif
PHP_WINUTIL_API char *php_win32_error_to_msg(HRESULT error);
PHP_WINUTIL_API void php_win32_error_msg_free(char *msg);
#define php_win_err() php_win32_error_to_msg(GetLastError())
#define php_win_err_free(err) php_win32_error_msg_free(err)
int php_win32_check_trailing_space(const char * path, const size_t path_len);
PHP_WINUTIL_API int php_win32_get_random_bytes(unsigned char *buf, size_t size);
#ifdef PHP_EXPORTS
BOOL php_win32_init_random_bytes(void);
BOOL php_win32_shutdown_random_bytes(void);
#endif
#if !defined(ECURDIR)
# define ECURDIR EACCES
#endif /* !ECURDIR */
#if !defined(ENOSYS)
# define ENOSYS EPERM
#endif /* !ENOSYS */
PHP_WINUTIL_API int php_win32_code_to_errno(unsigned long w32Err);
#define SET_ERRNO_FROM_WIN32_CODE(err) \
do { \
int ern = php_win32_code_to_errno(err); \
SetLastError(err); \
_set_errno(ern); \
} while (0)
PHP_WINUTIL_API char *php_win32_get_username(void);
PHP_WINUTIL_API BOOL php_win32_image_compatible(HMODULE handle, char **err);
PHP_WINUTIL_API BOOL php_win32_crt_compatible(char **err);
#endif
| 2,252 | 36.55 | 80 |
h
|
php-src
|
php-src-master/win32/wsyslog.c
|
/*
* This file modified from sources for imap4 for use
* in PHP 3
*/
/*
* Program: Unix compatibility routines
*
* Author: Mark Crispin
* Networks and Distributed Computing
* Computing & Communications
* University of Washington
* Administration Building, AG-44
* Seattle, WA 98195
* Internet: [email protected]
*
* Date: 14 September 1996
* Last Edited: 22 October 1996
*
* Copyright 1996 by the University of Washington
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appears in all copies and that both the
* above copyright notice and this permission notice appear in supporting
* documentation, and that the name of the University of Washington not be
* used in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. This software is made available
* "as is", and
* THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
* WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
* NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/* DEDICATION
* This file is dedicated to my dog, Unix, also known as Yun-chan and
* Unix J. Terwilliker Jehosophat Aloysius Monstrosity Animal Beast. Unix
* passed away at the age of 11 1/2 on September 14, 1996, 12:18 PM PDT, after
* a two-month bout with cirrhosis of the liver.
*
* He was a dear friend, and I miss him terribly.
*
* Lift a leg, Yunie. Luv ya forever!!!!
*/
#include "php.h" /*php specific */
#include "syslog.h"
#include <stdio.h>
#include <fcntl.h>
#include <process.h>
#include "php_win32_globals.h"
#include "wsyslog.h"
#include "codepage.h"
void closelog(void)
{
if (INVALID_HANDLE_VALUE != PW32G(log_source)) {
DeregisterEventSource(PW32G(log_source));
PW32G(log_source) = INVALID_HANDLE_VALUE;
}
if (PW32G(log_header)) {
free(PW32G(log_header));
PW32G(log_header) = NULL;
}
}
/* Emulator for BSD syslog() routine
* Accepts: priority
* message
* parameters
*/
void syslog(int priority, const char *message, ...)
{
va_list args;
va_start(args, message); /* initialize vararg mechanism */
vsyslog(priority, message, args);
va_end(args);
}
void vsyslog(int priority, const char *message, va_list args)
{
LPTSTR strs[2];
unsigned short etype;
char *tmp = NULL;
DWORD evid;
wchar_t *strsw[2];
/* default event source */
if (INVALID_HANDLE_VALUE == PW32G(log_source))
openlog("php", LOG_PID, LOG_SYSLOG);
switch (priority) { /* translate UNIX type into NT type */
case LOG_ALERT:
etype = EVENTLOG_ERROR_TYPE;
evid = PHP_SYSLOG_ERROR_TYPE;
break;
case LOG_INFO:
etype = EVENTLOG_INFORMATION_TYPE;
evid = PHP_SYSLOG_INFO_TYPE;
break;
default:
etype = EVENTLOG_WARNING_TYPE;
evid = PHP_SYSLOG_WARNING_TYPE;
}
vspprintf(&tmp, 0, message, args); /* build message */
strsw[0] = php_win32_cp_any_to_w(PW32G(log_header));
strsw[1] = php_win32_cp_any_to_w(tmp);
/* report the event */
if (strsw[0] && strsw[1]) {
ReportEventW(PW32G(log_source), etype, (unsigned short) priority, evid, NULL, 2, 0, strsw, NULL);
free(strsw[0]);
free(strsw[1]);
efree(tmp);
return;
}
free(strsw[0]);
free(strsw[1]);
strs[0] = PW32G(log_header); /* write header */
strs[1] = tmp; /* then the message */
ReportEventA(PW32G(log_source), etype, (unsigned short) priority, evid, NULL, 2, 0, strs, NULL);
efree(tmp);
}
/* Emulator for BSD openlog() routine
* Accepts: identity
* options
* facility
*/
void openlog(const char *ident, int logopt, int facility)
{
size_t header_len;
closelog();
PW32G(log_source) = RegisterEventSource(NULL, "PHP-" PHP_VERSION);
header_len = strlen(ident) + 2 + 11;
PW32G(log_header) = malloc(header_len*sizeof(char));
sprintf_s(PW32G(log_header), header_len, (logopt & LOG_PID) ? "%s[%d]" : "%s", ident, getpid());
}
| 4,427 | 27.203822 | 99 |
c
|
php-src
|
php-src-master/win32/build/deplister.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 little application will list the DLL dependencies for a PE
* module to it's stdout for use by distro/installer building tools */
#include <windows.h>
#include <stdio.h>
#include <imagehlp.h>
BOOL CALLBACK StatusRoutine(IMAGEHLP_STATUS_REASON reason,
PCSTR image_name, PCSTR dll_name,
ULONG_PTR va, ULONG_PTR param)
{
switch (reason) {
case BindImportModuleFailed:
printf("%s,NOTFOUND\n", dll_name);
return TRUE;
case BindImportModule:
printf("%s,OK\n", dll_name);
return TRUE;
}
return TRUE;
}
/* usage:
* deplister.exe path\to\module.exe path\to\symbols\root
* */
int main(int argc, char *argv[])
{
return BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
argv[1], NULL, argv[2], StatusRoutine);
}
| 1,743 | 34.591837 | 77 |
c
|
3DDFA
|
3DDFA-master/c++/face_reconstruction.h
|
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/core/types_c.h>
#include <opencv2/opencv.hpp>
#include <opencv2/dnn/dnn.hpp>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <chrono>
#include "matrix.h"
class FaceReconstruction {
private:
cv::Mat blob;
std::vector<cv::Mat> out;
cv::dnn::Net predictor;
Matrix param_mean = Matrix(62, 1);
Matrix param_std = Matrix(62, 1);
Matrix u_base = Matrix(204, 1);
Matrix w_exp_base = Matrix(204, 40);
Matrix w_shp_base = Matrix(204, 10);
Matrix p = Matrix(3, 3);
Matrix offset = Matrix(3, 68);
Matrix alpha_shp = Matrix(40, 1);
Matrix alpha_exp = Matrix(10, 1);
int STD_SIZE = 120;
public:
FaceReconstruction(std::string s);
std::vector<cv::Point2f> extract_landmarks(cv::Mat& img_crop, cv::Rect& rect, bool benchmark_flg);
void parseParam(void);
};
| 913 | 26.69697 | 102 |
h
|
3DDFA
|
3DDFA-master/c++/yolo.h
|
#pragma once
#include <opencv2/core/types_c.h>
#include <opencv2/opencv.hpp>
#include <opencv2/dnn/dnn.hpp>
#include <iostream>
#include <cmath>
using namespace std;
using namespace cv;
using namespace dnn;
namespace yolo {
class faceDetection {
private:
Point classIdPoint;
Mat blob;
vector<Mat> out;
dnn::Net net;
Ptr<dnn::Layer> lastLayer;
vector<string> names;
vector<string> lnames;
public:
explicit faceDetection(const string modelWeights = "weights/tiny-yolo-azface-fddb_82000.weights",
const string modelConf = "weights/tiny-yolo-azface-fddb.cfg");
void InitInput(cv::Mat &img);
vector<cv::Rect> detectFace(int w, int h);
void clear();
};
}
| 789 | 22.939394 | 105 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/lklbs.h
|
/*
* lklbs.h
* lowly_project
*
* Created by Karim Benabed on 24/04/09.
* Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#include "pmc.h"
#ifndef __LKLBS__
#define __LKLBS__
#define TT_off 0
#define EE_off 1
#define BB_off 2
#define TE_off 3
#define TB_off 4
#define EB_off 5
#define _extra_size 256
typedef char extraname[_extra_size];
// definitions
typedef void compute_cl_func(void*, double*, double*, error **);
typedef struct {
void *lkl_data;
posterior_log_pdf_func* lkl_func;
posterior_log_free *lkl_free;
int lmax[6];
int mlmax;
int xdim,ndim;
double *pars;
} cmblkl_select;
typedef struct {
void *lkl_data;
posterior_log_pdf_func* lkl_func;
posterior_log_free *lkl_free;
int nell,ndim,nbins,xdim;
int* ell;
int offset_cl[6];
double *wl;
double *bins,*pls;
double unit;
extraname *xnames;
} cmblkl;
typedef struct {
int ndim;
void* bs;
compute_cl_func* bs_compute;
posterior_log_free* bs_free;
extraname *xnames;
} bs_struct;
typedef struct {
cmblkl **lkls;
int nlkl;
bs_struct* rbs;
double *cl_theo,*cl_select;
int offset_lmax[6];
int *ell,*ofx,*rx;
int nell,ndim,tot_cl,nrx,xdim;
extraname *xnames;
} lklbs;
//lklbs funcs
distribution* init_fulllklbs_distribution(cmblkl** lkls,int nlkl,
bs_struct* rbs,
int *lmax, error **err);
lklbs* init_fulllklbs(cmblkl** lkls,int nlkl,
bs_struct* rbs,
int *lmax, error **err);
void free_lklbs(void **pelf);
double lklbs_lkl(void* pelf, double* pars, error **err);
// bs support
bs_struct *init_bs_struct(int ndim, void* bs, compute_cl_func* bs_compute, posterior_log_free* bs_free, char **_xnames, error **err);
void free_bs_struct(void **prbs);
//cmblkl support
cmblkl *init_cmblkl_select(void* lkl_data, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
int *lmax,
int xdim, error **err);
double select_func(void* dt, double *pars,error **err);
void select_free(void** dt);
cmblkl *init_cmblkl(void* lkl_data, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
int nell,int* ell,int* has_cl,int lmax,double unit,double *wl,int wlselect,
double *bins,int nbins, int xdim,error **err);
void free_cmblkl(void **self);
void cmblkl_check_lmax(cmblkl *lkl,int *lmax,error **err);
double* cmblkl_select_cls(cmblkl *llkl,lklbs* self);
void cmblkl_max_lmax(cmblkl *lkl,int *lmax, error **err);
void cmblkl_set_names(cmblkl *lkl, char **names, error **err);
void cmblkl_check_xnames(cmblkl *self,int ii,error **err);
// support and deprecated
int lklbs_get_par_id(lklbs* self,extraname name, error **err);
lklbs* init_lklbs(void* lkl, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free, int ndim,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int nell, int* ell, int *lmax,error **err);
lklbs* init_multilklbs(cmblkl** lkls,int nlkl,int ndim,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int *lmax, error **err);
distribution* init_lklbs_distribution(int ndim,void* lkl, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int nell, int* ell, int *lmax,error **err);
distribution* init_multilklbs_distribution(int ndim,cmblkl** lkls,int nlkl,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int *lmax, error **err);
// minimal bs
typedef struct {
int ndim;
int lmax[6];
} zero_bs;
zero_bs* init_zero_bs(int *lmax, error **err);
void zero_bs_compute(void* zbs, double* prs, double* cls, error **err);
void free_zero_bs(void **pzbs);
/*typedef beamfunc(void* data, double* bdata, double* cls, double *bcls, error **);
typedef struct {
int ndim;
int xdim;
cmblkl target;
double *lars;
void *data;
beamfunc *bfunc;
posterior_log_free *bfree;
} beamed;
*/
#define lklbs_base -49000
#define lklbs_zero -1 + lklbs_base
#define lklbs_incompatible_lmax -2 + lklbs_base
#define clowly_base -9000
#define lowly_chol -1 + clowly_base
#define lowly_unkorder -4 + clowly_base
#define lowly_lbig -12 + clowly_base
#endif
| 4,888 | 27.424419 | 133 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/wlik.c
|
/*
* wlik.c
* lowly_project
*
* Created by Karim Benabed on 16/03/11.
* Copyright 2011 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#include "wlik.h"
// ARE YOU STILL READING ?
// YOU HAVE BEEN WARNED !
#include <errno.h>
#include <string.h>
typedef struct {
char tmpdir[800];
} wmap;
void free_wmap(void **none) {
wmap_extra_free_();
}
double wmap_lkl(void* none, double* pars, error **err) {
double lkl;
wmap_extra_lkl_(&lkl,pars);
return lkl;
}
cmblkl* wlik_wmap_init(char *dirname, int ttmin, int ttmax, int temin, int temax, int use_gibbs, int use_lowl_pol, error **err) {
int bok;
cmblkl *cing,*target;
int mlmax;
char pwd[5000];
int has_cl[6],lmaxs[6];
int *ell;
int lmax,l,n_cl,cli;
zero_bs* zbs;
//only one wmap
wmap_extra_only_one_(&bok);
testErrorRet(bok!=0,-100,"wmap already initialized",*err,__LINE__,NULL);
//change dir
testErrorRetVA(getcwd(pwd,4096)==NULL,-101010,"can't get cwd name (cause = '%s')",*err,__LINE__,NULL,strerror(errno));
testErrorRetVA(chdir(dirname)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,dirname,strerror(errno));
// call wmap_init
wmap_extra_parameter_init_(&ttmin,&ttmax,&temin,&temax,&use_gibbs,&use_lowl_pol);
//change dir back
testErrorRetVA(chdir(pwd)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,pwd,strerror(errno));
lmax = ttmax;
if (temax>ttmax) {
lmax = temax;
}
has_cl[0]=0;
has_cl[1]=0;
has_cl[2]=0;
has_cl[3]=0;
has_cl[4]=0;
has_cl[5]=0;
lmaxs[0]=-1;
lmaxs[1]=-1;
lmaxs[2]=-1;
lmaxs[3]=-1;
lmaxs[4]=-1;
lmaxs[5]=-1;
if (ttmin<=ttmax && ttmax>0) {
has_cl[0]=1;
}
if (temin<=temax && temax>0) {
has_cl[1]=1;
has_cl[2]=1;
has_cl[3]=1;
}
ell = malloc_err(sizeof(double)*(lmax+1),err);
forwardError(*err,__LINE__,NULL);
for(l=0;l<=lmax;l++) {
ell[l] = l;
}
cing = init_cmblkl(NULL, &wmap_lkl,
&free_wmap,
lmax+1,ell,
has_cl,lmax,1,NULL,0,NULL,0,0,err);
forwardError(*err,__LINE__,NULL);
n_cl = 0;
for(cli=0;cli<6;cli++) {
n_cl += (lmax+1)*has_cl[cli];
}
cmblkl_max_lmax(cing,lmaxs,err);
forwardError(*err,__LINE__,NULL);
zbs = init_zero_bs(lmaxs, err);
forwardError(*err,__LINE__,NULL);
target = init_multilklbs_distribution(n_cl , &cing,1,
zbs, &zero_bs_compute, &free_zero_bs, lmaxs, err);
forwardError(*err,__LINE__,NULL);
free(ell);
return target;
}
void wlik_get_has_cl(wlik_object *wlikid, int has_cl[6],error **_err) {
distribution *target;
lklbs *lbs;
int cli;
_dealwitherr;
lbs = _wlik_dig(wlikid,err);
_forwardError(*err,__LINE__,);
for(cli=0;cli<6;cli++) {
//fprintf(stderr," %d %d ",cli,lbs->offset_lmax[cli]);
if (lbs->offset_lmax[cli]!=-1) {
has_cl[cli]=1;
} else {
has_cl[cli]=0;
}
}
}
void wlik_get_lmax(wlik_object *wlikid, int lmax[6],error **_err) {
distribution *target;
lklbs *lbs;
zero_bs* zbs;
int cli;
_dealwitherr;
lbs = _wlik_dig(wlikid,err);
_forwardError(*err,__LINE__,);
zbs = lbs->rbs->bs;
for(cli=0;cli<6;cli++) {
lmax[cli] = zbs->lmax[cli];
}
}
void wlik_cleanup(wlik_object** pwlikid) {
free_distribution(pwlikid);
}
double wlik_compute(wlik_object* wlikid, double* cl_and_pars,error **_err) {
double res;
_dealwitherr;
res = distribution_lkl(wlikid, cl_and_pars,err);
_forwardError(*err,__LINE__,-1);
return res;
}
void* _wlik_dig(wlik_object* wlikid, error **err) {
distribution *target;
target = wlikid;
if (target->log_pdf == &combine_lkl) {
// return the first wlik likelihood
int i;
comb_dist_data* cbd;
cbd = target->data;
for (i=0;i<cbd->ndist;i++) {
if (cbd->dist[i]->log_pdf == &lklbs_lkl) {
return cbd->dist[i]->data;
}
}
}
if (target->log_pdf==&lklbs_lkl) {
return target->data;
}
testErrorRet(1==1,-111,"No wlik likelihood found",*err,__LINE__,NULL);
}
| 4,079 | 20.935484 | 129 |
c
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/minipmc/errorlist.h
|
/*
* errorlist.h
* likeli
*
* Created by Karim Benabed on 06/02/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef __ERRORLIST_H
#define __ERRORLIST_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#define TXT_SZ 4192
#define WHR_SZ 2048
#define TOT_SZ TXT_SZ+WHR_SZ
typedef struct _err {
char errWhere[WHR_SZ];
char errText[TXT_SZ];
int errValue;
struct _err* next;
} error;
typedef error sm2_error;
#define forwardErr -123456789
#define undefErr -987654321
#define noErr 0
#define placeHolderError 1020304050
#define el_alloc -42
error* newError(int errV, char* where, char* text, error* linkTo, error* addErr);
error* newErrorVA(int errV, const char* func,char* where, char* text, error* linkTo, error* addErr,...);
void stringError(char* str, error *err);
void printError(FILE* flog,error* err);
int getErrorValue(error* err);
void purgeError(error **err);
error* unpickleError(void* buf, int len);
int pickleError(error* err, void** buf);
error* initError(void);
void endError(error **err);
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define __func__ __FUNCTION__
# else
# define __func__ "<unknown>"
# endif
#endif
#define _DEBUGHERE_(extra,...) fprintf(stderr,"%s:("__FILE__":%d) "extra"\n",__func__,__LINE__,__VA_ARGS__);
#define someErrorVA(errV,txt,prev,next,li,...) newErrorVA(errV,__func__,"("__FILE__":"#li")",txt,prev,next,__VA_ARGS__)
#define topErrorVA(errV,txt,next,li,...) someErrorVA(errV,txt,NULL,next,li,__VA_ARGS__)
#define oneErrorVA(errV,txt,li,...) someErrorVA(errV,txt,NULL,NULL,li,__VA_ARGS__)
#define addErrorVA(errV,txt,prev,li,...) someErrorVA(errV,txt,prev,NULL,li,__VA_ARGS__)
#define someError(errV,txt,prev,next,li) someErrorVA(errV,txt,prev,next,li,"")
#define topError(errV,txt,next,li) topErrorVA(errV,txt,next,li,"")
#define oneError(errV,txt,li) oneErrorVA(errV,txt,li,"")
#define addError(errV,txt,prev,li) addErrorVA(errV,txt,prev,li,"")
// isError
#define isError(err) (_isError(err))
#define isErrorReturn(err,ret) { \
if (isError(err)) { \
return ret; \
} \
}
#define isErrorExit(err,F) { \
if (isError(err)) { \
printError(F,err); \
exit(getErrorValue(err)); \
} \
}
// forwards
#define forwardErrorNoReturn(err,line) { \
if (isError(err)) { \
err=topError(forwardErr,"",err,line); \
} \
}
#define forwardError(err,line,ret) { \
forwardErrorNoReturn(err,line); \
isErrorReturn(err,ret) \
}
// tests
#define testErrorVA(test,error_type,message,err,line,...) { \
if (test) { \
err=addErrorVA(error_type,message,err,line,__VA_ARGS__); \
} \
}
#define testErrorRetVA(test,error_type,message,err,line,return_value,...) { \
testErrorVA(test,error_type,message,err,line,__VA_ARGS__); \
isErrorReturn(err,return_value); \
}
#define testErrorExitVA(test,error_type,message,err,line,...) { \
testErrorVA(test,error_type,message,err,line,__VA_ARGS__); \
isErrorExit(err,stderr); \
}
#define testError(test,error_type,message,err,line) testErrorVA(test,error_type,message,err,line,"")
#define testErrorRet(test,error_type,message,err,line,return_value) testErrorRetVA(test,error_type,message,err,line,return_value,"")
#define testErrorExit(test,error_type,message,err,line) testErrorExitVA(test,error_type,message,err,line,"")
// exit and co
#define exitOnError(err,F) isErrorExit(err,F)
#define quitOnError(err,line,F) { \
forwardErrorNoReturn(err,line); \
isErrorExit(err,F); \
}
#define quitOnErrorStr(err,line,F,str) { \
forwardErrorNoReturn(err,line); \
if (isError(err)) { \
printError(F,err); \
fprintf(F, "%s\n", str); \
exit(getErrorValue(err)); \
} \
}
#define err_base -100
#define err_io -1 + err_base
#define err_allocate -2 + err_base
error* initError(void);
void endError(error **err);
int _isError(error *err);
#endif
| 4,651 | 29.807947 | 132 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/minipmc/io.c
|
/* ============================================================ *
* io.c *
* Martin Kilbinger, Karim Benabed *
* ============================================================ */
/* simplified version from pmclib*/
#include "io.h"
/* ============================================================ *
* I/O and memory tools. *
* ============================================================ */
FILE* fopen_err(const char* fname, const char *mode, error **err)
{
FILE* fp;
fp = fopen(fname, mode);
testErrorRetVA(fp==NULL, err_io, "Cannot open file '%s' (mode \"%s\")", *err,__LINE__,NULL,fname, mode);
return fp;
}
void* malloc_err(size_t sz, error **err)
{
void* res;
testErrorRetVA(sz<=0,err_allocate,"Size %ld has to be positive",*err,__LINE__,NULL,sz);
res = malloc(sz);
testErrorRetVA(res==NULL,err_allocate,"Cannot allocate %ld bytes",*err,__LINE__,NULL,sz);
return res;
}
void* calloc_err(size_t nl, size_t sz1, error **err)
{
void* res;
testErrorRetVA(nl<=0,err_allocate,"Size %ld has to be positive",*err,__LINE__,NULL,nl);
res = calloc(nl,sz1);
testErrorRetVA(res==NULL,err_allocate,"Cannot allocate %d objects of %d bytes (=%d total)",
*err,__LINE__,NULL,nl,sz1,nl*sz1);
return res;
}
void *realloc_err(void *ptr, size_t sz, error **err)
{
void *res;
res = realloc(ptr, sz);
testErrorVA(ptr==NULL, err_allocate, "Cannot reallocate %zu bytes", *err, __LINE__, NULL, sz);
testErrorVA(res==NULL, err_allocate, "Cannot reallocate %zu bytes", *err, __LINE__, NULL, sz);
return NULL;
}
/* Returns a pointer with content orig, resized from sz_orig to sz_new. If *
* free_orig=1, the original memory is freed.
* orig can be NULL or sz_orig can be 0, in that case, just allocate sz_new and returns
*/
void* resize_err(void* orig, size_t sz_orig, size_t sz_new, int free_orig, error **err)
{
void* res;
size_t minsz,o_size;
res = malloc_err(sz_new,err);
forwardError(*err,__LINE__,NULL);
if (orig == NULL || sz_orig==0) {
return res;
}
o_size = sz_orig;
minsz = o_size;
if (o_size > sz_new) {
minsz = sz_new;
}
memcpy(res,orig,minsz);
if(free_orig == 1) {
free(orig);
}
return res;
}
size_t read_line(FILE* fp, char* buff, int bmax, error **err) {
size_t i;
char cur;
int dsc;
i=0;
dsc=0;
while (i<bmax-1) {
cur=(char)fgetc(fp);
if (feof(fp) || cur=='\n') {
buff[i]='\0';
//fprintf(stderr,"Read |%s|\n",buff);
return i+1;
}
if (dsc==1) {
continue;
}
if (cur=='#' || cur=='!' || cur==';') {
dsc=1;
continue;
}
buff[i]=cur;
i++;
}
*err = addErrorVA(err_io,"One line of file is longer than the max size (%d)",*err,__LINE__,bmax);
return -1;
}
void* read_any_vector(const char* fnm, size_t n, char *prs, size_t sz, error **err) {
size_t nn;
char* res;
nn=n;
res = read_any_list(fnm, &nn, prs, sz, err);
forwardError(*err,__LINE__,NULL);
return res;
}
//#define _stp_ 4096
#define _stp_ 524288
void* read_any_list(const char* fnm, size_t *n, char *prs, size_t sz, error **err)
{
void *res;
size_t nlines;
res = read_any_list_count(fnm, n, prs, sz, &nlines, err);
forwardError(*err, __LINE__, NULL);
return res;
}
/* ============================================================ *
* Read white-spaced separated records of format prs and size *
* sz from the file fnm. The number of records is set in n on *
* output. On input, n should be set to zero, or ask Karim what *
* happens if not. Returns record as void pointer. *
* The number of lines is set in nlines on output. *
* Comment and empty lines are ignored. *
* ============================================================ */
void* read_any_list_count(const char* fnm, size_t *n, char *prs, size_t sz,
size_t *nlines, error **err)
{
FILE *fp;
size_t i,cz,j,j0,ibefore;
char *res;
char buffer[_stp_];
int clip;
if (*n>0) {
clip=1;
} else {
clip=0;
*n=_stp_;
}
res = (void*) malloc_err((*n)*sz,err);
forwardError(*err,__LINE__,NULL);
fp=fopen_err(fnm,"r",err);
forwardError(*err,__LINE__,NULL);
i=0;
*nlines = 0;
while(feof(fp)==0) {
cz=read_line(fp,buffer,_stp_,err);
testErrorRetVA(isError(*err),err_io,"Reading file '%s'",*err,__LINE__,NULL,fnm);
j=0;
//fprintf(stderr,"A %d %s\n",sz,prs);
ibefore = i;
while (j<cz) {
//fprintf(stderr,"%d %c\n",j,buffer[j]);
//look for first non blanc char
while(j<cz && isspace(buffer[j]) && buffer[j]!='\0') {
//fprintf(stderr,"%d %c\n",j,buffer[j]);
j++;
}
if (j==cz || buffer[j]=='\0') //blank line
break;
// find next blanck char
j0=j;
while(j<cz && !isspace(buffer[j]) && buffer[j]!='\0')
j++;
buffer[j]='\0';
j++;
//fprintf(stderr,"segment |%s|\n",&(buffer[j0]));
// read value between the two limits
testErrorRetVA(sscanf(buffer+j0,prs,res +i*sz)!=1,err_io,"Cannot read file '%s' at index %d",
*err,__LINE__,NULL,fnm,i)
//fprintf(stderr,prs,*(double*)(res +i*sz));
//fprintf(stderr,"\n");
i++;
if (i==*n) {
if (clip==1)
break;
res = resize_err(res,(*n)*sz,(*n)*2*sz,1,err);
forwardError(*err,__LINE__,NULL);
(*n) = (*n)*2;
}
}
/* NEW (MK) */
if (i>ibefore) {
/* A valid line was found: increase line count */
(*nlines) ++;
}
if (i==*n) {
if (clip==1)
break;
res = resize_err(res,(*n)*sz,(*n)*2*sz,1,err);
forwardError(*err,__LINE__,NULL);
(*n) = (*n)*2;
}
}
fclose(fp);
if (clip==1)
testErrorRetVA(i!=*n,err_io,"Not enough data in file '%s' (got %d entries, expected %d)\n",
*err,__LINE__,NULL,fnm,i,*n);
res = resize_err(res,(*n)*sz,i*sz,1,err);
forwardError(*err,__LINE__,NULL);
*n=i;
return res;
}
#undef _stp_
double* read_double_vector(const char* fnm, size_t n, error **err) {
double *res;
res = read_any_vector(fnm, n, "%lg", sizeof(double), err);
forwardError(*err,__LINE__,NULL);
return res;
}
double* read_double_list(const char* fnm, size_t *n, error **err) {
double *res;
res = read_any_list(fnm, n, "%lg", sizeof(double), err);
forwardError(*err,__LINE__,NULL);
return res;
}
float* read_float_vector(const char* fnm, size_t n, error **err) {
float *res;
res = read_any_vector(fnm, n, "%g", sizeof(float), err);
forwardError(*err,__LINE__,NULL);
return res;
}
float* read_float_list(const char* fnm,size_t *n, error **err) {
float *res;
res = read_any_list(fnm, n, "%g",sizeof(float),err);
forwardError(*err,__LINE__,NULL);
return res;
}
int* read_int_vector(const char* fnm,size_t n, error **err) {
int *res;
res = read_any_vector(fnm, n, "%d",sizeof(int),err);
forwardError(*err,__LINE__,NULL);
return res;
}
int* read_int_list(const char* fnm, size_t *n, error **err) {
int *res;
res = read_any_list(fnm, n, "%d",sizeof(int),err);
forwardError(*err,__LINE__,NULL);
return res;
}
long* read_long_vector(const char* fnm, size_t n, error **err) {
long *res;
res = read_any_vector(fnm, n, "%ld",sizeof(long),err);
forwardError(*err,__LINE__,NULL);
return res;
}
long* read_long_list(const char* fnm, size_t *n, error **err) {
long *res;
res = read_any_list(fnm, n, "%ld",sizeof(long),err);
forwardError(*err,__LINE__,NULL);
return res;
}
void* read_bin_vector(const char* fnm, size_t n, error **err) {
void *res;
FILE* ff;
size_t rr;
ff = fopen_err(fnm, "r", err);
forwardError(*err,__LINE__,NULL);
res = malloc_err(n,err);
forwardError(*err,__LINE__,NULL);
rr=fread(res, 1, n, ff);
testErrorRetVA(rr!=n,io_file,"File '%s' does not contain enough data (Expected %d bytes, got %d)",*err,__LINE__,NULL,fnm,n,rr);
fclose(ff);
return res;
}
void* read_bin_list(const char* fnm, size_t *n, error **err) {
void *res;
FILE* ff;
size_t rr;
struct stat stst;
testErrorRetVA(stat(fnm,&stst)!=0,io_file,"File '%s' cannot be stated",*err,__LINE__,NULL,fnm);
*n = stst.st_size;
ff = fopen_err(fnm, "r", err);
forwardError(*err,__LINE__,NULL);
res = malloc_err(*n,err);
forwardError(*err,__LINE__,NULL);
rr=fread(res, 1, *n, ff);
testErrorRetVA(rr!=*n,io_file,
"File '%s' does not contain enough data (Expected %d bytes, got %d)",
*err,__LINE__,NULL,fnm,*n,rr);
fclose(ff);
return res;
}
void write_bin_vector(void* buf, const char* fnm, size_t n, error **err) {
FILE* ff;
size_t rr;
ff = fopen_err(fnm, "w", err);
forwardError(*err,__LINE__,);
rr=fwrite(buf, 1, n, ff);
testErrorRetVA(rr!=n,io_file,
"Cannot write data in file '%s' (Expected %d bytes, got %d)",
*err,__LINE__,,fnm,n,rr);
fclose(ff);
fprintf(stderr,"Saved in %s\n", fnm);
}
time_t start_time(FILE *FOUT)
{
time_t t_start;
time(&t_start);
fprintf(FOUT, "Started at %s\n", ctime(&t_start));
fflush(FOUT);
return t_start;
}
void end_time(time_t t_start, FILE *FOUT)
{
time_t t_end;
double diff;
time(&t_end);
fprintf(FOUT, "Ended at %s", ctime(&t_end));
diff = difftime(t_end, t_start);
fprintf(FOUT, "Computation time %.0fs (= %dd %dh %dm %ds)\n",
diff, (int)diff/86400, ((int)diff%86400)/3600,
((int)diff%3600)/60, ((int)diff%60));
}
| 9,452 | 25.185596 | 129 |
c
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/minipmc/io.h
|
/* ============================================================ *
* io.h *
* Martin Kilbinger, Karim Benabed 2008 *
* ============================================================ */
#ifndef __IO_H
#define __IO_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __PLANCK__
#include "HL2_likely/tools/errorlist.h"
#else
#include "errorlist.h"
#endif
#define io_base -200
#define io_alloc -1 + io_base
#define io_file -2 + io_base
#define io_eof -3 + io_base
#define io_null -4 + io_base
#define io_inconsistent -5 + io_base
unsigned int numberoflines(const char *, error **err);
unsigned int numberoflines_comments(const char *name, unsigned int *ncomment, error **err);
/* The following three functions are used to read in the SNLS supernovae data */
int read_double(char** p, double *x);
int read_int(char** p, int *x);
double *readASCII(char *filename, int *fnx, int *fny, sm2_error **err);
FILE* fopen_err(const char* fname, const char *mode, error **err);
void* malloc_err(size_t sz, error **err);
void* calloc_err(size_t nl,size_t sz1, error **err);
void *realloc_err(void *ptr, size_t sz, error **err);
void* resize_err(void* orig, size_t sz_orig, size_t sz_new, int free_orig, error **err);
size_t read_line(FILE* fp, char* buff,int bmax, error **err);
void* read_any_vector(const char* fnm, size_t n, char *prs, size_t sz, error **err);
void* read_any_list(const char* fnm,size_t *n, char *prs, size_t sz, error **err);
void* read_any_list_count(const char* fnm, size_t *n, char *prs, size_t sz,
size_t *nlines, error **err);
double* read_double_vector(const char* fnm, size_t n, error **err);
double* read_double_list(const char* fnm, size_t *n, error **err);
int* read_int_vector(const char* fnm, size_t n, error **err);
int* read_int_list(const char* fnm, size_t *n, error **err);
float* read_float_vector(const char* fnm, size_t n, error **err);
float* read_float_list(const char* fnm, size_t *n, error **err);
long* read_long_vector(const char* fnm, size_t n, error **err);
long* read_long_list(const char* fnm,size_t *n, error **err);
void write_bin_vector(void* buf, const char* fnm, size_t n, error **err);
void* read_bin_vector(const char* fnm, size_t n, error **err);
void* read_bin_list(const char* fnm, size_t *n, error **err);
void chomp(char *x);
/* ============================================================ *
* To calculate the program run time. *
* ============================================================ */
time_t start_time(FILE *FOUT);
void end_time(time_t t_start, FILE *FOUT);
#endif
| 2,689 | 35.849315 | 91 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/minipmc/maths_base.h
|
/*
* maths_base.h
* ecosstat_project
*
* Created by Karim Benabed on 23/06/09.
* Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#ifndef __MATHS_BASE_H
#define __MATHS_BASE_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if 0
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_int.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#endif
#ifdef __PLANCK__
#include "HL2_likely/tools/errorlist.h"
#include "HL2_likely/tools/io.h"
#else
#include "errorlist.h"
#include "io.h"
#endif
#define math_base -300
#define math_negative -1 + math_base
#define math_singularValue -2 + math_base
#define math_tooManySteps -3 + math_base
#define math_underflow -4 + math_base
#define math_infnan -5 + math_base
#define math_wrongValue -6 + math_base
#define math_alloc -7 + math_base
#define math_interpoloutofrange -8 + math_base
#define math_interpol2small -9 + math_base
#define math_interpol2big -10 + math_base
#define math_stackTooSmall -11 + math_base
#define math_overflow -12 + math_base
#define math_unknown -13 + math_base
typedef double my_complex[2];
/* Mathematical constants */
#define pi 3.14159265358979323846
#define pi_sqr 9.86960440108935861883
#define twopi 6.28318530717958647693
#define ln2 0.69314718
#define ln2pi 1.837877066409
#define arcmin 2.90888208665721580e-4
#define arcsec 4.84813681e-6
/* Confidence levels, = erf({1,2,3}/sqrt(2)) */
#define conf_68 0.6827
#define conf_90 0.9000
#define conf_95 0.9545
#define conf_99 0.9973
/* Small numbers */
#define EPSILON 1.0e-5
#define EPSILON1 1.0e-8
#define EPSILON2 1.0e-18
/* Square of the absolute value of x (=|x|^2) */
#define ABSSQR(x) ((x)[0]*(x)[0] + (x)[1]*(x)[1])
/* Scalar product (x,y) */
#define SP(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1])
#endif
| 1,943 | 23.3 | 74 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap/src/minipmc/pmc.h
|
/*
* minipmc.h
* simplified pmc support from pmclib
*/
#ifndef __MC_DIST
#define __MC_DIST
#include "errorlist.h"
#include "io.h"
//#include "mvdens.h"
#include "maths_base.h"
#ifdef HAS_MKL
#include "mkl_lapack.h"
#elif HL2_ACML
#include <acml.h>
#include <acml_mv.h>
#elif LAPACK_CLIK
#include "lapack_clik.h"
#else
#include "clapack.h"
#endif
#include <dlfcn.h>
struct _pmc_simu_struct_;
struct _distribution_struct_;
typedef double posterior_log_pdf_func(void *, double *, error **);
typedef posterior_log_pdf_func log_pdf_func;
typedef void retrieve_ded_func(const void *, double *, error **);
typedef void (posterior_log_free)(void**);
typedef posterior_log_free free_func;
typedef long simulate_func(struct _pmc_simu_struct_ *, void *, void *, void *, error **);
typedef void filter_func(struct _pmc_simu_struct_* , void *, error **);
typedef void update_func(void *, struct _pmc_simu_struct_ *, error **);
typedef void* mpi_exchange_func(void *, error **);
typedef double first_derivative_func(void*, int , const double*, error **err);
typedef double second_derivative_func(void*, int ,int, const double*, error **err);
typedef char _char_name[1024];
typedef struct _distribution_struct_ {
int ndim, n_ded,ndef;
double *pars;
int * def;
void* data;
posterior_log_pdf_func* log_pdf;
retrieve_ded_func* retrieve;
posterior_log_free* free;
simulate_func *simulate;
mpi_exchange_func *broadcast_mpi;
first_derivative_func *f_der;
second_derivative_func *d_der;
void* dlhandle;
_char_name *name;
} distribution;
distribution* init_distribution_full(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
simulate_func *simulate,
int nded,
retrieve_ded_func* retrieve,
error **err);
distribution* init_simple_distribution(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
error **err);
distribution* init_distribution(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
simulate_func *simulate,
error **err);
void free_distribution(distribution **pdist) ;
int distribution_get_name(distribution *dist,char* name,error **err);
int* distribution_get_names(distribution *dist,int nname,char** name,int includeded,error **err);
void distribution_set_names(distribution *dist,char** name, error **err);
void distribution_set_broadcast(distribution* dist, mpi_exchange_func* broadcast, error **err);
double distribution_lkl(void* pdist, const double* pars, error **err);
#define distribution_log_pdf distribution_lkl
void distribution_retrieve(const void* pdist, double* pars, error **err);
void distribution_set_default(distribution *dist, int ndef, int* idef, double* vdef,error **err);
void distribution_set_default_name(distribution *dist, int ndef, char** idef, double* vdef,error **err);
void distribution_set_default(distribution *dist, int ndef, int* idef, double* vdef,error **err);
distribution * combine_distribution_init(int ndim, int nded, error **err);
double combine_lkl(void *pcbd, const double* pars, error **err);
void combine_retrieve(const void *pcbd, double* pded, error **err);
void add_to_combine_distribution(distribution *comb, distribution *addon, int *dim_idx, int *ded_idx, error **err);
void add_to_combine_distribution_name(distribution *comb, distribution *addon, error **err);
void combine_free(void **pcbd);
typedef struct {
double *pars,*pded,*dummy;
int *ded_from, **dim,**ded;
distribution **dist;
int ndim,nded,ndist,ndummy;
} comb_dist_data;
distribution *add_gaussian_prior(distribution *orig, int ndim, int *idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_2(distribution *orig, int ndim, int *idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_name(distribution *orig, int ndim, char**idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_2_name(distribution *orig, int ndim, char**idim, double* loc, double *var, error **err);
#define pmc_base -6000
#define pmc_allocate -1 + pmc_base
#define pmc_serialize -2 + pmc_base
#define pmc_outOfBound -3 + pmc_base
#define pmc_badComm -4 + pmc_base
#define pmc_negWeight -5 + pmc_base
#define pmc_cholesky -6 + pmc_base
#define pmc_negative -7 + pmc_base
#define pmc_undef -8 + pmc_base
#define pmc_file -9 + pmc_base
#define pmc_io -10 + pmc_base
#define pmc_tooManySteps -11 + pmc_base
#define pmc_dimension -12 + pmc_base
#define pmc_type -13 + pmc_base
#define pmc_negHatCl -14 + pmc_base
#define pmc_infnan -15 + pmc_base
#define pmc_incompat -16 + pmc_base
#define pmc_nosamplep -17 + pmc_base
#define pmc_sort -18 + pmc_base
#define pmc_infinite -19 + pmc_base
#define pmc_isLog -20 + pmc_base
#define dist_base -6700
#define dist_undef -1 + dist_base
#define dist_type -2 + dist_base
#define mv_base -700
#define mv_allocate -1 + mv_base
#define mv_serialize -2 + mv_base
#define mv_outOfBound -3 + mv_base
#define mv_badComm -4 + mv_base
#define mv_negWeight -5 + mv_base
#define mv_cholesky -6 + mv_base
#define mv_negative -7 + mv_base
#define mv_undef -8 + mv_base
#define mv_file -9 + mv_base
#define mv_io -10 + mv_base
#define mv_tooManySteps -11 + mv_base
#define mv_dimension -12 + mv_base
#define mv_type -13 + mv_base
#define mv_negHatCl -14 + mv_base
#define PI 3.141592653589793
#define LOGSQRT2PI 0.918938533204673
#define MALLOC_IF_NEEDED(ret,dest,size,err) { \
if (dest==NULL) { \
ret= (double*) malloc_err(size,err); \
} else { \
ret=dest; \
} \
}
#endif
| 6,198 | 33.438889 | 121 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/lklbs.h
|
/*
* lklbs.h
* lowly_project
*
* Created by Karim Benabed on 24/04/09.
* Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#include "pmc.h"
#ifndef __LKLBS__
#define __LKLBS__
#define TT_off 0
#define EE_off 1
#define BB_off 2
#define TE_off 3
#define TB_off 4
#define EB_off 5
#define _extra_size 256
typedef char extraname[_extra_size];
// definitions
typedef void compute_cl_func(void*, double*, double*, error **);
typedef struct {
void *lkl_data;
posterior_log_pdf_func* lkl_func;
posterior_log_free *lkl_free;
int lmax[6];
int mlmax;
int xdim,ndim;
double *pars;
} cmblkl_select;
typedef struct {
void *lkl_data;
posterior_log_pdf_func* lkl_func;
posterior_log_free *lkl_free;
int nell,ndim,nbins,xdim;
int* ell;
int offset_cl[6];
double *wl;
double *bins,*pls;
double unit;
extraname *xnames;
} cmblkl;
typedef struct {
int ndim;
void* bs;
compute_cl_func* bs_compute;
posterior_log_free* bs_free;
extraname *xnames;
} bs_struct;
typedef struct {
cmblkl **lkls;
int nlkl;
bs_struct* rbs;
double *cl_theo,*cl_select;
int offset_lmax[6];
int *ell,*ofx,*rx;
int nell,ndim,tot_cl,nrx,xdim;
extraname *xnames;
} lklbs;
//lklbs funcs
distribution* init_fulllklbs_distribution(cmblkl** lkls,int nlkl,
bs_struct* rbs,
int *lmax, error **err);
lklbs* init_fulllklbs(cmblkl** lkls,int nlkl,
bs_struct* rbs,
int *lmax, error **err);
void free_lklbs(void **pelf);
double lklbs_lkl(void* pelf, double* pars, error **err);
// bs support
bs_struct *init_bs_struct(int ndim, void* bs, compute_cl_func* bs_compute, posterior_log_free* bs_free, char **_xnames, error **err);
void free_bs_struct(void **prbs);
//cmblkl support
cmblkl *init_cmblkl_select(void* lkl_data, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
int *lmax,
int xdim, error **err);
double select_func(void* dt, double *pars,error **err);
void select_free(void** dt);
cmblkl *init_cmblkl(void* lkl_data, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
int nell,int* ell,int* has_cl,int lmax,double unit,double *wl,int wlselect,
double *bins,int nbins, int xdim,error **err);
void free_cmblkl(void **self);
void cmblkl_check_lmax(cmblkl *lkl,int *lmax,error **err);
double* cmblkl_select_cls(cmblkl *llkl,lklbs* self);
void cmblkl_max_lmax(cmblkl *lkl,int *lmax, error **err);
void cmblkl_set_names(cmblkl *lkl, char **names, error **err);
void cmblkl_check_xnames(cmblkl *self,int ii,error **err);
// support and deprecated
int lklbs_get_par_id(lklbs* self,extraname name, error **err);
lklbs* init_lklbs(void* lkl, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free, int ndim,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int nell, int* ell, int *lmax,error **err);
lklbs* init_multilklbs(cmblkl** lkls,int nlkl,int ndim,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int *lmax, error **err);
distribution* init_lklbs_distribution(int ndim,void* lkl, posterior_log_pdf_func* lkl_func,
posterior_log_free *lkl_free,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int nell, int* ell, int *lmax,error **err);
distribution* init_multilklbs_distribution(int ndim,cmblkl** lkls,int nlkl,
void* bs, compute_cl_func* bs_compute,
posterior_log_free* bs_free,
int *lmax, error **err);
// minimal bs
typedef struct {
int ndim;
int lmax[6];
} zero_bs;
zero_bs* init_zero_bs(int *lmax, error **err);
void zero_bs_compute(void* zbs, double* prs, double* cls, error **err);
void free_zero_bs(void **pzbs);
/*typedef beamfunc(void* data, double* bdata, double* cls, double *bcls, error **);
typedef struct {
int ndim;
int xdim;
cmblkl target;
double *lars;
void *data;
beamfunc *bfunc;
posterior_log_free *bfree;
} beamed;
*/
#define lklbs_base -49000
#define lklbs_zero -1 + lklbs_base
#define lklbs_incompatible_lmax -2 + lklbs_base
#define clowly_base -9000
#define lowly_chol -1 + clowly_base
#define lowly_unkorder -4 + clowly_base
#define lowly_lbig -12 + clowly_base
#endif
| 4,888 | 27.424419 | 133 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/wlik.c
|
/*
* wlik.c
* lowly_project
*
* Created by Karim Benabed on 16/03/11.
* Copyright 2011 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#include "wlik.h"
// ARE YOU STILL READING ?
// YOU HAVE BEEN WARNED !
#include <errno.h>
#include <string.h>
typedef struct {
char tmpdir[800];
} wmap;
void free_wmap(void **none) {
wmap_extra_free_();
}
double wmap_lkl(void* none, double* pars, error **err) {
double lkl;
wmap_extra_lkl_(&lkl,pars);
return lkl;
}
cmblkl* wlik_wmap_init(char *dirname, int ttmin, int ttmax, int temin, int temax, int use_gibbs, int use_lowl_pol, error **err) {
int bok;
cmblkl *cing,*target;
int mlmax;
char pwd[5000];
int has_cl[6],lmaxs[6];
int *ell;
int lmax,l,n_cl,cli;
zero_bs* zbs;
//only one wmap
wmap_extra_only_one_(&bok);
testErrorRet(bok!=0,-100,"wmap already initialized",*err,__LINE__,NULL);
//change dir
testErrorRetVA(getcwd(pwd,4096)==NULL,-101010,"can't get cwd name (cause = '%s')",*err,__LINE__,NULL,strerror(errno));
testErrorRetVA(chdir(dirname)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,dirname,strerror(errno));
// call wmap_init
wmap_extra_parameter_init_(&ttmin,&ttmax,&temin,&temax,&use_gibbs,&use_lowl_pol);
//change dir back
testErrorRetVA(chdir(pwd)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,pwd,strerror(errno));
lmax = ttmax;
if (temax>ttmax) {
lmax = temax;
}
has_cl[0]=0;
has_cl[1]=0;
has_cl[2]=0;
has_cl[3]=0;
has_cl[4]=0;
has_cl[5]=0;
lmaxs[0]=-1;
lmaxs[1]=-1;
lmaxs[2]=-1;
lmaxs[3]=-1;
lmaxs[4]=-1;
lmaxs[5]=-1;
if (ttmin<=ttmax && ttmax>0) {
has_cl[0]=1;
}
if (temin<=temax && temax>0) {
has_cl[1]=1;
has_cl[2]=1;
has_cl[3]=1;
}
ell = malloc_err(sizeof(double)*(lmax+1),err);
forwardError(*err,__LINE__,NULL);
for(l=0;l<=lmax;l++) {
ell[l] = l;
}
cing = init_cmblkl(NULL, &wmap_lkl,
&free_wmap,
lmax+1,ell,
has_cl,lmax,1,NULL,0,NULL,0,0,err);
forwardError(*err,__LINE__,NULL);
n_cl = 0;
for(cli=0;cli<6;cli++) {
n_cl += (lmax+1)*has_cl[cli];
}
cmblkl_max_lmax(cing,lmaxs,err);
forwardError(*err,__LINE__,NULL);
zbs = init_zero_bs(lmaxs, err);
forwardError(*err,__LINE__,NULL);
target = init_multilklbs_distribution(n_cl , &cing,1,
zbs, &zero_bs_compute, &free_zero_bs, lmaxs, err);
forwardError(*err,__LINE__,NULL);
free(ell);
return target;
}
void wlik_get_has_cl(wlik_object *wlikid, int has_cl[6],error **_err) {
distribution *target;
lklbs *lbs;
int cli;
_dealwitherr;
lbs = _wlik_dig(wlikid,err);
_forwardError(*err,__LINE__,);
for(cli=0;cli<6;cli++) {
//fprintf(stderr," %d %d ",cli,lbs->offset_lmax[cli]);
if (lbs->offset_lmax[cli]!=-1) {
has_cl[cli]=1;
} else {
has_cl[cli]=0;
}
}
}
void wlik_get_lmax(wlik_object *wlikid, int lmax[6],error **_err) {
distribution *target;
lklbs *lbs;
zero_bs* zbs;
int cli;
_dealwitherr;
lbs = _wlik_dig(wlikid,err);
_forwardError(*err,__LINE__,);
zbs = lbs->rbs->bs;
for(cli=0;cli<6;cli++) {
lmax[cli] = zbs->lmax[cli];
}
}
void wlik_cleanup(wlik_object** pwlikid) {
free_distribution(pwlikid);
}
double wlik_compute(wlik_object* wlikid, double* cl_and_pars,error **_err) {
double res;
_dealwitherr;
res = distribution_lkl(wlikid, cl_and_pars,err);
_forwardError(*err,__LINE__,-1);
return res;
}
void* _wlik_dig(wlik_object* wlikid, error **err) {
distribution *target;
target = wlikid;
if (target->log_pdf == &combine_lkl) {
// return the first wlik likelihood
int i;
comb_dist_data* cbd;
cbd = target->data;
for (i=0;i<cbd->ndist;i++) {
if (cbd->dist[i]->log_pdf == &lklbs_lkl) {
return cbd->dist[i]->data;
}
}
}
if (target->log_pdf==&lklbs_lkl) {
return target->data;
}
testErrorRet(1==1,-111,"No wlik likelihood found",*err,__LINE__,NULL);
}
| 4,079 | 20.935484 | 129 |
c
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/minipmc/errorlist.h
|
/*
* errorlist.h
* likeli
*
* Created by Karim Benabed on 06/02/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef __ERRORLIST_H
#define __ERRORLIST_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#define TXT_SZ 4192
#define WHR_SZ 2048
#define TOT_SZ TXT_SZ+WHR_SZ
typedef struct _err {
char errWhere[WHR_SZ];
char errText[TXT_SZ];
int errValue;
struct _err* next;
} error;
typedef error sm2_error;
#define forwardErr -123456789
#define undefErr -987654321
#define noErr 0
#define placeHolderError 1020304050
#define el_alloc -42
error* newError(int errV, char* where, char* text, error* linkTo, error* addErr);
error* newErrorVA(int errV, const char* func,char* where, char* text, error* linkTo, error* addErr,...);
void stringError(char* str, error *err);
void printError(FILE* flog,error* err);
int getErrorValue(error* err);
void purgeError(error **err);
error* unpickleError(void* buf, int len);
int pickleError(error* err, void** buf);
error* initError(void);
void endError(error **err);
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define __func__ __FUNCTION__
# else
# define __func__ "<unknown>"
# endif
#endif
#define _DEBUGHERE_(extra,...) fprintf(stderr,"%s:("__FILE__":%d) "extra"\n",__func__,__LINE__,__VA_ARGS__);
#define someErrorVA(errV,txt,prev,next,li,...) newErrorVA(errV,__func__,"("__FILE__":"#li")",txt,prev,next,__VA_ARGS__)
#define topErrorVA(errV,txt,next,li,...) someErrorVA(errV,txt,NULL,next,li,__VA_ARGS__)
#define oneErrorVA(errV,txt,li,...) someErrorVA(errV,txt,NULL,NULL,li,__VA_ARGS__)
#define addErrorVA(errV,txt,prev,li,...) someErrorVA(errV,txt,prev,NULL,li,__VA_ARGS__)
#define someError(errV,txt,prev,next,li) someErrorVA(errV,txt,prev,next,li,"")
#define topError(errV,txt,next,li) topErrorVA(errV,txt,next,li,"")
#define oneError(errV,txt,li) oneErrorVA(errV,txt,li,"")
#define addError(errV,txt,prev,li) addErrorVA(errV,txt,prev,li,"")
// isError
#define isError(err) (_isError(err))
#define isErrorReturn(err,ret) { \
if (isError(err)) { \
return ret; \
} \
}
#define isErrorExit(err,F) { \
if (isError(err)) { \
printError(F,err); \
exit(getErrorValue(err)); \
} \
}
// forwards
#define forwardErrorNoReturn(err,line) { \
if (isError(err)) { \
err=topError(forwardErr,"",err,line); \
} \
}
#define forwardError(err,line,ret) { \
forwardErrorNoReturn(err,line); \
isErrorReturn(err,ret) \
}
// tests
#define testErrorVA(test,error_type,message,err,line,...) { \
if (test) { \
err=addErrorVA(error_type,message,err,line,__VA_ARGS__); \
} \
}
#define testErrorRetVA(test,error_type,message,err,line,return_value,...) { \
testErrorVA(test,error_type,message,err,line,__VA_ARGS__); \
isErrorReturn(err,return_value); \
}
#define testErrorExitVA(test,error_type,message,err,line,...) { \
testErrorVA(test,error_type,message,err,line,__VA_ARGS__); \
isErrorExit(err,stderr); \
}
#define testError(test,error_type,message,err,line) testErrorVA(test,error_type,message,err,line,"")
#define testErrorRet(test,error_type,message,err,line,return_value) testErrorRetVA(test,error_type,message,err,line,return_value,"")
#define testErrorExit(test,error_type,message,err,line) testErrorExitVA(test,error_type,message,err,line,"")
// exit and co
#define exitOnError(err,F) isErrorExit(err,F)
#define quitOnError(err,line,F) { \
forwardErrorNoReturn(err,line); \
isErrorExit(err,F); \
}
#define quitOnErrorStr(err,line,F,str) { \
forwardErrorNoReturn(err,line); \
if (isError(err)) { \
printError(F,err); \
fprintf(F, "%s\n", str); \
exit(getErrorValue(err)); \
} \
}
#define err_base -100
#define err_io -1 + err_base
#define err_allocate -2 + err_base
error* initError(void);
void endError(error **err);
int _isError(error *err);
#endif
| 4,651 | 29.807947 | 132 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/minipmc/io.c
|
/* ============================================================ *
* io.c *
* Martin Kilbinger, Karim Benabed *
* ============================================================ */
/* simplified version from pmclib*/
#include "io.h"
/* ============================================================ *
* I/O and memory tools. *
* ============================================================ */
FILE* fopen_err(const char* fname, const char *mode, error **err)
{
FILE* fp;
fp = fopen(fname, mode);
testErrorRetVA(fp==NULL, err_io, "Cannot open file '%s' (mode \"%s\")", *err,__LINE__,NULL,fname, mode);
return fp;
}
void* malloc_err(size_t sz, error **err)
{
void* res;
testErrorRetVA(sz<=0,err_allocate,"Size %ld has to be positive",*err,__LINE__,NULL,sz);
res = malloc(sz);
testErrorRetVA(res==NULL,err_allocate,"Cannot allocate %ld bytes",*err,__LINE__,NULL,sz);
return res;
}
void* calloc_err(size_t nl, size_t sz1, error **err)
{
void* res;
testErrorRetVA(nl<=0,err_allocate,"Size %ld has to be positive",*err,__LINE__,NULL,nl);
res = calloc(nl,sz1);
testErrorRetVA(res==NULL,err_allocate,"Cannot allocate %d objects of %d bytes (=%d total)",
*err,__LINE__,NULL,nl,sz1,nl*sz1);
return res;
}
void *realloc_err(void *ptr, size_t sz, error **err)
{
void *res;
res = realloc(ptr, sz);
testErrorVA(ptr==NULL, err_allocate, "Cannot reallocate %zu bytes", *err, __LINE__, NULL, sz);
testErrorVA(res==NULL, err_allocate, "Cannot reallocate %zu bytes", *err, __LINE__, NULL, sz);
return NULL;
}
/* Returns a pointer with content orig, resized from sz_orig to sz_new. If *
* free_orig=1, the original memory is freed.
* orig can be NULL or sz_orig can be 0, in that case, just allocate sz_new and returns
*/
void* resize_err(void* orig, size_t sz_orig, size_t sz_new, int free_orig, error **err)
{
void* res;
size_t minsz,o_size;
res = malloc_err(sz_new,err);
forwardError(*err,__LINE__,NULL);
if (orig == NULL || sz_orig==0) {
return res;
}
o_size = sz_orig;
minsz = o_size;
if (o_size > sz_new) {
minsz = sz_new;
}
memcpy(res,orig,minsz);
if(free_orig == 1) {
free(orig);
}
return res;
}
size_t read_line(FILE* fp, char* buff, int bmax, error **err) {
size_t i;
char cur;
int dsc;
i=0;
dsc=0;
while (i<bmax-1) {
cur=(char)fgetc(fp);
if (feof(fp) || cur=='\n') {
buff[i]='\0';
//fprintf(stderr,"Read |%s|\n",buff);
return i+1;
}
if (dsc==1) {
continue;
}
if (cur=='#' || cur=='!' || cur==';') {
dsc=1;
continue;
}
buff[i]=cur;
i++;
}
*err = addErrorVA(err_io,"One line of file is longer than the max size (%d)",*err,__LINE__,bmax);
return -1;
}
void* read_any_vector(const char* fnm, size_t n, char *prs, size_t sz, error **err) {
size_t nn;
char* res;
nn=n;
res = read_any_list(fnm, &nn, prs, sz, err);
forwardError(*err,__LINE__,NULL);
return res;
}
//#define _stp_ 4096
#define _stp_ 524288
void* read_any_list(const char* fnm, size_t *n, char *prs, size_t sz, error **err)
{
void *res;
size_t nlines;
res = read_any_list_count(fnm, n, prs, sz, &nlines, err);
forwardError(*err, __LINE__, NULL);
return res;
}
/* ============================================================ *
* Read white-spaced separated records of format prs and size *
* sz from the file fnm. The number of records is set in n on *
* output. On input, n should be set to zero, or ask Karim what *
* happens if not. Returns record as void pointer. *
* The number of lines is set in nlines on output. *
* Comment and empty lines are ignored. *
* ============================================================ */
void* read_any_list_count(const char* fnm, size_t *n, char *prs, size_t sz,
size_t *nlines, error **err)
{
FILE *fp;
size_t i,cz,j,j0,ibefore;
char *res;
char buffer[_stp_];
int clip;
if (*n>0) {
clip=1;
} else {
clip=0;
*n=_stp_;
}
res = (void*) malloc_err((*n)*sz,err);
forwardError(*err,__LINE__,NULL);
fp=fopen_err(fnm,"r",err);
forwardError(*err,__LINE__,NULL);
i=0;
*nlines = 0;
while(feof(fp)==0) {
cz=read_line(fp,buffer,_stp_,err);
testErrorRetVA(isError(*err),err_io,"Reading file '%s'",*err,__LINE__,NULL,fnm);
j=0;
//fprintf(stderr,"A %d %s\n",sz,prs);
ibefore = i;
while (j<cz) {
//fprintf(stderr,"%d %c\n",j,buffer[j]);
//look for first non blanc char
while(j<cz && isspace(buffer[j]) && buffer[j]!='\0') {
//fprintf(stderr,"%d %c\n",j,buffer[j]);
j++;
}
if (j==cz || buffer[j]=='\0') //blank line
break;
// find next blanck char
j0=j;
while(j<cz && !isspace(buffer[j]) && buffer[j]!='\0')
j++;
buffer[j]='\0';
j++;
//fprintf(stderr,"segment |%s|\n",&(buffer[j0]));
// read value between the two limits
testErrorRetVA(sscanf(buffer+j0,prs,res +i*sz)!=1,err_io,"Cannot read file '%s' at index %d",
*err,__LINE__,NULL,fnm,i)
//fprintf(stderr,prs,*(double*)(res +i*sz));
//fprintf(stderr,"\n");
i++;
if (i==*n) {
if (clip==1)
break;
res = resize_err(res,(*n)*sz,(*n)*2*sz,1,err);
forwardError(*err,__LINE__,NULL);
(*n) = (*n)*2;
}
}
/* NEW (MK) */
if (i>ibefore) {
/* A valid line was found: increase line count */
(*nlines) ++;
}
if (i==*n) {
if (clip==1)
break;
res = resize_err(res,(*n)*sz,(*n)*2*sz,1,err);
forwardError(*err,__LINE__,NULL);
(*n) = (*n)*2;
}
}
fclose(fp);
if (clip==1)
testErrorRetVA(i!=*n,err_io,"Not enough data in file '%s' (got %d entries, expected %d)\n",
*err,__LINE__,NULL,fnm,i,*n);
res = resize_err(res,(*n)*sz,i*sz,1,err);
forwardError(*err,__LINE__,NULL);
*n=i;
return res;
}
#undef _stp_
double* read_double_vector(const char* fnm, size_t n, error **err) {
double *res;
res = read_any_vector(fnm, n, "%lg", sizeof(double), err);
forwardError(*err,__LINE__,NULL);
return res;
}
double* read_double_list(const char* fnm, size_t *n, error **err) {
double *res;
res = read_any_list(fnm, n, "%lg", sizeof(double), err);
forwardError(*err,__LINE__,NULL);
return res;
}
float* read_float_vector(const char* fnm, size_t n, error **err) {
float *res;
res = read_any_vector(fnm, n, "%g", sizeof(float), err);
forwardError(*err,__LINE__,NULL);
return res;
}
float* read_float_list(const char* fnm,size_t *n, error **err) {
float *res;
res = read_any_list(fnm, n, "%g",sizeof(float),err);
forwardError(*err,__LINE__,NULL);
return res;
}
int* read_int_vector(const char* fnm,size_t n, error **err) {
int *res;
res = read_any_vector(fnm, n, "%d",sizeof(int),err);
forwardError(*err,__LINE__,NULL);
return res;
}
int* read_int_list(const char* fnm, size_t *n, error **err) {
int *res;
res = read_any_list(fnm, n, "%d",sizeof(int),err);
forwardError(*err,__LINE__,NULL);
return res;
}
long* read_long_vector(const char* fnm, size_t n, error **err) {
long *res;
res = read_any_vector(fnm, n, "%ld",sizeof(long),err);
forwardError(*err,__LINE__,NULL);
return res;
}
long* read_long_list(const char* fnm, size_t *n, error **err) {
long *res;
res = read_any_list(fnm, n, "%ld",sizeof(long),err);
forwardError(*err,__LINE__,NULL);
return res;
}
void* read_bin_vector(const char* fnm, size_t n, error **err) {
void *res;
FILE* ff;
size_t rr;
ff = fopen_err(fnm, "r", err);
forwardError(*err,__LINE__,NULL);
res = malloc_err(n,err);
forwardError(*err,__LINE__,NULL);
rr=fread(res, 1, n, ff);
testErrorRetVA(rr!=n,io_file,"File '%s' does not contain enough data (Expected %d bytes, got %d)",*err,__LINE__,NULL,fnm,n,rr);
fclose(ff);
return res;
}
void* read_bin_list(const char* fnm, size_t *n, error **err) {
void *res;
FILE* ff;
size_t rr;
struct stat stst;
testErrorRetVA(stat(fnm,&stst)!=0,io_file,"File '%s' cannot be stated",*err,__LINE__,NULL,fnm);
*n = stst.st_size;
ff = fopen_err(fnm, "r", err);
forwardError(*err,__LINE__,NULL);
res = malloc_err(*n,err);
forwardError(*err,__LINE__,NULL);
rr=fread(res, 1, *n, ff);
testErrorRetVA(rr!=*n,io_file,
"File '%s' does not contain enough data (Expected %d bytes, got %d)",
*err,__LINE__,NULL,fnm,*n,rr);
fclose(ff);
return res;
}
void write_bin_vector(void* buf, const char* fnm, size_t n, error **err) {
FILE* ff;
size_t rr;
ff = fopen_err(fnm, "w", err);
forwardError(*err,__LINE__,);
rr=fwrite(buf, 1, n, ff);
testErrorRetVA(rr!=n,io_file,
"Cannot write data in file '%s' (Expected %d bytes, got %d)",
*err,__LINE__,,fnm,n,rr);
fclose(ff);
fprintf(stderr,"Saved in %s\n", fnm);
}
time_t start_time(FILE *FOUT)
{
time_t t_start;
time(&t_start);
fprintf(FOUT, "Started at %s\n", ctime(&t_start));
fflush(FOUT);
return t_start;
}
void end_time(time_t t_start, FILE *FOUT)
{
time_t t_end;
double diff;
time(&t_end);
fprintf(FOUT, "Ended at %s", ctime(&t_end));
diff = difftime(t_end, t_start);
fprintf(FOUT, "Computation time %.0fs (= %dd %dh %dm %ds)\n",
diff, (int)diff/86400, ((int)diff%86400)/3600,
((int)diff%3600)/60, ((int)diff%60));
}
| 9,452 | 25.185596 | 129 |
c
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/minipmc/io.h
|
/* ============================================================ *
* io.h *
* Martin Kilbinger, Karim Benabed 2008 *
* ============================================================ */
#ifndef __IO_H
#define __IO_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __PLANCK__
#include "HL2_likely/tools/errorlist.h"
#else
#include "errorlist.h"
#endif
#define io_base -200
#define io_alloc -1 + io_base
#define io_file -2 + io_base
#define io_eof -3 + io_base
#define io_null -4 + io_base
#define io_inconsistent -5 + io_base
unsigned int numberoflines(const char *, error **err);
unsigned int numberoflines_comments(const char *name, unsigned int *ncomment, error **err);
/* The following three functions are used to read in the SNLS supernovae data */
int read_double(char** p, double *x);
int read_int(char** p, int *x);
double *readASCII(char *filename, int *fnx, int *fny, sm2_error **err);
FILE* fopen_err(const char* fname, const char *mode, error **err);
void* malloc_err(size_t sz, error **err);
void* calloc_err(size_t nl,size_t sz1, error **err);
void *realloc_err(void *ptr, size_t sz, error **err);
void* resize_err(void* orig, size_t sz_orig, size_t sz_new, int free_orig, error **err);
size_t read_line(FILE* fp, char* buff,int bmax, error **err);
void* read_any_vector(const char* fnm, size_t n, char *prs, size_t sz, error **err);
void* read_any_list(const char* fnm,size_t *n, char *prs, size_t sz, error **err);
void* read_any_list_count(const char* fnm, size_t *n, char *prs, size_t sz,
size_t *nlines, error **err);
double* read_double_vector(const char* fnm, size_t n, error **err);
double* read_double_list(const char* fnm, size_t *n, error **err);
int* read_int_vector(const char* fnm, size_t n, error **err);
int* read_int_list(const char* fnm, size_t *n, error **err);
float* read_float_vector(const char* fnm, size_t n, error **err);
float* read_float_list(const char* fnm, size_t *n, error **err);
long* read_long_vector(const char* fnm, size_t n, error **err);
long* read_long_list(const char* fnm,size_t *n, error **err);
void write_bin_vector(void* buf, const char* fnm, size_t n, error **err);
void* read_bin_vector(const char* fnm, size_t n, error **err);
void* read_bin_list(const char* fnm, size_t *n, error **err);
void chomp(char *x);
/* ============================================================ *
* To calculate the program run time. *
* ============================================================ */
time_t start_time(FILE *FOUT);
void end_time(time_t t_start, FILE *FOUT);
#endif
| 2,689 | 35.849315 | 91 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/minipmc/maths_base.h
|
/*
* maths_base.h
* ecosstat_project
*
* Created by Karim Benabed on 23/06/09.
* Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#ifndef __MATHS_BASE_H
#define __MATHS_BASE_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if 0
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_int.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#endif
#ifdef __PLANCK__
#include "HL2_likely/tools/errorlist.h"
#include "HL2_likely/tools/io.h"
#else
#include "errorlist.h"
#include "io.h"
#endif
#define math_base -300
#define math_negative -1 + math_base
#define math_singularValue -2 + math_base
#define math_tooManySteps -3 + math_base
#define math_underflow -4 + math_base
#define math_infnan -5 + math_base
#define math_wrongValue -6 + math_base
#define math_alloc -7 + math_base
#define math_interpoloutofrange -8 + math_base
#define math_interpol2small -9 + math_base
#define math_interpol2big -10 + math_base
#define math_stackTooSmall -11 + math_base
#define math_overflow -12 + math_base
#define math_unknown -13 + math_base
typedef double my_complex[2];
/* Mathematical constants */
#define pi 3.14159265358979323846
#define pi_sqr 9.86960440108935861883
#define twopi 6.28318530717958647693
#define ln2 0.69314718
#define ln2pi 1.837877066409
#define arcmin 2.90888208665721580e-4
#define arcsec 4.84813681e-6
/* Confidence levels, = erf({1,2,3}/sqrt(2)) */
#define conf_68 0.6827
#define conf_90 0.9000
#define conf_95 0.9545
#define conf_99 0.9973
/* Small numbers */
#define EPSILON 1.0e-5
#define EPSILON1 1.0e-8
#define EPSILON2 1.0e-18
/* Square of the absolute value of x (=|x|^2) */
#define ABSSQR(x) ((x)[0]*(x)[0] + (x)[1]*(x)[1])
/* Scalar product (x,y) */
#define SP(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1])
#endif
| 1,943 | 23.3 | 74 |
h
|
montepython_public
|
montepython_public-master/wrapper_wmap_v4p1/src/minipmc/pmc.h
|
/*
* minipmc.h
* simplified pmc support from pmclib
*/
#ifndef __MC_DIST
#define __MC_DIST
#include "errorlist.h"
#include "io.h"
//#include "mvdens.h"
#include "maths_base.h"
#ifdef HAS_MKL
#include "mkl_lapack.h"
#elif HL2_ACML
#include <acml.h>
#include <acml_mv.h>
#elif LAPACK_CLIK
#include "lapack_clik.h"
#else
#include "clapack.h"
#endif
#include <dlfcn.h>
struct _pmc_simu_struct_;
struct _distribution_struct_;
typedef double posterior_log_pdf_func(void *, double *, error **);
typedef posterior_log_pdf_func log_pdf_func;
typedef void retrieve_ded_func(const void *, double *, error **);
typedef void (posterior_log_free)(void**);
typedef posterior_log_free free_func;
typedef long simulate_func(struct _pmc_simu_struct_ *, void *, void *, void *, error **);
typedef void filter_func(struct _pmc_simu_struct_* , void *, error **);
typedef void update_func(void *, struct _pmc_simu_struct_ *, error **);
typedef void* mpi_exchange_func(void *, error **);
typedef double first_derivative_func(void*, int , const double*, error **err);
typedef double second_derivative_func(void*, int ,int, const double*, error **err);
typedef char _char_name[1024];
typedef struct _distribution_struct_ {
int ndim, n_ded,ndef;
double *pars;
int * def;
void* data;
posterior_log_pdf_func* log_pdf;
retrieve_ded_func* retrieve;
posterior_log_free* free;
simulate_func *simulate;
mpi_exchange_func *broadcast_mpi;
first_derivative_func *f_der;
second_derivative_func *d_der;
void* dlhandle;
_char_name *name;
} distribution;
distribution* init_distribution_full(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
simulate_func *simulate,
int nded,
retrieve_ded_func* retrieve,
error **err);
distribution* init_simple_distribution(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
error **err);
distribution* init_distribution(int ndim,
void* data,
posterior_log_pdf_func* log_pdf,
posterior_log_free* freef,
simulate_func *simulate,
error **err);
void free_distribution(distribution **pdist) ;
int distribution_get_name(distribution *dist,char* name,error **err);
int* distribution_get_names(distribution *dist,int nname,char** name,int includeded,error **err);
void distribution_set_names(distribution *dist,char** name, error **err);
void distribution_set_broadcast(distribution* dist, mpi_exchange_func* broadcast, error **err);
double distribution_lkl(void* pdist, const double* pars, error **err);
#define distribution_log_pdf distribution_lkl
void distribution_retrieve(const void* pdist, double* pars, error **err);
void distribution_set_default(distribution *dist, int ndef, int* idef, double* vdef,error **err);
void distribution_set_default_name(distribution *dist, int ndef, char** idef, double* vdef,error **err);
void distribution_set_default(distribution *dist, int ndef, int* idef, double* vdef,error **err);
distribution * combine_distribution_init(int ndim, int nded, error **err);
double combine_lkl(void *pcbd, const double* pars, error **err);
void combine_retrieve(const void *pcbd, double* pded, error **err);
void add_to_combine_distribution(distribution *comb, distribution *addon, int *dim_idx, int *ded_idx, error **err);
void add_to_combine_distribution_name(distribution *comb, distribution *addon, error **err);
void combine_free(void **pcbd);
typedef struct {
double *pars,*pded,*dummy;
int *ded_from, **dim,**ded;
distribution **dist;
int ndim,nded,ndist,ndummy;
} comb_dist_data;
distribution *add_gaussian_prior(distribution *orig, int ndim, int *idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_2(distribution *orig, int ndim, int *idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_name(distribution *orig, int ndim, char**idim, double* loc, double *var, error **err);
distribution *add_gaussian_prior_2_name(distribution *orig, int ndim, char**idim, double* loc, double *var, error **err);
#define pmc_base -6000
#define pmc_allocate -1 + pmc_base
#define pmc_serialize -2 + pmc_base
#define pmc_outOfBound -3 + pmc_base
#define pmc_badComm -4 + pmc_base
#define pmc_negWeight -5 + pmc_base
#define pmc_cholesky -6 + pmc_base
#define pmc_negative -7 + pmc_base
#define pmc_undef -8 + pmc_base
#define pmc_file -9 + pmc_base
#define pmc_io -10 + pmc_base
#define pmc_tooManySteps -11 + pmc_base
#define pmc_dimension -12 + pmc_base
#define pmc_type -13 + pmc_base
#define pmc_negHatCl -14 + pmc_base
#define pmc_infnan -15 + pmc_base
#define pmc_incompat -16 + pmc_base
#define pmc_nosamplep -17 + pmc_base
#define pmc_sort -18 + pmc_base
#define pmc_infinite -19 + pmc_base
#define pmc_isLog -20 + pmc_base
#define dist_base -6700
#define dist_undef -1 + dist_base
#define dist_type -2 + dist_base
#define mv_base -700
#define mv_allocate -1 + mv_base
#define mv_serialize -2 + mv_base
#define mv_outOfBound -3 + mv_base
#define mv_badComm -4 + mv_base
#define mv_negWeight -5 + mv_base
#define mv_cholesky -6 + mv_base
#define mv_negative -7 + mv_base
#define mv_undef -8 + mv_base
#define mv_file -9 + mv_base
#define mv_io -10 + mv_base
#define mv_tooManySteps -11 + mv_base
#define mv_dimension -12 + mv_base
#define mv_type -13 + mv_base
#define mv_negHatCl -14 + mv_base
#define PI 3.141592653589793
#define LOGSQRT2PI 0.918938533204673
#define MALLOC_IF_NEEDED(ret,dest,size,err) { \
if (dest==NULL) { \
ret= (double*) malloc_err(size,err); \
} else { \
ret=dest; \
} \
}
#endif
| 6,198 | 33.438889 | 121 |
h
|
null |
AESC-main/aesc/graph.h
|
#ifndef GRAPH_H
#define GRAPH_H
#include "utils.h"
class Graph{
public:
std::vector<std::vector<uint>> m_edges; // edges of each node
std::vector<uint> m_deg; // degree of each node
private:
std::string m_folder;
std::string m_graph;
uint m_n; // the number of nodes
uint64 m_m; // the number of edges
double m_lambda; // the 2nd largest eigenvalue
void readNM();
void readGraph();
void addEdge(uint u, uint v);
public:
uint getDeg(uint u) const;
uint64 getM() const;
uint getN() const;
double getLambda() const;
std::string getGraphFolder() const;
Graph(const std::string& t_folder, const std::string& t_graph);
};
#endif
| 774 | 22.484848 | 71 |
h
|
null |
AESC-main/aesc/utils.h
|
#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
#include <algorithm> // std::find
#include <ctime>
#include <chrono>
#include <fstream>
#include <queue>
#include <sstream>
#include <iterator>
#include <cstring>
#include <math.h> /* log */
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <list>
#include <random>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <algorithm>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
// #include "sparsehash/dense_hash_map"
using namespace std;
typedef unsigned int uint;
typedef unsigned char uint8;
typedef long long int64;
typedef unsigned long long uint64;
typedef std::pair<uint, uint> ipair;
typedef std::pair<double, double> dpair;
#define MP std::make_pair
#ifndef TIMES_PER_SEC
#define TIMES_PER_SEC (1.0e9)
#endif
#define SIZE(t) (int)(t.size())
#define ALL(t) (t).begin(), (t).end()
#define FOR(i, n) for(int (i)=0; (i)<((int)(n)); (i)++)
const std::string MC = "mc";
const std::string MCC = "mcc";
const std::string TGTP = "tgt+";
const std::string TGT = "tgt";
struct Config{
std::string strFolder;
std::string strGraph;
std::string strAlgo;
double epsilon=0;
double lambda=0;
double delta=0;
uint64 numwalks=0;
uint lenwalk=0;
uint ell=0;
int gamma=0;
int omega = 64;
int evaflag = 1;
void display(){
std::cout << "====================Configurations==================" << std::endl;
// std::cout << "data folder: " << strFolder << '\n';
std::cout << "graph file name: " << strGraph << '\n';
std::cout << "algorithm: " << strAlgo << '\n';
std::cout << "absolute error epsilon: " << epsilon << '\n';
std::cout << "failure probability: " << delta << '\n';
std::cout << "candidate size gamma: " << gamma << '\n';
std::cout << "omega: " << omega << '\n';
// std::cout << "#randomwalks: " << numwalks << '\n';
//std::cout << "iteration: " << iteration << '\n';
std::cout << "====================Configurations==================" << std::endl;
}
void check(){
std::vector<std::string> Algos = {MC,MCC,TGT,TGTP};
auto f = std::find(Algos.begin(), Algos.end(), strAlgo);
assert (f != Algos.end());
}
void setTP(uint64 m){
ell = uint(log(4.0/epsilon/(1-lambda))/log(1.0/lambda)-1.0);
// cout<<ell<<endl;
lenwalk = ell;
numwalks = uint64(40*lenwalk*lenwalk*log(8*m*lenwalk/delta)/epsilon/epsilon);
}
void setTPC(){
ell = uint(log(4.0/epsilon/(1-lambda))/log(1.0/lambda)-1.0);
lenwalk = ell;
// numwalks = 20000*(sqrt()+pow(lenwalk,3)/epsilon/epsilon);
}
};
void process_mem_usage(double& vm_usage, double& resident_set);
double time_by(double start);
void disp_mem_usage();
uint getProcMemory();
class Timer {
public:
static std::vector<double> timeUsed;
static std::vector<string> timeUsedDesc;
int id;
std::chrono::steady_clock::time_point startTime;
bool showOnDestroy;
Timer(int id, string desc = "", bool showOnDestroy = false) {
this->id = id;
while ((int) timeUsed.size() <= id) {
timeUsed.push_back(0);
timeUsedDesc.push_back("");
}
timeUsedDesc[id] = desc;
startTime = std::chrono::steady_clock::now();
this->showOnDestroy = showOnDestroy;
}
static double used(int id) {
return timeUsed[id] / TIMES_PER_SEC;
}
~Timer() {
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - startTime).count();
if (showOnDestroy) {
std::cout << "time spend on " << timeUsedDesc[id] << ":" << duration / TIMES_PER_SEC << "s" << std::endl;
}
timeUsed[id] += duration;
}
static void show(bool debug = false) {
cout << "##### Timer #####" << endl;
for (int i = 0; i < (int) timeUsed.size(); i++) {
if (timeUsed[i] > 0) {
char str[100];
sprintf(str, "%.6lf", timeUsed[i] / TIMES_PER_SEC);
string s = str;
if ((int) s.size() < 15) s = " " + s;
char t[100];
memset(t, 0, sizeof t);
sprintf(t, "%4d %s %s", i, s.c_str(), timeUsedDesc[i].c_str());
cout << t << endl;
}
}
}
static void reset(int id){
if(id>=0 && id<timeUsed.size()){
timeUsed[id] = 0;
}
}
static void clearAll() {
timeUsed.clear();
timeUsedDesc.clear();
}
};
const int VectorDefaultSize=20;
template <typename _T>
class iVector
{
public:
uint m_size;
_T* m_data;
uint m_num;
void free_mem()
{
delete[] m_data;
}
iVector()
{
//printf("%d\n",VectorDefaultSize);
m_size = VectorDefaultSize;
m_data = new _T[VectorDefaultSize];
m_num = 0;
}
iVector( uint n )
{
if ( n == 0 )
{
n = VectorDefaultSize;
}
// printf("iVector allocate: %d\n",n);
m_size = n;
m_data = new _T[m_size];
m_num = 0;
}
void push_back( _T d )
{
// if ( m_num == m_size )
// {
// re_allocate( m_size*2 );
// }
m_data[m_num] = d ;
m_num++;
}
void push_back( const _T* p, uint len )
{
while ( m_num + len > m_size )
{
re_allocate( m_size*2 );
}
memcpy( m_data+m_num, p, sizeof(_T)*len );
m_num += len;
}
void re_allocate( uint size )
{
if ( size < m_num )
{
return;
}
_T* tmp = new _T[size];
memcpy( tmp, m_data, sizeof(_T)*m_num );
m_size = size;
delete[] m_data;
m_data = tmp;
}
void Sort()
{
if ( m_num < 20 )
{
int k ;
_T tmp;
for ( int i = 0 ; i < m_num-1 ; ++i )
{
k = i ;
for ( int j = i+1 ; j < m_num ; ++j )
if ( m_data[j] < m_data[k] ) k = j ;
if ( k != i )
{
tmp = m_data[i];
m_data[i] = m_data[k];
m_data[k] = tmp;
}
}
}
else sort( m_data, m_data+m_num );
}
void unique()
{
if ( m_num == 0 ) return;
Sort();
uint j = 0;
for ( uint i = 0 ; i < m_num ; ++i )
if ( !(m_data[i] == m_data[j]) )
{
++j;
if ( j != i ) m_data[j] = m_data[i];
}
m_num = j+1;
}
int BinarySearch( _T& data )
{
for ( int x = 0 , y = m_num-1 ; x <= y ; )
{
int p = (x+y)/2;
if ( m_data[p] == data ) return p;
if ( m_data[p] < data ) x = p+1;
else y = p-1;
}
return -1;
}
void clean()
{
m_num = 0;
}
void assign( iVector& t )
{
m_num = t.m_num;
m_size = t.m_size;
delete[] m_data;
m_data = t.m_data;
}
bool remove( _T& x )
{
for ( int l = 0 , r = m_num ; l < r ; )
{
int m = (l+r)/2;
if ( m_data[m] == x )
{
m_num--;
if ( m_num > m ) memmove( m_data+m, m_data+m+1, sizeof(_T)*(m_num-m) );
return true;
}
else if ( m_data[m] < x ) l = m+1;
else r = m;
}
return false;
}
void sorted_insert( _T& x )
{
if ( m_num == 0 )
{
push_back( x );
return;
}
if ( m_num == m_size ) re_allocate( m_size*2 );
int l,r;
for ( l = 0 , r = m_num ; l < r ; )
{
int m = (l+r)/2;
if ( m_data[m] < x ) l = m+1;
else r = m;
}
if ( l < m_num && m_data[l] == x )
{
//printf("Insert Duplicate....\n");
//cout<<x<<endl;
// break;
}
else
{
if ( m_num > l )
{
memmove( m_data+l+1, m_data+l, sizeof(_T)*(m_num-l) );
}
m_num++;
m_data[l] = x;
}
}
bool remove_unsorted( _T& x )
{
for ( int m = 0 ; m < m_num ; ++m )
{
if ( m_data[m] == x )
{
m_num--;
if ( m_num > m ) memcpy( m_data+m, m_data+m+1, sizeof(_T)*(m_num-m) );
return true;
}
}
return false;
}
_T& operator[]( uint i )
{
//if ( i < 0 || i >= m_num )
//{
// printf("iVector [] out of range!!!\n");
//}
return m_data[i];
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//close range check for [] in iVector if release
};
template <typename _T>
struct iMap
{
_T* m_data;
uint m_num;
uint cur;
iVector<uint> occur;
_T nil;
iMap()
{
m_data = NULL;
m_num = 0;
//nil = std::make_pair((long)-9,(long)-9);
//nil = 1073741834;
}
iMap(uint size){
initialize(size);
}
void free_mem()
{
delete[] m_data;
occur.free_mem();
}
void initialize( uint n )
{
occur.re_allocate(n);
occur.clean();
m_num = n;
nil = -9;
if ( m_data != NULL )
delete[] m_data;
m_data = new _T[m_num];
for ( int i = 0 ; i < m_num ; ++i )
m_data[i] = nil;
cur = 0;
}
void clean()
{
for ( int i = 0 ; i < occur.m_num ; ++i ){
m_data[occur[i]] = nil;
}
// occur.clean();
occur.m_num = 0;
cur = 0;
}
//init keys 0-n, value as 0
void init_keys(uint n){
occur.re_allocate(n);
occur.clean();
m_num = n;
nil = -9;
if ( m_data != NULL )
delete[] m_data;
m_data = new _T[m_num];
for ( int i = 0 ; i < m_num ; ++i ){
m_data[i] = 0;
occur.push_back( i );
cur++;
}
}
//reset all values to be zero
void reset_zero_values(){
// for ( int i = 0 ; i < m_num ; ++i )
// m_data[i] = 0.0;
memset( m_data, 0.0, m_num*sizeof(_T) );
}
void reset_one_values(){
for ( int i = 0 ; i < m_num ; ++i )
m_data[i] = 1.0;
// memset( m_data, 0.0, m_num*sizeof(_T) );
}
_T get( uint p )
{
//if ( p < 0 || p >= m_num )
//{
// printf("iMap get out of range!!!\n");
// return -8;
//}
return m_data[p];
}
_T& operator[]( uint p )
{
//if ( i < 0 || i >= m_num )
//{
// printf("iVector [] out of range!!!\n");
//}
return m_data[p];
}
void erase( uint p )
{
//if ( p < 0 || p >= m_num )
//{
// printf("iMap get out of range!!!\n");
//}
m_data[p] = nil;
cur--;
}
bool notexist( uint p )
{
return m_data[p] == nil ;
}
bool exist( uint p )
{
return !(m_data[p] == nil);
}
void insert( uint p , _T d )
{
//if ( p < 0 || p >= m_num )
//{
// printf("iMap insert out of range!!!\n");
//}
if ( m_data[p] == nil )
{
occur.push_back( p );
cur++;
}
m_data[p] = d;
}
void inc( uint p , _T x )
{
if ( m_data[p] == nil ){
insert(p, x);
}
else{
m_data[p] += x;
}
}
void dec( uint p )
{
//if ( m_data[p] == nil )
//{
// printf("dec some unexisted point\n" );
//}
m_data[p]--;
}
//close range check when release!!!!!!!!!!!!!!!!!!!!
};
template <typename _T>
struct myMap
{
_T* m_data;
int* m_keys;
long m_num;
long cur;
_T nil;
myMap(){
m_data = NULL;
m_num = 0;
cur = 0;
}
myMap(long size){
initialize(size);
}
void free_mem(){
delete[] m_data;
delete[] m_keys;
m_num = 0;
cur = 0;
}
void initialize( long n ){
m_num = n;
nil = 0;
if ( m_data != NULL )
delete[] m_data;
if( m_keys != NULL )
delete[] m_keys;
m_data = new _T[m_num];
m_keys = new int[m_num];
for ( long i = 0 ; i < m_num ; ++i )
m_data[i] = nil;
cur = 0;
}
void clean(){
for(long i=0; i<cur; i++){
m_data[m_keys[i]]=nil;
}
cur = 0;
}
_T get( int p ){
return m_data[p];
}
int getid( int p ){
return m_keys[p];
}
_T& operator[]( int p ){
return m_data[p];
}
bool notexist( int p ){
return !m_data[p];
}
void insert( int p , _T d ){
if(!m_data[p]){
m_keys[cur]=p;
cur++;
}
m_data[p] = d;
}
void inc( int p , _T x ){
if (!m_data[p]){
m_keys[cur]=p;
m_data[p] = x;
cur++;
}
else{
m_data[p] += x;
}
}
};
static uint32_t g_seed;
void fastSrand();
uint32_t fastRand();
static uint32_t x_state;
void xorshifinit();
uint32_t xorshift32(void);
| 13,724 | 21.836938 | 131 |
h
|
openalpr
|
openalpr-master/src/bindings/go/openalprgo.h
|
#if defined(_MSC_VER)
// Microsoft
#define OPENALPR_EXPORT __declspec(dllexport)
#else
// do nothing
#define OPENALPR_EXPORT
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Alpr;
OPENALPR_EXPORT Alpr AlprInit(char* country, char* configFile, char* runtimeDir);
OPENALPR_EXPORT void SetDetectRegion(Alpr alpr, int detectRegion);
OPENALPR_EXPORT void SetTopN(Alpr alpr, int topN);
OPENALPR_EXPORT void SetDefaultRegion(Alpr alpr, char* region);
OPENALPR_EXPORT int IsLoaded(Alpr alpr);
OPENALPR_EXPORT void Unload(Alpr alpr);
OPENALPR_EXPORT char* RecognizeByFilePath(Alpr alpr, char* filePath);
OPENALPR_EXPORT char* RecognizeByBlob(Alpr alpr, char* imageBytes, int len);
OPENALPR_EXPORT char* GetVersion();
#ifdef __cplusplus
}
#endif
| 765 | 27.37037 | 82 |
h
|
openalpr
|
openalpr-master/src/bindings/java/com_openalpr_jni_Alpr.h
|
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_openalpr_jni_Alpr */
#ifndef _Included_com_openalpr_jni_Alpr
#define _Included_com_openalpr_jni_Alpr
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_openalpr_jni_Alpr
* Method: initialize
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_initialize
(JNIEnv *, jobject, jstring, jstring, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: dispose
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_dispose
(JNIEnv *, jobject);
/*
* Class: com_openalpr_jni_Alpr
* Method: is_loaded
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_com_openalpr_jni_Alpr_is_1loaded
(JNIEnv *, jobject);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize__Ljava_lang_String_2
(JNIEnv *, jobject, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: ([B)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize___3B
(JNIEnv *, jobject, jbyteArray);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: (JIII)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize__JIII
(JNIEnv *, jobject, jlong, jint, jint, jint);
/*
* Class: com_openalpr_jni_Alpr
* Method: set_default_region
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_set_1default_1region
(JNIEnv *, jobject, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: detect_region
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_detect_1region
(JNIEnv *, jobject, jboolean);
/*
* Class: com_openalpr_jni_Alpr
* Method: set_top_n
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_set_1top_1n
(JNIEnv *, jobject, jint);
/*
* Class: com_openalpr_jni_Alpr
* Method: get_version
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_get_1version
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
| 2,353 | 24.042553 | 91 |
h
|
openalpr
|
openalpr-master/src/daemon/beanstalk.c
|
#include "beanstalk.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <assert.h>
#include <strings.h>
#include <netinet/tcp.h>
#include <inttypes.h>
#include <poll.h>
#define BS_STATUS_IS(message, code) strncmp(message, code, strlen(code)) == 0
#define BS_MESSAGE_NO_BODY 0
#define BS_MESSAGE_HAS_BODY 1
#ifndef BS_READ_CHUNK_SIZE
#define BS_READ_CHUNK_SIZE 4096
#endif
#define DATA_PENDING (errno == EAGAIN || errno == EWOULDBLOCK)
const char *bs_status_verbose[] = {
"Success",
"Operation failed",
"Expected CRLF",
"Job too big",
"Queue draining",
"Timed out",
"Not found",
"Deadline soon",
"Buried",
"Not ignored"
};
const char bs_resp_using[] = "USING";
const char bs_resp_watching[] = "WATCHING";
const char bs_resp_inserted[] = "INSERTED";
const char bs_resp_buried[] = "BURIED";
const char bs_resp_expected_crlf[] = "EXPECTED_CRLF";
const char bs_resp_job_too_big[] = "JOB_TOO_BIG";
const char bs_resp_draining[] = "DRAINING";
const char bs_resp_reserved[] = "RESERVED";
const char bs_resp_deadline_soon[] = "DEADLINE_SOON";
const char bs_resp_timed_out[] = "TIMED_OUT";
const char bs_resp_deleted[] = "DELETED";
const char bs_resp_not_found[] = "NOT_FOUND";
const char bs_resp_released[] = "RELEASED";
const char bs_resp_touched[] = "TOUCHED";
const char bs_resp_not_ignored[] = "NOT_IGNORED";
const char bs_resp_found[] = "FOUND";
const char bs_resp_kicked[] = "KICKED";
const char bs_resp_ok[] = "OK";
const char* bs_status_text(int code) {
unsigned int cindex = (unsigned int) abs(code);
return (cindex > sizeof(bs_status_verbose) / sizeof(char*)) ? 0 : bs_status_verbose[cindex];
}
int bs_resolve_address(char *host, int port, struct sockaddr_in *server) {
char service[64];
struct addrinfo *addr, *rec;
snprintf(service, 64, "%d", port);
if (getaddrinfo(host, service, 0, &addr) != 0)
return BS_STATUS_FAIL;
for (rec = addr; rec != 0; rec = rec->ai_next) {
if (rec->ai_family == AF_INET) {
memcpy(server, rec->ai_addr, sizeof(*server));
break;
}
}
freeaddrinfo(addr);
return BS_STATUS_OK;
}
int bs_connect(char *host, int port) {
int fd, state = 1;
struct sockaddr_in server;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0 || bs_resolve_address(host, port, &server) < 0)
return BS_STATUS_FAIL;
if (connect(fd, (struct sockaddr*)&server, sizeof(server)) != 0) {
close(fd);
return BS_STATUS_FAIL;
}
/* disable nagle - we buffer in the application layer */
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &state, sizeof(state));
return fd;
}
int bs_connect_with_timeout(char *host, int port, float secs) {
struct sockaddr_in server;
int fd, res, option, state = 1;
socklen_t option_length;
struct pollfd pfd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0 || bs_resolve_address(host, port, &server) < 0)
return BS_STATUS_FAIL;
// Set non-blocking
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, NULL) | O_NONBLOCK);
res = connect(fd, (struct sockaddr*)&server, sizeof(server));
if (res < 0) {
if (errno == EINPROGRESS) {
// Init poll structure
pfd.fd = fd;
pfd.events = POLLOUT;
if (poll(&pfd, 1, (int)(secs*1000)) > 0) {
option_length = sizeof(int);
getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)(&option), &option_length);
if (option) {
close(fd);
return BS_STATUS_FAIL;
}
} else {
close(fd);
return BS_STATUS_FAIL;
}
} else {
close(fd);
return BS_STATUS_FAIL;
}
}
// Set to blocking mode
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, NULL) & ~(O_NONBLOCK));
/* disable nagle - we buffer in the application layer */
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &state, sizeof(state));
return fd;
}
int bs_disconnect(int fd) {
close(fd);
return BS_STATUS_OK;
}
void bs_free_message(BSM* m) {
if (m->status)
free(m->status);
if (m->data)
free(m->data);
free(m);
}
void bs_free_job(BSJ *job) {
if (job->data)
free(job->data);
free(job);
}
// optional polling
bs_poll_function bs_poll = 0;
void bs_start_polling(bs_poll_function f) {
bs_poll = f;
}
void bs_reset_polling() {
bs_poll = 0;
}
BSM* bs_recv_message(int fd, int expect_data) {
char *token, *data;
size_t bytes, data_size, status_size, status_max = 512, expect_data_bytes = 0;
ssize_t ret;
BSM *message = (BSM*)calloc(1, sizeof(BSM));
if (!message) return 0;
message->status = (char*)calloc(1, status_max);
if (!message->status) {
bs_free_message(message);
return 0;
}
// poll until ready to read
if (bs_poll) bs_poll(1, fd);
ret = recv(fd, message->status, status_max - 1, 0);
if (ret < 0) {
bs_free_message(message);
return 0;
} else {
bytes = (size_t) ret;
}
token = strstr(message->status, "\r\n");
if (!token) {
bs_free_message(message);
return 0;
}
*token = 0;
status_size = (size_t) (token - message->status);
if (expect_data) {
token = rindex(message->status, ' ');
expect_data_bytes = token ? strtoul(token + 1, NULL, 10) : 0;
}
if (!expect_data || expect_data_bytes == 0)
return message;
message->size = bytes - status_size - 2;
data_size = message->size > BS_READ_CHUNK_SIZE ? message->size + BS_READ_CHUNK_SIZE : BS_READ_CHUNK_SIZE;
message->data = (char*)malloc(data_size);
if (!message->data) {
bs_free_message(message);
return 0;
}
memcpy(message->data, message->status + status_size + 2, message->size);
data = message->data + message->size;
// already read the body along with status, all good.
if ((expect_data_bytes + 2) <= message->size) {
message->size = expect_data_bytes;
return message;
}
while (1) {
// poll until ready to read.
if (bs_poll) bs_poll(1, fd);
ret = recv(fd, data, data_size - message->size, 0);
if (ret < 0) {
if (bs_poll && DATA_PENDING)
continue;
else {
bs_free_message(message);
return 0;
}
} else {
bytes = (size_t) ret;
}
// doneski, we have read enough bytes + \r\n
if (message->size + bytes >= expect_data_bytes + 2) {
message->size = expect_data_bytes;
break;
}
data_size += BS_READ_CHUNK_SIZE;
message->size += bytes;
message->data = (char*)realloc(message->data, data_size);
if (!message->data) {
bs_free_message(message);
return 0;
}
// move ahead pointer for reading more.
data = message->data + message->size;
}
return message;
}
ssize_t bs_send_message(int fd, char *message, size_t size) {
// poll until ready to write.
if (bs_poll) bs_poll(2, fd);
return send(fd, message, size, bs_poll ? MSG_DONTWAIT : 0);
}
typedef struct bs_message_packet {
char *data;
size_t offset;
size_t size;
} BSMP;
BSMP* bs_message_packet_new(size_t bytes) {
BSMP *packet = (BSMP*)malloc(sizeof(BSMP));
assert(packet);
packet->data = (char*)malloc(bytes);
assert(packet->data);
packet->offset = 0;
packet->size = bytes;
return packet;
}
void bs_message_packet_append(BSMP *packet, char *data, size_t bytes) {
if (packet->offset + bytes > packet->size) {
packet->data = (char*)realloc(packet->data, packet->size + bytes);
assert(packet->data);
packet->size += bytes;
}
memcpy(packet->data + packet->offset, data, bytes);
packet->offset += bytes;
}
void bs_message_packet_free(BSMP *packet) {
free(packet->data);
free(packet);
}
#define BS_SEND(fd, command, size) { \
if (bs_send_message(fd, command, size) < 0) \
return BS_STATUS_FAIL; \
}
#define BS_CHECK_MESSAGE(message) { \
if (!message) \
return BS_STATUS_FAIL; \
}
#define BS_RETURN_OK_WHEN(message, okstatus) { \
if (BS_STATUS_IS(message->status, okstatus)) { \
bs_free_message(message); \
return BS_STATUS_OK; \
} \
}
#define BS_RETURN_FAIL_WHEN(message, nokstatus, nokcode) { \
if (BS_STATUS_IS(message->status, nokstatus)) { \
bs_free_message(message); \
return nokcode; \
} \
}
#define BS_RETURN_INVALID(message) { \
bs_free_message(message); \
return BS_STATUS_FAIL; \
}
int bs_use(int fd, char *tube) {
BSM *message;
char command[1024];
snprintf(command, 1024, "use %s\r\n", tube);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_using);
BS_RETURN_INVALID(message);
}
int bs_watch(int fd, char *tube) {
BSM *message;
char command[1024];
snprintf(command, 1024, "watch %s\r\n", tube);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_watching);
BS_RETURN_INVALID(message);
}
int bs_ignore(int fd, char *tube) {
BSM *message;
char command[1024];
snprintf(command, 1024, "ignore %s\r\n", tube);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_watching);
BS_RETURN_INVALID(message);
}
int64_t bs_put(int fd, uint32_t priority, uint32_t delay, uint32_t ttr, char *data, size_t bytes) {
int64_t id;
BSMP *packet;
BSM *message;
char command[1024];
size_t command_bytes;
snprintf(command, 1024, "put %"PRIu32" %"PRIu32" %"PRIu32" %lu\r\n", priority, delay, ttr, bytes);
command_bytes = strlen(command);
packet = bs_message_packet_new(command_bytes + bytes + 3);
bs_message_packet_append(packet, command, command_bytes);
bs_message_packet_append(packet, data, bytes);
bs_message_packet_append(packet, "\r\n", 2);
// Can't use BS_SEND here, allocated memory needs to
// be cleared on error
int ret_code = bs_send_message(fd, packet->data, packet->offset);
bs_message_packet_free(packet);
if (ret_code <0) {
return BS_STATUS_FAIL;
}
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
if (BS_STATUS_IS(message->status, bs_resp_inserted)) {
id = strtoll(message->status + strlen(bs_resp_inserted) + 1, NULL, 10);
bs_free_message(message);
return id;
}
if (BS_STATUS_IS(message->status, bs_resp_buried)) {
id = strtoll(message->status + strlen(bs_resp_buried) + 1, NULL, 10);
bs_free_message(message);
return id;
}
BS_RETURN_FAIL_WHEN(message, bs_resp_expected_crlf, BS_STATUS_EXPECTED_CRLF);
BS_RETURN_FAIL_WHEN(message, bs_resp_job_too_big, BS_STATUS_JOB_TOO_BIG);
BS_RETURN_FAIL_WHEN(message, bs_resp_draining, BS_STATUS_DRAINING);
BS_RETURN_INVALID(message);
}
int bs_delete(int fd, int64_t job) {
BSM *message;
char command[512];
snprintf(command, 512, "delete %"PRId64"\r\n", job);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_deleted);
BS_RETURN_FAIL_WHEN(message, bs_resp_not_found, BS_STATUS_NOT_FOUND);
BS_RETURN_INVALID(message);
}
int bs_reserve_job(int fd, char *command, BSJ **result) {
BSJ *job;
BSM *message;
// XXX: debug
// struct timeval start, end;
// gettimeofday(&start, 0);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_HAS_BODY);
BS_CHECK_MESSAGE(message);
if (BS_STATUS_IS(message->status, bs_resp_reserved)) {
*result = job = (BSJ*)malloc(sizeof(BSJ));
if (!job) {
bs_free_message(message);
return BS_STATUS_FAIL;
}
sscanf(message->status + strlen(bs_resp_reserved) + 1, "%"PRId64" %lu", &job->id, &job->size);
job->data = message->data;
message->data = 0;
bs_free_message(message);
// XXX: debug
// gettimeofday(&end, 0);
// printf("elapsed: %lu\n", (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec));
return BS_STATUS_OK;
}
// i don't think we'll ever hit this status code here.
BS_RETURN_FAIL_WHEN(message, bs_resp_timed_out, BS_STATUS_TIMED_OUT);
BS_RETURN_FAIL_WHEN(message, bs_resp_deadline_soon, BS_STATUS_DEADLINE_SOON);
BS_RETURN_INVALID(message);
}
int bs_reserve(int fd, BSJ **result) {
char *command = "reserve\r\n";
return bs_reserve_job(fd, command, result);
}
int bs_reserve_with_timeout(int fd, uint32_t ttl, BSJ **result) {
char command[512];
snprintf(command, 512, "reserve-with-timeout %"PRIu32"\r\n", ttl);
return bs_reserve_job(fd, command, result);
}
int bs_release(int fd, int64_t id, uint32_t priority, uint32_t delay) {
BSM *message;
char command[512];
snprintf(command, 512, "release %"PRId64" %"PRIu32" %"PRIu32"\r\n", id, priority, delay);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_released);
BS_RETURN_FAIL_WHEN(message, bs_resp_buried, BS_STATUS_BURIED);
BS_RETURN_FAIL_WHEN(message, bs_resp_not_found, BS_STATUS_NOT_FOUND);
BS_RETURN_INVALID(message);
}
int bs_bury(int fd, int64_t id, uint32_t priority) {
BSM *message;
char command[512];
snprintf(command, 512, "bury %"PRId64" %"PRIu32"\r\n", id, priority);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_buried);
BS_RETURN_FAIL_WHEN(message, bs_resp_not_found, BS_STATUS_NOT_FOUND);
BS_RETURN_INVALID(message);
}
int bs_touch(int fd, int64_t id) {
BSM *message;
char command[512];
snprintf(command, 512, "touch %"PRId64"\r\n", id);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_touched);
BS_RETURN_FAIL_WHEN(message, bs_resp_not_found, BS_STATUS_NOT_FOUND);
BS_RETURN_INVALID(message);
}
int bs_peek_job(int fd, char *command, BSJ **result) {
BSJ *job;
BSM *message;
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_HAS_BODY);
BS_CHECK_MESSAGE(message);
if (BS_STATUS_IS(message->status, bs_resp_found)) {
*result = job = (BSJ*)malloc(sizeof(BSJ));
if (!job) {
bs_free_message(message);
return BS_STATUS_FAIL;
}
sscanf(message->status + strlen(bs_resp_found) + 1, "%"PRId64" %lu", &job->id, &job->size);
job->data = message->data;
message->data = 0;
bs_free_message(message);
return BS_STATUS_OK;
}
BS_RETURN_FAIL_WHEN(message, bs_resp_not_found, BS_STATUS_NOT_FOUND);
BS_RETURN_INVALID(message);
}
int bs_peek(int fd, int64_t id, BSJ **job) {
char command[512];
snprintf(command, 512, "peek %"PRId64"\r\n", id);
return bs_peek_job(fd, command, job);
}
int bs_peek_ready(int fd, BSJ **job) {
return bs_peek_job(fd, "peek-ready\r\n", job);
}
int bs_peek_delayed(int fd, BSJ **job) {
return bs_peek_job(fd, "peek-delayed\r\n", job);
}
int bs_peek_buried(int fd, BSJ **job) {
return bs_peek_job(fd, "peek-buried\r\n", job);
}
int bs_kick(int fd, int bound) {
BSM *message;
char command[512];
snprintf(command, 512, "kick %d\r\n", bound);
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
BS_CHECK_MESSAGE(message);
BS_RETURN_OK_WHEN(message, bs_resp_kicked);
BS_RETURN_INVALID(message);
}
int bs_list_tube_used(int fd, char **tube) {
BSM *message;
char command[64];
snprintf(command, 64, "list-tube-used\r\n");
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_NO_BODY);
if (BS_STATUS_IS(message->status, bs_resp_using)) {
*tube = (char*)calloc(1, strlen(message->status) - strlen(bs_resp_using) + 1);
strcpy(*tube, message->status + strlen(bs_resp_using) + 1);
bs_free_message(message);
return BS_STATUS_OK;
}
BS_RETURN_INVALID(message);
}
int bs_get_info(int fd, char *command, char **yaml) {
BSM *message;
size_t size;
BS_SEND(fd, command, strlen(command));
message = bs_recv_message(fd, BS_MESSAGE_HAS_BODY);
BS_CHECK_MESSAGE(message);
if (BS_STATUS_IS(message->status, bs_resp_ok)) {
sscanf(message->status + strlen(bs_resp_ok) + 1, "%lu", &size);
*yaml = message->data;
(*yaml)[size] = 0;
message->data = 0;
bs_free_message(message);
return BS_STATUS_OK;
}
BS_RETURN_INVALID(message);
}
int bs_list_tubes(int fd, char **yaml) {
char command[64];
snprintf(command, 64, "list-tubes\r\n");
return bs_get_info(fd, command, yaml);
}
int bs_list_tubes_watched(int fd, char **yaml) {
char command[64];
snprintf(command, 64, "list-tubes-watched\r\n");
return bs_get_info(fd, command, yaml);
}
int bs_stats(int fd, char **yaml) {
char command[64];
snprintf(command, 64, "stats\r\n");
return bs_get_info(fd, command, yaml);
}
int bs_stats_job(int fd, int64_t id, char **yaml) {
char command[128];
snprintf(command, 128, "stats-job %"PRId64"\r\n", id);
return bs_get_info(fd, command, yaml);
}
int bs_stats_tube(int fd, char *tube, char **yaml) {
char command[512];
snprintf(command, 512, "stats-tube %s\r\n", tube);
return bs_get_info(fd, command, yaml);
}
void bs_version(int *major, int *minor, int *patch)
{
*major = BS_MAJOR_VERSION;
*minor = BS_MINOR_VERSION;
*patch = BS_PATCH_VERSION;
}
| 19,039 | 28.337442 | 114 |
c
|
openalpr
|
openalpr-master/src/daemon/beanstalk.h
|
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/fcntl.h>
#define BS_MAJOR_VERSION 1
#define BS_MINOR_VERSION 2
#define BS_PATCH_VERSION 0
#define BS_STATUS_OK 0
#define BS_STATUS_FAIL -1
#define BS_STATUS_EXPECTED_CRLF -2
#define BS_STATUS_JOB_TOO_BIG -3
#define BS_STATUS_DRAINING -4
#define BS_STATUS_TIMED_OUT -5
#define BS_STATUS_NOT_FOUND -6
#define BS_STATUS_DEADLINE_SOON -7
#define BS_STATUS_BURIED -8
#define BS_STATUS_NOT_IGNORED -9
#ifdef __cplusplus
extern "C" {
#endif
typedef struct bs_message {
char *data;
char *status;
size_t size;
} BSM;
typedef struct bs_job {
int64_t id;
char *data;
size_t size;
} BSJ;
// optional polling call, returns 1 if the socket is ready of the rw operation specified.
// rw: 1 => read, 2 => write, 3 => read/write
// fd: file descriptor of the socket
typedef int (*bs_poll_function)(int rw, int fd);
/* Handle DSO symbol visibility - Stolen from zmq.h */
#if defined _WIN32
# if defined DLL_EXPORT
# define BSC_EXPORT __declspec(dllexport)
# else
# define BSC_EXPORT __declspec(dllimport)
# endif
#else
# if defined __SUNPRO_C || defined __SUNPRO_CC
# define BSC_EXPORT __global
# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER
# define BSC_EXPORT __attribute__ ((visibility("default")))
# else
# define BSC_EXPORT
# endif
#endif
// export version
BSC_EXPORT void bs_version(int *major, int *minor, int *patch);
// polling setup
BSC_EXPORT void bs_start_polling(bs_poll_function f);
BSC_EXPORT void bs_reset_polling(void);
// returns a descriptive text of the error code.
BSC_EXPORT const char* bs_status_text(int code);
BSC_EXPORT void bs_free_message(BSM* m);
BSC_EXPORT void bs_free_job(BSJ *job);
// returns socket descriptor or BS_STATUS_FAIL
BSC_EXPORT int bs_connect(char *host, int port);
BSC_EXPORT int bs_connect_with_timeout(char *host, int port, float secs);
// returns job id or one of the negative failure codes.
BSC_EXPORT int64_t bs_put(int fd, uint32_t priority, uint32_t delay, uint32_t ttr, char *data, size_t bytes);
// rest return BS_STATUS_OK or one of the failure codes.
BSC_EXPORT int bs_disconnect(int fd);
BSC_EXPORT int bs_use(int fd, char *tube);
BSC_EXPORT int bs_watch(int fd, char *tube);
BSC_EXPORT int bs_ignore(int fd, char *tube);
BSC_EXPORT int bs_delete(int fd, int64_t job);
BSC_EXPORT int bs_reserve(int fd, BSJ **job);
BSC_EXPORT int bs_reserve_with_timeout(int fd, uint32_t ttl, BSJ **job);
BSC_EXPORT int bs_release(int fd, int64_t id, uint32_t priority, uint32_t delay);
BSC_EXPORT int bs_bury(int fd, int64_t id, uint32_t priority);
BSC_EXPORT int bs_touch(int fd, int64_t id);
BSC_EXPORT int bs_peek(int fd, int64_t id, BSJ **job);
BSC_EXPORT int bs_peek_ready(int fd, BSJ **job);
BSC_EXPORT int bs_peek_delayed(int fd, BSJ **job);
BSC_EXPORT int bs_peek_buried(int fd, BSJ **job);
BSC_EXPORT int bs_kick(int fd, int bound);
BSC_EXPORT int bs_list_tube_used(int fd, char **tube);
BSC_EXPORT int bs_list_tubes(int fd, char **yaml);
BSC_EXPORT int bs_list_tubes_watched(int fd, char **yaml);
BSC_EXPORT int bs_stats(int fd, char **yaml);
BSC_EXPORT int bs_stats_job(int fd, int64_t id, char **yaml);
BSC_EXPORT int bs_stats_tube(int fd, char *tube, char **yaml);
#ifdef __cplusplus
}
#endif
| 3,475 | 29.761062 | 109 |
h
|
openalpr
|
openalpr-master/src/misc_utilities/benchmarks/endtoendtest.h
|
#ifndef OPENALPR_ENDTOENDTEST_H
#define OPENALPR_ENDTOENDTEST_H
#include <string>
#include <vector>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "detection/detector_types.h"
#include "prewarp.h"
#include "alpr_impl.h"
#include "benchmark_utils.h"
class EndToEndTest
{
public:
EndToEndTest(std::string inputDir, std::string outputDir);
void runTest(std::string country, std::vector<std::string> files);
private:
bool rectMatches(cv::Rect actualPlate, alpr::PlateRegion candidate);
int totalRectCount(alpr::PlateRegion rootCandidate);
std::string inputDir;
std::string outputDir;
};
class EndToEndBenchmarkResult {
public:
EndToEndBenchmarkResult()
{
this->imageName = "";
this->detectedPlate = false;
this->topResultCorrect = false;
this->top10ResultCorrect = false;
this->detectionFalsePositives = 0;
this->resultsFalsePositives = 0;
}
std::string imageName;
bool detectedPlate;
bool topResultCorrect;
bool top10ResultCorrect;
int detectionFalsePositives;
int resultsFalsePositives;
};
#endif //OPENALPR_ENDTOENDTEST_H
| 1,177 | 21.653846 | 72 |
h
|
openalpr
|
openalpr-master/src/openalpr/TRexpp.h
|
#ifndef _TREXPP_H_
#define _TREXPP_H_
/***************************************************************
T-Rex a tiny regular expression library
Copyright (C) 2003-2004 Alberto Demichelis
This software is provided 'as-is', without any express
or implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for
any purpose, including commercial applications, and to alter
it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
****************************************************************/
extern "C" {
#include "trex.h"
}
struct TRexParseException
{
TRexParseException(const TRexChar *c):desc(c) {} const TRexChar *desc;
};
class TRexpp
{
public:
TRexpp()
{
_exp = (TRex *)0;
}
~TRexpp()
{
CleanUp();
}
// compiles a regular expression
void Compile(const TRexChar *pattern)
{
const TRexChar *error;
CleanUp();
if(!(_exp = trex_compile(pattern,&error)))
throw TRexParseException(error);
}
// return true if the given text match the expression
bool Match(const TRexChar* text)
{
return _exp?(trex_match(_exp,text) != 0):false;
}
// Searches for the first match of the expression in a zero terminated string
bool Search(const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
{
return _exp?(trex_search(_exp,text,out_begin,out_end) != 0):false;
}
// Searches for the first match of the expression in a string sarting at text_begin and ending at text_end
bool SearchRange(const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
{
return _exp?(trex_searchrange(_exp,text_begin,text_end,out_begin,out_end) != 0):false;
}
bool GetSubExp(int n, const TRexChar** out_begin, int *out_len)
{
TRexMatch match;
TRexBool res = _exp?(trex_getsubexp(_exp,n,&match)):TRex_False;
if(res)
{
*out_begin = match.begin;
*out_len = match.len;
return true;
}
return false;
}
int GetSubExpCount()
{
return _exp?trex_getsubexpcount(_exp):0;
}
private:
void CleanUp()
{
if(_exp) trex_free(_exp);
_exp = (TRex *)0;
}
TRex *_exp;
};
#endif //_TREXPP_H_
| 2,865 | 28.244898 | 126 |
h
|
openalpr
|
openalpr-master/src/openalpr/binarize_wolf.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_BINARIZEWOLF_H
#define OPENALPR_BINARIZEWOLF_H
#include "support/filesystem.h"
#include "opencv2/opencv.hpp"
namespace alpr
{
enum NiblackVersion
{
NIBLACK=0,
SAUVOLA,
WOLFJOLION,
};
#define BINARIZEWOLF_VERSION "2.3 (February 26th, 2013)"
#define BINARIZEWOLF_DEFAULTDR 128
#define uget(x,y) at<unsigned char>(y,x)
#define uset(x,y,v) at<unsigned char>(y,x)=v;
#define fget(x,y) at<float>(y,x)
#define fset(x,y,v) at<float>(y,x)=v;
void NiblackSauvolaWolfJolion (cv::Mat im, cv::Mat output, NiblackVersion version,
int winx, int winy, double k, double dR=BINARIZEWOLF_DEFAULTDR);
}
#endif // OPENALPR_BINARIZEWOLF_H
| 1,484 | 28.117647 | 97 |
h
|
openalpr
|
openalpr-master/src/openalpr/colorfilter.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_COLORFILTER_H
#define OPENALPR_COLORFILTER_H
#include <iomanip>
#include "opencv2/imgproc/imgproc.hpp"
#include "constants.h"
#include "utility.h"
#include "config.h"
namespace alpr
{
class ColorFilter
{
public:
ColorFilter(cv::Mat image, cv::Mat characterMask, Config* config);
virtual ~ColorFilter();
cv::Mat colorMask;
private:
Config* config;
bool debug;
cv::Mat hsv;
cv::Mat charMask;
bool grayscale;
void preprocessImage();
void findCharColors();
bool imageIsGrayscale(cv::Mat image);
int getMajorityOpinion(std::vector<float> values, float minPercentAgreement, float maxValDifference);
};
}
#endif // OPENALPR_COLORFILTER_H
| 1,517 | 23.885246 | 107 |
h
|
openalpr
|
openalpr-master/src/openalpr/config.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_CONFIG_H
#define OPENALPR_CONFIG_H
#include "constants.h"
#include <string>
#include <vector>
namespace alpr
{
class Config
{
public:
Config(const std::string country, const std::string config_file = "", const std::string runtime_dir = "");
virtual ~Config();
bool load_countries(const std::string countries);
bool loaded;
std::string config_file_path;
std::string country;
int detector;
float detection_iteration_increase;
int detectionStrictness;
float maxPlateWidthPercent;
float maxPlateHeightPercent;
int maxDetectionInputWidth;
int maxDetectionInputHeight;
float contrastDetectionThreshold;
bool skipDetection;
std::string detection_mask_image;
int analysis_count;
bool auto_invert;
bool always_invert;
std::string prewarp;
int maxPlateAngleDegrees;
float minPlateSizeWidthPx;
float minPlateSizeHeightPx;
bool multiline;
float plateWidthMM;
float plateHeightMM;
std::vector<float> charHeightMM;
std::vector<float> charWidthMM;
float avgCharHeightMM;
float avgCharWidthMM;
float charWhitespaceTopMM;
float charWhitespaceBotMM;
float charWhitespaceBetweenLinesMM;
int templateWidthPx;
int templateHeightPx;
int ocrImageWidthPx;
int ocrImageHeightPx;
int stateIdImageWidthPx;
int stateIdimageHeightPx;
float charAnalysisMinPercent;
float charAnalysisHeightRange;
float charAnalysisHeightStepSize;
int charAnalysisNumSteps;
float plateLinesSensitivityVertical;
float plateLinesSensitivityHorizontal;
float segmentationMinSpeckleHeightPercent;
int segmentationMinBoxWidthPx;
float segmentationMinCharHeightPercent;
float segmentationMaxCharWidthvsAverage;
std::string detectorFile;
std::string ocrLanguage;
int ocrMinFontSize;
bool mustMatchPattern;
float postProcessMinConfidence;
float postProcessConfidenceSkipLevel;
unsigned int postProcessMinCharacters;
unsigned int postProcessMaxCharacters;
std::string postProcessRegexLetters;
std::string postProcessRegexNumbers;
bool debugGeneral;
bool debugTiming;
bool debugPrewarp;
bool debugDetector;
bool debugStateId;
bool debugPlateLines;
bool debugPlateCorners;
bool debugCharSegmenter;
bool debugCharAnalysis;
bool debugColorFiler;
bool debugOcr;
bool debugPostProcess;
bool debugShowImages;
bool debugPauseOnFrame;
void setDebug(bool value);
std::string getKeypointsRuntimeDir();
std::string getCascadeRuntimeDir();
std::string getPostProcessRuntimeDir();
std::string getTessdataPrefix();
std::string runtimeBaseDir;
std::vector<std::string> loaded_countries;
bool setCountry(std::string country);
private:
float ocrImagePercent;
float stateIdImagePercent;
std::vector<std::string> parse_country_string(std::string countries);
bool country_is_loaded(std::string country);
void loadCommonValues(std::string configFile);
void loadCountryValues(std::string configFile, std::string country);
};
enum DETECTOR_TYPE
{
DETECTOR_LBP_CPU=0,
DETECTOR_LBP_GPU=1,
DETECTOR_MORPH_CPU=2,
DETECTOR_LBP_OPENCL=3
};
}
#endif // OPENALPR_CONFIG_H
| 4,353 | 23.324022 | 112 |
h
|
openalpr
|
openalpr-master/src/openalpr/config_helper.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_CONFIG_HELPER_H
#define OPENALPR_CONFIG_HELPER_H
#include "simpleini/simpleini.h"
#include <string>
#include <vector>
namespace alpr
{
bool hasValue(CSimpleIniA* ini, std::string section, std::string key);
int getInt(CSimpleIniA* ini, std::string section, std::string key, int defaultValue);
float getFloat(CSimpleIniA* ini, std::string section, std::string key, float defaultValue);
std::string getString(CSimpleIniA* ini, std::string section, std::string key, std::string defaultValue);
bool getBoolean(CSimpleIniA* ini, std::string section, std::string key, bool defaultValue);
std::vector<float> getAllFloats(CSimpleIniA* ini, std::string section, std::string key);
// Checks the ini objects in the order they are placed in the vector
// e.g., second ini object overrides the first if they both have the value
int getInt(CSimpleIniA* ini, CSimpleIniA* defaultIni, std::string section, std::string key, int defaultValue);
float getFloat(CSimpleIniA* ini, CSimpleIniA* defaultIni, std::string section, std::string key, float defaultValue);
std::string getString(CSimpleIniA* ini, CSimpleIniA* defaultIni, std::string section, std::string key, std::string defaultValue);
bool getBoolean(CSimpleIniA* ini, CSimpleIniA* defaultIni, std::string section, std::string key, bool defaultValue);
}
#endif /* CONFIG_HELPER_H */
| 2,147 | 42.836735 | 131 |
h
|
openalpr
|
openalpr-master/src/openalpr/constants.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_CONSTANTS_H
#define OPENALPR_CONSTANTS_H
#define RUNTIME_DIR "/runtime_data"
#define CONFIG_FILE "/openalpr.conf"
#define KEYPOINTS_DIR "/keypoints"
#define CASCADE_DIR "/region/"
#define POSTPROCESS_DIR "/postprocess"
#define DEFAULT_SHARE_DIR INSTALL_PREFIX "/share/openalpr"
#define DEFAULT_RUNTIME_DATA_DIR DEFAULT_SHARE_DIR "/runtime_data"
#define CONFIG_FILE_TEMPLATE_LOCATION DEFAULT_SHARE_DIR "/config/openalpr.defaults.conf"
#ifndef DEFAULT_CONFIG_FILE
#define DEFAULT_CONFIG_FILE "/etc/openalpr/openalpr.conf"
#endif
#define ENV_VARIABLE_CONFIG_FILE "OPENALPR_CONFIG_FILE"
#endif // OPENALPR_CONSTANTS_H
| 1,423 | 33.731707 | 89 |
h
|
openalpr
|
openalpr-master/src/openalpr/motiondetector.h
|
#ifndef OPENALPR_MOTIONDETECTOR_H
#define OPENALPR_MOTIONDETECTOR_H
#include "opencv2/opencv.hpp"
#include "utility.h"
namespace alpr
{
class MotionDetector
{
private: cv::Ptr<cv::BackgroundSubtractor> pMOG2; //MOG2 Background subtractor
private: cv::Mat fgMaskMOG2;
public:
MotionDetector();
virtual ~MotionDetector();
void ResetMotionDetection(cv::Mat* frame);
cv::Rect MotionDetect(cv::Mat* frame);
};
}
#endif // OPENALPR_MOTIONDETECTOR_H
| 511 | 21.26087 | 84 |
h
|
openalpr
|
openalpr-master/src/openalpr/result_aggregator.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_RESULTAGGREGATOR_H
#define OPENALPR_RESULTAGGREGATOR_H
#include "alpr_impl.h"
#include "prewarp.h"
// Runs the analysis for multiple training sets, and aggregates the results into the best matches
struct PlateShapeInfo
{
cv::Point2f center;
float area;
int max_width;
int max_height;
};
namespace alpr
{
enum ResultMergeStrategy
{
MERGE_COMBINE, // Used when running an analysis multiple times for accuracy improvement. Merges results together
MERGE_PICK_BEST // Used when analyzing multiple countries. Chooses results from one country or the other
};
struct ResultPlateScore
{
AlprPlate plate;
float score_total;
int count;
};
struct ResultRegionScore
{
std::string region;
float confidence;
};
class ResultAggregator
{
public:
ResultAggregator(ResultMergeStrategy merge_strategy, int topn, Config* config);
virtual ~ResultAggregator();
void addResults(AlprFullDetails full_results);
AlprFullDetails getAggregateResults();
cv::Mat applyImperceptibleChange(cv::Mat image, int index);
private:
int topn;
PreWarp* prewarp;
Config* config;
std::vector<AlprFullDetails> all_results;
PlateShapeInfo getShapeInfo(AlprPlateResult plate);
ResultMergeStrategy merge_strategy;
ResultRegionScore findBestRegion(std::vector<AlprPlateResult> cluster);
std::vector<std::vector<AlprPlateResult> > findClusters();
int overlaps(AlprPlateResult plate, std::vector<std::vector<AlprPlateResult> > clusters);
};
}
#endif //OPENALPR_RESULTAGGREGATOR_H
| 2,391 | 24.446809 | 118 |
h
|
openalpr
|
openalpr-master/src/openalpr/transformation.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_TRANSFORMATION_H
#define OPENALPR_TRANSFORMATION_H
#include "opencv2/imgproc/imgproc.hpp"
#include "utility.h"
namespace alpr
{
class Transformation {
public:
Transformation(cv::Mat bigImage, cv::Mat smallImage, cv::Rect regionInBigImage);
virtual ~Transformation();
std::vector<cv::Point2f> transformSmallPointsToBigImage(std::vector<cv::Point> points);
std::vector<cv::Point2f> transformSmallPointsToBigImage(std::vector<cv::Point2f> points);
cv::Mat getTransformationMatrix(std::vector<cv::Point2f> corners, cv::Size outputImageSize);
cv::Mat getTransformationMatrix(std::vector<cv::Point2f> corners, std::vector<cv::Point2f> outputCorners);
cv::Mat crop(cv::Size outputImageSize, cv::Mat transformationMatrix);
std::vector<cv::Point2f> remapSmallPointstoCrop(std::vector<cv::Point> smallPoints, cv::Mat transformationMatrix);
std::vector<cv::Point2f> remapSmallPointstoCrop(std::vector<cv::Point2f> smallPoints, cv::Mat transformationMatrix);
cv::Size getCropSize(std::vector<cv::Point2f> areaCorners, cv::Size targetSize);
private:
cv::Mat bigImage;
cv::Mat smallImage;
cv::Rect regionInBigImage;
};
}
#endif /* OPENALPR_TRANSFORMATION_H */
| 2,003 | 34.157895 | 120 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detector.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_REGIONDETECTOR_H
#define OPENALPR_REGIONDETECTOR_H
#include <string>
#include <vector>
#include "utility.h"
#include "detector_types.h"
#include "support/timing.h"
#include "constants.h"
#include "detectormask.h"
#include "prewarp.h"
namespace alpr
{
class Detector
{
public:
Detector(Config* config, PreWarp* prewarp);
virtual ~Detector();
bool isLoaded();
std::vector<PlateRegion> detect(cv::Mat frame);
std::vector<PlateRegion> detect(cv::Mat frame, std::vector<cv::Rect> regionsOfInterest);
virtual std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size)=0;
void setMask(cv::Mat mask);
protected:
Config* config;
bool loaded;
DetectorMask detector_mask;
std::string get_detector_file();
float computeScaleFactor(int width, int height);
std::vector<PlateRegion> aggregateRegions(std::vector<cv::Rect> regions);
};
}
#endif // OPENALPR_REGIONDETECTOR_H
| 1,826 | 24.027397 | 115 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detector_types.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTOR_TYPES_H
#define OPENALPR_DETECTOR_TYPES_H
namespace alpr
{
struct PlateRegion
{
cv::Rect rect;
std::vector<PlateRegion> children;
};
}
#endif /* OPENALPR_DETECTOR_TYPES_H */
| 990 | 27.314286 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectorcpu.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORCPU_H
#define OPENALPR_DETECTORCPU_H
#include <vector>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#include "detector.h"
namespace alpr
{
class DetectorCPU : public Detector {
public:
DetectorCPU(Config* config, PreWarp* prewarp);
virtual ~DetectorCPU();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
cv::CascadeClassifier plate_cascade;
};
}
#endif /* OPENALPR_DETECTORCPU_H */
| 1,385 | 25.653846 | 105 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectorcuda.h
|
/*
* Copyright (c) 2013 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORCUDA_H
#define OPENALPR_DETECTORCUDA_H
#include <vector>
#ifdef COMPILE_GPU
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#if OPENCV_MAJOR_VERSION == 2
#include "opencv2/gpu/gpu.hpp"
#else
#include "opencv2/cudaobjdetect.hpp"
#endif
#include "detector.h"
#include "detectorcpu.h"
namespace alpr
{
class DetectorCUDA : public Detector {
public:
DetectorCUDA(Config* config, PreWarp* prewarp);
virtual ~DetectorCUDA();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
#if OPENCV_MAJOR_VERSION == 2
cv::gpu::CascadeClassifier_GPU cuda_cascade;
#else
cv::Ptr<cv::cuda::CascadeClassifier> cuda_cascade;
#endif
};
}
#endif
#endif /* OPENALPR_DETECTORCUDA_H */
| 1,660 | 23.426471 | 105 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectorfactory.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORFACTORY_H
#define OPENALPR_DETECTORFACTORY_H
#include "detectorcpu.h"
#include "detectorcuda.h"
#include "config.h"
namespace alpr
{
Detector* createDetector(Config* config, PreWarp* prewarp);
}
#endif /* OPENALPR_DETECTORFACTORY_H */
| 1,035 | 28.6 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectormask.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORMASK_H
#define OPENALPR_DETECTORMASK_H
#include <string>
#include "opencv2/imgproc/imgproc.hpp"
#include "config.h"
#include "prewarp.h"
namespace alpr
{
class DetectorMask {
public:
DetectorMask(Config* config, PreWarp* prewarp);
virtual ~DetectorMask();
void setMask(cv::Mat mask);
cv::Rect getRoiInsideMask(cv::Rect roi);
cv::Size mask_size();
bool region_is_masked(cv::Rect region);
cv::Mat apply_mask(cv::Mat image);
bool mask_loaded;
private:
void resize_mask(cv::Mat image);
PreWarp* prewarp;
std::string last_prewarp_hash;
cv::Mat mask;
cv::Mat resized_mask;
bool resized_mask_loaded;
Config* config;
cv::Rect scan_area;
};
}
#endif /* DETECTORMASK_H */
| 1,593 | 22.101449 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectormorph.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORMORPH_H
#define OPENALPR_DETECTORMORPH_H
#include <vector>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#include "detector.h"
namespace alpr {
class DetectorMorph : public Detector {
public:
DetectorMorph(Config* config, PreWarp* prewarp);
virtual ~DetectorMorph();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
bool CheckSizes(cv::RotatedRect& mr);
bool ValidateCharAspect(cv::Rect& r0, float idealAspect);
};
}
#endif /* OPENALPR_DETECTORMORPH_H */
| 1,450 | 27.45098 | 103 |
h
|
openalpr
|
openalpr-master/src/openalpr/detection/detectorocl.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTOROPENCL_H
#define OPENALPR_DETECTOROPENCL_H
#include <vector>
#if OPENCV_MAJOR_VERSION == 3
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/core/ocl.hpp"
#include "detector.h"
namespace alpr
{
class DetectorOCL : public Detector {
public:
DetectorOCL(Config* config, PreWarp* prewarp);
virtual ~DetectorOCL();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
cv::CascadeClassifier plate_cascade;
};
}
#endif
#endif /* OPENALPR_DETECTOROPENCL_H */
| 1,451 | 24.473684 | 103 |
h
|
openalpr
|
openalpr-master/src/openalpr/edges/edgefinder.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_EDGEFINDER_H
#define OPENALPR_EDGEFINDER_H
#include "opencv2/imgproc/imgproc.hpp"
#include "pipeline_data.h"
#include "transformation.h"
#include "platelines.h"
#include "platecorners.h"
namespace alpr
{
class EdgeFinder {
public:
EdgeFinder(PipelineData* pipeline_data);
virtual ~EdgeFinder();
std::vector<cv::Point2f> findEdgeCorners();
private:
PipelineData* pipeline_data;
std::vector<cv::Point2f> detection(bool high_contrast);
std::vector<cv::Point> highContrastDetection(cv::Mat newCrop, std::vector<TextLine> newLines);
std::vector<cv::Point> normalDetection(cv::Mat newCrop, std::vector<TextLine> newLines);
bool is_high_contrast(const cv::Mat crop);
};
}
#endif /* OPENALPR_EDGEFINDER_H */
| 1,551 | 27.218182 | 98 |
h
|
openalpr
|
openalpr-master/src/openalpr/edges/platecorners.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_PLATECORNERS_H
#define OPENALPR_PLATECORNERS_H
#include "opencv2/imgproc/imgproc.hpp"
#include "platelines.h"
#include "utility.h"
#include "config.h"
#include "textlinecollection.h"
#include "scorekeeper.h"
#define NO_LINE -1
#define SCORING_MISSING_SEGMENT_PENALTY_VERTICAL 10
#define SCORING_MISSING_SEGMENT_PENALTY_HORIZONTAL 1
#define SCORING_PLATEHEIGHT_WEIGHT 2.2
#define SCORING_TOP_BOTTOM_SPACE_VS_CHARHEIGHT_WEIGHT 2.0
#define SCORING_ANGLE_MATCHES_LPCHARS_WEIGHT 1.1
#define SCORING_DISTANCE_WEIGHT_VERTICAL 4.0
#define SCORING_LINE_CONFIDENCE_WEIGHT 18.0
namespace alpr
{
class PlateCorners
{
public:
PlateCorners(cv::Mat inputImage, PlateLines* plateLines, PipelineData* pipelineData, std::vector<TextLine> textLines) ;
virtual ~PlateCorners();
std::vector<cv::Point> findPlateCorners();
private:
PipelineData* pipelineData;
cv::Mat inputImage;
std::vector<TextLine> textLines;
TextLineCollection tlc;
float bestHorizontalScore;
float bestVerticalScore;
LineSegment bestTop;
LineSegment bestBottom;
LineSegment bestLeft;
LineSegment bestRight;
PlateLines* plateLines;
void scoreHorizontals( int h1, int h2 );
void scoreVerticals( int v1, int v2 );
};
}
#endif // OPENALPR_PLATELINES_H
| 2,188 | 26.3625 | 125 |
h
|
openalpr
|
openalpr-master/src/openalpr/edges/platelines.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_PLATELINES_H
#define OPENALPR_PLATELINES_H
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "utility.h"
#include "binarize_wolf.h"
#include "config.h"
#include "pipeline_data.h"
namespace alpr
{
struct PlateLine
{
LineSegment line;
float confidence;
};
class PlateLines
{
public:
PlateLines(PipelineData* pipelineData);
virtual ~PlateLines();
void processImage(cv::Mat img, std::vector<TextLine> textLines, float sensitivity=1.0);
std::vector<PlateLine> horizontalLines;
std::vector<PlateLine> verticalLines;
std::vector<cv::Point> winningCorners;
private:
PipelineData* pipelineData;
bool debug;
cv::Mat customGrayscaleConversion(cv::Mat src);
void findLines(cv::Mat inputImage);
std::vector<PlateLine> getLines(cv::Mat edges, float sensitivityMultiplier, bool vertical);
};
}
#endif // OPENALPR_PLATELINES_H
| 1,740 | 25.378788 | 97 |
h
|
openalpr
|
openalpr-master/src/openalpr/edges/scorekeeper.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_SCOREKEEPER_H
#define OPENALPR_SCOREKEEPER_H
#include <string>
#include <vector>
namespace alpr
{
class ScoreKeeper {
public:
ScoreKeeper();
virtual ~ScoreKeeper();
void setScore(std::string weight_id, float score, float weight);
float getTotal();
int size();
void printDebugScores();
private:
std::vector<std::string> weight_ids;
std::vector<float> weights;
std::vector<float> scores;
};
}
#endif /* OPENALPR_SCOREKEEPER_H */
| 1,269 | 22.518519 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/ocr.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_OCR_H
#define OPENALPR_OCR_H
#include "postprocess/postprocess.h"
#include "pipeline_data.h"
namespace alpr
{
struct OcrChar
{
std::string letter;
int char_index;
float confidence;
};
class OCR {
public:
OCR(Config* config);
virtual ~OCR();
void performOCR(PipelineData* pipeline_data);
PostProcess postProcessor;
protected:
virtual std::vector<OcrChar> recognize_line(int line_index, PipelineData* pipeline_data)=0;
virtual void segment(PipelineData* pipeline_data)=0;
Config* config;
};
}
#endif /* OPENALPR_OCR_H */
| 1,374 | 24 | 95 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/ocrfactory.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_OCRFACTORY_H
#define OPENALPR_OCRFACTORY_H
#include "config.h"
#include "ocr.h"
namespace alpr
{
OCR* createOcr(Config* config);
}
#endif /* OPENALPR_DETECTORFACTORY_H */
| 963 | 27.352941 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/tesseract_ocr.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_TESSERACTOCR_H
#define OPENALPR_TESSERACTOCR_H
#include <vector>
#include "utility.h"
#include "config.h"
#include "pipeline_data.h"
#include "constants.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "support/filesystem.h"
#include "support/version.h"
#include "ocr.h"
#include "tesseract/baseapi.h"
namespace alpr
{
class TesseractOcr : public OCR
{
public:
TesseractOcr(Config* config);
virtual ~TesseractOcr();
private:
std::vector<OcrChar> recognize_line(int line_index, PipelineData* pipeline_data);
void segment(PipelineData* pipeline_data);
tesseract::TessBaseAPI tesseract;
};
}
#endif // OPENALPR_TESSERACTOCR_H
| 1,474 | 23.180328 | 87 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/segmentation/histogram.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_HISTOGRAM_H
#define OPENALPR_HISTOGRAM_H
#include "opencv2/imgproc/imgproc.hpp"
#include "utility.h"
namespace alpr
{
class Histogram
{
public:
Histogram();
virtual ~Histogram();
cv::Mat histoImg;
// Returns the lowest X position between two points.
int getLocalMinimum(int leftX, int rightX);
// Returns the highest X position between two points.
int getLocalMaximum(int leftX, int rightX);
int getHeightAt(int x);
std::vector<std::pair<int, int> > get1DHits(int yOffset);
protected:
std::vector<int> colHeights;
void analyzeImage(cv::Mat inputImage, cv::Mat mask, bool use_y_axis);
int detect_peak(const double *data, int data_count, int *emi_peaks,
int *num_emi_peaks, int max_emi_peaks, int *absop_peaks,
int *num_absop_peaks, int max_absop_peaks, double delta,
int emi_first);
};
}
#endif //OPENALPR_HISTOGRAM_H
| 1,733 | 27.42623 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/segmentation/histogramhorizontal.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_HISTOGRAMHORIZONTAL_H
#define OPENALPR_HISTOGRAMHORIZONTAL_H
#include "opencv2/imgproc/imgproc.hpp"
#include "histogram.h"
namespace alpr
{
class HistogramHorizontal : public Histogram
{
public:
HistogramHorizontal(cv::Mat inputImage, cv::Mat mask);
};
}
#endif //OPENALPR_HISTOGRAMHORIZONTAL_H
| 1,095 | 29.444444 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/segmentation/histogramvertical.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_VERTICALHISTOGRAM_H
#define OPENALPR_VERTICALHISTOGRAM_H
#include "opencv2/imgproc/imgproc.hpp"
#include "histogram.h"
#include "utility.h"
namespace alpr
{
class HistogramVertical : public Histogram
{
public:
HistogramVertical(cv::Mat inputImage, cv::Mat mask);
};
}
#endif // OPENALPR_VERTICALHISTOGRAM_H
| 1,116 | 24.386364 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/segmentation/segment.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_SEGMENT_H
#define OPENALPR_SEGMENT_H
#include "opencv2/imgproc/imgproc.hpp"
namespace alpr
{
class Segment
{
public:
Segment(cv::Rect newSegment);
virtual ~Segment();
cv::Rect segment;
bool matches(cv::Rect newSegment);
};
}
#endif // OPENALPR_SEGMENTATIONGROUP_H
| 1,094 | 23.886364 | 76 |
h
|
openalpr
|
openalpr-master/src/openalpr/ocr/segmentation/segmentationgroup.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_SEGMENTATIONGROUP_H
#define OPENALPR_SEGMENTATIONGROUP_H
#include <vector>
#include "opencv2/imgproc/imgproc.hpp"
#include "segment.h"
namespace alpr
{
class SegmentationGroup
{
public:
SegmentationGroup();
virtual ~SegmentationGroup();
void add(int segmentID);
std::vector<int> segmentIDs;
bool equals(SegmentationGroup otherGroup);
private:
float strength; // Debuggin purposes -- how many threshold segmentations match this one perfectly
};
}
#endif // OPENALPR_SEGMENTATIONGROUP_H
| 1,334 | 23.722222 | 103 |
h
|
openalpr
|
openalpr-master/src/openalpr/postprocess/postprocess.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_POSTPROCESS_H
#define OPENALPR_POSTPROCESS_H
#include "regexrule.h"
#include "constants.h"
#include "utility.h"
#include <set>
#include <string>
#include <vector>
#include "config.h"
#define SKIP_CHAR "~"
namespace alpr
{
struct Letter
{
std::string letter;
int line_index;
int charposition;
float totalscore;
int occurrences;
};
struct PPResult
{
std::string letters;
float totalscore;
bool matchesTemplate;
std::vector<Letter> letter_details;
};
bool letterCompare( const Letter &left, const Letter &right );
class PostProcess
{
public:
PostProcess(Config* config);
~PostProcess();
void addLetter(std::string letter, int line_index, int charposition, float score);
void clear();
void analyze(std::string templateregion, int topn);
std::string bestChars;
bool matchesTemplate;
const std::vector<PPResult> getResults();
bool regionIsValid(std::string templateregion);
std::vector<std::string> getPatterns();
void setConfidenceThreshold(float min_confidence, float skip_level);
private:
Config* config;
void findAllPermutations(std::string templateregion, int topn);
bool analyzePermutation(std::vector<int> letterIndices, std::string templateregion, int topn);
void insertLetter(std::string letter, int line_index, int charPosition, float score);
std::map<std::string, std::vector<RegexRule*> > rules;
float calculateMaxConfidenceScore();
std::vector<std::vector<Letter> > letters;
std::vector<int> unknownCharPositions;
std::vector<PPResult> allPossibilities;
std::set<std::string> allPossibilitiesLetters;
float min_confidence;
float skip_level;
};
}
#endif // OPENALPR_POSTPROCESS_H
| 2,624 | 24.485437 | 100 |
h
|
openalpr
|
openalpr-master/src/openalpr/postprocess/regexrule.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_REGEXRULE_H
#define OPENALPR_REGEXRULE_H
#include <string>
#include "support/re2.h"
#include "support/utf8.h"
#include "support/tinythread.h"
namespace alpr
{
class RegexRule
{
public:
RegexRule(std::string region, std::string pattern, std::string letters_regex, std::string numbers_regex);
virtual ~RegexRule();
bool match(std::string text);
private:
bool valid;
int numchars;
re2::RE2* re2_regex;
std::string original;
std::string regex;
std::string region;
};
}
#endif /* OPENALPR_REGEXRULE_H */
| 1,366 | 25.288462 | 111 |
h
|
openalpr
|
openalpr-master/src/openalpr/simpleini/ConvertUTF.c
|
/*
* Copyright © 1991-2015 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in
* http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of the Unicode data files and any associated documentation
* (the "Data Files") or Unicode software and any associated documentation
* (the "Software") to deal in the Data Files or Software
* without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, and/or sell copies of
* the Data Files or Software, and to permit persons to whom the Data Files
* or Software are furnished to do so, provided that
* (a) this copyright and permission notice appear with all copies
* of the Data Files or Software,
* (b) this copyright and permission notice appear in associated
* documentation, and
* (c) there is clear notice in each modified Data File or in the Software
* as well as in the documentation associated with the Data File(s) or
* Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
* NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
* DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale,
* use or other dealings in these Data Files or Software without prior
* written authorization of the copyright holder.
*/
/* ---------------------------------------------------------------------
Conversions between UTF32, UTF-16, and UTF-8. Source code file.
Author: Mark E. Davis, 1994.
Rev History: Rick McGowan, fixes & updates May 2001.
Sept 2001: fixed const & error conditions per
mods suggested by S. Parent & A. Lillich.
June 2002: Tim Dodd added detection and handling of incomplete
source sequences, enhanced error detection, added casts
to eliminate compiler warnings.
July 2003: slight mods to back out aggressive FFFE detection.
Jan 2004: updated switches in from-UTF8 conversions.
Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.
See the header file "ConvertUTF.h" for complete documentation.
------------------------------------------------------------------------ */
#include "ConvertUTF.h"
#ifdef CVTUTF_DEBUG
#include <stdio.h>
#endif
static const int halfShift = 10; /* used for shifting by 10 bits */
static const UTF32 halfBase = 0x0010000UL;
static const UTF32 halfMask = 0x3FFUL;
#define UNI_SUR_HIGH_START (UTF32)0xD800
#define UNI_SUR_HIGH_END (UTF32)0xDBFF
#define UNI_SUR_LOW_START (UTF32)0xDC00
#define UNI_SUR_LOW_END (UTF32)0xDFFF
#define false 0
#define true 1
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF32toUTF16 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF32* source = *sourceStart;
UTF16* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
if (target >= targetEnd) {
result = targetExhausted; break;
}
ch = *source++;
if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
/* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = (UTF16)ch; /* normal case */
}
} else if (ch > UNI_MAX_LEGAL_UTF32) {
if (flags == strictConversion) {
result = sourceIllegal;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (target + 1 >= targetEnd) {
--source; /* Back up source pointer! */
result = targetExhausted; break;
}
ch -= halfBase;
*target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
*target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF16toUTF32 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF16* source = *sourceStart;
UTF32* target = *targetStart;
UTF32 ch, ch2;
while (source < sourceEnd) {
const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
ch = *source++;
/* If we have a surrogate pair, convert to UTF32 first. */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
/* If the 16 bits following the high surrogate are in the source buffer... */
if (source < sourceEnd) {
ch2 = *source;
/* If it's a low surrogate, convert to UTF32. */
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
++source;
} else if (flags == strictConversion) { /* it's an unpaired high surrogate */
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
} else { /* We don't have the 16 bits following the high surrogate. */
--source; /* return to the high surrogate */
result = sourceExhausted;
break;
}
} else if (flags == strictConversion) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
if (target >= targetEnd) {
source = oldSource; /* Back up source pointer! */
result = targetExhausted; break;
}
*target++ = ch;
}
*sourceStart = source;
*targetStart = target;
#ifdef CVTUTF_DEBUG
if (result == sourceIllegal) {
fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2);
fflush(stderr);
}
#endif
return result;
}
/* --------------------------------------------------------------------- */
/*
* Index into the table below with the first byte of a UTF-8 sequence to
* get the number of trailing bytes that are supposed to follow it.
* Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
* left as-is for anyone who may want to do such conversion, which was
* allowed in earlier algorithms.
*/
static const char trailingBytesForUTF8[256] = {
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,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};
/*
* Magic values subtracted from a buffer value during UTF8 conversion.
* This table contains as many values as there might be trailing bytes
* in a UTF-8 sequence.
*/
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
0x03C82080UL, 0xFA082080UL, 0x82082080UL };
/*
* Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
* into the first byte, depending on how many bytes follow. There are
* as many entries in this table as there are UTF-8 sequence types.
* (I.e., one byte sequence, two byte... etc.). Remember that sequencs
* for *legal* UTF-8 will be 4 or fewer bytes total.
*/
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
/* --------------------------------------------------------------------- */
/* The interface converts a whole buffer to avoid function-call overhead.
* Constants have been gathered. Loops & conditionals have been removed as
* much as possible for efficiency, in favor of drop-through switches.
* (See "Note A" at the bottom of the file for equivalent code.)
* If your compiler supports it, the "isLegalUTF8" call can be turned
* into an inline function.
*/
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF16toUTF8 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF16* source = *sourceStart;
UTF8* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
unsigned short bytesToWrite = 0;
const UTF32 byteMask = 0xBF;
const UTF32 byteMark = 0x80;
const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
ch = *source++;
/* If we have a surrogate pair, convert to UTF32 first. */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
/* If the 16 bits following the high surrogate are in the source buffer... */
if (source < sourceEnd) {
UTF32 ch2 = *source;
/* If it's a low surrogate, convert to UTF32. */
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
++source;
} else if (flags == strictConversion) { /* it's an unpaired high surrogate */
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
} else { /* We don't have the 16 bits following the high surrogate. */
--source; /* return to the high surrogate */
result = sourceExhausted;
break;
}
} else if (flags == strictConversion) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
/* Figure out how many bytes the result will require */
if (ch < (UTF32)0x80) { bytesToWrite = 1;
} else if (ch < (UTF32)0x800) { bytesToWrite = 2;
} else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
} else if (ch < (UTF32)0x110000) { bytesToWrite = 4;
} else { bytesToWrite = 3;
ch = UNI_REPLACEMENT_CHAR;
}
target += bytesToWrite;
if (target > targetEnd) {
source = oldSource; /* Back up source pointer! */
target -= bytesToWrite; result = targetExhausted; break;
}
switch (bytesToWrite) { /* note: everything falls through. */
case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]);
}
target += bytesToWrite;
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
/*
* Utility routine to tell whether a sequence of bytes is legal UTF-8.
* This must be called with the length pre-determined by the first byte.
* If not calling this from ConvertUTF8to*, then the length can be set by:
* length = trailingBytesForUTF8[*source]+1;
* and the sequence is illegal right away if there aren't that many bytes
* available.
* If presented with a length > 4, this returns false. The Unicode
* definition of UTF-8 goes up to 4-byte sequences.
*/
static Boolean isLegalUTF8(const UTF8 *source, int length) {
UTF8 a;
const UTF8 *srcptr = source+length;
switch (length) {
default: return false;
/* Everything else falls through when "true"... */
case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
case 2: if ((a = (*--srcptr)) > 0xBF) return false;
switch (*source) {
/* no fall-through in this inner switch */
case 0xE0: if (a < 0xA0) return false; break;
case 0xED: if (a > 0x9F) return false; break;
case 0xF0: if (a < 0x90) return false; break;
case 0xF4: if (a > 0x8F) return false; break;
default: if (a < 0x80) return false;
}
case 1: if (*source >= 0x80 && *source < 0xC2) return false;
}
if (*source > 0xF4) return false;
return true;
}
/* --------------------------------------------------------------------- */
/*
* Exported function to return whether a UTF-8 sequence is legal or not.
* This is not used here; it's just exported.
*/
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
int length = trailingBytesForUTF8[*source]+1;
if (source+length > sourceEnd) {
return false;
}
return isLegalUTF8(source, length);
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF8toUTF16 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF8* source = *sourceStart;
UTF16* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch = 0;
unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
if (source + extraBytesToRead >= sourceEnd) {
result = sourceExhausted; break;
}
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1)) {
result = sourceIllegal;
break;
}
/*
* The cases all fall through. See "Note A" below.
*/
switch (extraBytesToRead) {
case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
}
ch -= offsetsFromUTF8[extraBytesToRead];
if (target >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up source pointer! */
result = targetExhausted; break;
}
if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
source -= (extraBytesToRead+1); /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = (UTF16)ch; /* normal case */
}
} else if (ch > UNI_MAX_UTF16) {
if (flags == strictConversion) {
result = sourceIllegal;
source -= (extraBytesToRead+1); /* return to the start */
break; /* Bail out; shouldn't continue */
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (target + 1 >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up source pointer! */
result = targetExhausted; break;
}
ch -= halfBase;
*target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
*target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF32toUTF8 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF32* source = *sourceStart;
UTF8* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
unsigned short bytesToWrite = 0;
const UTF32 byteMask = 0xBF;
const UTF32 byteMark = 0x80;
ch = *source++;
if (flags == strictConversion ) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
/*
* Figure out how many bytes the result will require. Turn any
* illegally large UTF32 things (> Plane 17) into replacement chars.
*/
if (ch < (UTF32)0x80) { bytesToWrite = 1;
} else if (ch < (UTF32)0x800) { bytesToWrite = 2;
} else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
} else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4;
} else { bytesToWrite = 3;
ch = UNI_REPLACEMENT_CHAR;
result = sourceIllegal;
}
target += bytesToWrite;
if (target > targetEnd) {
--source; /* Back up source pointer! */
target -= bytesToWrite; result = targetExhausted; break;
}
switch (bytesToWrite) { /* note: everything falls through. */
case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
}
target += bytesToWrite;
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF8toUTF32 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF8* source = *sourceStart;
UTF32* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch = 0;
unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
if (source + extraBytesToRead >= sourceEnd) {
result = sourceExhausted; break;
}
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1)) {
result = sourceIllegal;
break;
}
/*
* The cases all fall through. See "Note A" below.
*/
switch (extraBytesToRead) {
case 5: ch += *source++; ch <<= 6;
case 4: ch += *source++; ch <<= 6;
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
}
ch -= offsetsFromUTF8[extraBytesToRead];
if (target >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up the source pointer! */
result = targetExhausted; break;
}
if (ch <= UNI_MAX_LEGAL_UTF32) {
/*
* UTF-16 surrogate values are illegal in UTF-32, and anything
* over Plane 17 (> 0x10FFFF) is illegal.
*/
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
source -= (extraBytesToRead+1); /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = ch;
}
} else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
result = sourceIllegal;
*target++ = UNI_REPLACEMENT_CHAR;
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* ---------------------------------------------------------------------
Note A.
The fall-through switches in UTF-8 reading code save a
temp variable, some decrements & conditionals. The switches
are equivalent to the following loop:
{
int tmpBytesToRead = extraBytesToRead+1;
do {
ch += *source++;
--tmpBytesToRead;
if (tmpBytesToRead) ch <<= 6;
} while (tmpBytesToRead > 0);
}
In UTF-8 writing code, the switches on "bytesToWrite" are
similarly unrolled loops.
--------------------------------------------------------------------- */
| 20,219 | 35.366906 | 99 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.