repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
zedshaw/earing
src/module.h
<reponame>zedshaw/earing<gh_stars>1-10 #ifndef module_h #define module_h #include <stdio.h> #include <string.h> #include "tst.h" #include "token.h" #include <gc/cord.h> #include "array.h" #include "hash.h" #include "types.h" #include "function.h" typedef struct Machine { tst_t *directives; tst_t *libraries; tst_t *modules; } Machine; typedef struct Module { CORD module_name; unsigned int curline; int errors; int current_is_leaf; // kind of a hack, need something else Function *current; size_t max_code_size; hash_t *data; hash_t *imports; hash_t *libraries; hash_t *functions; } Module; typedef void(*Module_directive_cb)(Module *state, array_t *params); typedef void(*Module_default_directives_cb)(); int Module_compile(Module *state, CORD source); int Module_register_directive(Module *state, CORD name, Module_directive_cb call, Module_directive_cb destroy); void Module_dump_directives(Module *state, FILE *out); void Module_call_directive(Module *state, Token *ident, array_t *params); Token *Module_resolve_function(Module *state, Token *module, Token *ident); Token *Module_resolve_data(Module *state, Token *ident); Token *Module_outside_function_data(Module *state, Token *func_ref, Token *ident); Module *Module_resolve_module(Module *state, Token *ident); Module *Module_create(const char *name, size_t max_code_size); void Module_create_constant(Module *state, Token *ident, Token *expr); void Module_create_function_constant(Module *state, Token *ident, Token *expr); void Call_operation(Module *state, Function *func, Token *op, Token *type, array_t *params); #endif
zedshaw/earing
src/error.h
#ifndef error_h #define error_h #include "module.h" void error(Module *state, const char *format, ...); void die(Module *state, const char *format, ...); #endif
zedshaw/earing
src/dis.h
#ifndef dis_h #define dis_h void dis_functions(Module *state); #endif
zedshaw/earing
src/unsupported.h
<gh_stars>1-10 /** This file contains combinations of macros and types that do not exist in lightning. * They should not exist, and instead act as error markers so that the code generation * for the ops.c file can be consistent and raise errors for any given type. * * It was obtained by trying to compile ops.c, and then any jit_*_* macros that were * missing were created here. Takes about two seconds in vim. */ #define jit_addci_d(...) assert(!"Type d not supported for addci.") #define jit_addci_f(...) assert(!"Type f not supported for addci.") #ifndef jit_addci_l #define jit_addci_l(...) assert(!"Type l not supported for addci.") #endif #define jit_addci_p(...) assert(!"Type p not supported for addci.") #define jit_addcr_d(...) assert(!"Type d not supported for addcr.") #define jit_addcr_f(...) assert(!"Type f not supported for addcr.") #ifndef jit_addcr_l #define jit_addcr_l(...) assert(!"Type l not supported for addcr.") #endif #define jit_addcr_p(...) assert(!"Type p not supported for addcr.") #define jit_addi_d(...) assert(!"Type d not supported for addi.") #define jit_addi_f(...) assert(!"Type f not supported for addi.") #define jit_addxi_d(...) assert(!"Type d not supported for addxi.") #define jit_addxi_f(...) assert(!"Type f not supported for addxi.") #ifndef jit_addxi_l #define jit_addxi_l(...) assert(!"Type l not supported for addxi.") #endif #define jit_addxi_p(...) assert(!"Type p not supported for addxi.") #define jit_addxr_d(...) assert(!"Type d not supported for addxr.") #define jit_addxr_f(...) assert(!"Type f not supported for addxr.") #ifndef jit_addxr_l #define jit_addxr_l(...) assert(!"Type l not supported for addxr.") #endif #define jit_addxr_p(...) assert(!"Type p not supported for addxr.") #define jit_andi_d(...) assert(!"Type d not supported for andi.") #define jit_andi_f(...) assert(!"Type f not supported for andi.") #define jit_andi_p(...) assert(!"Type p not supported for andi.") #define jit_andr_d(...) assert(!"Type d not supported for andr.") #define jit_andr_f(...) assert(!"Type f not supported for andr.") #define jit_andr_p(...) assert(!"Type p not supported for andr.") #define jit_beqi_d(...) assert(!"Type d not supported for beqi.") #define jit_beqi_f(...) assert(!"Type f not supported for beqi.") #define jit_bgei_d(...) assert(!"Type d not supported for bgei.") #define jit_bgei_f(...) assert(!"Type f not supported for bgei.") #define jit_bgti_d(...) assert(!"Type d not supported for bgti.") #define jit_bgti_f(...) assert(!"Type f not supported for bgti.") #define jit_blei_d(...) assert(!"Type d not supported for blei.") #define jit_blei_f(...) assert(!"Type f not supported for blei.") #define jit_bltgtr_i(...) assert(!"Type i not supported for bltgtr.") #define jit_bltgtr_l(...) assert(!"Type l not supported for bltgtr.") #define jit_bltgtr_p(...) assert(!"Type p not supported for bltgtr.") #define jit_bltgtr_ui(...) assert(!"Type ui not supported for bltgtr.") #define jit_blti_d(...) assert(!"Type d not supported for blti.") #define jit_blti_f(...) assert(!"Type f not supported for blti.") #define jit_bmci_d(...) assert(!"Type d not supported for bmci.") #define jit_bmci_f(...) assert(!"Type f not supported for bmci.") #define jit_bmci_p(...) assert(!"Type p not supported for bmci.") #define jit_bmcr_d(...) assert(!"Type d not supported for bmcr.") #define jit_bmcr_f(...) assert(!"Type f not supported for bmcr.") #define jit_bmcr_p(...) assert(!"Type p not supported for bmcr.") #define jit_bmsi_d(...) assert(!"Type d not supported for bmsi.") #define jit_bmsi_f(...) assert(!"Type f not supported for bmsi.") #define jit_bmsi_p(...) assert(!"Type p not supported for bmsi.") #define jit_bmsr_d(...) assert(!"Type d not supported for bmsr.") #define jit_bmsr_uc(...) assert(!"Type uc not supported for bmsr.") #define jit_bmsr_f(...) assert(!"Type f not supported for bmsr.") #define jit_bmsr_p(...) assert(!"Type p not supported for bmsr.") #define jit_bnei_d(...) assert(!"Type d not supported for bnei.") #define jit_bnei_f(...) assert(!"Type f not supported for bnei.") #define jit_boaddi_d(...) assert(!"Type d not supported for boaddi.") #define jit_boaddi_f(...) assert(!"Type f not supported for boaddi.") #define jit_boaddi_p(...) assert(!"Type p not supported for boaddi.") #define jit_boaddr_d(...) assert(!"Type d not supported for boaddr.") #define jit_boaddr_f(...) assert(!"Type f not supported for boaddr.") #define jit_boaddr_p(...) assert(!"Type p not supported for boaddr.") #define jit_bordr_i(...) assert(!"Type i not supported for bordr.") #define jit_bordr_l(...) assert(!"Type l not supported for bordr.") #define jit_bordr_p(...) assert(!"Type p not supported for bordr.") #define jit_bordr_ui(...) assert(!"Type ui not supported for bordr.") #define jit_bosubi_d(...) assert(!"Type d not supported for bosubi.") #define jit_bosubi_f(...) assert(!"Type f not supported for bosubi.") #define jit_bosubi_p(...) assert(!"Type p not supported for bosubi.") #define jit_bosubr_d(...) assert(!"Type d not supported for bosubr.") #define jit_bosubr_f(...) assert(!"Type f not supported for bosubr.") #define jit_bosubr_p(...) assert(!"Type p not supported for bosubr.") #define jit_buneqr_i(...) assert(!"Type i not supported for buneqr.") #define jit_buneqr_l(...) assert(!"Type l not supported for buneqr.") #define jit_buneqr_p(...) assert(!"Type p not supported for buneqr.") #define jit_buneqr_ui(...) assert(!"Type ui not supported for buneqr.") #define jit_bunger_i(...) assert(!"Type i not supported for bunger.") #define jit_bunger_l(...) assert(!"Type l not supported for bunger.") #define jit_bunger_p(...) assert(!"Type p not supported for bunger.") #define jit_bunger_ui(...) assert(!"Type ui not supported for bunger.") #define jit_bungtr_i(...) assert(!"Type i not supported for bungtr.") #define jit_bungtr_l(...) assert(!"Type l not supported for bungtr.") #define jit_bungtr_p(...) assert(!"Type p not supported for bungtr.") #define jit_bungtr_ui(...) assert(!"Type ui not supported for bungtr.") #define jit_bunler_i(...) assert(!"Type i not supported for bunler.") #define jit_bunler_l(...) assert(!"Type l not supported for bunler.") #define jit_bunler_p(...) assert(!"Type p not supported for bunler.") #define jit_bunler_ui(...) assert(!"Type ui not supported for bunler.") #define jit_bunltr_i(...) assert(!"Type i not supported for bunltr.") #define jit_bunltr_l(...) assert(!"Type l not supported for bunltr.") #define jit_bunltr_p(...) assert(!"Type p not supported for bunltr.") #define jit_bunltr_ui(...) assert(!"Type ui not supported for bunltr.") #define jit_bunordr_i(...) assert(!"Type i not supported for bunordr.") #define jit_bunordr_l(...) assert(!"Type l not supported for bunordr.") #define jit_bunordr_p(...) assert(!"Type p not supported for bunordr.") #define jit_bunordr_ui(...) assert(!"Type ui not supported for bunordr.") #define jit_ceilr_d(...) assert(!"Type d not supported for ceilr.") #define jit_ceilr_f(...) assert(!"Type f not supported for ceilr.") #define jit_ceilr_i(...) assert(!"Type i not supported for ceilr.") #define jit_ceilr_l(...) assert(!"Type l not supported for ceilr.") #define jit_ceilr_p(...) assert(!"Type p not supported for ceilr.") #define jit_ceilr_ui(...) assert(!"Type ui not supported for ceilr.") #define jit_divi_d(...) assert(!"Type d not supported for divi.") #define jit_divi_f(...) assert(!"Type f not supported for divi.") #define jit_divi_p(...) assert(!"Type p not supported for divi.") #define jit_divr_p(...) assert(!"Type p not supported for divr.") #define jit_eqi_d(...) assert(!"Type d not supported for eqi.") #define jit_eqi_f(...) assert(!"Type f not supported for eqi.") #define jit_extr_d(...) assert(!"Type d not supported for extr.") #define jit_extr_f(...) assert(!"Type f not supported for extr.") #define jit_extr_i(...) assert(!"Type i not supported for extr.") #define jit_extr_l(...) assert(!"Type l not supported for extr.") #define jit_extr_p(...) assert(!"Type p not supported for extr.") #define jit_extr_ui(...) assert(!"Type ui not supported for extr.") #define jit_floorr_d(...) assert(!"Type d not supported for floorr.") #define jit_floorr_f(...) assert(!"Type f not supported for floorr.") #define jit_floorr_i(...) assert(!"Type i not supported for floorr.") #define jit_floorr_l(...) assert(!"Type l not supported for floorr.") #define jit_floorr_p(...) assert(!"Type p not supported for floorr.") #define jit_floorr_ui(...) assert(!"Type ui not supported for floorr.") #define jit_gei_d(...) assert(!"Type d not supported for gei.") #define jit_gei_f(...) assert(!"Type f not supported for gei.") #define jit_gti_d(...) assert(!"Type d not supported for gti.") #define jit_gti_f(...) assert(!"Type f not supported for gti.") #define jit_hmuli_d(...) assert(!"Type d not supported for hmuli.") #define jit_hmuli_f(...) assert(!"Type f not supported for hmuli.") #define jit_hmuli_p(...) assert(!"Type p not supported for hmuli.") #define jit_hmulr_d(...) assert(!"Type d not supported for hmulr.") #define jit_hmulr_f(...) assert(!"Type f not supported for hmulr.") #define jit_hmulr_p(...) assert(!"Type p not supported for hmulr.") #define jit_hton_d(...) assert(!"Type d not supported for hton.") #define jit_hton_f(...) assert(!"Type f not supported for hton.") #define jit_hton_i(...) assert(!"Type i not supported for hton.") #define jit_hton_l(...) assert(!"Type l not supported for hton.") #define jit_hton_p(...) assert(!"Type p not supported for hton.") #define jit_lei_d(...) assert(!"Type d not supported for lei.") #define jit_lei_f(...) assert(!"Type f not supported for lei.") #define jit_lshi_d(...) assert(!"Type d not supported for lshi.") #define jit_lshi_f(...) assert(!"Type f not supported for lshi.") #define jit_lshi_p(...) assert(!"Type p not supported for lshi.") #define jit_lshr_d(...) assert(!"Type d not supported for lshr.") #define jit_lshr_f(...) assert(!"Type f not supported for lshr.") #define jit_lshr_p(...) assert(!"Type p not supported for lshr.") #define jit_ltgtr_i(...) assert(!"Type i not supported for ltgtr.") #define jit_ltgtr_l(...) assert(!"Type l not supported for ltgtr.") #define jit_ltgtr_p(...) assert(!"Type p not supported for ltgtr.") #define jit_ltgtr_ui(...) assert(!"Type ui not supported for ltgtr.") #define jit_lti_d(...) assert(!"Type d not supported for lti.") #define jit_lti_f(...) assert(!"Type f not supported for lti.") #define jit_modi_d(...) assert(!"Type d not supported for modi.") #define jit_modi_f(...) assert(!"Type f not supported for modi.") #define jit_modi_p(...) assert(!"Type p not supported for modi.") #define jit_modr_d(...) assert(!"Type d not supported for modr.") #define jit_modr_f(...) assert(!"Type f not supported for modr.") #define jit_modr_p(...) assert(!"Type p not supported for modr.") #define jit_muli_d(...) assert(!"Type d not supported for muli.") #define jit_muli_f(...) assert(!"Type f not supported for muli.") #define jit_muli_p(...) assert(!"Type p not supported for muli.") #define jit_mulr_l_(...) assert(!"Type l_ not supported for mulr.") #define jit_mulr_p(...) assert(!"Type p not supported for mulr.") #ifndef jit_negr_d #define jit_negr_d(...) assert(!"Type d not supported for negr.") #endif #ifndef jit_negr_f #define jit_negr_f(...) assert(!"Type f not supported for negr.") #endif #define jit_negr_p(...) assert(!"Type p not supported for negr.") #define jit_negr_ui(...) assert(!"Type ui not supported for negr.") #define jit_nei_d(...) assert(!"Type d not supported for nei.") #define jit_nei_f(...) assert(!"Type f not supported for nei.") #define jit_notr_d(...) assert(!"Type d not supported for notr.") #define jit_notr_f(...) assert(!"Type f not supported for notr.") #define jit_notr_p(...) assert(!"Type p not supported for notr.") #define jit_ntoh_d(...) assert(!"Type d not supported for ntoh.") #define jit_ntoh_f(...) assert(!"Type f not supported for ntoh.") #define jit_ntoh_i(...) assert(!"Type i not supported for ntoh.") #define jit_ntoh_l(...) assert(!"Type l not supported for ntoh.") #define jit_ntoh_p(...) assert(!"Type p not supported for ntoh.") #define jit_ordr_i(...) assert(!"Type i not supported for ordr.") #define jit_ordr_l(...) assert(!"Type l not supported for ordr.") #define jit_ordr_p(...) assert(!"Type p not supported for ordr.") #define jit_ordr_ui(...) assert(!"Type ui not supported for ordr.") #define jit_ori_d(...) assert(!"Type d not supported for ori.") #define jit_ori_f(...) assert(!"Type f not supported for ori.") #define jit_ori_p(...) assert(!"Type p not supported for ori.") #define jit_orr_d(...) assert(!"Type d not supported for orr.") #define jit_orr_f(...) assert(!"Type f not supported for orr.") #define jit_orr_p(...) assert(!"Type p not supported for orr.") #define jit_prepare_l(...) assert(!"Type l not supported for prepare.") #define jit_prepare_p(...) assert(!"Type p not supported for prepare.") #define jit_prepare_ui(...) assert(!"Type ui not supported for prepare.") #define jit_roundr_d(...) assert(!"Type d not supported for roundr.") #define jit_roundr_f(...) assert(!"Type f not supported for roundr.") #define jit_roundr_i(...) assert(!"Type i not supported for roundr.") #define jit_roundr_l(...) assert(!"Type l not supported for roundr.") #define jit_roundr_p(...) assert(!"Type p not supported for roundr.") #define jit_roundr_ui(...) assert(!"Type ui not supported for roundr.") #define jit_rsbi_d(...) assert(!"Type d not supported for rsbi.") #define jit_rsbi_f(...) assert(!"Type f not supported for rsbi.") #define jit_rshi_d(...) assert(!"Type d not supported for rshi.") #define jit_rshi_f(...) assert(!"Type f not supported for rshi.") #define jit_rshi_p(...) assert(!"Type p not supported for rshi.") #define jit_rshr_d(...) assert(!"Type d not supported for rshr.") #define jit_rshr_f(...) assert(!"Type f not supported for rshr.") #define jit_rshr_p(...) assert(!"Type p not supported for rshr.") #define jit_subci_d(...) assert(!"Type d not supported for subci.") #define jit_subci_f(...) assert(!"Type f not supported for subci.") #define jit_subci_p(...) assert(!"Type p not supported for subci.") #define jit_subcr_d(...) assert(!"Type d not supported for subcr.") #define jit_subcr_f(...) assert(!"Type f not supported for subcr.") #ifndef jit_subcr_l #define jit_subcr_l(...) assert(!"Type l not supported for subcr.") #endif #define jit_subcr_p(...) assert(!"Type p not supported for subcr.") #define jit_subi_d(...) assert(!"Type d not supported for subi.") #define jit_subi_f(...) assert(!"Type f not supported for subi.") #define jit_subxi_d(...) assert(!"Type d not supported for subxi.") #define jit_subxi_f(...) assert(!"Type f not supported for subxi.") #ifndef jit_subxi_l #define jit_subxi_l(...) assert(!"Type l not supported for subxi.") #endif #define jit_subxi_p(...) assert(!"Type p not supported for subxi.") #define jit_subxr_d(...) assert(!"Type d not supported for subxr.") #define jit_subxr_f(...) assert(!"Type f not supported for subxr.") #ifndef jit_subxr_l #define jit_subxr_l(...) assert(!"Type l not supported for subxr.") #endif #define jit_subxr_p(...) assert(!"Type p not supported for subxr.") #define jit_truncr_d(...) assert(!"Type d not supported for truncr.") #define jit_truncr_f(...) assert(!"Type f not supported for truncr.") #define jit_truncr_i(...) assert(!"Type i not supported for truncr.") #define jit_truncr_l(...) assert(!"Type l not supported for truncr.") #define jit_truncr_p(...) assert(!"Type p not supported for truncr.") #define jit_truncr_ui(...) assert(!"Type ui not supported for truncr.") #define jit_uneqr_i(...) assert(!"Type i not supported for uneqr.") #define jit_uneqr_l(...) assert(!"Type l not supported for uneqr.") #define jit_uneqr_p(...) assert(!"Type p not supported for uneqr.") #define jit_uneqr_ui(...) assert(!"Type ui not supported for uneqr.") #define jit_unger_i(...) assert(!"Type i not supported for unger.") #define jit_unger_l(...) assert(!"Type l not supported for unger.") #define jit_unger_p(...) assert(!"Type p not supported for unger.") #define jit_unger_ui(...) assert(!"Type ui not supported for unger.") #define jit_ungtr_i(...) assert(!"Type i not supported for ungtr.") #define jit_ungtr_l(...) assert(!"Type l not supported for ungtr.") #define jit_ungtr_p(...) assert(!"Type p not supported for ungtr.") #define jit_ungtr_ui(...) assert(!"Type ui not supported for ungtr.") #define jit_unler_i(...) assert(!"Type i not supported for unler.") #define jit_unler_l(...) assert(!"Type l not supported for unler.") #define jit_unler_p(...) assert(!"Type p not supported for unler.") #define jit_unler_ui(...) assert(!"Type ui not supported for unler.") #define jit_unltr_i(...) assert(!"Type i not supported for unltr.") #define jit_unltr_l(...) assert(!"Type l not supported for unltr.") #define jit_unltr_p(...) assert(!"Type p not supported for unltr.") #define jit_unltr_ui(...) assert(!"Type ui not supported for unltr.") #define jit_unordr_i(...) assert(!"Type i not supported for unordr.") #define jit_unordr_l(...) assert(!"Type l not supported for unordr.") #define jit_unordr_p(...) assert(!"Type p not supported for unordr.") #define jit_unordr_ui(...) assert(!"Type ui not supported for unordr.") #define jit_xori_d(...) assert(!"Type d not supported for xori.") #define jit_xori_f(...) assert(!"Type f not supported for xori.") #define jit_xori_p(...) assert(!"Type p not supported for xori.") #define jit_xorr_d(...) assert(!"Type d not supported for xorr.") #define jit_xorr_f(...) assert(!"Type f not supported for xorr.") #define jit_xorr_p(...) assert(!"Type p not supported for xorr.") #ifndef jit_allocai #define jit_allocai(...) assert(!"You are using lightning 1.2 so no jit_allocai.") #endif #ifndef jit_beqr_f #define jit_beqr_f(...) assert(!"Type f not supported for beqr."); #endif #ifndef jit_bger_f #define jit_bger_f(...) assert(!"Type f not supported for bger."); #endif #ifndef jit_bgtr_f #define jit_bgtr_f(...) assert(!"Type f not supported for bgtr."); #endif #ifndef jit_bler_f #define jit_bler_f(...) assert(!"Type f not supported for bler."); #endif #ifndef jit_bltgtr_f #define jit_bltgtr_f(...) assert(!"Type f not supported for bltgtr."); #endif #ifndef jit_bltr_f #define jit_bltr_f(...) assert(!"Type f not supported for bltr."); #endif #ifndef jit_bner_f #define jit_bner_f(...) assert(!"Type f not supported for bner."); #endif #ifndef jit_bordr_f #define jit_bordr_f(...) assert(!"Type f not supported for bordr."); #endif #ifndef jit_buneqr_f #define jit_buneqr_f(...) assert(!"Type f not supported for buneqr."); #endif #ifndef jit_bunger_f #define jit_bunger_f(...) assert(!"Type f not supported for bunger."); #endif #ifndef jit_bungtr_f #define jit_bungtr_f(...) assert(!"Type f not supported for bungtr."); #endif #ifndef jit_bunler_f #define jit_bunler_f(...) assert(!"Type f not supported for bunler."); #endif #ifndef jit_bunltr_f #define jit_bunltr_f(...) assert(!"Type f not supported for bunltr."); #endif #ifndef jit_bunordr_f #define jit_bunordr_f(...) assert(!"Type f not supported for bunordr."); // these aren't in lightning 1.2 we use the fact that bunordr_f isn't as well // to then clean up some dumbassery in lightning #define JCm(...) (1) #define JNCm(...) (2) #undef jit_bger_d #undef jit_bger_d #undef jit_bler_d #undef jit_bltgtr_d #undef jit_bordr_d #define jit_bger_d(...) assert(!"Type d not supported for bger."); #define jit_bler_d(...) assert(!"Type d not supported for bler."); #define jit_bltgtr_d(...) assert(!"Type d not supported for bltgtr."); #define jit_bordr_d(...) assert(!"Type d not supported for bordr."); #endif #define jit_addr_c(...) assert("Unsupported type c for instruction addr.") #define jit_addr_c(...) assert("Unsupported type c for instruction addr.") #define jit_addr_s(...) assert("Unsupported type s for instruction addr.") #define jit_addr_us(...) assert("Unsupported type us for instruction addr.") #define jit_addi_c(...) assert("Unsupported type c for instruction addi.") #define jit_addi_c(...) assert("Unsupported type c for instruction addi.") #define jit_addi_s(...) assert("Unsupported type s for instruction addi.") #define jit_addi_us(...) assert("Unsupported type us for instruction addi.") #define jit_addxr_c(...) assert("Unsupported type c for instruction addxr.") #define jit_addxr_c(...) assert("Unsupported type c for instruction addxr.") #define jit_addxr_s(...) assert("Unsupported type s for instruction addxr.") #define jit_addxr_us(...) assert("Unsupported type us for instruction addxr.") #define jit_addxi_c(...) assert("Unsupported type c for instruction addxi.") #define jit_addxi_c(...) assert("Unsupported type c for instruction addxi.") #define jit_addxi_s(...) assert("Unsupported type s for instruction addxi.") #define jit_addxi_us(...) assert("Unsupported type us for instruction addxi.") #define jit_addcr_c(...) assert("Unsupported type c for instruction addcr.") #define jit_addcr_c(...) assert("Unsupported type c for instruction addcr.") #define jit_addcr_s(...) assert("Unsupported type s for instruction addcr.") #define jit_addcr_us(...) assert("Unsupported type us for instruction addcr.") #define jit_addci_c(...) assert("Unsupported type c for instruction addci.") #define jit_addci_c(...) assert("Unsupported type c for instruction addci.") #define jit_addci_s(...) assert("Unsupported type s for instruction addci.") #define jit_addci_us(...) assert("Unsupported type us for instruction addci.") #define jit_subr_c(...) assert("Unsupported type c for instruction subr.") #define jit_subr_c(...) assert("Unsupported type c for instruction subr.") #define jit_subr_s(...) assert("Unsupported type s for instruction subr.") #define jit_subr_us(...) assert("Unsupported type us for instruction subr.") #define jit_subi_c(...) assert("Unsupported type c for instruction subi.") #define jit_subi_c(...) assert("Unsupported type c for instruction subi.") #define jit_subi_s(...) assert("Unsupported type s for instruction subi.") #define jit_subi_us(...) assert("Unsupported type us for instruction subi.") #define jit_subxr_c(...) assert("Unsupported type c for instruction subxr.") #define jit_subxr_c(...) assert("Unsupported type c for instruction subxr.") #define jit_subxr_s(...) assert("Unsupported type s for instruction subxr.") #define jit_subxr_us(...) assert("Unsupported type us for instruction subxr.") #define jit_subxi_c(...) assert("Unsupported type c for instruction subxi.") #define jit_subxi_c(...) assert("Unsupported type c for instruction subxi.") #define jit_subxi_s(...) assert("Unsupported type s for instruction subxi.") #define jit_subxi_us(...) assert("Unsupported type us for instruction subxi.") #define jit_subcr_c(...) assert("Unsupported type c for instruction subcr.") #define jit_subcr_c(...) assert("Unsupported type c for instruction subcr.") #define jit_subcr_s(...) assert("Unsupported type s for instruction subcr.") #define jit_subcr_us(...) assert("Unsupported type us for instruction subcr.") #define jit_subci_c(...) assert("Unsupported type c for instruction subci.") #define jit_subci_c(...) assert("Unsupported type c for instruction subci.") #define jit_subci_s(...) assert("Unsupported type s for instruction subci.") #define jit_subci_us(...) assert("Unsupported type us for instruction subci.") #define jit_rsbr_c(...) assert("Unsupported type c for instruction rsbr.") #define jit_rsbr_c(...) assert("Unsupported type c for instruction rsbr.") #define jit_rsbr_s(...) assert("Unsupported type s for instruction rsbr.") #define jit_rsbr_us(...) assert("Unsupported type us for instruction rsbr.") #define jit_rsbi_c(...) assert("Unsupported type c for instruction rsbi.") #define jit_rsbi_c(...) assert("Unsupported type c for instruction rsbi.") #define jit_rsbi_s(...) assert("Unsupported type s for instruction rsbi.") #define jit_rsbi_us(...) assert("Unsupported type us for instruction rsbi.") #define jit_mulr_c(...) assert("Unsupported type c for instruction mulr.") #define jit_mulr_c(...) assert("Unsupported type c for instruction mulr.") #define jit_mulr_s(...) assert("Unsupported type s for instruction mulr.") #define jit_mulr_us(...) assert("Unsupported type us for instruction mulr.") #define jit_muli_c(...) assert("Unsupported type c for instruction muli.") #define jit_muli_c(...) assert("Unsupported type c for instruction muli.") #define jit_muli_s(...) assert("Unsupported type s for instruction muli.") #define jit_muli_us(...) assert("Unsupported type us for instruction muli.") #define jit_hmulr_c(...) assert("Unsupported type c for instruction hmulr.") #define jit_hmulr_c(...) assert("Unsupported type c for instruction hmulr.") #define jit_hmulr_s(...) assert("Unsupported type s for instruction hmulr.") #define jit_hmulr_us(...) assert("Unsupported type us for instruction hmulr.") #define jit_hmuli_c(...) assert("Unsupported type c for instruction hmuli.") #define jit_hmuli_c(...) assert("Unsupported type c for instruction hmuli.") #define jit_hmuli_s(...) assert("Unsupported type s for instruction hmuli.") #define jit_hmuli_us(...) assert("Unsupported type us for instruction hmuli.") #define jit_divr_c(...) assert("Unsupported type c for instruction divr.") #define jit_divr_c(...) assert("Unsupported type c for instruction divr.") #define jit_divr_s(...) assert("Unsupported type s for instruction divr.") #define jit_divr_us(...) assert("Unsupported type us for instruction divr.") #define jit_divi_c(...) assert("Unsupported type c for instruction divi.") #define jit_divi_c(...) assert("Unsupported type c for instruction divi.") #define jit_divi_s(...) assert("Unsupported type s for instruction divi.") #define jit_divi_us(...) assert("Unsupported type us for instruction divi.") #define jit_modr_c(...) assert("Unsupported type c for instruction modr.") #define jit_modr_c(...) assert("Unsupported type c for instruction modr.") #define jit_modr_s(...) assert("Unsupported type s for instruction modr.") #define jit_modr_us(...) assert("Unsupported type us for instruction modr.") #define jit_modi_c(...) assert("Unsupported type c for instruction modi.") #define jit_modi_c(...) assert("Unsupported type c for instruction modi.") #define jit_modi_s(...) assert("Unsupported type s for instruction modi.") #define jit_modi_us(...) assert("Unsupported type us for instruction modi.") #define jit_andr_c(...) assert("Unsupported type c for instruction andr.") #define jit_andr_c(...) assert("Unsupported type c for instruction andr.") #define jit_andr_s(...) assert("Unsupported type s for instruction andr.") #define jit_andr_us(...) assert("Unsupported type us for instruction andr.") #define jit_andi_c(...) assert("Unsupported type c for instruction andi.") #define jit_andi_c(...) assert("Unsupported type c for instruction andi.") #define jit_andi_s(...) assert("Unsupported type s for instruction andi.") #define jit_andi_us(...) assert("Unsupported type us for instruction andi.") #define jit_orr_c(...) assert("Unsupported type c for instruction orr.") #define jit_orr_c(...) assert("Unsupported type c for instruction orr.") #define jit_orr_s(...) assert("Unsupported type s for instruction orr.") #define jit_orr_us(...) assert("Unsupported type us for instruction orr.") #define jit_ori_c(...) assert("Unsupported type c for instruction ori.") #define jit_ori_c(...) assert("Unsupported type c for instruction ori.") #define jit_ori_s(...) assert("Unsupported type s for instruction ori.") #define jit_ori_us(...) assert("Unsupported type us for instruction ori.") #define jit_xorr_c(...) assert("Unsupported type c for instruction xorr.") #define jit_xorr_c(...) assert("Unsupported type c for instruction xorr.") #define jit_xorr_s(...) assert("Unsupported type s for instruction xorr.") #define jit_xorr_us(...) assert("Unsupported type us for instruction xorr.") #define jit_xori_c(...) assert("Unsupported type c for instruction xori.") #define jit_xori_c(...) assert("Unsupported type c for instruction xori.") #define jit_xori_s(...) assert("Unsupported type s for instruction xori.") #define jit_xori_us(...) assert("Unsupported type us for instruction xori.") #define jit_lshr_c(...) assert("Unsupported type c for instruction lshr.") #define jit_lshr_c(...) assert("Unsupported type c for instruction lshr.") #define jit_lshr_s(...) assert("Unsupported type s for instruction lshr.") #define jit_lshr_us(...) assert("Unsupported type us for instruction lshr.") #define jit_lshi_c(...) assert("Unsupported type c for instruction lshi.") #define jit_lshi_c(...) assert("Unsupported type c for instruction lshi.") #define jit_lshi_s(...) assert("Unsupported type s for instruction lshi.") #define jit_lshi_us(...) assert("Unsupported type us for instruction lshi.") #define jit_rshr_c(...) assert("Unsupported type c for instruction rshr.") #define jit_rshr_c(...) assert("Unsupported type c for instruction rshr.") #define jit_rshr_s(...) assert("Unsupported type s for instruction rshr.") #define jit_rshr_us(...) assert("Unsupported type us for instruction rshr.") #define jit_rshi_c(...) assert("Unsupported type c for instruction rshi.") #define jit_rshi_c(...) assert("Unsupported type c for instruction rshi.") #define jit_rshi_s(...) assert("Unsupported type s for instruction rshi.") #define jit_rshi_us(...) assert("Unsupported type us for instruction rshi.") #define jit_negr_c(...) assert("Unsupported type c for instruction negr.") #define jit_negr_c(...) assert("Unsupported type c for instruction negr.") #define jit_negr_s(...) assert("Unsupported type s for instruction negr.") #define jit_negr_us(...) assert("Unsupported type us for instruction negr.") #define jit_xori_c(...) assert("Unsupported type c for instruction xori.") #define jit_xori_c(...) assert("Unsupported type c for instruction xori.") #define jit_xori_s(...) assert("Unsupported type s for instruction xori.") #define jit_xori_s(...) assert("Unsupported type s for instruction xori.") #define jit_ltr_c(...) assert("Unsupported type c for instruction ltr.") #define jit_ltr_c(...) assert("Unsupported type c for instruction ltr.") #define jit_ltr_s(...) assert("Unsupported type s for instruction ltr.") #define jit_ltr_us(...) assert("Unsupported type us for instruction ltr.") #define jit_lti_c(...) assert("Unsupported type c for instruction lti.") #define jit_lti_c(...) assert("Unsupported type c for instruction lti.") #define jit_lti_s(...) assert("Unsupported type s for instruction lti.") #define jit_lti_us(...) assert("Unsupported type us for instruction lti.") #define jit_ler_c(...) assert("Unsupported type c for instruction ler.") #define jit_ler_c(...) assert("Unsupported type c for instruction ler.") #define jit_ler_s(...) assert("Unsupported type s for instruction ler.") #define jit_ler_us(...) assert("Unsupported type us for instruction ler.") #define jit_lei_c(...) assert("Unsupported type c for instruction lei.") #define jit_lei_c(...) assert("Unsupported type c for instruction lei.") #define jit_lei_s(...) assert("Unsupported type s for instruction lei.") #define jit_lei_us(...) assert("Unsupported type us for instruction lei.") #define jit_gtr_c(...) assert("Unsupported type c for instruction gtr.") #define jit_gtr_c(...) assert("Unsupported type c for instruction gtr.") #define jit_gtr_s(...) assert("Unsupported type s for instruction gtr.") #define jit_gtr_us(...) assert("Unsupported type us for instruction gtr.") #define jit_gti_c(...) assert("Unsupported type c for instruction gti.") #define jit_gti_c(...) assert("Unsupported type c for instruction gti.") #define jit_gti_s(...) assert("Unsupported type s for instruction gti.") #define jit_gti_us(...) assert("Unsupported type us for instruction gti.") #define jit_ger_c(...) assert("Unsupported type c for instruction ger.") #define jit_ger_c(...) assert("Unsupported type c for instruction ger.") #define jit_ger_s(...) assert("Unsupported type s for instruction ger.") #define jit_ger_us(...) assert("Unsupported type us for instruction ger.") #define jit_gei_c(...) assert("Unsupported type c for instruction gei.") #define jit_gei_c(...) assert("Unsupported type c for instruction gei.") #define jit_gei_s(...) assert("Unsupported type s for instruction gei.") #define jit_gei_us(...) assert("Unsupported type us for instruction gei.") #define jit_eqr_c(...) assert("Unsupported type c for instruction eqr.") #define jit_eqr_c(...) assert("Unsupported type c for instruction eqr.") #define jit_eqr_s(...) assert("Unsupported type s for instruction eqr.") #define jit_eqr_us(...) assert("Unsupported type us for instruction eqr.") #define jit_eqi_c(...) assert("Unsupported type c for instruction eqi.") #define jit_eqi_c(...) assert("Unsupported type c for instruction eqi.") #define jit_eqi_s(...) assert("Unsupported type s for instruction eqi.") #define jit_eqi_us(...) assert("Unsupported type us for instruction eqi.") #define jit_ner_c(...) assert("Unsupported type c for instruction ner.") #define jit_ner_c(...) assert("Unsupported type c for instruction ner.") #define jit_ner_s(...) assert("Unsupported type s for instruction ner.") #define jit_ner_us(...) assert("Unsupported type us for instruction ner.") #define jit_nei_c(...) assert("Unsupported type c for instruction nei.") #define jit_nei_c(...) assert("Unsupported type c for instruction nei.") #define jit_nei_s(...) assert("Unsupported type s for instruction nei.") #define jit_nei_us(...) assert("Unsupported type us for instruction nei.") #define jit_unltr_c(...) assert("Unsupported type c for instruction unltr.") #define jit_unltr_c(...) assert("Unsupported type c for instruction unltr.") #define jit_unltr_s(...) assert("Unsupported type s for instruction unltr.") #define jit_unltr_us(...) assert("Unsupported type us for instruction unltr.") #define jit_unler_c(...) assert("Unsupported type c for instruction unler.") #define jit_unler_c(...) assert("Unsupported type c for instruction unler.") #define jit_unler_s(...) assert("Unsupported type s for instruction unler.") #define jit_unler_us(...) assert("Unsupported type us for instruction unler.") #define jit_ungtr_c(...) assert("Unsupported type c for instruction ungtr.") #define jit_ungtr_c(...) assert("Unsupported type c for instruction ungtr.") #define jit_ungtr_s(...) assert("Unsupported type s for instruction ungtr.") #define jit_ungtr_us(...) assert("Unsupported type us for instruction ungtr.") #define jit_unger_c(...) assert("Unsupported type c for instruction unger.") #define jit_unger_c(...) assert("Unsupported type c for instruction unger.") #define jit_unger_s(...) assert("Unsupported type s for instruction unger.") #define jit_unger_us(...) assert("Unsupported type us for instruction unger.") #define jit_uneqr_c(...) assert("Unsupported type c for instruction uneqr.") #define jit_uneqr_c(...) assert("Unsupported type c for instruction uneqr.") #define jit_uneqr_s(...) assert("Unsupported type s for instruction uneqr.") #define jit_uneqr_us(...) assert("Unsupported type us for instruction uneqr.") #define jit_ltgtr_c(...) assert("Unsupported type c for instruction ltgtr.") #define jit_ltgtr_c(...) assert("Unsupported type c for instruction ltgtr.") #define jit_ltgtr_s(...) assert("Unsupported type s for instruction ltgtr.") #define jit_ltgtr_us(...) assert("Unsupported type us for instruction ltgtr.") #define jit_ordr_c(...) assert("Unsupported type c for instruction ordr.") #define jit_ordr_c(...) assert("Unsupported type c for instruction ordr.") #define jit_ordr_s(...) assert("Unsupported type s for instruction ordr.") #define jit_ordr_us(...) assert("Unsupported type us for instruction ordr.") #define jit_unordr_c(...) assert("Unsupported type c for instruction unordr.") #define jit_unordr_c(...) assert("Unsupported type c for instruction unordr.") #define jit_unordr_s(...) assert("Unsupported type s for instruction unordr.") #define jit_unordr_us(...) assert("Unsupported type us for instruction unordr.") #define jit_movr_c(...) assert("Unsupported type c for instruction movr.") #define jit_movr_c(...) assert("Unsupported type c for instruction movr.") #define jit_movr_s(...) assert("Unsupported type s for instruction movr.") #define jit_movr_us(...) assert("Unsupported type us for instruction movr.") #define jit_movi_c(...) assert("Unsupported type c for instruction movi.") #define jit_movi_c(...) assert("Unsupported type c for instruction movi.") #define jit_movi_s(...) assert("Unsupported type s for instruction movi.") #define jit_movi_us(...) assert("Unsupported type us for instruction movi.") #define jit_extr_c(...) assert("Unsupported type c for instruction extr.") #define jit_extr_c(...) assert("Unsupported type c for instruction extr.") #define jit_extr_s(...) assert("Unsupported type s for instruction extr.") #define jit_extr_us(...) assert("Unsupported type us for instruction extr.") #define jit_roundr_c(...) assert("Unsupported type c for instruction roundr.") #define jit_roundr_c(...) assert("Unsupported type c for instruction roundr.") #define jit_roundr_s(...) assert("Unsupported type s for instruction roundr.") #define jit_roundr_us(...) assert("Unsupported type us for instruction roundr.") #define jit_truncr_c(...) assert("Unsupported type c for instruction truncr.") #define jit_truncr_c(...) assert("Unsupported type c for instruction truncr.") #define jit_truncr_s(...) assert("Unsupported type s for instruction truncr.") #define jit_truncr_us(...) assert("Unsupported type us for instruction truncr.") #define jit_floorr_c(...) assert("Unsupported type c for instruction floorr.") #define jit_floorr_c(...) assert("Unsupported type c for instruction floorr.") #define jit_floorr_s(...) assert("Unsupported type s for instruction floorr.") #define jit_floorr_us(...) assert("Unsupported type us for instruction floorr.") #define jit_ceilr_c(...) assert("Unsupported type c for instruction ceilr.") #define jit_ceilr_c(...) assert("Unsupported type c for instruction ceilr.") #define jit_ceilr_s(...) assert("Unsupported type s for instruction ceilr.") #define jit_ceilr_us(...) assert("Unsupported type us for instruction ceilr.") #define jit_hton_c(...) assert("Unsupported type c for instruction hton.") #define jit_hton_c(...) assert("Unsupported type c for instruction hton.") #define jit_hton_s(...) assert("Unsupported type s for instruction hton.") #define jit_ntoh_c(...) assert("Unsupported type c for instruction ntoh.") #define jit_ntoh_c(...) assert("Unsupported type c for instruction ntoh.") #define jit_ntoh_s(...) assert("Unsupported type s for instruction ntoh.") #define jit_bltr_c(...) assert("Unsupported type c for instruction bltr.") #define jit_bltr_c(...) assert("Unsupported type c for instruction bltr.") #define jit_bltr_s(...) assert("Unsupported type s for instruction bltr.") #define jit_bltr_us(...) assert("Unsupported type us for instruction bltr.") #define jit_blti_c(...) assert("Unsupported type c for instruction blti.") #define jit_blti_c(...) assert("Unsupported type c for instruction blti.") #define jit_blti_s(...) assert("Unsupported type s for instruction blti.") #define jit_blti_us(...) assert("Unsupported type us for instruction blti.") #define jit_bler_c(...) assert("Unsupported type c for instruction bler.") #define jit_bler_c(...) assert("Unsupported type c for instruction bler.") #define jit_bler_s(...) assert("Unsupported type s for instruction bler.") #define jit_bler_us(...) assert("Unsupported type us for instruction bler.") #define jit_blei_c(...) assert("Unsupported type c for instruction blei.") #define jit_blei_c(...) assert("Unsupported type c for instruction blei.") #define jit_blei_s(...) assert("Unsupported type s for instruction blei.") #define jit_blei_us(...) assert("Unsupported type us for instruction blei.") #define jit_bgtr_c(...) assert("Unsupported type c for instruction bgtr.") #define jit_bgtr_c(...) assert("Unsupported type c for instruction bgtr.") #define jit_bgtr_s(...) assert("Unsupported type s for instruction bgtr.") #define jit_bgtr_us(...) assert("Unsupported type us for instruction bgtr.") #define jit_bgti_c(...) assert("Unsupported type c for instruction bgti.") #define jit_bgti_c(...) assert("Unsupported type c for instruction bgti.") #define jit_bgti_s(...) assert("Unsupported type s for instruction bgti.") #define jit_bgti_us(...) assert("Unsupported type us for instruction bgti.") #define jit_bger_c(...) assert("Unsupported type c for instruction bger.") #define jit_bger_c(...) assert("Unsupported type c for instruction bger.") #define jit_bger_s(...) assert("Unsupported type s for instruction bger.") #define jit_bger_us(...) assert("Unsupported type us for instruction bger.") #define jit_bgei_c(...) assert("Unsupported type c for instruction bgei.") #define jit_bgei_c(...) assert("Unsupported type c for instruction bgei.") #define jit_bgei_s(...) assert("Unsupported type s for instruction bgei.") #define jit_bgei_us(...) assert("Unsupported type us for instruction bgei.") #define jit_beqr_c(...) assert("Unsupported type c for instruction beqr.") #define jit_beqr_c(...) assert("Unsupported type c for instruction beqr.") #define jit_beqr_s(...) assert("Unsupported type s for instruction beqr.") #define jit_beqr_us(...) assert("Unsupported type us for instruction beqr.") #define jit_beqi_c(...) assert("Unsupported type c for instruction beqi.") #define jit_beqi_c(...) assert("Unsupported type c for instruction beqi.") #define jit_beqi_s(...) assert("Unsupported type s for instruction beqi.") #define jit_beqi_us(...) assert("Unsupported type us for instruction beqi.") #define jit_bner_c(...) assert("Unsupported type c for instruction bner.") #define jit_bner_c(...) assert("Unsupported type c for instruction bner.") #define jit_bner_s(...) assert("Unsupported type s for instruction bner.") #define jit_bner_us(...) assert("Unsupported type us for instruction bner.") #define jit_bnei_c(...) assert("Unsupported type c for instruction bnei.") #define jit_bnei_c(...) assert("Unsupported type c for instruction bnei.") #define jit_bnei_s(...) assert("Unsupported type s for instruction bnei.") #define jit_bnei_us(...) assert("Unsupported type us for instruction bnei.") #define jit_bunltr_c(...) assert("Unsupported type c for instruction bunltr.") #define jit_bunltr_c(...) assert("Unsupported type c for instruction bunltr.") #define jit_bunltr_s(...) assert("Unsupported type s for instruction bunltr.") #define jit_bunltr_us(...) assert("Unsupported type us for instruction bunltr.") #define jit_bunler_c(...) assert("Unsupported type c for instruction bunler.") #define jit_bunler_c(...) assert("Unsupported type c for instruction bunler.") #define jit_bunler_s(...) assert("Unsupported type s for instruction bunler.") #define jit_bunler_us(...) assert("Unsupported type us for instruction bunler.") #define jit_bungtr_c(...) assert("Unsupported type c for instruction bungtr.") #define jit_bungtr_c(...) assert("Unsupported type c for instruction bungtr.") #define jit_bungtr_s(...) assert("Unsupported type s for instruction bungtr.") #define jit_bungtr_us(...) assert("Unsupported type us for instruction bungtr.") #define jit_bunger_c(...) assert("Unsupported type c for instruction bunger.") #define jit_bunger_c(...) assert("Unsupported type c for instruction bunger.") #define jit_bunger_s(...) assert("Unsupported type s for instruction bunger.") #define jit_bunger_us(...) assert("Unsupported type us for instruction bunger.") #define jit_buneqr_c(...) assert("Unsupported type c for instruction buneqr.") #define jit_buneqr_c(...) assert("Unsupported type c for instruction buneqr.") #define jit_buneqr_s(...) assert("Unsupported type s for instruction buneqr.") #define jit_buneqr_us(...) assert("Unsupported type us for instruction buneqr.") #define jit_bltgtr_c(...) assert("Unsupported type c for instruction bltgtr.") #define jit_bltgtr_c(...) assert("Unsupported type c for instruction bltgtr.") #define jit_bltgtr_s(...) assert("Unsupported type s for instruction bltgtr.") #define jit_bltgtr_us(...) assert("Unsupported type us for instruction bltgtr.") #define jit_bordr_c(...) assert("Unsupported type c for instruction bordr.") #define jit_bordr_c(...) assert("Unsupported type c for instruction bordr.") #define jit_bordr_s(...) assert("Unsupported type s for instruction bordr.") #define jit_bordr_us(...) assert("Unsupported type us for instruction bordr.") #define jit_bunordr_c(...) assert("Unsupported type c for instruction bunordr.") #define jit_bunordr_c(...) assert("Unsupported type c for instruction bunordr.") #define jit_bunordr_s(...) assert("Unsupported type s for instruction bunordr.") #define jit_bunordr_us(...) assert("Unsupported type us for instruction bunordr.") #define jit_bmsr_c(...) assert("Unsupported type c for instruction bmsr.") #define jit_bmsr_c(...) assert("Unsupported type c for instruction bmsr.") #define jit_bmsr_s(...) assert("Unsupported type s for instruction bmsr.") #define jit_bmsr_us(...) assert("Unsupported type us for instruction bmsr.") #define jit_bmsi_c(...) assert("Unsupported type c for instruction bmsi.") #define jit_bmsi_c(...) assert("Unsupported type c for instruction bmsi.") #define jit_bmsi_s(...) assert("Unsupported type s for instruction bmsi.") #define jit_bmsi_us(...) assert("Unsupported type us for instruction bmsi.") #define jit_bmcr_c(...) assert("Unsupported type c for instruction bmcr.") #define jit_bmcr_c(...) assert("Unsupported type c for instruction bmcr.") #define jit_bmcr_s(...) assert("Unsupported type s for instruction bmcr.") #define jit_bmcr_us(...) assert("Unsupported type us for instruction bmcr.") #define jit_bmci_c(...) assert("Unsupported type c for instruction bmci.") #define jit_bmci_c(...) assert("Unsupported type c for instruction bmci.") #define jit_bmci_s(...) assert("Unsupported type s for instruction bmci.") #define jit_bmci_us(...) assert("Unsupported type us for instruction bmci.") #define jit_addr_uc(...) assert("Unsupported type uc for instruction addr.") #define jit_addi_uc(...) assert("Unsupported type uc for instruction addi.") #define jit_addxr_uc(...) assert("Unsupported type uc for instruction addxr.") #define jit_addxi_uc(...) assert("Unsupported type uc for instruction addxi.") #define jit_addcr_uc(...) assert("Unsupported type uc for instruction addcr.") #define jit_addci_uc(...) assert("Unsupported type uc for instruction addci.") #define jit_subr_uc(...) assert("Unsupported type uc for instruction subr.") #define jit_subi_uc(...) assert("Unsupported type uc for instruction subi.") #define jit_subxr_uc(...) assert("Unsupported type uc for instruction subxr.") #define jit_subxi_uc(...) assert("Unsupported type uc for instruction subxi.") #define jit_subcr_uc(...) assert("Unsupported type uc for instruction subcr.") #define jit_subci_uc(...) assert("Unsupported type uc for instruction subci.") #define jit_rsbr_uc(...) assert("Unsupported type uc for instruction rsbr.") #define jit_rsbi_uc(...) assert("Unsupported type uc for instruction rsbi.") #define jit_mulr_uc(...) assert("Unsupported type uc for instruction mulr.") #define jit_muli_uc(...) assert("Unsupported type uc for instruction muli.") #define jit_mulr_ul_(...) assert("Unsupported type ul for instruction mulr.") #define jit_hmulr_uc(...) assert("Unsupported type uc for instruction hmulr.") #define jit_hmuli_uc(...) assert("Unsupported type uc for instruction hmuli.") #define jit_divr_uc(...) assert("Unsupported type uc for instruction divr.") #define jit_divi_uc(...) assert("Unsupported type uc for instruction divi.") #define jit_modr_uc(...) assert("Unsupported type uc for instruction modr.") #define jit_modi_uc(...) assert("Unsupported type uc for instruction modi.") #define jit_andr_uc(...) assert("Unsupported type uc for instruction andr.") #define jit_andi_uc(...) assert("Unsupported type uc for instruction andi.") #define jit_orr_uc(...) assert("Unsupported type uc for instruction orr.") #define jit_ori_uc(...) assert("Unsupported type uc for instruction ori.") #define jit_xorr_uc(...) assert("Unsupported type uc for instruction xorr.") #define jit_xori_uc(...) assert("Unsupported type uc for instruction xori.") #define jit_lshr_uc(...) assert("Unsupported type uc for instruction lshr.") #define jit_lshi_uc(...) assert("Unsupported type uc for instruction lshi.") #define jit_rshr_uc(...) assert("Unsupported type uc for instruction rshr.") #define jit_rshi_uc(...) assert("Unsupported type uc for instruction rshi.") #define jit_negr_ul(...) assert("Unsupported type ul for instruction negr.") #define jit_negr_uc(...) assert("Unsupported type uc for instruction negr.") #define jit_ltr_uc(...) assert("Unsupported type uc for instruction ltr.") #define jit_lti_uc(...) assert("Unsupported type uc for instruction lti.") #define jit_ler_uc(...) assert("Unsupported type uc for instruction ler.") #define jit_lei_uc(...) assert("Unsupported type uc for instruction lei.") #define jit_gtr_uc(...) assert("Unsupported type uc for instruction gtr.") #define jit_gti_uc(...) assert("Unsupported type uc for instruction gti.") #define jit_ger_uc(...) assert("Unsupported type uc for instruction ger.") #define jit_gei_uc(...) assert("Unsupported type uc for instruction gei.") #define jit_eqr_uc(...) assert("Unsupported type uc for instruction eqr.") #define jit_eqi_uc(...) assert("Unsupported type uc for instruction eqi.") #define jit_ner_uc(...) assert("Unsupported type uc for instruction ner.") #define jit_nei_uc(...) assert("Unsupported type uc for instruction nei.") #define jit_unltr_ul(...) assert("Unsupported type ul for instruction unltr.") #define jit_unltr_uc(...) assert("Unsupported type uc for instruction unltr.") #define jit_unler_ul(...) assert("Unsupported type ul for instruction unler.") #define jit_unler_uc(...) assert("Unsupported type uc for instruction unler.") #define jit_ungtr_ul(...) assert("Unsupported type ul for instruction ungtr.") #define jit_ungtr_uc(...) assert("Unsupported type uc for instruction ungtr.") #define jit_unger_ul(...) assert("Unsupported type ul for instruction unger.") #define jit_unger_uc(...) assert("Unsupported type uc for instruction unger.") #define jit_uneqr_ul(...) assert("Unsupported type ul for instruction uneqr.") #define jit_uneqr_uc(...) assert("Unsupported type uc for instruction uneqr.") #define jit_ltgtr_ul(...) assert("Unsupported type ul for instruction ltgtr.") #define jit_ltgtr_uc(...) assert("Unsupported type uc for instruction ltgtr.") #define jit_ordr_ul(...) assert("Unsupported type ul for instruction ordr.") #define jit_ordr_uc(...) assert("Unsupported type uc for instruction ordr.") #define jit_unordr_ul(...) assert("Unsupported type ul for instruction unordr.") #define jit_unordr_uc(...) assert("Unsupported type uc for instruction unordr.") #define jit_movr_uc(...) assert("Unsupported type uc for instruction movr.") #define jit_movi_uc(...) assert("Unsupported type uc for instruction movi.") #define jit_extr_ul(...) assert("Unsupported type ul for instruction extr.") #define jit_extr_uc(...) assert("Unsupported type uc for instruction extr.") #define jit_roundr_ul(...) assert("Unsupported type ul for instruction roundr.") #define jit_roundr_uc(...) assert("Unsupported type uc for instruction roundr.") #define jit_truncr_ul(...) assert("Unsupported type ul for instruction truncr.") #define jit_truncr_uc(...) assert("Unsupported type uc for instruction truncr.") #define jit_floorr_ul(...) assert("Unsupported type ul for instruction floorr.") #define jit_floorr_uc(...) assert("Unsupported type uc for instruction floorr.") #define jit_ceilr_ul(...) assert("Unsupported type ul for instruction ceilr.") #define jit_ceilr_uc(...) assert("Unsupported type uc for instruction ceilr.") #define jit_hton_ul(...) assert("Unsupported type ul for instruction hton.") #define jit_hton_uc(...) assert("Unsupported type uc for instruction hton.") #define jit_ntoh_ul(...) assert("Unsupported type ul for instruction ntoh.") #define jit_ntoh_uc(...) assert("Unsupported type uc for instruction ntoh.") #define jit_bltr_uc(...) assert("Unsupported type uc for instruction bltr.") #define jit_blti_uc(...) assert("Unsupported type uc for instruction blti.") #define jit_bler_uc(...) assert("Unsupported type uc for instruction bler.") #define jit_blei_uc(...) assert("Unsupported type uc for instruction blei.") #define jit_bgtr_uc(...) assert("Unsupported type uc for instruction bgtr.") #define jit_bgti_uc(...) assert("Unsupported type uc for instruction bgti.") #define jit_bger_uc(...) assert("Unsupported type uc for instruction bger.") #define jit_bgei_uc(...) assert("Unsupported type uc for instruction bgei.") #define jit_beqr_uc(...) assert("Unsupported type uc for instruction beqr.") #define jit_beqi_uc(...) assert("Unsupported type uc for instruction beqi.") #define jit_bner_uc(...) assert("Unsupported type uc for instruction bner.") #define jit_bnei_uc(...) assert("Unsupported type uc for instruction bnei.") #define jit_bunltr_ul(...) assert("Unsupported type ul for instruction bunltr.") #define jit_bunltr_uc(...) assert("Unsupported type uc for instruction bunltr.") #define jit_bunler_ul(...) assert("Unsupported type ul for instruction bunler.") #define jit_bunler_uc(...) assert("Unsupported type uc for instruction bunler.") #define jit_bungtr_ul(...) assert("Unsupported type ul for instruction bungtr.") #define jit_bungtr_uc(...) assert("Unsupported type uc for instruction bungtr.") #define jit_bunger_ul(...) assert("Unsupported type ul for instruction bunger.") #define jit_bunger_uc(...) assert("Unsupported type uc for instruction bunger.") #define jit_buneqr_ul(...) assert("Unsupported type ul for instruction buneqr.") #define jit_buneqr_uc(...) assert("Unsupported type uc for instruction buneqr.") #define jit_bltgtr_ul(...) assert("Unsupported type ul for instruction bltgtr.") #define jit_bltgtr_uc(...) assert("Unsupported type uc for instruction bltgtr.") #define jit_bordr_ul(...) assert("Unsupported type ul for instruction bordr.") #define jit_bordr_uc(...) assert("Unsupported type uc for instruction bordr.") #define jit_bunordr_ul(...) assert("Unsupported type ul for instruction bunordr.") #define jit_bunordr_uc(...) assert("Unsupported type uc for instruction bunordr.") #define jit_bmsi_uc(...) assert("Unsupported type uc for instruction bmsi.") #define jit_bmcr_uc(...) assert("Unsupported type uc for instruction bmcr.") #define jit_bmci_uc(...) assert("Unsupported type uc for instruction bmci.")
zedshaw/earing
src/label.c
#include "function.h" #include "label.h" #include <assert.h> Label *Label_find(Function *func, Token *tk) { hnode_t *hn = hash_lookup(func->labels, tk->data); return hn ? hnode_get(hn) : NULL; } Token *Label_expression(Function *func, Token *tk) { Label *label = Label_find(func, tk); if(!label) { // forward label expression, create but not realized // label = Label_create_and_add(func, tk, 0); assert(label && "You must fix this Zed."); } else { if(label->realized) { // backward label expression tk->value = (unsigned long)label->ref; } else { // forward label expression that's being used again // do nothing with it, Call_operation will handle the gore } } return tk; }
zedshaw/earing
src/types.h
<filename>src/types.h #ifndef types_h #define types_h /** * These are used to determine the types of both operations and function returns. * For an operation it follows a '.' as in movi.ui(...). For functions it follows * the function's name after a ':' as in function adder : int. The lexer will actually * allow shorthand (i,ui,s,v) or long hand forms (int, uint, short, void) for * both functions and operations. */ typedef enum OpType { OpType_i, OpType_ui, OpType_l, OpType_ul, OpType_p, OpType_f, OpType_d, OpType_v, OpType_c, OpType_uc, OpType_s, OpType_us } OpType; const char *OpType_to_str(OpType type); #endif
zedshaw/earing
src/grammar.h
#define TK_EOL 1 #define TK_IDENT 2 #define TK_EQ 3 #define TK_LPAREN 4 #define TK_RPAREN 5 #define TK_COMMA 6 #define TK_OP 7 #define TK_DOT 8 #define TK_TYPE 9 #define TK_HEX 10 #define TK_FLOAT 11 #define TK_INT 12 #define TK_STR 13 #define TK_CHR 14 #define TK_REG 15 #define TK_LABEL 16 #define TK_LBRACK 17 #define TK_RBRACK 18 #define TK_PERCENT 19 #define TK_FUNCTION 20 #define TK_END 21 #define TK_COLON 22
zedshaw/earing
src/allocator.c
<filename>src/allocator.c #include "allocator.h" #include <gc/gc.h> #include "error.h" Token *Allocator_expression(Module *state, Token *tk) { if(!tk) { die(state, "invalid identifier given to allocation"); return NULL; } else { tk->value = (int)GC_MALLOC(tk->value); return tk; } } void *Allocator_malloc(int size) { return GC_MALLOC(size); } void *Allocator_realloc(void *mem, int new_size) { return GC_REALLOC(mem, new_size); } void Allocator_free(void *mem) { GC_FREE(mem); } void Allocator_collect() { GC_gcollect(); }
zedshaw/earing
tests/tst_tests.c
#include <cut/2.6/cut.h> #include "tst.h" #include <gc.h> void __CUT__tst_Bringup(void) { GC_INIT(); } void __CUT__tst_create(void) { tst_t *t = NULL; void *result = NULL; void *result2 = NULL; int val = 10; tst_collect_t vals; t = tst_insert(t, "test", 4, &val); ASSERT(t != NULL, "Failed to create."); result = tst_search(t, "test", 4); ASSERT(result == &val, "Wrong value returned."); t = tst_insert(t, "testit", 6, &result); ASSERT(t != NULL, "Failed to add more."); result2 = tst_search(t, "testit", 6); ASSERT(result2 == &result, "Second result wasn't right."); vals = tst_collect(t, "te", 2); ASSERT(vals.length == 2, "Didn't find all of them on collect."); ASSERT(vals.values[1] == &val, "Wrong first value."); ASSERT(vals.values[0] == &result, "Wrong second value."); }
zedshaw/earing
tests/error_tests.c
<filename>tests/error_tests.c #include <cut/2.6/cut.h> #include "error.h" #include <gc.h> void __CUT_error_Bringup(void) { GC_INIT(); } void __CUT__error_test(void) { CORD name = CORD_from_char_star("<NAME>"); int tested = 10; error(NULL, "%d times I called %r", tested, name); }
zedshaw/earing
src/util.c
<gh_stars>1-10 #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include "module.h" #include "error.h" #include <errno.h> #include "list.h" void run_function(Module *state, const char *named) { Function *func = NULL; func = tst_search(state->functions, named, strlen(named)); if(!func) { printf("Undefined function: '%s'\n", named); } else { if(list_isempty(func->params)) { printf("Sorry, this function takes parameters so it's not supported to call it yet.\n"); return; } switch(func->type) { case OpType_v: printf(">>\n"); func->fp.vptr(); break; case OpType_c: printf(">> %c\n", func->fp.cptr()); break; case OpType_uc: printf(">> %c\n", func->fp.ucptr()); break; case OpType_s: printf(">> %i\n", func->fp.sptr()); break; case OpType_us: printf(">> %i\n", func->fp.usptr()); break; case OpType_i: printf(">> %d\n", func->fp.iptr()); break; case OpType_ui: printf(">> %u\n", func->fp.uiptr()); break; case OpType_l: printf(">> %ld\n", func->fp.lptr()); break; case OpType_ul: printf(">> %lu\n", func->fp.ulptr()); break; case OpType_p: printf(">> %p\n", func->fp.pptr()); break; case OpType_f: printf(">> %f\n", func->fp.fptr()); break; case OpType_d: printf(">> %f\n", func->fp.dptr()); break; } } }
HPTears/commonDefine
Component/Classes/XKCommonEnum.h
// // XKCommonEnum.h // XKComponentBaseProject // // Created by Jamesholy on 2019/3/11. // Copyright © 2019 Jamesholy. All rights reserved. // #ifndef XKCommonEnum_h #define XKCommonEnum_h typedef NS_ENUM(NSInteger ,XKRelationType) { XKRelationNoting = 0, // 没关系 XKRelationOneWay, // 单向关系, 你关注了他 XKRelationTwoWay, // 双向关系 XKRelationThreeWay, // 他关注了你, 你没关注他 }; #endif /* XKCommonEnum_h */
HPTears/commonDefine
Component/Classes/XKComponentNotification.h
<reponame>HPTears/commonDefine // // XKComponentNotification.h // XKComponentBaseProject // // Created by Jamesholy on 2019/3/11. // Copyright © 2019 Jamesholy. All rights reserved. // #ifndef XKComponentNotification_h #define XKComponentNotification_h static NSString *const XKSecretFriendListInfoChangeNoti = @"XKSecretFriendListInfoChangeNoti"; //密友列表信息变化 加了密友/备注/删除/等请发这个通知 static NSString *const XKFriendListInfoChangeNoti = @"XKFriendListInfoChangeNoti"; // 可友信息列表变化 加了好友/备注/删除/等请发这个通知 static NSString *const XKSecretFriendListCacheChangeNoti = @"XKSecretFriendListCacheChangeNoti"; //密友缓存发生改变 static NSString *const XKFriendListCacheChangeNoti = @"XKFriendListCacheChangeNoti"; //好友缓存发生改变 static NSString *const XKUserCacheChangeNoti = @"XKUserCacheChangeNoti"; //relatetionUser缓存发生改变 #pragma mark - 刷新相关 static NSString *const XKIMBaseChatViewControllrtRefreshViewNotification = @"XKIMBaseChatViewControllrtRefreshViewNotification"; //刷新baseChatVC视图 #pragma mark - 音频相关 // IM开始播放音频 static NSString *const XKIMStartPlayAudioNotification = @"XKIMStartPlayAudioNotification"; // IM停止播放音频 static NSString *const XKIMStopPlayAudioNotification = @"XKIMStopPlayAudioNotification"; #endif /* XKComponentNotification_h */
HPTears/commonDefine
Component/Classes/XKCommonDefine.h
// // XKCommonDefine.h // XKComponentBaseProject // // Created by Jamesholy on 2019/2/28. // Copyright © 2019 Jamesholy. All rights reserved. // #ifndef XKCommonDefine_h #define XKCommonDefine_h //-------------------------- 数据库表名 -------------------------- //#define XKHistorySearchTable [NSString stringWithFormat:@"%@_%@", @"XKHistorySearchTable", [XKUserInfo getCurrentUserId]] #define XKIMP2PTopChatDataBaseTable @"XKIMP2PTopChatDataBaseTable" //可友单聊置顶 #define XKIMTeamTopChatDataBaseTable @"XKIMTeamTopChatDataBaseTable" //可友群聊置顶 #define XKIMSecretTopChatDataBaseTable @"XKIMSecretTopChatDataBaseTable" //密友单聊置顶 #define XKIMSecretSilenceChatDataBaseTable @"XKIMSecretSilenceChatDataBaseTable" //密友单聊静音 #define XKHistorySearchDataBaseTable @"XKHistorySearchDataBaseTable" //搜索历史 #define XKHistoryGamesDataBaseTable @"XKHistoryGamesDataBaseTable" //游戏历史(玩过的) #define XKHistorySearchGamesDataBaseTable @"XKHistorySearchGamesDataBaseTable" //搜索游戏历史 #define XKIMTeamChatShowNickNameBaseTable @"XKIMTeamChatShowNickNameBaseTable" //群聊显示昵称 #define XKIMSecretChatLastMessageDataBaseTable @"XKIMSecretChatLastMessageDataBaseTable" //密友最后一条消息 #define XKIMSecretMessageFireMyselfDataBaseTable @"XKIMSecretMessageFireMyselfDataBaseTable" //阅后即焚自己 #define XKIMSecretMessageFireOtherDataBaseTable @"XKIMSecretMessageFireOtherDataBaseTable" //阅后即焚对方 #define XKTouchIdOrFaceIdServerCheckCodeDataBaseTable @"XKTouchIdOrFaceIdServerCheckCodeDataBaseTable" //TouchID/FaceID服务器校验码 //-------------------------- 数据库表名 -------------------------- //app信息 #define XKAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] #define KEY_WINDOW [UIApplication sharedApplication].keyWindow //NavBar高度 #define NavigationBar_HEIGHT 44 //默认的NAVERgationBar 高度 #define kStatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height //状态栏高度。 iPhone X 之前是 20 iPhone X 是 44 #define NavigationAndStatue_Height (kStatusBarHeight+NavigationBar_HEIGHT) #define kBottomSafeHeight ((iPhoneX)?(34):(0)) //距离底部的安全距离 #define TabBar_Height (50 + kBottomSafeHeight) // Tabbar height. // 导航栏适配X #define kIphoneXNavi(XValue) (iPhoneX_Serious ? (XValue + 24) : (XValue)) //头像 大 #define BigAvatarWidth (SCREEN_WIDTH>320?44:40) //获取屏幕 宽度、高度 #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width #define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height #define BUTTON_WIDTH ((([UIScreen mainScreen].bounds.size.width) / 4) * 3) #define BUTTON_HEIGHT (((([UIScreen mainScreen].bounds.size.width) / 4) * 3) / 6.3) //根据375得到的比例 #define ScreenScale [NSString stringWithFormat:@"%.2f", SCREEN_WIDTH / 375.f].floatValue #define KFitScale (ScreenScale>1.0 ?:1.0) //根据667得到的比例 尽量不要使用这个 因为x xr xs 高度比正常的大 #define ScreenHeightScale [[UIScreen mainScreen] bounds].size.height/667.f // 三个屏幕尺寸对应的宽度高度 从大到小 #define kLMSScreenFit(L,M,S) ((SCREEN_WIDTH>=414.0f) ? (L) : (SCREEN_WIDTH>=375.0f) ? (M) : (S)) // 建议用这个适配 #define kLMS(L,M,S) kLMSScreenFit(L,M,S) //是否iphone5 320*568 #define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) // 是否为iPhone4/4S 320*480 #define iPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640,960), [[UIScreen mainScreen] currentMode].size) : NO) // 是否为iPhone6/6S/7/7S 375*667 #define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750,1334), [[UIScreen mainScreen] currentMode].size) : NO) // 是否为iPhone6*Plus/7*Plus 414*736 #define iPhone6P ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242,2208), [[UIScreen mainScreen] currentMode].size) : NO) //是否iPhone X 系列 兼容老代码 新代码判断是否有刘海请使用iPhoneX_Serious判断 单独判断iphoneX使用iphoneX_X #define iPhoneX iPhoneX_Serious //是否iPhone X 系列 用于判断是否有刘海 #define iPhoneX_Serious ([UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896) //判断iPhoneX、iPhoneXs 逻辑点375*812 #define iphoneX_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) #define iphoneX_Xs iphoneX_X //判断iPHoneXr 逻辑点414*896 #define iphoneX_Xr ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO) //判断iPhoneXs Max 逻辑点414*896 #define iphoneX_XsMax ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO) //************************** 颜色 ************************************************** // RGB颜色 #define RGB(r,g,b) RGBA(r,g,b,1) // RGB颜色 灰色 #define RGBGRAY(A) RGB(A,A,A) // 16进制颜色 #define HEX_RGB(rgbValue) HEX_RGBA(rgbValue, 1.0) // 获取RGB颜色 #define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a] #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] // 16进制颜色+透明度 #define HEX_RGBA(rgbValue, alphaValue) [UIColor \ colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0f \ green:((float)((rgbValue & 0x00FF00) >> 8))/255.0f \ blue:((float)(rgbValue & 0x0000FF))/255.0f \ alpha:alphaValue] //默认分割线颜色 #define XKSeparatorLineColor UIColorFromRGB(0xF1F1F1) //主体颜色 #define XKMainTypeColor UIColorFromRGB(0x4A90FA) #define XKMainRedColor UIColorFromRGB(0xEE6161) //密友颜色 #define XKSecreatFriendTypeColor UIColorFromRGB(0x4A90FA) //***************************** 字体 ************************************************* #define XKFont(fontName,fontSize) [UIFont setFontWithFontName:fontName andSize:fontSize] #define XKRegularFont(fontSize) XKFont(XK_PingFangSC_Regular,fontSize) #define XKSemiboldFont(fontSize) XKFont(XK_PingFangSC_Semibold,fontSize) #define XKMediumFont(fontSize) XKFont(XK_PingFangSC_Medium,fontSize) #define XKNormalFont(fontSize) [UIFont systemFontOfSize:fontSize] //***************************** UI ************************************************* #define XKViewSize(size) size * KFitScale #define XK_PingFangSC_Regular @"PingFangSC-Regular" #define XK_PingFangSC_Semibold @"PingFangSC-Semibold" #define XK_PingFangSC_Medium @"PingFangSC-Medium" //******************************* 强弱引用 *********************************************** #define XKWeakSelf(weakSelf) __weak __typeof(&*self) weakSelf = self; #define XKStrongSelf(strongSelf) __strong __typeof(&*self) strongSelf = weakSelf; // 一般对象的弱引用 #define WEAK_TYPES(instance) __weak typeof(instance) weak##instance = instance; //******************************* 安全执行block ******************************* #define EXECUTE_BLOCK(A,...) if(A){A(__VA_ARGS__);} // log #ifdef DEBUG #define NSLog(...) {NSTimeInterval time_interval = [[NSDate date]timeIntervalSince1970];\ NSString *logoInfo = [NSString stringWithFormat:__VA_ARGS__];\ printf("%f %s\n",time_interval,[logoInfo UTF8String]); \ [[NSNotificationCenter defaultCenter] postNotificationName:@"xk_log_noti" object: [NSString stringWithFormat:@"%.2f %@\n %@\n",time_interval,[NSThread currentThread],logoInfo]];} #else #define NSLog(...) #endif /* --------------------------- 常用工具宏-----------------------------*/ #define XKUserDefault [NSUserDefaults standardUserDefaults] #define IMG_NAME(imgName) [UIImage imageNamed:imgName] #define kURL(urlStr) [NSURL URLWithString:urlStr] #define kNeedFixHudOffestViewTag 1314520 #define FIXME_TO_WRITE_FUNCTION [XKAlertView showCommonAlertViewWithTitle:[NSString stringWithFormat:@"%s\n方法未实现功能",__func__]]; /* ------------------------- NSUserDefaults的相关 ------------------------*/ #define USER_DEFAULT [NSUserDefaults standardUserDefaults] // 获得存储的对象 #define UserDefaultSetObjectForKey(__VALUE__,__KEY__) \ {\ [[NSUserDefaults standardUserDefaults] setObject:__VALUE__ forKey:__KEY__];\ [[NSUserDefaults standardUserDefaults] synchronize];\ } // 取值 #define UserDefaultObjectForKey(__KEY__) [[NSUserDefaults standardUserDefaults] objectForKey:__KEY__] // 删除对象 #define UserDefaultRemoveObjectForKey(__KEY__) \ {\ [[NSUserDefaults standardUserDefaults] removeObjectForKey:__KEY__];\ [[NSUserDefaults standardUserDefaults] synchronize];\ } #endif /* XKCommonDefine_h */
Jongkeun/Papago-cpp
Papago-cpp/Papago-cppDlg.h
<reponame>Jongkeun/Papago-cpp<gh_stars>1-10 // Papago-cppDlg.h : header file // #pragma once // CPapagocppDlg dialog class CPapagocppDlg : public CDialogEx { // Construction public: CPapagocppDlg(CWnd* pParent = nullptr); // standard constructor // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_PAPAGOCPP_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CButton m_btnTranslation; afx_msg void OnBnClickedButtonTranslation(); CComboBox m_cboFrom; CComboBox m_cboTo; CEdit m_txtFrom; CEdit m_txtTo; CStatic m_lbCurrLang; };
yushansu/incubator-tvm
src/runtime/contrib/sparse/csrmm.h
<gh_stars>0 #pragma once #include <tvm/runtime/data_type.h> #include <tvm/runtime/registry.h> namespace tvm { namespace contrib { using namespace runtime; void jiacsrmm(int* colptr, int* rowidx, float* values, int N, int K, int C, float* l_a, float* l_c); } }
swegener/stlink
flash/main.c
/* simple wrapper around the stlink_flash_write function */ // TODO - this should be done as just a simple flag to the st-util command line... #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include "stlink-common.h" #define DEBUG_LOG_LEVEL 100 #define STND_LOG_LEVEL 50 enum st_cmds {DO_WRITE = 0, DO_READ = 1, DO_ERASE = 2}; struct opts { enum st_cmds cmd; const char* devname; char *serial; const char* filename; stm32_addr_t addr; size_t size; int reset; int log_level; }; static void usage(void) { puts("stlinkv1 command line: ./st-flash [--debug] [--reset] [--serial <iSerial>] {read|write} /dev/sgX path addr <size>"); puts("stlinkv1 command line: ./st-flash [--debug] /dev/sgX erase"); puts("stlinkv2 command line: ./st-flash [--debug] [--reset] [--serial <iSerial>] {read|write} path addr <size>"); puts("stlinkv2 command line: ./st-flash [--debug] [--serial <iSerial>] erase"); puts(" use hex format for addr, <iSerial> and <size>"); } static int get_opts(struct opts* o, int ac, char** av) { /* stlinkv1 command line: ./st-flash {read|write} /dev/sgX path addr <size> */ /* stlinkv2 command line: ./st-flash {read|write} path addr <size> */ unsigned int i = 0; if (ac < 1) return -1; if (strcmp(av[0], "--debug") == 0) { o->log_level = DEBUG_LOG_LEVEL; ac--; av++; } else { o->log_level = STND_LOG_LEVEL; } if (strcmp(av[0], "--reset") == 0) { o->reset = 1; ac--; av++; } else { o->reset = 0; } if (strcmp(av[0], "--serial") == 0) { ac--; av++; int i=strlen(av[0]); if(i%2 != 0){ puts("no valid hex value, length must be multiple of 2\n"); return -1; } int j=0; while(i>=0 && j<=13){ char buffer[3]={0}; memcpy(buffer,&av[0][i],2); o->serial[12-j] = (char)strtol((const char*)buffer,NULL, 16); j++; i-=2; } ac--; av++; } else { o->serial = NULL; } if (ac < 1) return -1; /* stlinkv2 */ o->devname = NULL; if (strcmp(av[0], "erase") == 0) { o->cmd = DO_ERASE; /* stlinkv1 mode */ if (ac == 2) { o->devname = av[1]; i = 1; } } else { if (ac < 3) return -1; if (strcmp(av[0], "read") == 0) { o->cmd = DO_READ; /* stlinkv1 mode */ if (ac == 5) { o->devname = av[1]; i = 1; } if (ac > 3) o->size = strtoul(av[i + 3], NULL, 16); } else if (strcmp(av[0], "write") == 0) { o->cmd = DO_WRITE; /* stlinkv1 mode */ if (ac == 4) { o->devname = av[1]; i = 1; } } else { return -1; } } o->filename = av[i + 1]; o->addr = strtoul(av[i + 2], NULL, 16); return 0; } int main(int ac, char** av) { stlink_t* sl = NULL; struct opts o; char serial_buffer[13] = {0}; o.serial = serial_buffer; int err = -1; o.size = 0; if (get_opts(&o, ac - 1, av + 1) == -1) { printf("invalid command line\n"); usage(); goto on_error; } if (o.devname != NULL) /* stlinkv1 */ { sl = stlink_v1_open(o.log_level, 1); if (sl == NULL) goto on_error; sl->verbose = o.log_level; } else /* stlinkv2 */ { sl = stlink_open_usb(o.log_level, 1, o.serial); if (sl == NULL) goto on_error; sl->verbose = o.log_level; } if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE) stlink_exit_dfu_mode(sl); if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE) stlink_enter_swd_mode(sl); if (o.reset){ stlink_jtag_reset(sl,2); stlink_reset(sl); } // Disable DMA - Set All DMA CCR Registers to zero. - AKS 1/7/2013 if (sl->chip_id == STM32_CHIPID_F4) { memset(sl->q_buf,0,4); for (int i=0;i<8;i++) { stlink_write_mem32(sl,0x40026000+0x10+0x18*i,4); stlink_write_mem32(sl,0x40026400+0x10+0x18*i,4); stlink_write_mem32(sl,0x40026000+0x24+0x18*i,4); stlink_write_mem32(sl,0x40026400+0x24+0x18*i,4); } } // Core must be halted to use RAM based flashloaders stlink_force_debug(sl); stlink_status(sl); if (o.cmd == DO_WRITE) /* write */ { if ((o.addr >= sl->flash_base) && (o.addr < sl->flash_base + sl->flash_size)) { err = stlink_fwrite_flash(sl, o.filename, o.addr); if (err == -1) { printf("stlink_fwrite_flash() == -1\n"); goto on_error; } } else if ((o.addr >= sl->sram_base) && (o.addr < sl->sram_base + sl->sram_size)) { err = stlink_fwrite_sram(sl, o.filename, o.addr); if (err == -1) { printf("stlink_sram_flash() == -1\n"); goto on_error; } } } else if (o.cmd == DO_ERASE) { err = stlink_erase_flash_mass(sl); if (err == -1) { printf("stlink_fwrite_flash() == -1\n"); goto on_error; } } else /* read */ { if ((o.addr >= sl->flash_base) && (o.size == 0) && (o.addr < sl->flash_base + sl->flash_size)) o.size = sl->flash_size; else if ((o.addr >= sl->sram_base) && (o.size == 0) && (o.addr < sl->sram_base + sl->sram_size)) o.size = sl->sram_size; err = stlink_fread(sl, o.filename, o.addr, o.size); if (err == -1) { printf("stlink_fread() == -1\n"); goto on_error; } } if (o.reset){ stlink_jtag_reset(sl,2); stlink_reset(sl); } /* success */ err = 0; on_error: if (sl != NULL) { stlink_exit_debug_mode(sl); stlink_close(sl); } return err; }
C0rmander/software3DEngine
VertexShader.h
<gh_stars>0 #ifndef VERTEXSHADER_H #define VERTEXSHADER_H #include <vector> #include <SDL.h> #include <string> #include <unordered_map> #include "Vector3D.h" #include "Face3D.h" using namespace std; class VertexShader { public: VertexShader(); VertexShader(unordered_map<int, vector<Vector3D> > Normals); vector<Vector3D> rotateMesh(vector<Vector3D>& vec3d, struct Matrix3D& mat); //Vector3D* getNormals(vector<Vector3D>& vec3d, vector<Face3D>& face); Vector3D* updateNormals(Vector3D*& normals, Matrix3D& Mat, size_t normalsSize); void addNormalsToMap(const int facePoint, Vector3D& normal); unordered_map<int, vector<Vector3D>> getNormals(); vector<Vector3D> getNormalsAtPoint(int point); void ClearMap(); }; #endif // VERTEXSHADER_H
C0rmander/software3DEngine
Matrix3D.h
#ifndef MATRIX3D_H #define MATRIX3D_H #include "Vector3D.h" struct Matrix3D { private: float n[3] [3]; float test[3] [3]; public: Matrix3D() { } Matrix3D(float n00, float n01, float n02, float n10, float n11, float n12, float n20, float n21, float n22) { test[0][0] = n00; test[0][1] = n10; test[0][2] = n20; test[1][0] = n01; test[1][1] = n11; test[1][2] = n21; test[2][0] = n02; test[2][1] = n12; test[2][2] = n22; } // Matrix3D(float n00, float n01, float n10, float n11) // { // test[0][0] = n00; test[0][1] = n01; // test[1][0] = n10; test[1][1] = n11; // } // Matrix3D(Vector3D& a, Vector3D& b, Vector3D& c) // { // // // n[0][0] = a.getX(); n[0][1] = a.getY(); n[0][2] = a.getZ(); // n[1][0] = b.getX(); n[1][1] = b.getY(); n[1][2] = b.getZ(); // n[2][0] = c.getX(); n[2][1] = c.getY(); n[2][2] = c.getZ(); // } float& operator () (int i, int j) { return (test[j][i]); } const Vector3D& operator [] (int j) const { return (*reinterpret_cast<const Vector3D *>(test[j])); } const float& operator () (int i, int j) const { return (test[j][i]); } //inline Vector3D operator * (const Vector3D& v, float s) const Matrix3D Inverse(const Matrix3D& M) { const Vector3D a = M[0]; const Vector3D b = M[1]; const Vector3D c = M[2]; Vector3D r0 = r0.Cross(b,c); Vector3D r1 = r1.Cross(c,a); Vector3D r2 = r2.Cross(a,b); float invDet = 1.0f / r0.Dot (r2,c); return (Matrix3D(r0.x * invDet, r0.y * invDet, r0.z* invDet, r1.x * invDet, r1.y * invDet, r1.z* invDet, r2.x * invDet, r2.y * invDet, r2.z* invDet)); } }; inline Vector3D operator * (const Matrix3D& M, Vector3D& v) { return Vector3D((M(0,0) * v.x) + (M(0,1) * v.y) + (M(0,2)* v.z), (M(1,0) * v.x) + (M(1,1) * v.y) + (M(1,2)* v.z), (M(2,0) * v.x)+(M(2,1) * v.y)+(M(2,2) * v.z)); } #endif // MATRIX3D_H
C0rmander/software3DEngine
Face3D.h
#ifndef FACE3D_H #define FACE3D_H #include "Vector3D.h" struct Face3D { int f1,f2,f3; Face3D() { } Face3D(int a, int b, int c) { f1=a; f2=b; f3=c; } Face3D(const std::vector <float> &face) { if(face.size() == 3) { f1 = face[0]; f2 = face[1]; f3 = face[2]; } else { f1=0; f2=0; f3=0; } }; int getF1() { return f1; } int getF2() { return f2; } int getF3() { return f3; } void setF1(int a) { f1=a; } void setF2(int b) { f2=b; } void setF3(int c) { f3=c; } inline Vector3D FaceNormal(const Vector3D& vec1, const Vector3D& vec2,const Vector3D& vec3) { Vector3D n; return n.Cross(vec2 - vec1,vec3 - vec1); } }; #endif // FACE3D_H
C0rmander/software3DEngine
Obj_Loader.h
#ifndef OBJ_LOADER_H #define OBJ_LOADER_H #include "Vector3D.h" #include "Face3D.h" #include <vector> #include "Tex_Loader.h" #include <map> using namespace std; class Obj_Loader { public: Obj_Loader(); vector<struct Vector3D> verts(string OBJfile); vector<struct Face3D> faces(); vector<struct Vector3D> normals(); map<int,string> getMaterialNames(); }; #endif // OBJ_LOADER_H
C0rmander/software3DEngine
Draw.h
#ifndef DRAW_H #define DRAW_H #include "Draw.h" #include "Vector3D.h" #include <SDL.h> #include <stdio.h> #include <iostream> #include <fstream> #include<windows.h> #include <sstream> #include <string> using namespace std; const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; class Draw { public: Draw(); int startEngine(); void Triangle(struct Vector3D vec1,struct Vector3D vec2, struct Vector3D vec3); void Pixel(struct Vector3D vec1); void line(double x1, double y1, double x2, double y2); //float area(int x1, int y1, int x2, int y2, int x3, int y3); // bool cullingArea(int x1, int y1, int x2, int y2, int x3, int y3); Vector3D normalise(struct Vector3D vec1); Vector3D ScalePos(struct Vector3D vec); struct Matrix3D RotateRight(float timeStep); struct Matrix3D RotateLeft(float timeStep); struct Matrix3D RotateUp(float timeStep); struct Matrix3D RotateDown(float timeStep); }; #endif // DRAW_H
C0rmander/software3DEngine
Tex_Loader.h
#ifndef TEX_LOADER_H #define TEX_LOADER_H #include "Texture2D.h" #include <string> #include <vector> #include "Face3D.h" #include <SDL.h> using namespace std; class Tex_Loader { public: Tex_Loader(); SDL_Surface* getTex(string TEXfile); void setTexCoords(vector<Texture2D>& texcoords); vector<Texture2D> getTexCoords(); void setTexFaces(vector<Face3D>& texfaces); vector<Face3D> getTexFaces(); vector<SDL_Surface*> getMat(string Matfile, string mat); }; #endif // TEX_LOADER_H
C0rmander/software3DEngine
kiss_events_system.h
#ifndef KISS_EVENTS_SYSTEM_H #define KISS_EVENTS_SYSTEM_H #include "kiss_sdl.h" #include <stdio.h> #include <iostream> #include<vector> class kiss_events_system { public: kiss_events_system(); static void text_reset(kiss_textbox *textbox, kiss_vscrollbar *vscrollbar); static float hscrollbar_event(kiss_hscrollbar *hscrollbar, kiss_textbox *textbox2, SDL_Event *e, int *draw); static float hscrollbar_event_spec(kiss_hscrollbar *hscrollbar, kiss_label *label1, SDL_Event *e, int *draw); static float hscrollbar_event_diff(kiss_hscrollbar *hscrollbar, kiss_label *label1, SDL_Event *e, int *draw); static float hscrollbar_event_amb(kiss_hscrollbar *hscrollbar, kiss_label *label1, SDL_Event *e, int *draw); static void dirent_read(kiss_textbox *textbox1, kiss_vscrollbar *vscrollbar1, kiss_textbox *textbox2, kiss_vscrollbar *vscrollbar2, kiss_label *label_sel); static void textbox1_event(kiss_textbox *textbox, SDL_Event *e, kiss_vscrollbar *vscrollbar1, kiss_textbox *textbox2, kiss_vscrollbar *vscrollbar2, kiss_label *label_sel, int *draw); static void vscrollbar1_event(kiss_vscrollbar *vscrollbar, SDL_Event *e, kiss_textbox *textbox1, int *draw); static void textbox2_event(kiss_textbox *textbox, SDL_Event *e, kiss_vscrollbar *vscrollbar2, kiss_entry *entry, int *draw); static void vscrollbar2_event(kiss_vscrollbar *vscrollbar, SDL_Event *e, kiss_textbox *textbox2, int *draw); static void button_ok1_event(kiss_button *button, SDL_Event *e, kiss_window *window1, kiss_window *pane1, kiss_label *label_sel, kiss_entry *entry, kiss_label *label_res, kiss_progressbar *progressbar, int *draw); static void button_cancel_event(kiss_button *button, SDL_Event *e, int *quit, int *draw); static void button_ok2_event(kiss_button *button, SDL_Event *e, kiss_window *window1, kiss_window *pane1, kiss_progressbar *progressbar, int *draw); std::vector<float> mouse_move_window1_event(SDL_Window*& WINDOW1, SDL_Event *e, int *draw); }; #endif // KISS_EVENTS_SYSTEM_H
C0rmander/software3DEngine
Texture2D.h
<filename>Texture2D.h #ifndef TEXTURE2D_H #define TEXTURE2D_H #include <vector> struct Texture2D { double Tx,Ty; Texture2D() { } Texture2D(double a, double b) { Tx=a; Ty=b; } Texture2D(const std::vector <float> &tex) { // if(tex.size() == 2) // { Tx = tex[0]; Ty = tex[1]; // } }; double getTx() { return Tx; } double getTy() { return Ty; } void setTx(double a) { Tx=a; } void setTy(double b) { Ty=b; } }; #endif // FACE3D_H
C0rmander/software3DEngine
kiss_general.c
<reponame>C0rmander/software3DEngine /* kiss_sdl widget toolkit Copyright (c) 2016 <NAME> <<EMAIL>> 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. kiss_sdl version 1.2.0 */ #include "kiss_sdl.h" int kiss_makerect(SDL_Rect *rect, int x, int y, int w, int h) { if (!rect) return -1; rect->x = x; rect->y = y; rect->w = w; rect->h = h; return 0; } int kiss_pointinrect(int x, int y, SDL_Rect *rect) { return x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h; } int kiss_utf8next(char *str, int index) { int i; if (!str || index < 0) return -1; if (!str[index]) return 0; for (i = 1; str[index + i]; i++) if ((str[index + i] & 128) == 0 || (str[index + i] & 224) == 192 || (str[index + i] & 240) == 224 || (str[index + i] & 248) == 240) break; return i; } int kiss_utf8prev(char *str, int index) { int i; if (!str || index < 0) return -1; if (!index) return 0; for (i = 1; index - i; i++) if ((str[index - i] & 128) == 0 || (str[index - i] & 224) == 192 || (str[index - i] & 240) == 224 || (str[index - i] & 248) == 240) break; return i; } int kiss_utf8fix(char *str) { int len, i; if (!str || !str[0]) return -1; len = strlen(str); for (i = len - 1; i >= 0 && len - 1 - i < 3; i--) { if ((str[i] & 224) == 192 && len - 1 - i < 1) str[i] = 0; if ((str[i] & 240) == 224 && len - 1 - i < 2) str[i] = 0; if ((str[i] & 248) == 240 && len - 1 - i < 3) str[i] = 0; } return 0; } char *kiss_string_copy(char *dest, size_t size, char *str1, char *str2) { unsigned int len; char *p; if (!dest) return NULL; strcpy(dest, ""); if (size < 2) return dest; if (str1) strncpy(dest, str1, size); dest[size - 1] = 0; len = strlen(dest); if (!str2 || size - 1 <= len) return dest; p = dest; strncpy(p + len, str2, size - len); dest[size - 1] = 0; kiss_utf8fix(dest); return dest; } int kiss_string_compare(const void *a, const void *b) { return strcmp(*((char **) a), *((char **) b)); } char *kiss_backspace(char *str) { int len; if (!str) return NULL; if (!(len = strlen(str))) return NULL; str[len - 1] = 0; kiss_utf8fix(str); return str; } int kiss_array_new(kiss_array *a) { if (!a) return -1; a->size = KISS_MIN_LENGTH; a->length = 0; a->ref = 1; a->data = (void **) malloc(KISS_MIN_LENGTH * sizeof(void *)); a->id = (int *) malloc(KISS_MIN_LENGTH * sizeof(int)); return 0; } void *kiss_array_data(kiss_array *a, int index) { if (index < 0 || index >= a->size || !a) return NULL; return a->data[index]; } int kiss_array_id(kiss_array *a, int index) { if (!a || index < 0 || index >= a->size) return 0; return a->id[index]; } int kiss_array_assign(kiss_array *a, int index, int id, void *data) { if (!a || index < 0 || index >= a->length) return -1; free(a->data[index]); a->data[index] = data; a->id[index] = id; return 0; } int kiss_array_append(kiss_array *a, int id, void *data) { int i; if (!a) return -1; if (a->length >= a->size) { a->size *= 2; a->data = (void **) realloc(a->data, a->size * sizeof(void *)); a->id = (int *) realloc(a->id, a->size * sizeof(int)); for (i = a->length; i < a->size; i++) { a->data[i] = NULL; a->id[i] = 0; } } a->data[a->length] = data; a->id[a->length] = id; ++a->length; return 0; } int kiss_array_appendstring(kiss_array *a, int id, char *text1, char *text2) { char *p; if (!a) return -1; p = (char *) malloc(KISS_MAX_LENGTH); kiss_string_copy(p, KISS_MAX_LENGTH, text1, text2); kiss_array_append(a, id, p); return 0; } int kiss_array_insert(kiss_array *a, int index, int id, void *data) { int i; if (!a || index < 0 || index >= a->length) return -1; if (a->length >= a->size) { a->size *= 2; a->data = (void **) realloc(a->data, a->size * sizeof(void *)); a->id = (int *) realloc(a->id, a->size * sizeof(int)); for (i = a->length; i < a->size; i++) { a->data[i] = NULL; a->id[i] = 0; } } for (i = a->length - 1; i >= index; i--) { a->data[i + 1] = a->data[i]; a->id[i + 1] = a->id[i]; } a->data[index] = data; a->id[index] = id; ++a->length; return 0; } int kiss_array_remove(kiss_array *a, int index) { int i; if (!a || index < 0 || index >= a->length) return -1; free(a->data[index]); for (i = index; i < a->length - 1; i++) { a->data[i] = a->data[i + 1]; a->id[i] = a->id[i + 1]; } a->data[a->length - 1] = NULL; a->id[a->length - 1] = 0; --a->length; return 0; } int kiss_array_replace(kiss_array *a, int index, double num) { int i; if (!a || index < 0 || index >= a->length) return -1; free(a->data[index]); a->data[index] = &num; return 0; } int kiss_array_free(kiss_array *a) { int i; if (!a || !a->ref) return -1; if (a->ref > 1) { --a->ref; return 0; } if (a->length) for (i = 0; i < a->length; i++) free (a->data[i]); free(a->data); free(a->id); a->data = NULL; a->id = NULL; a->size = 0; a->length = 0; a->ref = 0; return 0; }
C0rmander/software3DEngine
MTL.h
<filename>MTL.h<gh_stars>0 #ifndef MTL_H #define MTL_H #include <string> #include "SDL.h" #include "Vector3D.h" struct MTL { Vector3D Ka,Kd,Ks; std::string newMTL; SDL_Surface* map_Kd = nullptr; MTL() { } MTL(std::string newmtl, Vector3D ka, Vector3D kd, Vector3D ks, SDL_Surface* map_kd) { newMTL = newmtl; Ka = ka; Kd = kd; Ks = ks; map_Kd = map_kd; } }; #endif // MTL_H
C0rmander/software3DEngine
Vector3D.h
#ifndef VECTOR3D_H #define VECTOR3D_H #include <cmath> #include <vector> struct Vector3D { float x,y,z; Vector3D() { } //Vector3D(double& a, double& b, double& c) //{ // x=a; // y=b; // z=c; //}; Vector3D(const std::vector <float> &vertex) { if(vertex.size() == 3) { x = vertex[0]; y = vertex[1]; z = vertex[2]; } }; Vector3D(float a, float b, float c) { x=a; y=b; z=c; }; inline Vector3D Cross (const Vector3D& a, const Vector3D& b) { return (Vector3D (a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x)); } double getX() { return x; } double getY() { return y; } double getZ() { return z; } void setX(float a) { x = a; } void setY(float b) { y = b; } void setZ(float c) { z = c; } inline float Dot(const Vector3D& vec1, const Vector3D& vec2) { return (vec1.x*vec2.x + vec1.y*vec2.y+vec1.z*vec2.z); } inline float Mag(const Vector3D& vec1) { return sqrt(pow(vec1.x,2.0) + pow(vec1.y,2.0) + pow(vec1.z,2.0)); } inline float Mag2D(const Vector3D& vec1) { return sqrt(pow(vec1.x,2.0) + pow(vec1.y,2.0)); } }; inline Vector3D operator / (const Vector3D& v, float s) { s = 1.0f / s; return (Vector3D(v.x*s, v.y*s, v.z*s)); } inline bool operator != (const Vector3D v1, const Vector3D v2) { if(v1.x != v2.x || v1.y != v2.y || v1.z != v2.z) { return true; } else { return false; } } inline bool operator == (const Vector3D v1, const Vector3D v2) { if(v1.x == v2.x && v1.y == v2.y && v1.z == v2.z) { return true; } else { return false; } } inline Vector3D operator * (const Vector3D& v, float s) { return (Vector3D(v.x*s, v.y*s, v.z*s)); } inline Vector3D operator * (const Vector3D& vec1, const Vector3D& vec2) { return (Vector3D(vec1.x*vec2.x, vec1.y*vec2.y, vec1.z*vec2.z)); } inline Vector3D operator + (const Vector3D& vec1, const Vector3D& vec2) { return (Vector3D(vec1.x+vec2.x, vec1.y+vec2.y, vec1.z+vec2.z)); } inline Vector3D operator - (const Vector3D& vec1, const Vector3D& vec2) { return (Vector3D(vec1.x-vec2.x, vec1.y-vec2.y, vec1.z-vec2.z)); } inline Vector3D operator - (const Vector3D& vec1, const float& s) { return (Vector3D(vec1.x-s, vec1.y-s, vec1.z-s)); } #endif // VECTOR3D_H
C0rmander/software3DEngine
MathsFunc.h
#ifndef MATHSFUNC_H #define MATHSFUNC_H #include <vector> #include "Vector3D.h" #include "Face3D.h" #include <string> using namespace std; class MathsFunc { public: MathsFunc(); struct Vector3D minXY(struct Vector3D vec1,struct Vector3D vec2,struct Vector3D vec3, int xTransform, int yTransform, int scaleX); struct Vector3D maxXY(struct Vector3D vec1,struct Vector3D vec2,struct Vector3D vec3, int xTransform, int yTransform, int scaleX); struct Vector3D normalise(struct Vector3D vec1); struct Vector3D Substract(struct Vector3D C, struct Vector3D A); struct Vector3D Add(struct Vector3D C, struct Vector3D A); float DotProduct(struct Vector3D vec1, struct Vector3D vec2); float Dot2D(struct Vector3D vec1, struct Vector3D vec2); float area(int x1, int y1, int x2, int y2, int x3, int y3); bool cullingArea(int x1, int y1, int x2, int y2, int x3, int y3); struct Vector3D ScalePos(struct Vector3D vec, int xTransform, int scaleX, int yTransform); struct Vector3D matrixMultiply(const struct Matrix3D mat, struct Vector3D vec); double doublearea(double x1, double y1, double x2, double y2, double x3, double y3); struct Vector3D VecDoubleMultiply(struct Vector3D vec1, double doub); struct vector<vector<Vector3D>> ReJigVecNorms(struct Vector3D vec1,struct Vector3D vec2,struct Vector3D vec3,struct Vector3D norm1, struct Vector3D norm2, struct Vector3D norm3); struct Vector3D VecAverage(const vector<Vector3D>& avg_normals); struct Vector3D rgb_multiply(struct Vector3D vec1, struct Vector3D vec2); float TriArea(Vector3D& vec1,Vector3D& vec2); vector<float> splitf(string str,char delim); }; #endif // MATHSFUNC_H
C0rmander/software3DEngine
FragmentShader.h
<gh_stars>0 #ifndef FRAGMENTSHADER_H #define FRAGMENTSHADER_H #include <vector> #include "Face3D.h" #include "Matrix3D.h" #include <SDL.h> #include <string> #include "MTL.h" using namespace std; class FragmentShader { public: FragmentShader(SDL_Renderer* render); void get_scanline(const vector<MTL>& materials, int Width, int Height, const vector<Face3D>& face, const vector<Vector3D> &vec3d, const float& Spec = 5); }; #endif // FRAGMENTSHADER_H
C0rmander/software3DEngine
MTL_Loader.h
#ifndef MTL_LOADER_H #define MTL_LOADER_H #include <vector> #include "Vector3D.h" #include "SDL.h" #include <string> #include <unordered_map> #include "MTL.h" class MTL_Loader { public: MTL_Loader(); std::vector<MTL> getMaterials(); std::vector<Vector3D> getAmbientColour(); std::vector<Vector3D> getDiffuseColour(); std::vector<Vector3D> getSpecularColour(); std::vector<SDL_Surface*> getSurfaces(); std::vector<std::string> getUrls(); std::vector<std::string> getMatNames(); std::vector <MTL> readFile(std::string MTLfile); }; #endif // MTL_LOADER_H
C0rmander/software3DEngine
Pixel.h
<filename>Pixel.h #ifndef PIXEL_H #define PIXEL_H #include "Vector3D.h" #include "SDL.h" struct Pixel { Vector3D Coordinates, Colour, Normal; Pixel(); Pixel(Vector3D coordinates, Vector3D colour, Vector3D normal) { Coordinates = coordinates; Colour = colour; Normal = normal; } }; #endif // PIXEL_H
C0rmander/software3DEngine
Widget.h
<reponame>C0rmander/software3DEngine #ifndef WIDGET_H #define WIDGET_H #include "MathsFunc.h" #include <stdio.h> #include <iostream> class Widget { public: Widget(); DrawArrow(float x, float y, uint32_t colour); protected: private: }; #endif // WIDGET_H
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/arch.h
<reponame>windayski/inclavare-containers /* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */ /** * Copyright(c) 2016-18 Intel Corporation. * * Contains data structures defined by the SGX architecture. Data structures * defined by the Linux software stack should not be placed here. */ #ifndef _ASM_X86_SGX_ARCH_H #define _ASM_X86_SGX_ARCH_H #include <assert.h> #include <linux/types.h> #define SGX_CPUID 0x12 #define SGX_CPUID_FIRST_VARIABLE_SUB_LEAF 2 #ifndef BIT #define BIT(nr) (1UL << (nr)) #endif #define EREPORT 0 /** * enum sgx_return_code - The return code type for ENCLS, ENCLU and ENCLV * %SGX_NOT_TRACKED: Previous ETRACK's shootdown sequence has not * been completed yet. * %SGX_INVALID_EINITTOKEN: EINITTOKEN is invalid and enclave signer's * public key does not match IA32_SGXLEPUBKEYHASH. * %SGX_UNMASKED_EVENT: An unmasked event, e.g. INTR, was received */ enum sgx_return_code { SGX_NOT_TRACKED = 11, SGX_INVALID_EINITTOKEN = 16, SGX_UNMASKED_EVENT = 128, }; /** * enum sgx_sub_leaf_types - SGX CPUID variable sub-leaf types * %SGX_CPUID_SUB_LEAF_INVALID: Indicates this sub-leaf is invalid. * %SGX_CPUID_SUB_LEAF_EPC_SECTION: Sub-leaf enumerates an EPC section. */ enum sgx_sub_leaf_types { SGX_CPUID_SUB_LEAF_INVALID = 0x0, SGX_CPUID_SUB_LEAF_EPC_SECTION = 0x1, }; #define SGX_CPUID_SUB_LEAF_TYPE_MASK GENMASK(3, 0) #define SGX_MODULUS_SIZE 384 /** * enum sgx_miscselect - additional information to an SSA frame * %SGX_MISC_EXINFO: Report #PF or #GP to the SSA frame. * * Save State Area (SSA) is a stack inside the enclave used to store processor * state when an exception or interrupt occurs. This enum defines additional * information stored to an SSA frame. */ enum sgx_miscselect { SGX_MISC_EXINFO = BIT(0), }; #define SGX_MISC_RESERVED_MASK GENMASK_ULL(63, 1) #define SGX_SSA_GPRS_SIZE 184 #define SGX_SSA_MISC_EXINFO_SIZE 16 /** * enum sgx_attributes - the attributes field in &struct sgx_secs * %SGX_ATTR_INIT: Enclave can be entered (is initialized). * %SGX_ATTR_DEBUG: Allow ENCLS(EDBGRD) and ENCLS(EDBGWR). * %SGX_ATTR_MODE64BIT: Tell that this a 64-bit enclave. * %SGX_ATTR_PROVISIONKEY: Allow to use provisioning keys for remote * attestation. * %SGX_ATTR_KSS: Allow to use key separation and sharing (KSS). * %SGX_ATTR_EINITTOKENKEY: Allow to use token signing key that is used to * sign cryptographic tokens that can be passed to * EINIT as an authorization to run an enclave. */ enum sgx_attribute { SGX_ATTR_INIT = BIT(0), SGX_ATTR_DEBUG = BIT(1), SGX_ATTR_MODE64BIT = BIT(2), SGX_ATTR_PROVISIONKEY = BIT(4), SGX_ATTR_EINITTOKENKEY = BIT(5), SGX_ATTR_KSS = BIT(7), }; #define SGX_ATTR_RESERVED_MASK (BIT_ULL(3) | BIT_ULL(6) | GENMASK_ULL(63, 8)) #define SGX_ATTR_ALLOWED_MASK (SGX_ATTR_DEBUG | SGX_ATTR_MODE64BIT | \ SGX_ATTR_KSS) /** * struct sgx_secs - SGX Enclave Control Structure (SECS) * @size: size of the address space * @base: base address of the address space * @ssa_frame_size: size of an SSA frame * @miscselect: additional information stored to an SSA frame * @attributes: attributes for enclave * @xfrm: XSave-Feature Request Mask (subset of XCR0) * @mrenclave: SHA256-hash of the enclave contents * @mrsigner: SHA256-hash of the public key used to sign the SIGSTRUCT * @config_id: a user-defined value that is used in key derivation * @isv_prod_id: a user-defined value that is used in key derivation * @isv_svn: a user-defined value that is used in key derivation * @config_svn: a user-defined value that is used in key derivation * * SGX Enclave Control Structure (SECS) is a special enclave page that is not * visible in the address space. In fact, this structure defines the address * range and other global attributes for the enclave and it is the first EPC * page created for any enclave. It is moved from a temporary buffer to an EPC * by the means of ENCLS(ECREATE) leaf. */ struct sgx_secs { uint64_t size; uint64_t base; uint32_t ssa_frame_size; uint32_t miscselect; uint8_t reserved1[24]; uint64_t attributes; uint64_t xfrm; uint32_t mrenclave[8]; uint8_t reserved2[32]; uint32_t mrsigner[8]; uint8_t reserved3[32]; uint32_t config_id[16]; uint16_t isv_prod_id; uint16_t isv_svn; uint16_t config_svn; uint8_t reserved4[3834]; } __packed; /** * enum sgx_tcs_flags - execution flags for TCS * %SGX_TCS_DBGOPTIN: If enabled allows single-stepping and breakpoints * inside an enclave. It is cleared by EADD but can * be set later with EDBGWR. */ enum sgx_tcs_flags { SGX_TCS_DBGOPTIN = 0x01, }; #define SGX_TCS_RESERVED_MASK GENMASK_ULL(63, 1) #define SGX_TCS_RESERVED_SIZE 4024 /** * struct sgx_tcs - Thread Control Structure (TCS) * @state: used to mark an entered TCS * @flags: execution flags (cleared by EADD) * @ssa_offset: SSA stack offset relative to the enclave base * @ssa_index: the current SSA frame index (cleard by EADD) * @nr_ssa_frames: the number of frame in the SSA stack * @entry_offset: entry point offset relative to the enclave base * @exit_addr: address outside the enclave to exit on an exception or * interrupt * @fs_offset: offset relative to the enclave base to become FS * segment inside the enclave * @gs_offset: offset relative to the enclave base to become GS * segment inside the enclave * @fs_limit: size to become a new FS-limit (only 32-bit enclaves) * @gs_limit: size to become a new GS-limit (only 32-bit enclaves) * * Thread Control Structure (TCS) is an enclave page visible in its address * space that defines an entry point inside the enclave. A thread enters inside * an enclave by supplying address of TCS to ENCLU(EENTER). A TCS can be entered * by only one thread at a time. */ struct sgx_tcs { uint64_t state; uint64_t flags; uint64_t ssa_offset; uint32_t ssa_index; uint32_t nr_ssa_frames; uint64_t entry_offset; uint64_t exit_addr; uint64_t fs_offset; uint64_t gs_offset; uint32_t fs_limit; uint32_t gs_limit; uint8_t reserved[SGX_TCS_RESERVED_SIZE]; } __packed; /** * struct sgx_pageinfo - an enclave page descriptor * @addr: address of the enclave page * @contents: pointer to the page contents * @metadata: pointer either to a SECINFO or PCMD instance * @secs: address of the SECS page */ struct sgx_pageinfo { uint64_t addr; uint64_t contents; uint64_t metadata; uint64_t secs; } __packed __aligned(32); /** * enum sgx_page_type - bits in the SECINFO flags defining the page type * %SGX_PAGE_TYPE_SECS: a SECS page * %SGX_PAGE_TYPE_TCS: a TCS page * %SGX_PAGE_TYPE_REG: a regular page * %SGX_PAGE_TYPE_VA: a VA page * %SGX_PAGE_TYPE_TRIM: a page in trimmed state */ enum sgx_page_type { SGX_PAGE_TYPE_SECS, SGX_PAGE_TYPE_TCS, SGX_PAGE_TYPE_REG, SGX_PAGE_TYPE_VA, SGX_PAGE_TYPE_TRIM, }; #define SGX_NR_PAGE_TYPES 5 #define SGX_PAGE_TYPE_MASK GENMASK(7, 0) /** * enum sgx_secinfo_flags - the flags field in &struct sgx_secinfo * %SGX_SECINFO_R: allow read * %SGX_SECINFO_W: allow write * %SGX_SECINFO_X: allow execution * %SGX_SECINFO_SECS: a SECS page * %SGX_SECINFO_TCS: a TCS page * %SGX_SECINFO_REG: a regular page * %SGX_SECINFO_VA: a VA page * %SGX_SECINFO_TRIM: a page in trimmed state */ enum sgx_secinfo_flags { SGX_SECINFO_R = BIT(0), SGX_SECINFO_W = BIT(1), SGX_SECINFO_X = BIT(2), SGX_SECINFO_SECS = (SGX_PAGE_TYPE_SECS << 8), SGX_SECINFO_TCS = (SGX_PAGE_TYPE_TCS << 8), SGX_SECINFO_REG = (SGX_PAGE_TYPE_REG << 8), SGX_SECINFO_VA = (SGX_PAGE_TYPE_VA << 8), SGX_SECINFO_TRIM = (SGX_PAGE_TYPE_TRIM << 8), }; #define SGX_SECINFO_PERMISSION_MASK GENMASK_ULL(2, 0) #define SGX_SECINFO_PAGE_TYPE_MASK (SGX_PAGE_TYPE_MASK << 8) #define SGX_SECINFO_RESERVED_MASK ~(SGX_SECINFO_PERMISSION_MASK | \ SGX_SECINFO_PAGE_TYPE_MASK) /** * struct sgx_secinfo - describes attributes of an EPC page * @flags: permissions and type * * Used together with ENCLS leaves that add or modify an EPC page to an * enclave to define page permissions and type. */ struct sgx_secinfo { uint64_t flags; uint8_t reserved[56]; } __packed __aligned(64); #define SGX_PCMD_RESERVED_SIZE 40 /** * struct sgx_pcmd - Paging Crypto Metadata (PCMD) * @enclave_id: enclave identifier * @mac: MAC over PCMD, page contents and isvsvn * * PCMD is stored for every swapped page to the regular memory. When ELDU loads * the page back it recalculates the MAC by using a isvsvn number stored in a * VA page. Together these two structures bring integrity and rollback * protection. */ struct sgx_pcmd { struct sgx_secinfo secinfo; uint64_t enclave_id; uint8_t reserved[SGX_PCMD_RESERVED_SIZE]; uint8_t mac[16]; } __packed __aligned(128); #define SGX_SIGSTRUCT_RESERVED1_SIZE 84 #define SGX_SIGSTRUCT_RESERVED2_SIZE 20 #define SGX_SIGSTRUCT_RESERVED3_SIZE 32 #define SGX_SIGSTRUCT_RESERVED4_SIZE 12 /** * struct sgx_sigstruct_header - defines author of the enclave * @header1: constant byte string * @vendor: must be either 0x0000 or 0x8086 * @date: YYYYMMDD in BCD * @header2: costant byte string * @swdefined: software defined value */ struct sgx_sigstruct_header { uint64_t header1[2]; uint32_t vendor; uint32_t date; uint64_t header2[2]; uint32_t swdefined; uint8_t reserved1[84]; } __packed; /** * struct sgx_sigstruct_body - defines contents of the enclave * @miscselect: additional information stored to an SSA frame * @misc_mask: required miscselect in SECS * @attributes: attributes for enclave * @xfrm: XSave-Feature Request Mask (subset of XCR0) * @attributes_mask: required attributes in SECS * @xfrm_mask: required XFRM in SECS * @mrenclave: SHA256-hash of the enclave contents * @isvprodid: a user-defined value that is used in key derivation * @isvsvn: a user-defined value that is used in key derivation */ struct sgx_sigstruct_body { uint32_t miscselect; uint32_t misc_mask; uint8_t reserved2[20]; uint64_t attributes; uint64_t xfrm; uint64_t attributes_mask; uint64_t xfrm_mask; uint8_t mrenclave[32]; uint8_t reserved3[32]; uint16_t isvprodid; uint16_t isvsvn; } __packed; /** * struct sgx_sigstruct - an enclave signature * @header: defines author of the enclave * @modulus: the modulus of the public key * @exponent: the exponent of the public key * @signature: the signature calculated over the fields except modulus, * @body: defines contents of the enclave * @q1: a value used in RSA signature verification * @q2: a value used in RSA signature verification * * Header and body are the parts that are actual signed. The remaining fields * define the signature of the enclave. */ struct sgx_sigstruct { struct sgx_sigstruct_header header; uint8_t modulus[SGX_MODULUS_SIZE]; uint32_t exponent; uint8_t signature[SGX_MODULUS_SIZE]; struct sgx_sigstruct_body body; uint8_t reserved4[12]; uint8_t q1[SGX_MODULUS_SIZE]; uint8_t q2[SGX_MODULUS_SIZE]; } __packed; struct sgx_einittoken_payload { uint32_t valid; uint32_t reserved1[11]; uint64_t attributes; uint64_t xfrm; uint8_t mrenclave[32]; uint8_t reserved2[32]; uint8_t mrsigner[32]; uint8_t reserved3[32]; }; struct sgx_einittoken { struct sgx_einittoken_payload payload; uint8_t cpusvnle[16]; uint16_t isvprodidle; uint16_t isvsvnle; uint8_t reserved2[24]; uint32_t maskedmiscselectle; uint64_t maskedattributesle; uint64_t maskedxfrmle; uint8_t keyid[32]; uint8_t mac[16]; }; #define SGX_LAUNCH_TOKEN_SIZE 304 #define SGX_TARGET_INFO_SIZE 512 struct sgx_target_info { uint8_t mrenclave[32]; uint64_t attributes; uint64_t xfrm; uint8_t cetattributes; uint8_t reserved1; uint16_t config_svn; uint32_t miscselect; uint8_t reserved2[8]; uint32_t config_id[16]; uint8_t reserved3[384]; } __packed __aligned(SGX_TARGET_INFO_SIZE); static_assert(sizeof(struct sgx_target_info) == SGX_TARGET_INFO_SIZE, "incorrect size of sgx_target_info"); #define SGX_REPORT_DATA_SIZE 64 struct sgx_report_data { uint8_t report_data[SGX_REPORT_DATA_SIZE]; } __packed __aligned(128); static_assert(sizeof(struct sgx_report_data) == 128, "incorrect size of sgx_report_data"); struct sgx_report_body { uint8_t cpusvn[16]; uint32_t miscselect; uint8_t cetattributes; uint8_t reserved1[11]; uint16_t isv_ext_prod_id[8]; uint64_t attributes; uint64_t xfrm; uint8_t mrenclave[32]; uint8_t reserved2[32]; uint8_t mrsigner[32]; uint8_t reserved3[32]; uint32_t config_id[16]; uint16_t isv_prod_id; uint16_t isv_svn; uint16_t config_svn; uint8_t reserved4[42]; uint8_t isv_family_id[16]; uint8_t report_data[64]; } __packed; static_assert(sizeof(struct sgx_report_body) == 384, "incorrect size of sgx_report_body"); #define SGX_REPORT_SIZE 432 struct sgx_report { struct sgx_report_body body; uint8_t key_id[32]; uint8_t mac[16]; } __packed __aligned(512); static_assert(sizeof(struct sgx_report) == 512, "incorrect size of sgx_report"); #endif /* _ASM_X86_SGX_ARCH_H */
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/sgxsign.c
<gh_stars>0 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) // Copyright(c) 2016-18 Intel Corporation. #define _GNU_SOURCE #include <getopt.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <openssl/err.h> #include <openssl/pem.h> #include "defines.h" struct sgx_sigstruct_payload { struct sgx_sigstruct_header header; struct sgx_sigstruct_body body; }; static bool check_crypto_errors(void) { int err; bool had_errors = false; const char *filename; int line; char str[256]; for ( ; ; ) { if (ERR_peek_error() == 0) break; had_errors = true; err = ERR_get_error_line(&filename, &line); ERR_error_string_n(err, str, sizeof(str)); fprintf(stderr, "crypto: %s: %s:%d\n", str, filename, line); } return had_errors; } static void exit_usage(const char *program) { fprintf(stderr, "Usage: %s/sign-le <key> <enclave> <sigstruct>\n", program); exit(1); } static inline const BIGNUM *get_modulus(RSA *key) { #if OPENSSL_VERSION_NUMBER < 0x10100000L return key->n; #else const BIGNUM *n; RSA_get0_key(key, &n, NULL, NULL); return n; #endif } static RSA *load_sign_key(const char *path) { FILE *f; RSA *key; f = fopen(path, "rb"); if (!f) { fprintf(stderr, "Unable to open %s\n", path); return NULL; } key = RSA_new(); if (!PEM_read_RSAPrivateKey(f, &key, NULL, NULL)) return NULL; fclose(f); if (BN_num_bytes(get_modulus(key)) != SGX_MODULUS_SIZE) { fprintf(stderr, "Invalid key size %d\n", BN_num_bytes(get_modulus(key))); RSA_free(key); return NULL; } return key; } static void reverse_bytes(void *data, int length) { int i = 0; int j = length - 1; uint8_t temp; uint8_t *ptr = data; while (i < j) { temp = ptr[i]; ptr[i] = ptr[j]; ptr[j] = temp; i++; j--; } } enum mrtags { MRECREATE = 0x0045544145524345, MREADD = 0x0000000044444145, MREEXTEND = 0x00444E4554584545, }; static bool mrenclave_update(EVP_MD_CTX *ctx, const void *data) { if (!EVP_DigestUpdate(ctx, data, 64)) { fprintf(stderr, "digest update failed\n"); return false; } return true; } static bool mrenclave_commit(EVP_MD_CTX *ctx, uint8_t *mrenclave) { unsigned int size; if (!EVP_DigestFinal_ex(ctx, (unsigned char *)mrenclave, &size)) { fprintf(stderr, "digest commit failed\n"); return false; } if (size != 32) { fprintf(stderr, "invalid digest size = %u\n", size); return false; } return true; } struct mrecreate { uint64_t tag; uint32_t ssaframesize; uint64_t size; uint8_t reserved[44]; } __attribute__((__packed__)); static bool mrenclave_ecreate(EVP_MD_CTX *ctx, uint64_t blob_size) { struct mrecreate mrecreate; uint64_t encl_size; for (encl_size = 0x1000; encl_size < blob_size; ) encl_size <<= 1; memset(&mrecreate, 0, sizeof(mrecreate)); mrecreate.tag = MRECREATE; mrecreate.ssaframesize = 1; mrecreate.size = encl_size; if (!EVP_DigestInit_ex(ctx, EVP_sha256(), NULL)) return false; return mrenclave_update(ctx, &mrecreate); } struct mreadd { uint64_t tag; uint64_t offset; uint64_t flags; /* SECINFO flags */ uint8_t reserved[40]; } __attribute__((__packed__)); static bool mrenclave_eadd(EVP_MD_CTX *ctx, uint64_t offset, uint64_t flags) { struct mreadd mreadd; memset(&mreadd, 0, sizeof(mreadd)); mreadd.tag = MREADD; mreadd.offset = offset; mreadd.flags = flags; return mrenclave_update(ctx, &mreadd); } struct mreextend { uint64_t tag; uint64_t offset; uint8_t reserved[48]; } __attribute__((__packed__)); static bool mrenclave_eextend(EVP_MD_CTX *ctx, uint64_t offset, uint8_t *data) { struct mreextend mreextend; int i; for (i = 0; i < 0x1000; i += 0x100) { memset(&mreextend, 0, sizeof(mreextend)); mreextend.tag = MREEXTEND; mreextend.offset = offset + i; if (!mrenclave_update(ctx, &mreextend)) return false; if (!mrenclave_update(ctx, &data[i + 0x00])) return false; if (!mrenclave_update(ctx, &data[i + 0x40])) return false; if (!mrenclave_update(ctx, &data[i + 0x80])) return false; if (!mrenclave_update(ctx, &data[i + 0xC0])) return false; } return true; } /** * measure_encl - measure enclave * @path: path to the enclave * @mrenclave: measurement * * Calculates MRENCLAVE. Assumes that the very first page is a TCS page and * following pages are regular pages. Does not measure the contents of the * enclave as the signing tool is used at the moment only for the launch * enclave, which is pass-through (everything gets a token). */ static bool measure_encl(const char *path, uint8_t *mrenclave) { FILE *file; struct stat sb; EVP_MD_CTX *ctx; uint64_t flags; uint64_t offset; uint8_t data[0x1000]; int rc; ctx = EVP_MD_CTX_create(); if (!ctx) return false; file = fopen(path, "rb"); if (!file) { perror("fopen"); EVP_MD_CTX_destroy(ctx); return false; } rc = stat(path, &sb); if (rc) { perror("stat"); goto out; } if (!sb.st_size || sb.st_size & 0xfff) { fprintf(stderr, "Invalid blob size %lu\n", sb.st_size); goto out; } if (!mrenclave_ecreate(ctx, sb.st_size)) goto out; for (offset = 0; offset < sb.st_size; offset += 0x1000) { if (!offset) flags = SGX_SECINFO_TCS; else flags = SGX_SECINFO_REG | SGX_SECINFO_R | SGX_SECINFO_W | SGX_SECINFO_X; if (!mrenclave_eadd(ctx, offset, flags)) goto out; rc = fread(data, 1, 0x1000, file); if (!rc) break; if (rc < 0x1000) goto out; if (!mrenclave_eextend(ctx, offset, data)) goto out; } if (!mrenclave_commit(ctx, mrenclave)) goto out; fclose(file); EVP_MD_CTX_destroy(ctx); return true; out: fclose(file); EVP_MD_CTX_destroy(ctx); return false; } /** * sign_encl - sign enclave * @sigstruct: pointer to SIGSTRUCT * @key: 3072-bit RSA key * @signature: byte array for the signature * * Calculates EMSA-PKCSv1.5 signature for the given SIGSTRUCT. The result is * stored in big-endian format so that it can be further passed to OpenSSL * libcrypto functions. */ static bool sign_encl(const struct sgx_sigstruct *sigstruct, RSA *key, uint8_t *signature) { struct sgx_sigstruct_payload payload; unsigned int siglen; uint8_t digest[SHA256_DIGEST_LENGTH]; bool ret; memcpy(&payload.header, &sigstruct->header, sizeof(sigstruct->header)); memcpy(&payload.body, &sigstruct->body, sizeof(sigstruct->body)); SHA256((unsigned char *)&payload, sizeof(payload), digest); ret = RSA_sign(NID_sha256, digest, SHA256_DIGEST_LENGTH, signature, &siglen, key); return ret; } struct q1q2_ctx { BN_CTX *bn_ctx; BIGNUM *m; BIGNUM *s; BIGNUM *q1; BIGNUM *qr; BIGNUM *q2; }; static void free_q1q2_ctx(struct q1q2_ctx *ctx) { BN_CTX_free(ctx->bn_ctx); BN_free(ctx->m); BN_free(ctx->s); BN_free(ctx->q1); BN_free(ctx->qr); BN_free(ctx->q2); } static bool alloc_q1q2_ctx(const uint8_t *s, const uint8_t *m, struct q1q2_ctx *ctx) { ctx->bn_ctx = BN_CTX_new(); ctx->s = BN_bin2bn(s, SGX_MODULUS_SIZE, NULL); ctx->m = BN_bin2bn(m, SGX_MODULUS_SIZE, NULL); ctx->q1 = BN_new(); ctx->qr = BN_new(); ctx->q2 = BN_new(); if (!ctx->bn_ctx || !ctx->s || !ctx->m || !ctx->q1 || !ctx->qr || !ctx->q2) { free_q1q2_ctx(ctx); return false; } return true; } static bool calc_q1q2(const uint8_t *s, const uint8_t *m, uint8_t *q1, uint8_t *q2) { struct q1q2_ctx ctx; if (!alloc_q1q2_ctx(s, m, &ctx)) { fprintf(stderr, "Not enough memory for Q1Q2 calculation\n"); return false; } if (!BN_mul(ctx.q1, ctx.s, ctx.s, ctx.bn_ctx)) goto out; if (!BN_div(ctx.q1, ctx.qr, ctx.q1, ctx.m, ctx.bn_ctx)) goto out; if (BN_num_bytes(ctx.q1) > SGX_MODULUS_SIZE) { fprintf(stderr, "Too large Q1 %d bytes\n", BN_num_bytes(ctx.q1)); goto out; } if (!BN_mul(ctx.q2, ctx.s, ctx.qr, ctx.bn_ctx)) goto out; if (!BN_div(ctx.q2, NULL, ctx.q2, ctx.m, ctx.bn_ctx)) goto out; if (BN_num_bytes(ctx.q2) > SGX_MODULUS_SIZE) { fprintf(stderr, "Too large Q2 %d bytes\n", BN_num_bytes(ctx.q2)); goto out; } BN_bn2bin(ctx.q1, q1); BN_bn2bin(ctx.q2, q2); free_q1q2_ctx(&ctx); return true; out: free_q1q2_ctx(&ctx); return false; } static bool save_sigstruct(const struct sgx_sigstruct *sigstruct, const char *path) { FILE *f = fopen(path, "wb"); if (!f) { fprintf(stderr, "Unable to open %s\n", path); return false; } fwrite(sigstruct, sizeof(*sigstruct), 1, f); fclose(f); return true; } int main(int argc, char **argv) { uint64_t header1[2] = {0x000000E100000006, 0x0000000000010000}; uint64_t header2[2] = {0x0000006000000101, 0x0000000100000060}; struct sgx_sigstruct ss; const char *program; int opt; RSA *sign_key; bool enclave_debug = true; char* const short_options = "p"; struct option long_options = {"product", 0, NULL, 'p'}; program = argv[0]; do { opt = getopt_long(argc, argv, short_options, &long_options, NULL); switch (opt) { case 'p': enclave_debug = false; break; case -1: break; default: exit_usage(program); } } while (opt != -1); argc -= optind; argv += optind; if (argc < 3) exit_usage(program); memset(&ss, 0, sizeof(ss)); ss.header.header1[0] = header1[0]; ss.header.header1[1] = header1[1]; ss.header.header2[0] = header2[0]; ss.header.header2[1] = header2[1]; ss.exponent = 3; #ifndef CONFIG_EINITTOKENKEY ss.body.attributes = SGX_ATTR_MODE64BIT; #else ss.body.attributes = SGX_ATTR_MODE64BIT | SGX_ATTR_EINITTOKENKEY; #endif if (enclave_debug) ss.body.attributes |= SGX_ATTR_DEBUG; ss.body.xfrm = 7; ss.body.attributes_mask = ss.body.attributes; /* sanity check only */ if (check_crypto_errors()) exit(1); sign_key = load_sign_key(argv[0]); if (!sign_key) goto out; BN_bn2bin(get_modulus(sign_key), ss.modulus); if (!measure_encl(argv[1], ss.body.mrenclave)) goto out; if (!sign_encl(&ss, sign_key, ss.signature)) goto out; if (!calc_q1q2(ss.signature, ss.modulus, ss.q1, ss.q2)) goto out; /* convert to little endian */ reverse_bytes(ss.signature, SGX_MODULUS_SIZE); reverse_bytes(ss.modulus, SGX_MODULUS_SIZE); reverse_bytes(ss.q1, SGX_MODULUS_SIZE); reverse_bytes(ss.q2, SGX_MODULUS_SIZE); if (!save_sigstruct(&ss, argv[2])) goto out; exit(0); out: check_crypto_errors(); exit(1); }
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/sgx_call.h
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright(c) 2016-19 Intel Corporation. */ #ifndef SGX_CALL_H #define SGX_CALL_H #define ECALL_MAGIC 0 #define ECALL_REPORT 1 #define MAX_ECALLS 2 #define EEXIT 4 #define INIT_MAGIC 0xdeadfacedeadbeefUL #ifndef __ASSEMBLER__ #define SGX_ENTER_1_ARG(ecall_num, tcs, a0) \ ({ \ int __ret; \ asm volatile( \ "mov %1, %%r10\n\t" \ "mov %2, %%r11\n\t" \ "call sgx_ecall\n\t" \ : "=a" (__ret) \ : "r" ((uint64_t)ecall_num), "r" (tcs), \ "D" (a0) \ : "r10", "r11" \ ); \ __ret; \ }) #define SGX_ENTER_3_ARGS(ecall_num, tcs, a0, a1, a2) \ ({ \ int __ret; \ asm volatile( \ "mov %1, %%r10\n\t" \ "mov %2, %%r11\n\t" \ "call sgx_ecall\n\t" \ : "=a" (__ret) \ : "r" ((uint64_t)ecall_num), "r" (tcs), \ "D" (a0), "S" (a1), "d" (a2) \ : "r10", "r11" \ ); \ __ret; \ }) #define ENCLU ".byte 0x0f, 0x01, 0xd7" #else #define ENCLU .byte 0x0f, 0x01, 0xd7 #endif #endif /* SGX_CALL_H */
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/encl.c
<filename>rune/libenclave/internal/runtime/pal/skeleton/encl.c // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) // Copyright(c) 2016-18 Intel Corporation. #include <stddef.h> #include "defines.h" #include "arch.h" #include "sgx_call.h" static void *memcpy(void *dest, const void *src, size_t n) { size_t i; for (i = 0; i < n; i++) ((char *)dest)[i] = ((char *)src)[i]; return dest; } static int encl_init(void *dst) { static uint64_t magic = INIT_MAGIC; memcpy(dst, &magic, 8); return 0; } static int encl_get_report(const struct sgx_target_info *target_info, const uint8_t *report_data, struct sgx_report *report) { struct sgx_target_info ti; memcpy(&ti, target_info, SGX_TARGET_INFO_SIZE); struct sgx_report_data rd; memcpy(&rd, report_data, SGX_REPORT_DATA_SIZE); struct sgx_report r; asm volatile( ENCLU "\n\t" :: "a" (EREPORT), "b" (&ti), "c" (&rd), "d" (&r) : "memory" ); memcpy(report, &r, SGX_REPORT_SIZE); return 0; } unsigned long enclave_call_table[MAX_ECALLS] = { (unsigned long)encl_init, (unsigned long)encl_get_report, };
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/liberpal-skeleton.h
<filename>rune/libenclave/internal/runtime/pal/skeleton/liberpal-skeleton.h #ifndef LIBERPAL_SKELETON_H #define LIBERPAL_SKELETON_H #include <stdbool.h> extern bool is_oot_driver; extern bool debugging; typedef struct { const char *args; const char *log_level; } pal_attr_t; typedef struct { int stdin, stdout, stderr; } pal_stdio_fds; typedef struct { char *path; char **argv; char **env; pal_stdio_fds *stdio; int *pid; } pal_create_process_args; typedef struct { int pid; int *exit_value; } pal_exec_args; int __pal_init(pal_attr_t *attr); int __pal_exec(char *path, char *argv[], pal_stdio_fds *stdio, int *exit_code); int __pal_create_process(pal_create_process_args *args); int wait4child(pal_exec_args *attr); int __pal_get_local_report(void *targetinfo, int targetinfo_len, void *report, int* report_len); int __pal_kill(int pid, int sig); int __pal_destory(void); #endif
windayski/inclavare-containers
rune/libenclave/internal/runtime/pal/skeleton/sgx.h
/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) WITH Linux-syscall-note */ /* * Copyright(c) 2016-19 Intel Corporation. */ #ifndef _UAPI_ASM_X86_SGX_H #define _UAPI_ASM_X86_SGX_H #include <linux/types.h> #include <linux/ioctl.h> /** * enum sgx_epage_flags - page control flags * %SGX_PAGE_MEASURE: Measure the page contents with a sequence of * ENCLS[EEXTEND] operations. */ enum sgx_page_flags { SGX_PAGE_MEASURE = 0x01, }; #define SGX_MAGIC 0xA4 #define SGX_IOC_ENCLAVE_CREATE \ _IOW(SGX_MAGIC, 0x00, struct sgx_enclave_create) #define SGX_IOC_ENCLAVE_ADD_PAGES \ _IOWR(SGX_MAGIC, 0x01, struct sgx_enclave_add_pages) #define SGX_IOC_ENCLAVE_ADD_PAGES_WITH_MRMASK \ _IOW(SGX_MAGIC, 0x01, struct sgx_enclave_add_pages_with_mrmask) #define SGX_IOC_ENCLAVE_INIT \ _IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init) #define SGX_IOC_ENCLAVE_INIT_WITH_TOKEN \ _IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init_with_token) #define SGX_IOC_ENCLAVE_SET_ATTRIBUTE \ _IOW(SGX_MAGIC, 0x03, struct sgx_enclave_set_attribute) /** * struct sgx_enclave_create - parameter structure for the * %SGX_IOC_ENCLAVE_CREATE ioctl * @src: address for the SECS page data */ struct sgx_enclave_create { __u64 src; }; /** * struct sgx_enclave_add_pages - parameter structure for the * %SGX_IOC_ENCLAVE_ADD_PAGE ioctl * @src: start address for the page data * @offset: starting page offset * @length: length of the data (multiple of the page size) * @secinfo: address for the SECINFO data * @flags: page control flags * @count: number of bytes added (multiple of the page size) */ struct sgx_enclave_add_pages { __u64 src; __u64 offset; __u64 length; __u64 secinfo; __u64 flags; __u64 count; }; /** * struct sgx_enclave_add_page - parameter structure for the * %SGX_IOC_ENCLAVE_ADD_PAGE_WITH_MRMASK ioctl * @addr: address in the ELRANGE * @src: address for the page data * @secinfo: address for the SECINFO data * @mrmask: bitmask for the 256 byte chunks that are to be measured */ struct sgx_enclave_add_pages_with_mrmask { __u64 addr; __u64 src; __u64 secinfo; __u16 mrmask; } __attribute__((__packed__)); /** * struct sgx_enclave_init - parameter structure for the * %SGX_IOC_ENCLAVE_INIT ioctl * @sigstruct: address for the SIGSTRUCT data */ struct sgx_enclave_init { __u64 sigstruct; }; /** * struct sgx_enclave_init - parameter structure for the * %SGX_IOC_ENCLAVE_INIT_WITH_TOKEN ioctl * @addr: address in the ELRANGE * @sigstruct: address for the page data * @einittoken: EINITTOKEN */ struct sgx_enclave_init_with_token { __u64 addr; __u64 sigstruct; __u64 einittoken; } __attribute__((__packed__)); /** * struct sgx_enclave_set_attribute - parameter structure for the * %SGX_IOC_ENCLAVE_SET_ATTRIBUTE ioctl * @attribute_fd: file handle of the attribute file in the securityfs */ struct sgx_enclave_set_attribute { __u64 attribute_fd; }; /** * struct sgx_enclave_exception - structure to report exceptions encountered in * __vdso_sgx_enter_enclave() * * @leaf: ENCLU leaf from \%eax at time of exception * @trapnr: exception trap number, a.k.a. fault vector * @error_code: exception error code * @address: exception address, e.g. CR2 on a #PF * @reserved: reserved for future use */ struct sgx_enclave_exception { __u32 leaf; __u16 trapnr; __u16 error_code; __u64 address; __u64 reserved[2]; }; /** * typedef sgx_enclave_exit_handler_t - Exit handler function accepted by * __vdso_sgx_enter_enclave() * * @rdi: RDI at the time of enclave exit * @rsi: RSI at the time of enclave exit * @rdx: RDX at the time of enclave exit * @ursp: RSP at the time of enclave exit (untrusted stack) * @r8: R8 at the time of enclave exit * @r9: R9 at the time of enclave exit * @tcs: Thread Control Structure used to enter enclave * @ret: 0 on success (EEXIT), -EFAULT on an exception * @e: Pointer to struct sgx_enclave_exception (as provided by caller) */ typedef int (*sgx_enclave_exit_handler_t)(long rdi, long rsi, long rdx, long ursp, long r8, long r9, void *tcs, int ret, struct sgx_enclave_exception *e); #endif /* _UAPI_ASM_X86_SGX_H */
wenwudong/tagVew
tagView/tagView/ViewController.h
// // ViewController.h // tagView // // Created by Mark on 16/1/11. // Copyright © 2016年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController /** * 背景图 */ @property (weak, nonatomic) IBOutlet UIImageView* backImage; /** * 菜名按钮 */ @property (weak, nonatomic) IBOutlet UIButton* dishName; /** * 价格按钮 */ @property (weak, nonatomic) IBOutlet UIButton* dishPrice; @end
wenwudong/tagVew
tagView/tagView/MDTagView.h
// // MDTagView.h // tagView // // Created by Mark on 16/1/11. // Copyright © 2016年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface MDTagView : UIView /** * 标签内容 */ @property (copy, nonatomic) NSString* labelText; /** * 标签位置(暂时无用) */ @property (assign, nonatomic) CGPoint point; /** * 标签正反 */ @property (assign, nonatomic) BOOL isPos; /** * 记录标签数据(暂时无用) */ @property (strong, nonatomic) NSMutableDictionary* dic; /** * 相当于tag(字典存储时一对一) */ @property (assign, nonatomic) NSInteger tags; /** * 标签的图片 */ @property (strong, nonatomic) UIImageView* imageView; @end
wenwudong/tagVew
tagView/tagView/UIView+Frame.h
#import <UIKit/UIKit.h> /** * 此扩展用于方便的修改控件的frame 获取控件的各个属性 */ @interface UIView (Frame) @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @property (nonatomic, assign) CGPoint origin; @property (nonatomic, assign) CGSize size; @property (nonatomic, assign) CGFloat centerX; @property (nonatomic, assign) CGFloat centerY; @property (nonatomic, assign) IBInspectable CGFloat cornerRadius; @property (nonatomic, assign) IBInspectable CGFloat boderWidth; @property (nonatomic, strong) IBInspectable UIColor* bodercolor; - (CGFloat)BottomY; - (CGFloat)RightX; - (CGFloat)LeftX; - (CGFloat)TopY; //- (CGFloat)Width; //- (CGFloat)Heigh; //- (CGSize) Size; @end
Shokwav/errhndl
test.c
<reponame>Shokwav/errhndl /* This file has no copyright assigned and is placed in the Public Domain. */ #include <stdio.h> #include <stdlib.h> #include "errhndl.h" enum { test_error = 1 }; int main(void){ errinfo err; ERRTRY(err, ERRTHROW(err, test_error); /* Comment this out for no error */ puts("No error"); )ERRCATCH(err, printf("Caught error (type = %i)\n", ERRGET(err)); ) ERRTHROW(err, test_error); /* Throwing outside of try block does nothing */ return (EXIT_SUCCESS); }
Shokwav/errhndl
errhndl.h
/* This file has no copyright assigned and is placed in the Public Domain. */ #ifndef ERRHNDL_H #define ERRHNDL_H #include <setjmp.h> /* "Internal" structure; only access through provided macros */ typedef struct { jmp_buf buffer; int type, in_try_block; } errinfo; #define ERRGET(err) ((err).type) #define ERRTHROW(err, t) do{ if((err).in_try_block){ longjmp((err).buffer, (err).type = (t)); } }while(0) #define ERRTRY(err, body) do{ (err).in_try_block = 1; }while(0); if((!setjmp((err).buffer))){ body (err).in_try_block = 0; } #define ERRCATCH(err, body) else{ (err).in_try_block = 0; body } do{}while(0) #endif
FahadGhouri/FreeRTOS_InterTaskCommunication
RTOS_IPC/WIN32-MSVC/main_exercise.c
/****************************************************************************** * NOTE: Windows will not be running the FreeRTOS demo threads continuously, so * do not expect to get real time behaviour from the FreeRTOS Windows port, or * this demo application. Also, the timing information in the FreeRTOS+Trace * logs have no meaningful units. See the documentation page for the Windows * port for further information: * http://www.freertos.org/FreeRTOS-Windows-Simulator-Emulator-for-Visual-Studio-and-Eclipse-MingW.html /* Standard includes. */ #include <stdio.h> #include <assert.h> #include <conio.h> /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" #include "timers.h" #include "semphr.h" #include "queue.h" /* Macro Definations */ #define QueueLengthSensor1 1 #define QueueLengthSensor2A 1 #define QueueLengthSensor2B 1 #define SensorTaskPriority 2 #define ControllerTaskPriority 3 #define SensorTaskStackSize 50 #define ControllerTaskStackSize 100 #define HotReserveTestTime_mS 5 #define Controller1FailTime_mS 2000 /* Global Variables */ /* Queue Handles */ QueueHandle_t Sensor1_Data_Queue, Sensor2A_Data_Queue, Sensor2B_Data_Queue; /* Queue Set Handle */ QueueSetHandle_t Sensor2_Data_QueueSet; /* Task Handles */ TaskHandle_t Controller1Task_Handle, Controller2Task_Handle; /* Function Prototypes */ static void Sensor1Task(void *pvParameters); static void Sensor2ATask(void *pvParameters); static void Sensor2BTask(void *pvParameters); static void ControllerTask(void *pvParameters); void main_exercise( void ) { /* Initialize Queues */ /* The idea is to keep the queue length as 1 to make sure always the latest sensor data is avilable for the controller task */ /* Queue size is set to 16bit INT to accomodate all the data range generated from the sensor tasks */ Sensor1_Data_Queue = xQueueCreate(QueueLengthSensor1, sizeof(uint16_t)); Sensor2A_Data_Queue = xQueueCreate(QueueLengthSensor2A, sizeof(uint16_t)); Sensor2B_Data_Queue = xQueueCreate(QueueLengthSensor2B, sizeof(uint16_t)); /* Initialize Queue Set for Sensor 2 Data Pair */ /* The Queue of 2A and 2B Sensor data are paired together using the QueueSet function offered by FreeRTOS to make the selection between data available on these two queues easier */ Sensor2_Data_QueueSet = xQueueCreateSet((QueueLengthSensor2A+QueueLengthSensor2B)); xQueueAddToSet(Sensor2A_Data_Queue, Sensor2_Data_QueueSet); xQueueAddToSet(Sensor2B_Data_Queue, Sensor2_Data_QueueSet); /* Create Tasks */ xTaskCreate(Sensor1Task, "Sensor1", SensorTaskStackSize, NULL, SensorTaskPriority, NULL); xTaskCreate(Sensor2ATask, "Sensor2A", SensorTaskStackSize, NULL, SensorTaskPriority, NULL); xTaskCreate(Sensor2BTask, "Sensor2B", SensorTaskStackSize, NULL, SensorTaskPriority, NULL); xTaskCreate(ControllerTask, "Controller1", ControllerTaskStackSize, &Controller1Task_Handle, ControllerTaskPriority, &Controller1Task_Handle); xTaskCreate(ControllerTask, "Controller2", ControllerTaskStackSize, &Controller2Task_Handle, ControllerTaskPriority, &Controller2Task_Handle); /* Start Schedular */ vTaskStartScheduler(); for (;; ); } /*-----------------------------------------------------------*/ static void Sensor1Task(void *pvParameters) { pvParameters = NULL; //For Complier Warnings TickType_t xLastWakeTime; /* Run Every 200 mSec */ const TickType_t xFrequency = pdMS_TO_TICKS(200); /* Initialise the xLastWakeTime variable with the current time */ xLastWakeTime = xTaskGetTickCount(); /* Sensor Synthetic Data Value */ uint16_t SensorData = 100; for (;;) { /* Write Data to Sensor Data Queue */ /* Data is Written in NonBlocking mode with OverWrite if a value is already present on the queue */ xQueueOverwrite(Sensor1_Data_Queue, &SensorData); /* Increase Sensor Data and Wrap around if out of range */ SensorData++; if (199 < SensorData) { SensorData = 100; } /* Wake Up in Next Period */ vTaskDelayUntil(&xLastWakeTime, xFrequency); } } /*-----------------------------------------------------------*/ static void Sensor2ATask(void *pvParameters) { pvParameters = NULL; //For Complier Warnings TickType_t xLastWakeTime; /* Run Every 500 mSec */ const TickType_t xFrequency = pdMS_TO_TICKS(500); /* Initialise the xLastWakeTime variable with the current time */ xLastWakeTime = xTaskGetTickCount(); /* Sensor Synthetic Data Value */ uint16_t SensorData = 200; for (;;) { /* Write Data to Sensor Data Queue */ /* Data is Written in NonBlocking mode with OverWrite if a value is already present on the queue */ xQueueOverwrite(Sensor2A_Data_Queue, &SensorData); /* Increase Sensor Data and Wrap around if out of range */ SensorData++; if (249 < SensorData) { SensorData = 200; } /* Wake Up in Next Period */ vTaskDelayUntil(&xLastWakeTime, xFrequency); } } /*-----------------------------------------------------------*/ static void Sensor2BTask(void *pvParameters) { pvParameters = NULL; //For Complier Warnings TickType_t xLastWakeTime; /* Run Every 1400 mSec */ const TickType_t xFrequency = pdMS_TO_TICKS(1400); /* Initialise the xLastWakeTime variable with the current time */ xLastWakeTime = xTaskGetTickCount(); /* Sensor Synthetic Data Value */ uint16_t SensorData = 250; for (;;) { /* Write Data to Sensor Data Queue */ /* Data is Written in NonBlocking mode with OverWrite if a value is already present on the queue */ xQueueOverwrite(Sensor2B_Data_Queue, &SensorData); /* Increase Sensor Data and Wrap around if out of range */ SensorData++; if (299 < SensorData) { SensorData = 250; } /* Wake Up in Next Period */ vTaskDelayUntil(&xLastWakeTime, xFrequency); } } /*-----------------------------------------------------------*/ static void ControllerTask(void *pvParameters) { TaskHandle_t* Handle = (TaskHandle_t*)(pvParameters); //pvParameters = NULL; //For Complier Warnings uint16_t Sensor1Data, Sensor2Data; QueueSetMemberHandle_t Sensor2Queue; for (;;) { /* If this task is an instance of Controller 2 it checks for Controller 1 to be active and functioning */ /* To demostrate this in FreeRTOS, the Controller 2 tasks keeps on waiting untill the Controller 1 task is no more valid */ if (0 == strcmp("Controller2", pcTaskGetName(*Handle))) { while (eDeleted != eTaskGetState(Controller1Task_Handle)) { vTaskDelay(pdMS_TO_TICKS(HotReserveTestTime_mS)); } } /* Read Value from Sensors */ /* Sensor 2 is being used as the first blocking source for the controller task */ /* This is because of lower Frequency of Sensor 2 Tasks */ /* The Data will be read by the help of queue-sets to arbitate between Sensor2A Data Queue and Sensor 2B Data Queue */ /* This Mechanism helps eliminate the need for Event Groups Function offered by FreeRTOS */ Sensor2Queue = xQueueSelectFromSet(Sensor2_Data_QueueSet, portMAX_DELAY); /* Use the Recieved Queue Handle to get Sensor2 Data */ if (pdFALSE == xQueueReceive(Sensor2Queue, &Sensor2Data, 0)) { printf("Debug: Sensor 2 Queue Error \n"); } /* Recieve value from Sensor 1 */ xQueueReceive(Sensor1_Data_Queue, &Sensor1Data, portMAX_DELAY); /* Check the Special Case of Deleting Controller 1 Task after 2000 ticks */ /* Controller 1 Task Fails After Consuming Data from Queues */ if (0 == strcmp("Controller1", pcTaskGetName(*Handle)) && Controller1FailTime_mS < xTaskGetTickCount()) { printf("%s has had an error at %d\n", pcTaskGetName(*Handle), xTaskGetTickCount()); /* Delete Task */ vTaskDelete(NULL); } /* Print to console */ printf("%s has received sensor Data at %d; Sensor1:%d; Sensor2:%d\n", pcTaskGetName(*Handle),xTaskGetTickCount(),Sensor1Data,Sensor2Data); } } /*-----------------------------------------------------------*/
Ultracoolguy/retroarch-switch-updater
source/main.c
// Include the most common headers from the C standard library #include <stdio.h> #include <string.h> #include <assert.h> #include <curl/curl.h> // Include the main libnx system header, for Switch development #include <switch.h> #include <minizip/unzip.h> #define URL "http://buildbot.libretro.com/nightly/nintendo/switch/libnx/RetroArch_loader_update.zip" #define ZIP_OUTPUT "/switch/RetroArch_loader_update.zip" #define NRO_OUTPUT "/switch/retroarch_switch.nro" #define BUFFER_SIZE 0x100000 // 1MiB #define MAX_FILENAME 256 struct Buffer { FILE* file; // file to write to when buffer is full. uint8_t *buf; // buffer to read into size_t size; // max size of the buffer size_t offset; // offset (position in the buffer) }; void clean_buffer(struct Buffer* buffer) { if (buffer->file) { fclose(buffer->file); buffer->file = NULL; } if (buffer->buf) { free(buffer->buf); buffer->buf = NULL; } } void flush_buffer(struct Buffer* buffer) { // if we have data if (buffer->offset > 0) { // todo: check for errors fwrite(buffer->buf, buffer->offset, 1, buffer->file); } // reset offset after writing buffer->offset = 0; } bool setup_buffer(struct Buffer* buffer, const char* path, size_t size) { memset(buffer, 0, sizeof(struct Buffer)); if (!(buffer->file = fopen(path, "wb"))) { goto oof; } if (!(buffer->buf = malloc(size))) { goto oof; } buffer->size = size; return true; oof: clean_buffer(buffer); return false; } size_t write_data(void *ptr, size_t size, size_t nmemb, void* _buffer) { struct Buffer *buffer = (struct Buffer*)_buffer; const size_t actual_size = size * nmemb; // this should never happen unless you fail to set the // buffer size or the buffer size is set to 32k. assert(buffer->size > actual_size); if ((buffer->offset + actual_size) > buffer->size) { flush_buffer(buffer); } // append the new data to the buffer-> memcpy(buffer->buf + buffer->offset, ptr, actual_size); // move the position in the buffer-> buffer->offset += actual_size; return actual_size; } int getfile() { //Blatantly taken from https://stackoverflow.com/questions/19404616/c-program-for-downloading-files-with-curl/19404752#19404752 CURL *curl; CURLcode res; struct Buffer buffer = {0}; const char *url = URL; if (!setup_buffer(&buffer, ZIP_OUTPUT, BUFFER_SIZE)) { puts("getfile(): Something went wrong when setting up buffer."); return 1; } curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); res = curl_easy_perform(curl); // flush rest of the data. flush_buffer(&buffer); clean_buffer(&buffer); curl_easy_cleanup(curl); if (res != 0) { puts("getfile(): Download somehow failed."); consoleUpdate(NULL); return 3; } else { return 0; } } else { puts("getfile(): Something failed when initting curl."); consoleUpdate(NULL); return 2; } curl_global_cleanup(); } int unzipfile() { int ret = 0; unzFile zip = unzOpen(ZIP_OUTPUT); unz_global_info zipinfo; unzGetGlobalInfo(zip, &zipinfo); void *buf = malloc(BUFFER_SIZE); if (buf == NULL) { puts("unzipfile(): Failed to allocate buffer!"); consoleUpdate(NULL); ret = 1; goto err; } for (size_t i = 0; i < zipinfo.number_entry; ++i) { char filename[MAX_FILENAME]; unz_file_info fileinfo; unzOpenCurrentFile(zip); unzGetCurrentFileInfo(zip, &fileinfo, filename, sizeof(filename), NULL, 0, NULL, 0); if (strcmp(filename, "retroarch_switch.nro") == 0) { puts("Found .nro in zipfile."); FILE *outfile = fopen(NRO_OUTPUT, "wb"); for (int j = unzReadCurrentFile(zip, buf, BUFFER_SIZE); j > 0; j = unzReadCurrentFile(zip, buf, BUFFER_SIZE)) fwrite(buf, 1, j, outfile); fclose(outfile); } else { puts("unzipfile(): Couldn't find .nro in zipfile."); ret = 2; } } err: unzCloseCurrentFile(zip); unzClose(zip); free(buf); return ret; } // Main program entrypoint int main(void) { int ret; PadState pad; consoleInit(NULL); padConfigureInput(1, HidNpadStyleSet_NpadStandard); padInitializeDefault(&pad); socketInitializeDefault(); printf("Do you want to update the RetroArch loader?\nPress + for returning to hbmenu, Y for updating.\n"); consoleUpdate(NULL); while (appletMainLoop()) { padUpdate(&pad); u64 kDown = padGetButtonsDown(&pad); if (kDown & HidNpadButton_Plus) break; else if (kDown & HidNpadButton_Y) { ret = getfile(); if (ret) { puts("Error: couldn't get file!"); consoleUpdate(NULL); continue; } else { puts("Downloaded zip!"); consoleUpdate(NULL); } ret = unzipfile(); if (ret) { puts("Error: couldn't unzip file!"); consoleUpdate(NULL); continue; } else { if (access(NRO_OUTPUT, F_OK) != -1) { puts("Unzipped and copied file! Retroarch has been updated."); remove(ZIP_OUTPUT); } else puts("Error: Even after unzipping, for whatever reason the nro doesn't exists."); consoleUpdate(NULL); } } } consoleExit(NULL); socketExit(); return 0; }
mikaelmessias/utfpr-algorithms
src/structures/graph/graph.h
<filename>src/structures/graph/graph.h /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #ifndef GRAPH_H #define GRAPH_H struct graph { int isWeighted; int vertices; int maxDegree; int **edges; float **weights; int *degree; }; typedef struct graph Graph; /** * @brief Allocates a graph structure in memory. * @param vertices The number of vertices in the graph. * @param degre The maximum degree of the graph * @param isWeighted A binary number that indicates if there is presence of weights in the graph * @return **/ Graph *graph_create(int verticesNumber, int maxDegree, int isWeighted); /** * @brief * @param graph **/ void graph_free(Graph *graph); /** * @brief * @param graph * @param orig * @param dest * @param isDigraph * @param weight * @return **/ int graph_insert_edge(Graph *graph, int orig, int dest, int isDigraph, float weight); /** * @brief * @param graph * @param orig * @param dest * @param isDigraph **/ int graph_remove_edge(Graph *graph, int orig, int dest, int isDigraph); /** * @brief * @param graph * @param initial * @param visited **/ void graph_depth_search(Graph *graph, int initial, int *visited); /** * @brief * @param graph * @param initial * @param visited **/ void graph_breadth_search(Graph *graph, int initial, int *visited); /** * @brief * @param graph * @param initial * @param ancestor * @param distance **/ void graph_shortest_path(Graph *graph, int initial, int *ancestor, float *distance); /** * @brief * @param graph * @param initial * @param ancestor * @param distance **/ void graph_print(Graph *graph); #endif // GRAPH_H
mikaelmessias/utfpr-algorithms
src/sort/merge.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "sort.h" static void merge(Type *v, int l, int m, int r) { int i = l; int j = m; int k = 0; // Temporary vector Type *w = malloc ((r - l) * sizeof(Type)); // Copies smaller elements to the left side and largest to the right side // of the w vector. while(i < m && j < r) { if(v[i] <= v[j]) { w[k] = v[i]; i++; } else { w[k] = v[j]; j++; } k++; } // Copies the remaining elements until it reaches the middle of the original // vector. while(i < m) { w[k++] = v[i++]; } // Copies the remaining elements until it reaches the end of the original // vector. while(j < r) { w[k++] = v[j++]; } // Copies the sorted elements of the temporary vector back to the original // vector. for (i = l; i < r; i++) { v[i] = w[i - l]; } w = vector_free(w); } static void mergesort(Type *v, int l, int r) { if(l < r - 1) { int m = (l + r) / 2; // Sort first and second halves mergesort(v, l, m); mergesort(v, m, r); // Merge the halves keeping them sorted merge(v, l, m, r); } } void merge_sort(Type *v, int n) { mergesort(v, 0, n); }
mikaelmessias/utfpr-algorithms
src/structures/stack/stack.h
#ifndef STACK_H #define STACK_H typedef struct node *Stack; Stack *stack_create(); void stack_push(); int stack_pop(); int stack_size(); void stack_destroy(); #endif
mikaelmessias/utfpr-algorithms
src/sort/heap.c
<filename>src/sort/heap.c<gh_stars>0 /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" static void heap_siftDown(Type *v, int start, int end) { int root = start; while((root * 2 + 1) <= end) { // Points to the left child int child = root * 2 + 1; // If the child has a sibling and the child's value is less than // its sibling's, then point to the right child. if((child + 1) <= end && v[child] < v[child + 1]) { child += 1; } // Out of max-heap order. if(v[root] < v[child]) { vector_swap(v, root, child); // Repeat to continue sift down the child now. root = child; } else { return; } } } static void heapify(Type *v, int n) { // The last parent node. int start = (n - 2) / 2; // Sift down the node at index start to the proper place such that all // nodes below the start index are in heap order. while(start >= 0) { heap_siftDown(v, start, n - 1); start -= 1; } } void heap_sort(Type *v, int n) { // First place a in max-heap order heapify(v, n); int end = n - 1; while(end > 0) { // Swap the maximum value of the heap with the last element. vector_swap(v, end, 0); // Decrements the size of the heap so that the previous max value // will stay in its proper place. end -= 1; // Put the heap back in max-heap order. heap_siftDown(v, 0, end); } }
mikaelmessias/utfpr-algorithms
src/sort/vector.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "sort.h" Type* vector_create(int n) { int i; Type *v = calloc(n, sizeof(Type)); if(v == NULL) { return NULL; } else { srand(time((void*) v)); for(i = 0; i < n; i++) { v[i] = rand() % n; } } return v; } Type* vector_create_ascending(int n) { int i, j; Type *v = calloc(n, sizeof(Type)); if(v != NULL) { srand(time((void*) v)); for(i = 0; i < n; i++) { Type x = rand() % n; int k = 0; while(x > v[k] && k < i) { k++; } j = i; while(j > k) { v[j] = v[j - 1]; j--; } v[j] = x; } return v; } return NULL; } Type* vector_create_descending(int n) { int i, j; Type *v = calloc(n, sizeof(Type)); if(v != NULL) { srand(time((void*) v)); for(i = 0; i < n; i++) { Type x = rand() % n; int k = n - 1; int elements = 0; while(x > v[k] && k > (k - i)) { k--; } j = n - i - 1; while(j < k) { v[j] = v[j + 1]; j++; } v[j] = x; } return v; } return NULL; } void vector_print(Type *v, int n) { if(v == NULL) { return; } int i; printf("["); for(i = 0; i < n; i++) { printf("%d", v[i]); if(i < n-1) { printf(", "); } } printf("]\n"); } int vector_isSorted(Type *v, int n) { if(v == NULL) { return -1; } int i; for(i = 1; i < n; i++) { if(v[i - 1] > v[i]) { return 0; } } return 1; } Type* vector_free(Type *v) { if(v != NULL) { free(v); } return NULL; } void vector_swap(Type *v, int a, int b) { Type x = v[a]; v[a] = v[b]; v[b] = x; }
mikaelmessias/utfpr-algorithms
src/sort/shell.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" void shell_sort(Type *v, int n) { int i, j; // Stores the leap between the elements to be compared. int h = 1; // Initial leap is calculated. do h = h * 3 + 1; while(h < n); do { // This line is here to prevent the h leap to // start bigger than the vector size. h /= 3; for(i = h; i < n; i++) { // Stores the i-th element. Type x = v[i]; j = i; while(v[j - h] > x) { // Pushes bigger elements one position to the right v[j] = v[j - h]; j -= h; if(j < h) { break; } } // Inserts the i-th element in its appropriate position v[j] = x; } } while(h != 1); }
mikaelmessias/utfpr-algorithms
src/sort/insertion.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" void insertion_sort(Type *v, int n) { int i, j; // Stores the i-th element. Type x; for(i = 1; i < n; i++) { x = v[i]; j = i - 1; // Searches for elements smaller than the i-th element. while(j >= 0 && x < v[j]) { v[j + 1] = v[j]; j--; } // The i-th element is allocated in its appropriate position. v[j + 1] = x; } }
mikaelmessias/utfpr-algorithms
src/structures/graph/main.c
#include <stdio.h> #include "graph.h" int main() { Graph *g = graph_create(3, 2, 0); if(g) { printf("Graph created sucessfully.\n\n"); printf("Vertices: %d\nMax degree: %d\nIs weighted? ", g->vertices, \ g->maxDegree); if(g->isWeighted) { printf("Yes\n"); } else { printf("No\n\n"); } } graph_insert_edge(g,0,1,0,0); graph_insert_edge(g,0,2,0,0); graph_insert_edge(g,1,2,0,0); graph_insert_edge(g,1,0,0,0); graph_print(g); graph_free(g); return 0; }
mikaelmessias/utfpr-algorithms
src/structures/stack/stack.c
<reponame>mikaelmessias/utfpr-algorithms #include <stdlib.h> #include "stack.h" struct node { int data; struct node *prox; }; typedef struct node Node; Stack *stack_create() { Stack *stack = (Stack *)malloc(sizeof(Stack)); if (stack != NULL) { *stack = NULL; } return stack; }
mikaelmessias/utfpr-algorithms
src/sort/selection.c
<filename>src/sort/selection.c /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" void selection_sort(Type *v, int n) { int i, j, smaller; for(i = 0; i < n-1; i++) { smaller = i; for(j = i + 1; j < n; j++) { // Searches if the smaller index stores an element larger // than those in positions ahead until the end of the vector. if(v[j] < v[smaller]) { smaller = j; } } // If there is no element smaller than the smaller position, // prevents unnecessarily call for function vector_swap. if(smaller != i) { vector_swap(v, smaller, i); } } }
mikaelmessias/utfpr-algorithms
src/sort/sort.h
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #ifndef SORT_H #define SORT_H #include "vector.h" /** ** SORT ALGORITHMS */ /** * @brief Sort a vector with the Bubble Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void bubble_sort(Type *v, int n); /** * @brief Sort a vector with the Selection Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void selection_sort(Type *v, int n); /** * @brief Sort a vector with the Insertion Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void insertion_sort(Type *v, int n); /** * @brief Sort a vector with the Shell Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void shell_sort(Type *v, int n); /** * @brief Sort a vector with the Quick Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void quick_sort(Type *v, int n); /** * @brief Sort a vector with the Heap Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void heap_sort(Type *v, int n); /** * @brief Sort a vector with the Merge Sort algorithm. * @param v The vector to be sorted. * @param n The size of the vector. */ void merge_sort(Type *v, int n); #endif /* SORT_H */
mikaelmessias/utfpr-algorithms
src/sort/main.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "sort.h" #define TYPES 3 #define SIZES 37 #define TESTS 10 static double runtime[SIZES][TESTS]; int sizes[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000}; Type *v; int i, j; char filename[100]; clock_t begin_t; #define EXECUTE(SIMPLE_NAME, FUNCTION_NAME, CREATE, VECTOR_STATUS) \ strcpy(filename, "benchmark/"); \ strcat(filename, #SIMPLE_NAME); \ strcat(filename, "/"); \ strcat(filename, #FUNCTION_NAME); \ strcat(filename, "_"); \ strcat(filename, #VECTOR_STATUS); \ strcat(filename, ".csv"); \ \ for(i = 0; i < SIZES; i++) { \ printf("\n> Line 41: Size: %d\n", sizes[i]); \ \ for(j = 0; j < TESTS; j++) { \ printf("> Line 44: Test %d\n", j); \ \ v = CREATE(sizes[i]); \ \ begin_t = clock(); \ FUNCTION_NAME(v, sizes[i]); \ \ runtime[i][j] = (((double) clock() - begin_t) * 1000) / \ CLOCKS_PER_SEC; \ } \ if(!vector_isSorted(v, i)) { \ printf("> Line 54: Array isn't sorted\n"); \ v = vector_free(v); \ exit(1); \ } \ vector_print(v, sizes[i]); \ v = vector_free(v); \ } \ printf("\n> Line 60: Running times saved sucessufully on %s\n", \ filename); \ save_csv(filename); void save_csv(char filename[40]); int main(){ EXECUTE(bubble, bubble_sort, vector_create, random); EXECUTE(bubble, bubble_sort, vector_create_ascending, ascending); EXECUTE(bubble, bubble_sort, vector_create_descending, descending); EXECUTE(selection, selection_sort, vector_create, random); EXECUTE(selection, selection_sort, vector_create_ascending, ascending); EXECUTE(selection, selection_sort, vector_create_descending, descending); EXECUTE(insertion, insertion_sort, vector_create, random); EXECUTE(insertion, insertion_sort, vector_create_ascending, ascending); EXECUTE(insertion, insertion_sort, vector_create_descending, descending); EXECUTE(shell, shell_sort, vector_create, random); EXECUTE(shell, shell_sort, vector_create_ascending, ascending); EXECUTE(shell, shell_sort, vector_create_descending, descending); EXECUTE(quick, quick_sort, vector_create, random); EXECUTE(quick, quick_sort, vector_create_ascending, ascending); EXECUTE(quick, quick_sort, vector_create_descending, descending); EXECUTE(heap, heap_sort, vector_create, random); EXECUTE(heap, heap_sort, vector_create_ascending, ascending); EXECUTE(heap, heap_sort, vector_create_descending, descending); EXECUTE(merge, merge_sort, vector_create, random); EXECUTE(merge, merge_sort, vector_create_ascending, ascending); EXECUTE(merge, merge_sort, vector_create_descending, descending); return 0; } void save_csv(char *filename) { FILE *fp = fopen(filename,"w+"); int i, j; printf("\n> Line 105: This content will be write in the file:\n\n"); for(i = 0; i < SIZES; i++) { for(j = 0; j < TESTS; j++) { printf("Size: %d\tTest: %d\tTime: %.4f\n", sizes[i], j+1, \ runtime[i][j]); } } fprintf(fp,"\nEntrada, Teste 1, Teste 2, Teste 3, Teste 4, Teste 5" \ ", Teste 6, teste 7, Teste 8, Teste 9, Teste 10\n"); for(i = 0; i < SIZES; i++) { fprintf(fp,"%d, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f," \ "%.4f, %.4f\n", sizes[i], runtime[i][0], runtime[i][1], \ runtime[i][2], runtime[i][3], runtime[i][4], runtime[i][5], \ runtime[i][6],runtime[i][7], runtime[i][8], runtime[i][9]); } fclose(fp); }
mikaelmessias/utfpr-algorithms
src/structures/stack/main.c
<filename>src/structures/stack/main.c #include <stdio.h> #include "stack.h" int main() { Stack *stack = stack_create(); printf("%lx", sizeof(stack)); return 0; }
mikaelmessias/utfpr-algorithms
src/sort/vector.h
<gh_stars>0 /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #ifndef VECTOR_H #define VECTOR_H typedef int Type; /** ** VECTOR */ /** * @brief Create a vector and generate random values to be stored inside it. * @param n The size of the vector. * @return A pointer to the allocated vector. */ Type* vector_create(int n); /** * @brief Create a vector, generate random values and insert them in ascending * order. * @param n The size of the vector. * @return A pointer to the allocated vector. */ Type* vector_create_ascending(int n); /** * @brief Create a vector, generate random values and insert them in descending * order. * @param n The size of the vector. * @return A pointer to the allocated vector. */ Type* vector_create_descending(int n); /** * @brief Print the vector formatted. * @param v The vector. * @param n The size of the vector. */ void vector_print(Type *v, int n); /** * @brief Check if the vector is sorted. * @param v The vector. * @param n The size of the vector. * @return The value 1 if sorted or 0 if not sorted. */ int vector_isSorted(Type *v, int n); /** * @brief Swap two elements from a vector. * @param v The vector. * @param a The first element position. * @param b The second element position. **/ void vector_swap(Type *v, int a, int b); /** * @brief Free the vector from memory. * @param v The vector. * @return Null element. */ Type* vector_free(Type *v); #endif /* VECTOR_H */
mikaelmessias/utfpr-algorithms
src/sort/bubble.c
/**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" void bubble_sort(Type *v, int n) { int i, j; // Stores the i-th element. int x; for(i = 0; i < n - 1; i++) { for(j = 1; j < n; j++) { // For each iteration, compares two contiguous positions and // swap them if the rightmost element is larger. if(v[j] < v[j - 1]) { vector_swap(v, j, j - 1); } } } }
mikaelmessias/utfpr-algorithms
src/structures/graph/graph.c
<reponame>mikaelmessias/utfpr-algorithms /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "graph.h" /* struct graph { int isWeighted; int vertices; int maxDegree; int **edges; float **weights; int *degree; };*/ Graph *graph_create(int verticesNumber, int maxDegree, int isWeighted) { Graph *g; g = (Graph*) malloc(sizeof(struct graph)); if(g != NULL) { int i; g->vertices = verticesNumber; g->maxDegree = maxDegree; g->isWeighted = (isWeighted != 0)?1:0;; g->degree = (int*) calloc(verticesNumber, sizeof(int)); g->edges = (int**) malloc(verticesNumber * sizeof(int*)); for(i = 0; i < verticesNumber; i++) { g->edges[i] = (int*) malloc(maxDegree * sizeof(int)); } if(g->isWeighted) { g->weights = (float**) malloc(verticesNumber * sizeof(float*)); for(i = 0; i < verticesNumber; i++) { g->weights[i] = (float*) malloc(maxDegree * sizeof(float)); } } } return g; } void graph_free(Graph *graph) { if(graph != NULL) { int i; for(i = 0; i < graph->vertices; i++) { free(graph->edges[i]); } free(graph->edges); if(graph->isWeighted) { for(i = 0; i < graph->vertices; i++) { free(graph->weights[i]); } free(graph->weights); } free(graph->degree); free(graph); } } int graph_insert_edge(Graph *graph, int orig, int dest, int isDigraph, float weight) { if(graph == NULL) { return 0; } if(orig < 0 || orig >= graph->vertices) { return 0; } if(dest < 0 || dest >= graph->vertices) { return 0; } graph->edges[orig][graph->degree[orig]] = dest; if(graph->isWeighted) { graph->weights[orig][graph->degree[orig]] = weight; } graph->degree[orig]++; if(isDigraph == 0) { graph_insert_edge(graph,dest,orig,1,weight); } return 1; } int graph_remove_edge(Graph *graph, int orig, int dest, int isDigraph) { if(graph == NULL) { return 0; } if(orig < 0 || orig >= graph->vertices) { return 0; } if(dest < 0 || dest >= graph->vertices) { return 0; } int i = 0; while(i < graph->degree[orig] && graph->edges[orig][i] != dest) { i++; } if(i == graph->degree[orig]) { // Could not find element return 0; } graph->degree[orig]--; graph->edges[orig][i] = graph->edges[orig][graph->degree[orig]]; if(graph->isWeighted) { graph->weights[orig][i] = graph->weights[orig][graph->degree[orig]]; } if(isDigraph == 0) { graph_remove_edge(graph,dest,orig,1); } return 1; } void graph_print(Graph *graph) { if(graph == NULL) { return; } int i, j; for(i = 0; i < graph->vertices; i++) { printf("%d: ", i); for(j = 0; j < graph->degree[i]; j++) { if(graph->isWeighted) { printf("%d(%.2f), ", graph->edges[i][j], graph->weights[i][j]); } else { printf("%d, ", graph->edges[i][j]); } } printf("\n"); } }
mikaelmessias/utfpr-algorithms
src/sort/quick.c
<reponame>mikaelmessias/utfpr-algorithms /**************************************************************************** * Copyright 2018 <NAME> <<EMAIL>> * * You can do whatever you want with this code, as long as you include the * original copyright and license notice in any copy of the software/source. * Furthermore, please read the LICENSE file for more information. ***************************************************************************/ #include <stdio.h> #include "sort.h" /** * @brief Chooses a pivot and places it in its correct position in the sorted * vector, moves the smallest elements to the left of the pivot and the largest * ones to the right. * @param v The vector. * @param l The smallest position. * @param r The largest position. * @return */ static int quick_partition(Type *v, int l, int r) { Type x = v[r]; // Index of smaller element. int i = (l - 1), j; for(j = l; j <= r - 1; j++) { // If current element is smaller than or equal to pivot. if(v[j] <= x) { i++; vector_swap(v, i, j); } } vector_swap(v, i + 1, r); return (i + 1); } static void quick_split(Type *v, int l, int r) { int p; if(l < r) { // p is the partitioning index, v[p] is now at right place. p = quick_partition(v, l, r); quick_split(v, l, p - 1); quick_split(v, p + 1, r); } } void quick_sort(Type *v, int n) { quick_split(v, 0, n - 1); }
bvbfan/sslxx
sslxx.h
<filename>sslxx.h /////////////////////////////////////////////////////////////////////////////// /// \author (c) <NAME> (<EMAIL>) /// 2017, <NAME> /// /// \license The MIT License (MIT) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include <memory> #include <string> #include <unistd.h> #include <exception> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <openssl/ssl.h> #include <openssl/opensslv.h> #ifndef __SSLXX__ #define __SSLXX__ namespace sslxx { #if OPENSSL_VERSION_NUMBER >= 0x10100000L #define openssl_client_method ::TLS_client_method() #define openssl_server_method ::TLS_server_method() #else #define openssl_client_method ::SSLv23_client_method() #define openssl_server_method ::SSLv23_server_method() #endif static void init_openssl() { struct library_init { library_init() { ::SSL_library_init(); ::OpenSSL_add_all_algorithms(); } ~library_init() { ::EVP_cleanup(); } }; static library_init one_time_init; } class exception : public std::exception { const char *m_text; public: exception(const char *text) : m_text(text) {} const char* what() const noexcept override { return m_text; } }; class stream { SSL *m_ssl = nullptr; public: stream(SSL *ssl) : m_ssl(ssl) {} stream(stream &&) = default; stream(const stream &) = delete; stream& operator=(stream &&) = default; stream& operator=(const stream &) = delete; ~stream() { if (!m_ssl) { return; } int fd = ::SSL_get_fd(m_ssl); ::SSL_free(m_ssl); if (fd != -1) { ::close(fd); } m_ssl = nullptr; } std::string receive() { ssize_t len = 0; std::string result; do { char buffer[256] = {}; len = ::SSL_read(m_ssl, buffer, 255); if (len > 0) { result.append(buffer, len); } } while (len == 255); return result; } size_t send(const std::string &buffer) { auto len = ::SSL_write(m_ssl, buffer.data(), buffer.size()); return len < 0 ? size_t(0) : size_t(len); } }; class connector { SSL_CTX *m_ctx = nullptr; struct sockaddr_in m_addr = {}; public: connector(const char *addr, int port) { init_openssl(); if (!(m_ctx = ::SSL_CTX_new(openssl_client_method))) { throw exception("Could not create ctx"); } m_addr.sin_family = AF_INET; m_addr.sin_port = htons(port); ::inet_aton(addr, &m_addr.sin_addr); } ~connector() { if (m_ctx) { ::SSL_CTX_free(m_ctx); m_ctx = nullptr; } } connector(connector &&) = default; connector(const connector &) = delete; connector& operator=(connector &&) = default; connector& operator=(const connector &) = delete; std::unique_ptr<stream> connect() { int fd = ::socket(PF_INET, SOCK_STREAM, 0); if (fd <= 0) { return { nullptr }; } if (::connect(fd, (struct sockaddr *)&m_addr, sizeof(m_addr))) { ::close(fd); return { nullptr }; } SSL *ssl = ::SSL_new(m_ctx); ::SSL_set_fd(ssl, fd); if (::SSL_connect(ssl) != 1) { ::SSL_free(ssl); ::close(fd); } return std::unique_ptr<stream>{ new stream(ssl) }; } }; class listener { int m_fd = 0; SSL_CTX *m_ctx = nullptr; void cleanup() { if (m_fd) { ::close(m_fd); m_fd = 0; } if (m_ctx) { ::SSL_CTX_free(m_ctx); m_ctx = nullptr; } } public: listener(int port, const char *cert_file) { init_openssl(); // NOTE: destructor will not be called on non-fully constructed object // thus cleanup should be called explicitly if (!(m_ctx = ::SSL_CTX_new(openssl_server_method))) { cleanup(); throw exception("Could not create ctx"); } ::SSL_CTX_set_ecdh_auto(m_ctx, 1); if (::SSL_CTX_use_certificate_file(m_ctx, cert_file, SSL_FILETYPE_PEM) <= 0) { cleanup(); throw exception("Could not use certificate file"); } if (::SSL_CTX_use_PrivateKey_file(m_ctx, cert_file, SSL_FILETYPE_PEM) <= 0) { cleanup(); throw exception("Could not use private key"); } m_fd = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (m_fd <= 0) { cleanup(); throw exception("Could not create socket"); } struct sockaddr_in server = {}; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = INADDR_ANY; if (::bind(m_fd, (struct sockaddr *)&server, sizeof(server)) < 0) { cleanup(); throw exception("Could not bind socket"); } if (::listen(m_fd, 16) != 0) { cleanup(); throw exception("Could not listen socket"); } } listener(listener &&) = default; listener(const listener &) = delete; listener& operator=(listener &&) = default; listener& operator=(const listener &) = delete; ~listener() { cleanup(); } std::unique_ptr<stream> accept() { struct sockaddr_in client; int sock_len = sizeof(client); int fd = ::accept(m_fd, (struct sockaddr *)&client, (socklen_t*)&sock_len); if (fd <= 0) { return { nullptr }; } SSL *ssl = ::SSL_new(m_ctx); ::SSL_set_fd(ssl, fd); if (::SSL_accept(ssl) <= 0) { ::SSL_free(ssl); ::close(fd); return { nullptr }; } return std::unique_ptr<stream>{ new stream(ssl) }; } }; } #endif // __SSLXX__
cojosef96/OpenSfM
opensfm/src/map/rig.h
<reponame>cojosef96/OpenSfM #pragma once #include <geometry/camera.h> #include <geometry/pose.h> #include <map/defines.h> #include <map/shot.h> #include <exception> #include <set> #include <unordered_map> namespace map { struct RigCamera { /* Pose of the camera wrt. the rig coordinate frame */ geometry::Pose pose; /* Unique identifier of this RigCamera inside the RigModel */ map::RigCameraId id; RigCamera() = default; RigCamera(const geometry::Pose& pose, const map::RigCameraId& id) : pose(pose), id(id) {} }; struct RigModel { enum RelativeType { // All instances of this rig have their relatives poses being held FIXED = 0, // All instances shares the same relatives poses which are optimized SHARED = 1, // Each rig instance has its own relative pose wich is optimized VARIABLE = 2, }; // Specify how to optimize rig relatives RelativeType relative_type{RelativeType::SHARED}; // Unique identifier of this rig map::RigModelId id; RigModel() = default; explicit RigModel(const map::RigModelId& id) : id(id) {} // RigCameras void AddRigCamera(const RigCamera& rig_camera) { rig_cameras_[rig_camera.id] = rig_camera; } RigCamera& GetRigCamera(const map::RigCameraId& rig_camera_id); const RigCamera& GetRigCamera(const map::RigCameraId& rig_camera_id) const; const std::unordered_map<map::RigCameraId, RigCamera>& GetRigCameras() const { return rig_cameras_; } std::unordered_map<map::RigCameraId, RigCamera>& GetRigCameras() { return rig_cameras_; } private: // RigCameras that constitues that rig std::unordered_map<map::RigCameraId, RigCamera> rig_cameras_; }; class RigInstance { public: map::RigInstanceId id; RigInstance(RigModel* rig_model, const RigInstanceId instance_id) : id(instance_id), rig_model_(rig_model) { if (rig_model->relative_type == RigModel::RelativeType::VARIABLE) { own_rig_model_.SetValue(*rig_model); rig_model_ = &own_rig_model_.Value(); } } // Getters std::unordered_map<map::ShotId, map::Shot*> GetShots() const { return shots_; } std::unordered_map<map::ShotId, map::Shot*>& GetShots() { return shots_; } RigModel* GetRigModel() { return rig_model_; } const RigModel* GetRigModel() const { return rig_model_; } std::set<map::ShotId> GetShotIDs() const; std::unordered_map<map::ShotId, map::RigCameraId> GetShotRigCameraIDs() const { return shots_rig_cameras_; } // Pose geometry::Pose GetPose() const { return pose_; } geometry::Pose& GetPose() { return pose_; } void SetPose(const geometry::Pose& pose) { pose_ = pose; } // Add a new shot to this instance void AddShot(const map::RigCameraId& rig_camera_id, map::Shot* shot); // Update instance pose and shot's poses wrt. to a given shot of the instance void UpdateInstancePoseWithShot(const map::ShotId& shot_id, const geometry::Pose& shot_pose); // Update pose of this instance's RigCamera void UpdateRigCameraPose(const map::RigCameraId& rig_camera_id, const geometry::Pose& pose); private: // Actual instanciation of a rig : each shot gets mapped to some RigCamera std::unordered_map<map::ShotId, map::Shot*> shots_; std::unordered_map<map::ShotId, map::RigCameraId> shots_rig_cameras_; // Pose of this rig coordinate frame wrt. world coordinates geometry::Pose pose_; // Model it instanciates RigModel* rig_model_; // For variable Rigs, each instance has its own copy foundation::OptionalValue<RigModel> own_rig_model_; }; } // namespace map
cojosef96/OpenSfM
opensfm/src/bundle/bundle_adjuster.h
<gh_stars>0 #pragma once #include <bundle/data/camera.h> #include <bundle/data/data.h> #include <bundle/data/pose.h> #include <bundle/data/rig.h> #include <bundle/data/shot.h> #include <foundation/optional.h> #include <geometry/camera.h> #include <geometry/pose.h> #include <cmath> #include <cstdio> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> #include "ceres/ceres.h" #include "ceres/cubic_interpolation.h" #include "ceres/rotation.h" extern "C" { #include <string.h> } namespace bundle { enum PositionConstraintType { X = 0x1, Y = 0x2, Z = 0x4, XY = X | Y, XYZ = XY | Z }; struct Point { std::string id; Eigen::Matrix<double, 3, 1> parameters; bool constant; std::map<std::string, VecXd> reprojection_errors; Vec3d GetPoint() const { return parameters; } void SetPoint(const Vec3d &p) { parameters = p; } }; struct Reconstruction { std::string id; std::map<std::string, double> scales; bool constant; bool shared; double *GetScalePtr(const std::string &shot) { if (shared) { return &(scales.begin()->second); } return &(scales[shot]); } double GetScale(const std::string &shot) { if (shared) { return scales.begin()->second; } return scales[shot]; } void SetScale(const std::string &shot, double v) { if (shared) { scales.begin()->second = v; } scales[shot] = v; } }; struct PointProjectionObservation { Vec2d coordinates; Point *point; Shot *shot; Camera *camera; double std_deviation; }; struct PointRigProjectionObservation { Vec2d coordinates; Point *point; RigShot *rig_shot; Camera *camera; double std_deviation; }; struct RotationPrior { Shot *shot; double rotation[3]; double std_deviation; }; struct TranslationPrior { Shot *shot; double translation[3]; double std_deviation; }; struct PositionPrior { Shot *shot; double position[3]; double std_deviation; }; struct PointPositionPrior { Point *point; double position[3]; double std_deviation; }; struct RelativeMotion { RelativeMotion(const std::string &reconstruction_i, const std::string &shot_i, const std::string &reconstruction_j, const std::string &shot_j, const Vec3d &rotation, const Vec3d &translation, double robust_multiplier) { reconstruction_id_i = reconstruction_i; shot_id_i = shot_i; reconstruction_id_j = reconstruction_j; shot_id_j = shot_j; parameters.resize(Pose::Parameter::NUM_PARAMS); parameters.segment(Pose::Parameter::RX, 3) = rotation; parameters.segment(Pose::Parameter::TX, 3) = translation; scale_matrix.resize(Pose::Parameter::NUM_PARAMS, Pose::Parameter::NUM_PARAMS); scale_matrix.setIdentity(); this->robust_multiplier = robust_multiplier; } Vec3d GetRotation() const { return parameters.segment(Pose::Parameter::RX, 3); } Vec3d GetTranslation() const { return parameters.segment(Pose::Parameter::TX, 3); } void SetRotation(const Vec3d &r) { parameters.segment(Pose::Parameter::RX, 3) = r; } void SetTranslation(const Vec3d &t) { parameters.segment(Pose::Parameter::TX, 3) = t; } void SetScaleMatrix(const MatXd &s) { scale_matrix = s; } std::string reconstruction_id_i; std::string shot_id_i; std::string reconstruction_id_j; std::string shot_id_j; VecXd parameters; MatXd scale_matrix; double robust_multiplier; }; struct RelativeSimilarity : public RelativeMotion { RelativeSimilarity(const std::string &reconstruction_i, const std::string &shot_i, const std::string &reconstruction_j, const std::string &shot_j, const Vec3d &rotation, const Vec3d &translation, double s, double robust_multiplier) : RelativeMotion(reconstruction_i, shot_i, reconstruction_j, shot_j, rotation, translation, robust_multiplier), scale(s) { scale_matrix.resize(Pose::Parameter::NUM_PARAMS + 1, Pose::Parameter::NUM_PARAMS + 1); scale_matrix.setIdentity(); } double scale; }; struct RelativeSimilarityCovariance { static const int Size = Pose::Parameter::NUM_PARAMS + 1; std::vector<Vec3d> points; Eigen::Matrix<double, Size, Size> covariance; void AddPoint(const Vec3d &v) { points.push_back(v); } void Compute() { covariance.setZero(); for (const auto &p : points) { const auto &x = p[0]; const auto &y = p[1]; const auto &z = p[2]; Eigen::Matrix<double, 3, Pose::Parameter::NUM_PARAMS + 1> local_jacobian; local_jacobian.block(0, Pose::Parameter::TX, 3, 3) = Eigen::Matrix<double, 3, 3>::Identity(); local_jacobian.block(0, Pose::Parameter::RX, 3, 3) << 0, z, -y, -z, 0, x, y, -x, 0; local_jacobian.block(0, Pose::Parameter::NUM_PARAMS, 3, 1) << x, y, z; covariance += local_jacobian.transpose() * local_jacobian; } if (covariance.determinant() < 1e-20) { covariance.setIdentity(); } else { covariance = covariance.inverse(); } } Eigen::Matrix<double, Size, Size> GetCovariance() const { return covariance; } }; struct RelativeRotation { RelativeRotation(const std::string &shot_i, const std::string &shot_j, const Vec3d &r) { shot_id_i = shot_i; shot_id_j = shot_j; rotation = r; scale_matrix.setIdentity(); } Vec3d GetRotation() const { return rotation; } void SetRotation(const Vec3d &r) { rotation = r; } void SetScaleMatrix(const Mat3d &s) { scale_matrix = s; } std::string shot_id_i; std::string shot_id_j; Vec3d rotation; Mat3d scale_matrix; }; struct CommonPosition { Shot *shot1; Shot *shot2; double margin; double std_deviation; }; struct AbsolutePosition { Shot *shot; Vec3d position; double std_deviation; std::string std_deviation_group; }; struct HeatmapInterpolator { HeatmapInterpolator(const std::vector<double> &flatten_heatmap, size_t width, double resolution); std::vector<double> heatmap; size_t width; size_t height; ceres::Grid2D<double> grid; ceres::BiCubicInterpolator<ceres::Grid2D<double>> interpolator; double resolution; }; struct AbsolutePositionHeatmap { Shot *shot; std::shared_ptr<HeatmapInterpolator> heatmap; double x_offset; double y_offset; double height; double width; double std_deviation; }; struct AbsoluteUpVector { Shot *shot; Vec3d up_vector; double std_deviation; }; struct AbsoluteAngle { Shot *shot; double angle; double std_deviation; }; struct LinearMotion { Shot *shot0; Shot *shot1; Shot *shot2; double alpha; double position_std_deviation; double orientation_std_deviation; }; struct PointPositionShot { std::string shot_id; std::string reconstruction_id; std::string point_id; Vec3d position; double std_deviation; PositionConstraintType type; }; struct PointPositionWorld { std::string point_id; Vec3d position; double std_deviation; PositionConstraintType type; }; class BundleAdjuster { public: BundleAdjuster(); virtual ~BundleAdjuster() = default; // Bundle variables // Basic void AddCamera(const std::string &id, const geometry::Camera &camera, const geometry::Camera &prior, bool constant); void AddShot(const std::string &id, const std::string &camera, const Vec3d &rotation, const Vec3d &translation, bool constant); void AddPoint(const std::string &id, const Vec3d &position, bool constant); // Rigs void AddRigInstance( const std::string &rig_instance_id, const geometry::Pose &rig_instance_pose, const std::string &rig_model, const std::unordered_map<std::string, std::string> &shot_cameras, const std::unordered_map<std::string, std::string> &shot_rig_cameras, bool fixed); void AddRigModel( const std::string &rig_model, const std::unordered_map<std::string, geometry::Pose> &cameras_poses, const std::unordered_map<std::string, geometry::Pose> &cameras_poses_prior, bool fixed); void AddRigPositionPrior(const std::string &instance_id, const Vec3d &position, double std_deviation); // Cluster-based void AddReconstruction(const std::string &id, bool constant); void AddReconstructionShot(const std::string &reconstruction_id, double scale, const std::string &shot_id); void SetScaleSharing(const std::string &id, bool share); // Averaging constraints // Point projection void AddPointProjectionObservation(const std::string &shot, const std::string &point, const Vec2d &observation, double std_deviation); void AddRotationPrior(const std::string &shot_id, double rx, double ry, double rz, double std_deviation); void AddTranslationPrior(const std::string &shot_id, double tx, double ty, double tz, double std_deviation); void AddPositionPrior(const std::string &shot_id, double x, double y, double z, double std_deviation); void AddPointPositionPrior(const std::string &point_id, double x, double y, double z, double std_deviation); void SetOriginShot(const std::string &shot_id); void SetUnitTranslationShot(const std::string &shot_id); // Relative motion ones void AddRelativeMotion(const RelativeMotion &rm); void AddRelativeSimilarity(const RelativeSimilarity &rm); void AddRelativeRotation(const RelativeRotation &rr); // Absolute motion ones void AddCommonPosition(const std::string &shot_id1, const std::string &shot_id2, double margin, double std_deviation); void AddAbsolutePosition(const std::string &shot_id, const Vec3d &position, double std_deviation, const std::string &std_deviation_group); void AddHeatmap(const std::string &heatmap_id, const std::vector<double> &in_heatmap, size_t in_width, double resolution); void AddAbsolutePositionHeatmap(const std::string &shot_id, const std::string &heatmap_id, double x_offset, double y_offset, double std_deviation); void AddAbsoluteUpVector(const std::string &shot_id, const Vec3d &up_vector, double std_deviation); void AddAbsolutePan(const std::string &shot_id, double angle, double std_deviation); void AddAbsoluteTilt(const std::string &shot_id, double angle, double std_deviation); void AddAbsoluteRoll(const std::string &shot_id, double angle, double std_deviation); // Motion priors void AddLinearMotion(const std::string &shot0_id, const std::string &shot1_id, const std::string &shot2_id, double alpha, double position_std_deviation, double orientation_std_deviation); // Point positions void AddPointPositionShot(const std::string &point_id, const std::string &shot_id, const std::string &reconstruction_id, const Vec3d &position, double std_deviation, const PositionConstraintType &type); void AddPointPositionWorld(const std::string &point_id, const Vec3d &position, double std_deviation, const PositionConstraintType &type); // Minimization setup void SetPointProjectionLossFunction(std::string name, double threshold); void SetRelativeMotionLossFunction(std::string name, double threshold); void SetAdjustAbsolutePositionStd(bool adjust); void SetMaxNumIterations(int miter); void SetNumThreads(int n); void SetUseAnalyticDerivatives(bool use); void SetLinearSolverType(std::string t); void SetInternalParametersPriorSD(double focal_sd, double c_sd, double k1_sd, double k2_sd, double p1_sd, double p2_sd, double k3_sd, double k4_sd); void SetRigParametersPriorSD(double rig_translation_sd, double rig_rotation_sd); void SetComputeCovariances(bool v); bool GetCovarianceEstimationValid(); void SetComputeReprojectionErrors(bool v); // Minimization void Run(); void ComputeCovariances(ceres::Problem *problem); void ComputeReprojectionErrors(); // Getters geometry::Camera GetCamera(const std::string &id); Shot GetShot(const std::string &id); Reconstruction GetReconstruction(const std::string &id); Point GetPoint(const std::string &id); RigModel GetRigModel(const std::string &model_id); RigInstance GetRigInstance(const std::string &instance_id); // Minimization details std::string BriefReport(); std::string FullReport(); private: // default sigmas geometry::Camera GetDefaultCameraSigma(const geometry::Camera &camera) const; geometry::Pose GetDefaultRigPoseSigma() const; // minimized data std::map<std::string, Camera> cameras_; std::map<std::string, Shot> shots_; std::map<std::string, RigShot> rig_shots_; std::map<std::string, Reconstruction> reconstructions_; std::map<std::string, Point> points_; std::map<std::string, RigModel> rig_models_; std::map<std::string, RigInstance> rig_instances_; bool use_analytic_{false}; // minimization constraints // reprojection observation std::vector<PointProjectionObservation> point_projection_observations_; std::vector<PointRigProjectionObservation> point_rig_projection_observations_; std::map<std::string, std::shared_ptr<HeatmapInterpolator>> heatmaps_; // relative motion between shots std::vector<RelativeMotion> relative_motions_; std::vector<RelativeSimilarity> relative_similarity_; std::vector<RelativeRotation> relative_rotations_; std::vector<CommonPosition> common_positions_; // shots absolute positions std::vector<AbsolutePositionHeatmap> absolute_positions_heatmaps_; std::vector<AbsolutePosition> absolute_positions_; std::vector<AbsoluteUpVector> absolute_up_vectors_; std::vector<AbsoluteAngle> absolute_pans_; std::vector<AbsoluteAngle> absolute_tilts_; std::vector<AbsoluteAngle> absolute_rolls_; std::vector<RotationPrior> rotation_priors_; std::vector<TranslationPrior> translation_priors_; std::vector<PositionPrior> position_priors_; std::vector<PointPositionPrior> point_position_priors_; Shot *unit_translation_shot_; // motion priors std::vector<LinearMotion> linear_motion_prior_; // points absolute constraints std::vector<PointPositionShot> point_positions_shot_; std::vector<PointPositionWorld> point_positions_world_; // Camera parameters prior double focal_prior_sd_; double c_prior_sd_; double k1_sd_; double k2_sd_; double p1_sd_; double p2_sd_; double k3_sd_; double k4_sd_; // Rig model extrinsics prior double rig_translation_sd_{1.0}; double rig_rotation_sd_{1.0}; // minimization setup std::string point_projection_loss_name_; double point_projection_loss_threshold_; std::string relative_motion_loss_name_; double relative_motion_loss_threshold_; bool adjust_absolute_position_std_; bool compute_covariances_; bool covariance_estimation_valid_; bool compute_reprojection_errors_; int max_num_iterations_; int num_threads_; std::string linear_solver_type_; // internal ceres::Solver::Summary last_run_summary_; }; } // namespace bundle
cojosef96/OpenSfM
opensfm/src/map/shot.h
#pragma once #include <foundation/optional.h> #include <geometry/camera.h> #include <geometry/pose.h> #include <map/defines.h> #include <map/landmark.h> #include <sfm/observation.h> #include <Eigen/Eigen> #include <iostream> #include <unordered_map> namespace map { class Map; class RigInstance; struct RigCamera; struct ShotMesh { EIGEN_MAKE_ALIGNED_OPERATOR_NEW void SetVertices(const MatXd& vertices) { vertices_ = vertices; } void SetFaces(const MatXd& faces) { faces_ = faces; } MatXd GetFaces() const { return faces_; } MatXd GetVertices() const { return vertices_; } MatXd vertices_; MatXd faces_; }; struct ShotMeasurements { EIGEN_MAKE_ALIGNED_OPERATOR_NEW foundation::OptionalValue<double> capture_time_; foundation::OptionalValue<Vec3d> gps_position_; foundation::OptionalValue<double> gps_accuracy_; foundation::OptionalValue<double> compass_accuracy_; foundation::OptionalValue<double> compass_angle_; foundation::OptionalValue<Vec3d> accelerometer_; foundation::OptionalValue<int> orientation_; foundation::OptionalValue<std::string> sequence_key_; void Set(const ShotMeasurements& other); }; class Shot { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // Shot construction Shot(const ShotId& shot_id, const geometry::Camera* const shot_camera, const geometry::Pose& pose); Shot(const ShotId& shot_id, const geometry::Camera& cam, const geometry::Pose& pose); ShotId GetId() const { return id_; } // Rig bool IsInRig() const { return (rig_instance_.HasValue() || rig_camera_.HasValue()); } void SetRig(const RigInstance* rig_instance, const RigCamera* rig_camera); RigInstanceId GetRigInstanceId() const; RigCameraId GetRigCameraId() const; RigModelId GetRigModelId() const; // Pose void SetPose(const geometry::Pose& pose); const geometry::Pose* const GetPose() const; geometry::Pose* const GetPose(); Mat4d GetWorldToCam() const { return GetPose()->WorldToCamera(); } Mat4d GetCamToWorld() const { return GetPose()->CameraToWorld(); } // Landmark management const std::map< Landmark*, Observation, KeyCompare, Eigen::aligned_allocator<std::pair<Landmark* const, Observation>>>& GetLandmarkObservations() const { return landmark_observations_; } std::map<Landmark*, Observation, KeyCompare, Eigen::aligned_allocator<std::pair<Landmark* const, Observation>>>& GetLandmarkObservations() { return landmark_observations_; } std::vector<Landmark*> ComputeValidLandmarks() { std::vector<Landmark*> valid_landmarks; valid_landmarks.reserve(landmark_observations_.size()); for (const auto& lm_obs : landmark_observations_) { valid_landmarks.push_back(lm_obs.first); } return valid_landmarks; } // Observation management const Observation& GetObservation(const FeatureId id) const { return landmark_observations_.at(landmark_id_.at(id)); } void CreateObservation(Landmark* lm, const Observation& obs) { landmark_observations_.insert(std::make_pair(lm, obs)); landmark_id_.insert(std::make_pair(obs.feature_id, lm)); } Observation* GetLandmarkObservation(Landmark* lm) { return &landmark_observations_.at(lm); } void RemoveLandmarkObservation(const FeatureId id); // Metadata such as GPS, IMU, time const ShotMeasurements& GetShotMeasurements() const { return shot_measurements_; } ShotMeasurements& GetShotMeasurements() { return shot_measurements_; } void SetShotMeasurements(const ShotMeasurements& other) { shot_measurements_.Set(other); } // Comparisons bool operator==(const Shot& shot) const { return id_ == shot.id_; } bool operator!=(const Shot& shot) const { return !(*this == shot); } bool operator<(const Shot& shot) const { return id_ < shot.id_; } bool operator<=(const Shot& shot) const { return id_ <= shot.id_; } bool operator>(const Shot& shot) const { return id_ > shot.id_; } bool operator>=(const Shot& shot) const { return id_ >= shot.id_; } const geometry::Camera* const GetCamera() const { return shot_camera_; } // Camera-related Vec2d Project(const Vec3d& global_pos) const; MatX2d ProjectMany(const MatX3d& points) const; Vec3d Bearing(const Vec2d& point) const; MatX3d BearingMany(const MatX2d& points) const; // Covariance MatXd GetCovariance() const { return covariance_.Value(); } void SetCovariance(const MatXd& cov) { covariance_.SetValue(cov); } public: const ShotId id_; // the file name ShotUniqueId unique_id_; // Ad-hoc merge-specific data ShotMesh mesh; long int merge_cc{0}; double scale{1.0}; private: geometry::Pose GetPoseInRig() const; // Pose mutable std::unique_ptr<geometry::Pose> pose_; foundation::OptionalValue<MatXd> covariance_; // Optional rig data foundation::OptionalValue<const RigInstance*> rig_instance_; foundation::OptionalValue<const RigCamera*> rig_camera_; // Camera pointer (can optionaly belong to the shot) foundation::OptionalValue<geometry::Camera> own_camera_; const geometry::Camera* const shot_camera_; // Metadata ShotMeasurements shot_measurements_; // In OpenSfM, we use a map to reproduce a similar behaviour std::map<Landmark*, Observation, KeyCompare, Eigen::aligned_allocator<std::pair<Landmark* const, Observation>>> landmark_observations_; std::unordered_map<FeatureId, Landmark*> landmark_id_; }; } // namespace map
cojosef96/OpenSfM
opensfm/src/bundle/data/rig.h
<reponame>cojosef96/OpenSfM #pragma once #include <bundle/data/camera.h> #include <bundle/data/data.h> #include <bundle/data/pose.h> namespace bundle { using RigCamera = Pose; struct RigModel : public DataContainer { RigModel( const std::string &id, const std::unordered_map<std::string, geometry::Pose> &rig_cameras_poses, const std::unordered_map<std::string, geometry::Pose> &rig_cameras_poses_prior, const geometry::Pose &sigma) : DataContainer(id) { for (const auto &rig_camera : rig_cameras_poses) { const auto rig_camera_id = rig_camera.first; const auto &prior = rig_cameras_poses_prior.at(rig_camera_id); auto &rig_camera_data = rig_cameras_ .emplace(std::piecewise_construct, std::forward_as_tuple(rig_camera_id), std::forward_as_tuple(rig_camera_id, rig_camera.second, prior, sigma)) .first->second; RegisterData(rig_camera_id, &rig_camera_data); } } RigCamera *GetRigCamera(const std::string &rig_camera_id) { return static_cast<RigCamera *>(GetData(rig_camera_id)); } std::unordered_map<std::string, RigCamera *> GetRigCameras() { std::unordered_map<std::string, RigCamera *> cameras; for (const auto &c : rig_cameras_) { cameras[c.first] = GetRigCamera(c.first); } return cameras; } private: std::unordered_map<std::string, RigCamera> rig_cameras_; }; using RigInstance = Pose; struct RigShot : public DataContainer { RigShot(const std::string &id, bundle::Camera *camera, RigCamera *rig_camera, RigInstance *rig_instance) : DataContainer(id) { RegisterData("camera", camera); RegisterData("rig_camera", rig_camera); RegisterData("rig_instance", rig_instance); } bundle::Camera *GetCamera() { return static_cast<bundle::Camera *>(GetData("camera")); } RigCamera *GetRigCamera() { return static_cast<RigCamera *>(GetData("rig_camera")); } RigInstance *GetRigInstance() { return static_cast<RigInstance *>(GetData("rig_instance")); } }; } // namespace bundle
EduardPetcu/Editor-text
nodes.h
<gh_stars>0 typedef struct node { char data; struct node * next; struct node * prev; } node; typedef struct TDoubleLinkedList { node *head; node *tail; int len; } TDoubleLinkedList; typedef struct ListaNode { TDoubleLinkedList linie; struct ListaNode * urmator; struct ListaNode * anterior; } ListaNode; typedef struct ListaLista { ListaNode *cap; ListaNode *coada; int nrlin; } ListaLista; typedef struct pozitie { int x,y; } pozitie; typedef struct nodeSt { char sir[100]; struct nodeSt *next; } nodeSt; typedef struct stiva { struct nodeSt *top; int len; } stiva; typedef struct nodeIndici { char c; pozitie val; struct nodeIndici *next; } nodeIndici; typedef struct stivaIndici { struct nodeIndici *top; int len; } stivaIndici;
EduardPetcu/Editor-text
functions.h
<gh_stars>0 #include "nodes.h" void initL(TDoubleLinkedList **list) { (*list) = malloc(sizeof(TDoubleLinkedList)); (*list)->head = NULL; (*list)->tail = NULL; (*list)->len=0; } void initListaLista() { lis = malloc(sizeof(ListaLista)); lis->cap = NULL; lis->coada = NULL; lis->nrlin=0; } void insertChar(TDoubleLinkedList *list, char c) { list->len++; node *nou; nou=(node*)malloc(sizeof(node)); nou->data=c; nou->next=NULL; nou->prev=NULL; if(list->head==NULL) { list->head=nou; list->tail=nou; return; } list->tail->next=nou; nou->prev=list->tail; list->tail=nou; } void insereaza(char line[]) { int n=strlen(line),i; TDoubleLinkedList *sir; initL(&sir); ListaNode *newLine; newLine=(ListaNode*)malloc(sizeof(ListaNode)); if(lis->nrlin==0)//lista de linii este goala { lis->cap=newLine; lis->coada=newLine; lis->nrlin++; } else { lis->coada->urmator=newLine; newLine->anterior=lis->coada; lis->coada=newLine; lis->nrlin++; } for(i=0;i<n;i++) { insertChar(sir,line[i]); } (newLine->linie)=*sir; } void print_line(TDoubleLinkedList *list) { node *nou2=list->head; while(nou2!=NULL) { fprintf(output,"%c",nou2->data); nou2=nou2->next; } } void print_ListaLista() { int contor=0; ListaNode *nou=lis->cap; while(contor<lis->nrlin) { print_line(nou); nou=nou->urmator; contor++; } }
EduardPetcu/Editor-text
Editor_text.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "nodes.h" #define LMAX 100 ListaLista *lis; FILE *input,*output; bool text_mode=1; int middleInsert=0,cate; pozitie cursor= {1,1},cc,semn= {0,0}; stiva *undo,*redo,*strings; stivaIndici *ind,*indredo,*chars,*dw_pos; void initS(stiva **s); void add_stack (stiva *s, char *sir); void add_stack_char(stivaIndici *s, char data); void pop_stack(stiva *s); void freeStackIND(stivaIndici **s); void freeStack(stiva **s); void freeList(ListaLista **list); void freeTDList(TDoubleLinkedList list); void initSI(stivaIndici **s); void add_stack_indici (stivaIndici *s, pozitie data); pozitie pop_stack_indici(stivaIndici *s); void initL(ListaNode **list); void initListaLista(ListaLista **lis); void insertChar(ListaNode *list, char c,int p); void insereaza(char line[]); void print_line(ListaNode *list); void print_ListaLista(); int read_command(char line[],int k); void gl(char line[]); void gc(char line[]); void dl(char line[]); void deleteLine(int n); void deleteChar(pozitie cursor,int p); void deleteMoreChars(int n,pozitie cursor,int p); ListaNode* searchLine(int n); void undoAction(); void redoAction(); void saveList(); void freee(); void da(char line[],int k); void ra(char line[],int k); int main() { input=fopen("editor.in","r"); initListaLista(&lis); initS(&undo); initS(&redo); initS(&strings); initSI(&ind); initSI(&indredo); initSI(&chars); initSI(&dw_pos); char line[LMAX]; while(fgets(line,LMAX,input)!=NULL) { if(strstr(line,"::i")!=NULL) { text_mode=text_mode^1; if(middleInsert>1) { cursor.y=1; add_stack_indici(ind,cursor); insereaza(strings->top->sir); add_stack(undo,strings->top->sir); middleInsert=0; } middleInsert=0; add_stack(undo,line); continue; } if(text_mode) { add_stack_indici(ind,cursor); insereaza(line); add_stack(undo,line); } else { add_stack_indici(ind,cursor); if(read_command(line,0)!=5) add_stack(undo,line); } } return 0; } void initL(ListaNode **list) { // initializarea unui nod de tip lista (*list) = malloc(sizeof(ListaNode)); (*list)->anterior = NULL; (*list)->urmator = NULL; (*list)->linie.len=0; (*list)->linie.head=NULL; (*list)->linie.tail=NULL; } void initListaLista(ListaLista **lis) { // initializarea unei liste de liste (*lis) = malloc(sizeof(ListaLista)); (*lis)->cap = NULL; (*lis)->coada = NULL; (*lis)->nrlin=0; } void insertChar(ListaNode *list,char c,int p) { // cand p=0 inseram inainte de caracterul 1 // cand p=1 inseram dupa caracterul 1 int contor=1; list->linie.len++; node *nou,*inainte,*inapoi; nou=(node*)malloc(sizeof(node)); nou->data=c; nou->next=NULL; nou->prev=NULL; if(list->linie.head==NULL) { // daca lista pe care inseram este goala list->linie.head=nou; list->linie.tail=nou; return; } else if(cursor.y<=1 && p==0) { // inserare la inceputul liniei list->linie.head->prev=nou; nou->next=list->linie.head; list->linie.head=nou; return; } else if(cursor.y==list->linie.len || cursor.y==list->linie.len-1) { // inserare la sfarsitul listei list->linie.tail->next=nou; nou->prev=list->linie.tail; list->linie.tail=nou; } else { // inserare la mijloc inapoi=list->linie.head; inainte=list->linie.head->next; while(inapoi!=NULL && contor<cursor.y) { inapoi=inapoi->next; inainte=inainte->next; ++contor; } if(cursor.y==contor) { nou->next=inapoi->next; nou->prev=inapoi; inapoi->next=nou; inainte->prev=nou; } } } void insereaza(char line[]) { node *nou; char w[100]; int n=strlen(line),i,contor=0; if(line[n-1]=='\n') { line[n-1]='\0'; n--; } ListaNode *newLine,*inapoi; if(lis->nrlin==0) { //lista de liste e goala initL(&newLine); lis->cap=newLine; lis->coada=newLine; lis->nrlin++; } else if(cursor.x>lis->nrlin) { //adaugare linie la final initL(&newLine); lis->coada->urmator=newLine; newLine->anterior=lis->coada; lis->coada=newLine; lis->nrlin++; } else { // adaugare linie la mijloc inapoi=lis->cap; while(contor<cursor.x-1) { inapoi=inapoi->urmator; ++contor; } if(cursor.x-1==contor && middleInsert>0) { // se insereaza rand nou la mijloc doar daca se insereaza cel putin 2 randuri initL(&newLine); newLine->urmator=inapoi; newLine->anterior=inapoi->anterior; inapoi->anterior->urmator=newLine; inapoi->anterior=newLine; lis->nrlin++; } } if(cursor.y==1 && (cursor.x>=lis->nrlin || middleInsert>0)) { // inserarea de caracter cu caracter pe randul nou inserat for(i=0; i<n; i++) { insertChar(newLine,line[i],0); cursor.y++; } cursor.x++; cursor.y=1; if(middleInsert>0) { // pentru cazul in care se insereaza cel putin 2 randuri // la mijlocul listei middleInsert++; deleteMoreChars(cate,cc,0); cate=0; } } else { for(i=n-1; i>=0; i--) { // se insereaza caracterele in ordine inversa // pe prima pozitie din linie insertChar(inapoi,line[i],(int)text_mode); } middleInsert++; cursor.y=cursor.y+n+1; nou=inapoi->linie.head; contor=1; while(contor<=cursor.y-1) { nou=nou->next; contor++; } n=inapoi->linie.len; for(i=cursor.y; i<=n; i++) { // pentru situatia in care se insereaza mai multe randuri la mijloc // in vectorul w se insereaza caracterele de dupa primul rand inserat la mijloc w[i-cursor.y]=nou->data; nou=nou->next; } w[n-cursor.y+1]='\0'; add_stack(strings,w); cate=inapoi->linie.len-cursor.y+1; cc=cursor; cursor.x++; cursor.y=1; } } void print_line(ListaNode *list) { node *nou2=list->linie.head; while(nou2!=NULL) { fprintf(output,"%c",nou2->data); nou2=nou2->next; } fprintf(output,"\n"); } void print_ListaLista() { int contor=0; ListaNode *nou=lis->cap; while(contor<lis->nrlin) { print_line(nou); nou=nou->urmator; contor++; } } int read_command(char line[],int k) { char com[3]; com[0]=line[0]; com[1]=line[1]; com[2]='\0'; if(!strcmp(com,"u\n") && k==0) { pop_stack_indici(ind); undoAction(); return 5; } else if(!strcmp(com,"r\n") && k==0) { redoAction(); return 5; } else if(!strcmp(com,"s\n")) saveList(); else if(!strcmp(com,"q\n")) return 1; else if(!strcmp(com,"b\n")) { if(k) return 1; if(cursor.x>lis->nrlin) { cursor.x--; cursor.y=lis->coada->linie.len; } // Dupa inserare, cursorul meu se muta pe linia urmatoare. deleteMoreChars(1,cursor,1); cursor.y--; } else if(!strcmp(com,"dl")) { if(k) return 1; dl(line); } else if(!strcmp(com,"gl")) { if(k) return 1; gl(line); } else if(!strcmp(com,"gc")) { if(k) return 1; gc(line); } else if(!strcmp(com,"d ") || !strcmp(com,"d\n")) { if(k) return 1; if(line[2]>='0' && line[2]<='9') deleteMoreChars((int)line[2]-'0',cursor,0); else deleteMoreChars(1,cursor,0); } else if(!strcmp(com,"re")) { add_stack(undo,line); ra(line+3,1); return 5; } else if(!strcmp(com,"ra")) { add_stack(undo,line); ra(line+3,0); return 5; } else if(!strcmp(com,"dw")) da(line+3,1); else if(!strcmp(com,"da")) da(line+3,0); return 0; } void gl(char line[]) { cursor.x=(int)(line[3]-'0'); cursor.y=0; } void gc(char line[]) { cursor.y=(int)(line[3]-'0'); if(line[5]>='0' && line[5]<='9') cursor.x=(int)(line[5]-'0'); } void dl(char line[]) { int n; if(line[3]>='0' && line[3]<='9') n=(int)(line[3]-'0'); else n=cursor.x; deleteLine(n); } int min(int a,int b) { if(a<b) return a; return b; } void deleteChar(pozitie cursor,int p) { // p=0 stergem dupa cursor, p=1 stergem inainte de cursor int contor=1; ListaNode *precedent; node *nou,*nou2; if(cursor.x==1) precedent=lis->cap; else if(cursor.x>=lis->nrlin) precedent=lis->coada; else { precedent=lis->cap; while(precedent!=NULL && contor<cursor.x) { precedent=precedent->urmator; contor++; } } contor=1; nou=precedent->linie.head; if(precedent->linie.len==1) { //free(nou); precedent->linie.len--; deleteLine(cursor.x); return; } if(cursor.y<=1) { if(p==0 && cursor.y==1) { nou2=nou->next; add_stack_char(chars,nou2->data); if(precedent->linie.len>2) nou->next->next->prev=nou; nou->next=nou->next->next; free(nou2); precedent->linie.len--; if(precedent->linie.len==1) precedent->linie.tail->data=precedent->linie.head->data; return; } nou2=nou; add_stack_char(chars,nou2->data); nou=nou->next; nou->prev=NULL; precedent->linie.head=nou; precedent->linie.len--; if(precedent->linie.len==1) precedent->linie.tail->data=precedent->linie.head->data; free(nou2); return; } else if(cursor.y>=precedent->linie.len || (p==0 && cursor.y>=precedent->linie.len-1)) { nou2=precedent->linie.tail; add_stack_char(chars,nou2->data); precedent->linie.tail->prev->next=NULL; precedent->linie.tail=precedent->linie.tail->prev; free(nou2); } else { while(nou!=NULL && contor<cursor.y-1) { nou=nou->next; contor++; } if(p==0) nou=nou->next; nou2=nou->next; add_stack_char(chars,nou2->data); nou->next->next->prev=nou; nou->next=nou->next->next; free(nou2); } precedent->linie.len--; if(precedent->linie.len==1) precedent->linie.tail->data=precedent->linie.head->data; } void deleteLine(int n) { node *nou2; ListaNode *precedent=lis->cap,*nou; int contor=1,contor2=1; if(n==1) { nou=lis->cap; nou2=lis->cap->linie.head; do { contor2++; nou2=lis->cap->linie.head; lis->cap->linie.head=lis->cap->linie.head->next; free(nou2); }while(contor2<=lis->cap->linie.len); lis->cap->urmator->anterior=NULL; lis->cap=lis->cap->urmator; lis->nrlin--; free(nou); } else if(n>=lis->nrlin) { nou=lis->coada; nou2=lis->coada->linie.head; do { contor2++; nou2=lis->coada->linie.head; lis->coada->linie.head=lis->coada->linie.head->next; free(nou2); }while(contor2<=lis->coada->linie.len); lis->coada->anterior->urmator=NULL; lis->coada=lis->coada->anterior; lis->nrlin--; free(nou); } else { while(precedent!=NULL && contor<n-1) { precedent=precedent->urmator; contor++; } nou=precedent->urmator; nou2=precedent->urmator->linie.head; do { contor2++; nou2=precedent->urmator->linie.head; precedent->urmator->linie.head=precedent->urmator->linie.head->next; free(nou2); }while(contor2<=precedent->urmator->linie.len); precedent->urmator->urmator->anterior=precedent; precedent->urmator=precedent->urmator->urmator; lis->nrlin--; free(nou); } } void deleteMoreChars(int n,pozitie cursor,int p) { int i; for(i=0; i<n; i++) { deleteChar(cursor,p); if(p) cursor.y--; } } void initS(stiva **s) { (*s) = malloc(sizeof(stiva)); (*s)->top=NULL; (*s)->len=0; } void add_stack(stiva *s, char sir[]) { nodeSt *p; p=(nodeSt*)malloc(sizeof(nodeSt)); strcpy(p->sir,sir); s->len++; p->next=s->top; s->top=p; } void pop_stack(stiva *s) { char valoare[LMAX]; nodeSt *p; p=s->top; strcpy(valoare,p->sir); s->top=s->top->next; free(p); s->len--; } void initSI(stivaIndici **s) { (*s) = malloc(sizeof(stivaIndici)); (*s)->top=NULL; (*s)->len=0; } void add_stack_indici(stivaIndici *s, pozitie data) { nodeIndici *nou; nou=(nodeIndici*)malloc(sizeof(nodeIndici)); nou->val=data; s->len++; nou->next=s->top; s->top=nou; } void add_stack_char(stivaIndici *s, char data) { nodeIndici *nou; nou=(nodeIndici*)malloc(sizeof(nodeIndici)); nou->c=data; s->len++; nou->next=s->top; s->top=nou; } pozitie pop_stack_indici(stivaIndici *s) { pozitie valoare; nodeIndici *p; p=s->top; valoare=p->val; s->top=s->top->next; free(p); s->len--; return valoare; } void undoAction() { pozitie copieCursor,copieCursor2; int n,i,contor,nrranduri; ListaNode *inapoi; char p[LMAX]; cursor=ind->top->val; strcpy(p,undo->top->sir); add_stack(redo,p); if(strstr(p,"::i")!=NULL)// undo de text { add_stack(redo,undo->top->sir); pop_stack(undo); strcpy(p,undo->top->sir); nrranduri=0; while(strstr(undo->top->sir,"::i")==NULL) { ++nrranduri; cursor=ind->top->val; n=strlen(p); if(cursor.y==1) cursor.y=0; deleteMoreChars(n,cursor,0); pop_stack_indici(ind); if(cursor.y==0) cursor.y=1; add_stack(redo,p); add_stack_indici(indredo,cursor); pop_stack(undo); strcpy(p,undo->top->sir); } if(cursor.x<lis->nrlin && nrranduri>1) { inapoi=lis->cap; contor=1; while(contor<cursor.x) { inapoi=inapoi->urmator; contor++; } strcpy(p,strings->top->sir); for(i=0; i<strlen(p); i++) { insertChar(inapoi,p[i],1); cursor.y++; } pop_stack(strings); } add_stack(redo,undo->top->sir); } else { add_stack_indici(indredo,cursor); if(strstr(p,"d ")!=NULL || strstr(p,"d\n")!=NULL) { { if(p[2]=='\0') n=1; else n=(int)(p[2]-'0'); contor=1; inapoi=lis->cap; while(inapoi!=NULL && contor<cursor.x) { inapoi=inapoi->urmator; ++contor; } } for(i=1; i<=n; i++) { insertChar(inapoi,chars->top->c,0); pop_stack_indici(chars); } } else if(strstr(p,"ra ")!=NULL) { char *w1,*w2,line[LMAX]; w2=strtok(p," \n"); w2=strtok(NULL," \n"); w1=w2; w2=strtok(NULL," \n"); strcpy(line,w2); strcat(line," "); strcat(line,w1); ra(line,0); } else if(strstr(p,"re ")!=NULL) { char *w1,*w2,line[LMAX]; w2=strtok(p," \n"); w2=strtok(NULL," \n"); w1=w2; w2=strtok(NULL," \n"); strcpy(line,w2); strcat(line," "); strcat(line,w1); ra(line,1); } else if(strstr(p,"dw ")!=NULL || strstr(p,"da ")!=NULL) { char line[LMAX],*w1; w1=strtok(p," \n"); w1=strtok(NULL," \n"); strcpy(line,w1); copieCursor=cursor; n=strlen(line); while(dw_pos->top->val.x!=semn.x || dw_pos->top->val.y!=semn.y) { int contor=1; cursor=dw_pos->top->val; pop_stack_indici(dw_pos); ListaNode *precedent=lis->cap; if(cursor.x>=lis->nrlin) precedent=lis->coada; else while(precedent!=NULL && contor<cursor.x) { precedent=precedent->urmator; contor++; } insertChar(precedent,line[0],0); copieCursor2=cursor; for(i=1; i<n; i++) { cursor.y++; insertChar(precedent,line[i],1); } cursor=copieCursor2; } cursor=copieCursor; } else if(strstr(p,"gc")!=NULL || strstr(p,"gl")!=NULL) { cursor=ind->top->val; } } pop_stack(undo); pop_stack_indici(ind); } void redoAction() { char p[LMAX]; add_stack_indici(ind,cursor);//adaugam in stiva de undo cursor=indredo->top->val; strcpy(p,redo->top->sir); add_stack(undo,p); if(strstr(p,"::i")!=NULL)// undo de text { add_stack(undo,redo->top->sir); pop_stack(redo); strcpy(p,redo->top->sir); while(strstr(p,"::i")==NULL) { insereaza(p); add_stack(undo,p); pop_stack(redo); strcpy(p,redo->top->sir); } add_stack_indici(ind,cursor); } else { read_command(p,0); add_stack(undo,p); } pop_stack(redo); pop_stack_indici(indredo); } void freee() { int contor=1,contor2; ListaNode *nou=lis->cap; node *nou2; while(contor<lis->nrlin) { nou=lis->cap; nou2=nou->linie.head; contor2=1; while(contor2<nou->linie.len) { nou2=nou->linie.head; nou->linie.head=nou->linie.head->next; free(nou2); contor2++; } //nou2=nou->linie.head; //free(nou2); free(nou); lis->cap=lis->cap->urmator; contor++; } nou=lis->cap; nou2=nou->linie.head; contor2=1; while(contor2<nou->linie.len) { nou2=nou->linie.head; nou->linie.head=nou->linie.head->next; free(nou2); contor2++; } free(nou2); free(nou); free(lis); } void freeStack(stiva **s) { nodeSt *p=(*s)->top; int contor=1; while(contor<(*s)->len) { p=(*s)->top; (*s)->top=(*s)->top->next; free(p); contor++; } p=(*s)->top; free(p); free(*s); } void freeStackIND(stivaIndici **s) { nodeIndici *p=(*s)->top; int contor=1; if((*s)->len<=0) { free(*s); return; } while(contor<(*s)->len) { p=(*s)->top; (*s)->top=(*s)->top->next; free(p); contor++; } p=(*s)->top; free(p); free(*s); } void saveList() { output=fopen("editor.out","w"); print_ListaLista(); fclose(output); } void da(char line[],int k) { int ok=0; if(cursor.y==0) { ok=1; cursor.y=1; } ListaNode *precedent=lis->cap; TDoubleLinkedList T; node *nou; int contor=1,n,contor2=1,i; n=strlen(line); if(line[n-1]=='\n') { line[n-1]='\0'; --n; } add_stack_indici(dw_pos,semn); pozitie copieCursor=cursor,cc3; if(copieCursor.x>=lis->nrlin) precedent=lis->coada; else while(precedent!=NULL && contor<copieCursor.x) { precedent=precedent->urmator; contor++; } T=precedent->linie; nou=T.head; if(copieCursor.y>=T.len) nou=T.tail; else while(nou!=NULL && contor2<copieCursor.y) { nou=nou->next; contor2++; } while(copieCursor.x<=lis->nrlin) { while(copieCursor.y<=T.len-n+1) { if(line[0]==nou->data) { nou=nou->next; copieCursor.y++; for(i=1; i<n; i++) { if(line[i]!=nou->data) break; nou=nou->next; copieCursor.y++; } if(i==n) { copieCursor.y--; cc3=copieCursor; cc3.y-=n; add_stack_indici(dw_pos,cc3); if(T.len==1) deleteMoreChars(n,copieCursor,0); else deleteMoreChars(n,copieCursor,1); if(k==1) { cursor.y-=ok; return; } T.len=precedent->linie.len; copieCursor.y=copieCursor.y-n+1; if(T.len<=0) copieCursor.x--; } } else { copieCursor.y++; nou=nou->next; continue; } } copieCursor.x++; copieCursor.y=1; if(precedent==lis->coada) break; precedent=precedent->urmator; T=precedent->linie; nou=T.head; } copieCursor.x=1; copieCursor.y=1; precedent=lis->cap; T=precedent->linie; nou=T.head; while(copieCursor.x<cursor.x) { while(copieCursor.y<=T.len-n+1) { if(line[0]==nou->data) { nou=nou->next; copieCursor.y++; for(i=1; i<n; i++) { if(line[i]!=nou->data) break; nou=nou->next; copieCursor.y++; } if(i==n) { copieCursor.y--; cc3=copieCursor; cc3.y-=n; add_stack_indici(dw_pos,cc3); if(T.len==1) deleteMoreChars(n,copieCursor,0); else deleteMoreChars(n,copieCursor,1); if(k==1) { cursor.y-=ok; return; } T.len=precedent->linie.len; copieCursor.y=copieCursor.y-n+1; if(T.len<=0) copieCursor.x--; } } else { copieCursor.y++; nou=nou->next; continue; } } copieCursor.x++; copieCursor.y=1; precedent=precedent->urmator; T=precedent->linie; nou=T.head; } cursor.y+=ok; } void ra(char line[],int k) { if(cursor.y==0) cursor.y=1; char *w1,*w2; w2=strtok(line," \n"); w1=w2; w2=strtok(NULL," \n"); ListaNode *precedent=lis->cap; TDoubleLinkedList T; node *nou,*nou2; int contor=1,n1,n2,contor2=1,i,j; n1=strlen(w1); n2=strlen(w2); pozitie copieCursor=cursor,copieCursor2,cc3; if(copieCursor.x>=lis->nrlin) precedent=lis->coada; else while(precedent!=NULL && contor<copieCursor.x) { precedent=precedent->urmator; contor++; } T=precedent->linie; nou=T.head; if(copieCursor.y>=T.len) nou=T.tail; else while(nou!=NULL && contor2<copieCursor.y) { nou=nou->next; contor2++; } while(copieCursor.x<=lis->nrlin) { while(copieCursor.y<=T.len-n1+1) { if(w1[0]==nou->data) { copieCursor2=copieCursor;//retinem pozitia de plecare copieCursor.y++; nou2=nou; nou=nou->next; for(i=1; i<n1; i++) { if(w1[i]!=nou->data) break; nou=nou->next; copieCursor.y++;//o sa ajunga pe pozitia copiecursor2.y+n1 } if(i==n1)//am ajuns la finalul sirului { for(j=1; j<=min(n1,n2); j++) { nou2->data=w2[j-1]; nou2=nou2->next; copieCursor2.y++; } cc3=cursor; if(n1>n2) { copieCursor.y--; deleteMoreChars(n1-n2,copieCursor,1); cursor=cc3; } else if(n1<n2) { cursor.x=copieCursor2.x; cursor.y=copieCursor2.y-1; for(; j<=n2; j++) insertChar(precedent,w2[j-1],0); cursor=cc3; copieCursor.y=copieCursor.y+n2-n1; } if(k==1) return; } T.len=T.len+n2-n1; } else { copieCursor.y++; nou=nou->next; continue; } } copieCursor.x++; copieCursor.y=1; if(precedent==lis->coada) break; precedent=precedent->urmator; T=precedent->linie; nou=T.head; } copieCursor.x=1; copieCursor.y=1; precedent=lis->cap; T=precedent->linie; nou=T.head; while(copieCursor.x<cursor.x) { while(copieCursor.y<=T.len-n1+1) { if(w1[0]==nou->data) { copieCursor2=copieCursor;//retinem pozitia de plecare copieCursor.y++; nou2=nou; nou=nou->next; for(i=1; i<n1; i++) { if(w1[i]!=nou->data) break; nou=nou->next; copieCursor.y++;//o sa ajunga pe pozitia copiecursor2.y+n1 } if(i==n1)//am ajuns la finalul sirului { for(j=1; j<=min(n1,n2); j++) { nou2->data=w2[j-1]; nou2=nou2->next; copieCursor2.y++; } cc3=cursor; if(n1>n2) { copieCursor.y--; deleteMoreChars(n1-n2,copieCursor,1); cursor=cc3; } else if(n1<n2) { cursor.x=copieCursor2.x; cursor.y=copieCursor2.y-1; insereaza(w2+j-1); cursor=cc3; copieCursor.y=copieCursor.y+n2-n1; } if(k==1) return; } T.len=T.len+n2-n1; } else { copieCursor.y++; nou=nou->next; continue; } } copieCursor.x++; copieCursor.y=1; if(precedent==lis->coada) break; precedent=precedent->urmator; T=precedent->linie; nou=T.head; } }
koreadragon/fuckpods
fuckpods/fuckpods/fuckpods/fuck.h
<reponame>koreadragon/fuckpods // // fuck.h // fuckpods // // Created by koreadragon on 2020/5/28. // Copyright © 2020 cytx. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface fuck : NSObject +(void)printVersion; @end NS_ASSUME_NONNULL_END
MartinWeindel/differential-datalog
rust/template/ddlog_ovsdb_test.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "ddlog.h" int main(int args, char *argv) { ddlog_prog prog = ddlog_run(1, true, NULL, 0); if (prog == NULL) { fprintf(stderr, "failed to initialize DDlog program\n"); return -1; }; // Each line in the input stream is a JSON <table-updates> value. while(true) { char *lineptr = NULL; size_t n = 0; if (getline(&lineptr, &n, stdin) < 0) { // eof break; } //printf("updates: %s\n", lineptr); // start transaction if (ddlog_transaction_start(prog) < 0) { fprintf(stderr, "failed to start transaction\n"); return -1; }; // apply updates if (ddlog_apply_ovsdb_updates(prog, "", lineptr) < 0) { fprintf(stderr, "failed to apply updates (%s)\n", lineptr); return -1; }; free(lineptr); // commit if (ddlog_transaction_commit(prog) < 0) { fprintf(stderr, "failed to commit transaction\n"); return -1; }; } if (ddlog_stop(prog) < 0) { fprintf(stderr, "failed to stop DDlog program\n"); return -1; } return 0; }
MartinWeindel/differential-datalog
lib/ddlog_log.h
/* * C prototypes for the logging API (see `log.dl`, `log.rs`) */ /* * Set logging callback and log level for a given module. * * `module` - Opaque module identifier. Can represent module, subsystem, log * stream, etc. * `cb` - Callback to be invoked for each log message with the given module * id and log level `<= max_level`. Passing `NULL` disables * logging for the given module. * `max_level` - Don't invoke the callback for messages whose log level is * `> max_level`. */ extern void ddlog_log_set_callback( int module, void (*cb)(uintptr_t arg, int level, const char* msg), uintptr_t cb_arg, int max_level); /* * Set default callback and log level for modules that were not configured * via `ddlog_log_set_callback`. * * `cb` - Callback to be invoked for each log message with level `<= max_level`. * Passing `NULL` disables logging by default. * `max_level` - Don't invoke the callback for messages whose log level is * `> max_level`. */ extern void ddlog_log_set_default_callback( void (*cb)(uintptr_t arg, int level, const char* msg), uintptr_t cb_arg, int max_level);
xnox/shim
include/test.h
// SPDX-License-Identifier: BSD-2-Clause-Patent /* * test.h - fake a bunch of EFI types so we can build test harnesses with libc * Copyright <NAME> <<EMAIL>> */ #ifdef SHIM_UNIT_TEST #ifndef TEST_H_ #define TEST_H_ #include <stdarg.h> #if defined(__aarch64__) #include <aa64/efibind.h> #elif defined(__arm__) #include <arm/efibind.h> #elif defined(__i386__) || defined(__i486__) || defined(__i686__) #include <ia32/efibind.h> #elif defined(__x86_64__) #include <x64/efibind.h> #else #error what arch is this #endif #include <efidef.h> #include <efidevp.h> #include <efiprot.h> #include <eficon.h> #include <efiapi.h> #include <efierr.h> #include <efipxebc.h> #include <efinet.h> #include <efiip.h> #include <stdlib.h> #define ZeroMem(buf, sz) memset(buf, 0, sz) #define SetMem(buf, sz, value) memset(buf, value, sz) #define CopyMem(dest, src, len) memcpy(dest, src, len) #define CompareMem(dest, src, len) memcmp(dest, src, len) #include <assert.h> #define AllocateZeroPool(x) calloc(1, (x)) #define AllocatePool(x) malloc(x) #define FreePool(x) free(x) #define ReallocatePool(old, oldsz, newsz) realloc(old, newsz) extern int debug; #ifdef dprint #undef dprint #define dprint(fmt, ...) {( if (debug) printf("%s:%d:" fmt, __func__, __LINE__, ##__VA_ARGS__); }) #endif #define eassert(cond, fmt, ...) \ ({ \ if (!(cond)) { \ printf("%s:%d:" fmt, __func__, __LINE__, \ ##__VA_ARGS__); \ } \ assert(cond); \ }) #define assert_equal_return(a, b, status, fmt, ...) \ ({ \ if (!((a) == (b))) { \ printf("%s:%d:" fmt, __func__, __LINE__, (a), (b), \ ##__VA_ARGS__); \ printf("%s:%d:Assertion `%s' failed.\n", __func__, \ __LINE__, __stringify(a == b)); \ return status; \ } \ }) #define assert_return(cond, status, fmt, ...) \ ({ \ if (!(cond)) { \ printf("%s:%d:" fmt, __func__, __LINE__, \ ##__VA_ARGS__); \ printf("%s:%d:Assertion `%s' failed.\n", __func__, \ __LINE__, __stringify(cond)); \ return status; \ } \ }) #define assert_goto(cond, label, fmt, ...) \ ({ \ if (!(cond)) { \ printf("%s:%d:" fmt, __func__, __LINE__, \ ##__VA_ARGS__); \ printf("%s:%d:Assertion `%s' failed.\n", __func__, \ __LINE__, __stringify(cond)); \ goto label; \ } \ }) #define assert_equal_goto(a, b, label, fmt, ...) \ ({ \ if (!((a) == (b))) { \ printf("%s:%d:" fmt, __func__, __LINE__, (a), (b), \ ##__VA_ARGS__); \ printf("%s:%d:Assertion `%s' failed.\n", __func__, \ __LINE__, __stringify(a == b)); \ goto label; \ } \ }) #define test(x, ...) \ ({ \ int rc; \ printf("running %s\n", __stringify(x)); \ rc = x(__VA_ARGS__); \ if (rc < 0) \ status = 1; \ printf("%s: %s\n", __stringify(x), \ rc < 0 ? "failed" : "passed"); \ }) #endif /* !TEST_H_ */ #endif /* SHIM_UNIT_TEST */ // vim:fenc=utf-8:tw=75:noet
xnox/shim
test-sbat.c
// SPDX-License-Identifier: BSD-2-Clause-Patent /* * test-sbat.c - test our sbat functions. */ #ifndef SHIM_UNIT_TEST #define SHIM_UNIT_TEST #endif #include "shim.h" #include <stdio.h> #define MAX_SIZE 512 list_t sbat_var; #if 0 /* * Mock test helpers */ static struct sbat_entry * create_mock_sbat_entry(const char* comp_name, const char* comp_gen, const char* vend_name, const char* vend_pkg_name, const char* vend_ver, const char* vend_url) { struct sbat_entry *new_entry = AllocatePool(sizeof(*new_entry)); if (!new_entry) return NULL; new_entry->component_name = comp_name; new_entry->component_generation = comp_gen; new_entry->vendor_name = vend_name; new_entry->vendor_package_name = vend_pkg_name; new_entry->vendor_version = vend_ver; new_entry->vendor_url = vend_url; return new_entry; } void free_mock_sbat_entry(struct sbat_entry *entry) { if (entry) FreePool(entry); } static struct sbat * create_mock_sbat_one_entry(char* comp_name, char* comp_gen, char* vend_name, char* vend_pkg_name, char* vend_ver, char* vend_url) { struct sbat *new_entry = AllocatePool(sizeof(*new_entry)); if (!new_entry) return NULL; struct sbat_entry *test_entry; struct sbat_entry **entries = AllocatePool(sizeof(*entries)); if (!entries) return NULL; test_entry = create_mock_sbat_entry(comp_name, comp_gen, vend_name, vend_pkg_name, vend_ver, vend_url); if (!test_entry) return NULL; entries[0] = test_entry; new_entry->size = 1; new_entry->entries = entries; return new_entry; } static struct sbat * create_mock_sbat_multiple_entries(struct sbat_entry *entry_array, size_t num_elem) { unsigned int i; struct sbat *new_entry = AllocatePool(sizeof(*new_entry)); if (!new_entry) return NULL; struct sbat_entry *test_entry; struct sbat_entry **entries = AllocatePool(num_elem * sizeof(*entries)); if (!entries) return NULL; for (i = 0; i < num_elem; i++) { test_entry = create_mock_sbat_entry(entry_array[i].component_name, entry_array[i].component_generation, entry_array[i].vendor_name, entry_array[i].vendor_package_name, entry_array[i].vendor_version, entry_array[i].vendor_url); if (!test_entry) return NULL; entries[i] = test_entry; } new_entry->size = num_elem; new_entry->entries = entries; return new_entry; } void free_mock_sbat(struct sbat *sbat) { unsigned int i; if (sbat) { for (i = 0; i < sbat->size; i++) { if (sbat->entries[i]) { FreePool(sbat->entries[i]); } } FreePool(sbat); } } static struct sbat_var * create_mock_sbat_var_entry(const char* comp_name, const char* comp_gen) { struct sbat_var *new_entry = AllocatePool(sizeof(*new_entry)); if (!new_entry) return NULL; INIT_LIST_HEAD(&new_entry->list); int comp_name_size = strlen(comp_name) + 1; CHAR8 *alloc_comp_name = AllocatePool(comp_name_size * sizeof(*alloc_comp_name)); if (!alloc_comp_name) return NULL; int comp_gen_size = strlen(comp_gen) + 1; CHAR8 *alloc_comp_gen = AllocatePool(comp_gen_size * sizeof(*alloc_comp_gen)); if (!alloc_comp_gen) return NULL; CopyMem(alloc_comp_name, comp_name, comp_name_size); CopyMem(alloc_comp_gen, comp_gen, comp_gen_size); new_entry->component_name = alloc_comp_name; new_entry->component_generation = alloc_comp_gen; return new_entry; } static list_t * create_mock_sbat_entries_one_entry(char* name, char* gen) { list_t *test_sbat_entries = AllocatePool(sizeof(*test_sbat_entries)); if (!test_sbat_entries) return NULL; INIT_LIST_HEAD(test_sbat_entries); struct sbat_var *test_entry; test_entry = create_mock_sbat_var_entry(name, gen); if (!test_entry) return NULL; list_add(&test_entry->list, test_sbat_entries); return test_sbat_entries; } static list_t * create_mock_sbat_entries_multiple_entries(struct sbat_var *var_array, size_t num_elem) { unsigned int i; list_t *test_sbat_entries = AllocatePool(sizeof(*test_sbat_entries)); if (!test_sbat_entries) return NULL; INIT_LIST_HEAD(test_sbat_entries); struct sbat_var *test_entry; for (i = 0; i < num_elem; i++) { test_entry = create_mock_sbat_var_entry(var_array[i].component_name, var_array[i].component_generation); if (!test_entry) return NULL; list_add(&test_entry->list, test_sbat_entries); } return test_sbat_entries; } void free_mock_sbat_entries(list_t *entries) { list_t *pos = NULL; list_t *n = NULL; struct sbat_var *entry; if (entries) { list_for_each_safe(pos, n, entries) { entry = list_entry(pos, struct sbat_var, list); list_del(&entry->list); if (entry->component_name) FreePool((CHAR8 *)entry->component_name); if (entry->component_generation) FreePool((CHAR8 *)entry->component_generation); FreePool(entry); } FreePool(entries); } } #endif /* * parse_sbat_section() tests */ int test_parse_sbat_section_null_sbat_base(void) { char *section_base = NULL; size_t section_size = 20; struct sbat_section_entry **entries; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, &entries); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_zero_sbat_size(void) { char section_base[] = "test1,1,SBAT test1,acme,1,testURL\n"; size_t section_size = 0; struct sbat_section_entry **entries; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, &entries); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_null_entries(void) { char section_base[] = "test1,1,SBAT test1,acme,1,testURL\n"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, NULL); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_null_count(void) { char section_base[] = "test1,1,SBAT test1,acme,1,testURL\n"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; struct sbat_section_entry **entries; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, NULL, &entries); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_no_newline(void) { char section_base[] = "test1,1,SBAT test1,acme,1,testURL"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; struct sbat_section_entry **entries; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, &entries); cleanup_sbat_section_entries(n, entries); assert_equal_return(status, EFI_SUCCESS, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_no_commas(void) { char section_base[] = "test1"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; struct sbat_section_entry **entries; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, &entries); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_too_few_elem(void) { char section_base[] = "test1,1,acme"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; struct sbat_section_entry **entries; size_t n = 0; EFI_STATUS status; status = parse_sbat_section(section_base, section_size, &n, &entries); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_section_too_many_elem(void) { char section_base[] = "test1,1,SBAT test1,acme1,1,testURL1,other1,stuff,is,here\n" "test2,2,SBAT test2,acme2,2,testURL2,other2"; /* intentionally not NUL terminated */ size_t section_size = sizeof(section_base) - 1; struct sbat_section_entry **entries; size_t n = 0, i; list_t *pos = NULL; EFI_STATUS status; struct sbat_section_entry test_section_entry1 = { "test1", "1", "SBAT test1", "acme1", "1", "testURL1" }; struct sbat_section_entry test_section_entry2 = { "test2", "2", "SBAT test2", "acme2", "2", "testURL2" }; struct sbat_section_entry *test_entries[] = { &test_section_entry1, &test_section_entry2, }; status = parse_sbat_section(section_base, section_size, &n, &entries); assert_equal_return(status, EFI_SUCCESS, -1, "got %#hhx expected %#hhx\n"); for (i = 0; i < n; i++) { struct sbat_section_entry *entry = entries[i]; struct sbat_section_entry *test_entry = test_entries[i]; #define mkassert(a) \ assert_equal_goto(strcmp(entry-> a, test_entry-> a), 0, fail, \ "got %zu expected %d\n") mkassert(component_name); mkassert(component_generation); mkassert(vendor_name); mkassert(vendor_package_name); mkassert(vendor_version); mkassert(vendor_url); #undef mkassert } assert_equal_goto(n, 2, fail, "got %zu expected %d\n"); return 0; fail: cleanup_sbat_section_entries(n, entries); return -1; } /* * parse_sbat_var() tests */ int test_parse_sbat_var_null_list(void) { EFI_STATUS status; INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var(NULL); cleanup_sbat_var(&sbat_var); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_var_data_null_list(void) { char sbat_var_data[] = "test1,1,2021022400"; /* * intentionally including the NUL termination, because * get_variable() will always include it. */ size_t sbat_var_data_size = sizeof(sbat_var_data); EFI_STATUS status; INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var_data(NULL, sbat_var_data, sbat_var_data_size); cleanup_sbat_var(&sbat_var); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_var_data_null_data(void) { size_t sbat_var_data_size = 4; EFI_STATUS status; INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var_data(&sbat_var, NULL, sbat_var_data_size); cleanup_sbat_var(&sbat_var); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_var_data_zero_size(void) { char sbat_var_data[] = "test1,1,2021022400"; EFI_STATUS status; INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var_data(&sbat_var, sbat_var_data, 0); cleanup_sbat_var(&sbat_var); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_parse_sbat_var_data(void) { char sbat_var_data[] = "test1,1,2021022400"; EFI_STATUS status; INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var_data(&sbat_var, sbat_var_data, 0); assert_equal_return(status, EFI_INVALID_PARAMETER, -1, "got %#hhx expected %#hhx\n"); return 0; } #if 0 /* * verify_sbat() tests * Note: verify_sbat also frees the underlying "sbat_entries" memory. */ int test_verify_sbat_null_sbat(void) { list_t *test_sbat_entries; test_sbat_entries = create_mock_sbat_entries_one_entry("test1", "1"); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(NULL, test_sbat_entries); assert(status == EFI_INVALID_PARAMETER); return 0; } int test_verify_sbat_null_sbat_entries(void) { struct sbat *test_sbat; test_sbat = create_mock_sbat_one_entry("test1","1","SBAT test1", "acme","1","testURL"); if (!test_sbat) return -1; list_t sbat_entries; INIT_LIST_HEAD(&sbat_entries); EFI_STATUS status; status = verify_sbat(test_sbat, &sbat_entries); assert(status == EFI_INVALID_PARAMETER); free_mock_sbat(test_sbat); return 0; } int test_verify_sbat_match_one_exact(void) { struct sbat *test_sbat; struct sbat_entry sbat_entry_array[2]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, 2); if (!test_sbat) return -1; list_t *test_sbat_entries; test_sbat_entries = create_mock_sbat_entries_one_entry("test1", "1"); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_match_one_higher(void) { struct sbat *test_sbat; struct sbat_entry sbat_entry_array[2]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, 2); if (!test_sbat) return -1; list_t *test_sbat_entries; test_sbat_entries = create_mock_sbat_entries_one_entry("test2", "1"); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_reject_one(void) { struct sbat *test_sbat; struct sbat_entry sbat_entry_array[2]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, 2); if (!test_sbat) return -1; list_t *test_sbat_entries; test_sbat_entries = create_mock_sbat_entries_one_entry("test2", "3"); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SECURITY_VIOLATION); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_reject_many(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "1"; sbat_var_array[1].component_name = "test2"; sbat_var_array[1].component_generation = "3"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SECURITY_VIOLATION); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_match_many_higher(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "3"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "5"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "1"; sbat_var_array[1].component_name = "test2"; sbat_var_array[1].component_generation = "2"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_match_many_exact(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "1"; sbat_var_array[1].component_name = "test2"; sbat_var_array[1].component_generation = "2"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_reject_many_all(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "3"; sbat_var_array[1].component_name = "test2"; sbat_var_array[1].component_generation = "5"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SECURITY_VIOLATION); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_match_diff_name(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "foo"; sbat_var_array[0].component_generation = "5"; sbat_var_array[1].component_name = "bar"; sbat_var_array[1].component_generation = "2"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_match_diff_name_mixed(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "1"; sbat_var_array[1].component_name = "bar"; sbat_var_array[1].component_generation = "2"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SUCCESS); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } int test_verify_sbat_reject_diff_name_mixed(void) { struct sbat *test_sbat; unsigned int sbat_entry_array_size = 2; struct sbat_entry sbat_entry_array[sbat_entry_array_size]; sbat_entry_array[0].component_name = "test1"; sbat_entry_array[0].component_generation = "1"; sbat_entry_array[0].vendor_name = "SBAT test1"; sbat_entry_array[0].vendor_package_name = "acme"; sbat_entry_array[0].vendor_version = "1"; sbat_entry_array[0].vendor_url = "testURL"; sbat_entry_array[1].component_name = "test2"; sbat_entry_array[1].component_generation = "2"; sbat_entry_array[1].vendor_name = "SBAT test2"; sbat_entry_array[1].vendor_package_name = "acme2"; sbat_entry_array[1].vendor_version = "2"; sbat_entry_array[1].vendor_url = "testURL2"; test_sbat = create_mock_sbat_multiple_entries(sbat_entry_array, sbat_entry_array_size); if (!test_sbat) return -1; list_t *test_sbat_entries; unsigned int sbat_var_array_size = 2; struct sbat_var sbat_var_array[sbat_var_array_size]; sbat_var_array[0].component_name = "test1"; sbat_var_array[0].component_generation = "5"; sbat_var_array[1].component_name = "bar"; sbat_var_array[1].component_generation = "2"; test_sbat_entries = create_mock_sbat_entries_multiple_entries(sbat_var_array, sbat_var_array_size); if (!test_sbat_entries) return -1; EFI_STATUS status; status = verify_sbat(test_sbat, test_sbat_entries); assert(status == EFI_SECURITY_VIOLATION); free_mock_sbat(test_sbat); free_mock_sbat_entries(test_sbat_entries); return 0; } #endif int test_parse_and_verify(void) { EFI_STATUS status; char sbat_section[] = "test1,1,SBAT test1,acme1,1,testURL1\n" "test2,2,SBAT test2,acme2,2,testURL2\n"; struct sbat_section_entry **section_entries = NULL; size_t n_section_entries = 0, i; struct sbat_section_entry test_section_entry1 = { "test1", "1", "SBAT test1", "acme1", "1", "testURL1" }; struct sbat_section_entry test_section_entry2 = { "test2", "2", "SBAT test2", "acme2", "2", "testURL2" }; struct sbat_section_entry *test_entries[] = { &test_section_entry1, &test_section_entry2, }; status = parse_sbat_section(sbat_section, sizeof(sbat_section)-1, &n_section_entries, &section_entries); eassert(status == EFI_SUCCESS, "expected %d got %d\n", EFI_SUCCESS, status); eassert(section_entries != NULL, "expected non-NULL got NULL\n"); for (i = 0; i < n_section_entries; i++) { struct sbat_section_entry *entry = section_entries[i]; struct sbat_section_entry *test_entry = test_entries[i]; #define mkassert(a) \ eassert(strcmp(entry-> a, test_entry-> a) == 0, \ "expected \"%s\" got \"%s\"\n", \ test_entry-> a, entry-> a ) mkassert(component_name); mkassert(component_generation); mkassert(vendor_name); mkassert(vendor_package_name); mkassert(vendor_version); mkassert(vendor_url); #undef mkassert } eassert(n_section_entries == 2, "expected %d got %d\n", 2, n_section_entries); char sbat_var_data[] = "test1,5\nbar,2\n"; size_t sbat_var_data_size = sizeof(sbat_var_data); char *sbat_var_alloced = calloc(1, sbat_var_data_size); if (!sbat_var_alloced) return -1; memcpy(sbat_var_alloced, sbat_var_data, sbat_var_data_size); INIT_LIST_HEAD(&sbat_var); status = parse_sbat_var_data(&sbat_var, sbat_var_alloced, sbat_var_data_size); if (status != EFI_SUCCESS || list_empty(&sbat_var)) return -1; status = verify_sbat(n_section_entries, section_entries); assert_equal_return(status, EFI_SECURITY_VIOLATION, -1, "expected %#x got %#x\n"); cleanup_sbat_var(&sbat_var); cleanup_sbat_section_entries(n_section_entries, section_entries); return 0; } int main(void) { int status = 0; // parse_sbat section tests test(test_parse_sbat_section_null_sbat_base); test(test_parse_sbat_section_zero_sbat_size); test(test_parse_sbat_section_null_entries); test(test_parse_sbat_section_null_count); test(test_parse_sbat_section_no_newline); test(test_parse_sbat_section_no_commas); test(test_parse_sbat_section_too_few_elem); test(test_parse_sbat_section_too_many_elem); // parse_sbat_var tests test(test_parse_sbat_var_null_list); test(test_parse_sbat_var_data_null_list); test(test_parse_sbat_var_data_null_data); test(test_parse_sbat_var_data_zero_size); #if 0 // verify_sbat tests //test_verify_sbat_null_sbat(); test_verify_sbat_null_sbat_entries(); test_verify_sbat_match_one_exact(); test_verify_sbat_match_one_higher(); test_verify_sbat_reject_one(); test_verify_sbat_reject_many(); test_verify_sbat_match_many_higher(); test_verify_sbat_match_many_exact(); test_verify_sbat_reject_many_all(); test_verify_sbat_match_diff_name(); test_verify_sbat_match_diff_name_mixed(); test_verify_sbat_reject_diff_name_mixed(); #endif test_parse_and_verify(); return 0; } // vim:fenc=utf-8:tw=75:noet
xnox/shim
include/str.h
<gh_stars>0 // SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef SHIM_STR_H #define SHIM_STR_H #ifdef SHIM_UNIT_TEST #pragma GCC diagnostic error "-Wnonnull-compare" #else #pragma GCC diagnostic ignored "-Wnonnull-compare" #endif static inline UNUSED NONNULL(1) unsigned long strnlena(const CHAR8 *s, unsigned long n) { unsigned long i; for (i = 0; i < n; i++) if (s[i] == '\0') break; return i; } static inline UNUSED RETURNS_NONNULL NONNULL(1, 2) CHAR8 * strncpya(CHAR8 *dest, const CHAR8 *src, unsigned long n) { unsigned long i; for (i = 0; i < n && src[i] != '\0'; i++) dest[i] = src[i]; for (; i < n; i++) dest[i] = '\0'; return dest; } static inline UNUSED RETURNS_NONNULL NONNULL(1, 2) CHAR8 * strcata(CHAR8 *dest, const CHAR8 *src) { unsigned long dest_len = strlena(dest); unsigned long i; for (i = 0; src[i] != '\0'; i++) dest[dest_len + i] = src[i]; dest[dest_len + i] = '\0'; return dest; } static inline UNUSED NONNULL(1) CHAR8 * strdup(const CHAR8 * const src) { UINTN len; CHAR8 *news = NULL; len = strlena(src); news = AllocateZeroPool(len + 1); if (news) strncpya(news, src, len); return news; } static inline UNUSED NONNULL(1) CHAR8 * strndupa(const CHAR8 * const src, const UINTN srcmax) { UINTN len; CHAR8 *news = NULL; len = strnlena(src, srcmax); news = AllocateZeroPool(len + 1); if (news) strncpya(news, src, len); return news; } static inline UNUSED RETURNS_NONNULL NONNULL(1, 2) char * stpcpy(char *dest, const char * const src) { size_t i = 0; for (i = 0; src[i]; i++) dest[i] = src[i]; dest[i] = '\000'; return &dest[i]; } static inline UNUSED CHAR8 * translate_slashes(CHAR8 *out, const char *str) { int i; int j; if (str == NULL || out == NULL) return NULL; for (i = 0, j = 0; str[i] != '\0'; i++, j++) { if (str[i] == '\\') { out[j] = '/'; if (str[i+1] == '\\') i++; } else out[j] = str[i]; } out[j] = '\0'; return out; } static inline UNUSED RETURNS_NONNULL NONNULL(1) CHAR8 * strchrnula(const CHAR8 *s, int c) { unsigned int i; for (i = 0; s[i] != '\000' && s[i] != c; i++) ; return (CHAR8 *)&s[i]; } static inline UNUSED NONNULL(1) CHAR8 * strchra(const CHAR8 *s, int c) { const CHAR8 *s1; s1 = strchrnula(s, c); if (!s1 || s1[0] == '\000') return NULL; return (CHAR8 *)s1; } static inline UNUSED RETURNS_NONNULL NONNULL(1) char * strnchrnul(const char *s, size_t max, int c) { unsigned int i; if (!s || !max) return (char *)s; for (i = 0; i < max && s[i] != '\0' && s[i] != c; i++) ; if (i == max) i--; return (char *)&s[i]; } /** * strntoken: tokenize a string, with a limit * str: your string (will be modified) * max: maximum number of bytes to ever touch * delims: string of one character delimeters, any of which will tokenize * *token: the token we're passing back (must be a pointer to NULL initially) * state: a pointer to one char of state for between calls * * Ensure that both token and state are preserved across calls. Do: * char state = 0; * char *token = NULL; * for (...) { * valid = strntoken(...) * not: * char state = 0; * for (...) { * char *token = NULL; * valid = strntoken(...) * * - it will not test bytes beyond str[max-1] * - it will not set *token to an address beyond &str[max-1] * - it will set *token to &str[max-1] without testing &str[max-2] for * &str[max-1] == str * - sequences of multiple delimeters will result in empty (pointer to '\0') * tokens. * - it expects you to update str and max on successive calls. * * return: * true means it hasn't tested str[max-1] yet and token is valid * false means it got to a NUL or str[max-1] and token is invalid */ static inline UNUSED NONNULL(1, 3, 4) int strntoken(char *str, size_t max, const char *delims, char **token, char *state) { char *tokend; const char *delim; int isdelim = 0; int state_is_delim = 0; if (!str || !max || !delims || !token || !state) return 0; tokend = &str[max-1]; if (!str || max == 0 || !delims || !token) return 0; /* * the very special case of "" with max=1, where we have no prior * state to let us know this is the same as right after a delim */ if (*token == NULL && max == 1 && *str == '\0') { state_is_delim = 1; } for (delim = delims; *delim; delim++) { char *tmp = NULL; if (*token && *delim == *state) state_is_delim = 1; tmp = strnchrnul(str, max, *delim); if (tmp < tokend) tokend = tmp; if (*tokend == *delim) isdelim = 1; } *token = str; if (isdelim) { *state = *tokend; *tokend = '\0'; return 1; } return state_is_delim; } #define UTF8_BOM { 0xef, 0xbb, 0xbf } #define UTF8_BOM_SIZE 3 static inline UNUSED NONNULL(1) BOOLEAN is_utf8_bom(CHAR8 *buf, size_t bufsize) { unsigned char bom[] = UTF8_BOM; return CompareMem(buf, bom, MIN(UTF8_BOM_SIZE, bufsize)) == 0; } /** * parse CSV data from data to end. * *data points to the first byte of the data * end points to a NUL byte at the end of the data * n_columns number of columns per entry * list the list head we're adding to * * On success, list will be populated with individually allocate a list of * struct csv_list objects, with one column per entry of the "columns" array, * filled left to right with up to n_columns elements, or NULL when a csv line * does not have enough elements. * * Note that the data will be modified; all comma, linefeed, and newline * characters will be set to '\000'. Additionally, consecutive linefeed and * newline characters will not result in rows in the results. * * On failure, list will be empty and all entries on it will have been freed, * using free_csv_list(), whether they were there before calling * parse_csv_data or not. */ struct csv_row { list_t list; /* this is a linked list */ size_t n_columns; /* this is how many columns are actually populated */ char *columns[0]; /* these are pointers to columns */ }; EFI_STATUS parse_csv_data(char *data, char *end, size_t n_columns, list_t *list); void free_csv_list(list_t *list); #ifdef SHIM_UNIT_TEST void NONNULL(1, 3, 4) parse_csv_line(char * line, size_t max, size_t *n_columns, const char *columns[]); #endif #endif /* SHIM_STR_H */
xnox/shim
test-str.c
// SPDX-License-Identifier: BSD-2-Clause-Patent /* * test-str.c - test our string functions. */ #ifndef SHIM_UNIT_TEST #define SHIM_UNIT_TEST #endif #include "shim.h" #include <stdio.h> #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic error "-Wnonnull" int test_strchrnul(void) { const char s0[] = "abcd\0fghi"; assert_equal_return(strchrnul(s0, 'a'), &s0[0], -1, "got %p expected %p\n"); assert_equal_return(strchrnul(s0, 'd'), &s0[3], -1, "got %p expected %p\n"); assert_equal_return(strchrnul(s0, '\000'), &s0[4], -1, "got %p expected %p\n"); assert_equal_return(strchrnul(s0, 'i'), &s0[4], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, 0, 'b'), &s0[0], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, -1, 'b'), &s0[1], 1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, 2, 'b'), &s0[1], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, 4, 'f'), &s0[3], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, 5, 'f'), &s0[4], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(s0, 8, 'f'), &s0[4], -1, "got %p expected %p\n"); assert_equal_return(strnchrnul(&s0[4], 1, 'f'), &s0[4], -1, "got %p expected %p\n"); return 0; } int test_strntoken_null(void) { bool ret; char *token = NULL; char state; char *delims = alloca(3); memcpy(delims, ",.", 3); ret = strntoken(NULL, 1, delims, &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); return 0; } int test_strntoken_size_0(void) { const char s1[] = "abc,def,.,gh,"; char s2[] = "abc,def,.,gh,"; char *token = NULL; bool ret; size_t max; char *s = s2; size_t tokensz; char state; ret = strntoken(s, 0, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, NULL, -1, "got %p expected %p\n"); assert_equal_return(memcmp(s, "abc,def,.,gh,", sizeof(s2)), 0, 1, "got %d expected %d\n"); return 0; } int test_strntoken_empty_size_1(void) { char s1[] = ""; char *s; bool ret; char *token = NULL; char *prevtok = NULL; size_t max; size_t tokensz; char state; s = s1; max = 1; ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token[0], '\0', -1, "got %#hhx expected %#hhx\n"); prevtok = token; tokensz = strlen(token) + 1; s += tokensz; max -= tokensz; assert_equal_return(s, &s1[1], -1, "got %p expected %p\n"); assert_equal_return(max, 0, -1, "got %d expected %d\n"); ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, prevtok, -1, "got %p expected %p\n"); return 0; } int test_strntoken_size_1(void) { char s1[] = ","; char *s; bool ret; char *token = NULL; char *prevtok = NULL; size_t max; size_t tokensz; char state; s = s1; max = 1; ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token[0], '\0', -1, "got %#hhx expected %#hhx\n"); prevtok = token; tokensz = strlen(token) + 1; s += tokensz; max -= tokensz; assert_equal_return(s, &s1[1], -1, "got %p expected %p\n"); assert_equal_return(max, 0, -1, "got %d expected %d\n"); ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, prevtok, -1, "got %p expected %p\n"); assert_equal_return(token[0], '\0', -1, "got %#hhx expected %#hhx\n"); return 0; } int test_strntoken_size_2(void) { char s1[] = ","; char *s; bool ret; char *token = NULL; char *prevtok = NULL; size_t max; size_t tokensz; char state; s = s1; max = 2; ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token[0], '\0', -1, "got %#hhx expected %#hhx\n"); tokensz = strlen(token) + 1; s += tokensz; max -= tokensz; assert_equal_return(s, &s1[1], -1, "got %p expected %p\n"); assert_equal_return(max, 1, -1, "got %d expected %d\n"); ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token[0], '\0', -1, "got %#hhx expected %#hhx\n"); prevtok = token; tokensz = strlen(token) + 1; s += tokensz; max -= tokensz; assert_equal_return(s, &s1[2], -1, "got %p expected %p\n"); assert_equal_return(max, 0, -1, "got %d expected %d\n"); ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, prevtok, -1, "got %#hhx expected %#hhx\n"); return 0; } int test_strntoken_no_ascii_nul(void) { const char s1[] = "abc,def,.,gh,"; char s2[] = "abc,def,.,gh,"; char *token = NULL; bool ret; size_t max; char *s = s2; size_t tokensz; char state; s = s2; max = sizeof(s2) - 1; assert_equal_return(max, 13, -1, "got %d expected %d\n"); /* * s="abc,def,.,gh," -> "abc\0def,.,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token, s, -1, "got %p expected %p\n"); assert_equal_return(s[2], 'c', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[3], '\0', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[4], 'd', -1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 9, -1, "got %d expected %d\n"); /* * s="def,.,gh," -> "def\0.,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token, s, -1, "got %p expected %p\n"); assert_equal_return(s[2], 'f', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[3], '\0', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[4], '.', -1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 5, -1, "got %d expected %d\n"); /* * s=".,gh," -> "\0,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token, s, -1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], ',', -1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 4, -1, "got %d expected %d\n"); /* * s=",gh," -> "\0gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token, s, -1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], 'g', -1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 3, -1, "got %d expected %d\n"); /* * s="gh," -> "gh\0" * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, -1, "got %d expected %d\n"); assert_equal_return(token, s, -1, "got %p expected %p\n"); assert_equal_return(s[0], 'g', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], 'h', -1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[2], '\0', -1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 0, -1, "got %d expected %d\n"); char *prevtok = token; /* * s="" -> "" * ^ token, but max is 0 */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, prevtok, -1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', -1, "got %#hhx expected %#hhx\n"); s[0] = 'x'; ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, -1, "got %d expected %d\n"); assert_equal_return(token, prevtok, -1, "got %p expected %p\n"); assert_equal_return(s[0], 'x', -1, "got %#hhx expected %#hhx\n"); return 0; } int test_strntoken_with_ascii_nul(void) { const char s1[] = "abc,def,.,gh,"; char s2[] = "abc,def,.,gh,"; char *token = NULL; bool ret; size_t max; char *s = s2; size_t tokensz; char s3[] = "abc,def,.,gh,"; char state; s = s2; max = sizeof(s2); assert_equal_return(max, 14, 1, "got %d expected %d\n"); /* * s="abc,def,.,gh," -> "abc\0def,.,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(s[2], 'c', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[3], '\0', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[4], 'd', 1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 10, 1, "got %d expected %d\n"); /* * s="def,.,gh," -> "def\0.,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(token, s, 1, "got %p expected %p\n"); assert_equal_return(s[2], 'f', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[3], '\0', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[4], '.', 1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 6, 1, "got %d expected %d\n"); /* * s=".,gh," -> "\0,gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(token, s, 1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], ',', 1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 5, 1, "got %d expected %d\n"); /* * s=",gh," -> "\0gh," * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(token, s, 1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], 'g', 1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 4, 1, "got %d expected %d\n"); /* * s="gh," -> "gh\0" * ^ token */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(token, s, 1, "got %p expected %p\n"); assert_equal_return(s[0], 'g', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[1], 'h', 1, "got %#hhx expected %#hhx\n"); assert_equal_return(s[2], '\0', 1, "got %#hhx expected %#hhx\n"); tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 1, 1, "got %d expected %d\n"); /* * s="" -> "" * ^ token, max is 1 */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, true, 1, "got %d expected %d\n"); assert_equal_return(token, s, 1, "got %p expected %p\n"); assert_equal_return(s[0], '\0', 1, "got %#hhx expected %#hhx\n"); char *prevtok = token; tokensz = strnlen(token, max) + 1; s += tokensz; max -= tokensz; assert_equal_return(max, 0, 1, "got %d expected %d\n"); /* * s="" -> "" * ^ token, max is 0 */ ret = strntoken(s, max, ",.", &token, &state); assert_equal_return(ret, false, 1, "got %d expected %d\n"); assert_equal_return(token, prevtok, 1, "got %p expected %p\n"); return 0; } int main(void) { int status = 0; test(test_strchrnul); test(test_strntoken_null); test(test_strntoken_size_0); test(test_strntoken_empty_size_1); test(test_strntoken_size_1); test(test_strntoken_size_2); test(test_strntoken_no_ascii_nul); test(test_strntoken_with_ascii_nul); return status; } // vim:fenc=utf-8:tw=75:noet
xnox/shim
include/sbat.h
<gh_stars>0 // SPDX-License-Identifier: BSD-2-Clause-Patent /* * sbat.c - parse SBAT data from the .sbat section data */ #ifndef SBAT_H_ #define SBAT_H_ extern UINTN _sbat, _esbat; struct sbat_var_entry { const CHAR8 *component_name; const CHAR8 *component_generation; /* * This column is only actually on the "sbat" version entry */ const CHAR8 *sbat_datestamp; list_t list; }; extern list_t sbat_var; #define SBAT_VAR_COLUMNS ((sizeof (struct sbat_var_entry) - sizeof(list_t)) / sizeof(CHAR8 *)) #define SBAT_VAR_REQUIRED_COLUMNS (SBAT_VAR_COLUMNS - 1) EFI_STATUS parse_sbat_var(list_t *entries); void cleanup_sbat_var(list_t *entries); struct sbat_section_entry { const CHAR8 *component_name; const CHAR8 *component_generation; const CHAR8 *vendor_name; const CHAR8 *vendor_package_name; const CHAR8 *vendor_version; const CHAR8 *vendor_url; }; #define SBAT_SECTION_COLUMNS (sizeof (struct sbat_section_entry) / sizeof(CHAR8 *)) EFI_STATUS parse_sbat_section(char *section_base, size_t section_size, size_t *n, struct sbat_section_entry ***entriesp); void cleanup_sbat_section_entries(size_t n, struct sbat_section_entry **entries); EFI_STATUS verify_sbat(size_t n, struct sbat_section_entry **entries); #ifdef SHIM_UNIT_TEST EFI_STATUS parse_sbat_var_data(list_t *entries, UINT8 *data, UINTN datasize); EFI_STATUS verify_sbat_helper(list_t *sbat_var, size_t n, struct sbat_section_entry **entries); #endif /* !SHIM_UNIT_TEST */ #endif /* !SBAT_H_ */ // vim:fenc=utf-8:tw=75:noet
xnox/shim
include/hexdump.h
// SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef STATIC_HEXDUMP_H #define STATIC_HEXDUMP_H #include <stdint.h> static inline unsigned long UNUSED prepare_hex(const void *data, size_t size, char *buf, unsigned int position) { char hexchars[] = "0123456789abcdef"; int offset = 0; unsigned long i; unsigned long j; unsigned long ret; unsigned long before = (position % 16); unsigned long after = (before+size >= 16) ? 0 : 16 - (before+size); for (i = 0; i < before; i++) { buf[offset++] = 'X'; buf[offset++] = 'X'; buf[offset++] = ' '; if (i == 7) buf[offset++] = ' '; } for (j = 0; j < 16 - after - before; j++) { uint8_t d = ((uint8_t *)data)[j]; buf[offset++] = hexchars[(d & 0xf0) >> 4]; buf[offset++] = hexchars[(d & 0x0f)]; if (i+j != 15) buf[offset++] = ' '; if (i+j == 7) buf[offset++] = ' '; } ret = 16 - after - before; j += i; for (i = 0; i < after; i++) { buf[offset++] = 'X'; buf[offset++] = 'X'; if (i+j != 15) buf[offset++] = ' '; if (i+j == 7) buf[offset++] = ' '; } buf[offset] = '\0'; return ret; } #define isprint(c) ((c) >= 0x20 && (c) <= 0x7e) static inline void UNUSED prepare_text(const void *data, size_t size, char *buf, unsigned int position) { int offset = 0; unsigned long i; unsigned long j; unsigned long before = position % 16; unsigned long after = (before+size > 16) ? 0 : 16 - (before+size); if (size == 0) { buf[0] = '\0'; return; } for (i = 0; i < before; i++) buf[offset++] = 'X'; buf[offset++] = '|'; for (j = 0; j < 16 - after - before; j++) { if (isprint(((uint8_t *)data)[j])) buf[offset++] = ((uint8_t *)data)[j]; else buf[offset++] = '.'; } buf[offset++] = size > 0 ? '|' : 'X'; buf[offset] = '\0'; } /* * variadic hexdump formatted * think of it as: printf("%s%s\n", vformat(fmt, ap), hexdump(data,size)); */ static inline void UNUSED vhexdumpf(const char *file, int line, const char *func, const CHAR16 * const fmt, const void *data, unsigned long size, size_t at, va_list ap) { unsigned long display_offset = at; unsigned long offset = 0; if (verbose == 0) return; while (offset < size) { char hexbuf[49]; char txtbuf[19]; unsigned long sz; sz = prepare_hex(data+offset, size-offset, hexbuf, (unsigned long)data+offset); if (sz == 0) return; prepare_text(data+offset, size-offset, txtbuf, (unsigned long)data+offset); if (fmt && fmt[0] != 0) vdprint_(fmt, file, line, func, ap); dprint_(L"%a:%d:%a() %08lx %a %a\n", file, line, func, display_offset, hexbuf, txtbuf); display_offset += sz; offset += sz; } } /* * hexdump formatted * think of it as: printf("%s%s", format(fmt, ...), hexdump(data,size)[lineN]); */ static inline void UNUSED hexdumpf(const char *file, int line, const char *func, const CHAR16 * const fmt, const void *data, unsigned long size, size_t at, ...) { va_list ap; va_start(ap, at); vhexdumpf(file, line, func, fmt, data, size, at, ap); va_end(ap); } static inline void UNUSED hexdump(const char *file, int line, const char *func, const void *data, unsigned long size) { hexdumpf(file, line, func, L"", data, size, (intptr_t)data); } static inline void UNUSED hexdumpat(const char *file, int line, const char *func, const void *data, unsigned long size, size_t at) { hexdumpf(file, line, func, L"", data, size, at); } #define LogHexdump(data, sz) LogHexdump_(__FILE__, __LINE__, __func__, data, sz) #define dhexdump(data, sz) hexdump(__FILE__, __LINE__, __func__, data, sz) #define dhexdumpat(data, sz, at) \ hexdumpat(__FILE__, __LINE__ - 1, __func__, data, sz, at) #define dhexdumpf(fmt, data, sz, at, ...) \ hexdumpf(__FILE__, __LINE__ - 1, __func__, fmt, data, sz, at, ##__VA_ARGS__) #endif /* STATIC_HEXDUMP_H */ // vim:fenc=utf-8:tw=75:noet
HexabitzPlatform/H0BR4x-Firmware
H0BR4/H0BR4.h
<reponame>HexabitzPlatform/H0BR4x-Firmware /* BitzOS (BOS) V0.2.5 - Copyright (C) 2017-2021 Hexabitz All rights reserved File Name : H0BR4.c Description : Header file for module H0BR4. IMU (ST LSM6DS3TR) + Digital Compass (ST LSM303AGRTR) */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef H0BR4_H #define H0BR4_H /* Includes ------------------------------------------------------------------*/ #include "BOS.h" #include "H0BR4_MemoryMap.h" #include "H0BR4_uart.h" #include "H0BR4_i2c.h" #include "H0BR4_gpio.h" #include "H0BR4_dma.h" /* Exported definitions -------------------------------------------------------*/ #define modulePN _H0BR4 /* Port-related definitions */ #define NumOfPorts 6 #define P_PROG P2 /* ST factory bootloader UART */ /* Define available ports */ #define _P1 #define _P2 #define _P3 #define _P4 #define _P5 #define _P6 /* Define available USARTs */ #define _Usart1 1 #define _Usart2 1 #define _Usart3 1 #define _Usart4 1 #define _Usart5 1 #define _Usart6 1 /* Port-UART mapping */ #define P1uart &huart4 #define P2uart &huart2 #define P3uart &huart6 #define P4uart &huart3 #define P5uart &huart1 #define P6uart &huart5 /* Port Definitions */ #define USART1_TX_PIN GPIO_PIN_9 #define USART1_RX_PIN GPIO_PIN_10 #define USART1_TX_PORT GPIOA #define USART1_RX_PORT GPIOA #define USART1_AF GPIO_AF1_USART1 #define USART2_TX_PIN GPIO_PIN_2 #define USART2_RX_PIN GPIO_PIN_3 #define USART2_TX_PORT GPIOA #define USART2_RX_PORT GPIOA #define USART2_AF GPIO_AF1_USART2 #define USART3_TX_PIN GPIO_PIN_10 #define USART3_RX_PIN GPIO_PIN_11 #define USART3_TX_PORT GPIOB #define USART3_RX_PORT GPIOB #define USART3_AF GPIO_AF4_USART3 #define USART4_TX_PIN GPIO_PIN_0 #define USART4_RX_PIN GPIO_PIN_1 #define USART4_TX_PORT GPIOA #define USART4_RX_PORT GPIOA #define USART4_AF GPIO_AF4_USART4 #define USART5_TX_PIN GPIO_PIN_3 #define USART5_RX_PIN GPIO_PIN_4 #define USART5_TX_PORT GPIOB #define USART5_RX_PORT GPIOB #define USART5_AF GPIO_AF4_USART5 #define USART6_TX_PIN GPIO_PIN_4 #define USART6_RX_PIN GPIO_PIN_5 #define USART6_TX_PORT GPIOA #define USART6_RX_PORT GPIOA #define USART6_AF GPIO_AF5_USART6 /* Module-specific Definitions */ #define IMU_INT1_PORT GPIOB #define IMU_INT1_PIN GPIO_PIN_12 #define IMU_INT1_GPIO_CLK() __GPIOB_CLK_ENABLE(); #define IMU_INT2_PORT GPIOA #define IMU_INT2_PIN GPIO_PIN_6 #define IMU_INT2_GPIO_CLK() __GPIOA_CLK_ENABLE(); #define MAG_INT_PORT GPIOA #define MAG_INT_PIN GPIO_PIN_7 #define MAG_INT_GPIO_CLK() __GPIOA_CLK_ENABLE(); #define XL_INT1_PORT GPIOB #define XL_INT1_PIN GPIO_PIN_1 #define XL_INT1_GPIO_CLK() __GPIOB_CLK_ENABLE(); #define XL_INT2_PORT GPIOB #define XL_INT2_PIN GPIO_PIN_0 #define XL_INT2_GPIO_CLK() __GPIOB_CLK_ENABLE(); #define _MEMS_I2C2_SDA_PORT GPIOB #define _MEMS_I2C2_SDA_PIN GPIO_PIN_14 #define _MEMS_I2C2_SDA_GPIO_CLK() __GPIOB_CLK_ENABLE(); #define _MEMS_I2C2_SCL_PORT GPIOB #define _MEMS_I2C2_SCL_PIN GPIO_PIN_13 #define _MEMS_I2C2_SCL_GPIO_CLK() __GPIOB_CLK_ENABLE(); #define NUM_MODULE_PARAMS 13 /* Module_Status Type Definition */ typedef enum { H0BR4_OK =0, H0BR4_ERR_UnknownMessage, H0BR4_ERR_GYRO, H0BR4_ERR_ACC, H0BR4_ERR_MAG, H0BR4_ERR_LSM6DS3, H0BR4_ERR_LSM303, H0BR4_ERR_BUSY, H0BR4_ERR_TIMEOUT, H0BR4_ERR_IO, H0BR4_ERR_TERMINATED, H0BR4_ERR_WrongParams, H0BR4_ERROR =25 } Module_Status; /* Indicator LED */ #define _IND_LED_PORT GPIOA #define _IND_LED_PIN GPIO_PIN_11 /* Export UART variables */ extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; extern UART_HandleTypeDef huart3; extern UART_HandleTypeDef huart4; extern UART_HandleTypeDef huart5; extern UART_HandleTypeDef huart6; /* Define UART Init prototypes */ extern void MX_USART1_UART_Init(void); extern void MX_USART2_UART_Init(void); extern void MX_USART3_UART_Init(void); extern void MX_USART4_UART_Init(void); extern void MX_USART5_UART_Init(void); extern void MX_USART6_UART_Init(void); /* ----------------------------------------------------------------------- | APIs | ----------------------------------------------------------------------- */ Module_Status SampleGyroMDPS(int *gyroX,int *gyroY,int *gyroZ); Module_Status SampleGyroRaw(int16_t *gyroX,int16_t *gyroY,int16_t *gyroZ); Module_Status SampleGyroDPS(float *x,float *y,float *z); Module_Status SampleGyroDPSToBuf(float *buffer); Module_Status SampleGyroDPSToString(char *cstring,size_t maxLen); Module_Status SampleGyroDPSToPort(uint8_t port,uint8_t module); Module_Status SampleAccMG(int *accX,int *accY,int *accZ); Module_Status SampleAccRaw(int16_t *accX,int16_t *accY,int16_t *accZ); Module_Status SampleAccG(float *x,float *y,float *z); Module_Status SampleAccGToBuf(float *buffer); Module_Status SampleAccGToString(char *cstring,size_t maxLen); Module_Status SampleAccGToPort(uint8_t port,uint8_t module); Module_Status SampleMagMGauss(int *magX,int *magY,int *magZ); Module_Status SampleMagRaw(int16_t *magX,int16_t *magY,int16_t *magZ); Module_Status SampleMagMGaussToBuf(float *buffer); Module_Status SampleMagMGaussToString(char *cstring,size_t maxLen); Module_Status SampleMagMGaussToPort(uint8_t port,uint8_t module); Module_Status SampleTempCelsius(float *temp); Module_Status SampleTempFahrenheit(float *temp); Module_Status SampleTempCToPort(uint8_t port,uint8_t module); Module_Status SampleTempCToString(char *cstring,size_t maxLen); Module_Status StreamGyroDPSToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout); Module_Status StreamGyroDPSToCLI(uint32_t period,uint32_t timeout); Module_Status StreamGyroDPSToBuffer(float *buffer,uint32_t period,uint32_t timeout); Module_Status StreamAccGToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout); Module_Status StreamAccGToCLI(uint32_t period,uint32_t timeout); Module_Status StreamAccGToBuffer(float *buffer,uint32_t period,uint32_t timeout); Module_Status StreamMagMGaussToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout); Module_Status StreamMagMGaussToCLI(uint32_t period,uint32_t timeout); Module_Status StreamMagMGaussToBuffer(float *buffer,uint32_t period,uint32_t timeout); Module_Status StreamTempCToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout); Module_Status StreamTempCToCLI(uint32_t period,uint32_t timeout); Module_Status StreamTempCToBuffer(float *buffer,uint32_t period,uint32_t timeout); void stopStreamMems(void); /* ----------------------------------------------------------------------- | Commands | ----------------------------------------------------------------------- */ #endif /* H0BR4_H */ /************************ (C) COPYRIGHT HEXABITZ *****END OF FILE****/
HexabitzPlatform/H0BR4x-Firmware
H0BR4/H0BR4.c
<gh_stars>1-10 /* BitzOS (BOS) V0.2.5 - Copyright (C) 2017-2021 Hexabitz All rights reserved File Name : H0BR4.c Description : Source code for module H0BR4. IMU (ST LSM6DS3TR) + Digital Compass (ST LSM303AGRTR) Required MCU resources : >> USARTs 1,2,3,4,5,6 for module ports. >> I2C2 for LSM6DS3TR and LSM303AGRTR communication. >> GPIOB 12, GPIOA 6 for LSM6DS3TR IMU_INT1 and IMU_INT2. >> GPIOB 1, GPIOB 0 for LSM303AGRTR XL_INT1 and XL_INT2. >> GPIOA 7 for LSM303AGRTR MAG_INT. */ /* Includes ------------------------------------------------------------------*/ #include "BOS.h" #include "LSM6DS3.h" #include "LSM303AGR_ACC.h" #include "LSM303AGR_MAG.h" #include <math.h> #define LSM303AGR_MAG_SENSITIVITY_FOR_FS_50G 1.5 /**< Sensitivity value for 16 gauss full scale [mgauss/LSB] */ #define MIN_MEMS_PERIOD_MS 200 #define MAX_MEMS_TIMEOUT_MS 0xFFFFFFFF /* Define UART variables */ UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; UART_HandleTypeDef huart3; UART_HandleTypeDef huart4; UART_HandleTypeDef huart5; UART_HandleTypeDef huart6; /* Exported variables */ extern FLASH_ProcessTypeDef pFlash; extern uint8_t numOfRecordedSnippets; /* Module exported parameters ------------------------------------------------*/ float H0BR4_gyroX =0.0f; float H0BR4_gyroY =0.0f; float H0BR4_gyroZ =0.0f; float H0BR4_accX =0.0f; float H0BR4_accY =0.0f; float H0BR4_accZ =0.0f; int H0BR4_magX =0.0f; int H0BR4_magY =0.0f; int H0BR4_magZ =0.0f; float H0BR4_temp =0.0f; //float x __attribute__((section(".mySection"))); //float y __attribute__((section(".mySection"))); //float z __attribute__((section(".mySection"))); float xGyro __attribute__((section(".mySection"))); float yGyro __attribute__((section(".mySection"))); float zGyro __attribute__((section(".mySection"))); float xAcc __attribute__((section(".mySection"))); float yAcc __attribute__((section(".mySection"))); float zAcc __attribute__((section(".mySection"))); int xMag __attribute__((section(".mySection"))); int yMag __attribute__((section(".mySection"))); int zMag __attribute__((section(".mySection"))); float temperature __attribute__((section(".mySection"))); //float xAcc,yAcc,zAcc; //float xGyro,yGyro,zGyro; //int xMag,yMag,zMag; //float temperature; module_param_t modParam[NUM_MODULE_PARAMS] ={{.paramPtr =&H0BR4_gyroX, .paramFormat =FMT_FLOAT, .paramName ="gyroX"}, {.paramPtr =&H0BR4_gyroY, .paramFormat =FMT_FLOAT, .paramName ="gyroY"}, {.paramPtr =&H0BR4_gyroZ, .paramFormat =FMT_FLOAT, .paramName ="gyroZ"}, {.paramPtr =&H0BR4_accX, .paramFormat =FMT_FLOAT, .paramName ="accX"}, {.paramPtr =&H0BR4_accY, .paramFormat =FMT_FLOAT, .paramName ="accY"}, {.paramPtr =&H0BR4_accZ, .paramFormat =FMT_FLOAT, .paramName ="accZ"}, {.paramPtr =&H0BR4_magX, .paramFormat =FMT_INT32, .paramName ="magX"}, {.paramPtr =&H0BR4_magY, .paramFormat =FMT_INT32, .paramName ="magY"}, {.paramPtr =&H0BR4_magZ, .paramFormat =FMT_INT32, .paramName ="magZ"}, {.paramPtr =&H0BR4_temp, .paramFormat =FMT_FLOAT, .paramName ="temp"}, }; typedef Module_Status (*SampleMemsToPort)(uint8_t,uint8_t); typedef Module_Status (*SampleMemsToString)(char*,size_t); typedef Module_Status (*SampleMemsToBuffer)(float *buffer); /* Private variables ---------------------------------------------------------*/ static bool stopStream = false; /* Private function prototypes -----------------------------------------------*/ static Module_Status LSM6DS3Init(void); //static Module_Status LSM303AccInit(void); static Module_Status LSM303MagInit(void); static Module_Status LSM6DS3SampleGyroMDPS(int *gyroX,int *gyroY,int *gyroZ); static Module_Status LSM6DS3SampleGyroRaw(int16_t *gyroX,int16_t *gyroY,int16_t *gyroZ); static Module_Status LSM6DS3SampleAccMG(int *accX,int *accY,int *accZ); static Module_Status LSM6DS3SampleAccRaw(int16_t *accX,int16_t *accY,int16_t *accZ); static Module_Status LSM6DS3SampleTempCelsius(float *temp); static Module_Status LSM6DS3SampleTempFahrenheit(float *temp); static Module_Status LSM303SampleMagMGauss(int *magX,int *magY,int *magZ); static Module_Status LSM303SampleMagRaw(int16_t *magX,int16_t *magY,int16_t *magZ); static Module_Status StreamMemsToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout,SampleMemsToPort function); static Module_Status StreamMemsToCLI(uint32_t period,uint32_t timeout,SampleMemsToString function); static Module_Status StreamMemsToBuf(float *buffer,uint32_t numDatapoints,uint32_t period,uint32_t timeout,SampleMemsToBuffer function); /* Create CLI commands --------------------------------------------------------*/ static portBASE_TYPE SampleSensorCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString); static portBASE_TYPE StreamSensorCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString); static portBASE_TYPE StopStreamCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString); const CLI_Command_Definition_t SampleCommandDefinition ={(const int8_t* )"sample", (const int8_t* )"sample:\r\n Syntax: sample [gyro]/[acc]/[mag]/[temp]\r\n \ \tGet filtered and calibrated Gyro, Acc, Mag or Temp values in \ dps, g, mguass or celsius units respectively.\r\n\r\n", SampleSensorCommand, 1}; const CLI_Command_Definition_t StreamCommandDefinition ={(const int8_t* )"stream", (const int8_t* )"stream:\r\n Syntax: stream [gyro]/[acc]/[mag]/[temp] (period in ms) (time in ms) [port]/[buffer] [module]\r\n \ \tGet stream of filtered and calibrated Gyro, Acc, Mag or Temp values in \ dps, g, mguass or celsius units respectively. Press ENTER to stop the stream.\r\n\r\n", StreamSensorCommand, -1}; const CLI_Command_Definition_t StopCommandDefinition ={(const int8_t* )"stop", (const int8_t* )"stop:\r\n Syntax: stop\r\n \ \tStop the current streaming of MEMS values. r\n\r\n", StopStreamCommand, 0}; /* ----------------------------------------------------------------------- | Private Functions | ----------------------------------------------------------------------- */ /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 48000000 * HCLK(Hz) = 48000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * HSE Frequency(Hz) = 8000000 * PREDIV = 1 * PLLMUL = 6 * Flash Latency(WS) = 1 * @param None * @retval None */ void SystemClock_Config(void){ RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInit; RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue =16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6; RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1; HAL_RCC_OscConfig(&RCC_OscInitStruct); RCC_ClkInitStruct.ClockType =(RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; HAL_RCC_ClockConfig(&RCC_ClkInitStruct,FLASH_LATENCY_1); PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3; PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1; PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1; PeriphClkInit.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1; HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit); __HAL_RCC_PWR_CLK_ENABLE(); HAL_PWR_EnableBkUpAccess(); PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32; HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit); HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000); HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); __SYSCFG_CLK_ENABLE() ; /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn,0,0); } /*-----------------------------------------------------------*/ /* --- H0BR4 module initialization. */ void Module_Peripheral_Init(void){ /* Peripheral clock enable */ /* Array ports */ MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_USART3_UART_Init(); MX_USART4_UART_Init(); MX_USART5_UART_Init(); MX_USART6_UART_Init(); // TODO: Initialize I2C MX_I2C_Init(); LSM6DS3Init(); LSM303MagInit(); // Disabling Accelerometer of LSM303AGR // LSM303AccInit(); } void initialValue(void) { xGyro=0; yGyro=0; zGyro=0; xAcc=0; yAcc=0; zAcc=0; xMag=0; yMag=0; zMag=0; temperature=0; } /*-----------------------------------------------------------*/ /* --- H0BR4 message processing task. */ Module_Status Module_MessagingTask(uint16_t code,uint8_t port,uint8_t src,uint8_t dst,uint8_t shift){ Module_Status result =H0BR4_OK; uint32_t period =0, timeout =0; switch(code){ case CODE_H0BR4_SAMPLE_PORT_GYRO: { SampleGyroDPSToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift]); break; } case CODE_H0BR4_SAMPLE_PORT_ACC: { SampleAccGToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift]); break; } case CODE_H0BR4_SAMPLE_PORT_MAG: { SampleMagMGaussToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift]); break; } case CODE_H0BR4_SAMPLE_PORT_TEMP: { SampleTempCToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift]); break; } case CODE_H0BR4_STREAM_PORT_GYRO: { period =((uint32_t )cMessage[port - 1][5 + shift] << 24) + ((uint32_t )cMessage[port - 1][4 + shift] << 16) + ((uint32_t )cMessage[port - 1][3 + shift] << 8) + cMessage[port - 1][2 + shift]; timeout =((uint32_t )cMessage[port - 1][9 + shift] << 24) + ((uint32_t )cMessage[port - 1][8 + shift] << 16) + ((uint32_t )cMessage[port - 1][7 + shift] << 8) + cMessage[port - 1][6 + shift]; if((result =StreamGyroDPSToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift],period,timeout)) != H0BR4_OK) break; break; } case CODE_H0BR4_STREAM_PORT_ACC: { period =((uint32_t )cMessage[port - 1][5 + shift] << 24) + ((uint32_t )cMessage[port - 1][4 + shift] << 16) + ((uint32_t )cMessage[port - 1][3 + shift] << 8) + cMessage[port - 1][2 + shift]; timeout =((uint32_t )cMessage[port - 1][9 + shift] << 24) + ((uint32_t )cMessage[port - 1][8 + shift] << 16) + ((uint32_t )cMessage[port - 1][7 + shift] << 8) + cMessage[port - 1][6 + shift]; if((result =StreamAccGToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift],period,timeout)) != H0BR4_OK) break; break; } case CODE_H0BR4_STREAM_PORT_MAG: { period =((uint32_t )cMessage[port - 1][5 + shift] << 24) + ((uint32_t )cMessage[port - 1][4 + shift] << 16) + ((uint32_t )cMessage[port - 1][3 + shift] << 8) + cMessage[port - 1][2 + shift]; timeout =((uint32_t )cMessage[port - 1][9 + shift] << 24) + ((uint32_t )cMessage[port - 1][8 + shift] << 16) + ((uint32_t )cMessage[port - 1][7 + shift] << 8) + cMessage[port - 1][6 + shift]; if((result =StreamMagMGaussToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift],period,timeout)) != H0BR4_OK) break; break; } case CODE_H0BR4_STREAM_PORT_TEMP: { period =((uint32_t )cMessage[port - 1][5 + shift] << 24) + ((uint32_t )cMessage[port - 1][4 + shift] << 16) + ((uint32_t )cMessage[port - 1][3 + shift] << 8) + cMessage[port - 1][2 + shift]; timeout =((uint32_t )cMessage[port - 1][9 + shift] << 24) + ((uint32_t )cMessage[port - 1][8 + shift] << 16) + ((uint32_t )cMessage[port - 1][7 + shift] << 8) + cMessage[port - 1][6 + shift]; if((result =StreamTempCToPort(cMessage[port - 1][shift],cMessage[port - 1][1+shift],period,timeout)) != H0BR4_OK) break; break; } case CODE_H0BR4_STREAM_STOP: { stopStreamMems(); result =H0BR4_OK; break; } default: result =H0BR4_ERR_UnknownMessage; break; } return result; } /*-----------------------------------------------------------*/ /* --- Register this module CLI Commands */ void RegisterModuleCLICommands(void){ FreeRTOS_CLIRegisterCommand(&SampleCommandDefinition); FreeRTOS_CLIRegisterCommand(&StreamCommandDefinition); FreeRTOS_CLIRegisterCommand(&StopCommandDefinition); } /*-----------------------------------------------------------*/ /* --- Get the port for a given UART. */ uint8_t GetPort(UART_HandleTypeDef *huart){ if(huart->Instance == USART4) return P1; else if(huart->Instance == USART2) return P2; else if(huart->Instance == USART6) return P3; else if(huart->Instance == USART3) return P4; else if(huart->Instance == USART1) return P5; else if(huart->Instance == USART5) return P6; return 0; } /*-----------------------------------------------------------*/ static Module_Status LSM6D3Enable(void){ // Check WHO_AM_I Register uint8_t who_am_i =0; if(LSM6DS3_ACC_GYRO_R_WHO_AM_I(&hi2c2,&who_am_i) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; if(who_am_i != LSM6DS3_ACC_GYRO_WHO_AM_I) return H0BR4_ERR_LSM6DS3; // Enable register address automatically incremented during a multiple byte access with a serial interface if(LSM6DS3_ACC_GYRO_W_IF_Addr_Incr(&hi2c2,LSM6DS3_ACC_GYRO_IF_INC_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Bypass Mode if(LSM6DS3_ACC_GYRO_W_FIFO_MODE(&hi2c2,LSM6DS3_ACC_GYRO_FIFO_MODE_BYPASS) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; return H0BR4_OK; } static Module_Status LSM6D3SetupGyro(void){ // Gyroscope ODR Init if(LSM6DS3_ACC_GYRO_W_ODR_G(&hi2c2,LSM6DS3_ACC_GYRO_ODR_G_13Hz) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; // Gyroscope FS Init if(LSM6DS3_ACC_GYRO_W_FS_G(&hi2c2,LSM6DS3_ACC_GYRO_FS_G_2000dps) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Gyroscope Axes Status Init if(LSM6DS3_ACC_GYRO_W_XEN_G(&hi2c2,LSM6DS3_ACC_GYRO_XEN_G_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; if(LSM6DS3_ACC_GYRO_W_YEN_G(&hi2c2,LSM6DS3_ACC_GYRO_YEN_G_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; if(LSM6DS3_ACC_GYRO_W_ZEN_G(&hi2c2,LSM6DS3_ACC_GYRO_ZEN_G_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; return H0BR4_OK; } static Module_Status LSM6D3SetupAcc(void){ // Accelerometer ODR Init if(LSM6DS3_ACC_GYRO_W_ODR_XL(&hi2c2,LSM6DS3_ACC_GYRO_ODR_XL_104Hz) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Bandwidth Selection // Selection of bandwidth and ODR should be in accordance of Nyquist Sampling theorem! if(LSM6DS3_ACC_GYRO_W_BW_XL(&hi2c2,LSM6DS3_ACC_GYRO_BW_XL_50Hz) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Accelerometer FS Init if(LSM6DS3_ACC_GYRO_W_FS_XL(&hi2c2,LSM6DS3_ACC_GYRO_FS_XL_16g) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Accelerometer Axes Status Init if(LSM6DS3_ACC_GYRO_W_XEN_XL(&hi2c2,LSM6DS3_ACC_GYRO_XEN_XL_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; if(LSM6DS3_ACC_GYRO_W_YEN_XL(&hi2c2,LSM6DS3_ACC_GYRO_YEN_XL_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; if(LSM6DS3_ACC_GYRO_W_ZEN_XL(&hi2c2,LSM6DS3_ACC_GYRO_ZEN_XL_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; // Enable Bandwidth Scaling if(LSM6DS3_ACC_GYRO_W_BW_Fixed_By_ODR(&hi2c2,LSM6DS3_ACC_GYRO_BW_SCAL_ODR_ENABLED) != MEMS_ERROR) return H0BR4_ERR_LSM6DS3; return H0BR4_OK; } static Module_Status LSM6DS3SampleGyroRaw(int16_t *gyroX,int16_t *gyroY,int16_t *gyroZ){ uint8_t temp[6]; if(LSM6DS3_ACC_GYRO_GetRawGyroData(&hi2c2,temp) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; *gyroX =concatBytes(temp[1],temp[0]); *gyroY =concatBytes(temp[3],temp[2]); *gyroZ =concatBytes(temp[5],temp[4]); return H0BR4_OK; } static Module_Status LSM6DS3SampleGyroMDPS(int *gyroX,int *gyroY,int *gyroZ){ int buff[3]; if(LSM6DS3_ACC_Get_AngularRate(&hi2c2,buff,0) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; *gyroX =buff[0]; *gyroY =buff[1]; *gyroZ =buff[2]; return H0BR4_OK; } static Module_Status LSM6DS3SampleAccRaw(int16_t *accX,int16_t *accY,int16_t *accZ){ uint8_t temp[6]; if(LSM6DS3_ACC_GYRO_GetRawAccData(&hi2c2,temp) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; *accX =concatBytes(temp[1],temp[0]); *accY =concatBytes(temp[3],temp[2]); *accZ =concatBytes(temp[5],temp[4]); return H0BR4_OK; } static Module_Status LSM6DS3SampleAccMG(int *accX,int *accY,int *accZ){ int buff[3]; if(LSM6DS3_ACC_Get_Acceleration(&hi2c2,buff,0) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; *accX =buff[0]; *accY =buff[1]; *accZ =buff[2]; return H0BR4_OK; } static Module_Status LSM6DS3SampleTempCelsius(float *temp){ uint8_t buff[2]; if(LSM6DS3_ACC_GYRO_ReadReg(&hi2c2,LSM6DS3_ACC_GYRO_OUT_TEMP_L,buff,2) != MEMS_SUCCESS) return H0BR4_ERR_LSM6DS3; int16_t rawTemp =concatBytes(buff[0],buff[1]); *temp =(((float )rawTemp) / 16) + 25; return H0BR4_OK; } static Module_Status LSM6DS3SampleTempFahrenheit(float *temp){ Module_Status status =H0BR4_OK; float celsius =0; if((status =LSM6DS3SampleTempCelsius(&celsius)) != H0BR4_OK) return status; *temp =celsiusToFahrenheit(celsius); return H0BR4_OK; } static Module_Status LSM6DS3Init(void){ // Common Init Module_Status status =H0BR4_OK; if((status =LSM6D3Enable()) != H0BR4_OK) return status; if((status =LSM6D3SetupGyro()) != H0BR4_OK) return status; if((status =LSM6D3SetupAcc()) != H0BR4_OK) return status; // TODO: Configure Interrupt Lines return status; } static Module_Status LSM303MagEnable(void){ if(LSM303AGR_MAG_W_MD(&hi2c2,LSM303AGR_MAG_MD_CONTINUOS_MODE) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; return H0BR4_OK; } static Module_Status LSM303MagInit(void){ // Check the Sensor uint8_t who_am_i =0x00; if(LSM303AGR_MAG_R_WHO_AM_I(&hi2c2,&who_am_i) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; if(who_am_i != LSM303AGR_MAG_WHO_AM_I) return H0BR4_ERR_LSM303; // Operating Mode: Power Down if(LSM303AGR_MAG_W_MD(&hi2c2,LSM303AGR_MAG_MD_IDLE1_MODE) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; // Enable Block Data Update if(LSM303AGR_MAG_W_BDU(&hi2c2,LSM303AGR_MAG_BDU_ENABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; // TODO: Change the default ODR if(LSM303AGR_MAG_W_ODR(&hi2c2,LSM303AGR_MAG_ODR_10Hz) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; // Self Test Disabled if(LSM303AGR_MAG_W_ST(&hi2c2,LSM303AGR_MAG_ST_DISABLED) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; return LSM303MagEnable(); } static Module_Status LSM303SampleMagRaw(int16_t *magX,int16_t *magY,int16_t *magZ){ int16_t *pData; uint8_t data[6]; memset(data,0,sizeof(data)); if(LSM303AGR_MAG_Get_Raw_Magnetic(&hi2c2,data) != MEMS_SUCCESS) return H0BR4_ERR_LSM303; pData =(int16_t* )data; *magX =pData[0]; *magY =pData[1]; *magZ =pData[2]; return H0BR4_OK; } static Module_Status LSM303SampleMagMGauss(int *magX,int *magY,int *magZ){ Module_Status status =H0BR4_OK; int16_t rawMagX, rawMagY, rawMagZ; /* Read raw data from LSM303AGR output register. */ if((status =LSM303SampleMagRaw(&rawMagX,&rawMagY,&rawMagZ)) != H0BR4_OK) return status; /* Set the raw data. */ *magX =rawMagX * (float )LSM303AGR_MAG_SENSITIVITY_FOR_FS_50G; *magY =rawMagY * (float )LSM303AGR_MAG_SENSITIVITY_FOR_FS_50G; *magZ =rawMagZ * (float )LSM303AGR_MAG_SENSITIVITY_FOR_FS_50G; return status; } static Module_Status PollingSleepCLISafe(uint32_t period){ const unsigned DELTA_SLEEP_MS =100; // milliseconds long numDeltaDelay =period / DELTA_SLEEP_MS; unsigned lastDelayMS =period % DELTA_SLEEP_MS; while(numDeltaDelay-- > 0){ vTaskDelay(pdMS_TO_TICKS(DELTA_SLEEP_MS)); // Look for ENTER key to stop the stream for(uint8_t chr =0; chr < MSG_RX_BUF_SIZE; chr++){ if(UARTRxBuf[PcPort - 1][chr] == '\r'){ UARTRxBuf[PcPort - 1][chr] =0; return H0BR4_ERR_TERMINATED; } } if(stopStream) return H0BR4_ERR_TERMINATED; } vTaskDelay(pdMS_TO_TICKS(lastDelayMS)); return H0BR4_OK; } static Module_Status StreamMemsToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout,SampleMemsToPort function){ Module_Status status =H0BR4_OK; if(period < MIN_MEMS_PERIOD_MS) return H0BR4_ERR_WrongParams; if(port == 0) return H0BR4_ERR_WrongParams; if(port == PcPort) // Check if CLI is not enabled at that port! return H0BR4_ERR_BUSY; if(period > timeout) timeout =period; long numTimes =timeout / period; stopStream = false; while((numTimes-- > 0) || (timeout >= MAX_MEMS_TIMEOUT_MS)){ if((status =function(port,module)) != H0BR4_OK) break; vTaskDelay(pdMS_TO_TICKS(period)); if(stopStream){ status =H0BR4_ERR_TERMINATED; break; } } return status; } static Module_Status StreamMemsToCLI(uint32_t period,uint32_t timeout,SampleMemsToString function){ Module_Status status =H0BR4_OK; int8_t *pcOutputString = NULL; if(period < MIN_MEMS_PERIOD_MS) return H0BR4_ERR_WrongParams; // TODO: Check if CLI is enable or not if(period > timeout) timeout =period; long numTimes =timeout / period; stopStream = false; while((numTimes-- > 0) || (timeout >= MAX_MEMS_TIMEOUT_MS)){ pcOutputString =FreeRTOS_CLIGetOutputBuffer(); if((status =function((char* )pcOutputString,100)) != H0BR4_OK) break; writePxMutex(PcPort,(char* )pcOutputString,strlen((char* )pcOutputString),cmd500ms,HAL_MAX_DELAY); if(PollingSleepCLISafe(period) != H0BR4_OK) break; } memset((char* )pcOutputString,0,configCOMMAND_INT_MAX_OUTPUT_SIZE); sprintf((char* )pcOutputString,"\r\n"); return status; } static Module_Status StreamMemsToBuf(float *buffer,uint32_t numDatapoints,uint32_t period,uint32_t timeout,SampleMemsToBuffer function){ Module_Status status =H0BR4_OK; if(period < MIN_MEMS_PERIOD_MS) return H0BR4_ERR_WrongParams; // TODO: Check if CLI is enable or not if(period > timeout) timeout =period; long numTimes =timeout / period; stopStream = false; while((numTimes-- > 0) || (timeout >= MAX_MEMS_TIMEOUT_MS)){ if((status =function(buffer)) != H0BR4_OK) break; buffer +=numDatapoints; vTaskDelay(pdMS_TO_TICKS(period)); if(stopStream){ status =H0BR4_ERR_TERMINATED; break; } } return status; } /* ----------------------------------------------------------------------- | APIs | ----------------------------------------------------------------------- */ Module_Status SampleGyroMDPS(int *gyroX,int *gyroY,int *gyroZ){ return LSM6DS3SampleGyroMDPS(gyroX,gyroY,gyroZ); } Module_Status SampleGyroRaw(int16_t *gyroX,int16_t *gyroY,int16_t *gyroZ){ return LSM6DS3SampleGyroRaw(gyroX,gyroY,gyroZ); } Module_Status SampleGyroDPSToPort(uint8_t port,uint8_t module){ float buffer[3]; // Three Samples X, Y, Z static uint8_t temp[12]; Module_Status status =H0BR4_OK; if((status =SampleGyroDPSToBuf(buffer)) != H0BR4_OK) return status; /*memcpy(messageParams, buffer, sizeof(buffer)); if (SendMessageFromPort(port, myID, module, CODE_H0BR4_RESULT_GYRO, sizeof(buffer)) != BOS_OK) status = H0BR4_ERR_IO;*/ if(module == myID){ temp[0] =*((__IO uint8_t* )(&buffer[0]) + 3); temp[1] =*((__IO uint8_t* )(&buffer[0]) + 2); temp[2] =*((__IO uint8_t* )(&buffer[0]) + 1); temp[3] =*((__IO uint8_t* )(&buffer[0]) + 0); temp[4] =*((__IO uint8_t* )(&buffer[1]) + 3); temp[5] =*((__IO uint8_t* )(&buffer[1]) + 2); temp[6] =*((__IO uint8_t* )(&buffer[1]) + 1); temp[7] =*((__IO uint8_t* )(&buffer[1]) + 0); temp[8] =*((__IO uint8_t* )(&buffer[2]) + 3); temp[9] =*((__IO uint8_t* )(&buffer[2]) + 2); temp[10] =*((__IO uint8_t* )(&buffer[2]) + 1); temp[11] =*((__IO uint8_t* )(&buffer[2]) + 0); writePxITMutex(port,(char* )&temp[0],12 * sizeof(uint8_t),10); } else{ messageParams[0] =port; messageParams[1] =*((__IO uint8_t* )(&buffer[0]) + 3); messageParams[2] =*((__IO uint8_t* )(&buffer[0]) + 2); messageParams[3] =*((__IO uint8_t* )(&buffer[0]) + 1); messageParams[4] =*((__IO uint8_t* )(&buffer[0]) + 0); messageParams[5] =*((__IO uint8_t* )(&buffer[1]) + 3); messageParams[6] =*((__IO uint8_t* )(&buffer[1]) + 2); messageParams[7] =*((__IO uint8_t* )(&buffer[1]) + 1); messageParams[8] =*((__IO uint8_t* )(&buffer[1]) + 0); messageParams[9] =*((__IO uint8_t* )(&buffer[2]) + 3); messageParams[10] =*((__IO uint8_t* )(&buffer[2]) + 2); messageParams[11] =*((__IO uint8_t* )(&buffer[2]) + 1); messageParams[12] =*((__IO uint8_t* )(&buffer[2]) + 0); SendMessageToModule(module,CODE_PORT_FORWARD,(sizeof(float) * 3) + 1); } return status; } Module_Status SampleGyroDPSToString(char *cstring,size_t maxLen){ Module_Status status =H0BR4_OK; float x =0, y =0, z =0; if((status =SampleGyroDPS(&x,&y,&z)) != H0BR4_OK) return status; xGyro=x; yGyro=y; zGyro=z; snprintf(cstring,maxLen,"Gyro(DPS) | X: %.2f, Y: %.2f, Z: %.2f\r\n",x,y,z); return status; } Module_Status SampleGyroDPS(float *x,float *y,float *z){ Module_Status status =H0BR4_OK; int xInMDPS =0, yInMDPS =0, zInMDPS =0; if((status =LSM6DS3SampleGyroMDPS(&xInMDPS,&yInMDPS,&zInMDPS)) != H0BR4_OK) return status; *x =((float )xInMDPS) / 1000; *y =((float )yInMDPS) / 1000; *z =((float )zInMDPS) / 1000; return status; } Module_Status SampleGyroDPSToBuf(float *buffer){ return SampleGyroDPS(buffer,buffer + 1,buffer + 2); } Module_Status SampleAccMG(int *accX,int *accY,int *accZ){ return LSM6DS3SampleAccMG(accX,accY,accZ); } Module_Status SampleAccRaw(int16_t *accX,int16_t *accY,int16_t *accZ){ return LSM6DS3SampleAccRaw(accX,accY,accZ); } Module_Status SampleAccGToPort(uint8_t port,uint8_t module){ float buffer[3]; // Three Samples X, Y, Z static uint8_t temp[12]; Module_Status status =H0BR4_OK; if((status =SampleAccGToBuf(buffer)) != H0BR4_OK) return status; /*memcpy(messageParams, buffer, sizeof(buffer)); if (SendMessageFromPort(port, myID, module, CODE_H0BR4_RESULT_ACC, sizeof(buffer)) != BOS_OK) status = H0BR4_ERR_IO;*/ if(module == myID){ temp[0] =*((__IO uint8_t* )(&buffer[0]) + 3); temp[1] =*((__IO uint8_t* )(&buffer[0]) + 2); temp[2] =*((__IO uint8_t* )(&buffer[0]) + 1); temp[3] =*((__IO uint8_t* )(&buffer[0]) + 0); temp[4] =*((__IO uint8_t* )(&buffer[1]) + 3); temp[5] =*((__IO uint8_t* )(&buffer[1]) + 2); temp[6] =*((__IO uint8_t* )(&buffer[1]) + 1); temp[7] =*((__IO uint8_t* )(&buffer[1]) + 0); temp[8] =*((__IO uint8_t* )(&buffer[2]) + 3); temp[9] =*((__IO uint8_t* )(&buffer[2]) + 2); temp[10] =*((__IO uint8_t* )(&buffer[2]) + 1); temp[11] =*((__IO uint8_t* )(&buffer[2]) + 0); writePxITMutex(port,(char* )&temp[0],12 * sizeof(uint8_t),10); //memset(temp,0,12*sizeof(uint8_t)); } else{ messageParams[0] =port; messageParams[1] =*((__IO uint8_t* )(&buffer[0]) + 3); messageParams[2] =*((__IO uint8_t* )(&buffer[0]) + 2); messageParams[3] =*((__IO uint8_t* )(&buffer[0]) + 1); messageParams[4] =*((__IO uint8_t* )(&buffer[0]) + 0); messageParams[5] =*((__IO uint8_t* )(&buffer[1]) + 3); messageParams[6] =*((__IO uint8_t* )(&buffer[1]) + 2); messageParams[7] =*((__IO uint8_t* )(&buffer[1]) + 1); messageParams[8] =*((__IO uint8_t* )(&buffer[1]) + 0); messageParams[9] =*((__IO uint8_t* )(&buffer[2]) + 3); messageParams[10] =*((__IO uint8_t* )(&buffer[2]) + 2); messageParams[11] =*((__IO uint8_t* )(&buffer[2]) + 1); messageParams[12] =*((__IO uint8_t* )(&buffer[2]) + 0); SendMessageToModule(module,CODE_PORT_FORWARD,(sizeof(float) * 3) + 1); } return status; } Module_Status SampleAccGToString(char *cstring,size_t maxLen){ Module_Status status =H0BR4_OK; float x =0, y =0, z =0; if((status =SampleAccG(&x,&y,&z)) != H0BR4_OK) return status; xAcc=x; yAcc=y; zAcc=z; snprintf(cstring,maxLen,"Acc(G) | X: %.2f, Y: %.2f, Z: %.2f\r\n",x,y,z); return status; } Module_Status SampleAccG(float *x,float *y,float *z){ Module_Status status =H0BR4_OK; int xInMG =0, yInMG =0, zInMG =0; if((status =LSM6DS3SampleAccMG(&xInMG,&yInMG,&zInMG)) != H0BR4_OK) return status; *x =((float )xInMG) / 1000; *y =((float )yInMG) / 1000; *z =((float )zInMG) / 1000; return status; } Module_Status SampleAccGToBuf(float *buffer){ return SampleAccG(buffer,buffer + 1,buffer + 2); } Module_Status SampleMagMGauss(int *magX,int *magY,int *magZ){ return LSM303SampleMagMGauss(magX,magY,magZ); } Module_Status SampleMagRaw(int16_t *magX,int16_t *magY,int16_t *magZ){ return LSM303SampleMagRaw(magX,magY,magZ); } Module_Status SampleMagMGaussToPort(uint8_t port,uint8_t module){ float buffer[3]; // Three Samples X, Y, Z static uint8_t temp[12]; Module_Status status =H0BR4_OK; if((status =SampleMagMGaussToBuf(buffer)) != H0BR4_OK) return status; /*memcpy(messageParams, buffer, sizeof(buffer)); if (SendMessageFromPort(port, myID, module, CODE_H0BR4_RESULT_MAG, sizeof(buffer)) != BOS_OK) status = H0BR4_ERR_TIMEOUT;*/ if(module == myID){ temp[0] =*((__IO uint8_t* )(&buffer[0]) + 3); temp[1] =*((__IO uint8_t* )(&buffer[0]) + 2); temp[2] =*((__IO uint8_t* )(&buffer[0]) + 1); temp[3] =*((__IO uint8_t* )(&buffer[0]) + 0); temp[4] =*((__IO uint8_t* )(&buffer[1]) + 3); temp[5] =*((__IO uint8_t* )(&buffer[1]) + 2); temp[6] =*((__IO uint8_t* )(&buffer[1]) + 1); temp[7] =*((__IO uint8_t* )(&buffer[1]) + 0); temp[8] =*((__IO uint8_t* )(&buffer[2]) + 3); temp[9] =*((__IO uint8_t* )(&buffer[2]) + 2); temp[10] =*((__IO uint8_t* )(&buffer[2]) + 1); temp[11] =*((__IO uint8_t* )(&buffer[2]) + 0); writePxITMutex(port,(char* )&temp[0],12 * sizeof(uint8_t),10); //memset(temp,0,12*sizeof(uint8_t)); } else{ messageParams[0] =port; messageParams[1] =*((__IO uint8_t* )(&buffer[0]) + 3); messageParams[2] =*((__IO uint8_t* )(&buffer[0]) + 2); messageParams[3] =*((__IO uint8_t* )(&buffer[0]) + 1); messageParams[4] =*((__IO uint8_t* )(&buffer[0]) + 0); messageParams[5] =*((__IO uint8_t* )(&buffer[1]) + 3); messageParams[6] =*((__IO uint8_t* )(&buffer[1]) + 2); messageParams[7] =*((__IO uint8_t* )(&buffer[1]) + 1); messageParams[8] =*((__IO uint8_t* )(&buffer[1]) + 0); messageParams[9] =*((__IO uint8_t* )(&buffer[2]) + 3); messageParams[10] =*((__IO uint8_t* )(&buffer[2]) + 2); messageParams[11] =*((__IO uint8_t* )(&buffer[2]) + 1); messageParams[12] =*((__IO uint8_t* )(&buffer[2]) + 0); SendMessageToModule(module,CODE_PORT_FORWARD,(sizeof(float) * 3) + 1); } return status; } Module_Status SampleMagMGaussToString(char *cstring,size_t maxLen){ Module_Status status =H0BR4_OK; int x =0, y =0, z =0; if((status =LSM303SampleMagMGauss(&x,&y,&z)) != H0BR4_OK) return status; xMag=x; yMag=y; zMag=z; snprintf(cstring,maxLen,"Mag(mGauss) | X: %d, Y: %d, Z: %d\r\n",x,y,z); return status; } Module_Status SampleMagMGaussToBuf(float *buffer){ int iMagMGauss[3]; Module_Status status =LSM303SampleMagMGauss(iMagMGauss,iMagMGauss + 1,iMagMGauss + 2); buffer[0] =iMagMGauss[0]; buffer[1] =iMagMGauss[1]; buffer[2] =iMagMGauss[2]; return status; } Module_Status SampleTempCelsius(float *temp){ return LSM6DS3SampleTempCelsius(temp); } Module_Status SampleTempFahrenheit(float *temp){ return LSM6DS3SampleTempFahrenheit(temp); } Module_Status SampleTempCToPort(uint8_t port,uint8_t module){ float temp; static uint8_t tempD[4]; Module_Status status =H0BR4_OK; if((status =LSM6DS3SampleTempCelsius(&temp)) != H0BR4_OK) return status; /*memcpy(messageParams, &temp, sizeof(temp)); if (SendMessageFromPort(port, myID, module, CODE_H0BR4_RESULT_TEMP, sizeof(temp)) != BOS_OK) status = H0BR4_ERR_TERMINATED;*/ if(module == myID){ tempD[0] =*((__IO uint8_t* )(&temp) + 3); tempD[1] =*((__IO uint8_t* )(&temp) + 2); tempD[2] =*((__IO uint8_t* )(&temp) + 1); tempD[3] =*((__IO uint8_t* )(&temp) + 0); writePxMutex(port,(char* )&tempD[0],4 * sizeof(uint8_t),10,10); //writePxITMutex(port, (char *)&tempD[0], 4*sizeof(uint8_t), 10); //memset(tempD,0,4*sizeof(uint8_t)); } else{ messageParams[0] =port; messageParams[1] =*((__IO uint8_t* )(&temp) + 3); messageParams[2] =*((__IO uint8_t* )(&temp) + 2); messageParams[3] =*((__IO uint8_t* )(&temp) + 1); messageParams[4] =*((__IO uint8_t* )(&temp) + 0); SendMessageToModule(module,CODE_PORT_FORWARD,sizeof(float) + 1); } return status; } Module_Status SampleTempCToString(char *cstring,size_t maxLen){ Module_Status status =H0BR4_OK; float temp; if((status =LSM6DS3SampleTempCelsius(&temp)) != H0BR4_OK) return status; temperature=temp; snprintf(cstring,maxLen,"Temp(Celsius) | %0.2f\r\n",temp); return status; } Module_Status StreamGyroDPSToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout){ return StreamMemsToPort(port,module,period,timeout,SampleGyroDPSToPort); } Module_Status StreamGyroDPSToCLI(uint32_t period,uint32_t timeout){ return StreamMemsToCLI(period,timeout,SampleGyroDPSToString); } Module_Status StreamGyroDPSToBuffer(float *buffer,uint32_t period,uint32_t timeout){ return StreamMemsToBuf(buffer,sizeof(*buffer) * 3,period,timeout,SampleGyroDPSToBuf); } Module_Status StreamAccGToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout){ return StreamMemsToPort(port,module,period,timeout,SampleAccGToPort); } Module_Status StreamAccGToCLI(uint32_t period,uint32_t timeout){ return StreamMemsToCLI(period,timeout,SampleAccGToString); } Module_Status StreamAccGToBuffer(float *buffer,uint32_t period,uint32_t timeout){ return StreamMemsToBuf(buffer,sizeof(*buffer) * 3,period,timeout,SampleAccGToBuf); } Module_Status StreamMagMGaussToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout){ return StreamMemsToPort(port,module,period,timeout,SampleMagMGaussToPort); } Module_Status StreamMagMGaussToCLI(uint32_t period,uint32_t timeout){ return StreamMemsToCLI(period,timeout,SampleMagMGaussToString); } Module_Status StreamMagMGaussToBuffer(float *buffer,uint32_t period,uint32_t timeout){ return StreamMemsToBuf(buffer,sizeof(*buffer) * 3,period,timeout,SampleMagMGaussToBuf); } Module_Status StreamTempCToPort(uint8_t port,uint8_t module,uint32_t period,uint32_t timeout){ return StreamMemsToPort(port,module,period,timeout,SampleTempCToPort); } Module_Status StreamTempCToCLI(uint32_t period,uint32_t timeout){ return StreamMemsToCLI(period,timeout,SampleTempCToString); } Module_Status StreamTempCToBuffer(float *buffer,uint32_t period,uint32_t timeout){ return StreamMemsToBuf(buffer,sizeof(*buffer),period,timeout,SampleTempCelsius); } void stopStreamMems(void){ stopStream = true; } /* ----------------------------------------------------------------------- | Commands | ----------------------------------------------------------------------- */ static portBASE_TYPE SampleSensorCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString){ const char *const gyroCmdName ="gyro"; const char *const accCmdName ="acc"; const char *const magCmdName ="mag"; const char *const tempCmdName ="temp"; const char *pSensName = NULL; portBASE_TYPE sensNameLen =0; // Make sure we return something *pcWriteBuffer ='\0'; pSensName =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,1,&sensNameLen); if(pSensName == NULL){ snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Invalid Arguments\r\n"); return pdFALSE; } do{ if(!strncmp(pSensName,gyroCmdName,strlen(gyroCmdName))){ if(SampleGyroDPSToString((char* )pcWriteBuffer,xWriteBufferLen) != H0BR4_OK) break; } else if(!strncmp(pSensName,accCmdName,strlen(accCmdName))){ if(SampleAccGToString((char* )pcWriteBuffer,xWriteBufferLen) != H0BR4_OK) break; } else if(!strncmp(pSensName,magCmdName,strlen(magCmdName))){ if(SampleMagMGaussToString((char* )pcWriteBuffer,xWriteBufferLen) != H0BR4_OK) break; } else if(!strncmp(pSensName,tempCmdName,strlen(tempCmdName))){ if(SampleTempCToString((char* )pcWriteBuffer,xWriteBufferLen) != H0BR4_OK) break; } else{ snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Invalid Arguments\r\n"); } return pdFALSE; } while(0); snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Error reading Sensor\r\n"); return pdFALSE; } // Port Mode => false and CLI Mode => true static bool StreamCommandParser(const int8_t *pcCommandString,const char **ppSensName,portBASE_TYPE *pSensNameLen, bool *pPortOrCLI,uint32_t *pPeriod,uint32_t *pTimeout,uint8_t *pPort,uint8_t *pModule){ const char *pPeriodMSStr = NULL; const char *pTimeoutMSStr = NULL; portBASE_TYPE periodStrLen =0; portBASE_TYPE timeoutStrLen =0; const char *pPortStr = NULL; const char *pModStr = NULL; portBASE_TYPE portStrLen =0; portBASE_TYPE modStrLen =0; *ppSensName =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,1,pSensNameLen); pPeriodMSStr =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,2,&periodStrLen); pTimeoutMSStr =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,3,&timeoutStrLen); // At least 3 Parameters are required! if((*ppSensName == NULL) || (pPeriodMSStr == NULL) || (pTimeoutMSStr == NULL)) return false; // TODO: Check if Period and Timeout are integers or not! *pPeriod =atoi(pPeriodMSStr); *pTimeout =atoi(pTimeoutMSStr); *pPortOrCLI = true; pPortStr =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,4,&portStrLen); pModStr =(const char* )FreeRTOS_CLIGetParameter(pcCommandString,5,&modStrLen); if((pModStr == NULL) && (pPortStr == NULL)) return true; if((pModStr == NULL) || (pPortStr == NULL)) // If user has provided 4 Arguments. return false; *pPort =atoi(pPortStr); *pModule =atoi(pModStr); *pPortOrCLI = false; return true; } static portBASE_TYPE StreamSensorCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString){ const char *const gyroCmdName ="gyro"; const char *const accCmdName ="acc"; const char *const magCmdName ="mag"; const char *const tempCmdName ="temp"; uint32_t period =0; uint32_t timeout =0; uint8_t port =0; uint8_t module =0; bool portOrCLI = true; // Port Mode => false and CLI Mode => true const char *pSensName = NULL; portBASE_TYPE sensNameLen =0; // Make sure we return something *pcWriteBuffer ='\0'; if(!StreamCommandParser(pcCommandString,&pSensName,&sensNameLen,&portOrCLI,&period,&timeout,&port,&module)){ snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Invalid Arguments\r\n"); return pdFALSE; } do{ if(!strncmp(pSensName,gyroCmdName,strlen(gyroCmdName))){ if(portOrCLI){ if(StreamGyroDPSToCLI(period,timeout) != H0BR4_OK) break; } else{ if(StreamGyroDPSToPort(port,module,period,timeout) != H0BR4_OK) break; } } else if(!strncmp(pSensName,accCmdName,strlen(accCmdName))){ if(portOrCLI){ if(StreamAccGToCLI(period,timeout) != H0BR4_OK) break; } else{ if(StreamAccGToPort(port,module,period,timeout) != H0BR4_OK) break; } } else if(!strncmp(pSensName,magCmdName,strlen(magCmdName))){ if(portOrCLI){ if(StreamMagMGaussToCLI(period,timeout) != H0BR4_OK) break; } else{ if(StreamMagMGaussToPort(port,module,period,timeout) != H0BR4_OK) break; } } else if(!strncmp(pSensName,tempCmdName,strlen(tempCmdName))){ if(portOrCLI){ if(StreamTempCToCLI(period,timeout) != H0BR4_OK) break; } else{ if(StreamTempCToPort(port,module,period,timeout) != H0BR4_OK) break; } } else{ snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Invalid Arguments\r\n"); } snprintf((char* )pcWriteBuffer,xWriteBufferLen,"\r\n"); return pdFALSE; } while(0); snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Error reading Sensor\r\n"); return pdFALSE; } static portBASE_TYPE StopStreamCommand(int8_t *pcWriteBuffer,size_t xWriteBufferLen,const int8_t *pcCommandString){ // Make sure we return something pcWriteBuffer[0] ='\0'; snprintf((char* )pcWriteBuffer,xWriteBufferLen,"Stopping Streaming MEMS...\r\n"); stopStreamMems(); return pdFALSE; } /* --- Save array topology and Command Snippets in Flash RO --- */ uint8_t SaveToRO(void){ BOS_Status result =BOS_OK; HAL_StatusTypeDef FlashStatus =HAL_OK; uint16_t add =2, temp =0; uint8_t snipBuffer[sizeof(snippet_t) + 1] ={0}; HAL_FLASH_Unlock(); /* Erase RO area */ FLASH_PageErase(RO_START_ADDRESS); FlashStatus =FLASH_WaitForLastOperation((uint32_t )HAL_FLASH_TIMEOUT_VALUE); if(FlashStatus != HAL_OK){ return pFlash.ErrorCode; } else{ /* Operation is completed, disable the PER Bit */ CLEAR_BIT(FLASH->CR,FLASH_CR_PER); } /* Save number of modules and myID */ if(myID){ temp =(uint16_t )(N << 8) + myID; HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,RO_START_ADDRESS,temp); FlashStatus =FLASH_WaitForLastOperation((uint32_t )HAL_FLASH_TIMEOUT_VALUE); if(FlashStatus != HAL_OK){ return pFlash.ErrorCode; } else{ /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR,FLASH_CR_PG); } /* Save topology */ for(uint8_t i =1; i <= N; i++){ for(uint8_t j =0; j <= MaxNumOfPorts; j++){ if(array[i - 1][0]){ HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,RO_START_ADDRESS + add,array[i - 1][j]); add +=2; FlashStatus =FLASH_WaitForLastOperation((uint32_t )HAL_FLASH_TIMEOUT_VALUE); if(FlashStatus != HAL_OK){ return pFlash.ErrorCode; } else{ /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR,FLASH_CR_PG); } } } } } // Save Command Snippets int currentAdd = RO_MID_ADDRESS; for(uint8_t s =0; s < numOfRecordedSnippets; s++){ if(snippets[s].cond.conditionType){ snipBuffer[0] =0xFE; // A marker to separate Snippets memcpy((uint8_t* )&snipBuffer[1],(uint8_t* )&snippets[s],sizeof(snippet_t)); // Copy the snippet struct buffer (20 x numOfRecordedSnippets). Note this is assuming sizeof(snippet_t) is even. for(uint8_t j =0; j < (sizeof(snippet_t) / 2); j++){ HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,currentAdd,*(uint16_t* )&snipBuffer[j * 2]); FlashStatus =FLASH_WaitForLastOperation((uint32_t )HAL_FLASH_TIMEOUT_VALUE); if(FlashStatus != HAL_OK){ return pFlash.ErrorCode; } else{ /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR,FLASH_CR_PG); currentAdd +=2; } } // Copy the snippet commands buffer. Always an even number. Note the string termination char might be skipped for(uint8_t j =0; j < ((strlen(snippets[s].cmd) + 1) / 2); j++){ HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,currentAdd,*(uint16_t* )(snippets[s].cmd + j * 2)); FlashStatus =FLASH_WaitForLastOperation((uint32_t )HAL_FLASH_TIMEOUT_VALUE); if(FlashStatus != HAL_OK){ return pFlash.ErrorCode; } else{ /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR,FLASH_CR_PG); currentAdd +=2; } } } } HAL_FLASH_Lock(); return result; } /* --- Clear array topology in SRAM and Flash RO --- */ uint8_t ClearROtopology(void){ // Clear the array memset(array,0,sizeof(array)); N =1; myID =0; return SaveToRO(); } /*-----------------------------------------------------------*/ /************************ (C) COPYRIGHT HEXABITZ *****END OF FILE****/
HexabitzPlatform/H0BR4x-Firmware
H0BR4/H0BR4_i2c.h
<reponame>HexabitzPlatform/H0BR4x-Firmware /* BitzOS (BOS) V0.2.5 - Copyright (C) 2017-2021 Hexabitz All rights reserved File Name : H08R6_i2c.h Description : This file contains all the functions prototypes for the i2c */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __i2c_H #define __i2c_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal.h" extern I2C_HandleTypeDef hi2c2; extern void MX_I2C_Init(void); extern void MX_I2C2_Init(void); #ifdef __cplusplus } #endif #endif /*__i2c_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
HexabitzPlatform/H0BR4x-Firmware
H0BR4/H0BR4_i2c.c
<reponame>HexabitzPlatform/H0BR4x-Firmware /* BitzOS (BOS) V0.2.5 - Copyright (C) 2017-2021 Hexabitz All rights reserved File Name : H0BR4_i2c.c Description : This file provides code for the configuration of the I2C instances. */ /* Includes ------------------------------------------------------------------*/ #include "BOS.h" #include "LSM6DS3.h" #include "LSM303AGR_ACC.h" #include "LSM303AGR_MAG.h" I2C_HandleTypeDef hi2c2; /*----------------------------------------------------------------------------*/ /* Configure I2C */ /*----------------------------------------------------------------------------*/ void MX_I2C_Init(void); void MX_I2C2_Init(void); /** I2C Configuration */ void MX_I2C_Init(void){ /* GPIO Ports Clock Enable */ __GPIOC_CLK_ENABLE() ; __GPIOA_CLK_ENABLE() ; __GPIOD_CLK_ENABLE() ; __GPIOB_CLK_ENABLE() ; __GPIOF_CLK_ENABLE() ; // for HSE and Boot0 MX_I2C2_Init(); } //-- Configure indicator LED void MX_I2C2_Init(void){ hi2c2.Instance = I2C2; /* hi2c2.Init.Timing = 0x2010091A; *//* fast mode: 400 KHz */ hi2c2.Init.Timing =0x20303E5D; /* Standard mode: 100 KHz */ hi2c2.Init.OwnAddress1 =0; hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c2.Init.OwnAddress2 =0; hi2c2.Init.OwnAddress2Masks = I2C_OA2_NOMASK; hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; HAL_I2C_Init(&hi2c2); /** Configure Analogue filter */ HAL_I2CEx_ConfigAnalogFilter(&hi2c2,I2C_ANALOGFILTER_ENABLE); /** Configure Digital filter */ HAL_I2CEx_ConfigDigitalFilter(&hi2c2,0); } uint8_t LSM6DS3_I2C_Write(void *handle,uint8_t WriteAddr,uint8_t *pBuffer,uint16_t nBytesToWrite){ if(HAL_I2C_Mem_Write(handle,LSM6DS3_ACC_GYRO_I2C_ADDRESS_HIGH,WriteAddr,sizeof(WriteAddr),pBuffer,nBytesToWrite,100) != HAL_OK){ return 1; } return 0; } uint8_t LSM6DS3_I2C_Read(void *handle,uint8_t ReadAddr,uint8_t *pBuffer,uint16_t nBytesToRead){ if(HAL_I2C_Mem_Read(handle,LSM6DS3_ACC_GYRO_I2C_ADDRESS_HIGH,ReadAddr,sizeof(ReadAddr),pBuffer,nBytesToRead,100) != HAL_OK){ return 1; } return 0; } uint8_t LSM303AGR_ACC_I2C_Write(void *handle,uint8_t WriteAddr,uint8_t *pBuffer,uint16_t nBytesToWrite){ if(HAL_I2C_Mem_Write(handle,LSM303AGR_ACC_I2C_ADDRESS,WriteAddr,sizeof(WriteAddr),pBuffer,nBytesToWrite,100) != HAL_OK){ return 1; } return 0; } uint8_t LSM303AGR_ACC_I2C_Read(void *handle,uint8_t ReadAddr,uint8_t *pBuffer,uint16_t nBytesToRead){ if(HAL_I2C_Mem_Read(handle,LSM303AGR_ACC_I2C_ADDRESS,ReadAddr,sizeof(ReadAddr),pBuffer,nBytesToRead,100) != HAL_OK){ return 1; } return 0; } uint8_t LSM303AGR_MAG_I2C_Write(void *handle,uint8_t WriteAddr,uint8_t *pBuffer,uint16_t nBytesToWrite){ if(HAL_I2C_Mem_Write(handle,LSM303AGR_MAG_I2C_ADDRESS,WriteAddr,sizeof(WriteAddr),pBuffer,nBytesToWrite,100) != HAL_OK){ return 1; } return 0; } uint8_t LSM303AGR_MAG_I2C_Read(void *handle,uint8_t ReadAddr,uint8_t *pBuffer,uint16_t nBytesToRead){ if(HAL_I2C_Mem_Read(handle,LSM303AGR_MAG_I2C_ADDRESS,ReadAddr,sizeof(ReadAddr),pBuffer,nBytesToRead,100) != HAL_OK){ return 1; } return 0; } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
84KaliPleXon3/sslstrip-hsts-openwrt
python2.7/site-packages/twisted/internet/iocpreactor/_iocp.c
#include <Python.h> #include <winsock2.h> #include <mswsock.h> #include <windows.h> #include "structmember.h" static int g_imallocs, g_ifrees, g_amallocs, g_afrees; static int g_incobj, g_decobj, g_incarg, g_decarg; static PyObject * callWithLogger; //#define SPEW // compensate for mingw's (and MSVC6's) lack of recent Windows headers #ifndef WSAID_CONNECTEX #define WSAID_CONNECTEX {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}} #define WSAID_ACCEPTEX {0xb5367df1,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}} typedef BOOL (PASCAL FAR * LPFN_CONNECTEX) ( IN SOCKET s, IN const struct sockaddr FAR *name, IN int namelen, IN PVOID lpSendBuffer OPTIONAL, IN DWORD dwSendDataLength, OUT LPDWORD lpdwBytesSent, IN LPOVERLAPPED lpOverlapped ); typedef BOOL (PASCAL FAR * LPFN_ACCEPTEX)( IN SOCKET sListenSocket, IN SOCKET sAcceptSocket, IN PVOID lpOutputBuffer, IN DWORD dwReceiveDataLength, IN DWORD dwLocalAddressLength, IN DWORD dwRemoteAddressLength, OUT LPDWORD lpdwBytesReceived, IN LPOVERLAPPED lpOverlapped ); #endif typedef struct { int size; char buffer[0]; } AddrBuffer; LPFN_CONNECTEX gConnectEx; LPFN_ACCEPTEX gAcceptEx; typedef struct { OVERLAPPED ov; PyObject *callback; PyObject *callback_arg; } MyOVERLAPPED; typedef struct { PyObject_HEAD // PyObject *cur_ops; HANDLE iocp; } iocpcore; void CALLBACK dummy_completion(DWORD err, DWORD bytes, OVERLAPPED *ov, DWORD flags) { } static void iocpcore_dealloc(iocpcore *self) { // PyDict_Clear(self->cur_ops); // Py_DECREF(self->cur_ops); CloseHandle(self->iocp); self->ob_type->tp_free((PyObject*)self); } /* static PyObject * iocpcore_getattr(iocpcore *self, char *name) { if(!strcmp(name, "have_connectex } */ static PyObject * iocpcore_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { iocpcore *self; self = (iocpcore *)type->tp_alloc(type, 0); if(self != NULL) { self->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if(!self->iocp) { Py_DECREF(self); return PyErr_SetFromWindowsErr(0); } // self->cur_ops = PyDict_New(); // if(!self->cur_ops) { // CloseHandle(self->iocp); // Py_DECREF(self); // return NULL; // } } return (PyObject *)self; } static PyObject *iocpcore_doIteration(iocpcore* self, PyObject *args) { long timeout; double ftimeout; PyObject *tm, *ret, *object, *object_arg; DWORD bytes; unsigned long key; MyOVERLAPPED *ov; int res, err; if(!PyArg_ParseTuple(args, "d", &ftimeout)) { PyErr_Clear(); if(!PyArg_ParseTuple(args, "O", &tm)) { return NULL; } if(tm == Py_None) { // Default to 0.1 like other reactors do. timeout = (int)(0.1 * 1000); } else { PyErr_SetString(PyExc_TypeError, "Wrong timeout argument"); return NULL; } } else { timeout = (int)(ftimeout * 1000); } Py_BEGIN_ALLOW_THREADS; res = GetQueuedCompletionStatus(self->iocp, &bytes, &key, (OVERLAPPED**)&ov, timeout); Py_END_ALLOW_THREADS; #ifdef SPEW printf("gqcs returned res %d, ov 0x%p\n", res, ov); #endif err = GetLastError(); #ifdef SPEW printf(" GLE returned %d\n", err); #endif if(!res) { if(!ov) { #ifdef SPEW printf("gqcs returned NULL ov\n"); #endif if(err != WAIT_TIMEOUT) { return PyErr_SetFromWindowsErr(err); } else { return Py_BuildValue(""); } } } // At this point, ov is non-NULL // steal its reference, then clobber it to death! I mean free it! object = ov->callback; object_arg = ov->callback_arg; if(object) { // this is retarded. GQCS only sets error value if it wasn't succesful // (what about forth case, when handle is closed?) if(res) { err = 0; } #ifdef SPEW printf("calling callback with err %d, bytes %ld\n", err, bytes); #endif /* def callWithLogger(logger, func, *args, **kw) */ ret = PyObject_CallFunction(callWithLogger, "OOllO", self, object, err, bytes, object_arg); if(!ret) { Py_DECREF(object); g_decobj++; PyMem_Free(ov); g_ifrees++; return NULL; } Py_DECREF(ret); Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; } PyMem_Free(ov); g_ifrees++; return Py_BuildValue(""); } static PyObject *iocpcore_WriteFile(iocpcore* self, PyObject *args) { HANDLE handle; char *buf; int buflen, res; DWORD err, bytes; PyObject *object, *object_arg; MyOVERLAPPED *ov; // LARGE_INTEGER time, time_after; // QueryPerformanceCounter(&time); if(!PyArg_ParseTuple(args, "lt#OO", &handle, &buf, &buflen, &object, &object_arg)) { return NULL; } if(buflen <= 0) { PyErr_SetString(PyExc_ValueError, "Invalid length specified"); return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; CreateIoCompletionPort(handle, self->iocp, 0, 1); #ifdef SPEW printf("calling WriteFile(%p, 0x%p, %d, 0x%p, 0x%p)\n", handle, buf, buflen, &bytes, ov); #endif Py_BEGIN_ALLOW_THREADS; res = WriteFile(handle, buf, buflen, &bytes, (OVERLAPPED *)ov); Py_END_ALLOW_THREADS; err = GetLastError(); #ifdef SPEW printf(" wf returned %d, err %ld\n", res, err); #endif if(!res && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(res) { err = 0; } // QueryPerformanceCounter(&time_after); // printf("wf total ticks is %ld", time_after.LowPart - time.LowPart); return Py_BuildValue("ll", err, bytes); } static PyObject *iocpcore_ReadFile(iocpcore* self, PyObject *args) { HANDLE handle; char *buf; int buflen, res; DWORD err, bytes; PyObject *object, *object_arg; MyOVERLAPPED *ov; // LARGE_INTEGER time, time_after; // QueryPerformanceCounter(&time); if(!PyArg_ParseTuple(args, "lw#OO", &handle, &buf, &buflen, &object, &object_arg)) { return NULL; } if(buflen <= 0) { PyErr_SetString(PyExc_ValueError, "Invalid length specified"); return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; CreateIoCompletionPort(handle, self->iocp, 0, 1); #ifdef SPEW printf("calling ReadFile(%p, 0x%p, %d, 0x%p, 0x%p)\n", handle, buf, buflen, &bytes, ov); #endif Py_BEGIN_ALLOW_THREADS; res = ReadFile(handle, buf, buflen, &bytes, (OVERLAPPED *)ov); Py_END_ALLOW_THREADS; err = GetLastError(); #ifdef SPEW printf(" rf returned %d, err %ld\n", res, err); #endif if(!res && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(res) { err = 0; } // QueryPerformanceCounter(&time_after); // printf("rf total ticks is %ld", time_after.LowPart - time.LowPart); return Py_BuildValue("ll", err, bytes); } // yay, rape'n'paste of getsockaddrarg from socketmodule.c. "I couldn't understand what it does, so I removed it!" static int makesockaddr(int sock_family, PyObject *args, struct sockaddr **addr_ret, int *len_ret) { switch (sock_family) { case AF_INET: { struct sockaddr_in* addr; char *host; int port; unsigned long result; if(!PyTuple_Check(args)) { PyErr_Format(PyExc_TypeError, "AF_INET address must be tuple, not %.500s", args->ob_type->tp_name); return 0; } if(!PyArg_ParseTuple(args, "si", &host, &port)) { return 0; } addr = PyMem_Malloc(sizeof(struct sockaddr_in)); g_amallocs++; result = inet_addr(host); if(result == -1) { PyMem_Free(addr); g_afrees++; PyErr_SetString(PyExc_ValueError, "Can't parse ip address string"); return 0; } #ifdef SPEW printf("makesockaddr setting addr, %lu, %d, %hu\n", result, AF_INET, htons((short)port)); #endif addr->sin_addr.s_addr = result; addr->sin_family = AF_INET; addr->sin_port = htons((short)port); *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } default: PyErr_SetString(PyExc_ValueError, "bad family"); return 0; } } static PyObject *iocpcore_WSASendTo(iocpcore* self, PyObject *args) { HANDLE handle; char *buf; int buflen, res, family, addrlen; DWORD err, bytes, flags = 0; PyObject *object, *object_arg, *address; MyOVERLAPPED *ov; WSABUF wbuf; struct sockaddr *addr; // LARGE_INTEGER time, time_after; // QueryPerformanceCounter(&time); if(!PyArg_ParseTuple(args, "lt#iOOO", &handle, &buf, &buflen, &family, &address, &object, &object_arg)) { return NULL; } if(buflen <= 0) { PyErr_SetString(PyExc_ValueError, "Invalid length specified"); return NULL; } if(!makesockaddr(family, address, &addr, &addrlen)) { return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; wbuf.len = buflen; wbuf.buf = buf; CreateIoCompletionPort(handle, self->iocp, 0, 1); #ifdef SPEW printf("calling WSASendTo(%d, 0x%p, %d, 0x%p, %ld, 0x%p, %d, 0x%p, 0x%p)\n", handle, &wbuf, 1, &bytes, flags, addr, addrlen, ov, NULL); #endif Py_BEGIN_ALLOW_THREADS; res = WSASendTo((SOCKET)handle, &wbuf, 1, &bytes, flags, addr, addrlen, (OVERLAPPED *)ov, NULL); Py_END_ALLOW_THREADS; err = GetLastError(); #ifdef SPEW printf(" wst returned %d, err %ld\n", res, err); #endif if(res == SOCKET_ERROR && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(!res) { err = 0; } // QueryPerformanceCounter(&time_after); // printf("st total ticks is %ld", time_after.LowPart - time.LowPart); return Py_BuildValue("ll", err, bytes); } static PyObject *iocpcore_WSARecvFrom(iocpcore* self, PyObject *args) { HANDLE handle; char *buf; int buflen, res, ablen; DWORD err, bytes, flags = 0; PyObject *object, *object_arg; MyOVERLAPPED *ov; WSABUF wbuf; AddrBuffer *ab; // LARGE_INTEGER time, time_after; // QueryPerformanceCounter(&time); if(!PyArg_ParseTuple(args, "lw#w#OO", &handle, &buf, &buflen, &ab, &ablen, &object, &object_arg)) { return NULL; } if(buflen <= 0) { PyErr_SetString(PyExc_ValueError, "Invalid length specified"); return NULL; } if(ablen < sizeof(int)+sizeof(struct sockaddr)) { PyErr_SetString(PyExc_ValueError, "Address buffer too small"); return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; wbuf.len = buflen; wbuf.buf = buf; ab->size = ablen; CreateIoCompletionPort(handle, self->iocp, 0, 1); #ifdef SPEW printf("calling WSARecvFrom(%d, 0x%p, %d, 0x%p, 0x%p, 0x%p, 0x%p, 0x%p, 0x%p)\n", handle, &wbuf, 1, &bytes, &flags, (struct sockaddr *)ab->buffer, &ab->size, ov, NULL); #endif Py_BEGIN_ALLOW_THREADS; res = WSARecvFrom((SOCKET)handle, &wbuf, 1, &bytes, &flags, (struct sockaddr *)ab->buffer, &ab->size, (OVERLAPPED *)ov, NULL); Py_END_ALLOW_THREADS; err = GetLastError(); #ifdef SPEW printf(" wrf returned %d, err %ld\n", res, err); #endif if(res == SOCKET_ERROR && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(!res) { err = 0; } // QueryPerformanceCounter(&time_after); // printf("wrf total ticks is %ld", time_after.LowPart - time.LowPart); return Py_BuildValue("ll", err, bytes); } // rape'n'paste from socketmodule.c static PyObject *parsesockaddr(struct sockaddr *addr, int addrlen) { PyObject *ret = NULL; if (addrlen == 0) { /* No address -- may be recvfrom() from known socket */ Py_INCREF(Py_None); return Py_None; } switch (addr->sa_family) { case AF_INET: { struct sockaddr_in *a = (struct sockaddr_in *)addr; char *s; s = inet_ntoa(a->sin_addr); if (s) { ret = Py_BuildValue("si", s, ntohs(a->sin_port)); } else { PyErr_SetString(PyExc_ValueError, "Invalid AF_INET address"); } return ret; } default: /* If we don't know the address family, don't raise an exception -- return it as a tuple. */ return Py_BuildValue("is#", addr->sa_family, addr->sa_data, sizeof(addr->sa_data)); } } static PyObject *iocpcore_interpretAB(iocpcore* self, PyObject *args) { char *buf; int len; AddrBuffer *ab; if(!PyArg_ParseTuple(args, "t#", &buf, &len)) { return NULL; } ab = (AddrBuffer *)buf; return parsesockaddr((struct sockaddr *)(ab->buffer), ab->size); } static PyObject *iocpcore_getsockinfo(iocpcore* self, PyObject *args) { SOCKET handle; WSAPROTOCOL_INFO pinfo; int size = sizeof(pinfo), res; if(!PyArg_ParseTuple(args, "l", &handle)) { return NULL; } res = getsockopt(handle, SOL_SOCKET, SO_PROTOCOL_INFO, (char *)&pinfo, &size); if(res == SOCKET_ERROR) { return PyErr_SetFromWindowsErr(0); } return Py_BuildValue("iiii", pinfo.iMaxSockAddr, pinfo.iAddressFamily, pinfo.iSocketType, pinfo.iProtocol); } static PyObject *iocpcore_AcceptEx(iocpcore* self, PyObject *args) { SOCKET handle, acc_sock; char *buf; int buflen, res; DWORD bytes, err; PyObject *object, *object_arg; MyOVERLAPPED *ov; if(!PyArg_ParseTuple(args, "llOOw#", &handle, &acc_sock, &object, &object_arg, &buf, &buflen)) { return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; CreateIoCompletionPort((HANDLE)handle, self->iocp, 0, 1); #ifdef SPEW printf("calling AcceptEx(%d, %d, 0x%p, %d, %d, %d, 0x%p, 0x%p)\n", handle, acc_sock, buf, 0, buflen/2, buflen/2, &bytes, ov); #endif Py_BEGIN_ALLOW_THREADS; res = gAcceptEx(handle, acc_sock, buf, 0, buflen/2, buflen/2, &bytes, (OVERLAPPED *)ov); Py_END_ALLOW_THREADS; err = WSAGetLastError(); #ifdef SPEW printf(" ae returned %d, err %ld\n", res, err); #endif if(!res && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(res) { err = 0; } return Py_BuildValue("ll", err, 0); } static PyObject *iocpcore_ConnectEx(iocpcore* self, PyObject *args) { SOCKET handle; int res, addrlen, family; DWORD err; PyObject *object, *object_arg, *address; MyOVERLAPPED *ov; struct sockaddr *addr; if(!PyArg_ParseTuple(args, "liOOO", &handle, &family, &address, &object, &object_arg)) { return NULL; } if(!makesockaddr(family, address, &addr, &addrlen)) { return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; CreateIoCompletionPort((HANDLE)handle, self->iocp, 0, 1); #ifdef SPEW printf("calling ConnectEx(%d, 0x%p, %d, 0x%p)\n", handle, addr, addrlen, ov); #endif Py_BEGIN_ALLOW_THREADS; res = gConnectEx(handle, addr, addrlen, NULL, 0, NULL, (OVERLAPPED *)ov); Py_END_ALLOW_THREADS; PyMem_Free(addr); g_afrees++; err = WSAGetLastError(); #ifdef SPEW printf(" ce returned %d, err %ld\n", res, err); #endif if(!res && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(res) { err = 0; } return Py_BuildValue("ll", err, 0); } static PyObject *iocpcore_PostQueuedCompletionStatus(iocpcore* self, PyObject *args) { int res; DWORD err; PyObject *object, *object_arg; MyOVERLAPPED *ov; if(!PyArg_ParseTuple(args, "OO", &object, &object_arg)) { return NULL; } if(!PyCallable_Check(object)) { PyErr_SetString(PyExc_TypeError, "Callback must be callable"); return NULL; } ov = PyMem_Malloc(sizeof(MyOVERLAPPED)); g_imallocs++; if(!ov) { PyErr_NoMemory(); return NULL; } memset(ov, 0, sizeof(MyOVERLAPPED)); Py_INCREF(object); g_incobj++; Py_INCREF(object_arg); g_incarg++; ov->callback = object; ov->callback_arg = object_arg; #ifdef SPEW printf("calling PostQueuedCompletionStatus(0x%p)\n", ov); #endif Py_BEGIN_ALLOW_THREADS; res = PostQueuedCompletionStatus(self->iocp, 0, 0, (OVERLAPPED *)ov); Py_END_ALLOW_THREADS; err = WSAGetLastError(); #ifdef SPEW printf(" pqcs returned %d, err %ld\n", res, err); #endif if(!res && err != ERROR_IO_PENDING) { Py_DECREF(object); g_decobj++; Py_DECREF(object_arg); g_decarg++; PyMem_Free(ov); g_ifrees++; return PyErr_SetFromWindowsErr(err); } if(res) { err = 0; } return Py_BuildValue("ll", err, 0); } PyObject *iocpcore_AllocateReadBuffer(PyObject *self, PyObject *args) { int bufSize; if(!PyArg_ParseTuple(args, "i", &bufSize)) { return NULL; } return PyBuffer_New(bufSize); } PyObject *iocpcore_get_mstats(PyObject *self, PyObject *args) { if(!PyArg_ParseTuple(args, "")) { return NULL; } return Py_BuildValue("(ii)(ii)(ii)(ii)", g_imallocs, g_ifrees, g_amallocs, g_afrees, g_incobj, g_decobj, g_incarg, g_decarg); } static PyMethodDef iocpcore_methods[] = { {"doIteration", (PyCFunction)iocpcore_doIteration, METH_VARARGS, "Perform one event loop iteration"}, {"issueWriteFile", (PyCFunction)iocpcore_WriteFile, METH_VARARGS, "Issue an overlapped WriteFile operation"}, {"issueReadFile", (PyCFunction)iocpcore_ReadFile, METH_VARARGS, "Issue an overlapped ReadFile operation"}, {"issueWSASendTo", (PyCFunction)iocpcore_WSASendTo, METH_VARARGS, "Issue an overlapped WSASendTo operation"}, {"issueWSARecvFrom", (PyCFunction)iocpcore_WSARecvFrom, METH_VARARGS, "Issue an overlapped WSARecvFrom operation"}, {"interpretAB", (PyCFunction)iocpcore_interpretAB, METH_VARARGS, "Interpret address buffer as returned by WSARecvFrom"}, {"issueAcceptEx", (PyCFunction)iocpcore_AcceptEx, METH_VARARGS, "Issue an overlapped AcceptEx operation"}, {"issueConnectEx", (PyCFunction)iocpcore_ConnectEx, METH_VARARGS, "Issue an overlapped ConnectEx operation"}, {"issuePostQueuedCompletionStatus", (PyCFunction)iocpcore_PostQueuedCompletionStatus, METH_VARARGS, "Issue an overlapped PQCS operation"}, {"getsockinfo", (PyCFunction)iocpcore_getsockinfo, METH_VARARGS, "Given a socket handle, retrieve its protocol info"}, {"AllocateReadBuffer", (PyCFunction)iocpcore_AllocateReadBuffer, METH_VARARGS, "Allocate a buffer to read into"}, {"get_mstats", (PyCFunction)iocpcore_get_mstats, METH_VARARGS, "Get memory leak statistics"}, {NULL} }; static PyTypeObject iocpcoreType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "_iocp.iocpcore", /*tp_name*/ sizeof(iocpcore), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)iocpcore_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ // (getattrfunc)iocpcore_getattr, /*tp_getattr*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "core functionality for IOCP reactor", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ iocpcore_methods, /* tp_methods */ // iocpcore_members, /* tp_members */ 0, /* tp_members */ // iocpcore_getseters, /* tp_getset */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ // (initproc)iocpcore_init, /* tp_init */ 0, /* tp_init */ 0, /* tp_alloc */ iocpcore_new, /* tp_new */ }; static PyMethodDef module_methods[] = { {NULL} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC init_iocp(void) { int have_connectex = 1; PyObject *m; PyObject *tp_log; GUID guid1 = WSAID_CONNECTEX; // should use one GUID variable, but oh well GUID guid2 = WSAID_ACCEPTEX; DWORD bytes, ret; SOCKET s; if(PyType_Ready(&iocpcoreType) < 0) { return; } m = PyImport_ImportModule("_socket"); // cause WSAStartup to get called if(!m) { return; } Py_DECREF(m); s = socket(AF_INET, SOCK_STREAM, 0); ret = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid1, sizeof(GUID), &gConnectEx, sizeof(gConnectEx), &bytes, NULL, NULL); if(ret == SOCKET_ERROR) { have_connectex = 0; } ret = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid2, sizeof(GUID), &gAcceptEx, sizeof(gAcceptEx), &bytes, NULL, NULL); if(ret == SOCKET_ERROR) { PyErr_SetFromWindowsErr(0); return; } closesocket(s); /* Grab twisted.python.log.callWithLogger */ tp_log = PyImport_ImportModule("twisted.python.log"); if (!tp_log) { return; } callWithLogger = PyObject_GetAttrString(tp_log, "callWithLogger"); Py_DECREF(tp_log); if (!callWithLogger) { return; } m = Py_InitModule3("_iocp", module_methods, "core functionality for IOCP reactor"); if(!m) { return; } ret = PyModule_AddIntConstant(m, "have_connectex", have_connectex); if(ret == -1) { return; } Py_INCREF(&iocpcoreType); PyModule_AddObject(m, "iocpcore", (PyObject *)&iocpcoreType); }
84KaliPleXon3/sslstrip-hsts-openwrt
python2.7/site-packages/twisted/python/_epoll.c
<gh_stars>100-1000 /* Generated by Pyrex 0.9.4.1 on Sun Oct 15 15:04:09 2006 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) PyInt_AsLong(o) #endif #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif __PYX_EXTERN_C double pow(double, double); #include "stdio.h" #include "errno.h" #include "string.h" #include "stdint.h" #include "sys/epoll.h" typedef struct {const char *s; const void **p;} __Pyx_CApiTabEntry; /*proto*/ typedef struct {PyObject **p; char *s;} __Pyx_InternTabEntry; /*proto*/ typedef struct {PyObject **p; char *s; long n;} __Pyx_StringTabEntry; /*proto*/ static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t); /*proto*/ static int __Pyx_EndUnpack(PyObject *, Py_ssize_t); /*proto*/ static int __Pyx_PrintItem(PyObject *); /*proto*/ static int __Pyx_PrintNewline(void); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static void __Pyx_ReRaise(void); /*proto*/ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ static PyObject *__Pyx_GetExcValue(void); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name); /*proto*/ static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static int __Pyx_GetStarArgs(PyObject **args, PyObject **kwds, char *kwd_list[], Py_ssize_t nargs, PyObject **args2, PyObject **kwds2); /*proto*/ static void __Pyx_WriteUnraisable(char *name); /*proto*/ static void __Pyx_AddTraceback(char *funcname); /*proto*/ static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ static int __Pyx_GetVtable(PyObject *dict, void *vtabptr); /*proto*/ static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, char *modname); /*proto*/ static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ static int __Pyx_InitCApi(PyObject *module); /*proto*/ static int __Pyx_ImportModuleCApi(__Pyx_CApiTabEntry *t); /*proto*/ static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static PyObject *__pyx_m; static PyObject *__pyx_b; static int __pyx_lineno; static char *__pyx_filename; static char **__pyx_f; static char __pyx_mdoc[] = "\nInterface to epoll I/O event notification facility.\n"; /* Declarations from _epoll */ struct __pyx_obj_6_epoll_epoll { PyObject_HEAD int fd; int initialized; }; static PyTypeObject *__pyx_ptype_6_epoll_epoll = 0; /* Implementation of _epoll */ static PyObject *__pyx_n_CTL_ADD; static PyObject *__pyx_n_CTL_DEL; static PyObject *__pyx_n_CTL_MOD; static PyObject *__pyx_n_IN; static PyObject *__pyx_n_OUT; static PyObject *__pyx_n_PRI; static PyObject *__pyx_n_ERR; static PyObject *__pyx_n_HUP; static PyObject *__pyx_n_ET; static PyObject *__pyx_n_RDNORM; static PyObject *__pyx_n_RDBAND; static PyObject *__pyx_n_WRNORM; static PyObject *__pyx_n_WRBAND; static PyObject *__pyx_n_MSG; static PyObject *__pyx_n_IOError; static int __pyx_f_6_epoll_5epoll___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_6_epoll_5epoll___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_size; int __pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; static char *__pyx_argnames[] = {"size",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "i", __pyx_argnames, &__pyx_v_size)) return -1; Py_INCREF(__pyx_v_self); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":77 */ ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd = epoll_create(__pyx_v_size); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":78 */ __pyx_1 = (((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd == (-1)); if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":79 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_IOError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} __pyx_3 = PyInt_FromLong(errno); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} __pyx_4 = PyString_FromString(strerror(errno)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_3 = PyObject_Call(__pyx_2, __pyx_5, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":80 */ ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->initialized = 1; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); Py_XDECREF(__pyx_5); __Pyx_AddTraceback("_epoll.epoll.__init__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static void __pyx_f_6_epoll_5epoll___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_f_6_epoll_5epoll___dealloc__(PyObject *__pyx_v_self) { int __pyx_1; Py_INCREF(__pyx_v_self); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":83 */ __pyx_1 = ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->initialized; if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":84 */ close(((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":85 */ ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->initialized = 0; goto __pyx_L2; } __pyx_L2:; goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("_epoll.epoll.__dealloc__"); __pyx_L0:; Py_DECREF(__pyx_v_self); } static PyObject *__pyx_f_6_epoll_5epoll_close(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6_epoll_5epoll_close[] = "\n Close the epoll file descriptor.\n "; static PyObject *__pyx_f_6_epoll_5epoll_close(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":91 */ __pyx_1 = ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->initialized; if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":92 */ __pyx_1 = (close(((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd) == (-1)); if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":93 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_IOError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_3 = PyInt_FromLong(errno); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_4 = PyString_FromString(strerror(errno)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_3 = PyObject_Call(__pyx_2, __pyx_5, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} goto __pyx_L3; } __pyx_L3:; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":94 */ ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->initialized = 0; goto __pyx_L2; } __pyx_L2:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); Py_XDECREF(__pyx_5); __Pyx_AddTraceback("_epoll.epoll.close"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_6_epoll_5epoll_fileno(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6_epoll_5epoll_fileno[] = "\n Return the epoll file descriptor number.\n "; static PyObject *__pyx_f_6_epoll_5epoll_fileno(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":100 */ __pyx_1 = PyInt_FromLong(((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; goto __pyx_L1;} __pyx_r = __pyx_1; __pyx_1 = 0; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("_epoll.epoll.fileno"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_6_epoll_5epoll__control(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6_epoll_5epoll__control[] = "\n Modify the monitored state of a particular file descriptor.\n \n Wrap epoll_ctl(2).\n\n @type op: C{int}\n @param op: One of CTL_ADD, CTL_DEL, or CTL_MOD\n\n @type fd: C{int}\n @param fd: File descriptor to modify\n\n @type events: C{int}\n @param events: A bit set of IN, OUT, PRI, ERR, HUP, and ET.\n\n @raise IOError: Raised if the underlying epoll_ctl() call fails.\n "; static PyObject *__pyx_f_6_epoll_5epoll__control(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_op; int __pyx_v_fd; int __pyx_v_events; int __pyx_v_result; struct epoll_event __pyx_v_evt; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; static char *__pyx_argnames[] = {"op","fd","events",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "iii", __pyx_argnames, &__pyx_v_op, &__pyx_v_fd, &__pyx_v_events)) return 0; Py_INCREF(__pyx_v_self); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":121 */ __pyx_v_evt.events = __pyx_v_events; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":122 */ __pyx_v_evt.data.fd = __pyx_v_fd; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":123 */ __pyx_v_result = epoll_ctl(((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd,__pyx_v_op,__pyx_v_fd,(&__pyx_v_evt)); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":124 */ __pyx_1 = (__pyx_v_result == (-1)); if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":125 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_IOError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} __pyx_3 = PyInt_FromLong(errno); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} __pyx_4 = PyString_FromString(strerror(errno)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_3 = PyObject_Call(__pyx_2, __pyx_5, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); Py_XDECREF(__pyx_5); __Pyx_AddTraceback("_epoll.epoll._control"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_n_append; static PyObject *__pyx_f_6_epoll_5epoll_wait(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6_epoll_5epoll_wait[] = "\n Wait for an I/O event, wrap epoll_wait(2).\n\n @type maxevents: C{int}\n @param maxevents: Maximum number of events returned.\n\n @type timeout: C{int}\n @param timeout: Maximum time waiting for events. 0 makes it return\n immediately whereas -1 makes it wait indefinitely.\n \n @raise IOError: Raised if the underlying epoll_wait() call fails.\n "; static PyObject *__pyx_f_6_epoll_5epoll_wait(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { unsigned int __pyx_v_maxevents; int __pyx_v_timeout; struct epoll_event (*__pyx_v_events); int __pyx_v_result; int __pyx_v_nbytes; int __pyx_v_fd; PyThreadState (*__pyx_v__save); PyObject *__pyx_v_results; PyObject *__pyx_v_i; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; long __pyx_6; Py_ssize_t __pyx_7; static char *__pyx_argnames[] = {"maxevents","timeout",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "Ii", __pyx_argnames, &__pyx_v_maxevents, &__pyx_v_timeout)) return 0; Py_INCREF(__pyx_v_self); __pyx_v_results = Py_None; Py_INCREF(Py_None); __pyx_v_i = Py_None; Py_INCREF(Py_None); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":146 */ __pyx_v_nbytes = ((sizeof(struct epoll_event )) * __pyx_v_maxevents); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":147 */ __pyx_v_events = ((struct epoll_event (*))malloc(__pyx_v_nbytes)); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":148 */ memset(__pyx_v_events,0,__pyx_v_nbytes); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":149 */ /*try:*/ { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":150 */ __pyx_v_fd = ((struct __pyx_obj_6_epoll_epoll *)__pyx_v_self)->fd; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":152 */ __pyx_v__save = PyEval_SaveThread(); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":153 */ __pyx_v_result = epoll_wait(__pyx_v_fd,__pyx_v_events,__pyx_v_maxevents,__pyx_v_timeout); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":154 */ PyEval_RestoreThread(__pyx_v__save); /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":156 */ __pyx_1 = (__pyx_v_result == (-1)); if (__pyx_1) { /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":157 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_IOError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} __pyx_3 = PyInt_FromLong(errno); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} __pyx_4 = PyString_FromString(strerror(errno)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_3 = PyObject_Call(__pyx_2, __pyx_5, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; goto __pyx_L3;} goto __pyx_L5; } __pyx_L5:; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":158 */ __pyx_4 = PyList_New(0); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; goto __pyx_L3;} Py_DECREF(__pyx_v_results); __pyx_v_results = __pyx_4; __pyx_4 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":159 */ for (__pyx_6 = 0; __pyx_6 < __pyx_v_result; ++__pyx_6) { __pyx_2 = PyInt_FromLong(__pyx_6); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; goto __pyx_L3;} Py_DECREF(__pyx_v_i); __pyx_v_i = __pyx_2; __pyx_2 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":160 */ __pyx_5 = PyObject_GetAttr(__pyx_v_results, __pyx_n_append); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} __pyx_7 = PyInt_AsSsize_t(__pyx_v_i); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} __pyx_3 = PyInt_FromLong((__pyx_v_events[__pyx_7]).data.fd); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} __pyx_7 = PyInt_AsSsize_t(__pyx_v_i); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} __pyx_4 = PyInt_FromLong(((int )(__pyx_v_events[__pyx_7]).events)); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} __pyx_2 = PyTuple_New(2); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} PyTuple_SET_ITEM(__pyx_2, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_2, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} PyTuple_SET_ITEM(__pyx_3, 0, __pyx_2); __pyx_2 = 0; __pyx_4 = PyObject_Call(__pyx_5, __pyx_3, 0); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; goto __pyx_L3;} Py_DECREF(__pyx_5); __pyx_5 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; __pyx_L6:; } __pyx_L7:; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":161 */ Py_INCREF(__pyx_v_results); __pyx_r = __pyx_v_results; goto __pyx_L2; } /*finally:*/ { int __pyx_why; __pyx_why = 0; goto __pyx_L4; __pyx_L2: __pyx_why = 3; goto __pyx_L4; __pyx_L3: { __pyx_why = 4; Py_XDECREF(__pyx_2); __pyx_2 = 0; Py_XDECREF(__pyx_5); __pyx_5 = 0; Py_XDECREF(__pyx_3); __pyx_3 = 0; Py_XDECREF(__pyx_4); __pyx_4 = 0; PyErr_Fetch(&__pyx_2, &__pyx_5, &__pyx_3); __pyx_1 = __pyx_lineno; goto __pyx_L4; } __pyx_L4:; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":163 */ free(__pyx_v_events); switch (__pyx_why) { case 3: goto __pyx_L0; case 4: { PyErr_Restore(__pyx_2, __pyx_5, __pyx_3); __pyx_lineno = __pyx_1; __pyx_2 = 0; __pyx_5 = 0; __pyx_3 = 0; goto __pyx_L1; } } } __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); Py_XDECREF(__pyx_5); __Pyx_AddTraceback("_epoll.epoll.wait"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_results); Py_DECREF(__pyx_v_i); Py_DECREF(__pyx_v_self); return __pyx_r; } static __Pyx_InternTabEntry __pyx_intern_tab[] = { {&__pyx_n_CTL_ADD, "CTL_ADD"}, {&__pyx_n_CTL_DEL, "CTL_DEL"}, {&__pyx_n_CTL_MOD, "CTL_MOD"}, {&__pyx_n_ERR, "ERR"}, {&__pyx_n_ET, "ET"}, {&__pyx_n_HUP, "HUP"}, {&__pyx_n_IN, "IN"}, {&__pyx_n_IOError, "IOError"}, {&__pyx_n_MSG, "MSG"}, {&__pyx_n_OUT, "OUT"}, {&__pyx_n_PRI, "PRI"}, {&__pyx_n_RDBAND, "RDBAND"}, {&__pyx_n_RDNORM, "RDNORM"}, {&__pyx_n_WRBAND, "WRBAND"}, {&__pyx_n_WRNORM, "WRNORM"}, {&__pyx_n_append, "append"}, {0, 0} }; static PyObject *__pyx_tp_new_6_epoll_epoll(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o = (*t->tp_alloc)(t, 0); struct __pyx_obj_6_epoll_epoll *p = (struct __pyx_obj_6_epoll_epoll *)o; return o; } static void __pyx_tp_dealloc_6_epoll_epoll(PyObject *o) { struct __pyx_obj_6_epoll_epoll *p = (struct __pyx_obj_6_epoll_epoll *)o; { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++o->ob_refcnt; __pyx_f_6_epoll_5epoll___dealloc__(o); if (PyErr_Occurred()) PyErr_WriteUnraisable(o); --o->ob_refcnt; PyErr_Restore(etype, eval, etb); } (*o->ob_type->tp_free)(o); } static int __pyx_tp_traverse_6_epoll_epoll(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_6_epoll_epoll *p = (struct __pyx_obj_6_epoll_epoll *)o; return 0; } static int __pyx_tp_clear_6_epoll_epoll(PyObject *o) { struct __pyx_obj_6_epoll_epoll *p = (struct __pyx_obj_6_epoll_epoll *)o; return 0; } static struct PyMethodDef __pyx_methods_6_epoll_epoll[] = { {"close", (PyCFunction)__pyx_f_6_epoll_5epoll_close, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6_epoll_5epoll_close}, {"fileno", (PyCFunction)__pyx_f_6_epoll_5epoll_fileno, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6_epoll_5epoll_fileno}, {"_control", (PyCFunction)__pyx_f_6_epoll_5epoll__control, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6_epoll_5epoll__control}, {"wait", (PyCFunction)__pyx_f_6_epoll_5epoll_wait, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6_epoll_5epoll_wait}, {0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number_epoll = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_divide*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ 0, /*nb_coerce*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ 0, /*nb_oct*/ 0, /*nb_hex*/ 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ 0, /*nb_inplace_divide*/ 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ }; static PySequenceMethods __pyx_tp_as_sequence_epoll = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_epoll = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_epoll = { 0, /*bf_getreadbuffer*/ 0, /*bf_getwritebuffer*/ 0, /*bf_getsegcount*/ 0, /*bf_getcharbuffer*/ }; PyTypeObject __pyx_type_6_epoll_epoll = { PyObject_HEAD_INIT(0) 0, /*ob_size*/ "_epoll.epoll", /*tp_name*/ sizeof(struct __pyx_obj_6_epoll_epoll), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_6_epoll_epoll, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number_epoll, /*tp_as_number*/ &__pyx_tp_as_sequence_epoll, /*tp_as_sequence*/ &__pyx_tp_as_mapping_epoll, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_epoll, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "\n Represent a set of file descriptors being monitored for events.\n ", /*tp_doc*/ __pyx_tp_traverse_6_epoll_epoll, /*tp_traverse*/ __pyx_tp_clear_6_epoll_epoll, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_6_epoll_epoll, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_f_6_epoll_5epoll___init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_6_epoll_epoll, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ }; static struct PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; static void __pyx_init_filenames(void); /*proto*/ PyMODINIT_FUNC init_epoll(void); /*proto*/ PyMODINIT_FUNC init_epoll(void) { PyObject *__pyx_1 = 0; __pyx_init_filenames(); __pyx_m = Py_InitModule4("_epoll", __pyx_methods, __pyx_mdoc, 0, PYTHON_API_VERSION); if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}; __pyx_b = PyImport_AddModule("__builtin__"); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}; if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}; if (__Pyx_InternStrings(__pyx_intern_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}; if (PyType_Ready(&__pyx_type_6_epoll_epoll) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; goto __pyx_L1;} if (PyObject_SetAttrString(__pyx_m, "epoll", (PyObject *)&__pyx_type_6_epoll_epoll) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; goto __pyx_L1;} __pyx_ptype_6_epoll_epoll = &__pyx_type_6_epoll_epoll; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":165 */ __pyx_1 = PyInt_FromLong(EPOLL_CTL_ADD); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_CTL_ADD, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":166 */ __pyx_1 = PyInt_FromLong(EPOLL_CTL_DEL); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_CTL_DEL, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":167 */ __pyx_1 = PyInt_FromLong(EPOLL_CTL_MOD); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_CTL_MOD, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":169 */ __pyx_1 = PyInt_FromLong(EPOLLIN); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_IN, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":170 */ __pyx_1 = PyInt_FromLong(EPOLLOUT); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_OUT, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":171 */ __pyx_1 = PyInt_FromLong(EPOLLPRI); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_PRI, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":172 */ __pyx_1 = PyInt_FromLong(EPOLLERR); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_ERR, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":173 */ __pyx_1 = PyInt_FromLong(EPOLLHUP); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_HUP, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":174 */ __pyx_1 = PyInt_FromLong(EPOLLET); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_ET, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":176 */ __pyx_1 = PyInt_FromLong(EPOLLRDNORM); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_RDNORM, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":177 */ __pyx_1 = PyInt_FromLong(EPOLLRDBAND); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_RDBAND, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":178 */ __pyx_1 = PyInt_FromLong(EPOLLWRNORM); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_WRNORM, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":179 */ __pyx_1 = PyInt_FromLong(EPOLLWRBAND); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_WRBAND, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/exarkun/Projects/Twisted/branches/epollreactor-1953-2/twisted/python/_epoll.pyx":180 */ __pyx_1 = PyInt_FromLong(EPOLLMSG); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_MSG, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; return; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("_epoll"); } static char *__pyx_filenames[] = { "_epoll.pyx", }; /* Runtime support code */ static void __pyx_init_filenames(void) { __pyx_f = __pyx_filenames; } static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { PyObject *result; result = PyObject_GetAttr(dict, name); if (!result) PyErr_SetObject(PyExc_NameError, name); return result; } static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) { Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { Py_DECREF(tb); tb = 0; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } /* Next, replace a missing value with None */ if (value == NULL) { value = Py_None; Py_INCREF(value); } /* Next, repeatedly, replace a tuple exception with its first item */ while (PyTuple_Check(type) && PyTuple_Size(type) > 0) { PyObject *tmp = type; type = PyTuple_GET_ITEM(type, 0); Py_INCREF(type); Py_DECREF(tmp); } if (PyString_CheckExact(type)) { /* Raising builtin string is deprecated but still allowed -- * do nothing. Raising an instance of a new-style str * subclass is right out. */ if (PyErr_Warn(PyExc_DeprecationWarning, "raising a string exception is deprecated")) goto raise_error; } else if (PyType_Check(type) || PyClass_Check(type)) ; /* PyErr_NormalizeException(&type, &value, &tb); */ else if (PyInstance_Check(type)) { /* Raising an instance. The value should be a dummy. */ if (value != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } else { /* Normalize to raise <class>, <instance> */ Py_DECREF(value); value = type; type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); } } else if (PyType_IsSubtype(type->ob_type, (PyTypeObject*)PyExc_Exception)) { /* Raising a new-style object (in Py2.5). The value should be a dummy. */ if (value != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } else { /* Normalize to raise <class>, <instance> */ Py_DECREF(value); value = type; type = (PyObject*) type->ob_type; Py_INCREF(type); } } else { /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ PyErr_Format(PyExc_TypeError, "exceptions must be classes, instances, or " "strings (deprecated), not %s", type->ob_type->tp_name); goto raise_error; } PyErr_Restore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } static int __Pyx_InternStrings(__Pyx_InternTabEntry *t) { while (t->p) { *t->p = PyString_InternFromString(t->s); if (!*t->p) return -1; ++t; } return 0; } #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_tuple = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_srcfile = PyString_FromString(__pyx_filename); if (!py_srcfile) goto bad; py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; empty_tuple = PyTuple_New(0); if (!empty_tuple) goto bad; empty_string = PyString_FromString(""); if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_Get(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); }
84KaliPleXon3/sslstrip-hsts-openwrt
python2.7/site-packages/twisted/protocols/_c_urlarg.c
/* * Copyright (c) 2001-2004 Twisted Matrix Laboratories. * See LICENSE for details. * */ /* _c_urlarg.c */ #ifdef __cplusplus extern "C" { #endif #include <Python.h> #include <cStringIO.h> #ifdef __cplusplus } #endif #ifdef __GNUC__ # define TM_INLINE inline #else # define TM_INLINE /* */ #endif static PyObject* UrlargError; #define OUTPUTCHAR(c,n) PycStringIO->cwrite(output, c, n) #define STATE_INITIAL 0 #define STATE_PERCENT 1 #define STATE_HEXDIGIT 2 #define NOT_HEXDIGIT 255 unsigned char hexdigits[256]; TM_INLINE int ishexdigit(unsigned char c) { return hexdigits[c]; } static PyObject *unquote(PyObject *self, PyObject *args, PyObject *kwargs) { unsigned char *s, *r, *end; unsigned char quotedchar, quotedchartmp = 0, tmp; unsigned char escchar = '%'; /* the character we use to begin %AB sequences */ static char *kwlist[] = {"s", "escchar", NULL}; int state = STATE_INITIAL, length; PyObject *output, *str; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|c:unquote", kwlist, &s, &length, &escchar)) { return NULL; } /* output = cStringIO() */ output = PycStringIO->NewOutput(length); if (output == NULL) { return NULL; } end = s + length; s = s - 1; while ((++s) < end) { switch(state) { case STATE_INITIAL: if (*s == escchar) { state = STATE_PERCENT; } else { r = s - 1; while (*(++r) != escchar && r < end); OUTPUTCHAR(s, r-s); s = r-1; } break; case STATE_PERCENT: if ((quotedchartmp = ishexdigit(*s)) != NOT_HEXDIGIT) { tmp = *s; state = STATE_HEXDIGIT; } else { state = STATE_INITIAL; OUTPUTCHAR(&escchar, 1); s--; } break; case STATE_HEXDIGIT: state = STATE_INITIAL; if ((quotedchar = ishexdigit(*s)) != NOT_HEXDIGIT) { quotedchar |= (quotedchartmp << 4); OUTPUTCHAR(&quotedchar, 1); } else { OUTPUTCHAR(&escchar, 1); s -= 2; } break; } } switch(state) { case STATE_PERCENT: OUTPUTCHAR(&escchar, 1); break; case STATE_HEXDIGIT: OUTPUTCHAR(&escchar, 1); OUTPUTCHAR(&tmp, 1); break; } /* return output.getvalue() */ str = PycStringIO->cgetvalue(output); Py_DECREF(output); return str; } static PyMethodDef _c_urlarg_methods[] = { {"unquote", (PyCFunction)unquote, METH_VARARGS|METH_KEYWORDS}, {NULL, NULL} /* sentinel */ }; DL_EXPORT(void) init_c_urlarg(void) { PyObject* m; PyObject* d; unsigned char i; PycString_IMPORT; m = Py_InitModule("_c_urlarg", _c_urlarg_methods); d = PyModule_GetDict(m); /* add our base exception class */ UrlargError = PyErr_NewException("urlarg.UrlargError", PyExc_Exception, NULL); PyDict_SetItemString(d, "UrlargError", UrlargError); /* initialize hexdigits */ for(i = 0; i < 255; i++) { hexdigits[i] = NOT_HEXDIGIT; } hexdigits[255] = NOT_HEXDIGIT; for(i = '0'; i <= '9'; i++) { hexdigits[i] = i - '0'; } for(i = 'a'; i <= 'f'; i++) { hexdigits[i] = 10 + (i - 'a'); } for(i = 'A'; i <= 'F'; i++) { hexdigits[i] = 10 + (i - 'A'); } /* Check for errors */ if (PyErr_Occurred()) { PyErr_Print(); Py_FatalError("can't initialize module _c_urlarg"); } }
84KaliPleXon3/sslstrip-hsts-openwrt
python2.7/site-packages/twisted/internet/cfsupport/cfsupport.c
<gh_stars>10-100 /* Generated by Pyrex 0.9.3 on Sat Mar 12 04:43:18 2005 */ #include "Python.h" #include "structmember.h" #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #include "pymactoolbox.h" typedef struct {PyObject **p; char *s;} __Pyx_InternTabEntry; /*proto*/ typedef struct {PyObject **p; char *s; long n;} __Pyx_StringTabEntry; /*proto*/ static PyObject *__Pyx_UnpackItem(PyObject *, int); /*proto*/ static int __Pyx_EndUnpack(PyObject *, int); /*proto*/ static int __Pyx_PrintItem(PyObject *); /*proto*/ static int __Pyx_PrintNewline(void); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static void __Pyx_ReRaise(void); /*proto*/ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ static PyObject *__Pyx_GetExcValue(void); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name); /*proto*/ static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static int __Pyx_GetStarArgs(PyObject **args, PyObject **kwds, char *kwd_list[], int nargs, PyObject **args2, PyObject **kwds2); /*proto*/ static void __Pyx_WriteUnraisable(char *name); /*proto*/ static void __Pyx_AddTraceback(char *funcname); /*proto*/ static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ static int __Pyx_GetVtable(PyObject *dict, void *vtabptr); /*proto*/ static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, char *modname); /*proto*/ static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static PyObject *__pyx_m; static PyObject *__pyx_b; static int __pyx_lineno; static char *__pyx_filename; staticforward char **__pyx_f; /* Declarations from cfsupport */ staticforward PyTypeObject __pyx_type_9cfsupport_PyCFSocket; struct __pyx_obj_9cfsupport_PyCFSocket { PyObject_HEAD PyObject *readcallback; PyObject *writecallback; PyObject *connectcallback; PyObject *reading; PyObject *writing; CFSocketRef cf; CFRunLoopSourceRef source; CFSocketNativeHandle fileno; CFSocketContext context; }; staticforward PyTypeObject __pyx_type_9cfsupport_PyCFRunLoopTimer; struct __pyx_obj_9cfsupport_PyCFRunLoopTimer { PyObject_HEAD CFRunLoopTimerRef cf; PyObject *callout; CFRunLoopTimerContext context; }; staticforward PyTypeObject __pyx_type_9cfsupport_PyCFRunLoop; struct __pyx_obj_9cfsupport_PyCFRunLoop { PyObject_HEAD PyObject *cf; }; static PyTypeObject *__pyx_ptype_9cfsupport_PyCFSocket = 0; static PyTypeObject *__pyx_ptype_9cfsupport_PyCFRunLoopTimer = 0; static PyTypeObject *__pyx_ptype_9cfsupport_PyCFRunLoop = 0; static PyObject *__pyx_k2; static PyObject *__pyx_k3; static PyObject *__pyx_k4; static PyObject *__pyx_k6; static void (__pyx_f_9cfsupport_socketCallBack(CFSocketRef ,CFSocketCallBackType ,CFDataRef ,void (*),void (*))); /*proto*/ static void (__pyx_f_9cfsupport_gilSocketCallBack(CFSocketRef ,CFSocketCallBackType ,CFDataRef ,void (*),void (*))); /*proto*/ static void (__pyx_f_9cfsupport_runLoopTimerCallBack(CFRunLoopTimerRef ,void (*))); /*proto*/ static void (__pyx_f_9cfsupport_gilRunLoopTimerCallBack(CFRunLoopTimerRef ,void (*))); /*proto*/ /* Implementation of cfsupport */ static char (__pyx_k7[]) = "0.4"; static PyObject *__pyx_n_now; static PyObject *__pyx_n_traceback; static PyObject *__pyx_n___version__; static PyObject *__pyx_k7p; static PyObject *__pyx_f_9cfsupport_now(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_now(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfdate.pxi":2 */ __pyx_1 = PyFloat_FromDouble(CFAbsoluteTimeGetCurrent()); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; goto __pyx_L1;} __pyx_r = __pyx_1; __pyx_1 = 0; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("cfsupport.now"); __pyx_r = 0; __pyx_L0:; return __pyx_r; } static PyObject *__pyx_n_print_exc; static void __pyx_f_9cfsupport_socketCallBack(CFSocketRef __pyx_v_s,CFSocketCallBackType __pyx_v__type,CFDataRef __pyx_v_address,void (*__pyx_v_data),void (*__pyx_v_info)) { struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket; int __pyx_v_res; int __pyx_v_mask; PyObject *__pyx_1 = 0; int __pyx_2; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; ((PyObject*)__pyx_v_socket) = Py_None; Py_INCREF(((PyObject*)__pyx_v_socket)); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":9 */ __pyx_1 = (PyObject *)__pyx_v_info; Py_INCREF(__pyx_1); Py_DECREF(((PyObject *)__pyx_v_socket)); ((PyObject *)__pyx_v_socket) = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":11 */ /*try:*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":12 */ __pyx_2 = (__pyx_v__type == kCFSocketReadCallBack); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":13 */ __pyx_2 = PyObject_IsTrue(__pyx_v_socket->readcallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; goto __pyx_L2;} if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":14 */ __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; goto __pyx_L2;} __pyx_3 = PyObject_CallObject(__pyx_v_socket->readcallback, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; goto __pyx_L2;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; goto __pyx_L5; } __pyx_L5:; goto __pyx_L4; } __pyx_2 = (__pyx_v__type == kCFSocketWriteCallBack); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":16 */ __pyx_2 = PyObject_IsTrue(__pyx_v_socket->writecallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 16; goto __pyx_L2;} if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":17 */ __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 17; goto __pyx_L2;} __pyx_3 = PyObject_CallObject(__pyx_v_socket->writecallback, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 17; goto __pyx_L2;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; goto __pyx_L6; } __pyx_L6:; goto __pyx_L4; } __pyx_2 = (__pyx_v__type == kCFSocketConnectCallBack); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":19 */ __pyx_2 = (__pyx_v_data == 0); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":20 */ __pyx_v_res = 0; goto __pyx_L7; } /*else*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":22 */ __pyx_v_res = (((int (*))__pyx_v_data)[0]); } __pyx_L7:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":23 */ __pyx_2 = PyObject_IsTrue(__pyx_v_socket->connectcallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 23; goto __pyx_L2;} if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":24 */ __pyx_1 = PyInt_FromLong(__pyx_v_res); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;} __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;} PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1); __pyx_1 = 0; __pyx_1 = PyObject_CallObject(__pyx_v_socket->connectcallback, __pyx_3); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;} Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; goto __pyx_L8; } __pyx_L8:; goto __pyx_L4; } __pyx_L4:; } goto __pyx_L3; __pyx_L2:; Py_XDECREF(__pyx_3); __pyx_3 = 0; Py_XDECREF(__pyx_1); __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":25 */ /*except:*/ { __Pyx_AddTraceback("cfsupport.socketCallBack"); __pyx_3 = __Pyx_GetExcValue(); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 25; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":26 */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_traceback); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_n_print_exc); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;} __pyx_4 = PyObject_CallObject(__pyx_3, __pyx_1); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; goto __pyx_L3; } __pyx_L3:; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); __Pyx_WriteUnraisable("cfsupport.socketCallBack"); __pyx_L0:; Py_DECREF(__pyx_v_socket); } static void __pyx_f_9cfsupport_gilSocketCallBack(CFSocketRef __pyx_v_s,CFSocketCallBackType __pyx_v__type,CFDataRef __pyx_v_address,void (*__pyx_v_data),void (*__pyx_v_info)) { PyGILState_STATE __pyx_v_gil; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":30 */ __pyx_v_gil = PyGILState_Ensure(); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":31 */ __pyx_f_9cfsupport_socketCallBack(__pyx_v_s,__pyx_v__type,__pyx_v_address,__pyx_v_data,__pyx_v_info); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":32 */ PyGILState_Release(__pyx_v_gil); goto __pyx_L0; __pyx_L1:; __Pyx_WriteUnraisable("cfsupport.gilSocketCallBack"); __pyx_L0:; } static PyObject *__pyx_n_False; static PyObject *__pyx_n_ValueError; static PyObject *__pyx_k8p; static PyObject *__pyx_k9p; static char (__pyx_k8[]) = "Invalid Socket"; static char (__pyx_k9[]) = "Couldn't create runloop source"; static int __pyx_f_9cfsupport_10PyCFSocket___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_9cfsupport_10PyCFSocket___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_fileno; PyObject *__pyx_v_readcallback = 0; PyObject *__pyx_v_writecallback = 0; PyObject *__pyx_v_connectcallback = 0; int __pyx_r; PyObject *__pyx_1 = 0; int __pyx_2; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; static char *__pyx_argnames[] = {"fileno","readcallback","writecallback","connectcallback",0}; __pyx_v_readcallback = __pyx_k2; __pyx_v_writecallback = __pyx_k3; __pyx_v_connectcallback = __pyx_k4; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "i|OOO", __pyx_argnames, &__pyx_v_fileno, &__pyx_v_readcallback, &__pyx_v_writecallback, &__pyx_v_connectcallback)) return -1; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_readcallback); Py_INCREF(__pyx_v_writecallback); Py_INCREF(__pyx_v_connectcallback); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":47 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->fileno = __pyx_v_fileno; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":48 */ Py_INCREF(__pyx_v_readcallback); Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->readcallback); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->readcallback = __pyx_v_readcallback; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":49 */ Py_INCREF(__pyx_v_writecallback); Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writecallback); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writecallback = __pyx_v_writecallback; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":50 */ Py_INCREF(__pyx_v_connectcallback); Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->connectcallback); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->connectcallback = __pyx_v_connectcallback; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":51 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.version = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":52 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.info = ((void (*))__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":53 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.retain = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":54 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.release = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":55 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.copyDescription = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":56 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 56; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":57 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 57; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":58 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf = CFSocketCreateWithNative(kCFAllocatorDefault,__pyx_v_fileno,((kCFSocketConnectCallBack | kCFSocketReadCallBack) | kCFSocketWriteCallBack),((CFSocketCallBack )(&__pyx_f_9cfsupport_gilSocketCallBack)),(&((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context)); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":59 */ __pyx_2 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf == 0); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":60 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;} __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;} Py_INCREF(__pyx_k8p); PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k8p); __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __Pyx_Raise(__pyx_4, 0, 0); Py_DECREF(__pyx_4); __pyx_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":61 */ ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,10000); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":62 */ __pyx_2 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source == 0); if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":63 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;} __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;} Py_INCREF(__pyx_k9p); PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k9p); __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __Pyx_Raise(__pyx_4, 0, 0); Py_DECREF(__pyx_4); __pyx_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;} goto __pyx_L3; } __pyx_L3:; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); __Pyx_AddTraceback("cfsupport.PyCFSocket.__new__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_readcallback); Py_DECREF(__pyx_v_writecallback); Py_DECREF(__pyx_v_connectcallback); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_10PyCFSocket_update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_10PyCFSocket_update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_mask; int __pyx_v_offmask; int __pyx_v_automask; PyObject *__pyx_r; int __pyx_1; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":70 */ __pyx_v_mask = (kCFSocketConnectCallBack | kCFSocketAcceptCallBack); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":71 */ __pyx_v_offmask = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":72 */ __pyx_v_automask = kCFSocketAutomaticallyReenableAcceptCallBack; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":73 */ __pyx_1 = PyObject_IsTrue(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading); if (__pyx_1 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; goto __pyx_L1;} if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":74 */ __pyx_v_mask = (__pyx_v_mask | kCFSocketReadCallBack); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":75 */ __pyx_v_automask = (__pyx_v_automask | kCFSocketAutomaticallyReenableReadCallBack); goto __pyx_L2; } /*else*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":77 */ __pyx_v_offmask = (__pyx_v_offmask | kCFSocketReadCallBack); } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":78 */ __pyx_1 = PyObject_IsTrue(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing); if (__pyx_1 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 78; goto __pyx_L1;} if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":79 */ __pyx_v_mask = (__pyx_v_mask | kCFSocketWriteCallBack); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":80 */ __pyx_v_automask = (__pyx_v_automask | kCFSocketAutomaticallyReenableWriteCallBack); goto __pyx_L3; } /*else*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":82 */ __pyx_v_offmask = (__pyx_v_offmask | kCFSocketWriteCallBack); } __pyx_L3:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":83 */ CFSocketDisableCallBacks(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_offmask); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":84 */ CFSocketEnableCallBacks(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_mask); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":85 */ CFSocketSetSocketFlags(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_automask); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFSocket.update"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_n_True; static PyObject *__pyx_n_update; static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":89 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_True); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 89; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":90 */ __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;} __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;} __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); __Pyx_AddTraceback("cfsupport.PyCFSocket.startReading"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":93 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 93; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":94 */ __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;} __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;} __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); __Pyx_AddTraceback("cfsupport.PyCFSocket.stopReading"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":97 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_True); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 97; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":98 */ __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;} __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;} __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); __Pyx_AddTraceback("cfsupport.PyCFSocket.startWriting"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":101 */ __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing); ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":102 */ __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;} __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;} __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); __Pyx_AddTraceback("cfsupport.PyCFSocket.stopWriting"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static void __pyx_f_9cfsupport_10PyCFSocket___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_f_9cfsupport_10PyCFSocket___dealloc__(PyObject *__pyx_v_self) { int __pyx_1; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":106 */ __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source != 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":107 */ CFRelease(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source); goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":108 */ __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf != 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":109 */ CFSocketInvalidate(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":110 */ CFRelease(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf); goto __pyx_L3; } __pyx_L3:; goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFSocket.__dealloc__"); __pyx_L0:; Py_DECREF(__pyx_v_self); } static PyObject *__pyx_k10p; static char (__pyx_k10[]) = "Invalid Socket"; static int __pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_fireDate; double __pyx_v_interval; PyObject *__pyx_v_callout = 0; int __pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; static char *__pyx_argnames[] = {"fireDate","interval","callout",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "ddO", __pyx_argnames, &__pyx_v_fireDate, &__pyx_v_interval, &__pyx_v_callout)) return -1; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_callout); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":11 */ Py_INCREF(__pyx_v_callout); Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->callout); ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->callout = __pyx_v_callout; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":12 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.version = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":13 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.info = ((void (*))__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":14 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.retain = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":15 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.release = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":16 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.copyDescription = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":17 */ ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf = CFRunLoopTimerCreate(kCFAllocatorDefault,__pyx_v_fireDate,__pyx_v_interval,0,0,((CFRunLoopTimerCallBack )(&__pyx_f_9cfsupport_gilRunLoopTimerCallBack)),(&((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context)); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":18 */ __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":19 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;} __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;} Py_INCREF(__pyx_k10p); PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k10p); __pyx_4 = PyObject_CallObject(__pyx_2, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; __Pyx_Raise(__pyx_4, 0, 0); Py_DECREF(__pyx_4); __pyx_4 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.__new__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_callout); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; PyObject *__pyx_1 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":22 */ __pyx_1 = PyFloat_FromDouble(CFRunLoopTimerGetNextFireDate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf)); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 22; goto __pyx_L1;} __pyx_r = __pyx_1; __pyx_1 = 0; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.getNextFireDate"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_fireDate; PyObject *__pyx_r; static char *__pyx_argnames[] = {"fireDate",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "d", __pyx_argnames, &__pyx_v_fireDate)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":25 */ CFRunLoopTimerSetNextFireDate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf,__pyx_v_fireDate); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.setNextFireDate"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":28 */ CFRunLoopTimerInvalidate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.invalidate"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static void __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(PyObject *__pyx_v_self) { int __pyx_1; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":31 */ __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf != 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":32 */ CFRelease(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf); goto __pyx_L2; } __pyx_L2:; goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.__dealloc__"); __pyx_L0:; Py_DECREF(__pyx_v_self); } static void __pyx_f_9cfsupport_runLoopTimerCallBack(CFRunLoopTimerRef __pyx_v_timer,void (*__pyx_v_info)) { struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_obj; PyObject *__pyx_1 = 0; int __pyx_2; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; ((PyObject*)__pyx_v_obj) = Py_None; Py_INCREF(((PyObject*)__pyx_v_obj)); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":36 */ __pyx_1 = (PyObject *)__pyx_v_info; Py_INCREF(__pyx_1); Py_DECREF(((PyObject *)__pyx_v_obj)); ((PyObject *)__pyx_v_obj) = __pyx_1; __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":37 */ /*try:*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":38 */ __pyx_2 = PyObject_IsTrue(__pyx_v_obj->callout); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 38; goto __pyx_L2;} if (__pyx_2) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":39 */ __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 39; goto __pyx_L2;} __pyx_3 = PyObject_CallObject(__pyx_v_obj->callout, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 39; goto __pyx_L2;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; goto __pyx_L4; } __pyx_L4:; } goto __pyx_L3; __pyx_L2:; Py_XDECREF(__pyx_1); __pyx_1 = 0; Py_XDECREF(__pyx_3); __pyx_3 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":40 */ /*except:*/ { __Pyx_AddTraceback("cfsupport.runLoopTimerCallBack"); __pyx_1 = __Pyx_GetExcValue(); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 40; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":41 */ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n_traceback); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(__pyx_3, __pyx_n_print_exc); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_3 = PyTuple_New(0); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;} __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; goto __pyx_L3; } __pyx_L3:; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); __Pyx_WriteUnraisable("cfsupport.runLoopTimerCallBack"); __pyx_L0:; Py_DECREF(__pyx_v_obj); } static void __pyx_f_9cfsupport_gilRunLoopTimerCallBack(CFRunLoopTimerRef __pyx_v_timer,void (*__pyx_v_info)) { PyGILState_STATE __pyx_v_gil; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":45 */ __pyx_v_gil = PyGILState_Ensure(); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":46 */ __pyx_f_9cfsupport_runLoopTimerCallBack(__pyx_v_timer,__pyx_v_info); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":47 */ PyGILState_Release(__pyx_v_gil); goto __pyx_L0; __pyx_L1:; __Pyx_WriteUnraisable("cfsupport.gilRunLoopTimerCallBack"); __pyx_L0:; } static int __pyx_f_9cfsupport_11PyCFRunLoop___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_9cfsupport_11PyCFRunLoop___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_runLoop = 0; CFTypeRef __pyx_v__runLoop; int __pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"runLoop",0}; __pyx_v_runLoop = __pyx_k6; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "|O", __pyx_argnames, &__pyx_v_runLoop)) return -1; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_runLoop); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":54 */ __pyx_1 = __pyx_v_runLoop == Py_None; if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":55 */ __pyx_v__runLoop = CFRunLoopGetCurrent(); goto __pyx_L2; } /*else*/ { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":57 */ __pyx_1 = (CFObj_Convert(__pyx_v_runLoop,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":58 */ __Pyx_ReRaise(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 58; goto __pyx_L1;} goto __pyx_L3; } __pyx_L3:; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":61 */ __pyx_2 = CFObj_New(CFRetain(__pyx_v__runLoop)); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 61; goto __pyx_L1;} Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf); ((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf = __pyx_2; __pyx_2 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.__new__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_runLoop); return __pyx_r; } static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_run(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_run(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_r; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":64 */ CFRunLoopRun(); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("cfsupport.PyCFRunLoop.run"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_k11p; static char (__pyx_k11[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_stop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_stop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":68 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":69 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 69; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k11p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 69; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":70 */ CFRunLoopStop(__pyx_v__runLoop); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.stop"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_k12p; static char (__pyx_k12[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_currentMode(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_currentMode(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { CFTypeRef __pyx_v__currentMode; CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; Py_INCREF(__pyx_v_self); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":75 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":76 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 76; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k12p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 76; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":77 */ __pyx_v__currentMode = CFRunLoopCopyCurrentMode(__pyx_v__runLoop); /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":78 */ __pyx_1 = (__pyx_v__currentMode == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":79 */ Py_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":80 */ __pyx_2 = CFObj_New(__pyx_v__currentMode); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 80; goto __pyx_L1;} __pyx_r = __pyx_2; __pyx_2 = 0; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.currentMode"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); return __pyx_r; } static PyObject *__pyx_k13p; static char (__pyx_k13[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket = 0; CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"socket",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_socket)) return 0; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_socket); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_socket), __pyx_ptype_9cfsupport_PyCFSocket, 0, "socket")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 82; goto __pyx_L1;} /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":84 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":85 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 85; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k13p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 85; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":86 */ CFRunLoopAddSource(__pyx_v__runLoop,__pyx_v_socket->source,kCFRunLoopCommonModes); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.addSocket"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_socket); return __pyx_r; } static PyObject *__pyx_k14p; static char (__pyx_k14[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket = 0; CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"socket",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_socket)) return 0; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_socket); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_socket), __pyx_ptype_9cfsupport_PyCFSocket, 0, "socket")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 88; goto __pyx_L1;} /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":90 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":91 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 91; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k14p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 91; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":92 */ CFRunLoopRemoveSource(__pyx_v__runLoop,__pyx_v_socket->source,kCFRunLoopCommonModes); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.removeSocket"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_socket); return __pyx_r; } static PyObject *__pyx_k15p; static char (__pyx_k15[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_timer = 0; CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"timer",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_timer)) return 0; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_timer); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_timer), __pyx_ptype_9cfsupport_PyCFRunLoopTimer, 0, "timer")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 94; goto __pyx_L1;} /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":96 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":97 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 97; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k15p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 97; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":98 */ CFRunLoopAddTimer(__pyx_v__runLoop,__pyx_v_timer->cf,kCFRunLoopCommonModes); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.addTimer"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_timer); return __pyx_r; } static PyObject *__pyx_k16p; static char (__pyx_k16[]) = "CFRunLoopReference is invalid"; static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_timer = 0; CFTypeRef __pyx_v__runLoop; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"timer",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_timer)) return 0; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_timer); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_timer), __pyx_ptype_9cfsupport_PyCFRunLoopTimer, 0, "timer")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 100; goto __pyx_L1;} /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":102 */ __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0); if (__pyx_1) { /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":103 */ __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 103; goto __pyx_L1;} __Pyx_Raise(__pyx_2, __pyx_k16p, 0); Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 103; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":104 */ CFRunLoopRemoveTimer(__pyx_v__runLoop,__pyx_v_timer->cf,kCFRunLoopCommonModes); __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("cfsupport.PyCFRunLoop.removeTimer"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_timer); return __pyx_r; } static __Pyx_InternTabEntry __pyx_intern_tab[] = { {&__pyx_n_False, "False"}, {&__pyx_n_True, "True"}, {&__pyx_n_ValueError, "ValueError"}, {&__pyx_n___version__, "__version__"}, {&__pyx_n_now, "now"}, {&__pyx_n_print_exc, "print_exc"}, {&__pyx_n_traceback, "traceback"}, {&__pyx_n_update, "update"}, {0, 0} }; static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_k7p, __pyx_k7, sizeof(__pyx_k7)}, {&__pyx_k8p, __pyx_k8, sizeof(__pyx_k8)}, {&__pyx_k9p, __pyx_k9, sizeof(__pyx_k9)}, {&__pyx_k10p, __pyx_k10, sizeof(__pyx_k10)}, {&__pyx_k11p, __pyx_k11, sizeof(__pyx_k11)}, {&__pyx_k12p, __pyx_k12, sizeof(__pyx_k12)}, {&__pyx_k13p, __pyx_k13, sizeof(__pyx_k13)}, {&__pyx_k14p, __pyx_k14, sizeof(__pyx_k14)}, {&__pyx_k15p, __pyx_k15, sizeof(__pyx_k15)}, {&__pyx_k16p, __pyx_k16, sizeof(__pyx_k16)}, {0, 0, 0} }; static PyObject *__pyx_tp_new_9cfsupport_PyCFSocket(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o = (*t->tp_alloc)(t, 0); struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o; p->readcallback = Py_None; Py_INCREF(p->readcallback); p->writecallback = Py_None; Py_INCREF(p->writecallback); p->connectcallback = Py_None; Py_INCREF(p->connectcallback); p->reading = Py_None; Py_INCREF(p->reading); p->writing = Py_None; Py_INCREF(p->writing); if (__pyx_f_9cfsupport_10PyCFSocket___new__(o, a, k) < 0) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_9cfsupport_PyCFSocket(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o; { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++o->ob_refcnt; __pyx_f_9cfsupport_10PyCFSocket___dealloc__(o); if (PyErr_Occurred()) PyErr_WriteUnraisable(o); --o->ob_refcnt; PyErr_Restore(etype, eval, etb); } Py_XDECREF(p->readcallback); Py_XDECREF(p->writecallback); Py_XDECREF(p->connectcallback); Py_XDECREF(p->reading); Py_XDECREF(p->writing); (*o->ob_type->tp_free)(o); } static int __pyx_tp_traverse_9cfsupport_PyCFSocket(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o; if (p->readcallback) { e = (*v)(p->readcallback, a); if (e) return e; } if (p->writecallback) { e = (*v)(p->writecallback, a); if (e) return e; } if (p->connectcallback) { e = (*v)(p->connectcallback, a); if (e) return e; } if (p->reading) { e = (*v)(p->reading, a); if (e) return e; } if (p->writing) { e = (*v)(p->writing, a); if (e) return e; } return 0; } static int __pyx_tp_clear_9cfsupport_PyCFSocket(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o; Py_XDECREF(p->readcallback); p->readcallback = Py_None; Py_INCREF(p->readcallback); Py_XDECREF(p->writecallback); p->writecallback = Py_None; Py_INCREF(p->writecallback); Py_XDECREF(p->connectcallback); p->connectcallback = Py_None; Py_INCREF(p->connectcallback); Py_XDECREF(p->reading); p->reading = Py_None; Py_INCREF(p->reading); Py_XDECREF(p->writing); p->writing = Py_None; Py_INCREF(p->writing); return 0; } static struct PyMethodDef __pyx_methods_9cfsupport_PyCFSocket[] = { {"update", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_update, METH_VARARGS|METH_KEYWORDS, 0}, {"startReading", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_startReading, METH_VARARGS|METH_KEYWORDS, 0}, {"stopReading", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_stopReading, METH_VARARGS|METH_KEYWORDS, 0}, {"startWriting", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_startWriting, METH_VARARGS|METH_KEYWORDS, 0}, {"stopWriting", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_stopWriting, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; static struct PyMemberDef __pyx_members_9cfsupport_PyCFSocket[] = { {"readcallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, readcallback), 0, 0}, {"writecallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, writecallback), 0, 0}, {"connectcallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, connectcallback), 0, 0}, {"reading", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, reading), 0, 0}, {"writing", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, writing), 0, 0}, {"fileno", T_INT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, fileno), READONLY, 0}, {0, 0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number_PyCFSocket = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_divide*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ 0, /*nb_coerce*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ 0, /*nb_oct*/ 0, /*nb_hex*/ 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ 0, /*nb_inplace_divide*/ 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ }; static PySequenceMethods __pyx_tp_as_sequence_PyCFSocket = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_PyCFSocket = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_PyCFSocket = { 0, /*bf_getreadbuffer*/ 0, /*bf_getwritebuffer*/ 0, /*bf_getsegcount*/ 0, /*bf_getcharbuffer*/ }; statichere PyTypeObject __pyx_type_9cfsupport_PyCFSocket = { PyObject_HEAD_INIT(0) 0, /*ob_size*/ "cfsupport.PyCFSocket", /*tp_name*/ sizeof(struct __pyx_obj_9cfsupport_PyCFSocket), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9cfsupport_PyCFSocket, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number_PyCFSocket, /*tp_as_number*/ &__pyx_tp_as_sequence_PyCFSocket, /*tp_as_sequence*/ &__pyx_tp_as_mapping_PyCFSocket, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_PyCFSocket, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_9cfsupport_PyCFSocket, /*tp_traverse*/ __pyx_tp_clear_9cfsupport_PyCFSocket, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9cfsupport_PyCFSocket, /*tp_methods*/ __pyx_members_9cfsupport_PyCFSocket, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9cfsupport_PyCFSocket, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ }; static PyObject *__pyx_tp_new_9cfsupport_PyCFRunLoopTimer(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o = (*t->tp_alloc)(t, 0); struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o; p->callout = Py_None; Py_INCREF(p->callout); if (__pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(o, a, k) < 0) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_9cfsupport_PyCFRunLoopTimer(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o; { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++o->ob_refcnt; __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(o); if (PyErr_Occurred()) PyErr_WriteUnraisable(o); --o->ob_refcnt; PyErr_Restore(etype, eval, etb); } Py_XDECREF(p->callout); (*o->ob_type->tp_free)(o); } static int __pyx_tp_traverse_9cfsupport_PyCFRunLoopTimer(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o; if (p->callout) { e = (*v)(p->callout, a); if (e) return e; } return 0; } static int __pyx_tp_clear_9cfsupport_PyCFRunLoopTimer(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o; Py_XDECREF(p->callout); p->callout = Py_None; Py_INCREF(p->callout); return 0; } static struct PyMethodDef __pyx_methods_9cfsupport_PyCFRunLoopTimer[] = { {"getNextFireDate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate, METH_VARARGS|METH_KEYWORDS, 0}, {"setNextFireDate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate, METH_VARARGS|METH_KEYWORDS, 0}, {"invalidate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; static struct PyMemberDef __pyx_members_9cfsupport_PyCFRunLoopTimer[] = { {"callout", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFRunLoopTimer, callout), 0, 0}, {0, 0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number_PyCFRunLoopTimer = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_divide*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ 0, /*nb_coerce*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ 0, /*nb_oct*/ 0, /*nb_hex*/ 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ 0, /*nb_inplace_divide*/ 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ }; static PySequenceMethods __pyx_tp_as_sequence_PyCFRunLoopTimer = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_PyCFRunLoopTimer = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_PyCFRunLoopTimer = { 0, /*bf_getreadbuffer*/ 0, /*bf_getwritebuffer*/ 0, /*bf_getsegcount*/ 0, /*bf_getcharbuffer*/ }; statichere PyTypeObject __pyx_type_9cfsupport_PyCFRunLoopTimer = { PyObject_HEAD_INIT(0) 0, /*ob_size*/ "cfsupport.PyCFRunLoopTimer", /*tp_name*/ sizeof(struct __pyx_obj_9cfsupport_PyCFRunLoopTimer), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9cfsupport_PyCFRunLoopTimer, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number_PyCFRunLoopTimer, /*tp_as_number*/ &__pyx_tp_as_sequence_PyCFRunLoopTimer, /*tp_as_sequence*/ &__pyx_tp_as_mapping_PyCFRunLoopTimer, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_PyCFRunLoopTimer, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_9cfsupport_PyCFRunLoopTimer, /*tp_traverse*/ __pyx_tp_clear_9cfsupport_PyCFRunLoopTimer, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9cfsupport_PyCFRunLoopTimer, /*tp_methods*/ __pyx_members_9cfsupport_PyCFRunLoopTimer, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9cfsupport_PyCFRunLoopTimer, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ }; static PyObject *__pyx_tp_new_9cfsupport_PyCFRunLoop(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o = (*t->tp_alloc)(t, 0); struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o; p->cf = Py_None; Py_INCREF(p->cf); if (__pyx_f_9cfsupport_11PyCFRunLoop___new__(o, a, k) < 0) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_9cfsupport_PyCFRunLoop(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o; Py_XDECREF(p->cf); (*o->ob_type->tp_free)(o); } static int __pyx_tp_traverse_9cfsupport_PyCFRunLoop(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o; if (p->cf) { e = (*v)(p->cf, a); if (e) return e; } return 0; } static int __pyx_tp_clear_9cfsupport_PyCFRunLoop(PyObject *o) { struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o; Py_XDECREF(p->cf); p->cf = Py_None; Py_INCREF(p->cf); return 0; } static struct PyMethodDef __pyx_methods_9cfsupport_PyCFRunLoop[] = { {"run", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_run, METH_VARARGS|METH_KEYWORDS, 0}, {"stop", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_stop, METH_VARARGS|METH_KEYWORDS, 0}, {"currentMode", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_currentMode, METH_VARARGS|METH_KEYWORDS, 0}, {"addSocket", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_addSocket, METH_VARARGS|METH_KEYWORDS, 0}, {"removeSocket", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket, METH_VARARGS|METH_KEYWORDS, 0}, {"addTimer", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_addTimer, METH_VARARGS|METH_KEYWORDS, 0}, {"removeTimer", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; static struct PyMemberDef __pyx_members_9cfsupport_PyCFRunLoop[] = { {"cf", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFRunLoop, cf), 0, 0}, {0, 0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number_PyCFRunLoop = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_divide*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ 0, /*nb_coerce*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ 0, /*nb_oct*/ 0, /*nb_hex*/ 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ 0, /*nb_inplace_divide*/ 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ }; static PySequenceMethods __pyx_tp_as_sequence_PyCFRunLoop = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_PyCFRunLoop = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_PyCFRunLoop = { 0, /*bf_getreadbuffer*/ 0, /*bf_getwritebuffer*/ 0, /*bf_getsegcount*/ 0, /*bf_getcharbuffer*/ }; statichere PyTypeObject __pyx_type_9cfsupport_PyCFRunLoop = { PyObject_HEAD_INIT(0) 0, /*ob_size*/ "cfsupport.PyCFRunLoop", /*tp_name*/ sizeof(struct __pyx_obj_9cfsupport_PyCFRunLoop), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9cfsupport_PyCFRunLoop, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number_PyCFRunLoop, /*tp_as_number*/ &__pyx_tp_as_sequence_PyCFRunLoop, /*tp_as_sequence*/ &__pyx_tp_as_mapping_PyCFRunLoop, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_PyCFRunLoop, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_9cfsupport_PyCFRunLoop, /*tp_traverse*/ __pyx_tp_clear_9cfsupport_PyCFRunLoop, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9cfsupport_PyCFRunLoop, /*tp_methods*/ __pyx_members_9cfsupport_PyCFRunLoop, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9cfsupport_PyCFRunLoop, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ }; static struct PyMethodDef __pyx_methods[] = { {"now", (PyCFunction)__pyx_f_9cfsupport_now, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; DL_EXPORT(void) initcfsupport(void); /*proto*/ DL_EXPORT(void) initcfsupport(void) { PyObject *__pyx_1 = 0; __pyx_m = Py_InitModule4("cfsupport", __pyx_methods, 0, 0, PYTHON_API_VERSION); if (!__pyx_m) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;}; __pyx_b = PyImport_AddModule("__builtin__"); if (!__pyx_b) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;}; if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;}; if (__Pyx_InternStrings(__pyx_intern_tab) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;}; if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;}; __pyx_type_9cfsupport_PyCFSocket.tp_free = _PyObject_GC_Del; if (PyType_Ready(&__pyx_type_9cfsupport_PyCFSocket) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 34; goto __pyx_L1;} if (PyObject_SetAttrString(__pyx_m, "PyCFSocket", (PyObject *)&__pyx_type_9cfsupport_PyCFSocket) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 34; goto __pyx_L1;} __pyx_ptype_9cfsupport_PyCFSocket = &__pyx_type_9cfsupport_PyCFSocket; __pyx_type_9cfsupport_PyCFRunLoopTimer.tp_free = _PyObject_GC_Del; if (PyType_Ready(&__pyx_type_9cfsupport_PyCFRunLoopTimer) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 5; goto __pyx_L1;} if (PyObject_SetAttrString(__pyx_m, "PyCFRunLoopTimer", (PyObject *)&__pyx_type_9cfsupport_PyCFRunLoopTimer) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 5; goto __pyx_L1;} __pyx_ptype_9cfsupport_PyCFRunLoopTimer = &__pyx_type_9cfsupport_PyCFRunLoopTimer; __pyx_type_9cfsupport_PyCFRunLoop.tp_free = _PyObject_GC_Del; if (PyType_Ready(&__pyx_type_9cfsupport_PyCFRunLoop) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 49; goto __pyx_L1;} if (PyObject_SetAttrString(__pyx_m, "PyCFRunLoop", (PyObject *)&__pyx_type_9cfsupport_PyCFRunLoop) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 49; goto __pyx_L1;} __pyx_ptype_9cfsupport_PyCFRunLoop = &__pyx_type_9cfsupport_PyCFRunLoop; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":1 */ __pyx_1 = __Pyx_Import(__pyx_n_traceback, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_traceback, __pyx_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":45 */ Py_INCREF(Py_None); __pyx_k2 = Py_None; Py_INCREF(Py_None); __pyx_k3 = Py_None; Py_INCREF(Py_None); __pyx_k4 = Py_None; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":1 */ __pyx_1 = __Pyx_Import(__pyx_n_traceback, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_traceback, __pyx_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":52 */ Py_INCREF(Py_None); __pyx_k6 = Py_None; /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsupport.pyx":6 */ if (PyObject_SetAttr(__pyx_m, __pyx_n___version__, __pyx_k7p) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 6; goto __pyx_L1;} return; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("cfsupport"); } static char *__pyx_filenames[] = { "cfdate.pxi", "cfsocket.pxi", "cfrunloop.pxi", "cfsupport.pyx", }; statichere char **__pyx_f = __pyx_filenames; /* Runtime support code */ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name) { if (!type) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if ((none_allowed && obj == Py_None) || PyObject_TypeCheck(obj, type)) return 1; PyErr_Format(PyExc_TypeError, "Argument '%s' has incorrect type (expected %s, got %s)", name, type->tp_name, obj->ob_type->tp_name); return 0; } static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) { PyObject *__import__ = 0; PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; __import__ = PyObject_GetAttrString(__pyx_b, "__import__"); if (!__import__) goto bad; if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; module = PyObject_CallFunction(__import__, "OOOO", name, global_dict, empty_dict, list); bad: Py_XDECREF(empty_list); Py_XDECREF(__import__); Py_XDECREF(empty_dict); return module; } static PyObject *__Pyx_GetExcValue(void) { PyObject *type = 0, *value = 0, *tb = 0; PyObject *result = 0; PyThreadState *tstate = PyThreadState_Get(); PyErr_Fetch(&type, &value, &tb); PyErr_NormalizeException(&type, &value, &tb); if (PyErr_Occurred()) goto bad; if (!value) { value = Py_None; Py_INCREF(value); } Py_XDECREF(tstate->exc_type); Py_XDECREF(tstate->exc_value); Py_XDECREF(tstate->exc_traceback); tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; result = value; Py_XINCREF(result); type = 0; value = 0; tb = 0; bad: Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); return result; } static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { PyObject *result; result = PyObject_GetAttr(dict, name); if (!result) PyErr_SetObject(PyExc_NameError, name); return result; } static void __Pyx_WriteUnraisable(char *name) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; PyErr_Fetch(&old_exc, &old_val, &old_tb); ctx = PyString_FromString(name); PyErr_Restore(old_exc, old_val, old_tb); if (!ctx) ctx = Py_None; PyErr_WriteUnraisable(ctx); } static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) { Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { Py_DECREF(tb); tb = 0; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } /* Next, replace a missing value with None */ if (value == NULL) { value = Py_None; Py_INCREF(value); } /* Next, repeatedly, replace a tuple exception with its first item */ while (PyTuple_Check(type) && PyTuple_Size(type) > 0) { PyObject *tmp = type; type = PyTuple_GET_ITEM(type, 0); Py_INCREF(type); Py_DECREF(tmp); } if (PyString_Check(type)) ; else if (PyClass_Check(type)) ; /*PyErr_NormalizeException(&type, &value, &tb);*/ else if (PyInstance_Check(type)) { /* Raising an instance. The value should be a dummy. */ if (value != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } else { /* Normalize to raise <class>, <instance> */ Py_DECREF(value); value = type; type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); } } else { /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ PyErr_Format(PyExc_TypeError, "exceptions must be strings, classes, or " "instances, not %s", type->ob_type->tp_name); goto raise_error; } PyErr_Restore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } static void __Pyx_ReRaise(void) { PyThreadState *tstate = PyThreadState_Get(); PyObject *type = tstate->exc_type; PyObject *value = tstate->exc_value; PyObject *tb = tstate->exc_traceback; Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); PyErr_Restore(type, value, tb); } static int __Pyx_InternStrings(__Pyx_InternTabEntry *t) { while (t->p) { *t->p = PyString_InternFromString(t->s); if (!*t->p) return -1; ++t; } return 0; } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); if (!*t->p) return -1; ++t; } return 0; } #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_tuple = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_srcfile = PyString_FromString(__pyx_filename); if (!py_srcfile) goto bad; py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; empty_tuple = PyTuple_New(0); if (!empty_tuple) goto bad; empty_string = PyString_FromString(""); if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_Get(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); }
skn123/penguinV
test/performance_tests/cuda/performance_test_image_function_cuda.h
#pragma once class PerformanceTestFramework; void addTests_Image_Function_Cuda( PerformanceTestFramework & framework );
skn123/penguinV
test/unit_tests/unit_test_image_function.h
#pragma once class UnitTestFramework; void addTests_Image_Function( UnitTestFramework & framework );
skn123/penguinV
test/unit_tests/unit_test_file.h
#pragma once class UnitTestFramework; void addTests_File( UnitTestFramework & framework );
skn123/penguinV
test/performance_tests/performance_test_edge_detection.h
<reponame>skn123/penguinV<gh_stars>100-1000 #pragma once class PerformanceTestFramework; void addTests_Edge_Detection( PerformanceTestFramework & framework );
skn123/penguinV
test/performance_tests/performance_test_blob_detection.h
#pragma once class PerformanceTestFramework; void addTests_Blob_Detection( PerformanceTestFramework & framework );
skn123/penguinV
src/opencl/image_buffer_opencl.h
#pragma once #if defined(__APPLE__) || defined(__MACOSX) #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #include "../image_buffer.h" #include "opencl_device.h" namespace penguinV { template <typename TColorDepth> class ImageTemplateOpenCL : public ImageTemplate<TColorDepth> { public: explicit ImageTemplateOpenCL( uint32_t width_ = 0u, uint32_t height_ = 0u, uint8_t colorCount_ = 1u, uint8_t alignment_ = 1u ) { ImageTemplate<TColorDepth>::_setType( 3, _allocateMemory, _deallocateMemory, _copyMemory, _setMemory ); ImageTemplate<TColorDepth>::setColorCount( colorCount_ ); ImageTemplate<TColorDepth>::setAlignment( alignment_ ); ImageTemplate<TColorDepth>::resize( width_, height_ ); } ImageTemplateOpenCL( const ImageTemplateOpenCL & image ) { ImageTemplate<TColorDepth>::operator=( image ); } ImageTemplateOpenCL( ImageTemplateOpenCL && image ) { ImageTemplate<TColorDepth>::swap( image ); } ImageTemplateOpenCL & operator=( const ImageTemplateOpenCL & image ) { ImageTemplate<TColorDepth>::operator=( image ); return (*this); } ImageTemplateOpenCL & operator=( ImageTemplateOpenCL && image ) { ImageTemplate<TColorDepth>::swap( image ); return (*this); } private: static TColorDepth * _allocateMemory( size_t size ) { return reinterpret_cast<TColorDepth*>( multiCL::MemoryManager::memory().allocate<TColorDepth>( size ) ); } static void _deallocateMemory( TColorDepth * data ) { multiCL::MemoryManager::memory().free( reinterpret_cast<cl_mem>( data ) ); } static void _copyMemory( TColorDepth * out, TColorDepth * in, size_t size ) { cl_mem inMem = reinterpret_cast<cl_mem>( in ); cl_mem outMem = reinterpret_cast<cl_mem>( out ); const cl_int error = clEnqueueCopyBuffer( multiCL::OpenCLDeviceManager::instance().device().queue()(), inMem, outMem, 0, 0, size, 0, NULL, NULL ); if( error != CL_SUCCESS ) throw penguinVException( "Cannot copy a memory in GPU device" ); } static void _setMemory( TColorDepth * data, TColorDepth value, size_t size ) { cl_mem dataMem = reinterpret_cast<cl_mem>( data ); multiCL::MemoryManager::memorySet( dataMem, &value, sizeof( TColorDepth ), 0, size ); } }; typedef penguinV::ImageTemplateOpenCL<uint8_t> ImageOpenCL; }
skn123/penguinV
test/unit_tests/unit_test_edge_detection.h
#pragma once class UnitTestFramework; void addTests_Edge_Detection( UnitTestFramework & framework );
skn123/penguinV
test/unit_tests/opencl/unit_test_image_function_opencl.h
#pragma once class UnitTestFramework; void addTests_Image_Function_OpenCL( UnitTestFramework & framework );
skn123/penguinV
test/performance_tests/opencl/performance_test_image_function_opencl.h
#pragma once class PerformanceTestFramework; void addTests_Image_Function_OpenCL( PerformanceTestFramework & framework );
skn123/penguinV
test/unit_tests/unit_test_image_buffer.h
<gh_stars>100-1000 #pragma once class UnitTestFramework; void addTests_Image_Buffer( UnitTestFramework & framework );
skn123/penguinV
src/penguinv_exception.h
#pragma once #include <exception> #include <string> // Thanks to Visual Studio noexcept is no supported so we have to do like this :( #ifndef _MSC_VER #define NOEXCEPT noexcept #else #define NOEXCEPT #endif class penguinVException : public std::exception { public: penguinVException() : _name( "unknown image library exception" ) { } explicit penguinVException( const char * message ) : _name( message ) { } explicit penguinVException( const std::string & message ) : _name( message.data() ) { } penguinVException( const penguinVException & ex ) : std::exception( ex ) , _name ( ex._name ) { } virtual ~penguinVException() { } penguinVException & operator=( const penguinVException & ex ) { std::exception::operator=( ex ); _name = ex._name; return (*this); } virtual const char * what() const NOEXCEPT { return _name.c_str(); } private: std::string _name; };
skn123/penguinV
test/unit_tests/cuda/unit_test_image_function_cuda.h
<filename>test/unit_tests/cuda/unit_test_image_function_cuda.h #pragma once class UnitTestFramework; void addTests_Image_Function_Cuda( UnitTestFramework & framework );