filename
stringlengths
3
9
code
stringlengths
4
2.03M
10094.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2018-2019 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ int main () { return 0; }
6842.c
#include "/d/dagger/Torm/tormdefs.h" #include <std.h> inherit "/d/dagger/Torm/mon/dayvendor.c"; create() { ::create(); set_name("furtrader"); set_id(({"trader","fur trader","dayperson"})); set_short("Furtrader"); set("aggressive", 0); set_level(19); set_property("always interact",1); set_long( "The beastman stands proud and tall. An olive green fur covers his body, but no one else seems to pay him any more attention than the other vendors. He carries a leather pack full of tanning equipment. It is indeed very odd to see one of his race filling such a capacity, but you suppose Torm is a good place for misfits." ); set_gender("male"); set_alignment(5); set_race("beastman"); add_money("gold", random(50)); set_body_type("human"); set_storage_room(TSP+"furtrader.c"); set_property("no attack", 1); set_hd(19,3); set_exp(10); set_items_allowed("clothing"); set_max_hp(query_hp()); set_max_sp(query_hp()); set_sp(query_max_sp()); set_mp(random(500)); set_max_mp(query_mp()); } __List(str){ if(!at_shop()) return 1; return ::__List(str); } __Buy(str){ if(!at_shop()) return 1; return ::__Buy(str); } __Sell(str){ if(!at_shop()) return 1; return ::__Sell(str); } __Show(str){ if(!at_shop()) return 1; return ::__Show(str); } __Value(str){ if(!at_shop()) return 1; return ::__Value(str); } int at_shop(){ if(file_name(environment(TO)) !=TCITY+"57.c"){ //command("say Come see me in my shop!!\n"); return 1; } return 1; }
289121.c
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2004 by Blender Foundation. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): Joseph Eagar * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/editors/mesh/editmesh_tools.c * \ingroup edmesh */ #include <stddef.h> #include "MEM_guardedalloc.h" #include "DNA_key_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_modifier_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" #include "BLI_listbase.h" #include "BLI_noise.h" #include "BLI_math.h" #include "BLI_rand.h" #include "BLI_sort_utils.h" #include "BKE_material.h" #include "BKE_context.h" #include "BKE_deform.h" #include "BKE_depsgraph.h" #include "BKE_report.h" #include "BKE_texture.h" #include "BKE_main.h" #include "BKE_editmesh.h" #include "BLT_translation.h" #include "RNA_define.h" #include "RNA_access.h" #include "RNA_enum_types.h" #include "WM_api.h" #include "WM_types.h" #include "ED_mesh.h" #include "ED_object.h" #include "ED_screen.h" #include "ED_transform.h" #include "ED_transform_snap_object_context.h" #include "ED_uvedit.h" #include "ED_view3d.h" #include "RE_render_ext.h" #include "UI_interface.h" #include "UI_resources.h" #include "mesh_intern.h" /* own include */ #include "bmesh_tools.h" #define USE_FACE_CREATE_SEL_EXTEND static int edbm_subdivide_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int cuts = RNA_int_get(op->ptr, "number_cuts"); float smooth = RNA_float_get(op->ptr, "smoothness"); const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f; const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal"); if (RNA_boolean_get(op->ptr, "quadtri") && RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT) { RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT); } BM_mesh_esubdivide(em->bm, BM_ELEM_SELECT, smooth, SUBD_FALLOFF_LIN, false, fractal, along_normal, cuts, SUBDIV_SELECT_ORIG, RNA_enum_get(op->ptr, "quadcorner"), RNA_boolean_get(op->ptr, "quadtri"), true, false, RNA_int_get(op->ptr, "seed")); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } /* Note, these values must match delete_mesh() event values */ static EnumPropertyItem prop_mesh_cornervert_types[] = { {SUBD_CORNER_INNERVERT, "INNERVERT", 0, "Inner Vert", ""}, {SUBD_CORNER_PATH, "PATH", 0, "Path", ""}, {SUBD_CORNER_STRAIGHT_CUT, "STRAIGHT_CUT", 0, "Straight Cut", ""}, {SUBD_CORNER_FAN, "FAN", 0, "Fan", ""}, {0, NULL, 0, NULL, NULL} }; void MESH_OT_subdivide(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Subdivide"; ot->description = "Subdivide selected edges"; ot->idname = "MESH_OT_subdivide"; /* api callbacks */ ot->exec = edbm_subdivide_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ prop = RNA_def_int(ot->srna, "number_cuts", 1, 1, 100, "Number of Cuts", "", 1, 10); /* avoid re-using last var because it can cause _very_ high poly meshes and annoy users (or worse crash) */ RNA_def_property_flag(prop, PROP_SKIP_SAVE); RNA_def_float(ot->srna, "smoothness", 0.0f, 0.0f, 1e3f, "Smoothness", "Smoothness factor", 0.0f, 1.0f); RNA_def_boolean(ot->srna, "quadtri", 0, "Quad/Tri Mode", "Tries to prevent ngons"); RNA_def_enum(ot->srna, "quadcorner", prop_mesh_cornervert_types, SUBD_CORNER_STRAIGHT_CUT, "Quad Corner Type", "How to subdivide quad corners (anything other than Straight Cut will prevent ngons)"); RNA_def_float(ot->srna, "fractal", 0.0f, 0.0f, 1e6f, "Fractal", "Fractal randomness factor", 0.0f, 1000.0f); RNA_def_float(ot->srna, "fractal_along_normal", 0.0f, 0.0f, 1.0f, "Along Normal", "Apply fractal displacement along normal only", 0.0f, 1.0f); RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Random Seed", "Seed for the random number generator", 0, 255); } /* -------------------------------------------------------------------- */ /* Edge Ring Subdiv * (bridge code shares props) */ struct EdgeRingOpSubdProps { int interp_mode; int cuts; float smooth; int profile_shape; float profile_shape_factor; }; static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_default) { /* Note, these values must match delete_mesh() event values */ static EnumPropertyItem prop_subd_edgering_types[] = { {SUBD_RING_INTERP_LINEAR, "LINEAR", 0, "Linear", ""}, {SUBD_RING_INTERP_PATH, "PATH", 0, "Blend Path", ""}, {SUBD_RING_INTERP_SURF, "SURFACE", 0, "Blend Surface", ""}, {0, NULL, 0, NULL, NULL} }; PropertyRNA *prop; prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, 1000, "Number of Cuts", "", 0, 64); RNA_def_property_flag(prop, PROP_SKIP_SAVE); RNA_def_enum(ot->srna, "interpolation", prop_subd_edgering_types, SUBD_RING_INTERP_PATH, "Interpolation", "Interpolation method"); RNA_def_float(ot->srna, "smoothness", 1.0f, 0.0f, 1e3f, "Smoothness", "Smoothness factor", 0.0f, 2.0f); /* profile-shape */ RNA_def_float(ot->srna, "profile_shape_factor", 0.0f, -1e3f, 1e3f, "Profile Factor", "How much intermediary new edges are shrunk/expanded", -2.0f, 2.0f); prop = RNA_def_property(ot->srna, "profile_shape", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_proportional_falloff_curve_only_items); RNA_def_property_enum_default(prop, PROP_SMOOTH); RNA_def_property_ui_text(prop, "Profile Shape", "Shape of the profile"); RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */ } static void mesh_operator_edgering_props_get(wmOperator *op, struct EdgeRingOpSubdProps *op_props) { op_props->interp_mode = RNA_enum_get(op->ptr, "interpolation"); op_props->cuts = RNA_int_get(op->ptr, "number_cuts"); op_props->smooth = RNA_float_get(op->ptr, "smoothness"); op_props->profile_shape = RNA_enum_get(op->ptr, "profile_shape"); op_props->profile_shape_factor = RNA_float_get(op->ptr, "profile_shape_factor"); } static int edbm_subdivide_edge_ring_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); struct EdgeRingOpSubdProps op_props; mesh_operator_edgering_props_get(op, &op_props); if (!EDBM_op_callf(em, op, "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f " "profile_shape=%i profile_shape_factor=%f", BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth, op_props.profile_shape, op_props.profile_shape_factor)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_subdivide_edgering(wmOperatorType *ot) { /* identifiers */ ot->name = "Subdivide Edge-Ring"; ot->description = ""; ot->idname = "MESH_OT_subdivide_edgering"; /* api callbacks */ ot->exec = edbm_subdivide_edge_ring_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ mesh_operator_edgering_props(ot, 10); } static int edbm_unsubdivide_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const int iterations = RNA_int_get(op->ptr, "iterations"); EDBM_op_init(em, &bmop, op, "unsubdivide verts=%hv iterations=%i", BM_ELEM_SELECT, iterations); BMO_op_exec(em->bm, &bmop); if (!EDBM_op_finish(em, &bmop, op, true)) { return 0; } if ((em->selectmode & SCE_SELECT_VERTEX) == 0) { EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX); /* need to flush vert->face first */ } EDBM_selectmode_flush(em); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_unsubdivide(wmOperatorType *ot) { /* identifiers */ ot->name = "Un-Subdivide"; ot->description = "UnSubdivide selected edges & faces"; ot->idname = "MESH_OT_unsubdivide"; /* api callbacks */ ot->exec = edbm_unsubdivide_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_int(ot->srna, "iterations", 2, 1, 1000, "Iterations", "Number of times to unsubdivide", 1, 100); } void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em) { Object *obedit = em->ob; BMIter iter; BMVert *eve; ED_view3d_init_mats_rv3d(obedit, ar->regiondata); struct SnapObjectContext *snap_context = ED_transform_snap_object_context_create_view3d( CTX_data_main(C), CTX_data_scene(C), 0, ar, CTX_wm_view3d(C)); BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) { float mval[2], co_proj[3]; if (ED_view3d_project_float_object(ar, eve->co, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) { if (ED_transform_snap_object_project_view3d_mixed( snap_context, SCE_SELECT_FACE, &(const struct SnapObjectParams){ .snap_select = SNAP_NOT_ACTIVE, .use_object_edit_cage = false, }, mval, NULL, true, co_proj, NULL)) { mul_v3_m4v3(eve->co, obedit->imat, co_proj); } } } } ED_transform_snap_object_context_destroy(snap_context); } /* Note, these values must match delete_mesh() event values */ enum { MESH_DELETE_VERT = 0, MESH_DELETE_EDGE = 1, MESH_DELETE_FACE = 2, MESH_DELETE_EDGE_FACE = 3, MESH_DELETE_ONLY_FACE = 4, }; static void edbm_report_delete_info(ReportList *reports, BMesh *bm, const int totelem[3]) { BKE_reportf(reports, RPT_INFO, "Removed: %d vertices, %d edges, %d faces", totelem[0] - bm->totvert, totelem[1] - bm->totedge, totelem[2] - bm->totface); } static int edbm_delete_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int type = RNA_enum_get(op->ptr, "type"); switch (type) { case MESH_DELETE_VERT: if (!EDBM_op_callf(em, op, "delete geom=%hv context=%i", BM_ELEM_SELECT, DEL_VERTS)) /* Erase Vertices */ return OPERATOR_CANCELLED; break; case MESH_DELETE_EDGE: if (!EDBM_op_callf(em, op, "delete geom=%he context=%i", BM_ELEM_SELECT, DEL_EDGES)) /* Erase Edges */ return OPERATOR_CANCELLED; break; case MESH_DELETE_FACE: if (!EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_FACES)) /* Erase Faces */ return OPERATOR_CANCELLED; break; case MESH_DELETE_EDGE_FACE: /* Edges and Faces */ if (!EDBM_op_callf(em, op, "delete geom=%hef context=%i", BM_ELEM_SELECT, DEL_EDGESFACES)) return OPERATOR_CANCELLED; break; case MESH_DELETE_ONLY_FACE: /* Only faces. */ if (!EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_ONLYFACES)) return OPERATOR_CANCELLED; break; default: BLI_assert(0); break; } EDBM_flag_disable_all(em, BM_ELEM_SELECT); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_delete(wmOperatorType *ot) { static EnumPropertyItem prop_mesh_delete_types[] = { {MESH_DELETE_VERT, "VERT", 0, "Vertices", ""}, {MESH_DELETE_EDGE, "EDGE", 0, "Edges", ""}, {MESH_DELETE_FACE, "FACE", 0, "Faces", ""}, {MESH_DELETE_EDGE_FACE, "EDGE_FACE", 0, "Only Edges & Faces", ""}, {MESH_DELETE_ONLY_FACE, "ONLY_FACE", 0, "Only Faces", ""}, {0, NULL, 0, NULL, NULL} }; /* identifiers */ ot->name = "Delete"; ot->description = "Delete selected vertices, edges or faces"; ot->idname = "MESH_OT_delete"; /* api callbacks */ ot->invoke = WM_menu_invoke; ot->exec = edbm_delete_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ ot->prop = RNA_def_enum(ot->srna, "type", prop_mesh_delete_types, MESH_DELETE_VERT, "Type", "Method used for deleting mesh data"); } static bool bm_face_is_loose(BMFace *f) { BMLoop *l_iter, *l_first; l_iter = l_first = BM_FACE_FIRST_LOOP(f); do { if (!BM_edge_is_boundary(l_iter->e)) { return false; } } while ((l_iter = l_iter->next) != l_first); return true; } static int edbm_delete_loose_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; BMIter iter; const bool use_verts = (RNA_boolean_get(op->ptr, "use_verts") && bm->totvertsel); const bool use_edges = (RNA_boolean_get(op->ptr, "use_edges") && bm->totedgesel); const bool use_faces = (RNA_boolean_get(op->ptr, "use_faces") && bm->totfacesel); const int totelem[3] = {bm->totvert, bm->totedge, bm->totface}; BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false); if (use_faces) { BMFace *f; BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(f, BM_ELEM_SELECT)) { BM_elem_flag_set(f, BM_ELEM_TAG, bm_face_is_loose(f)); } } BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_FACES); } if (use_edges) { BMEdge *e; BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e, BM_ELEM_SELECT)) { BM_elem_flag_set(e, BM_ELEM_TAG, BM_edge_is_wire(e)); } } BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_EDGES); } if (use_verts) { BMVert *v; BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { BM_elem_flag_set(v, BM_ELEM_TAG, (v->e == NULL)); } } BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_VERTS); } EDBM_flag_disable_all(em, BM_ELEM_SELECT); EDBM_update_generic(em, true, true); edbm_report_delete_info(op->reports, bm, totelem); return OPERATOR_FINISHED; } void MESH_OT_delete_loose(wmOperatorType *ot) { /* identifiers */ ot->name = "Delete Loose"; ot->description = "Delete loose vertices, edges or faces"; ot->idname = "MESH_OT_delete_loose"; /* api callbacks */ ot->exec = edbm_delete_loose_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "use_verts", true, "Vertices", "Remove loose vertices"); RNA_def_boolean(ot->srna, "use_edges", true, "Edges", "Remove loose edges"); RNA_def_boolean(ot->srna, "use_faces", false, "Faces", "Remove loose faces"); } static int edbm_collapse_edge_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); if (!EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, true)) return OPERATOR_CANCELLED; EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_edge_collapse(wmOperatorType *ot) { /* identifiers */ ot->name = "Edge Collapse"; ot->description = "Collapse selected edges"; ot->idname = "MESH_OT_edge_collapse"; /* api callbacks */ ot->exec = edbm_collapse_edge_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static bool edbm_add_edge_face__smooth_get(BMesh *bm) { BMEdge *e; BMIter iter; unsigned int vote_on_smooth[2] = {0, 0}; BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) { vote_on_smooth[BM_elem_flag_test_bool(e->l->f, BM_ELEM_SMOOTH)]++; } } return (vote_on_smooth[0] < vote_on_smooth[1]); } #ifdef USE_FACE_CREATE_SEL_EXTEND /** * Function used to get a fixed number of edges linked to a vertex that passes a test function. * This is used so we can request all boundary edges connected to a vertex for eg. */ static int edbm_add_edge_face_exec__vert_edge_lookup( BMVert *v, BMEdge *e_used, BMEdge **e_arr, const int e_arr_len, bool (* func)(const BMEdge *)) { BMIter iter; BMEdge *e_iter; int i = 0; BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) { if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == false) { if ((e_used == NULL) || (e_used != e_iter)) { if (func(e_iter)) { e_arr[i++] = e_iter; if (i >= e_arr_len) { break; } } } } } return i; } static BMElem *edbm_add_edge_face_exec__tricky_extend_sel(BMesh *bm) { BMIter iter; bool found = false; if (bm->totvertsel == 1 && bm->totedgesel == 0 && bm->totfacesel == 0) { /* first look for 2 boundary edges */ BMVert *v; BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { found = true; break; } } if (found) { BMEdge *ed_pair[3]; if ( ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_wire) == 2) && (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false)) || ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_boundary) == 2) && (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false)) ) { BMEdge *e_other = BM_edge_exists(BM_edge_other_vert(ed_pair[0], v), BM_edge_other_vert(ed_pair[1], v)); BM_edge_select_set(bm, ed_pair[0], true); BM_edge_select_set(bm, ed_pair[1], true); if (e_other) { BM_edge_select_set(bm, e_other, true); } return (BMElem *)v; } } } else if (bm->totvertsel == 2 && bm->totedgesel == 1 && bm->totfacesel == 0) { /* first look for 2 boundary edges */ BMEdge *e; BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e, BM_ELEM_SELECT)) { found = true; break; } } if (found) { BMEdge *ed_pair_v1[2]; BMEdge *ed_pair_v2[2]; if ( ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire) == 1) && (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire) == 1) && (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) && (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) || #if 1 /* better support mixed cases [#37203] */ ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire) == 1) && (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) && (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) && (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) || ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) && (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire) == 1) && (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) && (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) || #endif ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) && (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) && (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) && (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ) { BMVert *v1_other = BM_edge_other_vert(ed_pair_v1[0], e->v1); BMVert *v2_other = BM_edge_other_vert(ed_pair_v2[0], e->v2); BMEdge *e_other = (v1_other != v2_other) ? BM_edge_exists(v1_other, v2_other) : NULL; BM_edge_select_set(bm, ed_pair_v1[0], true); BM_edge_select_set(bm, ed_pair_v2[0], true); if (e_other) { BM_edge_select_set(bm, e_other, true); } return (BMElem *)e; } } } return NULL; } static void edbm_add_edge_face_exec__tricky_finalize_sel(BMesh *bm, BMElem *ele_desel, BMFace *f) { /* now we need to find the edge that isnt connected to this element */ BM_select_history_clear(bm); /* Notes on hidden geometry: * - un-hide the face since its possible hidden was copied when copying surrounding face attributes. * - un-hide before adding to select history * since we may extend into an existing, hidden vert/edge. */ BM_elem_flag_disable(f, BM_ELEM_HIDDEN); BM_face_select_set(bm, f, false); if (ele_desel->head.htype == BM_VERT) { BMLoop *l = BM_face_vert_share_loop(f, (BMVert *)ele_desel); BLI_assert(f->len == 3); BM_vert_select_set(bm, (BMVert *)ele_desel, false); BM_edge_select_set(bm, l->next->e, true); BM_select_history_store(bm, l->next->e); } else { BMLoop *l = BM_face_edge_share_loop(f, (BMEdge *)ele_desel); BLI_assert(f->len == 4 || f->len == 3); BM_edge_select_set(bm, (BMEdge *)ele_desel, false); if (f->len == 4) { BMEdge *e_active = l->next->next->e; BM_elem_flag_disable(e_active, BM_ELEM_HIDDEN); BM_edge_select_set(bm, e_active, true); BM_select_history_store(bm, e_active); } else { BMVert *v_active = l->next->next->v; BM_elem_flag_disable(v_active, BM_ELEM_HIDDEN); BM_vert_select_set(bm, v_active, true); BM_select_history_store(bm, v_active); } } } #endif /* USE_FACE_CREATE_SEL_EXTEND */ static int edbm_add_edge_face_exec(bContext *C, wmOperator *op) { BMOperator bmop; Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_smooth = edbm_add_edge_face__smooth_get(em->bm); const int totedge_orig = em->bm->totedge; const int totface_orig = em->bm->totface; /* when this is used to dissolve we could avoid this, but checking isnt too slow */ #ifdef USE_FACE_CREATE_SEL_EXTEND BMElem *ele_desel; BMFace *ele_desel_face; /* be extra clever, figure out if a partial selection should be extended so we can create geometry * with single vert or single edge selection */ ele_desel = edbm_add_edge_face_exec__tricky_extend_sel(em->bm); #endif if (!EDBM_op_init(em, &bmop, op, "contextual_create geom=%hfev mat_nr=%i use_smooth=%b", BM_ELEM_SELECT, em->mat_nr, use_smooth)) { return OPERATOR_CANCELLED; } BMO_op_exec(em->bm, &bmop); /* cancel if nothing was done */ if ((totedge_orig == em->bm->totedge) && (totface_orig == em->bm->totface)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } #ifdef USE_FACE_CREATE_SEL_EXTEND /* normally we would want to leave the new geometry selected, * but being able to press F many times to add geometry is too useful! */ if (ele_desel && (BMO_slot_buffer_count(bmop.slots_out, "faces.out") == 1) && (ele_desel_face = BMO_slot_buffer_get_first(bmop.slots_out, "faces.out"))) { edbm_add_edge_face_exec__tricky_finalize_sel(em->bm, ele_desel, ele_desel_face); } else #endif { /* Newly created faces may include existing hidden edges, * copying face data from surrounding, may have copied hidden face flag too. * * Important that faces use flushing since 'edges.out' wont include hidden edges that already existed. */ BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_HIDDEN, true); BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, false); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true); } if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_edge_face_add(wmOperatorType *ot) { /* identifiers */ ot->name = "Make Edge/Face"; ot->description = "Add an edge or face to selected"; ot->idname = "MESH_OT_edge_face_add"; /* api callbacks */ ot->exec = edbm_add_edge_face_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* ************************* SEAMS AND EDGES **************** */ static int edbm_mark_seam_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Object *obedit = CTX_data_edit_object(C); Mesh *me = ((Mesh *)obedit->data); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; BMEdge *eed; BMIter iter; const bool clear = RNA_boolean_get(op->ptr, "clear"); /* auto-enable seams drawing */ if (clear == 0) { me->drawflag |= ME_DRAWSEAMS; } if (clear) { BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) { if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) continue; BM_elem_flag_disable(eed, BM_ELEM_SEAM); } } else { BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) { if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) continue; BM_elem_flag_enable(eed, BM_ELEM_SEAM); } } ED_uvedit_live_unwrap(scene, obedit); EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_mark_seam(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Mark Seam"; ot->idname = "MESH_OT_mark_seam"; ot->description = "(Un)mark selected edges as a seam"; /* api callbacks */ ot->exec = edbm_mark_seam_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", ""); RNA_def_property_flag(prop, PROP_SKIP_SAVE); } static int edbm_mark_sharp_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = ((Mesh *)obedit->data); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; BMEdge *eed; BMIter iter; const bool clear = RNA_boolean_get(op->ptr, "clear"); const bool use_verts = RNA_boolean_get(op->ptr, "use_verts"); /* auto-enable sharp edge drawing */ if (clear == 0) { me->drawflag |= ME_DRAWSHARP; } BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) { if (use_verts) { if (!(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) || BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))) { continue; } } else if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) { continue; } BM_elem_flag_set(eed, BM_ELEM_SMOOTH, clear); } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_mark_sharp(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Mark Sharp"; ot->idname = "MESH_OT_mark_sharp"; ot->description = "(Un)mark selected edges as sharp"; /* api callbacks */ ot->exec = edbm_mark_sharp_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); RNA_def_property_flag(prop, PROP_SKIP_SAVE); prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices", "Consider vertices instead of edges to select which edges to (un)tag as sharp"); RNA_def_property_flag(prop, PROP_SKIP_SAVE); } static int edbm_vert_connect_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; BMOperator bmop; bool is_pair = (bm->totvertsel == 2); int len = 0; bool check_degenerate = true; const int verts_len = bm->totvertsel; BMVert **verts; verts = MEM_mallocN(sizeof(*verts) * verts_len, __func__); { BMIter iter; BMVert *v; int i = 0; BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { verts[i++] = v; } } if (is_pair) { if (BM_vert_pair_share_face_check_cb( verts[0], verts[1], BM_elem_cb_check_hflag_disabled_simple(BMFace *, BM_ELEM_HIDDEN))) { check_degenerate = false; is_pair = false; } } } if (is_pair) { if (!EDBM_op_init(em, &bmop, op, "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf", verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN)) { goto finally; } } else { if (!EDBM_op_init(em, &bmop, op, "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b", verts, verts_len, BM_ELEM_HIDDEN, check_degenerate)) { goto finally; } } BMO_op_exec(bm, &bmop); len = BMO_slot_get(bmop.slots_out, "edges.out")->len; if (len) { if (is_pair) { /* new verts have been added, we have to select the edges, not just flush */ BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true); } } if (!EDBM_op_finish(em, &bmop, op, true)) { len = 0; } else { EDBM_selectmode_flush(em); /* so newly created edges get the selection state from the vertex */ EDBM_update_generic(em, true, true); } finally: MEM_freeN(verts); return len ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } void MESH_OT_vert_connect(wmOperatorType *ot) { /* identifiers */ ot->name = "Vertex Connect"; ot->idname = "MESH_OT_vert_connect"; ot->description = "Connect selected vertices of faces, splitting the face"; /* api callbacks */ ot->exec = edbm_vert_connect_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /** * check that endpoints are verts and only have a single selected edge connected. */ static bool bm_vert_is_select_history_open(BMesh *bm) { BMEditSelection *ele_a = bm->selected.first; BMEditSelection *ele_b = bm->selected.last; if ((ele_a->htype == BM_VERT) && (ele_b->htype == BM_VERT)) { if ((BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_a->ele, BM_ELEM_SELECT, true) == 1) && (BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_b->ele, BM_ELEM_SELECT, true) == 1)) { return true; } } return false; } static bool bm_vert_connect_pair(BMesh *bm, BMVert *v_a, BMVert *v_b) { BMOperator bmop; BMVert **verts; const int totedge_orig = bm->totedge; BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, "connect_vert_pair"); verts = BMO_slot_buffer_alloc(&bmop, bmop.slots_in, "verts", 2); verts[0] = v_a; verts[1] = v_b; BM_vert_normal_update(verts[0]); BM_vert_normal_update(verts[1]); BMO_op_exec(bm, &bmop); BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true); BMO_op_finish(bm, &bmop); return (bm->totedge != totedge_orig); } static bool bm_vert_connect_select_history(BMesh *bm) { /* Logic is as follows: * * - If there are any isolated/wire verts - connect as edges. * - Otherwise connect faces. * - If all edges have been created already, closed the loop. */ if (BLI_listbase_count_ex(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) { BMEditSelection *ese; int tot = 0; bool changed = false; bool has_wire = false; // bool all_verts; /* ensure all verts have history */ for (ese = bm->selected.first; ese; ese = ese->next, tot++) { BMVert *v; if (ese->htype != BM_VERT) { break; } v = (BMVert *)ese->ele; if ((has_wire == false) && ((v->e == NULL) || BM_vert_is_wire(v))) { has_wire = true; } } // all_verts = (ese == NULL); if (has_wire == false) { /* all verts have faces , connect verts via faces! */ if (tot == bm->totvertsel) { BMEditSelection *ese_last; ese_last = bm->selected.first; ese = ese_last->next; do { if (BM_edge_exists((BMVert *)ese_last->ele, (BMVert *)ese->ele)) { /* pass, edge exists (and will be selected) */ } else { changed |= bm_vert_connect_pair(bm, (BMVert *)ese_last->ele, (BMVert *)ese->ele); } } while ((void) (ese_last = ese), (ese = ese->next)); if (changed) { return true; } } if (changed == false) { /* existing loops: close the selection */ if (bm_vert_is_select_history_open(bm)) { changed |= bm_vert_connect_pair( bm, (BMVert *)((BMEditSelection *)bm->selected.first)->ele, (BMVert *)((BMEditSelection *)bm->selected.last)->ele); if (changed) { return true; } } } } else { /* no faces, simply connect the verts by edges */ BMEditSelection *ese_prev; ese_prev = bm->selected.first; ese = ese_prev->next; do { if (BM_edge_exists((BMVert *)ese_prev->ele, (BMVert *)ese->ele)) { /* pass, edge exists (and will be selected) */ } else { BMEdge *e; e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0); BM_edge_select_set(bm, e, true); changed = true; } } while ((void) (ese_prev = ese), (ese = ese->next)); if (changed == false) { /* existing loops: close the selection */ if (bm_vert_is_select_history_open(bm)) { BMEdge *e; ese_prev = bm->selected.first; ese = bm->selected.last; e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0); BM_edge_select_set(bm, e, true); } } return true; } } return false; } /** * Convert an edge selection to a temp vertex selection * (which must be cleared after use as a path to connect). */ static bool bm_vert_connect_select_history_edge_to_vert_path(BMesh *bm, ListBase *r_selected) { ListBase selected_orig = {NULL, NULL}; BMEditSelection *ese; int edges_len = 0; bool side = false; /* first check all edges are OK */ for (ese = bm->selected.first; ese; ese = ese->next) { if (ese->htype == BM_EDGE) { edges_len += 1; } else { return false; } } /* if this is a mixed selection, bail out! */ if (bm->totedgesel != edges_len) { return false; } SWAP(ListBase, bm->selected, selected_orig); /* convert edge selection into 2 ordered loops (where the first edge ends up in the middle) */ for (ese = selected_orig.first; ese; ese = ese->next) { BMEdge *e_curr = (BMEdge *)ese->ele; BMEdge *e_prev = ese->prev ? (BMEdge *)ese->prev->ele : NULL; BMLoop *l_curr; BMLoop *l_prev; BMVert *v; if (e_prev) { BMFace *f = BM_edge_pair_share_face_by_len(e_curr, e_prev, &l_curr, &l_prev, true); if (f) { if ((e_curr->v1 != l_curr->v) == (e_prev->v1 != l_prev->v)) { side = !side; } } else if (is_quad_flip_v3(e_curr->v1->co, e_curr->v2->co, e_prev->v2->co, e_prev->v1->co)) { side = !side; } } v = (&e_curr->v1)[side]; if (!bm->selected.last || (BMVert *)((BMEditSelection *)bm->selected.last)->ele != v) { BM_select_history_store_notest(bm, v); } v = (&e_curr->v1)[!side]; if (!bm->selected.first || (BMVert *)((BMEditSelection *)bm->selected.first)->ele != v) { BM_select_history_store_head_notest(bm, v); } e_prev = e_curr; } *r_selected = bm->selected; bm->selected = selected_orig; return true; } static int edbm_vert_connect_path_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; bool is_pair = (em->bm->totvertsel == 2); ListBase selected_orig = {NULL, NULL}; int retval; /* when there is only 2 vertices, we can ignore selection order */ if (is_pair) { return edbm_vert_connect_exec(C, op); } if (bm->selected.first) { BMEditSelection *ese = bm->selected.first; if (ese->htype == BM_EDGE) { if (bm_vert_connect_select_history_edge_to_vert_path(bm, &selected_orig)) { SWAP(ListBase, bm->selected, selected_orig); } } } if (bm_vert_connect_select_history(bm)) { EDBM_selectmode_flush(em); EDBM_update_generic(em, true, true); retval = OPERATOR_FINISHED; } else { BKE_report(op->reports, RPT_ERROR, "Invalid selection order"); retval = OPERATOR_CANCELLED; } if (!BLI_listbase_is_empty(&selected_orig)) { BM_select_history_clear(bm); bm->selected = selected_orig; } return retval; } void MESH_OT_vert_connect_path(wmOperatorType *ot) { /* identifiers */ ot->name = "Vertex Connect Path"; ot->idname = "MESH_OT_vert_connect_path"; ot->description = "Connect vertices by their selection order, creating edges, splitting faces"; /* api callbacks */ ot->exec = edbm_vert_connect_path_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int edbm_vert_connect_concave_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); if (!EDBM_op_call_and_selectf( em, op, "faces.out", true, "connect_verts_concave faces=%hf", BM_ELEM_SELECT)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_vert_connect_concave(wmOperatorType *ot) { /* identifiers */ ot->name = "Split Concave Faces"; ot->idname = "MESH_OT_vert_connect_concave"; ot->description = "Make all faces convex"; /* api callbacks */ ot->exec = edbm_vert_connect_concave_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const float angle_limit = RNA_float_get(op->ptr, "angle_limit"); if (!EDBM_op_call_and_selectf( em, op, "faces.out", true, "connect_verts_nonplanar faces=%hf angle_limit=%f", BM_ELEM_SELECT, angle_limit)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Split Non-Planar Faces"; ot->idname = "MESH_OT_vert_connect_nonplanar"; ot->description = "Split non-planar faces that exceed the angle threshold"; /* api callbacks */ ot->exec = edbm_vert_connect_nonplaner_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f), "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f)); RNA_def_property_float_default(prop, DEG2RADF(5.0f)); } static int edbm_face_make_planar_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int repeat = RNA_int_get(op->ptr, "repeat"); const float fac = RNA_float_get(op->ptr, "factor"); if (!EDBM_op_callf( em, op, "planar_faces faces=%hf iterations=%i factor=%f", BM_ELEM_SELECT, repeat, fac)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_face_make_planar(wmOperatorType *ot) { /* identifiers */ ot->name = "Make Planar Faces"; ot->idname = "MESH_OT_face_make_planar"; ot->description = "Flatten selected faces"; /* api callbacks */ ot->exec = edbm_face_make_planar_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_float(ot->srna, "factor", 1.0f, -10.0f, 10.0f, "Factor", "", 0.0f, 1.0f); RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200); } static int edbm_edge_split_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); if (!EDBM_op_call_and_selectf( em, op, "edges.out", false, "split_edges edges=%he", BM_ELEM_SELECT)) { return OPERATOR_CANCELLED; } if (em->selectmode == SCE_SELECT_FACE) { EDBM_select_flush(em); } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_edge_split(wmOperatorType *ot) { /* identifiers */ ot->name = "Edge Split"; ot->idname = "MESH_OT_edge_split"; ot->description = "Split selected edges so that each neighbor face gets its own copy"; /* api callbacks */ ot->exec = edbm_edge_split_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /****************** add duplicate operator ***************/ static int edbm_duplicate_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMesh *bm = em->bm; BMOperator bmop; EDBM_op_init( em, &bmop, op, "duplicate geom=%hvef use_select_history=%b", BM_ELEM_SELECT, true); BMO_op_exec(bm, &bmop); /* de-select all would clear otherwise */ BM_SELECT_HISTORY_BACKUP(bm); EDBM_flag_disable_all(em, BM_ELEM_SELECT); BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true); /* rebuild editselection */ BM_SELECT_HISTORY_RESTORE(bm); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { WM_cursor_wait(1); edbm_duplicate_exec(C, op); WM_cursor_wait(0); return OPERATOR_FINISHED; } void MESH_OT_duplicate(wmOperatorType *ot) { /* identifiers */ ot->name = "Duplicate"; ot->description = "Duplicate selected vertices, edges or faces"; ot->idname = "MESH_OT_duplicate"; /* api callbacks */ ot->invoke = edbm_duplicate_invoke; ot->exec = edbm_duplicate_exec; ot->poll = ED_operator_editmesh; /* to give to transform */ RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX); } static int edbm_flip_normals_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); if (!EDBM_op_callf( em, op, "reverse_faces faces=%hf flip_multires=%b", BM_ELEM_SELECT, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_flip_normals(wmOperatorType *ot) { /* identifiers */ ot->name = "Flip Normals"; ot->description = "Flip the direction of selected faces' normals (and of their vertices)"; ot->idname = "MESH_OT_flip_normals"; /* api callbacks */ ot->exec = edbm_flip_normals_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* only accepts 1 selected edge, or 2 selected faces */ static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; BMEdge *eed; BMIter iter; const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw"); int tot = 0; if (em->bm->totedgesel == 0) { BKE_report(op->reports, RPT_ERROR, "Select edges or face pairs for edge loops to rotate about"); return OPERATOR_CANCELLED; } /* first see if we have two adjacent faces */ BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) { BM_elem_flag_disable(eed, BM_ELEM_TAG); if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) { BMFace *fa, *fb; if (BM_edge_face_pair(eed, &fa, &fb)) { /* if both faces are selected we rotate between them, * otherwise - rotate between 2 unselected - but not mixed */ if (BM_elem_flag_test(fa, BM_ELEM_SELECT) == BM_elem_flag_test(fb, BM_ELEM_SELECT)) { BM_elem_flag_enable(eed, BM_ELEM_TAG); tot++; } } } } /* ok, we don't have two adjacent faces, but we do have two selected ones. * that's an error condition.*/ if (tot == 0) { BKE_report(op->reports, RPT_ERROR, "Could not find any selected edges that can be rotated"); return OPERATOR_CANCELLED; } EDBM_op_init(em, &bmop, op, "rotate_edges edges=%he use_ccw=%b", BM_ELEM_TAG, use_ccw); /* avoids leaving old verts selected which can be a problem running multiple times, * since this means the edges become selected around the face which then attempt to rotate */ BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_in, "edges", BM_EDGE, BM_ELEM_SELECT, true); BMO_op_exec(em->bm, &bmop); /* edges may rotate into hidden vertices, if this does _not_ run we get an ilogical state */ BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, true); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true); const int tot_rotate = BMO_slot_buffer_count(bmop.slots_out, "edges.out"); const int tot_failed = tot - tot_rotate; if (tot_failed != 0) { /* If some edges fail to rotate, we need to re-select them, * otherwise we can end up with invalid selection * (unselected edge between 2 selected faces). */ BM_mesh_elem_hflag_enable_test(em->bm, BM_EDGE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG); BKE_reportf(op->reports, RPT_WARNING, "Unable to rotate %d edge(s)", tot_failed); } EDBM_selectmode_flush(em); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_edge_rotate(wmOperatorType *ot) { /* identifiers */ ot->name = "Rotate Selected Edge"; ot->description = "Rotate selected edge or adjoining faces"; ot->idname = "MESH_OT_edge_rotate"; /* api callbacks */ ot->exec = edbm_edge_rotate_selected_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", ""); } static int edbm_hide_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); EDBM_mesh_hide(em, RNA_boolean_get(op->ptr, "unselected")); EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_hide(wmOperatorType *ot) { /* identifiers */ ot->name = "Hide Selection"; ot->idname = "MESH_OT_hide"; ot->description = "Hide (un)selected vertices, edges or faces"; /* api callbacks */ ot->exec = edbm_hide_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "unselected", false, "Unselected", "Hide unselected rather than selected"); } static int edbm_reveal_exec(bContext *C, wmOperator *UNUSED(op)) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); EDBM_mesh_reveal(em); EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_reveal(wmOperatorType *ot) { /* identifiers */ ot->name = "Reveal Hidden"; ot->idname = "MESH_OT_reveal"; ot->description = "Reveal all hidden vertices, edges and faces"; /* api callbacks */ ot->exec = edbm_reveal_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); /* doflip has to do with bmesh_rationalize_normals, it's an internal * thing */ if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT)) return OPERATOR_CANCELLED; if (RNA_boolean_get(op->ptr, "inside")) { EDBM_op_callf(em, op, "reverse_faces faces=%hf flip_multires=%b", BM_ELEM_SELECT, true); } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_normals_make_consistent(wmOperatorType *ot) { /* identifiers */ ot->name = "Make Normals Consistent"; ot->description = "Make face and vertex normals point either outside or inside the mesh"; ot->idname = "MESH_OT_normals_make_consistent"; /* api callbacks */ ot->exec = edbm_normals_make_consistent_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_boolean(ot->srna, "inside", false, "Inside", ""); } static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = obedit->data; BMEditMesh *em = BKE_editmesh_from_object(obedit); ModifierData *md; bool mirrx = false, mirry = false, mirrz = false; int i, repeat; float clip_dist = 0.0f; const float fac = RNA_float_get(op->ptr, "factor"); const bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0; const bool xaxis = RNA_boolean_get(op->ptr, "xaxis"); const bool yaxis = RNA_boolean_get(op->ptr, "yaxis"); const bool zaxis = RNA_boolean_get(op->ptr, "zaxis"); /* mirror before smooth */ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) { EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology); } /* if there is a mirror modifier with clipping, flag the verts that * are within tolerance of the plane(s) of reflection */ for (md = obedit->modifiers.first; md; md = md->next) { if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) { MirrorModifierData *mmd = (MirrorModifierData *)md; if (mmd->flag & MOD_MIR_CLIPPING) { if (mmd->flag & MOD_MIR_AXIS_X) mirrx = true; if (mmd->flag & MOD_MIR_AXIS_Y) mirry = true; if (mmd->flag & MOD_MIR_AXIS_Z) mirrz = true; clip_dist = mmd->tolerance; } } } repeat = RNA_int_get(op->ptr, "repeat"); if (!repeat) repeat = 1; for (i = 0; i < repeat; i++) { if (!EDBM_op_callf(em, op, "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b " "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b", BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis)) { return OPERATOR_CANCELLED; } } /* apply mirror */ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) { EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0); EDBM_verts_mirror_cache_end(em); } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_vertices_smooth(wmOperatorType *ot) { /* identifiers */ ot->name = "Smooth Vertex"; ot->description = "Flatten angles of selected vertices"; ot->idname = "MESH_OT_vertices_smooth"; /* api callbacks */ ot->exec = edbm_do_smooth_vertex_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float(ot->srna, "factor", 0.5f, -10.0f, 10.0f, "Smoothing", "Smoothing factor", 0.0f, 1.0f); RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Repeat", "Number of times to smooth the mesh", 1, 100); RNA_def_boolean(ot->srna, "xaxis", true, "X-Axis", "Smooth along the X axis"); RNA_def_boolean(ot->srna, "yaxis", true, "Y-Axis", "Smooth along the Y axis"); RNA_def_boolean(ot->srna, "zaxis", true, "Z-Axis", "Smooth along the Z axis"); } static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); Mesh *me = obedit->data; bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0; bool usex = true, usey = true, usez = true, preserve_volume = true; int i, repeat; float lambda_factor; float lambda_border; BMIter fiter; BMFace *f; /* Check if select faces are triangles */ BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(f, BM_ELEM_SELECT)) { if (f->len > 4) { BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads"); return OPERATOR_CANCELLED; } } } /* mirror before smooth */ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) { EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology); } repeat = RNA_int_get(op->ptr, "repeat"); lambda_factor = RNA_float_get(op->ptr, "lambda_factor"); lambda_border = RNA_float_get(op->ptr, "lambda_border"); usex = RNA_boolean_get(op->ptr, "use_x"); usey = RNA_boolean_get(op->ptr, "use_y"); usez = RNA_boolean_get(op->ptr, "use_z"); preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume"); if (!repeat) repeat = 1; for (i = 0; i < repeat; i++) { if (!EDBM_op_callf(em, op, "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b", BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume)) { return OPERATOR_CANCELLED; } } /* apply mirror */ if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) { EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0); EDBM_verts_mirror_cache_end(em); } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot) { /* identifiers */ ot->name = "Laplacian Smooth Vertex"; ot->description = "Laplacian smooth of selected vertices"; ot->idname = "MESH_OT_vertices_smooth_laplacian"; /* api callbacks */ ot->exec = edbm_do_smooth_laplacian_vertex_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Number of iterations to smooth the mesh", "", 1, 200); RNA_def_float(ot->srna, "lambda_factor", 5e-5f, 1e-7f, 1000.0f, "Lambda factor", "", 1e-7f, 1000.0f); RNA_def_float(ot->srna, "lambda_border", 5e-5f, 1e-7f, 1000.0f, "Lambda factor in border", "", 1e-7f, 1000.0f); RNA_def_boolean(ot->srna, "use_x", true, "Smooth X Axis", "Smooth object along X axis"); RNA_def_boolean(ot->srna, "use_y", true, "Smooth Y Axis", "Smooth object along Y axis"); RNA_def_boolean(ot->srna, "use_z", true, "Smooth Z Axis", "Smooth object along Z axis"); RNA_def_boolean(ot->srna, "preserve_volume", true, "Preserve Volume", "Apply volume preservation after smooth"); } /********************** Smooth/Solid Operators *************************/ static void mesh_set_smooth_faces(BMEditMesh *em, short smooth) { BMIter iter; BMFace *efa; if (em == NULL) return; BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) { BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth); } } } static int edbm_faces_shade_smooth_exec(bContext *C, wmOperator *UNUSED(op)) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); mesh_set_smooth_faces(em, 1); EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } void MESH_OT_faces_shade_smooth(wmOperatorType *ot) { /* identifiers */ ot->name = "Shade Smooth"; ot->description = "Display faces smooth (using vertex normals)"; ot->idname = "MESH_OT_faces_shade_smooth"; /* api callbacks */ ot->exec = edbm_faces_shade_smooth_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op)) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); mesh_set_smooth_faces(em, 0); EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } void MESH_OT_faces_shade_flat(wmOperatorType *ot) { /* identifiers */ ot->name = "Shade Flat"; ot->description = "Display faces flat"; ot->idname = "MESH_OT_faces_shade_flat"; /* api callbacks */ ot->exec = edbm_faces_shade_flat_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** UV/Color Operators *************************/ static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMOperator bmop; /* get the direction from RNA */ const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw"); /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */ EDBM_op_init(em, &bmop, op, "rotate_uvs faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw); /* execute the operator */ BMO_op_exec(em->bm, &bmop); /* finish the operator */ if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } static int edbm_reverse_uvs_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMOperator bmop; /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */ EDBM_op_init(em, &bmop, op, "reverse_uvs faces=%hf", BM_ELEM_SELECT); /* execute the operator */ BMO_op_exec(em->bm, &bmop); /* finish the operator */ if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } static int edbm_rotate_colors_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMOperator bmop; /* get the direction from RNA */ const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw"); /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */ EDBM_op_init(em, &bmop, op, "rotate_colors faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw); /* execute the operator */ BMO_op_exec(em->bm, &bmop); /* finish the operator */ if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } /* dependencies graph and notification stuff */ EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } static int edbm_reverse_colors_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMOperator bmop; /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */ EDBM_op_init(em, &bmop, op, "reverse_colors faces=%hf", BM_ELEM_SELECT); /* execute the operator */ BMO_op_exec(em->bm, &bmop); /* finish the operator */ if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } void MESH_OT_uvs_rotate(wmOperatorType *ot) { /* identifiers */ ot->name = "Rotate UVs"; ot->idname = "MESH_OT_uvs_rotate"; ot->description = "Rotate UV coordinates inside faces"; /* api callbacks */ ot->exec = edbm_rotate_uvs_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", ""); } void MESH_OT_uvs_reverse(wmOperatorType *ot) { /* identifiers */ ot->name = "Reverse UVs"; ot->idname = "MESH_OT_uvs_reverse"; ot->description = "Flip direction of UV coordinates inside faces"; /* api callbacks */ ot->exec = edbm_reverse_uvs_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror UVs around"); } void MESH_OT_colors_rotate(wmOperatorType *ot) { /* identifiers */ ot->name = "Rotate Colors"; ot->idname = "MESH_OT_colors_rotate"; ot->description = "Rotate vertex colors inside faces"; /* api callbacks */ ot->exec = edbm_rotate_colors_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", ""); } void MESH_OT_colors_reverse(wmOperatorType *ot) { /* identifiers */ ot->name = "Reverse Colors"; ot->idname = "MESH_OT_colors_reverse"; ot->description = "Flip direction of vertex colors inside faces"; /* api callbacks */ ot->exec = edbm_reverse_colors_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around"); } enum { MESH_MERGE_LAST = 1, MESH_MERGE_CENTER = 3, MESH_MERGE_CURSOR = 4, MESH_MERGE_COLLAPSE = 5, MESH_MERGE_FIRST = 6, }; static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use_uvmerge, wmOperator *wmop) { BMVert *mergevert; BMEditSelection *ese; /* operator could be called directly from shortcut or python, * so do extra check for data here */ /* do sanity check in mergemenu in edit.c ?*/ if (use_first == false) { if (!em->bm->selected.last || ((BMEditSelection *)em->bm->selected.last)->htype != BM_VERT) return false; ese = em->bm->selected.last; mergevert = (BMVert *)ese->ele; } else { if (!em->bm->selected.first || ((BMEditSelection *)em->bm->selected.first)->htype != BM_VERT) return false; ese = em->bm->selected.first; mergevert = (BMVert *)ese->ele; } if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT)) return false; if (use_uvmerge) { if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert)) return false; } if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, mergevert->co)) return false; return true; } static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob, const bool use_cursor, const bool use_uvmerge, wmOperator *wmop) { BMIter iter; BMVert *v; float co[3], cent[3] = {0.0f, 0.0f, 0.0f}; const float *vco = NULL; if (use_cursor) { vco = ED_view3d_cursor3d_get(scene, v3d); copy_v3_v3(co, vco); mul_m4_v3(ob->imat, co); } else { float fac; int i = 0; BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) { if (!BM_elem_flag_test(v, BM_ELEM_SELECT)) continue; add_v3_v3(cent, v->co); i++; } if (!i) return false; fac = 1.0f / (float)i; mul_v3_fl(cent, fac); copy_v3_v3(co, cent); vco = co; } if (!vco) return false; if (use_uvmerge) { if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT)) return false; } if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, co)) return false; return true; } static int edbm_merge_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); View3D *v3d = CTX_wm_view3d(C); Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int type = RNA_enum_get(op->ptr, "type"); const bool uvs = RNA_boolean_get(op->ptr, "uvs"); bool ok = false; switch (type) { case MESH_MERGE_CENTER: ok = merge_target(em, scene, v3d, obedit, false, uvs, op); break; case MESH_MERGE_CURSOR: ok = merge_target(em, scene, v3d, obedit, true, uvs, op); break; case MESH_MERGE_LAST: ok = merge_firstlast(em, false, uvs, op); break; case MESH_MERGE_FIRST: ok = merge_firstlast(em, true, uvs, op); break; case MESH_MERGE_COLLAPSE: ok = EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, uvs); break; default: BLI_assert(0); break; } if (!ok) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); /* once collapsed, we can't have edge/face selection */ if ((em->selectmode & SCE_SELECT_VERTEX) == 0) { EDBM_flag_disable_all(em, BM_ELEM_SELECT); } return OPERATOR_FINISHED; } static EnumPropertyItem merge_type_items[] = { {MESH_MERGE_FIRST, "FIRST", 0, "At First", ""}, {MESH_MERGE_LAST, "LAST", 0, "At Last", ""}, {MESH_MERGE_CENTER, "CENTER", 0, "At Center", ""}, {MESH_MERGE_CURSOR, "CURSOR", 0, "At Cursor", ""}, {MESH_MERGE_COLLAPSE, "COLLAPSE", 0, "Collapse", ""}, {0, NULL, 0, NULL, NULL} }; static EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) { Object *obedit; EnumPropertyItem *item = NULL; int totitem = 0; if (!C) /* needed for docs */ return merge_type_items; obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_MESH) { BMEditMesh *em = BKE_editmesh_from_object(obedit); if (em->selectmode & SCE_SELECT_VERTEX) { if (em->bm->selected.first && em->bm->selected.last && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) { RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST); RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST); } else if (em->bm->selected.first && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT) { RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST); } else if (em->bm->selected.last && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) { RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST); } } RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CENTER); RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CURSOR); RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_COLLAPSE); RNA_enum_item_end(&item, &totitem); *r_free = true; return item; } return NULL; } void MESH_OT_merge(wmOperatorType *ot) { /* identifiers */ ot->name = "Merge"; ot->description = "Merge selected vertices"; ot->idname = "MESH_OT_merge"; /* api callbacks */ ot->exec = edbm_merge_exec; ot->invoke = WM_menu_invoke; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ ot->prop = RNA_def_enum(ot->srna, "type", merge_type_items, MESH_MERGE_CENTER, "Type", "Merge method to use"); RNA_def_enum_funcs(ot->prop, merge_type_itemf); RNA_def_boolean(ot->srna, "uvs", false, "UVs", "Move UVs according to merge"); } static int edbm_remove_doubles_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const float threshold = RNA_float_get(op->ptr, "threshold"); const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected"); const int totvert_orig = em->bm->totvert; int count; char htype_select; /* avoid loosing selection state (select -> tags) */ if (em->selectmode & SCE_SELECT_VERTEX) htype_select = BM_VERT; else if (em->selectmode & SCE_SELECT_EDGE) htype_select = BM_EDGE; else htype_select = BM_FACE; /* store selection as tags */ BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_TAG, true, true, BM_ELEM_SELECT); if (use_unselected) { EDBM_op_init(em, &bmop, op, "automerge verts=%hv dist=%f", BM_ELEM_SELECT, threshold); BMO_op_exec(em->bm, &bmop); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } } else { EDBM_op_init(em, &bmop, op, "find_doubles verts=%hv dist=%f", BM_ELEM_SELECT, threshold); BMO_op_exec(em->bm, &bmop); if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) { BMO_op_finish(em->bm, &bmop); return OPERATOR_CANCELLED; } if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } } count = totvert_orig - em->bm->totvert; BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count); /* restore selection from tags */ BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_SELECT, true, true, BM_ELEM_TAG); EDBM_selectmode_flush(em); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_remove_doubles(wmOperatorType *ot) { /* identifiers */ ot->name = "Remove Doubles"; ot->description = "Remove duplicate vertices"; ot->idname = "MESH_OT_remove_doubles"; /* api callbacks */ ot->exec = edbm_remove_doubles_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float_distance(ot->srna, "threshold", 1e-4f, 1e-6f, 50.0f, "Merge Distance", "Minimum distance between elements to merge", 1e-5f, 10.0f); RNA_def_boolean(ot->srna, "use_unselected", false, "Unselected", "Merge selected to other unselected vertices"); } /************************ Shape Operators *************************/ /* BMESH_TODO this should be properly encapsulated in a bmop. but later.*/ static void shape_propagate(BMEditMesh *em, wmOperator *op) { BMIter iter; BMVert *eve = NULL; float *co; int i, totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY); if (!CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) { BKE_report(op->reports, RPT_ERROR, "Mesh does not have shape keys"); return; } BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) { if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) continue; for (i = 0; i < totshape; i++) { co = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, i); copy_v3_v3(co, eve->co); } } #if 0 //TAG Mesh Objects that share this data for (base = scene->base.first; base; base = base->next) { if (base->object && base->object->data == me) { DAG_id_tag_update(&base->object->id, OB_RECALC_DATA); } } #endif } static int edbm_shape_propagate_to_all_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = obedit->data; BMEditMesh *em = me->edit_btmesh; shape_propagate(em, op); EDBM_update_generic(em, false, false); return OPERATOR_FINISHED; } void MESH_OT_shape_propagate_to_all(wmOperatorType *ot) { /* identifiers */ ot->name = "Shape Propagate"; ot->description = "Apply selected vertex locations to all other shape keys"; ot->idname = "MESH_OT_shape_propagate_to_all"; /* api callbacks */ ot->exec = edbm_shape_propagate_to_all_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* BMESH_TODO this should be properly encapsulated in a bmop. but later.*/ static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = obedit->data; Key *key = me->key; KeyBlock *kb = NULL; BMEditMesh *em = me->edit_btmesh; BMVert *eve; BMIter iter; float co[3], *sco; int totshape; const float blend = RNA_float_get(op->ptr, "blend"); const int shape = RNA_enum_get(op->ptr, "shape"); const bool use_add = RNA_boolean_get(op->ptr, "add"); /* sanity check */ totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY); if (totshape == 0 || shape < 0 || shape >= totshape) return OPERATOR_CANCELLED; /* get shape key - needed for finding reference shape (for add mode only) */ if (key) { kb = BLI_findlink(&key->block, shape); } /* perform blending on selected vertices*/ BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) { if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) continue; /* get coordinates of shapekey we're blending from */ sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape); copy_v3_v3(co, sco); if (use_add) { /* in add mode, we add relative shape key offset */ if (kb) { const float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative); sub_v3_v3v3(co, co, rco); } madd_v3_v3fl(eve->co, co, blend); } else { /* in blend mode, we interpolate to the shape key */ interp_v3_v3v3(eve->co, eve->co, co, blend); } } EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } static EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em; EnumPropertyItem *item = NULL; int totitem = 0; if ((obedit && obedit->type == OB_MESH) && (em = BKE_editmesh_from_object(obedit)) && CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) { EnumPropertyItem tmp = {0, "", 0, "", ""}; int a; for (a = 0; a < em->bm->vdata.totlayer; a++) { if (em->bm->vdata.layers[a].type != CD_SHAPEKEY) continue; tmp.value = totitem; tmp.identifier = em->bm->vdata.layers[a].name; tmp.name = em->bm->vdata.layers[a].name; /* RNA_enum_item_add sets totitem itself! */ RNA_enum_item_add(&item, &totitem, &tmp); } } RNA_enum_item_end(&item, &totitem); *r_free = true; return item; } static void edbm_blend_from_shape_ui(bContext *C, wmOperator *op) { uiLayout *layout = op->layout; PointerRNA ptr; Object *obedit = CTX_data_edit_object(C); Mesh *me = obedit->data; PointerRNA ptr_key; RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); RNA_id_pointer_create((ID *)me->key, &ptr_key); uiItemPointerR(layout, &ptr, "shape", &ptr_key, "key_blocks", "", ICON_SHAPEKEY_DATA); uiItemR(layout, &ptr, "blend", 0, NULL, ICON_NONE); uiItemR(layout, &ptr, "add", 0, NULL, ICON_NONE); } void MESH_OT_blend_from_shape(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Blend From Shape"; ot->description = "Blend in shape from a shape key"; ot->idname = "MESH_OT_blend_from_shape"; /* api callbacks */ ot->exec = edbm_blend_from_shape_exec; // ot->invoke = WM_operator_props_popup_call; /* disable because search popup closes too easily */ ot->ui = edbm_blend_from_shape_ui; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ prop = RNA_def_enum(ot->srna, "shape", DummyRNA_NULL_items, 0, "Shape", "Shape key to use for blending"); RNA_def_enum_funcs(prop, shape_itemf); RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE | PROP_NEVER_UNLINK); RNA_def_float(ot->srna, "blend", 1.0f, -1e3f, 1e3f, "Blend", "Blending factor", -2.0f, 2.0f); RNA_def_boolean(ot->srna, "add", true, "Add", "Add rather than blend between shapes"); } static int edbm_solidify_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = obedit->data; BMEditMesh *em = me->edit_btmesh; BMesh *bm = em->bm; BMOperator bmop; const float thickness = RNA_float_get(op->ptr, "thickness"); if (!EDBM_op_init(em, &bmop, op, "solidify geom=%hf thickness=%f", BM_ELEM_SELECT, thickness)) { return OPERATOR_CANCELLED; } /* deselect only the faces in the region to be solidified (leave wire * edges and loose verts selected, as there will be no corresponding * geometry selected below) */ BMO_slot_buffer_hflag_disable(bm, bmop.slots_in, "geom", BM_FACE, BM_ELEM_SELECT, true); /* run the solidify operator */ BMO_op_exec(bm, &bmop); /* select the newly generated faces */ BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_solidify(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Solidify"; ot->description = "Create a solid skin by extruding, compensating for sharp angles"; ot->idname = "MESH_OT_solidify"; /* api callbacks */ ot->exec = edbm_solidify_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_float_distance(ot->srna, "thickness", 0.01f, -1e4f, 1e4f, "Thickness", "", -10.0f, 10.0f); RNA_def_property_ui_range(prop, -10.0, 10.0, 0.1, 4); } /* ******************************************************************** */ /* Knife Subdivide Tool. Subdivides edges intersected by a mouse trail * drawn by user. * * Currently mapped to KKey when in MeshEdit mode. * Usage: * - Hit Shift K, Select Centers or Exact * - Hold LMB down to draw path, hit RETKEY. * - ESC cancels as expected. * * Contributed by Robert Wenzlaff (Det. Thorn). * * 2.5 Revamp: * - non modal (no menu before cutting) * - exit on mouse release * - polygon/segment drawing can become handled by WM cb later * * bmesh port version */ #define KNIFE_EXACT 1 #define KNIFE_MIDPOINT 2 #define KNIFE_MULTICUT 3 static EnumPropertyItem knife_items[] = { {KNIFE_EXACT, "EXACT", 0, "Exact", ""}, {KNIFE_MIDPOINT, "MIDPOINTS", 0, "Midpoints", ""}, {KNIFE_MULTICUT, "MULTICUT", 0, "Multicut", ""}, {0, NULL, 0, NULL, NULL} }; /* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2], float (*mouse_path)[2], int len, char mode, int *isected) { #define MAXSLOPE 100000 float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max; float y2min, dist, lastdist = 0, xdiff2, xdiff1; float m1, b1, m2, b2, x21, x22, y21, y22, xi; float yi, x1min, x1max, y1max, y1min, perc = 0; float threshold = 0.0; int i; //threshold = 0.000001; /* tolerance for vertex intersection */ // XXX threshold = scene->toolsettings->select_thresh / 100; /* Get screen coords of verts */ x21 = sco_a[0]; y21 = sco_a[1]; x22 = sco_b[0]; y22 = sco_b[1]; xdiff2 = (x22 - x21); if (xdiff2) { m2 = (y22 - y21) / xdiff2; b2 = ((x22 * y21) - (x21 * y22)) / xdiff2; } else { m2 = MAXSLOPE; /* Verticle slope */ b2 = x22; } *isected = 0; /* check for _exact_ vertex intersection first */ if (mode != KNIFE_MULTICUT) { for (i = 0; i < len; i++) { if (i > 0) { x11 = x12; y11 = y12; } else { x11 = mouse_path[i][0]; y11 = mouse_path[i][1]; } x12 = mouse_path[i][0]; y12 = mouse_path[i][1]; /* test e->v1 */ if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) { perc = 0; *isected = 1; return perc; } /* test e->v2 */ else if ((x11 == x22 && y11 == y22) || (x12 == x22 && y12 == y22)) { perc = 0; *isected = 2; return perc; } } } /* now check for edge intersect (may produce vertex intersection as well) */ for (i = 0; i < len; i++) { if (i > 0) { x11 = x12; y11 = y12; } else { x11 = mouse_path[i][0]; y11 = mouse_path[i][1]; } x12 = mouse_path[i][0]; y12 = mouse_path[i][1]; /* Perp. Distance from point to line */ if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2); /* /sqrt(m2 * m2 + 1); Only looking for */ /* change in sign. Skip extra math */ else dist = x22 - x12; if (i == 0) lastdist = dist; /* if dist changes sign, and intersect point in edge's Bound Box */ if ((lastdist * dist) <= 0) { xdiff1 = (x12 - x11); /* Equation of line between last 2 points */ if (xdiff1) { m1 = (y12 - y11) / xdiff1; b1 = ((x12 * y11) - (x11 * y12)) / xdiff1; } else { m1 = MAXSLOPE; b1 = x12; } x2max = max_ff(x21, x22) + 0.001f; /* prevent missed edges */ x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */ y2max = max_ff(y21, y22) + 0.001f; y2min = min_ff(y21, y22) - 0.001f; /* Found an intersect, calc intersect point */ if (m1 == m2) { /* co-incident lines */ /* cut at 50% of overlap area */ x1max = max_ff(x11, x12); x1min = min_ff(x11, x12); xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f; y1max = max_ff(y11, y12); y1min = min_ff(y11, y12); yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f; } else if (m2 == MAXSLOPE) { xi = x22; yi = m1 * x22 + b1; } else if (m1 == MAXSLOPE) { xi = x12; yi = m2 * x12 + b2; } else { xi = (b1 - b2) / (m2 - m1); yi = (b1 * m2 - m1 * b2) / (m2 - m1); } /* Intersect inside bounding box of edge?*/ if ((xi >= x2min) && (xi <= x2max) && (yi <= y2max) && (yi >= y2min)) { /* test for vertex intersect that may be 'close enough'*/ if (mode != KNIFE_MULTICUT) { if (xi <= (x21 + threshold) && xi >= (x21 - threshold)) { if (yi <= (y21 + threshold) && yi >= (y21 - threshold)) { *isected = 1; perc = 0; break; } } if (xi <= (x22 + threshold) && xi >= (x22 - threshold)) { if (yi <= (y22 + threshold) && yi >= (y22 - threshold)) { *isected = 2; perc = 0; break; } } } if ((m2 <= 1.0f) && (m2 >= -1.0f)) perc = (xi - x21) / (x22 - x21); else perc = (yi - y21) / (y22 - y21); /* lower slope more accurate */ //isect = 32768.0 * (perc + 0.0000153); /* Percentage in 1 / 32768ths */ break; } } lastdist = dist; } return perc; } #define ELE_EDGE_CUT 1 static int edbm_knife_cut_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; ARegion *ar = CTX_wm_region(C); BMVert *bv; BMIter iter; BMEdge *be; BMOperator bmop; float isect = 0.0f; int len = 0, isected, i; short numcuts = 1; const short mode = RNA_int_get(op->ptr, "type"); BMOpSlot *slot_edge_percents; /* allocd vars */ float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2]; /* edit-object needed for matrix, and ar->regiondata for projections to work */ if (ELEM(NULL, obedit, ar, ar->regiondata)) return OPERATOR_CANCELLED; if (bm->totvertsel < 2) { BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on"); return OPERATOR_CANCELLED; } len = RNA_collection_length(op->ptr, "path"); if (len < 2) { BKE_report(op->reports, RPT_ERROR, "Mouse path too short"); return OPERATOR_CANCELLED; } mouse_path = MEM_mallocN(len * sizeof(*mouse_path), __func__); /* get the cut curve */ RNA_BEGIN (op->ptr, itemptr, "path") { RNA_float_get_array(&itemptr, "loc", (float *)&mouse_path[len]); } RNA_END; /* for ED_view3d_project_float_object */ ED_view3d_init_mats_rv3d(obedit, ar->regiondata); /* TODO, investigate using index lookup for screen_vert_coords() rather then a hash table */ /* the floating point coordinates of verts in screen space will be stored in a hash table according to the vertices pointer */ screen_vert_coords = sco = MEM_mallocN(bm->totvert * sizeof(float) * 2, __func__); BM_ITER_MESH_INDEX (bv, &iter, bm, BM_VERTS_OF_MESH, i) { if (ED_view3d_project_float_object(ar, bv->co, *sco, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) { copy_v2_fl(*sco, FLT_MAX); /* set error value */ } BM_elem_index_set(bv, i); /* set_inline */ sco++; } bm->elem_index_dirty &= ~BM_VERT; /* clear dirty flag */ if (!EDBM_op_init(em, &bmop, op, "subdivide_edges")) { MEM_freeN(mouse_path); MEM_freeN(screen_vert_coords); return OPERATOR_CANCELLED; } /* store percentage of edge cut for KNIFE_EXACT here.*/ slot_edge_percents = BMO_slot_get(bmop.slots_in, "edge_percents"); BM_ITER_MESH (be, &iter, bm, BM_EDGES_OF_MESH) { bool is_cut = false; if (BM_elem_flag_test(be, BM_ELEM_SELECT)) { const float *sco_a = screen_vert_coords[BM_elem_index_get(be->v1)]; const float *sco_b = screen_vert_coords[BM_elem_index_get(be->v2)]; /* check for error value (vert cant be projected) */ if ((sco_a[0] != FLT_MAX) && (sco_b[0] != FLT_MAX)) { isect = bm_edge_seg_isect(sco_a, sco_b, mouse_path, len, mode, &isected); if (isect != 0.0f) { if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) { BMO_slot_map_float_insert(&bmop, slot_edge_percents, be, isect); } } } } BMO_edge_flag_set(bm, be, ELE_EDGE_CUT, is_cut); } /* free all allocs */ MEM_freeN(screen_vert_coords); MEM_freeN(mouse_path); BMO_slot_buffer_from_enabled_flag(bm, &bmop, bmop.slots_in, "edges", BM_EDGE, ELE_EDGE_CUT); if (mode == KNIFE_MIDPOINT) numcuts = 1; BMO_slot_int_set(bmop.slots_in, "cuts", numcuts); BMO_slot_int_set(bmop.slots_in, "quad_corner_type", SUBD_CORNER_STRAIGHT_CUT); BMO_slot_bool_set(bmop.slots_in, "use_single_edge", false); BMO_slot_bool_set(bmop.slots_in, "use_grid_fill", false); BMO_slot_float_set(bmop.slots_in, "radius", 0); BMO_op_exec(bm, &bmop); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } #undef ELE_EDGE_CUT void MESH_OT_knife_cut(wmOperatorType *ot) { PropertyRNA *prop; ot->name = "Knife Cut"; ot->description = "Cut selected edges and faces into parts"; ot->idname = "MESH_OT_knife_cut"; ot->invoke = WM_gesture_lines_invoke; ot->modal = WM_gesture_lines_modal; ot->exec = edbm_knife_cut_exec; ot->poll = EDBM_view3d_poll; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_enum(ot->srna, "type", knife_items, KNIFE_EXACT, "Type", ""); prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath); /* internal */ RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, BC_NUMCURSORS, "Cursor", "", 0, BC_NUMCURSORS); } /* *************** Operator: separate parts *************/ enum { MESH_SEPARATE_SELECTED = 0, MESH_SEPARATE_MATERIAL = 1, MESH_SEPARATE_LOOSE = 2, }; static Base *mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old) { Base *base_new; Object *obedit = base_old->object; BMesh *bm_new; bm_new = BM_mesh_create( &bm_mesh_allocsize_default, &((struct BMeshCreateParams){.use_toolflags = true,})); BM_mesh_elem_toolflags_ensure(bm_new); /* needed for 'duplicate' bmo */ CustomData_copy(&bm_old->vdata, &bm_new->vdata, CD_MASK_BMESH, CD_CALLOC, 0); CustomData_copy(&bm_old->edata, &bm_new->edata, CD_MASK_BMESH, CD_CALLOC, 0); CustomData_copy(&bm_old->ldata, &bm_new->ldata, CD_MASK_BMESH, CD_CALLOC, 0); CustomData_copy(&bm_old->pdata, &bm_new->pdata, CD_MASK_BMESH, CD_CALLOC, 0); CustomData_bmesh_init_pool(&bm_new->vdata, bm_mesh_allocsize_default.totvert, BM_VERT); CustomData_bmesh_init_pool(&bm_new->edata, bm_mesh_allocsize_default.totedge, BM_EDGE); CustomData_bmesh_init_pool(&bm_new->ldata, bm_mesh_allocsize_default.totloop, BM_LOOP); CustomData_bmesh_init_pool(&bm_new->pdata, bm_mesh_allocsize_default.totface, BM_FACE); base_new = ED_object_add_duplicate(bmain, scene, base_old, USER_DUP_MESH); /* DAG_relations_tag_update(bmain); */ /* normally would call directly after but in this case delay recalc */ assign_matarar(base_new->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */ ED_base_object_select(base_new, BA_SELECT); BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE), "duplicate geom=%hvef dest=%p", BM_ELEM_TAG, bm_new); BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE), "delete geom=%hvef context=%i", BM_ELEM_TAG, DEL_FACES); /* deselect loose data - this used to get deleted, * we could de-select edges and verts only, but this turns out to be less complicated * since de-selecting all skips selection flushing logic */ BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false); BM_mesh_normals_update(bm_new); BM_mesh_bm_to_me(bm_new, base_new->object->data, (&(struct BMeshToMeshParams){0})); BM_mesh_free(bm_new); ((Mesh *)base_new->object->data)->edit_btmesh = NULL; return base_new; } static bool mesh_separate_selected(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old) { /* we may have tags from previous operators */ BM_mesh_elem_hflag_disable_all(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, false); /* sel -> tag */ BM_mesh_elem_hflag_enable_test(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, true, false, BM_ELEM_SELECT); return (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL); } /* flush a hflag to from verts to edges/faces */ static void bm_mesh_hflag_flush_vert(BMesh *bm, const char hflag) { BMEdge *e; BMLoop *l_iter; BMLoop *l_first; BMFace *f; BMIter eiter; BMIter fiter; bool ok; BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e->v1, hflag) && BM_elem_flag_test(e->v2, hflag)) { BM_elem_flag_enable(e, hflag); } else { BM_elem_flag_disable(e, hflag); } } BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) { ok = true; l_iter = l_first = BM_FACE_FIRST_LOOP(f); do { if (!BM_elem_flag_test(l_iter->v, hflag)) { ok = false; break; } } while ((l_iter = l_iter->next) != l_first); BM_elem_flag_set(f, hflag, ok); } } /** * Sets an object to a single material. from one of its slots. * * \note This could be used for split-by-material for non mesh types. * \note This could take material data from another object or args. */ static void mesh_separate_material_assign_mat_nr(Main *bmain, Object *ob, const short mat_nr) { ID *obdata = ob->data; Material ***matarar; const short *totcolp; totcolp = give_totcolp_id(obdata); matarar = give_matarar_id(obdata); if ((totcolp && matarar) == 0) { BLI_assert(0); return; } if (*totcolp) { Material *ma_ob; Material *ma_obdata; char matbit; if (mat_nr < ob->totcol) { ma_ob = ob->mat[mat_nr]; matbit = ob->matbits[mat_nr]; } else { ma_ob = NULL; matbit = 0; } if (mat_nr < *totcolp) { ma_obdata = (*matarar)[mat_nr]; } else { ma_obdata = NULL; } BKE_material_clear_id(bmain, obdata, true); BKE_material_resize_object(bmain, ob, 1, true); BKE_material_resize_id(bmain, obdata, 1, true); ob->mat[0] = ma_ob; id_us_plus((ID *)ma_ob); ob->matbits[0] = matbit; (*matarar)[0] = ma_obdata; id_us_plus((ID *)ma_obdata); } else { BKE_material_clear_id(bmain, obdata, true); BKE_material_resize_object(bmain, ob, 0, true); BKE_material_resize_id(bmain, obdata, 0, true); } } static bool mesh_separate_material(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old) { BMFace *f_cmp, *f; BMIter iter; bool result = false; while ((f_cmp = BM_iter_at_index(bm_old, BM_FACES_OF_MESH, NULL, 0))) { Base *base_new; const short mat_nr = f_cmp->mat_nr; int tot = 0; BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false); BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) { if (f->mat_nr == mat_nr) { BMLoop *l_iter; BMLoop *l_first; BM_elem_flag_enable(f, BM_ELEM_TAG); l_iter = l_first = BM_FACE_FIRST_LOOP(f); do { BM_elem_flag_enable(l_iter->v, BM_ELEM_TAG); BM_elem_flag_enable(l_iter->e, BM_ELEM_TAG); } while ((l_iter = l_iter->next) != l_first); tot++; } } /* leave the current object with some materials */ if (tot == bm_old->totface) { mesh_separate_material_assign_mat_nr(bmain, base_old->object, mat_nr); /* since we're in editmode, must set faces here */ BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) { f->mat_nr = 0; } break; } /* Move selection into a separate object */ base_new = mesh_separate_tagged(bmain, scene, base_old, bm_old); if (base_new) { mesh_separate_material_assign_mat_nr(bmain, base_new->object, mat_nr); } result |= (base_new != NULL); } return result; } static bool mesh_separate_loose(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old) { int i; BMEdge *e; BMVert *v_seed; BMWalker walker; bool result = false; int max_iter = bm_old->totvert; /* Clear all selected vertices */ BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false); /* A "while (true)" loop should work here as each iteration should * select and remove at least one vertex and when all vertices * are selected the loop will break out. But guard against bad * behavior by limiting iterations to the number of vertices in the * original mesh.*/ for (i = 0; i < max_iter; i++) { int tot = 0; /* Get a seed vertex to start the walk */ v_seed = BM_iter_at_index(bm_old, BM_VERTS_OF_MESH, NULL, 0); /* No vertices available, can't do anything */ if (v_seed == NULL) { break; } /* Select the seed explicitly, in case it has no edges */ if (!BM_elem_flag_test(v_seed, BM_ELEM_TAG)) { BM_elem_flag_enable(v_seed, BM_ELEM_TAG); tot++; } /* Walk from the single vertex, selecting everything connected * to it */ BMW_init(&walker, bm_old, BMW_VERT_SHELL, BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP, BMW_FLAG_NOP, BMW_NIL_LAY); for (e = BMW_begin(&walker, v_seed); e; e = BMW_step(&walker)) { if (!BM_elem_flag_test(e->v1, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v1, BM_ELEM_TAG); tot++; } if (!BM_elem_flag_test(e->v2, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v2, BM_ELEM_TAG); tot++; } } BMW_end(&walker); if (bm_old->totvert == tot) { /* Every vertex selected, nothing to separate, work is done */ break; } /* Flush the selection to get edge/face selections matching * the vertex selection */ bm_mesh_hflag_flush_vert(bm_old, BM_ELEM_TAG); /* Move selection into a separate object */ result |= (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL); } return result; } static int edbm_separate_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); const int type = RNA_enum_get(op->ptr, "type"); int retval = 0; if (ED_operator_editmesh(C)) { Base *base = CTX_data_active_base(C); BMEditMesh *em = BKE_editmesh_from_object(base->object); if (type == 0) { if ((em->bm->totvertsel == 0) && (em->bm->totedgesel == 0) && (em->bm->totfacesel == 0)) { BKE_report(op->reports, RPT_ERROR, "Nothing selected"); return OPERATOR_CANCELLED; } } /* editmode separate */ switch (type) { case MESH_SEPARATE_SELECTED: retval = mesh_separate_selected(bmain, scene, base, em->bm); break; case MESH_SEPARATE_MATERIAL: retval = mesh_separate_material(bmain, scene, base, em->bm); break; case MESH_SEPARATE_LOOSE: retval = mesh_separate_loose(bmain, scene, base, em->bm); break; default: BLI_assert(0); break; } if (retval) { EDBM_update_generic(em, true, true); } } else { if (type == MESH_SEPARATE_SELECTED) { BKE_report(op->reports, RPT_ERROR, "Selection not supported in object mode"); return OPERATOR_CANCELLED; } /* object mode separate */ CTX_DATA_BEGIN(C, Base *, base_iter, selected_editable_bases) { Object *ob = base_iter->object; if (ob->type == OB_MESH) { Mesh *me = ob->data; if (!ID_IS_LINKED_DATABLOCK(me)) { BMesh *bm_old = NULL; int retval_iter = 0; bm_old = BM_mesh_create( &bm_mesh_allocsize_default, &((struct BMeshCreateParams){.use_toolflags = true,})); BM_mesh_bm_from_me(bm_old, me, (&(struct BMeshFromMeshParams){0})); switch (type) { case MESH_SEPARATE_MATERIAL: retval_iter = mesh_separate_material(bmain, scene, base_iter, bm_old); break; case MESH_SEPARATE_LOOSE: retval_iter = mesh_separate_loose(bmain, scene, base_iter, bm_old); break; default: BLI_assert(0); break; } if (retval_iter) { BM_mesh_bm_to_me(bm_old, me, (&(struct BMeshToMeshParams){0})); DAG_id_tag_update(&me->id, OB_RECALC_DATA); WM_event_add_notifier(C, NC_GEOM | ND_DATA, me); } BM_mesh_free(bm_old); retval |= retval_iter; } } } CTX_DATA_END; } if (retval) { /* delay depsgraph recalc until all objects are duplicated */ DAG_relations_tag_update(bmain); WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL); return OPERATOR_FINISHED; } return OPERATOR_CANCELLED; } void MESH_OT_separate(wmOperatorType *ot) { static EnumPropertyItem prop_separate_types[] = { {MESH_SEPARATE_SELECTED, "SELECTED", 0, "Selection", ""}, {MESH_SEPARATE_MATERIAL, "MATERIAL", 0, "By Material", ""}, {MESH_SEPARATE_LOOSE, "LOOSE", 0, "By loose parts", ""}, {0, NULL, 0, NULL, NULL} }; /* identifiers */ ot->name = "Separate"; ot->description = "Separate selected geometry into a new mesh"; ot->idname = "MESH_OT_separate"; /* api callbacks */ ot->invoke = WM_menu_invoke; ot->exec = edbm_separate_exec; ot->poll = ED_operator_scene_editable; /* object and editmode */ /* flags */ ot->flag = OPTYPE_UNDO; ot->prop = RNA_def_enum(ot->srna, "type", prop_separate_types, MESH_SEPARATE_SELECTED, "Type", ""); } static int edbm_fill_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_beauty = RNA_boolean_get(op->ptr, "use_beauty"); BMOperator bmop; const int totface_orig = em->bm->totface; int ret; if (em->bm->totedgesel == 0) { BKE_report(op->reports, RPT_WARNING, "No edges selected"); return OPERATOR_CANCELLED; } if (!EDBM_op_init(em, &bmop, op, "triangle_fill edges=%he use_beauty=%b", BM_ELEM_SELECT, use_beauty)) { return OPERATOR_CANCELLED; } BMO_op_exec(em->bm, &bmop); if (totface_orig != em->bm->totface) { /* select new geometry */ BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE | BM_EDGE, BM_ELEM_SELECT, true); EDBM_update_generic(em, true, true); ret = OPERATOR_FINISHED; } else { BKE_report(op->reports, RPT_WARNING, "No faces filled"); ret = OPERATOR_CANCELLED; } if (!EDBM_op_finish(em, &bmop, op, true)) { ret = OPERATOR_CANCELLED; } return ret; } void MESH_OT_fill(wmOperatorType *ot) { /* identifiers */ ot->name = "Fill"; ot->idname = "MESH_OT_fill"; ot->description = "Fill a selected edge loop with faces"; /* api callbacks */ ot->exec = edbm_fill_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_boolean(ot->srna, "use_beauty", true, "Beauty", "Use best triangulation division"); } /* -------------------------------------------------------------------- */ /* Grid Fill (and helper functions) */ static bool bm_edge_test_fill_grid_cb(BMEdge *e, void *UNUSED(bm_v)) { return BM_elem_flag_test_bool(e, BM_ELEM_TAG); } static float edbm_fill_grid_vert_tag_angle(BMVert *v) { BMIter iter; BMEdge *e_iter; BMVert *v_pair[2]; int i = 0; BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) { if (BM_elem_flag_test(e_iter, BM_ELEM_TAG)) { v_pair[i++] = BM_edge_other_vert(e_iter, v); } } BLI_assert(i == 2); return fabsf((float)M_PI - angle_v3v3v3(v_pair[0]->co, v->co, v_pair[1]->co)); } /** * non-essential utility function to select 2 open edge loops from a closed loop. */ static void edbm_fill_grid_prepare(BMesh *bm, int offset, int *r_span, bool span_calc) { /* angle differences below this value are considered 'even' * in that they shouldn't be used to calculate corners used for the 'span' */ const float eps_even = 1e-3f; BMEdge *e; BMIter iter; int count; int span = *r_span; ListBase eloops = {NULL}; struct BMEdgeLoopStore *el_store; // LinkData *el_store; /* select -> tag */ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT)); } count = BM_mesh_edgeloops_find(bm, &eloops, bm_edge_test_fill_grid_cb, bm); el_store = eloops.first; if (count == 1 && BM_edgeloop_is_closed(el_store) && (BM_edgeloop_length_get(el_store) & 1) == 0) { /* be clever! detect 2 edge loops from one closed edge loop */ const int verts_len = BM_edgeloop_length_get(el_store); ListBase *verts = BM_edgeloop_verts_get(el_store); BMVert *v_act = BM_mesh_active_vert_get(bm); LinkData *v_act_link; BMEdge **edges = MEM_mallocN(sizeof(*edges) * verts_len, __func__); int i; if (v_act && (v_act_link = BLI_findptr(verts, v_act, offsetof(LinkData, data)))) { /* pass */ } else { /* find the vertex with the best angle (a corner vertex) */ LinkData *v_link, *v_link_best = NULL; float angle_best = -1.0f; for (v_link = verts->first; v_link; v_link = v_link->next) { const float angle = edbm_fill_grid_vert_tag_angle(v_link->data); if ((angle > angle_best) || (v_link_best == NULL)) { angle_best = angle; v_link_best = v_link; } } v_act_link = v_link_best; v_act = v_act_link->data; } /* set this vertex first */ BLI_listbase_rotate_first(verts, v_act_link); if (offset != 0) { v_act_link = BLI_findlink(verts, offset); v_act = v_act_link->data; BLI_listbase_rotate_first(verts, v_act_link); } BM_edgeloop_edges_get(el_store, edges); if (span_calc) { /* calculate the span by finding the next corner in 'verts' * we dont know what defines a corner exactly so find the 4 verts * in the loop with the greatest angle. * Tag them and use the first tagged vertex to calculate the span. * * note: we may have already checked 'edbm_fill_grid_vert_tag_angle()' on each * vert, but advantage of de-duplicating is minimal. */ struct SortPointerByFloat *ele_sort = MEM_mallocN(sizeof(*ele_sort) * verts_len, __func__); LinkData *v_link; for (v_link = verts->first, i = 0; v_link; v_link = v_link->next, i++) { BMVert *v = v_link->data; const float angle = edbm_fill_grid_vert_tag_angle(v); ele_sort[i].sort_value = angle; ele_sort[i].data = v; BM_elem_flag_disable(v, BM_ELEM_TAG); } qsort(ele_sort, verts_len, sizeof(*ele_sort), BLI_sortutil_cmp_float_reverse); /* check that we have at least 3 corners, * if the angle on the 3rd angle is roughly the same as the last, * then we can't calculate 3+ corners - fallback to the even span. */ if ((ele_sort[2].sort_value - ele_sort[verts_len - 1].sort_value) > eps_even) { for (i = 0; i < 4; i++) { BMVert *v = ele_sort[i].data; BM_elem_flag_enable(v, BM_ELEM_TAG); } /* now find the first... */ for (v_link = verts->first, i = 0; i < verts_len / 2; v_link = v_link->next, i++) { BMVert *v = v_link->data; if (BM_elem_flag_test(v, BM_ELEM_TAG)) { if (v != v_act) { span = i; break; } } } } MEM_freeN(ele_sort); } /* end span calc */ /* un-flag 'rails' */ for (i = 0; i < span; i++) { BM_elem_flag_disable(edges[i], BM_ELEM_TAG); BM_elem_flag_disable(edges[(verts_len / 2) + i], BM_ELEM_TAG); } MEM_freeN(edges); } /* else let the bmesh-operator handle it */ BM_mesh_edgeloops_free(&eloops); *r_span = span; } static int edbm_fill_grid_exec(bContext *C, wmOperator *op) { BMOperator bmop; Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_smooth = edbm_add_edge_face__smooth_get(em->bm); const int totedge_orig = em->bm->totedge; const int totface_orig = em->bm->totface; const bool use_interp_simple = RNA_boolean_get(op->ptr, "use_interp_simple"); const bool use_prepare = true; if (use_prepare) { /* use when we have a single loop selected */ PropertyRNA *prop_span = RNA_struct_find_property(op->ptr, "span"); PropertyRNA *prop_offset = RNA_struct_find_property(op->ptr, "offset"); bool calc_span; const int clamp = em->bm->totvertsel; int span; int offset; if (RNA_property_is_set(op->ptr, prop_span)) { span = RNA_property_int_get(op->ptr, prop_span); span = min_ii(span, (clamp / 2) - 1); calc_span = false; } else { span = clamp / 4; calc_span = true; } offset = RNA_property_int_get(op->ptr, prop_offset); offset = clamp ? mod_i(offset, clamp) : 0; /* in simple cases, move selection for tags, but also support more advanced cases */ edbm_fill_grid_prepare(em->bm, offset, &span, calc_span); RNA_property_int_set(op->ptr, prop_span, span); } /* end tricky prepare code */ if (!EDBM_op_init(em, &bmop, op, "grid_fill edges=%he mat_nr=%i use_smooth=%b use_interp_simple=%b", use_prepare ? BM_ELEM_TAG : BM_ELEM_SELECT, em->mat_nr, use_smooth, use_interp_simple)) { return OPERATOR_CANCELLED; } BMO_op_exec(em->bm, &bmop); /* cancel if nothing was done */ if ((totedge_orig == em->bm->totedge) && (totface_orig == em->bm->totface)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_fill_grid(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Grid Fill"; ot->description = "Fill grid from two loops"; ot->idname = "MESH_OT_fill_grid"; /* api callbacks */ ot->exec = edbm_fill_grid_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ prop = RNA_def_int(ot->srna, "span", 1, 1, 1000, "Span", "Number of sides (zero disables)", 1, 100); RNA_def_property_flag(prop, PROP_SKIP_SAVE); prop = RNA_def_int(ot->srna, "offset", 0, -1000, 1000, "Offset", "Number of sides (zero disables)", -100, 100); RNA_def_property_flag(prop, PROP_SKIP_SAVE); RNA_def_boolean(ot->srna, "use_interp_simple", false, "Simple Blending", ""); } static int edbm_fill_holes_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int sides = RNA_int_get(op->ptr, "sides"); if (!EDBM_op_call_and_selectf( em, op, "faces.out", true, "holes_fill edges=%he sides=%i", BM_ELEM_SELECT, sides)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_fill_holes(wmOperatorType *ot) { /* identifiers */ ot->name = "Fill Holes"; ot->idname = "MESH_OT_fill_holes"; ot->description = "Fill in holes (boundary edge loops)"; /* api callbacks */ ot->exec = edbm_fill_holes_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_int(ot->srna, "sides", 4, 0, 1000, "Sides", "Number of sides in hole required to fill (zero fills all holes)", 0, 100); } static int edbm_beautify_fill_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const float angle_max = M_PI; const float angle_limit = RNA_float_get(op->ptr, "angle_limit"); char hflag; if (angle_limit >= angle_max) { hflag = BM_ELEM_SELECT; } else { BMIter iter; BMEdge *e; BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) { BM_elem_flag_set(e, BM_ELEM_TAG, (BM_elem_flag_test(e, BM_ELEM_SELECT) && BM_edge_calc_face_angle_ex(e, angle_max) < angle_limit)); } hflag = BM_ELEM_TAG; } if (!EDBM_op_call_and_selectf( em, op, "geom.out", true, "beautify_fill faces=%hf edges=%he", BM_ELEM_SELECT, hflag)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_beautify_fill(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Beautify Faces"; ot->idname = "MESH_OT_beautify_fill"; ot->description = "Rearrange some faces to try to get less degenerated geometry"; /* api callbacks */ ot->exec = edbm_beautify_fill_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f), "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f)); RNA_def_property_float_default(prop, DEG2RADF(180.0f)); } /********************** Poke Face **********************/ static int edbm_poke_face_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const float offset = RNA_float_get(op->ptr, "offset"); const bool use_relative_offset = RNA_boolean_get(op->ptr, "use_relative_offset"); const int center_mode = RNA_enum_get(op->ptr, "center_mode"); EDBM_op_init(em, &bmop, op, "poke faces=%hf offset=%f use_relative_offset=%b center_mode=%i", BM_ELEM_SELECT, offset, use_relative_offset, center_mode); BMO_op_exec(em->bm, &bmop); EDBM_flag_disable_all(em, BM_ELEM_SELECT); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "verts.out", BM_VERT, BM_ELEM_SELECT, true); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_mesh_normals_update(em); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_poke(wmOperatorType *ot) { static EnumPropertyItem poke_center_modes[] = { {BMOP_POKE_MEAN_WEIGHTED, "MEAN_WEIGHTED", 0, "Weighted Mean", "Weighted Mean Face Center"}, {BMOP_POKE_MEAN, "MEAN", 0, "Mean", "Mean Face Center"}, {BMOP_POKE_BOUNDS, "BOUNDS", 0, "Bounds", "Face Bounds Center"}, {0, NULL, 0, NULL, NULL}}; /* identifiers */ ot->name = "Poke Faces"; ot->idname = "MESH_OT_poke"; ot->description = "Split a face into a fan"; /* api callbacks */ ot->exec = edbm_poke_face_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float_distance(ot->srna, "offset", 0.0f, -1e3f, 1e3f, "Poke Offset", "Poke Offset", -1.0f, 1.0f); RNA_def_boolean(ot->srna, "use_relative_offset", false, "Offset Relative", "Scale the offset by surrounding geometry"); RNA_def_enum(ot->srna, "center_mode", poke_center_modes, BMOP_POKE_MEAN_WEIGHTED, "Poke Center", "Poke Face Center Calculation"); } /********************** Quad/Tri Operators *************************/ static int edbm_quads_convert_to_tris_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const int quad_method = RNA_enum_get(op->ptr, "quad_method"); const int ngon_method = RNA_enum_get(op->ptr, "ngon_method"); BMOIter oiter; BMFace *f; EDBM_op_init(em, &bmop, op, "triangulate faces=%hf quad_method=%i ngon_method=%i", BM_ELEM_SELECT, quad_method, ngon_method); BMO_op_exec(em->bm, &bmop); /* select the output */ BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); /* remove the doubles */ BMO_ITER (f, &oiter, bmop.slots_out, "face_map_double.out", BM_FACE) { BM_face_kill(em->bm, f); } EDBM_selectmode_flush(em); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_quads_convert_to_tris(wmOperatorType *ot) { /* identifiers */ ot->name = "Triangulate Faces"; ot->idname = "MESH_OT_quads_convert_to_tris"; ot->description = "Triangulate selected faces"; /* api callbacks */ ot->exec = edbm_quads_convert_to_tris_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_enum(ot->srna, "quad_method", rna_enum_modifier_triangulate_quad_method_items, MOD_TRIANGULATE_QUAD_BEAUTY, "Quad Method", "Method for splitting the quads into triangles"); RNA_def_enum(ot->srna, "ngon_method", rna_enum_modifier_triangulate_ngon_method_items, MOD_TRIANGULATE_NGON_BEAUTY, "Polygon Method", "Method for splitting the polygons into triangles"); } static int edbm_tris_convert_to_quads_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); bool do_seam, do_sharp, do_uvs, do_vcols, do_materials; float angle_face_threshold, angle_shape_threshold; PropertyRNA *prop; /* When joining exactly 2 faces, no limit. * this is useful for one off joins while editing. */ prop = RNA_struct_find_property(op->ptr, "face_threshold"); if ((em->bm->totfacesel == 2) && (RNA_property_is_set(op->ptr, prop) == false)) { angle_face_threshold = DEG2RADF(180.0f); } else { angle_face_threshold = RNA_property_float_get(op->ptr, prop); } prop = RNA_struct_find_property(op->ptr, "shape_threshold"); if ((em->bm->totfacesel == 2) && (RNA_property_is_set(op->ptr, prop) == false)) { angle_shape_threshold = DEG2RADF(180.0f); } else { angle_shape_threshold = RNA_property_float_get(op->ptr, prop); } do_seam = RNA_boolean_get(op->ptr, "seam"); do_sharp = RNA_boolean_get(op->ptr, "sharp"); do_uvs = RNA_boolean_get(op->ptr, "uvs"); do_vcols = RNA_boolean_get(op->ptr, "vcols"); do_materials = RNA_boolean_get(op->ptr, "materials"); if (!EDBM_op_call_and_selectf( em, op, "faces.out", true, "join_triangles faces=%hf angle_face_threshold=%f angle_shape_threshold=%f " "cmp_seam=%b cmp_sharp=%b cmp_uvs=%b cmp_vcols=%b cmp_materials=%b", BM_ELEM_SELECT, angle_face_threshold, angle_shape_threshold, do_seam, do_sharp, do_uvs, do_vcols, do_materials)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } static void join_triangle_props(wmOperatorType *ot) { PropertyRNA *prop; prop = RNA_def_float_rotation( ot->srna, "face_threshold", 0, NULL, 0.0f, DEG2RADF(180.0f), "Max Face Angle", "Face angle limit", 0.0f, DEG2RADF(180.0f)); RNA_def_property_float_default(prop, DEG2RADF(40.0f)); prop = RNA_def_float_rotation( ot->srna, "shape_threshold", 0, NULL, 0.0f, DEG2RADF(180.0f), "Max Shape Angle", "Shape angle limit", 0.0f, DEG2RADF(180.0f)); RNA_def_property_float_default(prop, DEG2RADF(40.0f)); RNA_def_boolean(ot->srna, "uvs", false, "Compare UVs", ""); RNA_def_boolean(ot->srna, "vcols", false, "Compare VCols", ""); RNA_def_boolean(ot->srna, "seam", false, "Compare Seam", ""); RNA_def_boolean(ot->srna, "sharp", false, "Compare Sharp", ""); RNA_def_boolean(ot->srna, "materials", false, "Compare Materials", ""); } void MESH_OT_tris_convert_to_quads(wmOperatorType *ot) { /* identifiers */ ot->name = "Tris to Quads"; ot->idname = "MESH_OT_tris_convert_to_quads"; ot->description = "Join triangles into quads"; /* api callbacks */ ot->exec = edbm_tris_convert_to_quads_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; join_triangle_props(ot); } /* -------------------------------------------------------------------- */ /** \name Decimate * * \note The function to decimate is intended for use as a modifier, * while its handy allow access as a tool - this does cause access to be a little awkward * (passing selection as weights for eg). * * \{ */ static int edbm_decimate_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; const float ratio = RNA_float_get(op->ptr, "ratio"); bool use_vertex_group = RNA_boolean_get(op->ptr, "use_vertex_group"); const float vertex_group_factor = RNA_float_get(op->ptr, "vertex_group_factor"); const bool invert_vertex_group = RNA_boolean_get(op->ptr, "invert_vertex_group"); const bool use_symmetry = RNA_boolean_get(op->ptr, "use_symmetry"); const float symmetry_eps = 0.00002f; const int symmetry_axis = use_symmetry ? RNA_enum_get(op->ptr, "symmetry_axis") : -1; /* nop */ if (ratio == 1.0f) { return OPERATOR_FINISHED; } float *vweights = MEM_mallocN(sizeof(*vweights) * bm->totvert, __func__); { const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT); const int defbase_act = obedit->actdef - 1; if (use_vertex_group && (cd_dvert_offset == -1)) { BKE_report(op->reports, RPT_WARNING, "No active vertex group"); use_vertex_group = false; } BMIter iter; BMVert *v; int i; BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) { float weight = 0.0f; if (BM_elem_flag_test(v, BM_ELEM_SELECT)) { if (use_vertex_group) { const MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(v, cd_dvert_offset); weight = defvert_find_weight(dv, defbase_act); if (invert_vertex_group) { weight = 1.0f - weight; } } else { weight = 1.0f; } } vweights[i] = weight; BM_elem_index_set(v, i); /* set_inline */ } bm->elem_index_dirty &= ~BM_VERT; } float ratio_adjust; if ((bm->totface == bm->totfacesel) || (ratio == 0.0f)) { ratio_adjust = ratio; } else { /** * Calculate a new ratio based on faces that could be remoevd during decimation. * needed so 0..1 has a meaningful range when operating on the selection. * * This doesn't have to be totally accurate, * but needs to be greater than the number of selected faces */ int totface_basis = 0; int totface_adjacent = 0; BMIter iter; BMFace *f; BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) { /* count faces during decimation, ngons are triangulated */ const int f_len = f->len > 4 ? (f->len - 2) : 1; totface_basis += f_len; BMLoop *l_iter, *l_first; l_iter = l_first = BM_FACE_FIRST_LOOP(f); do { if (vweights[BM_elem_index_get(l_iter->v)] != 0.0f) { totface_adjacent += f_len; break; } } while ((l_iter = l_iter->next) != l_first); } ratio_adjust = ratio; ratio_adjust = 1.0f - ratio_adjust; ratio_adjust *= (float)totface_adjacent / (float)totface_basis; ratio_adjust = 1.0f - ratio_adjust; } BM_mesh_decimate_collapse( em->bm, ratio_adjust, vweights, vertex_group_factor, false, symmetry_axis, symmetry_eps); MEM_freeN(vweights); { short selectmode = em->selectmode; if ((selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) == 0) { /* ensure we flush edges -> faces */ selectmode |= SCE_SELECT_EDGE; } EDBM_selectmode_flush_ex(em, selectmode); } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } static bool edbm_decimate_check(bContext *UNUSED(C), wmOperator *UNUSED(op)) { return true; } static void edbm_decimate_ui(bContext *UNUSED(C), wmOperator *op) { uiLayout *layout = op->layout, *box, *row, *col; PointerRNA ptr; RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); uiItemR(layout, &ptr, "ratio", 0, NULL, ICON_NONE); box = uiLayoutBox(layout); uiItemR(box, &ptr, "use_vertex_group", 0, NULL, ICON_NONE); col = uiLayoutColumn(box, false); uiLayoutSetActive(col, RNA_boolean_get(&ptr, "use_vertex_group")); uiItemR(col, &ptr, "vertex_group_factor", 0, NULL, ICON_NONE); uiItemR(col, &ptr, "invert_vertex_group", 0, NULL, ICON_NONE); box = uiLayoutBox(layout); uiItemR(box, &ptr, "use_symmetry", 0, NULL, ICON_NONE); row = uiLayoutRow(box, true); uiLayoutSetActive(row, RNA_boolean_get(&ptr, "use_symmetry")); uiItemR(row, &ptr, "symmetry_axis", UI_ITEM_R_EXPAND, NULL, ICON_NONE); } void MESH_OT_decimate(wmOperatorType *ot) { /* identifiers */ ot->name = "Decimate Geometry"; ot->idname = "MESH_OT_decimate"; ot->description = "Simplify geometry by collapsing edges"; /* api callbacks */ ot->exec = edbm_decimate_exec; ot->check = edbm_decimate_check; ot->ui = edbm_decimate_ui; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* Note, keep in sync with 'rna_def_modifier_decimate' */ RNA_def_float(ot->srna, "ratio", 1.0f, 0.0f, 1.0f, "Ratio", "", 0.0f, 1.0f); RNA_def_boolean(ot->srna, "use_vertex_group", false, "Vertex Group", "Use active vertex group as an influence"); RNA_def_float(ot->srna, "vertex_group_factor", 1.0f, 0.0f, 1000.0f, "Weight", "Vertex group strength", 0.0f, 10.0f); RNA_def_boolean(ot->srna, "invert_vertex_group", false, "Invert", "Invert vertex group influence"); RNA_def_boolean(ot->srna, "use_symmetry", false, "Symmetry", "Maintain symmetry on an axis"); RNA_def_enum(ot->srna, "symmetry_axis", rna_enum_axis_xyz_items, 1, "Axis", "Axis of symmetry"); } /** \} */ /* -------------------------------------------------------------------- */ /* Dissolve */ static void edbm_dissolve_prop__use_verts(wmOperatorType *ot, bool value, int flag) { PropertyRNA *prop; prop = RNA_def_boolean(ot->srna, "use_verts", value, "Dissolve Verts", "Dissolve remaining vertices"); if (flag) { RNA_def_property_flag(prop, flag); } } static void edbm_dissolve_prop__use_face_split(wmOperatorType *ot) { RNA_def_boolean(ot->srna, "use_face_split", false, "Face Split", "Split off face corners to maintain surrounding geometry"); } static void edbm_dissolve_prop__use_boundary_tear(wmOperatorType *ot) { RNA_def_boolean(ot->srna, "use_boundary_tear", false, "Tear Boundary", "Split off face corners instead of merging faces"); } static int edbm_dissolve_verts_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split"); const bool use_boundary_tear = RNA_boolean_get(op->ptr, "use_boundary_tear"); if (!EDBM_op_callf(em, op, "dissolve_verts verts=%hv use_face_split=%b use_boundary_tear=%b", BM_ELEM_SELECT, use_face_split, use_boundary_tear)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_dissolve_verts(wmOperatorType *ot) { /* identifiers */ ot->name = "Dissolve Vertices"; ot->description = "Dissolve verts, merge edges and faces"; ot->idname = "MESH_OT_dissolve_verts"; /* api callbacks */ ot->exec = edbm_dissolve_verts_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; edbm_dissolve_prop__use_face_split(ot); edbm_dissolve_prop__use_boundary_tear(ot); } static int edbm_dissolve_edges_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_verts = RNA_boolean_get(op->ptr, "use_verts"); const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split"); if (!EDBM_op_callf(em, op, "dissolve_edges edges=%he use_verts=%b use_face_split=%b", BM_ELEM_SELECT, use_verts, use_face_split)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_dissolve_edges(wmOperatorType *ot) { /* identifiers */ ot->name = "Dissolve Edges"; ot->description = "Dissolve edges, merging faces"; ot->idname = "MESH_OT_dissolve_edges"; /* api callbacks */ ot->exec = edbm_dissolve_edges_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; edbm_dissolve_prop__use_verts(ot, true, 0); edbm_dissolve_prop__use_face_split(ot); } static int edbm_dissolve_faces_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_verts = RNA_boolean_get(op->ptr, "use_verts"); if (!EDBM_op_call_and_selectf( em, op, "region.out", true, "dissolve_faces faces=%hf use_verts=%b", BM_ELEM_SELECT, use_verts)) { return OPERATOR_CANCELLED; } EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_dissolve_faces(wmOperatorType *ot) { /* identifiers */ ot->name = "Dissolve Faces"; ot->description = "Dissolve faces"; ot->idname = "MESH_OT_dissolve_faces"; /* api callbacks */ ot->exec = edbm_dissolve_faces_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; edbm_dissolve_prop__use_verts(ot, false, 0); } static int edbm_dissolve_mode_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); PropertyRNA *prop; prop = RNA_struct_find_property(op->ptr, "use_verts"); if (!RNA_property_is_set(op->ptr, prop)) { /* always enable in edge-mode */ if ((em->selectmode & SCE_SELECT_FACE) == 0) { RNA_property_boolean_set(op->ptr, prop, true); } } if (em->selectmode & SCE_SELECT_VERTEX) { return edbm_dissolve_verts_exec(C, op); } else if (em->selectmode & SCE_SELECT_EDGE) { return edbm_dissolve_edges_exec(C, op); } else { return edbm_dissolve_faces_exec(C, op); } } void MESH_OT_dissolve_mode(wmOperatorType *ot) { /* identifiers */ ot->name = "Dissolve Selection"; ot->description = "Dissolve geometry based on the selection mode"; ot->idname = "MESH_OT_dissolve_mode"; /* api callbacks */ ot->exec = edbm_dissolve_mode_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; edbm_dissolve_prop__use_verts(ot, false, PROP_SKIP_SAVE); edbm_dissolve_prop__use_face_split(ot); edbm_dissolve_prop__use_boundary_tear(ot); } static int edbm_dissolve_limited_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; const float angle_limit = RNA_float_get(op->ptr, "angle_limit"); const bool use_dissolve_boundaries = RNA_boolean_get(op->ptr, "use_dissolve_boundaries"); const int delimit = RNA_enum_get(op->ptr, "delimit"); char dissolve_flag; if (em->selectmode == SCE_SELECT_FACE) { /* flush selection to tags and untag edges/verts with partially selected faces */ BMIter iter; BMIter liter; BMElem *ele; BMFace *f; BMLoop *l; BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) { BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_SELECT)); } BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) { BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_SELECT)); } BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) { if (!BM_elem_flag_test(f, BM_ELEM_SELECT)) { BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) { BM_elem_flag_disable(l->v, BM_ELEM_TAG); BM_elem_flag_disable(l->e, BM_ELEM_TAG); } } } dissolve_flag = BM_ELEM_TAG; } else { dissolve_flag = BM_ELEM_SELECT; } EDBM_op_call_and_selectf( em, op, "region.out", true, "dissolve_limit edges=%he verts=%hv angle_limit=%f use_dissolve_boundaries=%b delimit=%i", dissolve_flag, dissolve_flag, angle_limit, use_dissolve_boundaries, delimit); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_dissolve_limited(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Limited Dissolve"; ot->idname = "MESH_OT_dissolve_limited"; ot->description = "Dissolve selected edges and verts, limited by the angle of surrounding geometry"; /* api callbacks */ ot->exec = edbm_dissolve_limited_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f), "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f)); RNA_def_property_float_default(prop, DEG2RADF(5.0f)); RNA_def_boolean(ot->srna, "use_dissolve_boundaries", false, "All Boundaries", "Dissolve all vertices inbetween face boundaries"); RNA_def_enum_flag(ot->srna, "delimit", rna_enum_mesh_delimit_mode_items, BMO_DELIM_NORMAL, "Delimit", "Delimit dissolve operation"); } static int edbm_dissolve_degenerate_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const float thresh = RNA_float_get(op->ptr, "threshold"); BMesh *bm = em->bm; const int totelem[3] = {bm->totvert, bm->totedge, bm->totface}; if (!EDBM_op_callf( em, op, "dissolve_degenerate edges=%he dist=%f", BM_ELEM_SELECT, thresh)) { return OPERATOR_CANCELLED; } /* tricky to maintain correct selection here, so just flush up from verts */ EDBM_select_flush(em); EDBM_update_generic(em, true, true); edbm_report_delete_info(op->reports, bm, totelem); return OPERATOR_FINISHED; } void MESH_OT_dissolve_degenerate(wmOperatorType *ot) { /* identifiers */ ot->name = "Degenerate Dissolve"; ot->idname = "MESH_OT_dissolve_degenerate"; ot->description = "Dissolve zero area faces and zero length edges"; /* api callbacks */ ot->exec = edbm_dissolve_degenerate_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float_distance(ot->srna, "threshold", 1e-4f, 1e-6f, 50.0f, "Merge Distance", "Minimum distance between elements to merge", 1e-5f, 10.0f); } /* internally uses dissolve */ static int edbm_delete_edgeloop_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split"); /* deal with selection */ { BMEdge *e; BMIter iter; BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false); BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) { BMLoop *l_iter = e->l; do { BM_elem_flag_enable(l_iter->f, BM_ELEM_TAG); } while ((l_iter = l_iter->radial_next) != e->l); } } } if (!EDBM_op_callf(em, op, "dissolve_edges edges=%he use_verts=%b use_face_split=%b", BM_ELEM_SELECT, true, use_face_split)) { return OPERATOR_CANCELLED; } BM_mesh_elem_hflag_enable_test(em->bm, BM_FACE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG); EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_delete_edgeloop(wmOperatorType *ot) { /* identifiers */ ot->name = "Delete Edge Loop"; ot->description = "Delete an edge loop by merging the faces on each side"; ot->idname = "MESH_OT_delete_edgeloop"; /* api callbacks */ ot->exec = edbm_delete_edgeloop_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_boolean(ot->srna, "use_face_split", true, "Face Split", "Split off face corners to maintain surrounding geometry"); } static int edbm_split_exec(bContext *C, wmOperator *op) { Object *ob = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(ob); BMOperator bmop; EDBM_op_init(em, &bmop, op, "split geom=%hvef use_only_faces=%b", BM_ELEM_SELECT, false); BMO_op_exec(em->bm, &bmop); BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } /* Geometry has changed, need to recalc normals and looptris */ EDBM_mesh_normals_update(em); EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } void MESH_OT_split(wmOperatorType *ot) { /* identifiers */ ot->name = "Split"; ot->idname = "MESH_OT_split"; ot->description = "Split off selected geometry from connected unselected geometry"; /* api callbacks */ ot->exec = edbm_split_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /****************************************************************************** * qsort routines. * Now unified, for vertices/edges/faces. */ enum { SRT_VIEW_ZAXIS = 1, /* Use view Z (deep) axis. */ SRT_VIEW_XAXIS, /* Use view X (left to right) axis. */ SRT_CURSOR_DISTANCE, /* Use distance from element to 3D cursor. */ SRT_MATERIAL, /* Face only: use mat number. */ SRT_SELECTED, /* Move selected elements in first, without modifying * relative order of selected and unselected elements. */ SRT_RANDOMIZE, /* Randomize selected elements. */ SRT_REVERSE, /* Reverse current order of selected elements. */ }; typedef struct BMElemSort { float srt; /* Sort factor */ int org_idx; /* Original index of this element _in its mempool_ */ } BMElemSort; static int bmelemsort_comp(const void *v1, const void *v2) { const BMElemSort *x1 = v1, *x2 = v2; return (x1->srt > x2->srt) - (x1->srt < x2->srt); } /* Reorders vertices/edges/faces using a given methods. Loops are not supported. */ static void sort_bmelem_flag(Scene *scene, Object *ob, View3D *v3d, RegionView3D *rv3d, const int types, const int flag, const int action, const int reverse, const unsigned int seed) { BMEditMesh *em = BKE_editmesh_from_object(ob); BMVert *ve; BMEdge *ed; BMFace *fa; BMIter iter; /* In all five elements below, 0 = vertices, 1 = edges, 2 = faces. */ /* Just to mark protected elements. */ char *pblock[3] = {NULL, NULL, NULL}, *pb; BMElemSort *sblock[3] = {NULL, NULL, NULL}, *sb; unsigned int *map[3] = {NULL, NULL, NULL}, *mp; int totelem[3] = {0, 0, 0}; int affected[3] = {0, 0, 0}; int i, j; if (!(types && flag && action)) return; if (types & BM_VERT) totelem[0] = em->bm->totvert; if (types & BM_EDGE) totelem[1] = em->bm->totedge; if (types & BM_FACE) totelem[2] = em->bm->totface; if (ELEM(action, SRT_VIEW_ZAXIS, SRT_VIEW_XAXIS)) { float mat[4][4]; float fact = reverse ? -1.0 : 1.0; int coidx = (action == SRT_VIEW_ZAXIS) ? 2 : 0; mul_m4_m4m4(mat, rv3d->viewmat, ob->obmat); /* Apply the view matrix to the object matrix. */ if (totelem[0]) { pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock"); sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock"); BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) { if (BM_elem_flag_test(ve, flag)) { float co[3]; mul_v3_m4v3(co, mat, ve->co); pb[i] = false; sb[affected[0]].org_idx = i; sb[affected[0]++].srt = co[coidx] * fact; } else { pb[i] = true; } } } if (totelem[1]) { pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock"); sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock"); BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) { if (BM_elem_flag_test(ed, flag)) { float co[3]; mid_v3_v3v3(co, ed->v1->co, ed->v2->co); mul_m4_v3(mat, co); pb[i] = false; sb[affected[1]].org_idx = i; sb[affected[1]++].srt = co[coidx] * fact; } else { pb[i] = true; } } } if (totelem[2]) { pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock"); sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { float co[3]; BM_face_calc_center_mean(fa, co); mul_m4_v3(mat, co); pb[i] = false; sb[affected[2]].org_idx = i; sb[affected[2]++].srt = co[coidx] * fact; } else { pb[i] = true; } } } } else if (action == SRT_CURSOR_DISTANCE) { float cur[3]; float mat[4][4]; float fact = reverse ? -1.0 : 1.0; if (v3d && v3d->localvd) copy_v3_v3(cur, v3d->cursor); else copy_v3_v3(cur, scene->cursor); invert_m4_m4(mat, ob->obmat); mul_m4_v3(mat, cur); if (totelem[0]) { pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock"); sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock"); BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) { if (BM_elem_flag_test(ve, flag)) { pb[i] = false; sb[affected[0]].org_idx = i; sb[affected[0]++].srt = len_squared_v3v3(cur, ve->co) * fact; } else { pb[i] = true; } } } if (totelem[1]) { pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock"); sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock"); BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) { if (BM_elem_flag_test(ed, flag)) { float co[3]; mid_v3_v3v3(co, ed->v1->co, ed->v2->co); pb[i] = false; sb[affected[1]].org_idx = i; sb[affected[1]++].srt = len_squared_v3v3(cur, co) * fact; } else { pb[i] = true; } } } if (totelem[2]) { pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock"); sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { float co[3]; BM_face_calc_center_mean(fa, co); pb[i] = false; sb[affected[2]].org_idx = i; sb[affected[2]++].srt = len_squared_v3v3(cur, co) * fact; } else { pb[i] = true; } } } } /* Faces only! */ else if (action == SRT_MATERIAL && totelem[2]) { pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock"); sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { /* Reverse materials' order, not order of faces inside each mat! */ /* Note: cannot use totcol, as mat_nr may sometimes be greater... */ float srt = reverse ? (float)(MAXMAT - fa->mat_nr) : (float)fa->mat_nr; pb[i] = false; sb[affected[2]].org_idx = i; /* Multiplying with totface and adding i ensures us we keep current order for all faces of same mat. */ sb[affected[2]++].srt = srt * ((float)totelem[2]) + ((float)i); /* printf("e: %d; srt: %f; final: %f\n", i, srt, srt * ((float)totface) + ((float)i));*/ } else { pb[i] = true; } } } else if (action == SRT_SELECTED) { unsigned int *tbuf[3] = {NULL, NULL, NULL}, *tb; if (totelem[0]) { tb = tbuf[0] = MEM_callocN(sizeof(int) * totelem[0], "sort_bmelem vert tbuf"); mp = map[0] = MEM_callocN(sizeof(int) * totelem[0], "sort_bmelem vert map"); BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) { if (BM_elem_flag_test(ve, flag)) { mp[affected[0]++] = i; } else { *tb = i; tb++; } } } if (totelem[1]) { tb = tbuf[1] = MEM_callocN(sizeof(int) * totelem[1], "sort_bmelem edge tbuf"); mp = map[1] = MEM_callocN(sizeof(int) * totelem[1], "sort_bmelem edge map"); BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) { if (BM_elem_flag_test(ed, flag)) { mp[affected[1]++] = i; } else { *tb = i; tb++; } } } if (totelem[2]) { tb = tbuf[2] = MEM_callocN(sizeof(int) * totelem[2], "sort_bmelem face tbuf"); mp = map[2] = MEM_callocN(sizeof(int) * totelem[2], "sort_bmelem face map"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { mp[affected[2]++] = i; } else { *tb = i; tb++; } } } for (j = 3; j--; ) { int tot = totelem[j]; int aff = affected[j]; tb = tbuf[j]; mp = map[j]; if (!(tb && mp)) continue; if (ELEM(aff, 0, tot)) { MEM_freeN(tb); MEM_freeN(mp); map[j] = NULL; continue; } if (reverse) { memcpy(tb + (tot - aff), mp, aff * sizeof(int)); } else { memcpy(mp + aff, tb, (tot - aff) * sizeof(int)); tb = mp; mp = map[j] = tbuf[j]; tbuf[j] = tb; } /* Reverse mapping, we want an org2new one! */ for (i = tot, tb = tbuf[j] + tot - 1; i--; tb--) { mp[*tb] = i; } MEM_freeN(tbuf[j]); } } else if (action == SRT_RANDOMIZE) { if (totelem[0]) { /* Re-init random generator for each element type, to get consistent random when * enabling/disabling an element type. */ RNG *rng = BLI_rng_new_srandom(seed); pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock"); sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock"); BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) { if (BM_elem_flag_test(ve, flag)) { pb[i] = false; sb[affected[0]].org_idx = i; sb[affected[0]++].srt = BLI_rng_get_float(rng); } else { pb[i] = true; } } BLI_rng_free(rng); } if (totelem[1]) { RNG *rng = BLI_rng_new_srandom(seed); pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock"); sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock"); BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) { if (BM_elem_flag_test(ed, flag)) { pb[i] = false; sb[affected[1]].org_idx = i; sb[affected[1]++].srt = BLI_rng_get_float(rng); } else { pb[i] = true; } } BLI_rng_free(rng); } if (totelem[2]) { RNG *rng = BLI_rng_new_srandom(seed); pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock"); sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { pb[i] = false; sb[affected[2]].org_idx = i; sb[affected[2]++].srt = BLI_rng_get_float(rng); } else { pb[i] = true; } } BLI_rng_free(rng); } } else if (action == SRT_REVERSE) { if (totelem[0]) { pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock"); sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock"); BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) { if (BM_elem_flag_test(ve, flag)) { pb[i] = false; sb[affected[0]].org_idx = i; sb[affected[0]++].srt = (float)-i; } else { pb[i] = true; } } } if (totelem[1]) { pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock"); sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock"); BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) { if (BM_elem_flag_test(ed, flag)) { pb[i] = false; sb[affected[1]].org_idx = i; sb[affected[1]++].srt = (float)-i; } else { pb[i] = true; } } } if (totelem[2]) { pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock"); sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock"); BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) { if (BM_elem_flag_test(fa, flag)) { pb[i] = false; sb[affected[2]].org_idx = i; sb[affected[2]++].srt = (float)-i; } else { pb[i] = true; } } } } /* printf("%d vertices: %d to be affected...\n", totelem[0], affected[0]);*/ /* printf("%d edges: %d to be affected...\n", totelem[1], affected[1]);*/ /* printf("%d faces: %d to be affected...\n", totelem[2], affected[2]);*/ if (affected[0] == 0 && affected[1] == 0 && affected[2] == 0) { for (j = 3; j--; ) { if (pblock[j]) MEM_freeN(pblock[j]); if (sblock[j]) MEM_freeN(sblock[j]); if (map[j]) MEM_freeN(map[j]); } return; } /* Sort affected elements, and populate mapping arrays, if needed. */ for (j = 3; j--; ) { pb = pblock[j]; sb = sblock[j]; if (pb && sb && !map[j]) { const char *p_blk; BMElemSort *s_blk; int tot = totelem[j]; int aff = affected[j]; qsort(sb, aff, sizeof(BMElemSort), bmelemsort_comp); mp = map[j] = MEM_mallocN(sizeof(int) * tot, "sort_bmelem map"); p_blk = pb + tot - 1; s_blk = sb + aff - 1; for (i = tot; i--; p_blk--) { if (*p_blk) { /* Protected! */ mp[i] = i; } else { mp[s_blk->org_idx] = i; s_blk--; } } } if (pb) MEM_freeN(pb); if (sb) MEM_freeN(sb); } BM_mesh_remap(em->bm, map[0], map[1], map[2]); /* DAG_id_tag_update(ob->data, 0);*/ for (j = 3; j--; ) { if (map[j]) MEM_freeN(map[j]); } } static int edbm_sort_elements_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Object *ob = CTX_data_edit_object(C); /* may be NULL */ View3D *v3d = CTX_wm_view3d(C); RegionView3D *rv3d = ED_view3d_context_rv3d(C); const int action = RNA_enum_get(op->ptr, "type"); PropertyRNA *prop_elem_types = RNA_struct_find_property(op->ptr, "elements"); const bool use_reverse = RNA_boolean_get(op->ptr, "reverse"); unsigned int seed = RNA_int_get(op->ptr, "seed"); int elem_types = 0; if (ELEM(action, SRT_VIEW_ZAXIS, SRT_VIEW_XAXIS)) { if (rv3d == NULL) { BKE_report(op->reports, RPT_ERROR, "View not found, cannot sort by view axis"); return OPERATOR_CANCELLED; } } /* If no elem_types set, use current selection mode to set it! */ if (RNA_property_is_set(op->ptr, prop_elem_types)) { elem_types = RNA_property_enum_get(op->ptr, prop_elem_types); } else { BMEditMesh *em = BKE_editmesh_from_object(ob); if (em->selectmode & SCE_SELECT_VERTEX) elem_types |= BM_VERT; if (em->selectmode & SCE_SELECT_EDGE) elem_types |= BM_EDGE; if (em->selectmode & SCE_SELECT_FACE) elem_types |= BM_FACE; RNA_enum_set(op->ptr, "elements", elem_types); } sort_bmelem_flag(scene, ob, v3d, rv3d, elem_types, BM_ELEM_SELECT, action, use_reverse, seed); return OPERATOR_FINISHED; } static bool edbm_sort_elements_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) { const char *prop_id = RNA_property_identifier(prop); const int action = RNA_enum_get(ptr, "type"); /* Only show seed for randomize action! */ if (STREQ(prop_id, "seed")) { if (action == SRT_RANDOMIZE) return true; else return false; } /* Hide seed for reverse and randomize actions! */ if (STREQ(prop_id, "reverse")) { if (ELEM(action, SRT_RANDOMIZE, SRT_REVERSE)) return false; else return true; } return true; } static void edbm_sort_elements_ui(bContext *C, wmOperator *op) { uiLayout *layout = op->layout; wmWindowManager *wm = CTX_wm_manager(C); PointerRNA ptr; RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); /* Main auto-draw call. */ uiDefAutoButsRNA(layout, &ptr, edbm_sort_elements_draw_check_prop, '\0'); } void MESH_OT_sort_elements(wmOperatorType *ot) { static EnumPropertyItem type_items[] = { {SRT_VIEW_ZAXIS, "VIEW_ZAXIS", 0, "View Z Axis", "Sort selected elements from farthest to nearest one in current view"}, {SRT_VIEW_XAXIS, "VIEW_XAXIS", 0, "View X Axis", "Sort selected elements from left to right one in current view"}, {SRT_CURSOR_DISTANCE, "CURSOR_DISTANCE", 0, "Cursor Distance", "Sort selected elements from nearest to farthest from 3D cursor"}, {SRT_MATERIAL, "MATERIAL", 0, "Material", "Sort selected elements from smallest to greatest material index (faces only!)"}, {SRT_SELECTED, "SELECTED", 0, "Selected", "Move all selected elements in first places, preserving their relative order " "(WARNING: this will affect unselected elements' indices as well!)"}, {SRT_RANDOMIZE, "RANDOMIZE", 0, "Randomize", "Randomize order of selected elements"}, {SRT_REVERSE, "REVERSE", 0, "Reverse", "Reverse current order of selected elements"}, {0, NULL, 0, NULL, NULL}, }; static EnumPropertyItem elem_items[] = { {BM_VERT, "VERT", 0, "Vertices", ""}, {BM_EDGE, "EDGE", 0, "Edges", ""}, {BM_FACE, "FACE", 0, "Faces", ""}, {0, NULL, 0, NULL, NULL}, }; /* identifiers */ ot->name = "Sort Mesh Elements"; ot->description = "The order of selected vertices/edges/faces is modified, based on a given method"; ot->idname = "MESH_OT_sort_elements"; /* api callbacks */ ot->invoke = WM_menu_invoke; ot->exec = edbm_sort_elements_exec; ot->poll = ED_operator_editmesh; ot->ui = edbm_sort_elements_ui; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ ot->prop = RNA_def_enum(ot->srna, "type", type_items, SRT_VIEW_ZAXIS, "Type", "Type of re-ordering operation to apply"); RNA_def_enum_flag(ot->srna, "elements", elem_items, BM_VERT, "Elements", "Which elements to affect (vertices, edges and/or faces)"); RNA_def_boolean(ot->srna, "reverse", false, "Reverse", "Reverse the sorting effect"); RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Seed", "Seed for random-based operations", 0, 255); } /****** end of qsort stuff ****/ static int edbm_noise_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); Material *ma; Tex *tex; BMVert *eve; BMIter iter; const float fac = RNA_float_get(op->ptr, "factor"); if (em == NULL) { return OPERATOR_FINISHED; } if ((ma = give_current_material(obedit, obedit->actcol)) == NULL || (tex = give_current_material_texture(ma)) == NULL) { BKE_report(op->reports, RPT_WARNING, "Mesh has no material or texture assigned"); return OPERATOR_FINISHED; } if (tex->type == TEX_STUCCI) { float b2, vec[3]; float ofs = tex->turbul / 200.0f; BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) { b2 = BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1], eve->co[2]); if (tex->stype) ofs *= (b2 * b2); vec[0] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0] + ofs, eve->co[1], eve->co[2])); vec[1] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1] + ofs, eve->co[2])); vec[2] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1], eve->co[2] + ofs)); add_v3_v3(eve->co, vec); } } } else { BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) { if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) { float tin = 0.0f, dum; if (ma->mtex[ma->texact] != NULL) { externtex(ma->mtex[ma->texact], eve->co, &tin, &dum, &dum, &dum, &dum, 0, NULL, false, false); } eve->co[2] += fac * tin; } } } EDBM_mesh_normals_update(em); EDBM_update_generic(em, true, false); return OPERATOR_FINISHED; } void MESH_OT_noise(wmOperatorType *ot) { /* identifiers */ ot->name = "Noise"; ot->description = "Use vertex coordinate as texture coordinate"; ot->idname = "MESH_OT_noise"; /* api callbacks */ ot->exec = edbm_noise_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float(ot->srna, "factor", 0.1f, -1e4f, 1e4f, "Factor", "", 0.0f, 1.0f); } enum { MESH_BRIDGELOOP_SINGLE = 0, MESH_BRIDGELOOP_CLOSED = 1, MESH_BRIDGELOOP_PAIRS = 2, }; static int edbm_bridge_tag_boundary_edges(BMesh *bm) { /* tags boundary edges from a face selection */ BMIter iter; BMFace *f; BMEdge *e; int totface_del = 0; BM_mesh_elem_hflag_disable_all(bm, BM_EDGE | BM_FACE, BM_ELEM_TAG, false); BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(e, BM_ELEM_SELECT)) { if (BM_edge_is_wire(e) || BM_edge_is_boundary(e)) { BM_elem_flag_enable(e, BM_ELEM_TAG); } else { BMIter fiter; bool is_all_sel = true; /* check if its only used by selected faces */ BM_ITER_ELEM (f, &fiter, e, BM_FACES_OF_EDGE) { if (BM_elem_flag_test(f, BM_ELEM_SELECT)) { /* tag face for removal*/ if (!BM_elem_flag_test(f, BM_ELEM_TAG)) { BM_elem_flag_enable(f, BM_ELEM_TAG); totface_del++; } } else { is_all_sel = false; } } if (is_all_sel == false) { BM_elem_flag_enable(e, BM_ELEM_TAG); } } } } return totface_del; } static int edbm_bridge_edge_loops_exec(bContext *C, wmOperator *op) { BMOperator bmop; Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); const int type = RNA_enum_get(op->ptr, "type"); const bool use_pairs = (type == MESH_BRIDGELOOP_PAIRS); const bool use_cyclic = (type == MESH_BRIDGELOOP_CLOSED); const bool use_merge = RNA_boolean_get(op->ptr, "use_merge"); const float merge_factor = RNA_float_get(op->ptr, "merge_factor"); const int twist_offset = RNA_int_get(op->ptr, "twist_offset"); const bool use_faces = (em->bm->totfacesel != 0); char edge_hflag; int totface_del = 0; BMFace **totface_del_arr = NULL; if (use_faces) { BMIter iter; BMFace *f; int i; totface_del = edbm_bridge_tag_boundary_edges(em->bm); totface_del_arr = MEM_mallocN(sizeof(*totface_del_arr) * totface_del, __func__); i = 0; BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(f, BM_ELEM_TAG)) { totface_del_arr[i++] = f; } } edge_hflag = BM_ELEM_TAG; } else { edge_hflag = BM_ELEM_SELECT; } EDBM_op_init(em, &bmop, op, "bridge_loops edges=%he use_pairs=%b use_cyclic=%b use_merge=%b merge_factor=%f twist_offset=%i", edge_hflag, use_pairs, use_cyclic, use_merge, merge_factor, twist_offset); if (use_faces && totface_del) { int i; BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false); for (i = 0; i < totface_del; i++) { BM_elem_flag_enable(totface_del_arr[i], BM_ELEM_TAG); } BMO_op_callf(em->bm, BMO_FLAG_DEFAULTS, "delete geom=%hf context=%i", BM_ELEM_TAG, DEL_FACES_KEEP_BOUNDARY); } BMO_op_exec(em->bm, &bmop); if (!BMO_error_occurred(em->bm)) { /* when merge is used the edges are joined and remain selected */ if (use_merge == false) { EDBM_flag_disable_all(em, BM_ELEM_SELECT); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); } if (use_merge == false) { struct EdgeRingOpSubdProps op_props; mesh_operator_edgering_props_get(op, &op_props); if (op_props.cuts) { BMOperator bmop_subd; /* we only need face normals updated */ EDBM_mesh_normals_update(em); BMO_op_initf( em->bm, &bmop_subd, 0, "subdivide_edgering edges=%S interp_mode=%i cuts=%i smooth=%f " "profile_shape=%i profile_shape_factor=%f", &bmop, "edges.out", op_props.interp_mode, op_props.cuts, op_props.smooth, op_props.profile_shape, op_props.profile_shape_factor ); BMO_op_exec(em->bm, &bmop_subd); BMO_slot_buffer_hflag_enable(em->bm, bmop_subd.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); BMO_op_finish(em->bm, &bmop_subd); } } } if (totface_del_arr) { MEM_freeN(totface_del_arr); } if (!EDBM_op_finish(em, &bmop, op, true)) { /* grr, need to return finished so the user can select different options */ //return OPERATOR_CANCELLED; return OPERATOR_FINISHED; } else { EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } } void MESH_OT_bridge_edge_loops(wmOperatorType *ot) { static EnumPropertyItem type_items[] = { {MESH_BRIDGELOOP_SINGLE, "SINGLE", 0, "Open Loop", ""}, {MESH_BRIDGELOOP_CLOSED, "CLOSED", 0, "Closed Loop", ""}, {MESH_BRIDGELOOP_PAIRS, "PAIRS", 0, "Loop Pairs", ""}, {0, NULL, 0, NULL, NULL} }; /* identifiers */ ot->name = "Bridge Edge Loops"; ot->description = "Make faces between two or more edge loops"; ot->idname = "MESH_OT_bridge_edge_loops"; /* api callbacks */ ot->exec = edbm_bridge_edge_loops_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; ot->prop = RNA_def_enum(ot->srna, "type", type_items, MESH_BRIDGELOOP_SINGLE, "Connect Loops", "Method of bridging multiple loops"); RNA_def_boolean(ot->srna, "use_merge", false, "Merge", "Merge rather than creating faces"); RNA_def_float(ot->srna, "merge_factor", 0.5f, 0.0f, 1.0f, "Merge Factor", "", 0.0f, 1.0f); RNA_def_int(ot->srna, "twist_offset", 0, -1000, 1000, "Twist", "Twist offset for closed loops", -1000, 1000); mesh_operator_edgering_props(ot, 0); } static int edbm_wireframe_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const bool use_boundary = RNA_boolean_get(op->ptr, "use_boundary"); const bool use_even_offset = RNA_boolean_get(op->ptr, "use_even_offset"); const bool use_replace = RNA_boolean_get(op->ptr, "use_replace"); const bool use_relative_offset = RNA_boolean_get(op->ptr, "use_relative_offset"); const bool use_crease = RNA_boolean_get(op->ptr, "use_crease"); const float crease_weight = RNA_float_get(op->ptr, "crease_weight"); const float thickness = RNA_float_get(op->ptr, "thickness"); const float offset = RNA_float_get(op->ptr, "offset"); EDBM_op_init(em, &bmop, op, "wireframe faces=%hf use_replace=%b use_boundary=%b use_even_offset=%b use_relative_offset=%b " "use_crease=%b crease_weight=%f thickness=%f offset=%f", BM_ELEM_SELECT, use_replace, use_boundary, use_even_offset, use_relative_offset, use_crease, crease_weight, thickness, offset); BMO_op_exec(em->bm, &bmop); BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } else { EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } } void MESH_OT_wireframe(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Wire Frame"; ot->idname = "MESH_OT_wireframe"; ot->description = "Create a solid wire-frame from faces"; /* api callbacks */ ot->exec = edbm_wireframe_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ RNA_def_boolean(ot->srna, "use_boundary", true, "Boundary", "Inset face boundaries"); RNA_def_boolean(ot->srna, "use_even_offset", true, "Offset Even", "Scale the offset to give more even thickness"); RNA_def_boolean(ot->srna, "use_relative_offset", false, "Offset Relative", "Scale the offset by surrounding geometry"); RNA_def_boolean(ot->srna, "use_replace", true, "Replace", "Remove original faces"); prop = RNA_def_float_distance(ot->srna, "thickness", 0.01f, 0.0f, 1e4f, "Thickness", "", 0.0f, 10.0f); /* use 1 rather then 10 for max else dragging the button moves too far */ RNA_def_property_ui_range(prop, 0.0, 1.0, 0.01, 4); RNA_def_float_distance(ot->srna, "offset", 0.01f, 0.0f, 1e4f, "Offset", "", 0.0f, 10.0f); RNA_def_boolean(ot->srna, "use_crease", false, "Crease", "Crease hub edges for improved subsurf"); prop = RNA_def_float(ot->srna, "crease_weight", 0.01f, 0.0f, 1e3f, "Crease weight", "", 0.0f, 1.0f); RNA_def_property_ui_range(prop, 0.0, 1.0, 0.1, 2); } static int edbm_offset_edgeloop_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const bool use_cap_endpoint = RNA_boolean_get(op->ptr, "use_cap_endpoint"); EDBM_op_init( em, &bmop, op, "offset_edgeloops edges=%he use_cap_endpoint=%b", BM_ELEM_SELECT, use_cap_endpoint); BMO_op_exec(em->bm, &bmop); BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false); /* If in face-only select mode, switch to edge select mode so that * an edge-only selection is not inconsistent state */ if (em->selectmode == SCE_SELECT_FACE) { em->selectmode = SCE_SELECT_EDGE; EDBM_selectmode_set(em); EDBM_selectmode_to_scene(C); } BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } else { EDBM_update_generic(em, true, true); return OPERATOR_FINISHED; } } void MESH_OT_offset_edge_loops(wmOperatorType *ot) { /* identifiers */ ot->name = "Offset Edge Loop"; ot->idname = "MESH_OT_offset_edge_loops"; ot->description = "Create offset edge loop from the current selection"; /* api callbacks */ ot->exec = edbm_offset_edgeloop_exec; ot->poll = ED_operator_editmesh; /* Keep internal, since this is only meant to be accessed via 'MESH_OT_offset_edge_loops_slide' */ /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; RNA_def_boolean(ot->srna, "use_cap_endpoint", false, "Cap Endpoint", "Extend loop around end-points"); } #ifdef WITH_BULLET static int edbm_convex_hull_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; EDBM_op_init(em, &bmop, op, "convex_hull input=%hvef " "use_existing_faces=%b", BM_ELEM_SELECT, RNA_boolean_get(op->ptr, "use_existing_faces")); BMO_op_exec(em->bm, &bmop); /* Hull fails if input is coplanar */ if (BMO_error_occurred(em->bm)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true); /* Delete unused vertices, edges, and faces */ if (RNA_boolean_get(op->ptr, "delete_unused")) { if (!EDBM_op_callf(em, op, "delete geom=%S context=%i", &bmop, "geom_unused.out", DEL_ONLYTAGGED)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } } /* Delete hole edges/faces */ if (RNA_boolean_get(op->ptr, "make_holes")) { if (!EDBM_op_callf(em, op, "delete geom=%S context=%i", &bmop, "geom_holes.out", DEL_ONLYTAGGED)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } } /* Merge adjacent triangles */ if (RNA_boolean_get(op->ptr, "join_triangles")) { float angle_face_threshold = RNA_float_get(op->ptr, "face_threshold"); float angle_shape_threshold = RNA_float_get(op->ptr, "shape_threshold"); if (!EDBM_op_call_and_selectf( em, op, "faces.out", true, "join_triangles faces=%S " "angle_face_threshold=%f angle_shape_threshold=%f", &bmop, "geom.out", angle_face_threshold, angle_shape_threshold)) { EDBM_op_finish(em, &bmop, op, true); return OPERATOR_CANCELLED; } } if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } else { EDBM_update_generic(em, true, true); EDBM_selectmode_flush(em); return OPERATOR_FINISHED; } } void MESH_OT_convex_hull(wmOperatorType *ot) { /* identifiers */ ot->name = "Convex Hull"; ot->description = "Enclose selected vertices in a convex polyhedron"; ot->idname = "MESH_OT_convex_hull"; /* api callbacks */ ot->exec = edbm_convex_hull_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "delete_unused", true, "Delete Unused", "Delete selected elements that are not used by the hull"); RNA_def_boolean(ot->srna, "use_existing_faces", true, "Use Existing Faces", "Skip hull triangles that are covered by a pre-existing face"); RNA_def_boolean(ot->srna, "make_holes", false, "Make Holes", "Delete selected faces that are used by the hull"); RNA_def_boolean(ot->srna, "join_triangles", true, "Join Triangles", "Merge adjacent triangles into quads"); join_triangle_props(ot); } #endif static int mesh_symmetrize_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMOperator bmop; const float thresh = RNA_float_get(op->ptr, "threshold"); EDBM_op_init(em, &bmop, op, "symmetrize input=%hvef direction=%i dist=%f", BM_ELEM_SELECT, RNA_enum_get(op->ptr, "direction"), thresh); BMO_op_exec(em->bm, &bmop); EDBM_flag_disable_all(em, BM_ELEM_SELECT); BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true); if (!EDBM_op_finish(em, &bmop, op, true)) { return OPERATOR_CANCELLED; } else { EDBM_update_generic(em, true, true); EDBM_selectmode_flush(em); return OPERATOR_FINISHED; } } void MESH_OT_symmetrize(struct wmOperatorType *ot) { /* identifiers */ ot->name = "Symmetrize"; ot->description = "Enforce symmetry (both form and topological) across an axis"; ot->idname = "MESH_OT_symmetrize"; /* api callbacks */ ot->exec = mesh_symmetrize_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; ot->prop = RNA_def_enum(ot->srna, "direction", rna_enum_symmetrize_direction_items, BMO_SYMMETRIZE_NEGATIVE_X, "Direction", "Which sides to copy from and to"); RNA_def_float(ot->srna, "threshold", 1e-4f, 0.0f, 10.0f, "Threshold", "", 1e-5f, 0.1f); } static int mesh_symmetry_snap_exec(bContext *C, wmOperator *op) { const float eps = 0.00001f; const float eps_sq = eps * eps; Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = BKE_editmesh_from_object(obedit); BMesh *bm = em->bm; int *index = MEM_mallocN(bm->totvert * sizeof(*index), __func__); const bool use_topology = false; const float thresh = RNA_float_get(op->ptr, "threshold"); const float fac = RNA_float_get(op->ptr, "factor"); const bool use_center = RNA_boolean_get(op->ptr, "use_center"); /* stats */ int totmirr = 0, totfail = 0, totfound = 0; /* axix */ const int axis_dir = RNA_enum_get(op->ptr, "direction"); int axis = axis_dir % 3; bool axis_sign = axis != axis_dir; /* vertex iter */ BMIter iter; BMVert *v; int i; EDBM_verts_mirror_cache_begin_ex(em, axis, true, true, use_topology, thresh, index); BM_mesh_elem_table_ensure(bm, BM_VERT); BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false); BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) { if ((BM_elem_flag_test(v, BM_ELEM_SELECT) != false) && (BM_elem_flag_test(v, BM_ELEM_TAG) == false)) { int i_mirr = index[i]; if (i_mirr != -1) { BMVert *v_mirr = BM_vert_at_index(bm, index[i]); if (v != v_mirr) { float co[3], co_mirr[3]; if ((v->co[axis] > v_mirr->co[axis]) == axis_sign) { SWAP(BMVert *, v, v_mirr); } copy_v3_v3(co_mirr, v_mirr->co); co_mirr[axis] *= -1.0f; if (len_squared_v3v3(v->co, co_mirr) > eps_sq) { totmirr++; } interp_v3_v3v3(co, v->co, co_mirr, fac); copy_v3_v3(v->co, co); co[axis] *= -1.0f; copy_v3_v3(v_mirr->co, co); BM_elem_flag_enable(v, BM_ELEM_TAG); BM_elem_flag_enable(v_mirr, BM_ELEM_TAG); totfound++; } else { if (use_center) { if (fabsf(v->co[axis]) > eps) { totmirr++; } v->co[axis] = 0.0f; } BM_elem_flag_enable(v, BM_ELEM_TAG); totfound++; } } else { totfail++; } } } if (totfail) { BKE_reportf(op->reports, RPT_WARNING, "%d already symmetrical, %d pairs mirrored, %d failed", totfound - totmirr, totmirr, totfail); } else { BKE_reportf(op->reports, RPT_INFO, "%d already symmetrical, %d pairs mirrored", totfound - totmirr, totmirr); } /* no need to end cache, just free the array */ MEM_freeN(index); return OPERATOR_FINISHED; } void MESH_OT_symmetry_snap(struct wmOperatorType *ot) { /* identifiers */ ot->name = "Snap to Symmetry"; ot->description = "Snap vertex pairs to their mirrored locations"; ot->idname = "MESH_OT_symmetry_snap"; /* api callbacks */ ot->exec = mesh_symmetry_snap_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; ot->prop = RNA_def_enum(ot->srna, "direction", rna_enum_symmetrize_direction_items, BMO_SYMMETRIZE_NEGATIVE_X, "Direction", "Which sides to copy from and to"); RNA_def_float_distance(ot->srna, "threshold", 0.05f, 0.0f, 10.0f, "Threshold", "", 1e-4f, 1.0f); RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0f, "Factor", "", 0.0f, 1.0f); RNA_def_boolean(ot->srna, "use_center", true, "Center", "Snap mid verts to the axis center"); } #ifdef WITH_FREESTYLE static int edbm_mark_freestyle_edge_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = (Mesh *)obedit->data; BMEditMesh *em = BKE_editmesh_from_object(obedit); BMEdge *eed; BMIter iter; FreestyleEdge *fed; const bool clear = RNA_boolean_get(op->ptr, "clear"); if (em == NULL) return OPERATOR_FINISHED; /* auto-enable Freestyle edge mark drawing */ if (clear == 0) { me->drawflag |= ME_DRAW_FREESTYLE_EDGE; } if (!CustomData_has_layer(&em->bm->edata, CD_FREESTYLE_EDGE)) { BM_data_layer_add(em->bm, &em->bm->edata, CD_FREESTYLE_EDGE); } if (clear) { BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(eed, BM_ELEM_SELECT) && !BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) { fed = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_FREESTYLE_EDGE); fed->flag &= ~FREESTYLE_EDGE_MARK; } } } else { BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) { if (BM_elem_flag_test(eed, BM_ELEM_SELECT) && !BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) { fed = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_FREESTYLE_EDGE); fed->flag |= FREESTYLE_EDGE_MARK; } } } DAG_id_tag_update(obedit->data, OB_RECALC_DATA); WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data); return OPERATOR_FINISHED; } void MESH_OT_mark_freestyle_edge(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Mark Freestyle Edge"; ot->description = "(Un)mark selected edges as Freestyle feature edges"; ot->idname = "MESH_OT_mark_freestyle_edge"; /* api callbacks */ ot->exec = edbm_mark_freestyle_edge_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); RNA_def_property_flag(prop, PROP_SKIP_SAVE); } static int edbm_mark_freestyle_face_exec(bContext *C, wmOperator *op) { Object *obedit = CTX_data_edit_object(C); Mesh *me = (Mesh *)obedit->data; BMEditMesh *em = BKE_editmesh_from_object(obedit); BMFace *efa; BMIter iter; FreestyleFace *ffa; const bool clear = RNA_boolean_get(op->ptr, "clear"); if (em == NULL) return OPERATOR_FINISHED; /* auto-enable Freestyle face mark drawing */ if (!clear) { me->drawflag |= ME_DRAW_FREESTYLE_FACE; } if (!CustomData_has_layer(&em->bm->pdata, CD_FREESTYLE_FACE)) { BM_data_layer_add(em->bm, &em->bm->pdata, CD_FREESTYLE_FACE); } if (clear) { BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) { ffa = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_FREESTYLE_FACE); ffa->flag &= ~FREESTYLE_FACE_MARK; } } } else { BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) { if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) { ffa = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_FREESTYLE_FACE); ffa->flag |= FREESTYLE_FACE_MARK; } } } DAG_id_tag_update(obedit->data, OB_RECALC_DATA); WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data); return OPERATOR_FINISHED; } void MESH_OT_mark_freestyle_face(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Mark Freestyle Face"; ot->description = "(Un)mark selected faces for exclusion from Freestyle feature edge detection"; ot->idname = "MESH_OT_mark_freestyle_face"; /* api callbacks */ ot->exec = edbm_mark_freestyle_face_exec; ot->poll = ED_operator_editmesh; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", ""); RNA_def_property_flag(prop, PROP_SKIP_SAVE); } #endif
226963.c
Mac OS X  2 RTEXTKAHL8
813252.c
// fake-gold.c inherit ITEM; void create() { set_name("黄金", ({"gold", "ingot", "gold_money"})); set_weight(150000); if( clonep() ) set_default_object(__FILE__); else { set("long", "黄澄澄的金子,人见人爱的金子,不过 ...颜色有点不对。\n"); set("unit", "块"); set("material", "lead"); } setup(); }
834514.c
/* * RFC 3389 comfort noise generator * Copyright (c) 2012 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <math.h> #include "libavutil/common.h" #include "avcodec.h" #include "celp_filters.h" #include "internal.h" #include "libavutil/lfg.h" typedef struct CNGContext { float *refl_coef, *target_refl_coef; float *lpc_coef; int order; int energy, target_energy; int inited; float *filter_out; float *excitation; AVLFG lfg; } CNGContext; static av_cold int cng_decode_close(AVCodecContext *avctx) { CNGContext *p = avctx->priv_data; av_freep(&p->refl_coef); av_freep(&p->target_refl_coef); av_freep(&p->lpc_coef); av_freep(&p->filter_out); av_freep(&p->excitation); return 0; } static av_cold int cng_decode_init(AVCodecContext *avctx) { CNGContext *p = avctx->priv_data; avctx->sample_fmt = AV_SAMPLE_FMT_S16; avctx->channels = 1; avctx->sample_rate = 8000; p->order = 12; avctx->frame_size = 640; p->refl_coef = av_mallocz_array(p->order, sizeof(*p->refl_coef)); p->target_refl_coef = av_mallocz_array(p->order, sizeof(*p->target_refl_coef)); p->lpc_coef = av_mallocz_array(p->order, sizeof(*p->lpc_coef)); p->filter_out = av_mallocz_array(avctx->frame_size + p->order, sizeof(*p->filter_out)); p->excitation = av_mallocz_array(avctx->frame_size, sizeof(*p->excitation)); if (!p->refl_coef || !p->target_refl_coef || !p->lpc_coef || !p->filter_out || !p->excitation) { cng_decode_close(avctx); return AVERROR(ENOMEM); } av_lfg_init(&p->lfg, 0); return 0; } static void make_lpc_coefs(float *lpc, const float *refl, int order) { float buf[100]; float *next, *cur; int m, i; next = buf; cur = lpc; for (m = 0; m < order; m++) { next[m] = refl[m]; for (i = 0; i < m; i++) next[i] = cur[i] + refl[m] * cur[m - i - 1]; FFSWAP(float*, next, cur); } if (cur != lpc) memcpy(lpc, cur, sizeof(*lpc) * order); } static void cng_decode_flush(AVCodecContext *avctx) { CNGContext *p = avctx->priv_data; p->inited = 0; } static int cng_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; CNGContext *p = avctx->priv_data; int buf_size = avpkt->size; int ret, i; int16_t *buf_out; float e = 1.0; float scaling; if (avpkt->size) { int dbov = -avpkt->data[0]; p->target_energy = 1081109975 * pow(10, dbov / 10.0) * 0.75; memset(p->target_refl_coef, 0, p->order * sizeof(*p->target_refl_coef)); for (i = 0; i < FFMIN(avpkt->size - 1, p->order); i++) { p->target_refl_coef[i] = (avpkt->data[1 + i] - 127) / 128.0; } } if (p->inited) { p->energy = p->energy / 2 + p->target_energy / 2; for (i = 0; i < p->order; i++) p->refl_coef[i] = 0.6 *p->refl_coef[i] + 0.4 * p->target_refl_coef[i]; } else { p->energy = p->target_energy; memcpy(p->refl_coef, p->target_refl_coef, p->order * sizeof(*p->refl_coef)); p->inited = 1; } make_lpc_coefs(p->lpc_coef, p->refl_coef, p->order); for (i = 0; i < p->order; i++) e *= 1.0 - p->refl_coef[i]*p->refl_coef[i]; scaling = sqrt(e * p->energy / 1081109975); for (i = 0; i < avctx->frame_size; i++) { int r = (av_lfg_get(&p->lfg) & 0xffff) - 0x8000; p->excitation[i] = scaling * r; } ff_celp_lp_synthesis_filterf(p->filter_out + p->order, p->lpc_coef, p->excitation, avctx->frame_size, p->order); frame->nb_samples = avctx->frame_size; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; buf_out = (int16_t *)frame->data[0]; for (i = 0; i < avctx->frame_size; i++) buf_out[i] = p->filter_out[i + p->order]; memcpy(p->filter_out, p->filter_out + avctx->frame_size, p->order * sizeof(*p->filter_out)); *got_frame_ptr = 1; return buf_size; } AVCodec ff_comfortnoise_decoder = { .name = "comfortnoise", .long_name = NULL_IF_CONFIG_SMALL("RFC 3389 comfort noise generator"), .type = AVMEDIA_TYPE_AUDIO, .id = AV_CODEC_ID_COMFORT_NOISE, .priv_data_size = sizeof(CNGContext), .init = cng_decode_init, .decode = cng_decode_frame, .flush = cng_decode_flush, .close = cng_decode_close, .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE }, .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1, };
360412.c
#include "maxminddb_test_helper.h" void test_metadata(MMDB_s *mmdb, const char *mode_desc) { cmp_ok(mmdb->metadata.node_count, "==", 37, "node_count is 37 - %s", mode_desc); cmp_ok(mmdb->metadata.record_size, "==", 24, "record_size is 24 - %s", mode_desc); cmp_ok(mmdb->metadata.ip_version, "==", 4, "ip_version is 4 - %s", mode_desc); is(mmdb->metadata.database_type, "Test", "database_type is Test - %s", mode_desc); // 2013-07-01T00:00:00Z uint64_t expect_epoch = 1372636800; int is_ok = cmp_ok(mmdb->metadata.build_epoch, ">=", expect_epoch, "build_epoch > %lli", expect_epoch); if (!is_ok) { diag(" epoch is %lli", mmdb->metadata.build_epoch); } cmp_ok(mmdb->metadata.binary_format_major_version, "==", 2, "binary_format_major_version is 2 - %s", mode_desc); cmp_ok(mmdb->metadata.binary_format_minor_version, "==", 0, "binary_format_minor_version is 0 - %s", mode_desc); cmp_ok(mmdb->metadata.languages.count, "==", 2, "found 2 languages - %s", mode_desc); is(mmdb->metadata.languages.names[0], "en", "first language is en - %s", mode_desc); is(mmdb->metadata.languages.names[1], "zh", "second language is zh - %s", mode_desc); cmp_ok(mmdb->metadata.description.count, "==", 2, "found 2 descriptions - %s", mode_desc); for (uint16_t i = 0; i < mmdb->metadata.description.count; i++) { const char *language = mmdb->metadata.description.descriptions[i]->language; const char *description = mmdb->metadata.description.descriptions[i]->description; if (strncmp(language, "en", 2) == 0) { ok(1, "found en description"); is(description, "Test Database", "en description"); } else if (strncmp(language, "zh", 2) == 0) { ok(1, "found zh description"); is(description, "Test Database Chinese", "zh description"); } else { ok(0, "found unknown description in unexpected language - %s", language); } } cmp_ok(mmdb->full_record_byte_size, "==", 6, "full_record_byte_size is 6 - %s", mode_desc); } MMDB_entry_data_list_s *test_languages_value(MMDB_entry_data_list_s *entry_data_list) { MMDB_entry_data_list_s *languages = entry_data_list = entry_data_list->next; cmp_ok(languages->entry_data.type, "==", MMDB_DATA_TYPE_ARRAY, "'languages' key's value is an array"); cmp_ok(languages->entry_data.data_size, "==", 2, "'languages' key's value has 2 elements"); MMDB_entry_data_list_s *idx0 = entry_data_list = entry_data_list->next; cmp_ok(idx0->entry_data.type, "==", MMDB_DATA_TYPE_UTF8_STRING, "first array entry is a UTF8_STRING"); const char *lang0 = dup_entry_string_or_bail(idx0->entry_data); is(lang0, "en", "first language is en"); free((void *)lang0); MMDB_entry_data_list_s *idx1 = entry_data_list = entry_data_list->next; cmp_ok(idx1->entry_data.type, "==", MMDB_DATA_TYPE_UTF8_STRING, "second array entry is a UTF8_STRING"); const char *lang1 = dup_entry_string_or_bail(idx1->entry_data); is(lang1, "zh", "second language is zh"); free((void *)lang1); return entry_data_list; } MMDB_entry_data_list_s *test_description_value( MMDB_entry_data_list_s *entry_data_list) { MMDB_entry_data_list_s *description = entry_data_list = entry_data_list->next; cmp_ok(description->entry_data.type, "==", MMDB_DATA_TYPE_MAP, "'description' key's value is a map"); cmp_ok(description->entry_data.data_size, "==", 2, "'description' key's value has 2 key/value pairs"); for (int i = 0; i < 2; i++) { MMDB_entry_data_list_s *key = entry_data_list = entry_data_list->next; cmp_ok(key->entry_data.type, "==", MMDB_DATA_TYPE_UTF8_STRING, "found a map key in 'map'"); const char *key_name = dup_entry_string_or_bail(key->entry_data); MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.type, "==", MMDB_DATA_TYPE_UTF8_STRING, "map value is a UTF8_STRING"); const char *description = dup_entry_string_or_bail(value->entry_data); if (strcmp(key_name, "en") == 0) { is(description, "Test Database", "en description == 'Test Database'"); } else if (strcmp(key_name, "zh") == 0) { is(description, "Test Database Chinese", "zh description == 'Test Database Chinese'"); } else { ok(0, "unknown key found in description map - %s", key_name); } free((void *)key_name); free((void *)description); } return entry_data_list; } void test_metadata_as_data_entry_list(MMDB_s * mmdb, const char *mode_desc) { MMDB_entry_data_list_s *entry_data_list, *first; int status = MMDB_get_metadata_as_entry_data_list(mmdb, &entry_data_list); first = entry_data_list; cmp_ok(status, "==", MMDB_SUCCESS, "get metadata as data_entry_list - %s", mode_desc); cmp_ok(first->entry_data.data_size, "==", 9, "metadata map has 9 key/value pairs"); while (1) { MMDB_entry_data_list_s *key = entry_data_list = entry_data_list->next; if (!key) { break; } cmp_ok(key->entry_data.type, "==", MMDB_DATA_TYPE_UTF8_STRING, "found a map key"); const char *key_name = dup_entry_string_or_bail(key->entry_data); if (strcmp(key_name, "node_count") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.uint32, "==", 37, "node_count == 37"); } else if (strcmp(key_name, "record_size") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.uint16, "==", 24, "record_size == 24"); } else if (strcmp(key_name, "ip_version") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.uint16, "==", 4, "ip_version == 4"); } else if (strcmp(key_name, "binary_format_major_version") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.uint16, "==", 2, "binary_format_major_version == 2"); } else if (strcmp(key_name, "binary_format_minor_version") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; cmp_ok(value->entry_data.uint16, "==", 0, "binary_format_minor_version == 0"); } else if (strcmp(key_name, "build_epoch") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; ok(value->entry_data.uint64 > 1373571901, "build_epoch > 1373571901"); } else if (strcmp(key_name, "database_type") == 0) { MMDB_entry_data_list_s *value = entry_data_list = entry_data_list->next; const char *type = dup_entry_string_or_bail(value->entry_data); is(type, "Test", "type == Test"); free((void *)type); } else if (strcmp(key_name, "languages") == 0) { entry_data_list = test_languages_value(entry_data_list); } else if (strcmp(key_name, "description") == 0) { entry_data_list = test_description_value(entry_data_list); } else { ok(0, "unknown key found in metadata map - %s", key_name); } free((void *)key_name); } MMDB_free_entry_data_list(first); } void run_tests(int mode, const char *mode_desc) { const char *file = "MaxMind-DB-test-ipv4-24.mmdb"; const char *path = test_database_path(file); MMDB_s *mmdb = open_ok(path, mode, mode_desc); // All of the remaining tests require an open mmdb if (NULL == mmdb) { diag("could not open %s - skipping remaining tests", path); return; } free((void *)path); test_metadata(mmdb, mode_desc); test_metadata_as_data_entry_list(mmdb, mode_desc); MMDB_close(mmdb); free(mmdb); } int main(void) { plan(NO_PLAN); for_all_modes(&run_tests); done_testing(); }
646881.c
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <TargetConditionals.h> #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/string/flsll.c,v 1.1 2008/11/03 10:22:19 kib Exp $"); #include <strings.h> /* * Find Last Set bit */ int flsll(long long mask) { #if __has_builtin(__builtin_flsll) return __builtin_flsll(mask); #elif __has_builtin(__builtin_clzll) if (mask == 0) return (0); return (sizeof(mask) << 3) - __builtin_clzll(mask); #else int bit; if (mask == 0) return (0); for (bit = 1; mask != 1; bit++) mask = (unsigned long long)mask >> 1; return (bit); #endif } //#if VARIANT_DYLD && TARGET_IPHONE_SIMULATOR int flsl(long mask) { #if __has_builtin(__builtin_flsl) return __builtin_flsl(mask); #elif __has_builtin(__builtin_clzl) if (mask == 0) return (0); return (sizeof(mask) << 3) - __builtin_clzl(mask); #else int bit; if (mask == 0) return (0); for (bit = 1; mask != 1; bit++) mask = (unsigned long)mask >> 1; return (bit); #endif } int fls(int mask) { #if __has_builtin(__builtin_fls) return __builtin_fls(mask); #elif __has_builtin(__builtin_clz) if (mask == 0) return (0); return (sizeof(mask) << 3) - __builtin_clz(mask); #else int bit; if (mask == 0) return (0); for (bit = 1; mask != 1; bit++) mask = (unsigned)mask >> 1; return (bit); #endif } //#endif
972865.c
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdlib/ndarray/base/napi/addon_arguments.h" #include "stdlib/ndarray/ctor.h" #include <node_api.h> #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> /** * Validates, extracts, and transforms (to native C types) function arguments provided to an ndarray Node-API add-on interface. * * ## Notes * * - The function assumes the following argument order: * * ```text * [ ib1, im1, ib2, im2, ..., ob1, om1, ob2, om2, ... ] * ``` * * where * * - `ib#` is a data buffer for an input ndarray * - `im#` is meta data for an input ndarray * - `ob#` is a data buffer for an output ndarray * - `om#` is meta data for an output ndarray * * - The function may return one of the following JavaScript errors: * * - `Error`: unable to allocate memory when processing input ndarray * - `Error`: unable to allocate memory when processing output ndarray * * @param env environment under which the function is invoked * @param argv ndarray function arguments * @param nargs total number of expected arguments * @param nin number of input ndarrays * @param arrays destination array for storing pointers to both input and output ndarrays * @param err pointer for storing a JavaScript error * @return status code indicating success or failure (returns `napi_ok` if success) * * @example * #include "stdlib/ndarray/base/napi/addon_arguments.h" * #include "stdlib/ndarray/ctor.h" * #include <node_api.h> * #include <stdint.h> * #include <assert.h> * * // Add-on function... * napi_value addon( napi_env env, napi_callback_info info ) { * napi_status status; * * // ... * * int64_t nargs = 6; * int64_t nin = 2; * * // Get callback arguments: * size_t argc = 6; * napi_value argv[ 6 ]; * status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr ); * assert( status == napi_ok ); * * // ... * * // Process the provided arguments: * struct ndarray *arrays[ 3 ]; * * napi_value err; * status = stdlib_ndarray_napi_addon_arguments( env, argv, nargs, nin, arrays, &err ); * assert( status == napi_ok ); * * // ... * * } */ napi_status stdlib_ndarray_napi_addon_arguments( const napi_env env, const napi_value *argv, const int64_t nargs, const int64_t nin, struct ndarray *arrays[], napi_value *err ) { napi_status status; // Reset the output error: *err = NULL; // Compute the index of the first output array argument: int64_t iout = nin * 2; // For each ndarray, we expect 2 arguments: the data buffer and the array meta data... for ( int64_t i = 0; i < nargs; i += 2 ) { // Retrieve the ndarray data buffer: uint8_t *data; status = napi_get_typedarray_info( env, argv[ i ], NULL, NULL, (void *)&data, NULL, NULL ); assert( status == napi_ok ); // Retrieve the ndarray meta data: uint8_t *meta; size_t byteoffset; status = napi_get_dataview_info( env, argv[ i+1 ], NULL, (void *)&meta, NULL, &byteoffset ); assert( status == napi_ok ); // Retrieve ndarray properties... uint8_t *ptr = meta + byteoffset + 1; // +1 as the first byte is the endianness, which we ignore based on the assumption that the endianness is the same for both C and JavaScript int16_t dtype = *(int16_t *)ptr; ptr += 2; int64_t ndims = *(int64_t *)ptr; ptr += 8; int64_t *shape = (int64_t *)ptr; ptr += ndims * 8; int64_t *strides = (int64_t *)ptr; ptr += ndims * 8; int64_t offset = *(int64_t *)ptr; ptr += 8; int8_t order = *(int8_t *)ptr; ptr += 1; int8_t imode = *(int8_t *)ptr; ptr += 1; int64_t nsubmodes = *(int64_t *)ptr; ptr += 8; int8_t *submodes = (int8_t *)ptr; // FIXME: the following is commented out, as we don't yet do anything with serialized flags (e.g., read-only flag, etc); once flags are supported, this comment should be removed and the following uncommented... // ptr += nsubmodes * 1; // int32_t *flags = (int32_t *)ptr; // Allocate a new ndarray: struct ndarray *arr = stdlib_ndarray_allocate( dtype, data, ndims, shape, strides, offset, order, imode, nsubmodes, submodes ); if ( arr == NULL ) { napi_value msg; if ( i < iout ) { status = napi_create_string_utf8( env, "runtime exception. Unable to allocate memory when processing an input ndarray.", NAPI_AUTO_LENGTH, &msg ); } else { status = napi_create_string_utf8( env, "runtime exception. Unable to allocate memory when processing an output ndarray.", NAPI_AUTO_LENGTH, &msg ); } assert( status == napi_ok ); napi_value code; status = napi_create_string_utf8( env, "ERR_MEMORY_ALLOCATION_FAILED", NAPI_AUTO_LENGTH, &code ); assert( status == napi_ok ); napi_value error; status = napi_create_error( env, code, msg, &error ); assert( status == napi_ok ); *err = error; return napi_ok; } // Set the output data: arrays[ i/2 ] = arr; } return napi_ok; }
347354.c
#include "hdr.h" void recover(FILE *fp,char *pidof) { char kill[MAXCHARS]; long timeout; timeout = RCV_INTERVAL * MINUTE; fputs("Entered recovery mode\n", fp); snprintf(kill, sizeof(kill),"kill -9 $(%s)", pidof); system(kill); while (timeout > 0){ fprintf(fp, "Time until retry %ldmin\n", timeout/MINUTE); fflush(fp); timeout -= MINUTE; sleep(MINUTE); } }
107106.c
/* * proc/fs/generic.c --- generic routines for the proc-fs * * This file contains generic proc-fs routines for handling * directories and files. * * Copyright (C) 1991, 1992 Linus Torvalds. * Copyright (C) 1997 Theodore Ts'o */ #include <linux/errno.h> #include <linux/time.h> #include <linux/proc_fs.h> #include <linux/stat.h> #include <linux/module.h> #include <linux/mount.h> #include <linux/smp_lock.h> #include <linux/init.h> #include <linux/idr.h> #include <linux/namei.h> #include <linux/bitops.h> #include <asm/uaccess.h> #include "internal.h" static ssize_t proc_file_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos); static ssize_t proc_file_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos); static loff_t proc_file_lseek(struct file *, loff_t, int); int proc_match(int len, const char *name, struct proc_dir_entry *de) { if (de->namelen != len) return 0; return !memcmp(name, de->name, len); } static struct file_operations proc_file_operations = { .llseek = proc_file_lseek, .read = proc_file_read, .write = proc_file_write, }; /* buffer size is one page but our output routines use some slack for overruns */ #define PROC_BLOCK_SIZE (PAGE_SIZE - 1024) static ssize_t proc_file_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct inode * inode = file->f_dentry->d_inode; char *page; ssize_t retval=0; int eof=0; ssize_t n, count; char *start; struct proc_dir_entry * dp; unsigned long long pos; /* * Gaah, please just use "seq_file" instead. The legacy /proc * interfaces cut loff_t down to off_t for reads, and ignore * the offset entirely for writes.. */ pos = *ppos; if (pos > MAX_NON_LFS) return 0; if (nbytes > MAX_NON_LFS - pos) nbytes = MAX_NON_LFS - pos; dp = PDE(inode); if (!(page = (char*) __get_free_page(GFP_KERNEL))) return -ENOMEM; while ((nbytes > 0) && !eof) { count = min_t(size_t, PROC_BLOCK_SIZE, nbytes); start = NULL; if (dp->get_info) { /* Handle old net routines */ n = dp->get_info(page, &start, *ppos, count); if (n < count) eof = 1; } else if (dp->read_proc) { /* * How to be a proc read function * ------------------------------ * Prototype: * int f(char *buffer, char **start, off_t offset, * int count, int *peof, void *dat) * * Assume that the buffer is "count" bytes in size. * * If you know you have supplied all the data you * have, set *peof. * * You have three ways to return data: * 0) Leave *start = NULL. (This is the default.) * Put the data of the requested offset at that * offset within the buffer. Return the number (n) * of bytes there are from the beginning of the * buffer up to the last byte of data. If the * number of supplied bytes (= n - offset) is * greater than zero and you didn't signal eof * and the reader is prepared to take more data * you will be called again with the requested * offset advanced by the number of bytes * absorbed. This interface is useful for files * no larger than the buffer. * 1) Set *start = an unsigned long value less than * the buffer address but greater than zero. * Put the data of the requested offset at the * beginning of the buffer. Return the number of * bytes of data placed there. If this number is * greater than zero and you didn't signal eof * and the reader is prepared to take more data * you will be called again with the requested * offset advanced by *start. This interface is * useful when you have a large file consisting * of a series of blocks which you want to count * and return as wholes. * (Hack by [email protected]) * 2) Set *start = an address within the buffer. * Put the data of the requested offset at *start. * Return the number of bytes of data placed there. * If this number is greater than zero and you * didn't signal eof and the reader is prepared to * take more data you will be called again with the * requested offset advanced by the number of bytes * absorbed. */ n = dp->read_proc(page, &start, *ppos, count, &eof, dp->data); } else break; if (n == 0) /* end of file */ break; if (n < 0) { /* error */ if (retval == 0) retval = n; break; } if (start == NULL) { if (n > PAGE_SIZE) { printk(KERN_ERR "proc_file_read: Apparent buffer overflow!\n"); n = PAGE_SIZE; } n -= *ppos; if (n <= 0) break; if (n > count) n = count; start = page + *ppos; } else if (start < page) { if (n > PAGE_SIZE) { printk(KERN_ERR "proc_file_read: Apparent buffer overflow!\n"); n = PAGE_SIZE; } if (n > count) { /* * Don't reduce n because doing so might * cut off part of a data block. */ printk(KERN_WARNING "proc_file_read: Read count exceeded\n"); } } else /* start >= page */ { unsigned long startoff = (unsigned long)(start - page); if (n > (PAGE_SIZE - startoff)) { printk(KERN_ERR "proc_file_read: Apparent buffer overflow!\n"); n = PAGE_SIZE - startoff; } if (n > count) n = count; } n -= copy_to_user(buf, start < page ? page : start, n); if (n == 0) { if (retval == 0) retval = -EFAULT; break; } *ppos += start < page ? (unsigned long)start : n; nbytes -= n; buf += n; retval += n; } free_page((unsigned long) page); return retval; } static ssize_t proc_file_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct inode *inode = file->f_dentry->d_inode; struct proc_dir_entry * dp; dp = PDE(inode); if (!dp->write_proc) return -EIO; /* FIXME: does this routine need ppos? probably... */ return dp->write_proc(file, buffer, count, dp->data); } static loff_t proc_file_lseek(struct file *file, loff_t offset, int orig) { loff_t retval = -EINVAL; switch (orig) { case 1: offset += file->f_pos; /* fallthrough */ case 0: if (offset < 0 || offset > MAX_NON_LFS) break; file->f_pos = retval = offset; } return retval; } static int proc_notify_change(struct dentry *dentry, struct iattr *iattr) { struct inode *inode = dentry->d_inode; struct proc_dir_entry *de = PDE(inode); int error; error = inode_change_ok(inode, iattr); if (error) goto out; error = inode_setattr(inode, iattr); if (error) goto out; de->uid = inode->i_uid; de->gid = inode->i_gid; de->mode = inode->i_mode; out: return error; } static int proc_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; struct proc_dir_entry *de = PROC_I(inode)->pde; if (de && de->nlink) inode->i_nlink = de->nlink; generic_fillattr(inode, stat); return 0; } static struct inode_operations proc_file_inode_operations = { .setattr = proc_notify_change, }; /* * This function parses a name such as "tty/driver/serial", and * returns the struct proc_dir_entry for "/proc/tty/driver", and * returns "serial" in residual. */ static int xlate_proc_name(const char *name, struct proc_dir_entry **ret, const char **residual) { const char *cp = name, *next; struct proc_dir_entry *de; int len; de = &proc_root; while (1) { next = strchr(cp, '/'); if (!next) break; len = next - cp; for (de = de->subdir; de ; de = de->next) { if (proc_match(len, cp, de)) break; } if (!de) return -ENOENT; cp += len + 1; } *residual = cp; *ret = de; return 0; } static DEFINE_IDR(proc_inum_idr); static DEFINE_SPINLOCK(proc_inum_lock); /* protects the above */ #define PROC_DYNAMIC_FIRST 0xF0000000UL /* * register the static proc_inum_idr lock with the simulator */ void __init proc_inum_idr_init(void){ idr_init_fast(&proc_inum_idr); } /* * Return an inode number between PROC_DYNAMIC_FIRST and * 0xffffffff, or zero on failure. */ static unsigned int get_inode_number(void) { int i, inum = 0; int error; retry: if (idr_pre_get(&proc_inum_idr, GFP_KERNEL) == 0) return 0; spin_lock(&proc_inum_lock); error = idr_get_new(&proc_inum_idr, NULL, &i); spin_unlock(&proc_inum_lock); if (error == -EAGAIN) goto retry; else if (error) return 0; inum = (i & MAX_ID_MASK) + PROC_DYNAMIC_FIRST; /* inum will never be more than 0xf0ffffff, so no check * for overflow. */ return inum; } static void release_inode_number(unsigned int inum) { int id = (inum - PROC_DYNAMIC_FIRST) | ~MAX_ID_MASK; spin_lock(&proc_inum_lock); idr_remove(&proc_inum_idr, id); spin_unlock(&proc_inum_lock); } static void *proc_follow_link(struct dentry *dentry, struct nameidata *nd) { nd_set_link(nd, PDE(dentry->d_inode)->data); return NULL; } static struct inode_operations proc_link_inode_operations = { .readlink = generic_readlink, .follow_link = proc_follow_link, }; /* * As some entries in /proc are volatile, we want to * get rid of unused dentries. This could be made * smarter: we could keep a "volatile" flag in the * inode to indicate which ones to keep. */ static int proc_delete_dentry(struct dentry * dentry) { return 1; } static struct dentry_operations proc_dentry_operations = { .d_delete = proc_delete_dentry, }; /* * Don't create negative dentries here, return -ENOENT by hand * instead. */ struct dentry *proc_lookup(struct inode * dir, struct dentry *dentry, struct nameidata *nd) { struct inode *inode = NULL; struct proc_dir_entry * de; int error = -ENOENT; lock_kernel(); de = PDE(dir); if (de) { for (de = de->subdir; de ; de = de->next) { if (de->namelen != dentry->d_name.len) continue; if (!memcmp(dentry->d_name.name, de->name, de->namelen)) { unsigned int ino = de->low_ino; error = -EINVAL; inode = proc_get_inode(dir->i_sb, ino, de); break; } } } unlock_kernel(); if (inode) { dentry->d_op = &proc_dentry_operations; d_add(dentry, inode); return NULL; } return ERR_PTR(error); } /* * This returns non-zero if at EOF, so that the /proc * root directory can use this and check if it should * continue with the <pid> entries.. * * Note that the VFS-layer doesn't care about the return * value of the readdir() call, as long as it's non-negative * for success.. */ int proc_readdir(struct file * filp, void * dirent, filldir_t filldir) { struct proc_dir_entry * de; unsigned int ino; int i; struct inode *inode = filp->f_dentry->d_inode; int ret = 0; lock_kernel(); ino = inode->i_ino; de = PDE(inode); if (!de) { ret = -EINVAL; goto out; } i = filp->f_pos; switch (i) { case 0: if (filldir(dirent, ".", 1, i, ino, DT_DIR) < 0) goto out; i++; filp->f_pos++; /* fall through */ case 1: if (filldir(dirent, "..", 2, i, parent_ino(filp->f_dentry), DT_DIR) < 0) goto out; i++; filp->f_pos++; /* fall through */ default: de = de->subdir; i -= 2; for (;;) { if (!de) { ret = 1; goto out; } if (!i) break; de = de->next; i--; } do { if (filldir(dirent, de->name, de->namelen, filp->f_pos, de->low_ino, de->mode >> 12) < 0) goto out; filp->f_pos++; de = de->next; } while (de); } ret = 1; out: unlock_kernel(); return ret; } /* * These are the generic /proc directory operations. They * use the in-memory "struct proc_dir_entry" tree to parse * the /proc directory. */ static struct file_operations proc_dir_operations = { .read = generic_read_dir, .readdir = proc_readdir, }; /* * proc directories can do almost nothing.. */ static struct inode_operations proc_dir_inode_operations = { .lookup = proc_lookup, .getattr = proc_getattr, .setattr = proc_notify_change, }; static int proc_register(struct proc_dir_entry * dir, struct proc_dir_entry * dp) { unsigned int i; i = get_inode_number(); if (i == 0) return -EAGAIN; dp->low_ino = i; dp->next = dir->subdir; dp->parent = dir; dir->subdir = dp; if (S_ISDIR(dp->mode)) { if (dp->proc_iops == NULL) { dp->proc_fops = &proc_dir_operations; dp->proc_iops = &proc_dir_inode_operations; } dir->nlink++; } else if (S_ISLNK(dp->mode)) { if (dp->proc_iops == NULL) dp->proc_iops = &proc_link_inode_operations; } else if (S_ISREG(dp->mode)) { if (dp->proc_fops == NULL) dp->proc_fops = &proc_file_operations; if (dp->proc_iops == NULL) dp->proc_iops = &proc_file_inode_operations; } return 0; } /* * Kill an inode that got unregistered.. */ static void proc_kill_inodes(struct proc_dir_entry *de) { struct list_head *p; struct super_block *sb = proc_mnt->mnt_sb; /* * Actually it's a partial revoke(). */ file_list_lock(); list_for_each(p, &sb->s_files) { struct file * filp = list_entry(p, struct file, f_u.fu_list); struct dentry * dentry = filp->f_dentry; struct inode * inode; struct file_operations *fops; if (dentry->d_op != &proc_dentry_operations) continue; inode = dentry->d_inode; if (PDE(inode) != de) continue; fops = filp->f_op; filp->f_op = NULL; fops_put(fops); } file_list_unlock(); } static struct proc_dir_entry *proc_create(struct proc_dir_entry **parent, const char *name, mode_t mode, nlink_t nlink) { struct proc_dir_entry *ent = NULL; const char *fn = name; int len; /* make sure name is valid */ if (!name || !strlen(name)) goto out; if (!(*parent) && xlate_proc_name(name, parent, &fn) != 0) goto out; /* At this point there must not be any '/' characters beyond *fn */ if (strchr(fn, '/')) goto out; len = strlen(fn); ent = kmalloc(sizeof(struct proc_dir_entry) + len + 1, GFP_KERNEL); if (!ent) goto out; memset(ent, 0, sizeof(struct proc_dir_entry)); memcpy(((char *) ent) + sizeof(struct proc_dir_entry), fn, len + 1); ent->name = ((char *) ent) + sizeof(*ent); ent->namelen = len; ent->mode = mode; ent->nlink = nlink; out: return ent; } struct proc_dir_entry *proc_symlink(const char *name, struct proc_dir_entry *parent, const char *dest) { struct proc_dir_entry *ent; ent = proc_create(&parent,name, (S_IFLNK | S_IRUGO | S_IWUGO | S_IXUGO),1); if (ent) { ent->data = kmalloc((ent->size=strlen(dest))+1, GFP_KERNEL); if (ent->data) { strcpy((char*)ent->data,dest); if (proc_register(parent, ent) < 0) { kfree(ent->data); kfree(ent); ent = NULL; } } else { kfree(ent); ent = NULL; } } return ent; } struct proc_dir_entry *proc_mkdir_mode(const char *name, mode_t mode, struct proc_dir_entry *parent) { struct proc_dir_entry *ent; ent = proc_create(&parent, name, S_IFDIR | mode, 2); if (ent) { ent->proc_fops = &proc_dir_operations; ent->proc_iops = &proc_dir_inode_operations; if (proc_register(parent, ent) < 0) { kfree(ent); ent = NULL; } } return ent; } struct proc_dir_entry *proc_mkdir(const char *name, struct proc_dir_entry *parent) { return proc_mkdir_mode(name, S_IRUGO | S_IXUGO, parent); } struct proc_dir_entry *create_proc_entry(const char *name, mode_t mode, struct proc_dir_entry *parent) { struct proc_dir_entry *ent; nlink_t nlink; if (S_ISDIR(mode)) { if ((mode & S_IALLUGO) == 0) mode |= S_IRUGO | S_IXUGO; nlink = 2; } else { if ((mode & S_IFMT) == 0) mode |= S_IFREG; if ((mode & S_IALLUGO) == 0) mode |= S_IRUGO; nlink = 1; } ent = proc_create(&parent,name,mode,nlink); if (ent) { if (S_ISDIR(mode)) { ent->proc_fops = &proc_dir_operations; ent->proc_iops = &proc_dir_inode_operations; } if (proc_register(parent, ent) < 0) { kfree(ent); ent = NULL; } } return ent; } void free_proc_entry(struct proc_dir_entry *de) { unsigned int ino = de->low_ino; if (ino < PROC_DYNAMIC_FIRST) return; release_inode_number(ino); if (S_ISLNK(de->mode) && de->data) kfree(de->data); kfree(de); } /* * Remove a /proc entry and free it if it's not currently in use. * If it is in use, we set the 'deleted' flag. */ void remove_proc_entry(const char *name, struct proc_dir_entry *parent) { struct proc_dir_entry **p; struct proc_dir_entry *de; const char *fn = name; int len; if (!parent && xlate_proc_name(name, &parent, &fn) != 0) goto out; len = strlen(fn); for (p = &parent->subdir; *p; p=&(*p)->next ) { if (!proc_match(len, fn, *p)) continue; de = *p; *p = de->next; de->next = NULL; if (S_ISDIR(de->mode)) parent->nlink--; proc_kill_inodes(de); de->nlink = 0; WARN_ON(de->subdir); if (!atomic_read(&de->count)) free_proc_entry(de); else { de->deleted = 1; printk("remove_proc_entry: %s/%s busy, count=%d\n", parent->name, de->name, atomic_read(&de->count)); } break; } out: return; }
680909.c
/**************************************************************************** * * Copyright 2022 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License\n"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ #include <tinyara/config.h> #include <stdio.h> #include <errno.h> #include <sys/socket.h> #include <wifi_manager/wifi_manager.h> #include <stress_tool/st_perf.h> #include "connect_test.h" #include "connect_test_server.h" #include "connect_test_log.h" #include "connect_test_data.h" #include "connect_test_utils.h" #define TAG "[CT_SERVER]" static bool is_network = false; static bool is_ap_on = false; bool g_tcp_server_recvd_data; bool g_tcp_server_sentack_data; bool g_tcp_server_sent_data; bool g_tcp_server_recvdack_data; bool g_tls_server_recvd_data; bool g_tls_server_sent_data; static struct ct_options* opt = NULL; static char *g_WM_AP_SSID = ""; static char *g_WM_AP_PASSWORD = ""; static wifi_manager_ap_auth_type_e g_WM_AP_AUTH = WIFI_MANAGER_AUTH_WPA2_PSK; static wifi_manager_ap_crypto_type_e g_WM_AP_CRYPTO = WIFI_MANAGER_CRYPTO_AES; static char *g_WM_SOFTAP_SSID = ""; static char *g_WM_SOFTAP_PASSWORD = ""; static int g_WM_SOFTAP_CHANNEL = 1; static uint32_t g_WM_REPEAT_COUNT = 300; static uint8_t g_WM_IS_DTLS = 0; static uint32_t g_WM_DTLS_DATA_SIZE = 64; static uint8_t g_WM_IS_TLS = 0; static uint32_t g_WM_TLS_DATA_SIZE = 64; static char *g_WM_HOSTNAME_FILE = NULL; static struct ct_queue *g_ct_queue = NULL; static char g_ipv4_buf[18] = { '\0', }; static char g_broadcast_message[30] = { '\0', }; char g_recv_mac_buf_server[MAC_BUF_SIZE] = { '\0', }; char g_mac_buf_server[MAC_BUF_SIZE] = { '\0', }; volatile bool g_broadcast_flag = -1; /* * callbacks */ static void wm_cb_sta_connected(wifi_manager_cb_msg_s msg, void *arg); static void wm_cb_sta_disconnected(wifi_manager_cb_msg_s msg, void *arg); static void wm_cb_softap_sta_join(wifi_manager_cb_msg_s msg, void *arg); static void wm_cb_softap_sta_leave(wifi_manager_cb_msg_s msg, void *arg); static void wm_cb_scan_done(wifi_manager_cb_msg_s msg, void *arg); static wifi_manager_cb_s g_wifi_callbacks = { wm_cb_sta_connected, wm_cb_sta_disconnected, wm_cb_softap_sta_join, wm_cb_softap_sta_leave, wm_cb_scan_done, }; void wm_cb_sta_connected(wifi_manager_cb_msg_s msg, void *arg) { CT_LOG(TAG, "--> res(%d)", msg.res); CT_LOG(TAG, "bssid %02x:%02x:%02x:%02x:%02x:%02x", msg.bssid[0], msg.bssid[1], msg.bssid[2], msg.bssid[3], msg.bssid[4], msg.bssid[5]); int conn = 0; if (WIFI_MANAGER_SUCCESS == msg.res) { conn = CT_CONN_SUCCESS; is_network = true; } else { conn = CT_CONN_FAIL; is_network = false; } CT_TEST_SIGNAL(conn, g_ct_queue); } void wm_cb_sta_disconnected(wifi_manager_cb_msg_s msg, void *arg) { CT_LOG(TAG, "--> res(%d) reason %d", msg.res, msg.reason); is_network = false; } void wm_cb_softap_sta_join(wifi_manager_cb_msg_s msg, void *arg) { CT_LOG(TAG, "--> res(%d)", msg.res); CT_LOG(TAG, "bssid %02x:%02x:%02x:%02x:%02x:%02x", msg.bssid[0], msg.bssid[1], msg.bssid[2], msg.bssid[3], msg.bssid[4], msg.bssid[5]); CT_TEST_SIGNAL(CT_CONN_SUCCESS, g_ct_queue); } void wm_cb_softap_sta_leave(wifi_manager_cb_msg_s msg, void *arg) { CT_LOG(TAG, "--> res(%d) reason %d", msg.res, msg.reason); } void wm_cb_scan_done(wifi_manager_cb_msg_s msg, void *arg) { CT_LOG(TAG, "--> res(%d)", msg.res); if (msg.res != WIFI_MANAGER_SUCCESS || msg.scanlist == NULL) { CT_TEST_SIGNAL(CT_CONN_FAIL, g_ct_queue); return; } ct_print_scanlist(msg.scanlist, g_WM_AP_SSID, &is_ap_on); CT_TEST_SIGNAL(CT_CONN_SUCCESS, g_ct_queue); } static void broadcast_data(void) { CT_LOG(TAG, "ENTRY"); struct sockaddr_in dest_addr; int sock; unsigned int retry = 10; retry_connection: if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { CT_LOGE(TAG, "Socket creation failed, error value is : %s-%d", strerror(errno), errno); return; } int broadcast = 1; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0) { CT_LOGE(TAG, "Error in setting Broadcast option, error description-value is : %s-%d", strerror(errno), errno); close(sock); return; } struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (struct timeval *)&tv, sizeof(struct timeval)) < 0) { CT_LOGE(TAG, "Set time out failed for sendto"); close(sock); return; } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(PORT); dest_addr.sin_addr.s_addr = INADDR_BROADCAST; int conn = 0; while (g_broadcast_flag && retry--) { int res = sendto(sock, g_broadcast_message, sizeof(g_broadcast_message), 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); if (res < 0) { if (!is_network) { CT_LOG(TAG, "connection_got_broken"); close(sock); CT_TEST_WAIT(conn, g_ct_queue); CT_LOG(TAG, "connection_resumed"); goto retry_connection; } if (errno == EWOULDBLOCK) { CT_LOGE(TAG, "send failed, error description-value is : %s-%d, try again", strerror(errno), errno); continue; } else { CT_LOGE(TAG, "send failed, error description-value is : %s-%d", strerror(errno), errno); close(sock); return; } } else { CT_LOG(TAG, "send message success"); CT_LOG(TAG, "adding 1 sec sleep which will give enough time to client to receive broadcast."); sleep(1); } } if (0 == retry) { CT_LOGE(TAG, "broadcast IP send failed even after %d retry", retry); } close(sock); } static int _run_procedure() { struct timeval start, end; long sum = 0; int conn = 0; int res; is_network = false; is_ap_on = false; g_tcp_server_recvd_data = false; g_tcp_server_sentack_data = false; g_tcp_server_sent_data = false; g_tcp_server_recvdack_data = false; g_tls_server_recvd_data = false; g_tls_server_sent_data = false; wifi_manager_result_e wres = WIFI_MANAGER_SUCCESS; /* Initialise Wifi */ CT_LOG(TAG, "init wi-fi"); wres = wifi_manager_init(&g_wifi_callbacks); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to init %d", wres); return -1; } /* Start softAP */ CT_LOG(TAG, "start softAP"); wifi_manager_softap_config_s softap_config; SET_START_TIME(Change to SoftAP mode); wm_get_softapinfo(&softap_config, g_WM_SOFTAP_SSID, g_WM_SOFTAP_PASSWORD, g_WM_SOFTAP_CHANNEL); wres = wifi_manager_set_mode(SOFTAP_MODE, &softap_config); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to start softap %d", wres); return -1; } CALCULATE_ELAPSED_TIME(Change to SoftAP mode, sum); /* wait join event */ CT_LOG(TAG, "wait join event"); CT_TEST_WAIT(conn, g_ct_queue); /* scan in softAP mode */ CT_LOG(TAG, "scan in softAP mode"); SET_START_TIME(Scan in SoftAP mode); wres = wifi_manager_scan_ap(NULL); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to scan %d", wres); return -1; } /* wait scan event */ CT_LOG(TAG, "wait scan done event"); CT_TEST_WAIT(conn, g_ct_queue); CALCULATE_ELAPSED_TIME(Scan in SoftAP mode, sum); /* Prepare MAC for transfer during UDP/DTLS */ res = get_device_mac(g_mac_buf_server, MAC_BUF_SIZE); if (res != 0) { CT_LOGE(TAG, "get_device_mac return %d", res); return -1; } /* Data transfer using UDP or DTLS */ if (g_WM_IS_DTLS) { _dtls_server(g_WM_DTLS_DATA_SIZE, &sum); } else { _udp_server(g_WM_DTLS_DATA_SIZE, &sum); } /* set STA */ CT_LOG(TAG, "start STA mode"); SET_START_TIME(Change to Station Mode); wres = wifi_manager_set_mode(STA_MODE, NULL); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "start STA fail %d", wres); return -1; } CALCULATE_ELAPSED_TIME(Change to STA mode, sum); /* scan in STA mode */ CT_LOG(TAG, "scan in STA mode"); SET_START_TIME(Scan in STA mode); wres = wifi_manager_scan_ap(NULL); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to scan %d", wres); return -1; } /* wait scan event */ CT_LOG(TAG, "wait scan done event in STA mode"); CT_TEST_WAIT(conn, g_ct_queue); CALCULATE_ELAPSED_TIME(Scan in STA mode, sum); // Scan till AP gets ON is_ap_on unsigned int retry_ap_scan = 30; while (!is_ap_on && retry_ap_scan--) { wifi_manager_result_e wres = wifi_manager_scan_ap(NULL); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to scan %d", wres); sleep(2); continue; } CT_TEST_WAIT(conn, g_ct_queue); // Wait scan done event sleep(2); } if (0 == retry_ap_scan) { CT_LOGE(TAG, "ap_scan failed even afer %d retry or passed ap does not exit", retry_ap_scan); return -1; } /* connect to AP */ wifi_manager_ap_config_s apconfig; wm_get_apinfo(&apconfig, g_WM_AP_SSID, g_WM_AP_PASSWORD, g_WM_AP_AUTH, g_WM_AP_CRYPTO); unsigned int retry_ap_connect = 30; while (!is_network && retry_ap_connect--) { wres = connect_AP(apconfig, g_ct_queue, 100000); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "connect_AP return %d", wres); sleep(2); continue; } } if (0 == retry_ap_connect) { CT_LOGE(TAG, "ap_connect failed even after %d retry", retry_ap_connect); return -1; } /* gethostname service */ dns_service(g_WM_HOSTNAME_FILE); /* Prepare broadcast data and broadcast it */ res = get_device_ip(g_ipv4_buf, IP_BUF_SIZE); if (res != 0) { CT_LOGE(TAG, "get_device_ip return %d", res); return -1; } strncpy(g_broadcast_message, (const char *)g_mac_buf_server, strlen((const char *)g_mac_buf_server)); strcat(g_broadcast_message, " "); strncat(g_broadcast_message, (const char *)g_ipv4_buf, strlen((const char *)g_ipv4_buf)); g_broadcast_flag = true; pthread_t tid; pthread_create(&tid, NULL, (void*)&broadcast_data, NULL); /* Data transfer using TCP or TLS */ CT_LOG(TAG, "Data_transfer_using_TCP_or_TLS"); while (true) { res = 0; if (g_WM_IS_TLS) { res = _tls_server(g_WM_TLS_DATA_SIZE, &sum); } else { res = _tcp_server(g_WM_TLS_DATA_SIZE, &sum); } if (res < 0) { if (!is_network) { CT_LOG(TAG, "connection_got_broken"); unsigned int retry_ap_connect = 10; while (true && retry_ap_connect--) { res = connect_AP(apconfig, g_ct_queue, 10000000); if (res != 0) { CT_LOGE(TAG, "connect_ap_failed_return %d", res); sleep(2); continue; } if (!is_network) { sleep(2); // Wait for 2 secs for station to get connected } if (is_network) { CT_LOG(TAG, "connection_resumed_station_connected"); break; } } if (0 == retry_ap_connect) { CT_LOGE(TAG, "ap_connect failed even after %d retry", retry_ap_connect); return -1; } } else { CT_LOG(TAG, "Connection is Ok but data transfer failed"); break; } } else { CT_LOG(TAG, "Data transfer success"); break; } } /* Deinitialise Wifi */ CT_LOG(TAG, "deinit wi-fi"); wres = wifi_manager_deinit(); if (wres != WIFI_MANAGER_SUCCESS) { CT_LOGE(TAG, "fail to deinit %d", wres); return -1; } CT_LOG(TAG, "Total time taken(for 7 operations) is %ld", sum); return 0; } TEST_F(easysetup_tc) { ST_START_TEST; ST_EXPECT_EQ(0, _run_procedure()); ST_END_TEST; } void connect_test_server(void *arg) { opt = (struct ct_options*)arg; g_WM_AP_SSID = opt->ssid; g_WM_AP_PASSWORD = opt->password; g_WM_AP_AUTH = opt->auth_type; g_WM_AP_CRYPTO = opt->crypto_type; g_WM_SOFTAP_SSID = opt->softap_ssid; g_WM_SOFTAP_PASSWORD = opt->softap_password; g_WM_SOFTAP_CHANNEL = opt->softap_channel; g_WM_REPEAT_COUNT = opt->repeat; g_WM_IS_DTLS = opt->is_dtls; g_WM_DTLS_DATA_SIZE = opt->dtls_data_size * 1024; g_WM_IS_TLS = opt->is_tls; g_WM_TLS_DATA_SIZE = opt->tls_data_size * 1024; if (opt->path) { g_WM_HOSTNAME_FILE = opt->path; } CT_LOG(TAG, "init sem"); g_ct_queue = ct_create_queue(); if (!g_ct_queue) { CT_LOGE(TAG, "create queue fail"); return; } ST_SET_PACK(wifi); ST_SET_SMOKE1(wifi, g_WM_REPEAT_COUNT, 60000000, "easysetup TC", easysetup_tc); ST_RUN_TEST(wifi); ST_RESULT_TEST(wifi); CT_LOG(TAG, "deinit sem"); ct_destroy_queue(g_ct_queue); }
120640.c
#include "str.h" bool whitespace(char c) { return c == ' ' || c == '\t' || c == '\n'; } bool allwhitespace(const char *s) { int n = strlen(s); for (int i = 0; i < n; ++i) { if (!whitespace(s[i])) return false; } return true; } bool str_contains(char *s, char c) { int n = strlen(s); for (int i = 0; i < n; ++i) { if (s[i] == c) return true; } return false; } int str_count(const char *s, char c) { int cnt, n; cnt = 0; n = strlen(s); for (int i = 0; i < n; ++i) { if (s[i] == c) ++cnt; } return cnt; } char *str_escape_nl(const char *s) { // Read, write, length, and number of newlines. int r, w, n, nnl; char *t; n = strlen(s); nnl = str_count(s, '\n'); t = malloc((n+1+nnl)*sizeof(char)); w = 0; for (r = 0; r < n; ++r, ++w) { if (s[r] == '\n') { t[w++] = '\\'; t[w] = 'n'; } else t[w] = s[r]; } t[w] = '\0'; return t; } char *str_rm_strconst_tab_nl(char *s) { int r, w, n; bool instr; n = strlen(s); instr = false; w = 0; for (r = 0; r < n; ++r) { if (r > 0 && s[r] == '"' && s[r-1] != '\\') instr = !instr; if (instr && s[r] != '\t' && s[r] != '\n') { s[w++] = s[r]; } else if (!instr) s[w++] = s[r]; } s = realloc(s, w+1); s[w] = '\0'; return s; } /** * str_rm - Remove all characters in the pattern from the string * * Return the new length of the string. Doesn't add a null term char. */ int str_rm(char *s, char *pat) { int r, w, n, m, j; bool fnd; // Found. n = strlen(s); m = strlen(pat); fnd = false; w = 0; for (r = 0; r < n; ++r) { for (j = 0; j < m; ++j) { if (s[r] == pat[j]) { fnd = true; break; } } if (!fnd) s[w++] = s[r]; fnd = false; } return w; } char *str_rm_tab_nl(char *s) { int n = str_rm(s, "\t\n"); s[n] = '\0'; return realloc(s, n+1); } char *strnewcpy(const char *src) { char *dest; int n = strlen(src); // Add 1 for null term. dest = malloc((n+1)*sizeof(char)); strncpy(dest, src, n+1); return dest; }
701678.c
// SPDX-License-Identifier: GPL-2.0 /* * nop tracer * * Copyright (C) 2008 Steven Noonan <[email protected]> * */ #include <linux/module.h> #include <linux/ftrace.h> #include "trace.h" /* Our two options */ enum { TRACE_NOP_OPT_ACCEPT = 0x1, TRACE_NOP_OPT_REFUSE = 0x2 }; /* Options for the tracer (see trace_options file) */ static struct tracer_opt nop_opts[] = { /* Option that will be accepted by set_flag callback */ { TRACER_OPT(test_nop_accept, TRACE_NOP_OPT_ACCEPT) }, /* Option that will be refused by set_flag callback */ { TRACER_OPT(test_nop_refuse, TRACE_NOP_OPT_REFUSE) }, { } /* Always set a last empty entry */ }; static struct tracer_flags nop_flags = { /* You can check your flags value here when you want. */ .val = 0, /* By default: all flags disabled */ .opts = nop_opts }; static struct trace_array *ctx_trace; static void start_nop_trace(struct trace_array *tr) { /* Nothing to do! */ } static void stop_nop_trace(struct trace_array *tr) { /* Nothing to do! */ } static int nop_trace_init(struct trace_array *tr) { ctx_trace = tr; start_nop_trace(tr); return 0; } static void nop_trace_reset(struct trace_array *tr) { stop_nop_trace(tr); } /* It only serves as a signal handler and a callback to * accept or refuse the setting of a flag. * If you don't implement it, then the flag setting will be * automatically accepted. */ static int nop_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set) { /* * Note that you don't need to update nop_flags.val yourself. * The tracing Api will do it automatically if you return 0 */ if (bit == TRACE_NOP_OPT_ACCEPT) { printk(KERN_DEBUG "nop_test_accept flag set to %d: we accept." " Now cat trace_options to see the result\n", set); return 0; } if (bit == TRACE_NOP_OPT_REFUSE) { printk(KERN_DEBUG "nop_test_refuse flag set to %d: we refuse." " Now cat trace_options to see the result\n", set); return -EINVAL; } return 0; } struct tracer nop_trace __read_mostly = { .name = "nop", .init = nop_trace_init, .reset = nop_trace_reset, #ifdef CONFIG_FTRACE_SELFTEST .selftest = trace_selftest_startup_nop, #endif .flags = &nop_flags, .set_flag = nop_set_flag, .allow_instances = true, };
269467.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "config.h" #include "encode-png.h" #include "guacamole/error.h" #include "guacamole/protocol.h" #include "guacamole/stream.h" #include "palette.h" #include <png.h> #include <cairo/cairo.h> #ifdef HAVE_PNGSTRUCT_H #include <pngstruct.h> #endif #include <inttypes.h> #include <setjmp.h> #include <stdint.h> #include <stdlib.h> #include <string.h> /** * Data describing the current write state of PNG data. */ typedef struct guac_png_write_state { /** * The socket over which all PNG blobs will be written. */ guac_socket* socket; /** * The Guacamole stream to associate with each PNG blob. */ guac_stream* stream; /** * Buffer of pending PNG data. */ char buffer[GUAC_PROTOCOL_BLOB_MAX_LENGTH]; /** * The number of bytes currently stored in the buffer. */ int buffer_size; } guac_png_write_state; /** * Writes the contents of the PNG write state as a blob to its associated * socket. * * @param write_state * The write state to flush. */ static void guac_png_flush_data(guac_png_write_state* write_state) { /* Send blob */ guac_protocol_send_blob(write_state->socket, write_state->stream, write_state->buffer, write_state->buffer_size); /* Clear buffer */ write_state->buffer_size = 0; } /** * Appends the given PNG data to the internal buffer of the given write state, * automatically flushing the write state as necessary. * socket. * * @param write_state * The write state to append the given data to. * * @param data * The PNG data to append. * * @param length * The size of the given PNG data, in bytes. */ static void guac_png_write_data(guac_png_write_state* write_state, const void* data, int length) { const unsigned char* current = data; /* Append all data given */ while (length > 0) { /* Calculate space remaining */ int remaining = sizeof(write_state->buffer) - write_state->buffer_size; /* If no space remains, flush buffer to make room */ if (remaining == 0) { guac_png_flush_data(write_state); remaining = sizeof(write_state->buffer); } /* Calculate size of next block of data to append */ int block_size = remaining; if (block_size > length) block_size = length; /* Append block */ memcpy(write_state->buffer + write_state->buffer_size, current, block_size); /* Next block */ current += block_size; write_state->buffer_size += block_size; length -= block_size; } } /** * Writes the given buffer of PNG data to the buffer of the given write state, * flushing that buffer to blob instructions if necessary. This handler is * called by Cairo when writing PNG data via * cairo_surface_write_to_png_stream(). * * @param closure * Pointer to arbitrary data passed to cairo_surface_write_to_png_stream(). * In the case of this handler, this data will be the guac_png_write_state. * * @param data * The buffer of PNG data to write. * * @param length * The size of the given buffer, in bytes. * * @return * A Cairo status code indicating whether the write operation succeeded. * In the case of this handler, this will always be CAIRO_STATUS_SUCCESS. */ static cairo_status_t guac_png_cairo_write_handler(void* closure, const unsigned char* data, unsigned int length) { guac_png_write_state* write_state = (guac_png_write_state*) closure; /* Append data to buffer, writing as necessary */ guac_png_write_data(write_state, data, length); return CAIRO_STATUS_SUCCESS; } /** * Implementation of guac_png_write() which uses Cairo's own PNG encoder to * write PNG data, rather than using libpng directly. * * @param socket * The socket to send PNG blobs over. * * @param stream * The stream to associate with each blob. * * @param surface * The Cairo surface to write to the given stream and socket as PNG blobs. * * @return * Zero if the encoding operation is successful, non-zero otherwise. */ static int guac_png_cairo_write(guac_socket* socket, guac_stream* stream, cairo_surface_t* surface) { guac_png_write_state write_state; /* Init write state */ write_state.socket = socket; write_state.stream = stream; write_state.buffer_size = 0; /* Write surface as PNG */ if (cairo_surface_write_to_png_stream(surface, guac_png_cairo_write_handler, &write_state) != CAIRO_STATUS_SUCCESS) { guac_error = GUAC_STATUS_INTERNAL_ERROR; guac_error_message = "Cairo PNG backend failed"; return -1; } /* Flush remaining PNG data */ guac_png_flush_data(&write_state); return 0; } /** * Writes the given buffer of PNG data to the buffer of the given write state, * flushing that buffer to blob instructions if necessary. This handler is * called by libpng when writing PNG data via png_write_png(). * * @param png * The PNG compression state structure associated with the write operation. * The pointer to arbitrary data will have been set to the * guac_png_write_state by png_set_write_fn(), and will be accessible via * png->io_ptr or png_get_io_ptr(png), depending on the version of libpng. * * @param data * The buffer of PNG data to write. * * @param length * The size of the given buffer, in bytes. */ static void guac_png_write_handler(png_structp png, png_bytep data, png_size_t length) { /* Get png buffer structure */ guac_png_write_state* write_state; #ifdef HAVE_PNG_GET_IO_PTR write_state = (guac_png_write_state*) png_get_io_ptr(png); #else write_state = (guac_png_write_state*) png->io_ptr; #endif /* Append data to buffer, writing as necessary */ guac_png_write_data(write_state, data, length); } /** * Flushes any PNG data within the buffer of the given write state as a blob * instruction. If no data is within the buffer, this function has no effect. * This handler is called by libpng when it has finished writing PNG data via * png_write_png(). * * @param png * The PNG compression state structure associated with the write operation. * The pointer to arbitrary data will have been set to the * guac_png_write_state by png_set_write_fn(), and will be accessible via * png->io_ptr or png_get_io_ptr(png), depending on the version of libpng. */ static void guac_png_flush_handler(png_structp png) { /* Get png buffer structure */ guac_png_write_state* write_state; #ifdef HAVE_PNG_GET_IO_PTR write_state = (guac_png_write_state*) png_get_io_ptr(png); #else write_state = (guac_png_write_state*) png->io_ptr; #endif /* Flush buffer */ guac_png_flush_data(write_state); } int guac_png_write(guac_socket* socket, guac_stream* stream, cairo_surface_t* surface) { png_structp png; png_infop png_info; png_byte** png_rows; int bpp; int x, y; guac_png_write_state write_state; /* Get image surface properties and data */ cairo_format_t format = cairo_image_surface_get_format(surface); int width = cairo_image_surface_get_width(surface); int height = cairo_image_surface_get_height(surface); int stride = cairo_image_surface_get_stride(surface); unsigned char* data = cairo_image_surface_get_data(surface); /* If not RGB24, use Cairo PNG writer */ if (format != CAIRO_FORMAT_RGB24 || data == NULL) return guac_png_cairo_write(socket, stream, surface); /* Flush pending operations to surface */ cairo_surface_flush(surface); /* Attempt to build palette */ guac_palette* palette = guac_palette_alloc(surface); /* If not possible, resort to Cairo PNG writer */ if (palette == NULL) return guac_png_cairo_write(socket, stream, surface); /* Calculate BPP from palette size */ if (palette->size <= 2) bpp = 1; else if (palette->size <= 4) bpp = 2; else if (palette->size <= 16) bpp = 4; else bpp = 8; /* Set up PNG writer */ png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png) { guac_palette_free(palette); guac_error = GUAC_STATUS_INTERNAL_ERROR; guac_error_message = "libpng failed to create write structure"; return -1; } png_info = png_create_info_struct(png); if (!png_info) { png_destroy_write_struct(&png, NULL); guac_palette_free(palette); guac_error = GUAC_STATUS_INTERNAL_ERROR; guac_error_message = "libpng failed to create info structure"; return -1; } /* Set error handler */ if (setjmp(png_jmpbuf(png))) { png_destroy_write_struct(&png, &png_info); guac_palette_free(palette); guac_error = GUAC_STATUS_IO_ERROR; guac_error_message = "libpng output error"; return -1; } /* Init write state */ write_state.socket = socket; write_state.stream = stream; write_state.buffer_size = 0; /* Set up writer */ png_set_write_fn(png, &write_state, guac_png_write_handler, guac_png_flush_handler); /* Copy data from surface into PNG data */ png_rows = (png_byte**) malloc(sizeof(png_byte*) * height); for (y=0; y<height; y++) { /* Allocate new PNG row */ png_byte* row = (png_byte*) malloc(sizeof(png_byte) * width); png_rows[y] = row; /* Copy data from surface into current row */ for (x=0; x<width; x++) { /* Get pixel color */ int color = ((uint32_t*) data)[x] & 0xFFFFFF; /* Set index in row */ row[x] = guac_palette_find(palette, color); } /* Advance to next data row */ data += stride; } /* Write image info */ png_set_IHDR( png, png_info, width, height, bpp, PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); /* Write palette */ png_set_PLTE(png, png_info, palette->colors, palette->size); /* Write image */ png_set_rows(png, png_info, png_rows); png_write_png(png, png_info, PNG_TRANSFORM_PACKING, NULL); /* Finish write */ png_destroy_write_struct(&png, &png_info); /* Free palette */ guac_palette_free(palette); /* Free PNG data */ for (y=0; y<height; y++) free(png_rows[y]); free(png_rows); /* Ensure all data is written */ guac_png_flush_data(&write_state); return 0; }
490713.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tree_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vtarasiu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:47:38 by vtarasiu #+# #+# */ /* Updated: 2019/04/25 16:26:42 by vtarasiu ### ########.fr */ /* */ /* ************************************************************************** */ #include "shell_script.h" #include "shell_script_parser.h" t_bresult *list_build(const t_state *state, struct s_result *last_build) { t_node *node; t_bresult *bresult; if (state->rule != &g_list_dash) return (last_build->ast); bresult = ft_memalloc(sizeof(t_bresult)); if (last_build->backup_ast == NULL || last_build->ast->root->left != NULL) { node = ast_new_node(NULL, NODE_SEPARATOR); node->right = last_build->ast->root; if (last_build->backup_ast != NULL) node->left = last_build->backup_ast->root; bresult->root = node; } else if (last_build->ast->root->node_type != NODE_SEPARATOR && last_build->ast->root->left != NULL) return (bresult); else { last_build->ast->root->left = last_build->backup_ast->root; bresult->root = last_build->ast->root; } ft_memdel((void **)&(last_build->ast)); ft_memdel((void **)&(last_build->backup_ast)); return (bresult); }
418817.c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Mike Jackson <[email protected]> | | Steven Lawrance <[email protected]> | | Harrie Hazewinkel <[email protected]> | | Johann Hanne <[email protected]> | | Boris Lytockin <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "main/php_network.h" #include "ext/standard/info.h" #include "php_snmp.h" #include "zend_exceptions.h" #include "ext/spl/spl_exceptions.h" #if HAVE_SNMP #include <sys/types.h> #include <errno.h> #ifdef PHP_WIN32 #include <winsock2.h> #include <process.h> #include "win32/time.h" #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifndef __P #ifdef __GNUC__ #define __P(args) args #else #define __P(args) () #endif #endif #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> /* For net-snmp prior to 5.4 */ #ifndef HAVE_SHUTDOWN_SNMP_LOGGING extern netsnmp_log_handler *logh_head; #define shutdown_snmp_logging() \ { \ snmp_disable_log(); \ while(NULL != logh_head) \ netsnmp_remove_loghandler( logh_head ); \ } #endif #define SNMP_VALUE_LIBRARY (0 << 0) #define SNMP_VALUE_PLAIN (1 << 0) #define SNMP_VALUE_OBJECT (1 << 1) typedef struct snmp_session php_snmp_session; #define PHP_SNMP_SESSION_RES_NAME "SNMP session" #define PHP_SNMP_ADD_PROPERTIES(a, b) \ { \ int i = 0; \ while (b[i].name != NULL) { \ php_snmp_add_property((a), (b)[i].name, (b)[i].name_length, \ (php_snmp_read_t)(b)[i].read_func, (php_snmp_write_t)(b)[i].write_func); \ i++; \ } \ } #define PHP_SNMP_ERRNO_NOERROR 0 #define PHP_SNMP_ERRNO_GENERIC (1 << 1) #define PHP_SNMP_ERRNO_TIMEOUT (1 << 2) #define PHP_SNMP_ERRNO_ERROR_IN_REPLY (1 << 3) #define PHP_SNMP_ERRNO_OID_NOT_INCREASING (1 << 4) #define PHP_SNMP_ERRNO_OID_PARSING_ERROR (1 << 5) #define PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES (1 << 6) #define PHP_SNMP_ERRNO_ANY ( \ PHP_SNMP_ERRNO_GENERIC | \ PHP_SNMP_ERRNO_TIMEOUT | \ PHP_SNMP_ERRNO_ERROR_IN_REPLY | \ PHP_SNMP_ERRNO_OID_NOT_INCREASING | \ PHP_SNMP_ERRNO_OID_PARSING_ERROR | \ PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES | \ PHP_SNMP_ERRNO_NOERROR \ ) ZEND_DECLARE_MODULE_GLOBALS(snmp) static PHP_GINIT_FUNCTION(snmp); /* constant - can be shared among threads */ static oid objid_mib[] = {1, 3, 6, 1, 2, 1}; static int le_snmp_session; /* Handlers */ static zend_object_handlers php_snmp_object_handlers; /* Class entries */ zend_class_entry *php_snmp_ce; zend_class_entry *php_snmp_exception_ce; /* Class object properties */ static HashTable php_snmp_properties; /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpget, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpgetnext, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpwalk, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmprealwalk, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpset, 0, 0, 5) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_get_quick_print, 0, 0, 1) ZEND_ARG_INFO(0, d) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_quick_print, 0, 0, 1) ZEND_ARG_INFO(0, quick_print) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_enum_print, 0, 0, 1) ZEND_ARG_INFO(0, enum_print) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_oid_output_format, 0, 0, 1) ZEND_ARG_INFO(0, oid_format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_get, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_getnext, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_walk, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_real_walk, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_set, 0, 0, 5) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_get, 0, 0, 8) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, sec_name) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_getnext, 0, 0, 8) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, sec_name) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_walk, 0, 0, 8) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, sec_name) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_real_walk, 0, 0, 8) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, sec_name) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_set, 0, 0, 10) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, sec_name) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_valueretrieval, 0, 0, 1) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_snmp_get_valueretrieval, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_read_mib, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() /* OO arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_create, 0, 0, 3) ZEND_ARG_INFO(0, version) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, community) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, retries) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_snmp_void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_setSecurity, 0, 0, 8) ZEND_ARG_INFO(0, sec_level) ZEND_ARG_INFO(0, auth_protocol) ZEND_ARG_INFO(0, auth_passphrase) ZEND_ARG_INFO(0, priv_protocol) ZEND_ARG_INFO(0, priv_passphrase) ZEND_ARG_INFO(0, contextName) ZEND_ARG_INFO(0, contextEngineID) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_get, 0, 0, 1) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, use_orignames) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_walk, 0, 0, 4) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, suffix_keys) ZEND_ARG_INFO(0, max_repetitions) ZEND_ARG_INFO(0, non_repeaters) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set, 0, 0, 3) ZEND_ARG_INFO(0, object_id) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* }}} */ struct objid_query { int count; int offset; int step; zend_long non_repeaters; zend_long max_repetitions; int valueretrieval; int array_output; int oid_increasing_check; snmpobjarg *vars; }; /* {{{ snmp_functions[] */ static const zend_function_entry snmp_functions[] = { PHP_FE(snmpget, arginfo_snmpget) PHP_FE(snmpgetnext, arginfo_snmpgetnext) PHP_FE(snmpwalk, arginfo_snmpwalk) PHP_FE(snmprealwalk, arginfo_snmprealwalk) PHP_FALIAS(snmpwalkoid, snmprealwalk, arginfo_snmprealwalk) PHP_FE(snmpset, arginfo_snmpset) PHP_FE(snmp_get_quick_print, arginfo_snmp_get_quick_print) PHP_FE(snmp_set_quick_print, arginfo_snmp_set_quick_print) PHP_FE(snmp_set_enum_print, arginfo_snmp_set_enum_print) PHP_FE(snmp_set_oid_output_format, arginfo_snmp_set_oid_output_format) PHP_FALIAS(snmp_set_oid_numeric_print, snmp_set_oid_output_format, arginfo_snmp_set_oid_output_format) PHP_FE(snmp2_get, arginfo_snmp2_get) PHP_FE(snmp2_getnext, arginfo_snmp2_getnext) PHP_FE(snmp2_walk, arginfo_snmp2_walk) PHP_FE(snmp2_real_walk, arginfo_snmp2_real_walk) PHP_FE(snmp2_set, arginfo_snmp2_set) PHP_FE(snmp3_get, arginfo_snmp3_get) PHP_FE(snmp3_getnext, arginfo_snmp3_getnext) PHP_FE(snmp3_walk, arginfo_snmp3_walk) PHP_FE(snmp3_real_walk, arginfo_snmp3_real_walk) PHP_FE(snmp3_set, arginfo_snmp3_set) PHP_FE(snmp_set_valueretrieval, arginfo_snmp_set_valueretrieval) PHP_FE(snmp_get_valueretrieval, arginfo_snmp_get_valueretrieval) PHP_FE(snmp_read_mib, arginfo_snmp_read_mib) PHP_FE_END }; /* }}} */ /* query an agent with GET method */ #define SNMP_CMD_GET (1<<0) /* query an agent with GETNEXT method */ #define SNMP_CMD_GETNEXT (1<<1) /* query an agent with SET method */ #define SNMP_CMD_SET (1<<2) /* walk the mib */ #define SNMP_CMD_WALK (1<<3) /* force values-only output */ #define SNMP_NUMERIC_KEYS (1<<7) /* use user-supplied OID names for keys in array output mode in GET method */ #define SNMP_ORIGINAL_NAMES_AS_KEYS (1<<8) /* use OID suffix (`index') for keys in array output mode in WALK method */ #define SNMP_USE_SUFFIX_AS_KEYS (1<<9) #ifdef COMPILE_DL_SNMP ZEND_GET_MODULE(snmp) #endif /* THREAD_LS snmp_module php_snmp_module; - may need one of these at some point */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(snmp) { snmp_globals->valueretrieval = SNMP_VALUE_LIBRARY; } /* }}} */ #define PHP_SNMP_SESSION_FREE(a) { \ if ((*session)->a) { \ efree((*session)->a); \ (*session)->a = NULL; \ } \ } static void netsnmp_session_free(php_snmp_session **session) /* {{{ */ { if (*session) { PHP_SNMP_SESSION_FREE(peername); PHP_SNMP_SESSION_FREE(community); PHP_SNMP_SESSION_FREE(securityName); PHP_SNMP_SESSION_FREE(contextEngineID); efree(*session); *session = NULL; } } /* }}} */ static void php_snmp_session_destructor(zend_resource *rsrc) /* {{{ */ { php_snmp_session *session = (php_snmp_session *)rsrc->ptr; netsnmp_session_free(&session); } /* }}} */ static void php_snmp_object_free_storage(zend_object *object) /* {{{ */ { php_snmp_object *intern = php_snmp_fetch_object(object); if (!intern) { return; } netsnmp_session_free(&(intern->session)); zend_object_std_dtor(&intern->zo); } /* }}} */ static zend_object *php_snmp_object_new(zend_class_entry *class_type) /* {{{ */ { php_snmp_object *intern; /* Allocate memory for it */ intern = zend_object_alloc(sizeof(php_snmp_object), class_type); zend_object_std_init(&intern->zo, class_type); object_properties_init(&intern->zo, class_type); intern->zo.handlers = &php_snmp_object_handlers; return &intern->zo; } /* }}} */ /* {{{ php_snmp_error * * Record last SNMP-related error in object * */ static void php_snmp_error(zval *object, int type, const char *format, ...) { va_list args; php_snmp_object *snmp_object = NULL; if (object) { snmp_object = Z_SNMP_P(object); if (type == PHP_SNMP_ERRNO_NOERROR) { memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr)); } else { va_start(args, format); vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args); va_end(args); } snmp_object->snmp_errno = type; } if (type == PHP_SNMP_ERRNO_NOERROR) { return; } if (object && (snmp_object->exceptions_enabled & type)) { zend_throw_exception_ex(php_snmp_exception_ce, type, "%s", snmp_object->snmp_errstr); } else { va_start(args, format); php_verror(NULL, "", E_WARNING, format, args); va_end(args); } } /* }}} */ /* {{{ php_snmp_getvalue * * SNMP value to zval converter * */ static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval, int valueretrieval) { zval val; char sbuf[512]; char *buf = &(sbuf[0]); char *dbuf = (char *)NULL; int buflen = sizeof(sbuf) - 1; int val_len = vars->val_len; /* use emalloc() for large values, use static array otherwize */ /* There is no way to know the size of buffer snprint_value() needs in order to print a value there. * So we are forced to probe it */ while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) { *buf = '\0'; if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) { if (val_len > 512*1024) { php_error_docref(NULL, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?"); break; } /* buffer is not long enough to hold full output, double it */ val_len *= 2; } else { break; } if (buf == dbuf) { dbuf = (char *)erealloc(dbuf, val_len + 1); } else { dbuf = (char *)emalloc(val_len + 1); } buf = dbuf; buflen = val_len; } if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){ dbuf = (char *)emalloc(val_len + 1); buf = dbuf; buflen = val_len; } if (valueretrieval & SNMP_VALUE_PLAIN) { *buf = 0; switch (vars->type) { case ASN_BIT_STR: /* 0x03, asn1.h */ ZVAL_STRINGL(&val, (char *)vars->val.bitstring, vars->val_len); break; case ASN_OCTET_STR: /* 0x04, asn1.h */ case ASN_OPAQUE: /* 0x44, snmp_impl.h */ ZVAL_STRINGL(&val, (char *)vars->val.string, vars->val_len); break; case ASN_NULL: /* 0x05, asn1.h */ ZVAL_NULL(&val); break; case ASN_OBJECT_ID: /* 0x06, asn1.h */ snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid)); ZVAL_STRING(&val, buf); break; case ASN_IPADDRESS: /* 0x40, snmp_impl.h */ snprintf(buf, buflen, "%d.%d.%d.%d", (vars->val.string)[0], (vars->val.string)[1], (vars->val.string)[2], (vars->val.string)[3]); buf[buflen]=0; ZVAL_STRING(&val, buf); break; case ASN_COUNTER: /* 0x41, snmp_impl.h */ case ASN_GAUGE: /* 0x42, snmp_impl.h */ /* ASN_UNSIGNED is the same as ASN_GAUGE */ case ASN_TIMETICKS: /* 0x43, snmp_impl.h */ case ASN_UINTEGER: /* 0x47, snmp_impl.h */ snprintf(buf, buflen, "%lu", *vars->val.integer); buf[buflen]=0; ZVAL_STRING(&val, buf); break; case ASN_INTEGER: /* 0x02, asn1.h */ snprintf(buf, buflen, "%ld", *vars->val.integer); buf[buflen]=0; ZVAL_STRING(&val, buf); break; #if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES) case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */ snprintf(buf, buflen, "%f", *vars->val.floatVal); ZVAL_STRING(&val, buf); break; case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */ snprintf(buf, buflen, "%f", *vars->val.doubleVal); ZVAL_STRING(&val, buf); break; case ASN_OPAQUE_I64: /* 0x80, asn1.h */ printI64(buf, vars->val.counter64); ZVAL_STRING(&val, buf); break; case ASN_OPAQUE_U64: /* 0x81, asn1.h */ #endif case ASN_COUNTER64: /* 0x46, snmp_impl.h */ printU64(buf, vars->val.counter64); ZVAL_STRING(&val, buf); break; default: ZVAL_STRING(&val, "Unknown value type"); php_error_docref(NULL, E_WARNING, "Unknown value type: %u", vars->type); break; } } else /* use Net-SNMP value translation */ { /* we have desired string in buffer, just use it */ ZVAL_STRING(&val, buf); } if (valueretrieval & SNMP_VALUE_OBJECT) { object_init(snmpval); add_property_long(snmpval, "type", vars->type); add_property_zval(snmpval, "value", &val); } else { ZVAL_COPY(snmpval, &val); } zval_ptr_dtor(&val); if (dbuf){ /* malloc was used to store value */ efree(dbuf); } } /* }}} */ /* {{{ php_snmp_internal * * SNMP object fetcher/setter for all SNMP versions * */ static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st, struct snmp_session *session, struct objid_query *objid_query) { struct snmp_session *ss; struct snmp_pdu *pdu=NULL, *response; struct variable_list *vars; oid root[MAX_NAME_LEN]; size_t rootlen = 0; int status, count, found; char buf[2048]; char buf2[2048]; int keepwalking=1; char *err; zval snmpval; int snmp_errno; /* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */ RETVAL_FALSE; /* reset errno and errstr */ php_snmp_error(getThis(), PHP_SNMP_ERRNO_NOERROR, ""); if (st & SNMP_CMD_WALK) { /* remember root OID */ memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid)); rootlen = objid_query->vars[0].name_length; objid_query->offset = objid_query->count; } if ((ss = snmp_open(session)) == NULL) { snmp_error(session, NULL, NULL, &err); php_error_docref(NULL, E_WARNING, "Could not open snmp connection: %s", err); free(err); RETVAL_FALSE; return; } if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) { php_snmp_error(getThis(), PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries"); } while (keepwalking) { keepwalking = 0; if (st & SNMP_CMD_WALK) { if (session->version == SNMP_VERSION_1) { pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); } else { pdu = snmp_pdu_create(SNMP_MSG_GETBULK); pdu->non_repeaters = objid_query->non_repeaters; pdu->max_repetitions = objid_query->max_repetitions; } snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length); } else { if (st & SNMP_CMD_GET) { pdu = snmp_pdu_create(SNMP_MSG_GET); } else if (st & SNMP_CMD_GETNEXT) { pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); } else if (st & SNMP_CMD_SET) { pdu = snmp_pdu_create(SNMP_MSG_SET); } else { snmp_close(ss); php_error_docref(NULL, E_ERROR, "Unknown SNMP command (internals)"); RETVAL_FALSE; return; } for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){ if (st & SNMP_CMD_SET) { if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) { snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length); php_snmp_error(getThis(), PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno)); snmp_free_pdu(pdu); snmp_close(ss); RETVAL_FALSE; return; } } else { snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length); } } if(pdu->variables == NULL){ snmp_free_pdu(pdu); snmp_close(ss); RETVAL_FALSE; return; } } retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (st & SNMP_CMD_SET) { if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */ keepwalking = 1; continue; } snmp_free_pdu(response); snmp_close(ss); RETVAL_TRUE; return; } for (vars = response->variables; vars; vars = vars->next_variable) { /* do not output errors as values */ if ( vars->type == SNMP_ENDOFMIBVIEW || vars->type == SNMP_NOSUCHOBJECT || vars->type == SNMP_NOSUCHINSTANCE ) { if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) { break; } snprint_objid(buf, sizeof(buf), vars->name, vars->name_length); snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars); php_snmp_error(getThis(), PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2); continue; } if ((st & SNMP_CMD_WALK) && (vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */ if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */ keepwalking = 0; } else { /* first fetched OID is out of subtree, fallback to GET query */ st |= SNMP_CMD_GET; st ^= SNMP_CMD_WALK; objid_query->offset = 0; keepwalking = 1; } break; } ZVAL_NULL(&snmpval); php_snmp_getvalue(vars, &snmpval, objid_query->valueretrieval); if (objid_query->array_output) { if (Z_TYPE_P(return_value) == IS_TRUE || Z_TYPE_P(return_value) == IS_FALSE) { array_init(return_value); } if (st & SNMP_NUMERIC_KEYS) { add_next_index_zval(return_value, &snmpval); } else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) { found = 0; for (count = 0; count < objid_query->count; count++) { if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) { found = 1; objid_query->vars[count].name_length = 0; /* mark this name as used */ break; } } if (found) { add_assoc_zval(return_value, objid_query->vars[count].oid, &snmpval); } else { snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length); php_error_docref(NULL, E_WARNING, "Could not find original OID name for '%s'", buf2); } } else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) { snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length); if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) { buf2[0] = '\0'; count = rootlen; while(count < vars->name_length){ sprintf(buf, "%lu.", vars->name[count]); strcat(buf2, buf); count++; } buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */ } add_assoc_zval(return_value, buf2, &snmpval); } else { snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length); add_assoc_zval(return_value, buf2, &snmpval); } } else { ZVAL_COPY_VALUE(return_value, &snmpval); break; } /* OID increase check */ if (st & SNMP_CMD_WALK) { if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) { snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length); php_snmp_error(getThis(), PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2); keepwalking = 0; } else { memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid)); objid_query->vars[0].name_length = vars->name_length; keepwalking = 1; } } } if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */ keepwalking = 1; } } else { if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */ objid_query->max_repetitions /= 2; snmp_free_pdu(response); keepwalking = 1; continue; } if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_TRUE || Z_TYPE_P(return_value) == IS_FALSE) { for (count=1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++); if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */ objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 ); objid_query->step /= 2; snmp_free_pdu(response); keepwalking = 1; continue; } if (vars) { snprint_objid(buf, sizeof(buf), vars->name, vars->name_length); php_snmp_error(getThis(), PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat)); } else { php_snmp_error(getThis(), PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat)); } if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */ if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) { snmp_free_pdu(response); goto retry; } } snmp_free_pdu(response); snmp_close(ss); if (objid_query->array_output) { zval_ptr_dtor(return_value); } RETVAL_FALSE; return; } } } else if (status == STAT_TIMEOUT) { php_snmp_error(getThis(), PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername); if (objid_query->array_output) { zval_ptr_dtor(return_value); } snmp_close(ss); RETVAL_FALSE; return; } else { /* status == STAT_ERROR */ snmp_error(ss, NULL, NULL, &err); php_snmp_error(getThis(), PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err); free(err); if (objid_query->array_output) { zval_ptr_dtor(return_value); } snmp_close(ss); RETVAL_FALSE; return; } if (response) { snmp_free_pdu(response); } } /* keepwalking */ snmp_close(ss); } /* }}} */ /* {{{ php_snmp_parse_oid * * OID parser (and type, value for SNMP_SET command) */ static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval *oid, zval *type, zval *value) { char *pptr; uint32_t idx_type = 0, idx_value = 0; zval *tmp_oid, *tmp_type, *tmp_value; if (Z_TYPE_P(oid) != IS_ARRAY) { convert_to_string_ex(oid); } if (st & SNMP_CMD_SET) { if (Z_TYPE_P(type) != IS_ARRAY) { convert_to_string_ex(type); } if (Z_TYPE_P(value) != IS_ARRAY) { convert_to_string_ex(value); } } objid_query->count = 0; objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE); if (Z_TYPE_P(oid) == IS_STRING) { objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg)); objid_query->vars[objid_query->count].oid = Z_STRVAL_P(oid); if (st & SNMP_CMD_SET) { if (Z_TYPE_P(type) == IS_STRING && Z_TYPE_P(value) == IS_STRING) { if (Z_STRLEN_P(type) != 1) { php_error_docref(NULL, E_WARNING, "Bogus type '%s', should be single char, got %zu", Z_STRVAL_P(type), Z_STRLEN_P(type)); efree(objid_query->vars); return FALSE; } pptr = Z_STRVAL_P(type); objid_query->vars[objid_query->count].type = *pptr; objid_query->vars[objid_query->count].value = Z_STRVAL_P(value); } else { php_error_docref(NULL, E_WARNING, "Single objid and multiple type or values are not supported"); efree(objid_query->vars); return FALSE; } } objid_query->count++; } else if (Z_TYPE_P(oid) == IS_ARRAY) { /* we got objid array */ if (zend_hash_num_elements(Z_ARRVAL_P(oid)) == 0) { php_error_docref(NULL, E_WARNING, "Got empty OID array"); return FALSE; } objid_query->vars = (snmpobjarg *)safe_emalloc(sizeof(snmpobjarg), zend_hash_num_elements(Z_ARRVAL_P(oid)), 0); objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE ); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(oid), tmp_oid) { convert_to_string_ex(tmp_oid); objid_query->vars[objid_query->count].oid = Z_STRVAL_P(tmp_oid); if (st & SNMP_CMD_SET) { if (Z_TYPE_P(type) == IS_STRING) { pptr = Z_STRVAL_P(type); objid_query->vars[objid_query->count].type = *pptr; } else if (Z_TYPE_P(type) == IS_ARRAY) { while (idx_type < Z_ARRVAL_P(type)->nNumUsed) { tmp_type = &Z_ARRVAL_P(type)->arData[idx_type].val; if (Z_TYPE_P(tmp_type) != IS_UNDEF) { break; } idx_type++; } if (idx_type < Z_ARRVAL_P(type)->nNumUsed) { convert_to_string_ex(tmp_type); if (Z_STRLEN_P(tmp_type) != 1) { php_error_docref(NULL, E_WARNING, "'%s': bogus type '%s', should be single char, got %zu", Z_STRVAL_P(tmp_oid), Z_STRVAL_P(tmp_type), Z_STRLEN_P(tmp_type)); efree(objid_query->vars); return FALSE; } pptr = Z_STRVAL_P(tmp_type); objid_query->vars[objid_query->count].type = *pptr; idx_type++; } else { php_error_docref(NULL, E_WARNING, "'%s': no type set", Z_STRVAL_P(tmp_oid)); efree(objid_query->vars); return FALSE; } } if (Z_TYPE_P(value) == IS_STRING) { objid_query->vars[objid_query->count].value = Z_STRVAL_P(value); } else if (Z_TYPE_P(value) == IS_ARRAY) { while (idx_value < Z_ARRVAL_P(value)->nNumUsed) { tmp_value = &Z_ARRVAL_P(value)->arData[idx_value].val; if (Z_TYPE_P(tmp_value) != IS_UNDEF) { break; } idx_value++; } if (idx_value < Z_ARRVAL_P(value)->nNumUsed) { convert_to_string_ex(tmp_value); objid_query->vars[objid_query->count].value = Z_STRVAL_P(tmp_value); idx_value++; } else { php_error_docref(NULL, E_WARNING, "'%s': no value set", Z_STRVAL_P(tmp_oid)); efree(objid_query->vars); return FALSE; } } } objid_query->count++; } ZEND_HASH_FOREACH_END(); } /* now parse all OIDs */ if (st & SNMP_CMD_WALK) { if (objid_query->count > 1) { php_snmp_error(object, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!"); efree(objid_query->vars); return FALSE; } objid_query->vars[0].name_length = MAX_NAME_LEN; if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */ if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) { php_snmp_error(object, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid); efree(objid_query->vars); return FALSE; } } else { memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib)); objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid); } } else { for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) { objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN; if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) { php_snmp_error(object, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid); efree(objid_query->vars); return FALSE; } } } objid_query->offset = 0; objid_query->step = objid_query->count; return (objid_query->count > 0); } /* }}} */ /* {{{ netsnmp_session_init allocates memory for session and session->peername, caller should free it manually using netsnmp_session_free() and efree() */ static int netsnmp_session_init(php_snmp_session **session_p, int version, char *hostname, char *community, int timeout, int retries) { php_snmp_session *session; char *pptr, *host_ptr; int force_ipv6 = FALSE; int n; struct sockaddr **psal; struct sockaddr **res; *session_p = (php_snmp_session *)emalloc(sizeof(php_snmp_session)); session = *session_p; memset(session, 0, sizeof(php_snmp_session)); snmp_sess_init(session); session->version = version; session->remote_port = SNMP_PORT; session->peername = emalloc(MAX_NAME_LEN); /* we copy original hostname for further processing */ strlcpy(session->peername, hostname, MAX_NAME_LEN); host_ptr = session->peername; /* Reading the hostname and its optional non-default port number */ if (*host_ptr == '[') { /* IPv6 address */ force_ipv6 = TRUE; host_ptr++; if ((pptr = strchr(host_ptr, ']'))) { if (pptr[1] == ':') { session->remote_port = atoi(pptr + 2); } *pptr = '\0'; } else { php_error_docref(NULL, E_WARNING, "malformed IPv6 address, closing square bracket missing"); return (-1); } } else { /* IPv4 address */ if ((pptr = strchr(host_ptr, ':'))) { session->remote_port = atoi(pptr + 1); *pptr = '\0'; } } /* since Net-SNMP library requires 'udp6:' prefix for all IPv6 addresses (in FQDN form too) we need to perform possible name resolution before running any SNMP queries */ if ((n = php_network_getaddresses(host_ptr, SOCK_DGRAM, &psal, NULL)) == 0) { /* some resolver error */ /* warnings sent, bailing out */ return (-1); } /* we have everything we need in psal, flush peername and fill it properly */ *(session->peername) = '\0'; res = psal; while (n-- > 0) { pptr = session->peername; #if HAVE_GETADDRINFO && HAVE_IPV6 && HAVE_INET_NTOP if (force_ipv6 && (*res)->sa_family != AF_INET6) { res++; continue; } if ((*res)->sa_family == AF_INET6) { strcpy(session->peername, "udp6:["); pptr = session->peername + strlen(session->peername); inet_ntop((*res)->sa_family, &(((struct sockaddr_in6*)(*res))->sin6_addr), pptr, MAX_NAME_LEN); strcat(pptr, "]"); } else if ((*res)->sa_family == AF_INET) { inet_ntop((*res)->sa_family, &(((struct sockaddr_in*)(*res))->sin_addr), pptr, MAX_NAME_LEN); } else { res++; continue; } #else if ((*res)->sa_family != AF_INET) { res++; continue; } strcat(pptr, inet_ntoa(((struct sockaddr_in*)(*res))->sin_addr)); #endif break; } if (strlen(session->peername) == 0) { php_error_docref(NULL, E_WARNING, "Unknown failure while resolving '%s'", hostname); return (-1); } /* XXX FIXME There should be check for non-empty session->peername! */ /* put back non-standard SNMP port */ if (session->remote_port != SNMP_PORT) { pptr = session->peername + strlen(session->peername); sprintf(pptr, ":%d", session->remote_port); } php_network_freeaddresses(psal); if (version == SNMP_VERSION_3) { /* Setting the security name. */ session->securityName = estrdup(community); session->securityNameLen = strlen(session->securityName); } else { session->authenticator = NULL; session->community = (u_char *)estrdup(community); session->community_len = strlen(community); } session->retries = retries; session->timeout = timeout; return (0); } /* }}} */ /* {{{ int netsnmp_session_set_sec_level(struct snmp_session *s, char *level) Set the security level in the snmpv3 session */ static int netsnmp_session_set_sec_level(struct snmp_session *s, char *level) { if (!strcasecmp(level, "noAuthNoPriv") || !strcasecmp(level, "nanp")) { s->securityLevel = SNMP_SEC_LEVEL_NOAUTH; } else if (!strcasecmp(level, "authNoPriv") || !strcasecmp(level, "anp")) { s->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV; } else if (!strcasecmp(level, "authPriv") || !strcasecmp(level, "ap")) { s->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV; } else { return (-1); } return (0); } /* }}} */ /* {{{ int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot) Set the authentication protocol in the snmpv3 session */ static int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot) { if (!strcasecmp(prot, "MD5")) { s->securityAuthProto = usmHMACMD5AuthProtocol; s->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN; } else if (!strcasecmp(prot, "SHA")) { s->securityAuthProto = usmHMACSHA1AuthProtocol; s->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN; } else { php_error_docref(NULL, E_WARNING, "Unknown authentication protocol '%s'", prot); return (-1); } return (0); } /* }}} */ /* {{{ int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot) Set the security protocol in the snmpv3 session */ static int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot) { if (!strcasecmp(prot, "DES")) { s->securityPrivProto = usmDESPrivProtocol; s->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN; #ifdef HAVE_AES } else if (!strcasecmp(prot, "AES128") || !strcasecmp(prot, "AES")) { s->securityPrivProto = usmAESPrivProtocol; s->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN; #endif } else { php_error_docref(NULL, E_WARNING, "Unknown security protocol '%s'", prot); return (-1); } return (0); } /* }}} */ /* {{{ int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass) Make key from pass phrase in the snmpv3 session */ static int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass) { int snmp_errno; s->securityAuthKeyLen = USM_AUTH_KU_LEN; if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen, (u_char *) pass, strlen(pass), s->securityAuthKey, &(s->securityAuthKeyLen)))) { php_error_docref(NULL, E_WARNING, "Error generating a key for authentication pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno)); return (-1); } return (0); } /* }}} */ /* {{{ int netsnmp_session_gen_sec_key(struct snmp_session *s, u_char *pass) Make key from pass phrase in the snmpv3 session */ static int netsnmp_session_gen_sec_key(struct snmp_session *s, char *pass) { int snmp_errno; s->securityPrivKeyLen = USM_PRIV_KU_LEN; if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen, (u_char *)pass, strlen(pass), s->securityPrivKey, &(s->securityPrivKeyLen)))) { php_error_docref(NULL, E_WARNING, "Error generating a key for privacy pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno)); return (-2); } return (0); } /* }}} */ /* {{{ in netsnmp_session_set_contextEngineID(struct snmp_session *s, u_char * contextEngineID) Set context Engine Id in the snmpv3 session */ static int netsnmp_session_set_contextEngineID(struct snmp_session *s, char * contextEngineID) { size_t ebuf_len = 32, eout_len = 0; u_char *ebuf = (u_char *) emalloc(ebuf_len); if (!snmp_hex_to_binary(&ebuf, &ebuf_len, &eout_len, 1, contextEngineID)) { php_error_docref(NULL, E_WARNING, "Bad engine ID value '%s'", contextEngineID); efree(ebuf); return (-1); } if (s->contextEngineID) { efree(s->contextEngineID); } s->contextEngineID = ebuf; s->contextEngineIDLen = eout_len; return (0); } /* }}} */ /* {{{ php_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID) Set all snmpv3-related security options */ static int netsnmp_session_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID) { /* Setting the security level. */ if (netsnmp_session_set_sec_level(session, sec_level)) { php_error_docref(NULL, E_WARNING, "Invalid security level '%s'", sec_level); return (-1); } if (session->securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { /* Setting the authentication protocol. */ if (netsnmp_session_set_auth_protocol(session, auth_protocol)) { /* Warning message sent already, just bail out */ return (-1); } /* Setting the authentication passphrase. */ if (netsnmp_session_gen_auth_key(session, auth_passphrase)) { /* Warning message sent already, just bail out */ return (-1); } if (session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { /* Setting the security protocol. */ if (netsnmp_session_set_sec_protocol(session, priv_protocol)) { /* Warning message sent already, just bail out */ return (-1); } /* Setting the security protocol passphrase. */ if (netsnmp_session_gen_sec_key(session, priv_passphrase)) { /* Warning message sent already, just bail out */ return (-1); } } } /* Setting contextName if specified */ if (contextName) { session->contextName = contextName; session->contextNameLen = strlen(contextName); } /* Setting contextEngineIS if specified */ if (contextEngineID && strlen(contextEngineID) && netsnmp_session_set_contextEngineID(session, contextEngineID)) { /* Warning message sent already, just bail out */ return (-1); } return (0); } /* }}} */ /* {{{ php_snmp * * Generic SNMP handler for all versions. * This function makes use of the internal SNMP object fetcher. * Used both in old (non-OO) and OO API * */ static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version) { zval *oid, *value, *type; char *a1, *a2, *a3, *a4, *a5, *a6, *a7; size_t a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len; zend_bool use_orignames = 0, suffix_keys = 0; zend_long timeout = SNMP_DEFAULT_TIMEOUT; zend_long retries = SNMP_DEFAULT_RETRIES; int argc = ZEND_NUM_ARGS(); struct objid_query objid_query; php_snmp_session *session; int session_less_mode = (getThis() == NULL); php_snmp_object *snmp_object; php_snmp_object glob_snmp_object; objid_query.max_repetitions = -1; objid_query.non_repeaters = 0; objid_query.valueretrieval = SNMP_G(valueretrieval); objid_query.oid_increasing_check = TRUE; if (session_less_mode) { if (version == SNMP_VERSION_3) { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc, "ssssssszzz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc, "sssssssz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc, "sszzz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc, "ssz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc, "zzz", &oid, &type, &value) == FAILURE) { RETURN_FALSE; } } else if (st & SNMP_CMD_WALK) { if (zend_parse_parameters(argc, "z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) { RETURN_FALSE; } if (suffix_keys) { st |= SNMP_USE_SUFFIX_AS_KEYS; } } else if (st & SNMP_CMD_GET) { if (zend_parse_parameters(argc, "z|b", &oid, &use_orignames) == FAILURE) { RETURN_FALSE; } if (use_orignames) { st |= SNMP_ORIGINAL_NAMES_AS_KEYS; } } else { /* SNMP_CMD_GETNEXT */ if (zend_parse_parameters(argc, "z", &oid) == FAILURE) { RETURN_FALSE; } } } if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value)) { RETURN_FALSE; } if (session_less_mode) { if (netsnmp_session_init(&session, version, a1, a2, timeout, retries)) { efree(objid_query.vars); netsnmp_session_free(&session); RETURN_FALSE; } if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL)) { efree(objid_query.vars); netsnmp_session_free(&session); /* Warning message sent already, just bail out */ RETURN_FALSE; } } else { zval *object = getThis(); snmp_object = Z_SNMP_P(object); session = snmp_object->session; if (!session) { php_error_docref(NULL, E_WARNING, "Invalid or uninitialized SNMP object"); efree(objid_query.vars); RETURN_FALSE; } if (snmp_object->max_oids > 0) { objid_query.step = snmp_object->max_oids; if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */ objid_query.max_repetitions = snmp_object->max_oids; } } objid_query.oid_increasing_check = snmp_object->oid_increasing_check; objid_query.valueretrieval = snmp_object->valueretrieval; glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print); glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print); glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format); } if (objid_query.max_repetitions < 0) { objid_query.max_repetitions = 20; /* provide correct default value */ } php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query); efree(objid_query.vars); if (session_less_mode) { netsnmp_session_free(&session); } else { netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format); } } /* }}} */ /* {{{ proto mixed snmpget(string host, string community, mixed object_id [, int timeout [, int retries]]) Fetch a SNMP object */ PHP_FUNCTION(snmpget) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_1); } /* }}} */ /* {{{ proto mixed snmpgetnext(string host, string community, mixed object_id [, int timeout [, int retries]]) Fetch a SNMP object */ PHP_FUNCTION(snmpgetnext) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_1); } /* }}} */ /* {{{ proto mixed snmpwalk(string host, string community, mixed object_id [, int timeout [, int retries]]) Return all objects under the specified object id */ PHP_FUNCTION(snmpwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1); } /* }}} */ /* {{{ proto mixed snmprealwalk(string host, string community, mixed object_id [, int timeout [, int retries]]) Return all objects including their respective object id within the specified one */ PHP_FUNCTION(snmprealwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1); } /* }}} */ /* {{{ proto bool snmpset(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]]) Set the value of a SNMP object */ PHP_FUNCTION(snmpset) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_1); } /* }}} */ /* {{{ proto bool snmp_get_quick_print(void) Return the current status of quick_print */ PHP_FUNCTION(snmp_get_quick_print) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)); } /* }}} */ /* {{{ proto bool snmp_set_quick_print(int quick_print) Return all objects including their respective object id within the specified one */ PHP_FUNCTION(snmp_set_quick_print) { zend_long a1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) { RETURN_FALSE; } netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, (int)a1); RETURN_TRUE; } /* }}} */ /* {{{ proto bool snmp_set_enum_print(int enum_print) Return all values that are enums with their enum value instead of the raw integer */ PHP_FUNCTION(snmp_set_enum_print) { zend_long a1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) { RETURN_FALSE; } netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1); RETURN_TRUE; } /* }}} */ /* {{{ proto bool snmp_set_oid_output_format(int oid_format) Set the OID output format. */ PHP_FUNCTION(snmp_set_oid_output_format) { zend_long a1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) { RETURN_FALSE; } switch((int) a1) { case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_UCD: case NETSNMP_OID_OUTPUT_NONE: netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1); RETURN_TRUE; break; default: php_error_docref(NULL, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1); RETURN_FALSE; break; } } /* }}} */ /* {{{ proto mixed snmp2_get(string host, string community, mixed object_id [, int timeout [, int retries]]) Fetch a SNMP object */ PHP_FUNCTION(snmp2_get) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_2c); } /* }}} */ /* {{{ proto mixed snmp2_getnext(string host, string community, mixed object_id [, int timeout [, int retries]]) Fetch a SNMP object */ PHP_FUNCTION(snmp2_getnext) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c); } /* }}} */ /* {{{ proto mixed snmp2_walk(string host, string community, mixed object_id [, int timeout [, int retries]]) Return all objects under the specified object id */ PHP_FUNCTION(snmp2_walk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_2c); } /* }}} */ /* {{{ proto mixed snmp2_real_walk(string host, string community, mixed object_id [, int timeout [, int retries]]) Return all objects including their respective object id within the specified one */ PHP_FUNCTION(snmp2_real_walk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_2c); } /* }}} */ /* {{{ proto bool snmp2_set(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]]) Set the value of a SNMP object */ PHP_FUNCTION(snmp2_set) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_2c); } /* }}} */ /* {{{ proto mixed snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]]) Fetch the value of a SNMP object */ PHP_FUNCTION(snmp3_get) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_3); } /* }}} */ /* {{{ proto mixed snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]]) Fetch the value of a SNMP object */ PHP_FUNCTION(snmp3_getnext) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_3); } /* }}} */ /* {{{ proto mixed snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]]) Fetch the value of a SNMP object */ PHP_FUNCTION(snmp3_walk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_3); } /* }}} */ /* {{{ proto mixed snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]]) Fetch the value of a SNMP object */ PHP_FUNCTION(snmp3_real_walk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_3); } /* }}} */ /* {{{ proto bool snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id, mixed type, mixed value [, int timeout [, int retries]]) Fetch the value of a SNMP object */ PHP_FUNCTION(snmp3_set) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_3); } /* }}} */ /* {{{ proto bool snmp_set_valueretrieval(int method) Specify the method how the SNMP values will be returned */ PHP_FUNCTION(snmp_set_valueretrieval) { zend_long method; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) { RETURN_FALSE; } if (method >= 0 && method <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) { SNMP_G(valueretrieval) = method; RETURN_TRUE; } else { php_error_docref(NULL, E_WARNING, "Unknown SNMP value retrieval method '" ZEND_LONG_FMT "'", method); RETURN_FALSE; } } /* }}} */ /* {{{ proto int snmp_get_valueretrieval() Return the method how the SNMP values will be returned */ PHP_FUNCTION(snmp_get_valueretrieval) { if (zend_parse_parameters_none() == FAILURE) { RETURN_FALSE; } RETURN_LONG(SNMP_G(valueretrieval)); } /* }}} */ /* {{{ proto bool snmp_read_mib(string filename) Reads and parses a MIB file into the active MIB tree. */ PHP_FUNCTION(snmp_read_mib) { char *filename; size_t filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &filename, &filename_len) == FAILURE) { RETURN_FALSE; } if (!read_mib(filename)) { char *error = strerror(errno); php_error_docref(NULL, E_WARNING, "Error while reading MIB file '%s': %s", filename, error); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto SNMP::__construct(int version, string hostname, string community|securityName [, int timeout [, int retries]]) Creates a new SNMP session to specified host. */ PHP_METHOD(snmp, __construct) { php_snmp_object *snmp_object; zval *object = ZEND_THIS; char *a1, *a2; size_t a1_len, a2_len; zend_long timeout = SNMP_DEFAULT_TIMEOUT; zend_long retries = SNMP_DEFAULT_RETRIES; zend_long version = SNMP_DEFAULT_VERSION; int argc = ZEND_NUM_ARGS(); snmp_object = Z_SNMP_P(object); if (zend_parse_parameters_throw(argc, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) { return; } switch (version) { case SNMP_VERSION_1: case SNMP_VERSION_2c: case SNMP_VERSION_3: break; default: zend_throw_exception(zend_ce_exception, "Unknown SNMP protocol version", 0); return; } /* handle re-open of snmp session */ if (snmp_object->session) { netsnmp_session_free(&(snmp_object->session)); } if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries)) { return; } snmp_object->max_oids = 0; snmp_object->valueretrieval = SNMP_G(valueretrieval); snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); snmp_object->oid_increasing_check = TRUE; snmp_object->exceptions_enabled = 0; } /* }}} */ /* {{{ proto bool SNMP::close() Close SNMP session */ PHP_METHOD(snmp, close) { php_snmp_object *snmp_object; zval *object = ZEND_THIS; snmp_object = Z_SNMP_P(object); if (zend_parse_parameters_none() == FAILURE) { RETURN_FALSE; } netsnmp_session_free(&(snmp_object->session)); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed SNMP::get(mixed object_id [, bool preserve_keys]) Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */ PHP_METHOD(snmp, get) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, (-1)); } /* }}} */ /* {{{ proto mixed SNMP::getnext(mixed object_id) Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */ PHP_METHOD(snmp, getnext) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, (-1)); } /* }}} */ /* {{{ proto mixed SNMP::walk(mixed object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters]]) Return all objects including their respective object id within the specified one as array of oid->value pairs */ PHP_METHOD(snmp, walk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, (-1)); } /* }}} */ /* {{{ proto bool SNMP::set(mixed object_id, mixed type, mixed value) Set the value of a SNMP object */ PHP_METHOD(snmp, set) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, (-1)); } /* }}} */ /* {{{ proto bool SNMP::setSecurity(string sec_level, [ string auth_protocol, string auth_passphrase [, string priv_protocol, string priv_passphrase [, string contextName [, string contextEngineID]]]]) Set SNMPv3 security-related session parameters */ PHP_METHOD(snmp, setSecurity) { php_snmp_object *snmp_object; zval *object = ZEND_THIS; char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = ""; size_t a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0; int argc = ZEND_NUM_ARGS(); snmp_object = Z_SNMP_P(object); if (zend_parse_parameters(argc, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) { RETURN_FALSE; } if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7)) { /* Warning message sent already, just bail out */ RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int SNMP::getErrno() Get last error code number */ PHP_METHOD(snmp, getErrno) { php_snmp_object *snmp_object; zval *object = ZEND_THIS; snmp_object = Z_SNMP_P(object); RETVAL_LONG(snmp_object->snmp_errno); return; } /* }}} */ /* {{{ proto int SNMP::getError() Get last error message */ PHP_METHOD(snmp, getError) { php_snmp_object *snmp_object; zval *object = ZEND_THIS; snmp_object = Z_SNMP_P(object); RETURN_STRING(snmp_object->snmp_errstr); } /* }}} */ /* {{{ */ void php_snmp_add_property(HashTable *h, const char *name, size_t name_length, php_snmp_read_t read_func, php_snmp_write_t write_func) { php_snmp_prop_handler p; zend_string *str; p.name = (char*) name; p.name_length = name_length; p.read_func = (read_func) ? read_func : NULL; p.write_func = (write_func) ? write_func : NULL; str = zend_string_init_interned(name, name_length, 1); zend_hash_add_mem(h, str, &p, sizeof(php_snmp_prop_handler)); zend_string_release_ex(str, 1); } /* }}} */ /* {{{ php_snmp_read_property(zval *object, zval *member, int type[, const zend_literal *key]) Generic object property reader */ zval *php_snmp_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv) { zval *retval; php_snmp_object *obj; php_snmp_prop_handler *hnd; int ret; obj = php_snmp_fetch_object(object); hnd = zend_hash_find_ptr(&php_snmp_properties, name); if (hnd && hnd->read_func) { ret = hnd->read_func(obj, rv); if (ret == SUCCESS) { retval = rv; } else { retval = &EG(uninitialized_zval); } } else { retval = zend_std_read_property(object, name, type, cache_slot, rv); } return retval; } /* }}} */ /* {{{ php_snmp_write_property(zval *object, zval *member, zval *value[, const zend_literal *key]) Generic object property writer */ zval *php_snmp_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot) { php_snmp_object *obj; php_snmp_prop_handler *hnd; obj = php_snmp_fetch_object(object); hnd = zend_hash_find_ptr(&php_snmp_properties, name); if (hnd && hnd->write_func) { hnd->write_func(obj, value); /* if (!PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) == 0) { Z_ADDREF_P(value); zval_ptr_dtor(&value); } */ } else { value = zend_std_write_property(object, name, value, cache_slot); } return value; } /* }}} */ /* {{{ php_snmp_has_property(zval *object, zval *member, int has_set_exists[, const zend_literal *key]) Generic object property checker */ static int php_snmp_has_property(zend_object *object, zend_string *name, int has_set_exists, void **cache_slot) { zval rv; php_snmp_prop_handler *hnd; int ret = 0; if ((hnd = zend_hash_find_ptr(&php_snmp_properties, name)) != NULL) { switch (has_set_exists) { case ZEND_PROPERTY_EXISTS: ret = 1; break; case ZEND_PROPERTY_ISSET: { zval *value = php_snmp_read_property(object, name, BP_VAR_IS, cache_slot, &rv); if (value != &EG(uninitialized_zval)) { ret = Z_TYPE_P(value) != IS_NULL? 1 : 0; zval_ptr_dtor(value); } break; } default: { zval *value = php_snmp_read_property(object, name, BP_VAR_IS, cache_slot, &rv); if (value != &EG(uninitialized_zval)) { convert_to_boolean(value); ret = Z_TYPE_P(value) == IS_TRUE? 1:0; } break; } } } else { ret = zend_std_has_property(object, name, has_set_exists, cache_slot); } return ret; } /* }}} */ static HashTable *php_snmp_get_gc(zend_object *object, zval **gc_data, int *gc_data_count) /* {{{ */ { *gc_data = NULL; *gc_data_count = 0; return zend_std_get_properties(object); } /* }}} */ /* {{{ php_snmp_get_properties(zval *object) Returns all object properties. Injects SNMP properties into object on first call */ static HashTable *php_snmp_get_properties(zend_object *object) { php_snmp_object *obj; php_snmp_prop_handler *hnd; HashTable *props; zval rv; zend_string *key; obj = php_snmp_fetch_object(object); props = zend_std_get_properties(object); ZEND_HASH_FOREACH_STR_KEY_PTR(&php_snmp_properties, key, hnd) { if (!hnd->read_func || hnd->read_func(obj, &rv) != SUCCESS) { ZVAL_NULL(&rv); } zend_hash_update(props, key, &rv); } ZEND_HASH_FOREACH_END(); return obj->zo.properties; } /* }}} */ /* {{{ */ static int php_snmp_read_info(php_snmp_object *snmp_object, zval *retval) { zval val; array_init(retval); if (snmp_object->session == NULL) { return SUCCESS; } ZVAL_STRINGL(&val, snmp_object->session->peername, strlen(snmp_object->session->peername)); add_assoc_zval(retval, "hostname", &val); ZVAL_LONG(&val, snmp_object->session->remote_port); add_assoc_zval(retval, "port", &val); ZVAL_LONG(&val, snmp_object->session->timeout); add_assoc_zval(retval, "timeout", &val); ZVAL_LONG(&val, snmp_object->session->retries); add_assoc_zval(retval, "retries", &val); return SUCCESS; } /* }}} */ /* {{{ */ static int php_snmp_read_max_oids(php_snmp_object *snmp_object, zval *retval) { if (snmp_object->max_oids > 0) { ZVAL_LONG(retval, snmp_object->max_oids); } else { ZVAL_NULL(retval); } return SUCCESS; } /* }}} */ #define PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(name) \ static int php_snmp_read_##name(php_snmp_object *snmp_object, zval *retval) \ { \ ZVAL_BOOL(retval, snmp_object->name); \ return SUCCESS; \ } PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(oid_increasing_check) PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(quick_print) PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(enum_print) #define PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(name) \ static int php_snmp_read_##name(php_snmp_object *snmp_object, zval *retval) \ { \ ZVAL_LONG(retval, snmp_object->name); \ return SUCCESS; \ } PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(valueretrieval) PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(oid_output_format) PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(exceptions_enabled) /* {{{ */ static int php_snmp_write_info(php_snmp_object *snmp_object, zval *newval) { php_error_docref(NULL, E_WARNING, "info property is read-only"); return FAILURE; } /* }}} */ /* {{{ */ static int php_snmp_write_max_oids(php_snmp_object *snmp_object, zval *newval) { int ret = SUCCESS; zend_long lval; if (Z_TYPE_P(newval) == IS_NULL) { snmp_object->max_oids = 0; return ret; } lval = zval_get_long(newval); if (lval > 0) { snmp_object->max_oids = lval; } else { php_error_docref(NULL, E_WARNING, "max_oids should be positive integer or NULL, got " ZEND_LONG_FMT, lval); } return ret; } /* }}} */ /* {{{ */ static int php_snmp_write_valueretrieval(php_snmp_object *snmp_object, zval *newval) { int ret = SUCCESS; zend_long lval = zval_get_long(newval); if (lval >= 0 && lval <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) { snmp_object->valueretrieval = lval; } else { php_error_docref(NULL, E_WARNING, "Unknown SNMP value retrieval method '" ZEND_LONG_FMT "'", lval); ret = FAILURE; } return ret; } /* }}} */ #define PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(name) \ static int php_snmp_write_##name(php_snmp_object *snmp_object, zval *newval) \ { \ zval ztmp; \ ZVAL_COPY(&ztmp, newval); \ convert_to_boolean(&ztmp); \ newval = &ztmp; \ \ snmp_object->name = Z_TYPE_P(newval) == IS_TRUE? 1 : 0; \ \ return SUCCESS; \ } PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(quick_print) PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(enum_print) PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(oid_increasing_check) /* {{{ */ static int php_snmp_write_oid_output_format(php_snmp_object *snmp_object, zval *newval) { int ret = SUCCESS; zend_long lval = zval_get_long(newval); switch(lval) { case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_UCD: case NETSNMP_OID_OUTPUT_NONE: snmp_object->oid_output_format = lval; break; default: php_error_docref(NULL, E_WARNING, "Unknown SNMP output print format '" ZEND_LONG_FMT "'", lval); ret = FAILURE; break; } return ret; } /* }}} */ /* {{{ */ static int php_snmp_write_exceptions_enabled(php_snmp_object *snmp_object, zval *newval) { int ret = SUCCESS; snmp_object->exceptions_enabled = zval_get_long(newval); return ret; } /* }}} */ static void free_php_snmp_properties(zval *el) /* {{{ */ { pefree(Z_PTR_P(el), 1); } /* }}} */ /* {{{ php_snmp_class_methods[] */ static const zend_function_entry php_snmp_class_methods[] = { PHP_ME(snmp, __construct, arginfo_snmp_create, ZEND_ACC_PUBLIC) PHP_ME(snmp, close, arginfo_snmp_void, ZEND_ACC_PUBLIC) PHP_ME(snmp, setSecurity, arginfo_snmp_setSecurity, ZEND_ACC_PUBLIC) PHP_ME(snmp, get, arginfo_snmp_get, ZEND_ACC_PUBLIC) PHP_ME(snmp, getnext, arginfo_snmp_get, ZEND_ACC_PUBLIC) PHP_ME(snmp, walk, arginfo_snmp_walk, ZEND_ACC_PUBLIC) PHP_ME(snmp, set, arginfo_snmp_set, ZEND_ACC_PUBLIC) PHP_ME(snmp, getErrno, arginfo_snmp_void, ZEND_ACC_PUBLIC) PHP_ME(snmp, getError, arginfo_snmp_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #define PHP_SNMP_PROPERTY_ENTRY_RECORD(name) \ { "" #name "", sizeof("" #name "") - 1, php_snmp_read_##name, php_snmp_write_##name } const php_snmp_prop_handler php_snmp_property_entries[] = { PHP_SNMP_PROPERTY_ENTRY_RECORD(info), PHP_SNMP_PROPERTY_ENTRY_RECORD(max_oids), PHP_SNMP_PROPERTY_ENTRY_RECORD(valueretrieval), PHP_SNMP_PROPERTY_ENTRY_RECORD(quick_print), PHP_SNMP_PROPERTY_ENTRY_RECORD(enum_print), PHP_SNMP_PROPERTY_ENTRY_RECORD(oid_output_format), PHP_SNMP_PROPERTY_ENTRY_RECORD(oid_increasing_check), PHP_SNMP_PROPERTY_ENTRY_RECORD(exceptions_enabled), { NULL, 0, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(snmp) { netsnmp_log_handler *logh; zend_class_entry ce, cex; le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number); init_snmp("snmpapp"); #ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE /* Prevent update of the snmpapp.conf file */ netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1); #endif /* Disable logging, use exit status'es and related variabled to detect errors */ shutdown_snmp_logging(); logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR); if (logh) { logh->pri_max = LOG_ERR; } memcpy(&php_snmp_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); php_snmp_object_handlers.read_property = php_snmp_read_property; php_snmp_object_handlers.write_property = php_snmp_write_property; php_snmp_object_handlers.has_property = php_snmp_has_property; php_snmp_object_handlers.get_properties = php_snmp_get_properties; php_snmp_object_handlers.get_gc = php_snmp_get_gc; /* Register SNMP Class */ INIT_CLASS_ENTRY(ce, "SNMP", php_snmp_class_methods); ce.create_object = php_snmp_object_new; php_snmp_object_handlers.offset = XtOffsetOf(php_snmp_object, zo); php_snmp_object_handlers.clone_obj = NULL; php_snmp_object_handlers.free_obj = php_snmp_object_free_storage; php_snmp_ce = zend_register_internal_class(&ce); /* Register SNMP Class properties */ zend_hash_init(&php_snmp_properties, 0, NULL, free_php_snmp_properties, 1); PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_SUFFIX", NETSNMP_OID_OUTPUT_SUFFIX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_MODULE", NETSNMP_OID_OUTPUT_MODULE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_FULL", NETSNMP_OID_OUTPUT_FULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NUMERIC", NETSNMP_OID_OUTPUT_NUMERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_UCD", NETSNMP_OID_OUTPUT_UCD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NONE", NETSNMP_OID_OUTPUT_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_VALUE_LIBRARY", SNMP_VALUE_LIBRARY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_VALUE_PLAIN", SNMP_VALUE_PLAIN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_VALUE_OBJECT", SNMP_VALUE_OBJECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_BIT_STR", ASN_BIT_STR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OCTET_STR", ASN_OCTET_STR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OPAQUE", ASN_OPAQUE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_NULL", ASN_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_OBJECT_ID", ASN_OBJECT_ID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_IPADDRESS", ASN_IPADDRESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_COUNTER", ASN_GAUGE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_UNSIGNED", ASN_UNSIGNED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_TIMETICKS", ASN_TIMETICKS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_UINTEGER", ASN_UINTEGER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_INTEGER", ASN_INTEGER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SNMP_COUNTER64", ASN_COUNTER64, CONST_CS | CONST_PERSISTENT); REGISTER_SNMP_CLASS_CONST_LONG("VERSION_1", SNMP_VERSION_1); REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2c", SNMP_VERSION_2c); REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2C", SNMP_VERSION_2c); REGISTER_SNMP_CLASS_CONST_LONG("VERSION_3", SNMP_VERSION_3); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_NOERROR", PHP_SNMP_ERRNO_NOERROR); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ANY", PHP_SNMP_ERRNO_ANY); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_GENERIC", PHP_SNMP_ERRNO_GENERIC); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_TIMEOUT", PHP_SNMP_ERRNO_TIMEOUT); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ERROR_IN_REPLY", PHP_SNMP_ERRNO_ERROR_IN_REPLY); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_NOT_INCREASING", PHP_SNMP_ERRNO_OID_NOT_INCREASING); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_PARSING_ERROR", PHP_SNMP_ERRNO_OID_PARSING_ERROR); REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_MULTIPLE_SET_QUERIES", PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES); /* Register SNMPException class */ INIT_CLASS_ENTRY(cex, "SNMPException", NULL); php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(snmp) { snmp_shutdown("snmpapp"); zend_hash_destroy(&php_snmp_properties); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(snmp) { php_info_print_table_start(); php_info_print_table_row(2, "NET-SNMP Support", "enabled"); php_info_print_table_row(2, "NET-SNMP Version", netsnmp_get_version()); php_info_print_table_end(); } /* }}} */ /* {{{ snmp_module_deps[] */ static const zend_module_dep snmp_module_deps[] = { ZEND_MOD_REQUIRED("spl") ZEND_MOD_END }; /* }}} */ /* {{{ snmp_module_entry */ zend_module_entry snmp_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, snmp_module_deps, "snmp", snmp_functions, PHP_MINIT(snmp), PHP_MSHUTDOWN(snmp), NULL, NULL, PHP_MINFO(snmp), PHP_SNMP_VERSION, PHP_MODULE_GLOBALS(snmp), PHP_GINIT(snmp), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #endif
359190.c
/* * Copyright 2005 Juan Lang * Copyright 2005-2006 Robert Shearman (for CodeWeavers) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #define COBJMACROS #define NONAMELESSUNION #include "ntstatus.h" #define WIN32_NO_STATUS #define USE_COM_CONTEXT_DEF #include "objbase.h" #include "ctxtcall.h" #include "oleauto.h" #include "dde.h" #include "winternl.h" #include "combase_private.h" #include "wine/debug.h" #include "wine/heap.h" WINE_DEFAULT_DEBUG_CHANNEL(ole); HINSTANCE hProxyDll; /* Ole32 exports */ extern void WINAPI DestroyRunningObjectTable(void); extern HRESULT WINAPI Ole32DllGetClassObject(REFCLSID rclsid, REFIID riid, void **obj); /* * Number of times CoInitialize is called. It is decreased every time CoUninitialize is called. When it hits 0, the COM libraries are freed */ static LONG com_lockcount; static LONG com_server_process_refcount; struct comclassredirect_data { ULONG size; ULONG flags; DWORD model; GUID clsid; GUID alias; GUID clsid2; GUID tlbid; ULONG name_len; ULONG name_offset; ULONG progid_len; ULONG progid_offset; ULONG clrdata_len; ULONG clrdata_offset; DWORD miscstatus; DWORD miscstatuscontent; DWORD miscstatusthumbnail; DWORD miscstatusicon; DWORD miscstatusdocprint; }; struct ifacepsredirect_data { ULONG size; DWORD mask; GUID iid; ULONG nummethods; GUID tlbid; GUID base; ULONG name_len; ULONG name_offset; }; struct progidredirect_data { ULONG size; DWORD reserved; ULONG clsid_offset; }; struct init_spy { struct list entry; IInitializeSpy *spy; unsigned int id; }; struct registered_ps { struct list entry; IID iid; CLSID clsid; }; static struct list registered_proxystubs = LIST_INIT(registered_proxystubs); static CRITICAL_SECTION cs_registered_ps; static CRITICAL_SECTION_DEBUG psclsid_cs_debug = { 0, 0, &cs_registered_ps, { &psclsid_cs_debug.ProcessLocksList, &psclsid_cs_debug.ProcessLocksList }, 0, 0, { (DWORD_PTR)(__FILE__ ": cs_registered_psclsid_list") } }; static CRITICAL_SECTION cs_registered_ps = { &psclsid_cs_debug, -1, 0, 0, 0, 0 }; /* * TODO: Make this data structure aware of inter-process communication. This * means that parts of this will be exported to rpcss. */ struct registered_class { struct list entry; CLSID clsid; OXID apartment_id; IUnknown *object; DWORD clscontext; DWORD flags; DWORD cookie; void *RpcRegistration; }; static struct list registered_classes = LIST_INIT(registered_classes); static CRITICAL_SECTION registered_classes_cs; static CRITICAL_SECTION_DEBUG registered_classes_cs_debug = { 0, 0, &registered_classes_cs, { &registered_classes_cs_debug.ProcessLocksList, &registered_classes_cs_debug.ProcessLocksList }, 0, 0, { (DWORD_PTR)(__FILE__ ": registered_classes_cs") } }; static CRITICAL_SECTION registered_classes_cs = { &registered_classes_cs_debug, -1, 0, 0, 0, 0 }; IUnknown * com_get_registered_class_object(const struct apartment *apt, REFCLSID rclsid, DWORD clscontext) { struct registered_class *cur; IUnknown *object = NULL; EnterCriticalSection(&registered_classes_cs); LIST_FOR_EACH_ENTRY(cur, &registered_classes, struct registered_class, entry) { if ((apt->oxid == cur->apartment_id) && (clscontext & cur->clscontext) && IsEqualGUID(&cur->clsid, rclsid)) { object = cur->object; IUnknown_AddRef(cur->object); break; } } LeaveCriticalSection(&registered_classes_cs); return object; } static struct init_spy *get_spy_entry(struct tlsdata *tlsdata, unsigned int id) { struct init_spy *spy; LIST_FOR_EACH_ENTRY(spy, &tlsdata->spies, struct init_spy, entry) { if (id == spy->id && spy->spy) return spy; } return NULL; } static NTSTATUS create_key(HKEY *retkey, ACCESS_MASK access, OBJECT_ATTRIBUTES *attr) { NTSTATUS status = NtCreateKey((HANDLE *)retkey, access, attr, 0, NULL, 0, NULL); if (status == STATUS_OBJECT_NAME_NOT_FOUND) { HANDLE subkey, root = attr->RootDirectory; WCHAR *buffer = attr->ObjectName->Buffer; DWORD attrs, pos = 0, i = 0, len = attr->ObjectName->Length / sizeof(WCHAR); UNICODE_STRING str; while (i < len && buffer[i] != '\\') i++; if (i == len) return status; attrs = attr->Attributes; attr->ObjectName = &str; while (i < len) { str.Buffer = buffer + pos; str.Length = (i - pos) * sizeof(WCHAR); status = NtCreateKey(&subkey, access, attr, 0, NULL, 0, NULL); if (attr->RootDirectory != root) NtClose(attr->RootDirectory); if (status) return status; attr->RootDirectory = subkey; while (i < len && buffer[i] == '\\') i++; pos = i; while (i < len && buffer[i] != '\\') i++; } str.Buffer = buffer + pos; str.Length = (i - pos) * sizeof(WCHAR); attr->Attributes = attrs; status = NtCreateKey((HANDLE *)retkey, access, attr, 0, NULL, 0, NULL); if (attr->RootDirectory != root) NtClose(attr->RootDirectory); } return status; } static HKEY classes_root_hkey; static HKEY create_classes_root_hkey(DWORD access) { HKEY hkey, ret = 0; OBJECT_ATTRIBUTES attr; UNICODE_STRING name; attr.Length = sizeof(attr); attr.RootDirectory = 0; attr.ObjectName = &name; attr.Attributes = 0; attr.SecurityDescriptor = NULL; attr.SecurityQualityOfService = NULL; RtlInitUnicodeString(&name, L"\\Registry\\Machine\\Software\\Classes"); if (create_key( &hkey, access, &attr )) return 0; TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey ); if (!(access & KEY_WOW64_64KEY)) { if (!(ret = InterlockedCompareExchangePointer( (void **)&classes_root_hkey, hkey, 0 ))) ret = hkey; else NtClose( hkey ); /* somebody beat us to it */ } else ret = hkey; return ret; } static HKEY get_classes_root_hkey(HKEY hkey, REGSAM access); static LSTATUS create_classes_key(HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey) { OBJECT_ATTRIBUTES attr; UNICODE_STRING nameW; if (!(hkey = get_classes_root_hkey(hkey, access))) return ERROR_INVALID_HANDLE; attr.Length = sizeof(attr); attr.RootDirectory = hkey; attr.ObjectName = &nameW; attr.Attributes = 0; attr.SecurityDescriptor = NULL; attr.SecurityQualityOfService = NULL; RtlInitUnicodeString( &nameW, name ); return RtlNtStatusToDosError(create_key(retkey, access, &attr)); } static HKEY get_classes_root_hkey(HKEY hkey, REGSAM access) { HKEY ret = hkey; const BOOL is_win64 = sizeof(void*) > sizeof(int); const BOOL force_wow32 = is_win64 && (access & KEY_WOW64_32KEY); if (hkey == HKEY_CLASSES_ROOT && ((access & KEY_WOW64_64KEY) || !(ret = classes_root_hkey))) ret = create_classes_root_hkey(MAXIMUM_ALLOWED | (access & KEY_WOW64_64KEY)); if (force_wow32 && ret && ret == classes_root_hkey) { access &= ~KEY_WOW64_32KEY; if (create_classes_key(classes_root_hkey, L"Wow6432Node", access, &hkey)) return 0; ret = hkey; } return ret; } static LSTATUS open_classes_key(HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey) { OBJECT_ATTRIBUTES attr; UNICODE_STRING nameW; if (!(hkey = get_classes_root_hkey(hkey, access))) return ERROR_INVALID_HANDLE; attr.Length = sizeof(attr); attr.RootDirectory = hkey; attr.ObjectName = &nameW; attr.Attributes = 0; attr.SecurityDescriptor = NULL; attr.SecurityQualityOfService = NULL; RtlInitUnicodeString( &nameW, name ); return RtlNtStatusToDosError(NtOpenKey((HANDLE *)retkey, access, &attr)); } HRESULT open_key_for_clsid(REFCLSID clsid, const WCHAR *keyname, REGSAM access, HKEY *subkey) { static const WCHAR clsidW[] = L"CLSID\\"; WCHAR path[CHARS_IN_GUID + ARRAY_SIZE(clsidW) - 1]; LONG res; HKEY key; lstrcpyW(path, clsidW); StringFromGUID2(clsid, path + lstrlenW(clsidW), CHARS_IN_GUID); res = open_classes_key(HKEY_CLASSES_ROOT, path, keyname ? KEY_READ : access, &key); if (res == ERROR_FILE_NOT_FOUND) return REGDB_E_CLASSNOTREG; else if (res != ERROR_SUCCESS) return REGDB_E_READREGDB; if (!keyname) { *subkey = key; return S_OK; } res = open_classes_key(key, keyname, access, subkey); RegCloseKey(key); if (res == ERROR_FILE_NOT_FOUND) return REGDB_E_KEYMISSING; else if (res != ERROR_SUCCESS) return REGDB_E_READREGDB; return S_OK; } /* open HKCR\\AppId\\{string form of appid clsid} key */ HRESULT open_appidkey_from_clsid(REFCLSID clsid, REGSAM access, HKEY *subkey) { static const WCHAR appidkeyW[] = L"AppId\\"; DWORD res; WCHAR buf[CHARS_IN_GUID]; WCHAR keyname[ARRAY_SIZE(appidkeyW) + CHARS_IN_GUID]; DWORD size; HKEY hkey; DWORD type; HRESULT hr; /* read the AppID value under the class's key */ hr = open_key_for_clsid(clsid, NULL, KEY_READ, &hkey); if (FAILED(hr)) return hr; size = sizeof(buf); res = RegQueryValueExW(hkey, L"AppId", NULL, &type, (LPBYTE)buf, &size); RegCloseKey(hkey); if (res == ERROR_FILE_NOT_FOUND) return REGDB_E_KEYMISSING; else if (res != ERROR_SUCCESS || type!=REG_SZ) return REGDB_E_READREGDB; lstrcpyW(keyname, appidkeyW); lstrcatW(keyname, buf); res = open_classes_key(HKEY_CLASSES_ROOT, keyname, access, subkey); if (res == ERROR_FILE_NOT_FOUND) return REGDB_E_KEYMISSING; else if (res != ERROR_SUCCESS) return REGDB_E_READREGDB; return S_OK; } /*********************************************************************** * InternalIsProcessInitialized (combase.@) */ BOOL WINAPI InternalIsProcessInitialized(void) { struct apartment *apt; if (!(apt = apartment_get_current_or_mta())) return FALSE; apartment_release(apt); return TRUE; } /*********************************************************************** * InternalTlsAllocData (combase.@) */ HRESULT WINAPI InternalTlsAllocData(struct tlsdata **data) { if (!(*data = heap_alloc_zero(sizeof(**data)))) return E_OUTOFMEMORY; list_init(&(*data)->spies); NtCurrentTeb()->ReservedForOle = *data; return S_OK; } static void com_cleanup_tlsdata(void) { struct tlsdata *tlsdata = NtCurrentTeb()->ReservedForOle; struct init_spy *cursor, *cursor2; if (!tlsdata) return; if (tlsdata->apt) apartment_release(tlsdata->apt); if (tlsdata->errorinfo) IErrorInfo_Release(tlsdata->errorinfo); if (tlsdata->state) IUnknown_Release(tlsdata->state); LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &tlsdata->spies, struct init_spy, entry) { list_remove(&cursor->entry); if (cursor->spy) IInitializeSpy_Release(cursor->spy); heap_free(cursor); } if (tlsdata->context_token) IObjContext_Release(tlsdata->context_token); heap_free(tlsdata); NtCurrentTeb()->ReservedForOle = NULL; } /*********************************************************************** * FreePropVariantArray (combase.@) */ HRESULT WINAPI FreePropVariantArray(ULONG count, PROPVARIANT *rgvars) { ULONG i; TRACE("%u, %p.\n", count, rgvars); if (!rgvars) return E_INVALIDARG; for (i = 0; i < count; ++i) PropVariantClear(&rgvars[i]); return S_OK; } static HRESULT propvar_validatetype(VARTYPE vt) { switch (vt) { case VT_EMPTY: case VT_NULL: case VT_I1: case VT_I2: case VT_I4: case VT_I8: case VT_R4: case VT_R8: case VT_CY: case VT_DATE: case VT_BSTR: case VT_ERROR: case VT_BOOL: case VT_DECIMAL: case VT_UI1: case VT_UI2: case VT_UI4: case VT_UI8: case VT_INT: case VT_UINT: case VT_LPSTR: case VT_LPWSTR: case VT_FILETIME: case VT_BLOB: case VT_DISPATCH: case VT_UNKNOWN: case VT_STREAM: case VT_STORAGE: case VT_STREAMED_OBJECT: case VT_STORED_OBJECT: case VT_BLOB_OBJECT: case VT_CF: case VT_CLSID: case VT_I1|VT_VECTOR: case VT_I2|VT_VECTOR: case VT_I4|VT_VECTOR: case VT_I8|VT_VECTOR: case VT_R4|VT_VECTOR: case VT_R8|VT_VECTOR: case VT_CY|VT_VECTOR: case VT_DATE|VT_VECTOR: case VT_BSTR|VT_VECTOR: case VT_ERROR|VT_VECTOR: case VT_BOOL|VT_VECTOR: case VT_VARIANT|VT_VECTOR: case VT_UI1|VT_VECTOR: case VT_UI2|VT_VECTOR: case VT_UI4|VT_VECTOR: case VT_UI8|VT_VECTOR: case VT_LPSTR|VT_VECTOR: case VT_LPWSTR|VT_VECTOR: case VT_FILETIME|VT_VECTOR: case VT_CF|VT_VECTOR: case VT_CLSID|VT_VECTOR: case VT_ARRAY|VT_I1: case VT_ARRAY|VT_UI1: case VT_ARRAY|VT_I2: case VT_ARRAY|VT_UI2: case VT_ARRAY|VT_I4: case VT_ARRAY|VT_UI4: case VT_ARRAY|VT_INT: case VT_ARRAY|VT_UINT: case VT_ARRAY|VT_R4: case VT_ARRAY|VT_R8: case VT_ARRAY|VT_CY: case VT_ARRAY|VT_DATE: case VT_ARRAY|VT_BSTR: case VT_ARRAY|VT_BOOL: case VT_ARRAY|VT_DECIMAL: case VT_ARRAY|VT_DISPATCH: case VT_ARRAY|VT_UNKNOWN: case VT_ARRAY|VT_ERROR: case VT_ARRAY|VT_VARIANT: return S_OK; } WARN("Bad type %d\n", vt); return STG_E_INVALIDPARAMETER; } static void propvar_free_cf_array(ULONG count, CLIPDATA *data) { ULONG i; for (i = 0; i < count; ++i) CoTaskMemFree(data[i].pClipData); } /*********************************************************************** * PropVariantClear (combase.@) */ HRESULT WINAPI PropVariantClear(PROPVARIANT *pvar) { HRESULT hr; TRACE("%p.\n", pvar); if (!pvar) return S_OK; hr = propvar_validatetype(pvar->vt); if (FAILED(hr)) { memset(pvar, 0, sizeof(*pvar)); return hr; } switch (pvar->vt) { case VT_EMPTY: case VT_NULL: case VT_I1: case VT_I2: case VT_I4: case VT_I8: case VT_R4: case VT_R8: case VT_CY: case VT_DATE: case VT_ERROR: case VT_BOOL: case VT_DECIMAL: case VT_UI1: case VT_UI2: case VT_UI4: case VT_UI8: case VT_INT: case VT_UINT: case VT_FILETIME: break; case VT_DISPATCH: case VT_UNKNOWN: case VT_STREAM: case VT_STREAMED_OBJECT: case VT_STORAGE: case VT_STORED_OBJECT: if (pvar->u.pStream) IStream_Release(pvar->u.pStream); break; case VT_CLSID: case VT_LPSTR: case VT_LPWSTR: /* pick an arbitrary typed pointer - we don't care about the type * as we are just freeing it */ CoTaskMemFree(pvar->u.puuid); break; case VT_BLOB: case VT_BLOB_OBJECT: CoTaskMemFree(pvar->u.blob.pBlobData); break; case VT_BSTR: SysFreeString(pvar->u.bstrVal); break; case VT_CF: if (pvar->u.pclipdata) { propvar_free_cf_array(1, pvar->u.pclipdata); CoTaskMemFree(pvar->u.pclipdata); } break; default: if (pvar->vt & VT_VECTOR) { ULONG i; switch (pvar->vt & ~VT_VECTOR) { case VT_VARIANT: FreePropVariantArray(pvar->u.capropvar.cElems, pvar->u.capropvar.pElems); break; case VT_CF: propvar_free_cf_array(pvar->u.caclipdata.cElems, pvar->u.caclipdata.pElems); break; case VT_BSTR: for (i = 0; i < pvar->u.cabstr.cElems; i++) SysFreeString(pvar->u.cabstr.pElems[i]); break; case VT_LPSTR: for (i = 0; i < pvar->u.calpstr.cElems; i++) CoTaskMemFree(pvar->u.calpstr.pElems[i]); break; case VT_LPWSTR: for (i = 0; i < pvar->u.calpwstr.cElems; i++) CoTaskMemFree(pvar->u.calpwstr.pElems[i]); break; } if (pvar->vt & ~VT_VECTOR) { /* pick an arbitrary VT_VECTOR structure - they all have the same * memory layout */ CoTaskMemFree(pvar->u.capropvar.pElems); } } else if (pvar->vt & VT_ARRAY) hr = SafeArrayDestroy(pvar->u.parray); else { WARN("Invalid/unsupported type %d\n", pvar->vt); hr = STG_E_INVALIDPARAMETER; } } memset(pvar, 0, sizeof(*pvar)); return hr; } /*********************************************************************** * PropVariantCopy (combase.@) */ HRESULT WINAPI PropVariantCopy(PROPVARIANT *pvarDest, const PROPVARIANT *pvarSrc) { ULONG len; HRESULT hr; TRACE("%p, %p vt %04x.\n", pvarDest, pvarSrc, pvarSrc->vt); hr = propvar_validatetype(pvarSrc->vt); if (FAILED(hr)) return DISP_E_BADVARTYPE; /* this will deal with most cases */ *pvarDest = *pvarSrc; switch (pvarSrc->vt) { case VT_EMPTY: case VT_NULL: case VT_I1: case VT_UI1: case VT_I2: case VT_UI2: case VT_BOOL: case VT_DECIMAL: case VT_I4: case VT_UI4: case VT_R4: case VT_ERROR: case VT_I8: case VT_UI8: case VT_INT: case VT_UINT: case VT_R8: case VT_CY: case VT_DATE: case VT_FILETIME: break; case VT_DISPATCH: case VT_UNKNOWN: case VT_STREAM: case VT_STREAMED_OBJECT: case VT_STORAGE: case VT_STORED_OBJECT: if (pvarDest->u.pStream) IStream_AddRef(pvarDest->u.pStream); break; case VT_CLSID: pvarDest->u.puuid = CoTaskMemAlloc(sizeof(CLSID)); *pvarDest->u.puuid = *pvarSrc->u.puuid; break; case VT_LPSTR: if (pvarSrc->u.pszVal) { len = strlen(pvarSrc->u.pszVal); pvarDest->u.pszVal = CoTaskMemAlloc((len+1)*sizeof(CHAR)); CopyMemory(pvarDest->u.pszVal, pvarSrc->u.pszVal, (len+1)*sizeof(CHAR)); } break; case VT_LPWSTR: if (pvarSrc->u.pwszVal) { len = lstrlenW(pvarSrc->u.pwszVal); pvarDest->u.pwszVal = CoTaskMemAlloc((len+1)*sizeof(WCHAR)); CopyMemory(pvarDest->u.pwszVal, pvarSrc->u.pwszVal, (len+1)*sizeof(WCHAR)); } break; case VT_BLOB: case VT_BLOB_OBJECT: if (pvarSrc->u.blob.pBlobData) { len = pvarSrc->u.blob.cbSize; pvarDest->u.blob.pBlobData = CoTaskMemAlloc(len); CopyMemory(pvarDest->u.blob.pBlobData, pvarSrc->u.blob.pBlobData, len); } break; case VT_BSTR: pvarDest->u.bstrVal = SysAllocString(pvarSrc->u.bstrVal); break; case VT_CF: if (pvarSrc->u.pclipdata) { len = pvarSrc->u.pclipdata->cbSize - sizeof(pvarSrc->u.pclipdata->ulClipFmt); pvarDest->u.pclipdata = CoTaskMemAlloc(sizeof (CLIPDATA)); pvarDest->u.pclipdata->cbSize = pvarSrc->u.pclipdata->cbSize; pvarDest->u.pclipdata->ulClipFmt = pvarSrc->u.pclipdata->ulClipFmt; pvarDest->u.pclipdata->pClipData = CoTaskMemAlloc(len); CopyMemory(pvarDest->u.pclipdata->pClipData, pvarSrc->u.pclipdata->pClipData, len); } break; default: if (pvarSrc->vt & VT_VECTOR) { int elemSize; ULONG i; switch (pvarSrc->vt & ~VT_VECTOR) { case VT_I1: elemSize = sizeof(pvarSrc->u.cVal); break; case VT_UI1: elemSize = sizeof(pvarSrc->u.bVal); break; case VT_I2: elemSize = sizeof(pvarSrc->u.iVal); break; case VT_UI2: elemSize = sizeof(pvarSrc->u.uiVal); break; case VT_BOOL: elemSize = sizeof(pvarSrc->u.boolVal); break; case VT_I4: elemSize = sizeof(pvarSrc->u.lVal); break; case VT_UI4: elemSize = sizeof(pvarSrc->u.ulVal); break; case VT_R4: elemSize = sizeof(pvarSrc->u.fltVal); break; case VT_R8: elemSize = sizeof(pvarSrc->u.dblVal); break; case VT_ERROR: elemSize = sizeof(pvarSrc->u.scode); break; case VT_I8: elemSize = sizeof(pvarSrc->u.hVal); break; case VT_UI8: elemSize = sizeof(pvarSrc->u.uhVal); break; case VT_CY: elemSize = sizeof(pvarSrc->u.cyVal); break; case VT_DATE: elemSize = sizeof(pvarSrc->u.date); break; case VT_FILETIME: elemSize = sizeof(pvarSrc->u.filetime); break; case VT_CLSID: elemSize = sizeof(*pvarSrc->u.puuid); break; case VT_CF: elemSize = sizeof(*pvarSrc->u.pclipdata); break; case VT_BSTR: elemSize = sizeof(pvarSrc->u.bstrVal); break; case VT_LPSTR: elemSize = sizeof(pvarSrc->u.pszVal); break; case VT_LPWSTR: elemSize = sizeof(pvarSrc->u.pwszVal); break; case VT_VARIANT: elemSize = sizeof(*pvarSrc->u.pvarVal); break; default: FIXME("Invalid element type: %ul\n", pvarSrc->vt & ~VT_VECTOR); return E_INVALIDARG; } len = pvarSrc->u.capropvar.cElems; pvarDest->u.capropvar.pElems = len ? CoTaskMemAlloc(len * elemSize) : NULL; if (pvarSrc->vt == (VT_VECTOR | VT_VARIANT)) { for (i = 0; i < len; i++) PropVariantCopy(&pvarDest->u.capropvar.pElems[i], &pvarSrc->u.capropvar.pElems[i]); } else if (pvarSrc->vt == (VT_VECTOR | VT_CF)) { FIXME("Copy clipformats\n"); } else if (pvarSrc->vt == (VT_VECTOR | VT_BSTR)) { for (i = 0; i < len; i++) pvarDest->u.cabstr.pElems[i] = SysAllocString(pvarSrc->u.cabstr.pElems[i]); } else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR)) { size_t strLen; for (i = 0; i < len; i++) { strLen = lstrlenA(pvarSrc->u.calpstr.pElems[i]) + 1; pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen); memcpy(pvarDest->u.calpstr.pElems[i], pvarSrc->u.calpstr.pElems[i], strLen); } } else if (pvarSrc->vt == (VT_VECTOR | VT_LPWSTR)) { size_t strLen; for (i = 0; i < len; i++) { strLen = (lstrlenW(pvarSrc->u.calpwstr.pElems[i]) + 1) * sizeof(WCHAR); pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen); memcpy(pvarDest->u.calpstr.pElems[i], pvarSrc->u.calpstr.pElems[i], strLen); } } else CopyMemory(pvarDest->u.capropvar.pElems, pvarSrc->u.capropvar.pElems, len * elemSize); } else if (pvarSrc->vt & VT_ARRAY) { pvarDest->u.uhVal.QuadPart = 0; return SafeArrayCopy(pvarSrc->u.parray, &pvarDest->u.parray); } else WARN("Invalid/unsupported type %d\n", pvarSrc->vt); } return S_OK; } /*********************************************************************** * CoFileTimeNow (combase.@) */ HRESULT WINAPI CoFileTimeNow(FILETIME *filetime) { GetSystemTimeAsFileTime(filetime); return S_OK; } /****************************************************************************** * CoCreateGuid (combase.@) */ HRESULT WINAPI CoCreateGuid(GUID *guid) { RPC_STATUS status; if (!guid) return E_INVALIDARG; status = UuidCreate(guid); if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK; return HRESULT_FROM_WIN32(status); } /****************************************************************************** * CoQueryProxyBlanket (combase.@) */ HRESULT WINAPI CoQueryProxyBlanket(IUnknown *proxy, DWORD *authn_service, DWORD *authz_service, OLECHAR **servername, DWORD *authn_level, DWORD *imp_level, void **auth_info, DWORD *capabilities) { IClientSecurity *client_security; HRESULT hr; TRACE("%p, %p, %p, %p, %p, %p, %p, %p.\n", proxy, authn_service, authz_service, servername, authn_level, imp_level, auth_info, capabilities); hr = IUnknown_QueryInterface(proxy, &IID_IClientSecurity, (void **)&client_security); if (SUCCEEDED(hr)) { hr = IClientSecurity_QueryBlanket(client_security, proxy, authn_service, authz_service, servername, authn_level, imp_level, auth_info, capabilities); IClientSecurity_Release(client_security); } if (FAILED(hr)) ERR("-- failed with %#x.\n", hr); return hr; } /****************************************************************************** * CoSetProxyBlanket (combase.@) */ HRESULT WINAPI CoSetProxyBlanket(IUnknown *proxy, DWORD authn_service, DWORD authz_service, OLECHAR *servername, DWORD authn_level, DWORD imp_level, void *auth_info, DWORD capabilities) { IClientSecurity *client_security; HRESULT hr; TRACE("%p, %u, %u, %p, %u, %u, %p, %#x.\n", proxy, authn_service, authz_service, servername, authn_level, imp_level, auth_info, capabilities); hr = IUnknown_QueryInterface(proxy, &IID_IClientSecurity, (void **)&client_security); if (SUCCEEDED(hr)) { hr = IClientSecurity_SetBlanket(client_security, proxy, authn_service, authz_service, servername, authn_level, imp_level, auth_info, capabilities); IClientSecurity_Release(client_security); } if (FAILED(hr)) ERR("-- failed with %#x.\n", hr); return hr; } /*********************************************************************** * CoCopyProxy (combase.@) */ HRESULT WINAPI CoCopyProxy(IUnknown *proxy, IUnknown **proxy_copy) { IClientSecurity *client_security; HRESULT hr; TRACE("%p, %p.\n", proxy, proxy_copy); hr = IUnknown_QueryInterface(proxy, &IID_IClientSecurity, (void **)&client_security); if (SUCCEEDED(hr)) { hr = IClientSecurity_CopyProxy(client_security, proxy, proxy_copy); IClientSecurity_Release(client_security); } if (FAILED(hr)) ERR("-- failed with %#x.\n", hr); return hr; } /*********************************************************************** * CoQueryClientBlanket (combase.@) */ HRESULT WINAPI CoQueryClientBlanket(DWORD *authn_service, DWORD *authz_service, OLECHAR **servername, DWORD *authn_level, DWORD *imp_level, RPC_AUTHZ_HANDLE *privs, DWORD *capabilities) { IServerSecurity *server_security; HRESULT hr; TRACE("%p, %p, %p, %p, %p, %p, %p.\n", authn_service, authz_service, servername, authn_level, imp_level, privs, capabilities); hr = CoGetCallContext(&IID_IServerSecurity, (void **)&server_security); if (SUCCEEDED(hr)) { hr = IServerSecurity_QueryBlanket(server_security, authn_service, authz_service, servername, authn_level, imp_level, privs, capabilities); IServerSecurity_Release(server_security); } return hr; } /*********************************************************************** * CoImpersonateClient (combase.@) */ HRESULT WINAPI CoImpersonateClient(void) { IServerSecurity *server_security; HRESULT hr; TRACE("\n"); hr = CoGetCallContext(&IID_IServerSecurity, (void **)&server_security); if (SUCCEEDED(hr)) { hr = IServerSecurity_ImpersonateClient(server_security); IServerSecurity_Release(server_security); } return hr; } /*********************************************************************** * CoRevertToSelf (combase.@) */ HRESULT WINAPI CoRevertToSelf(void) { IServerSecurity *server_security; HRESULT hr; TRACE("\n"); hr = CoGetCallContext(&IID_IServerSecurity, (void **)&server_security); if (SUCCEEDED(hr)) { hr = IServerSecurity_RevertToSelf(server_security); IServerSecurity_Release(server_security); } return hr; } /*********************************************************************** * CoInitializeSecurity (combase.@) */ HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR sd, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE *asAuthSvc, void *reserved1, DWORD authn_level, DWORD imp_level, void *reserved2, DWORD capabilities, void *reserved3) { FIXME("%p, %d, %p, %p, %d, %d, %p, %d, %p stub\n", sd, cAuthSvc, asAuthSvc, reserved1, authn_level, imp_level, reserved2, capabilities, reserved3); return S_OK; } /*********************************************************************** * CoGetObjectContext (combase.@) */ HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv) { IObjContext *context; HRESULT hr; TRACE("%s, %p.\n", debugstr_guid(riid), ppv); *ppv = NULL; hr = CoGetContextToken((ULONG_PTR *)&context); if (FAILED(hr)) return hr; return IObjContext_QueryInterface(context, riid, ppv); } /*********************************************************************** * CoGetDefaultContext (combase.@) */ HRESULT WINAPI CoGetDefaultContext(APTTYPE type, REFIID riid, void **obj) { FIXME("%d, %s, %p stub\n", type, debugstr_guid(riid), obj); return E_NOINTERFACE; } /*********************************************************************** * CoGetCallState (combase.@) */ HRESULT WINAPI CoGetCallState(int arg1, ULONG *arg2) { FIXME("%d, %p.\n", arg1, arg2); return E_NOTIMPL; } /*********************************************************************** * CoGetActivationState (combase.@) */ HRESULT WINAPI CoGetActivationState(GUID guid, DWORD arg2, DWORD *arg3) { FIXME("%s, %x, %p.\n", debugstr_guid(&guid), arg2, arg3); return E_NOTIMPL; } /****************************************************************************** * CoGetTreatAsClass (combase.@) */ HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, CLSID *clsidNew) { WCHAR buffW[CHARS_IN_GUID]; LONG len = sizeof(buffW); HRESULT hr = S_OK; HKEY hkey = NULL; TRACE("%s, %p.\n", debugstr_guid(clsidOld), clsidNew); if (!clsidOld || !clsidNew) return E_INVALIDARG; *clsidNew = *clsidOld; hr = open_key_for_clsid(clsidOld, L"TreatAs", KEY_READ, &hkey); if (FAILED(hr)) { hr = S_FALSE; goto done; } if (RegQueryValueW(hkey, NULL, buffW, &len)) { hr = S_FALSE; goto done; } hr = CLSIDFromString(buffW, clsidNew); if (FAILED(hr)) ERR("Failed to get CLSID from string %s, hr %#x.\n", debugstr_w(buffW), hr); done: if (hkey) RegCloseKey(hkey); return hr; } /****************************************************************************** * ProgIDFromCLSID (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *progid) { ACTCTX_SECTION_KEYED_DATA data; LONG progidlen = 0; HKEY hkey; HRESULT hr; if (!progid) return E_INVALIDARG; *progid = NULL; data.cbSize = sizeof(data); if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, clsid, &data)) { struct comclassredirect_data *comclass = (struct comclassredirect_data *)data.lpData; if (comclass->progid_len) { WCHAR *ptrW; *progid = CoTaskMemAlloc(comclass->progid_len + sizeof(WCHAR)); if (!*progid) return E_OUTOFMEMORY; ptrW = (WCHAR *)((BYTE *)comclass + comclass->progid_offset); memcpy(*progid, ptrW, comclass->progid_len + sizeof(WCHAR)); return S_OK; } else return REGDB_E_CLASSNOTREG; } hr = open_key_for_clsid(clsid, L"ProgID", KEY_READ, &hkey); if (FAILED(hr)) return hr; if (RegQueryValueW(hkey, NULL, NULL, &progidlen)) hr = REGDB_E_CLASSNOTREG; if (hr == S_OK) { *progid = CoTaskMemAlloc(progidlen * sizeof(WCHAR)); if (*progid) { if (RegQueryValueW(hkey, NULL, *progid, &progidlen)) { hr = REGDB_E_CLASSNOTREG; CoTaskMemFree(*progid); *progid = NULL; } } else hr = E_OUTOFMEMORY; } RegCloseKey(hkey); return hr; } static inline BOOL is_valid_hex(WCHAR c) { if (!(((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')))) return FALSE; return TRUE; } static const BYTE guid_conv_table[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 0x30 */ 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 */ 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf /* 0x60 */ }; static BOOL guid_from_string(LPCWSTR s, GUID *id) { int i; if (!s || s[0] != '{') { memset(id, 0, sizeof(*id)); if (!s) return TRUE; return FALSE; } TRACE("%s -> %p\n", debugstr_w(s), id); /* In form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */ id->Data1 = 0; for (i = 1; i < 9; ++i) { if (!is_valid_hex(s[i])) return FALSE; id->Data1 = (id->Data1 << 4) | guid_conv_table[s[i]]; } if (s[9] != '-') return FALSE; id->Data2 = 0; for (i = 10; i < 14; ++i) { if (!is_valid_hex(s[i])) return FALSE; id->Data2 = (id->Data2 << 4) | guid_conv_table[s[i]]; } if (s[14] != '-') return FALSE; id->Data3 = 0; for (i = 15; i < 19; ++i) { if (!is_valid_hex(s[i])) return FALSE; id->Data3 = (id->Data3 << 4) | guid_conv_table[s[i]]; } if (s[19] != '-') return FALSE; for (i = 20; i < 37; i += 2) { if (i == 24) { if (s[i] != '-') return FALSE; i++; } if (!is_valid_hex(s[i]) || !is_valid_hex(s[i + 1])) return FALSE; id->Data4[(i - 20) / 2] = guid_conv_table[s[i]] << 4 | guid_conv_table[s[i + 1]]; } if (s[37] == '}' && s[38] == '\0') return TRUE; return FALSE; } static HRESULT clsid_from_string_reg(LPCOLESTR progid, CLSID *clsid) { WCHAR buf2[CHARS_IN_GUID]; LONG buf2len = sizeof(buf2); HKEY xhkey; WCHAR *buf; memset(clsid, 0, sizeof(*clsid)); buf = heap_alloc((lstrlenW(progid) + 8) * sizeof(WCHAR)); if (!buf) return E_OUTOFMEMORY; lstrcpyW(buf, progid); lstrcatW(buf, L"\\CLSID"); if (open_classes_key(HKEY_CLASSES_ROOT, buf, MAXIMUM_ALLOWED, &xhkey)) { heap_free(buf); WARN("couldn't open key for ProgID %s\n", debugstr_w(progid)); return CO_E_CLASSSTRING; } heap_free(buf); if (RegQueryValueW(xhkey, NULL, buf2, &buf2len)) { RegCloseKey(xhkey); WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid)); return CO_E_CLASSSTRING; } RegCloseKey(xhkey); return guid_from_string(buf2, clsid) ? S_OK : CO_E_CLASSSTRING; } /****************************************************************************** * CLSIDFromProgID (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CLSIDFromProgID(LPCOLESTR progid, CLSID *clsid) { ACTCTX_SECTION_KEYED_DATA data; if (!progid || !clsid) return E_INVALIDARG; data.cbSize = sizeof(data); if (FindActCtxSectionStringW(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION, progid, &data)) { struct progidredirect_data *progiddata = (struct progidredirect_data *)data.lpData; CLSID *alias = (CLSID *)((BYTE *)data.lpSectionBase + progiddata->clsid_offset); *clsid = *alias; return S_OK; } return clsid_from_string_reg(progid, clsid); } /****************************************************************************** * CLSIDFromProgIDEx (combase.@) */ HRESULT WINAPI CLSIDFromProgIDEx(LPCOLESTR progid, CLSID *clsid) { FIXME("%s, %p: semi-stub\n", debugstr_w(progid), clsid); return CLSIDFromProgID(progid, clsid); } /****************************************************************************** * CLSIDFromString (combase.@) */ HRESULT WINAPI CLSIDFromString(LPCOLESTR str, LPCLSID clsid) { CLSID tmp_id; HRESULT hr; if (!clsid) return E_INVALIDARG; if (guid_from_string(str, clsid)) return S_OK; /* It appears a ProgID is also valid */ hr = clsid_from_string_reg(str, &tmp_id); if (SUCCEEDED(hr)) *clsid = tmp_id; return hr; } /****************************************************************************** * IIDFromString (combase.@) */ HRESULT WINAPI IIDFromString(LPCOLESTR str, IID *iid) { TRACE("%s, %p\n", debugstr_w(str), iid); if (!str) { memset(iid, 0, sizeof(*iid)); return S_OK; } /* length mismatch is a special case */ if (lstrlenW(str) + 1 != CHARS_IN_GUID) return E_INVALIDARG; if (str[0] != '{') return CO_E_IIDSTRING; return guid_from_string(str, iid) ? S_OK : CO_E_IIDSTRING; } /****************************************************************************** * StringFromCLSID (combase.@) */ HRESULT WINAPI StringFromCLSID(REFCLSID clsid, LPOLESTR *str) { if (!(*str = CoTaskMemAlloc(CHARS_IN_GUID * sizeof(WCHAR)))) return E_OUTOFMEMORY; StringFromGUID2(clsid, *str, CHARS_IN_GUID); return S_OK; } /****************************************************************************** * StringFromGUID2 (combase.@) */ INT WINAPI StringFromGUID2(REFGUID guid, LPOLESTR str, INT cmax) { if (!guid || cmax < CHARS_IN_GUID) return 0; swprintf(str, CHARS_IN_GUID, L"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid->Data1, guid->Data2, guid->Data3, guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]); return CHARS_IN_GUID; } static void init_multi_qi(DWORD count, MULTI_QI *mqi, HRESULT hr) { ULONG i; for (i = 0; i < count; i++) { mqi[i].pItf = NULL; mqi[i].hr = hr; } } static HRESULT return_multi_qi(IUnknown *unk, DWORD count, MULTI_QI *mqi, BOOL include_unk) { ULONG index = 0, fetched = 0; if (include_unk) { mqi[0].hr = S_OK; mqi[0].pItf = unk; index = fetched = 1; } for (; index < count; index++) { mqi[index].hr = IUnknown_QueryInterface(unk, mqi[index].pIID, (void **)&mqi[index].pItf); if (mqi[index].hr == S_OK) fetched++; } if (!include_unk) IUnknown_Release(unk); if (fetched == 0) return E_NOINTERFACE; return fetched == count ? S_OK : CO_S_NOTALLINTERFACES; } /*********************************************************************** * CoGetInstanceFromFile (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoGetInstanceFromFile(COSERVERINFO *server_info, CLSID *rclsid, IUnknown *outer, DWORD cls_context, DWORD grfmode, OLECHAR *filename, DWORD count, MULTI_QI *results) { IPersistFile *pf = NULL; IUnknown *obj = NULL; CLSID clsid; HRESULT hr; if (!count || !results) return E_INVALIDARG; if (server_info) FIXME("() non-NULL server_info not supported\n"); init_multi_qi(count, results, E_NOINTERFACE); if (!rclsid) { hr = GetClassFile(filename, &clsid); if (FAILED(hr)) { ERR("Failed to get CLSID from a file.\n"); return hr; } rclsid = &clsid; } hr = CoCreateInstance(rclsid, outer, cls_context, &IID_IUnknown, (void **)&obj); if (hr != S_OK) { init_multi_qi(count, results, hr); return hr; } /* Init from file */ hr = IUnknown_QueryInterface(obj, &IID_IPersistFile, (void **)&pf); if (FAILED(hr)) { init_multi_qi(count, results, hr); IUnknown_Release(obj); return hr; } hr = IPersistFile_Load(pf, filename, grfmode); IPersistFile_Release(pf); if (SUCCEEDED(hr)) return return_multi_qi(obj, count, results, FALSE); else { init_multi_qi(count, results, hr); IUnknown_Release(obj); return hr; } } /*********************************************************************** * CoGetInstanceFromIStorage (combase.@) */ HRESULT WINAPI CoGetInstanceFromIStorage(COSERVERINFO *server_info, CLSID *rclsid, IUnknown *outer, DWORD cls_context, IStorage *storage, DWORD count, MULTI_QI *results) { IPersistStorage *ps = NULL; IUnknown *obj = NULL; STATSTG stat; HRESULT hr; if (!count || !results || !storage) return E_INVALIDARG; if (server_info) FIXME("() non-NULL server_info not supported\n"); init_multi_qi(count, results, E_NOINTERFACE); if (!rclsid) { memset(&stat.clsid, 0, sizeof(stat.clsid)); hr = IStorage_Stat(storage, &stat, STATFLAG_NONAME); if (FAILED(hr)) { ERR("Failed to get CLSID from a storage.\n"); return hr; } rclsid = &stat.clsid; } hr = CoCreateInstance(rclsid, outer, cls_context, &IID_IUnknown, (void **)&obj); if (hr != S_OK) return hr; /* Init from IStorage */ hr = IUnknown_QueryInterface(obj, &IID_IPersistStorage, (void **)&ps); if (FAILED(hr)) ERR("failed to get IPersistStorage\n"); if (ps) { IPersistStorage_Load(ps, storage); IPersistStorage_Release(ps); } return return_multi_qi(obj, count, results, FALSE); } /*********************************************************************** * CoCreateInstance (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoCreateInstance(REFCLSID rclsid, IUnknown *outer, DWORD cls_context, REFIID riid, void **obj) { MULTI_QI multi_qi = { .pIID = riid }; HRESULT hr; TRACE("%s, %p, %#x, %s, %p.\n", debugstr_guid(rclsid), outer, cls_context, debugstr_guid(riid), obj); if (!obj) return E_POINTER; hr = CoCreateInstanceEx(rclsid, outer, cls_context, NULL, 1, &multi_qi); *obj = multi_qi.pItf; return hr; } /*********************************************************************** * CoCreateInstanceEx (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoCreateInstanceEx(REFCLSID rclsid, IUnknown *outer, DWORD cls_context, COSERVERINFO *server_info, ULONG count, MULTI_QI *results) { IClassFactory *factory; IUnknown *unk = NULL; CLSID clsid; HRESULT hr; TRACE("%s, %p, %#x, %p, %u, %p\n", debugstr_guid(rclsid), outer, cls_context, server_info, count, results); if (!count || !results) return E_INVALIDARG; if (server_info) FIXME("Server info is not supported.\n"); init_multi_qi(count, results, E_NOINTERFACE); hr = CoGetTreatAsClass(rclsid, &clsid); if (FAILED(hr)) clsid = *rclsid; hr = CoGetClassObject(&clsid, cls_context, NULL, &IID_IClassFactory, (void **)&factory); if (FAILED(hr)) return hr; hr = IClassFactory_CreateInstance(factory, outer, results[0].pIID, (void **)&unk); IClassFactory_Release(factory); if (FAILED(hr)) { if (hr == CLASS_E_NOAGGREGATION && outer) FIXME("Class %s does not support aggregation\n", debugstr_guid(&clsid)); else FIXME("no instance created for interface %s of class %s, hr %#x.\n", debugstr_guid(results[0].pIID), debugstr_guid(&clsid), hr); return hr; } return return_multi_qi(unk, count, results, TRUE); } /*********************************************************************** * CoGetClassObject (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoGetClassObject(REFCLSID rclsid, DWORD clscontext, COSERVERINFO *server_info, REFIID riid, void **obj) { struct class_reg_data clsreg = { 0 }; HRESULT hr = E_UNEXPECTED; IUnknown *registered_obj; struct apartment *apt; TRACE("%s, %s\n", debugstr_guid(rclsid), debugstr_guid(riid)); if (!obj) return E_INVALIDARG; *obj = NULL; if (!(apt = apartment_get_current_or_mta())) { ERR("apartment not initialised\n"); return CO_E_NOTINITIALIZED; } if (server_info) FIXME("server_info name %s, authinfo %p\n", debugstr_w(server_info->pwszName), server_info->pAuthInfo); if (clscontext & CLSCTX_INPROC_SERVER) { if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler) || IsEqualCLSID(rclsid, &CLSID_GlobalOptions) || IsEqualCLSID(rclsid, &CLSID_ManualResetEvent) || IsEqualCLSID(rclsid, &CLSID_StdGlobalInterfaceTable)) { apartment_release(apt); return Ole32DllGetClassObject(rclsid, riid, obj); } } if (clscontext & CLSCTX_INPROC) { ACTCTX_SECTION_KEYED_DATA data; data.cbSize = sizeof(data); /* search activation context first */ if (FindActCtxSectionGuid(FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, rclsid, &data)) { struct comclassredirect_data *comclass = (struct comclassredirect_data *)data.lpData; clsreg.u.actctx.module_name = (WCHAR *)((BYTE *)data.lpSectionBase + comclass->name_offset); clsreg.u.actctx.hactctx = data.hActCtx; clsreg.u.actctx.threading_model = comclass->model; clsreg.origin = CLASS_REG_ACTCTX; hr = apartment_get_inproc_class_object(apt, &clsreg, &comclass->clsid, riid, !(clscontext & WINE_CLSCTX_DONT_HOST), obj); ReleaseActCtx(data.hActCtx); apartment_release(apt); return hr; } } /* * First, try and see if we can't match the class ID with one of the * registered classes. */ if ((registered_obj = com_get_registered_class_object(apt, rclsid, clscontext))) { hr = IUnknown_QueryInterface(registered_obj, riid, obj); IUnknown_Release(registered_obj); apartment_release(apt); return hr; } /* First try in-process server */ if (clscontext & CLSCTX_INPROC_SERVER) { HKEY hkey; hr = open_key_for_clsid(rclsid, L"InprocServer32", KEY_READ, &hkey); if (FAILED(hr)) { if (hr == REGDB_E_CLASSNOTREG) ERR("class %s not registered\n", debugstr_guid(rclsid)); else if (hr == REGDB_E_KEYMISSING) { WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid)); hr = REGDB_E_CLASSNOTREG; } } if (SUCCEEDED(hr)) { clsreg.u.hkey = hkey; clsreg.origin = CLASS_REG_REGISTRY; hr = apartment_get_inproc_class_object(apt, &clsreg, rclsid, riid, !(clscontext & WINE_CLSCTX_DONT_HOST), obj); RegCloseKey(hkey); } /* return if we got a class, otherwise fall through to one of the * other types */ if (SUCCEEDED(hr)) { apartment_release(apt); return hr; } } /* Next try in-process handler */ if (clscontext & CLSCTX_INPROC_HANDLER) { HKEY hkey; hr = open_key_for_clsid(rclsid, L"InprocHandler32", KEY_READ, &hkey); if (FAILED(hr)) { if (hr == REGDB_E_CLASSNOTREG) ERR("class %s not registered\n", debugstr_guid(rclsid)); else if (hr == REGDB_E_KEYMISSING) { WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid)); hr = REGDB_E_CLASSNOTREG; } } if (SUCCEEDED(hr)) { clsreg.u.hkey = hkey; clsreg.origin = CLASS_REG_REGISTRY; hr = apartment_get_inproc_class_object(apt, &clsreg, rclsid, riid, !(clscontext & WINE_CLSCTX_DONT_HOST), obj); RegCloseKey(hkey); } /* return if we got a class, otherwise fall through to one of the * other types */ if (SUCCEEDED(hr)) { apartment_release(apt); return hr; } } apartment_release(apt); /* Next try out of process */ if (clscontext & CLSCTX_LOCAL_SERVER) { hr = rpc_get_local_class_object(rclsid, riid, obj); if (SUCCEEDED(hr)) return hr; } /* Finally try remote: this requires networked DCOM (a lot of work) */ if (clscontext & CLSCTX_REMOTE_SERVER) { FIXME ("CLSCTX_REMOTE_SERVER not supported\n"); hr = REGDB_E_CLASSNOTREG; } if (FAILED(hr)) ERR("no class object %s could be created for context %#x\n", debugstr_guid(rclsid), clscontext); return hr; } /*********************************************************************** * CoFreeUnusedLibraries (combase.@) */ void WINAPI DECLSPEC_HOTPATCH CoFreeUnusedLibraries(void) { CoFreeUnusedLibrariesEx(INFINITE, 0); } /*********************************************************************** * CoGetCallContext (combase.@) */ HRESULT WINAPI CoGetCallContext(REFIID riid, void **obj) { struct tlsdata *tlsdata; HRESULT hr; TRACE("%s, %p\n", debugstr_guid(riid), obj); if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (!tlsdata->call_state) return RPC_E_CALL_COMPLETE; return IUnknown_QueryInterface(tlsdata->call_state, riid, obj); } /*********************************************************************** * CoSwitchCallContext (combase.@) */ HRESULT WINAPI CoSwitchCallContext(IUnknown *context, IUnknown **old_context) { struct tlsdata *tlsdata; HRESULT hr; TRACE("%p, %p\n", context, old_context); if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; /* Reference counts are not touched. */ *old_context = tlsdata->call_state; tlsdata->call_state = context; return S_OK; } /****************************************************************************** * CoRegisterInitializeSpy (combase.@) */ HRESULT WINAPI CoRegisterInitializeSpy(IInitializeSpy *spy, ULARGE_INTEGER *cookie) { struct tlsdata *tlsdata; struct init_spy *entry; unsigned int id; HRESULT hr; TRACE("%p, %p\n", spy, cookie); if (!spy || !cookie) return E_INVALIDARG; if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; hr = IInitializeSpy_QueryInterface(spy, &IID_IInitializeSpy, (void **)&spy); if (FAILED(hr)) return hr; entry = heap_alloc(sizeof(*entry)); if (!entry) { IInitializeSpy_Release(spy); return E_OUTOFMEMORY; } entry->spy = spy; id = 0; while (get_spy_entry(tlsdata, id) != NULL) { id++; } entry->id = id; list_add_head(&tlsdata->spies, &entry->entry); cookie->u.HighPart = GetCurrentThreadId(); cookie->u.LowPart = entry->id; return S_OK; } /****************************************************************************** * CoRevokeInitializeSpy (combase.@) */ HRESULT WINAPI CoRevokeInitializeSpy(ULARGE_INTEGER cookie) { struct tlsdata *tlsdata; struct init_spy *spy; HRESULT hr; TRACE("%s\n", wine_dbgstr_longlong(cookie.QuadPart)); if (cookie.u.HighPart != GetCurrentThreadId()) return E_INVALIDARG; if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (!(spy = get_spy_entry(tlsdata, cookie.u.LowPart))) return E_INVALIDARG; IInitializeSpy_Release(spy->spy); spy->spy = NULL; if (!tlsdata->spies_lock) { list_remove(&spy->entry); heap_free(spy); } return S_OK; } static BOOL com_peek_message(struct apartment *apt, MSG *msg) { /* First try to retrieve messages for incoming COM calls to the apartment window */ return (apt->win && PeekMessageW(msg, apt->win, 0, 0, PM_REMOVE | PM_NOYIELD)) || /* Next retrieve other messages necessary for the app to remain responsive */ PeekMessageW(msg, NULL, WM_DDE_FIRST, WM_DDE_LAST, PM_REMOVE | PM_NOYIELD) || PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT | PM_QS_SENDMESSAGE | PM_REMOVE | PM_NOYIELD); } /*********************************************************************** * CoWaitForMultipleHandles (combase.@) */ HRESULT WINAPI CoWaitForMultipleHandles(DWORD flags, DWORD timeout, ULONG handle_count, HANDLE *handles, DWORD *index) { BOOL check_apc = !!(flags & COWAIT_ALERTABLE), post_quit = FALSE, message_loop; DWORD start_time, wait_flags = 0; struct tlsdata *tlsdata; struct apartment *apt; UINT exit_code; HRESULT hr; TRACE("%#x, %#x, %u, %p, %p\n", flags, timeout, handle_count, handles, index); if (!index) return E_INVALIDARG; *index = 0; if (!handles) return E_INVALIDARG; if (!handle_count) return RPC_E_NO_SYNC; if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; apt = com_get_current_apt(); message_loop = apt && !apt->multi_threaded; if (flags & COWAIT_WAITALL) wait_flags |= MWMO_WAITALL; if (flags & COWAIT_ALERTABLE) wait_flags |= MWMO_ALERTABLE; start_time = GetTickCount(); while (TRUE) { DWORD now = GetTickCount(), res; if (now - start_time > timeout) { hr = RPC_S_CALLPENDING; break; } if (message_loop) { TRACE("waiting for rpc completion or window message\n"); res = WAIT_TIMEOUT; if (check_apc) { res = WaitForMultipleObjectsEx(handle_count, handles, !!(flags & COWAIT_WAITALL), 0, TRUE); check_apc = FALSE; } if (res == WAIT_TIMEOUT) res = MsgWaitForMultipleObjectsEx(handle_count, handles, timeout == INFINITE ? INFINITE : start_time + timeout - now, QS_SENDMESSAGE | QS_ALLPOSTMESSAGE | QS_PAINT, wait_flags); if (res == WAIT_OBJECT_0 + handle_count) /* messages available */ { int msg_count = 0; MSG msg; /* call message filter */ if (apt->filter) { PENDINGTYPE pendingtype = tlsdata->pending_call_count_server ? PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL; DWORD be_handled = IMessageFilter_MessagePending(apt->filter, 0 /* FIXME */, now - start_time, pendingtype); TRACE("IMessageFilter_MessagePending returned %d\n", be_handled); switch (be_handled) { case PENDINGMSG_CANCELCALL: WARN("call canceled\n"); hr = RPC_E_CALL_CANCELED; break; case PENDINGMSG_WAITNOPROCESS: case PENDINGMSG_WAITDEFPROCESS: default: /* FIXME: MSDN is very vague about the difference * between WAITNOPROCESS and WAITDEFPROCESS - there * appears to be none, so it is possibly a left-over * from the 16-bit world. */ break; } } if (!apt->win) { /* If window is NULL on apartment, peek at messages so that it will not trigger * MsgWaitForMultipleObjects next time. */ PeekMessageW(NULL, NULL, 0, 0, PM_QS_POSTMESSAGE | PM_NOREMOVE | PM_NOYIELD); } /* Some apps (e.g. Visio 2010) don't handle WM_PAINT properly and loop forever, * so after processing 100 messages we go back to checking the wait handles */ while (msg_count++ < 100 && com_peek_message(apt, &msg)) { if (msg.message == WM_QUIT) { TRACE("Received WM_QUIT message\n"); post_quit = TRUE; exit_code = msg.wParam; } else { TRACE("Received message whilst waiting for RPC: 0x%04x\n", msg.message); TranslateMessage(&msg); DispatchMessageW(&msg); } } continue; } } else { TRACE("Waiting for rpc completion\n"); res = WaitForMultipleObjectsEx(handle_count, handles, !!(flags & COWAIT_WAITALL), (timeout == INFINITE) ? INFINITE : start_time + timeout - now, !!(flags & COWAIT_ALERTABLE)); } switch (res) { case WAIT_TIMEOUT: hr = RPC_S_CALLPENDING; break; case WAIT_FAILED: hr = HRESULT_FROM_WIN32(GetLastError()); break; default: *index = res; break; } break; } if (post_quit) PostQuitMessage(exit_code); TRACE("-- 0x%08x\n", hr); return hr; } /****************************************************************************** * CoRegisterMessageFilter (combase.@) */ HRESULT WINAPI CoRegisterMessageFilter(IMessageFilter *filter, IMessageFilter **ret_filter) { IMessageFilter *old_filter; struct apartment *apt; TRACE("%p, %p\n", filter, ret_filter); apt = com_get_current_apt(); /* Can't set a message filter in a multi-threaded apartment */ if (!apt || apt->multi_threaded) { WARN("Can't set message filter in MTA or uninitialized apt\n"); return CO_E_NOT_SUPPORTED; } if (filter) IMessageFilter_AddRef(filter); EnterCriticalSection(&apt->cs); old_filter = apt->filter; apt->filter = filter; LeaveCriticalSection(&apt->cs); if (ret_filter) *ret_filter = old_filter; else if (old_filter) IMessageFilter_Release(old_filter); return S_OK; } static void com_revoke_all_ps_clsids(void) { struct registered_ps *cur, *cur2; EnterCriticalSection(&cs_registered_ps); LIST_FOR_EACH_ENTRY_SAFE(cur, cur2, &registered_proxystubs, struct registered_ps, entry) { list_remove(&cur->entry); heap_free(cur); } LeaveCriticalSection(&cs_registered_ps); } static HRESULT get_ps_clsid_from_registry(const WCHAR* path, REGSAM access, CLSID *pclsid) { WCHAR value[CHARS_IN_GUID]; HKEY hkey; DWORD len; access |= KEY_READ; if (open_classes_key(HKEY_CLASSES_ROOT, path, access, &hkey)) return REGDB_E_IIDNOTREG; len = sizeof(value); if (ERROR_SUCCESS != RegQueryValueExW(hkey, NULL, NULL, NULL, (BYTE *)value, &len)) return REGDB_E_IIDNOTREG; RegCloseKey(hkey); if (CLSIDFromString(value, pclsid) != NOERROR) return REGDB_E_IIDNOTREG; return S_OK; } /***************************************************************************** * CoGetPSClsid (combase.@) */ HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid) { static const WCHAR interfaceW[] = L"Interface\\"; static const WCHAR psW[] = L"\\ProxyStubClsid32"; WCHAR path[ARRAY_SIZE(interfaceW) - 1 + CHARS_IN_GUID - 1 + ARRAY_SIZE(psW)]; ACTCTX_SECTION_KEYED_DATA data; struct registered_ps *cur; REGSAM opposite = (sizeof(void*) > sizeof(int)) ? KEY_WOW64_32KEY : KEY_WOW64_64KEY; BOOL is_wow64; HRESULT hr; TRACE("%s, %p\n", debugstr_guid(riid), pclsid); if (!InternalIsProcessInitialized()) { ERR("apartment not initialised\n"); return CO_E_NOTINITIALIZED; } if (!pclsid) return E_INVALIDARG; EnterCriticalSection(&cs_registered_ps); LIST_FOR_EACH_ENTRY(cur, &registered_proxystubs, struct registered_ps, entry) { if (IsEqualIID(&cur->iid, riid)) { *pclsid = cur->clsid; LeaveCriticalSection(&cs_registered_ps); return S_OK; } } LeaveCriticalSection(&cs_registered_ps); data.cbSize = sizeof(data); if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION, riid, &data)) { struct ifacepsredirect_data *ifaceps = (struct ifacepsredirect_data *)data.lpData; *pclsid = ifaceps->iid; return S_OK; } /* Interface\\{string form of riid}\\ProxyStubClsid32 */ lstrcpyW(path, interfaceW); StringFromGUID2(riid, path + ARRAY_SIZE(interfaceW) - 1, CHARS_IN_GUID); lstrcpyW(path + ARRAY_SIZE(interfaceW) - 1 + CHARS_IN_GUID - 1, psW); hr = get_ps_clsid_from_registry(path, 0, pclsid); if (FAILED(hr) && (opposite == KEY_WOW64_32KEY || (IsWow64Process(GetCurrentProcess(), &is_wow64) && is_wow64))) hr = get_ps_clsid_from_registry(path, opposite, pclsid); if (hr == S_OK) TRACE("() Returning CLSID %s\n", debugstr_guid(pclsid)); else WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid)); return hr; } /***************************************************************************** * CoRegisterPSClsid (combase.@) */ HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid) { struct registered_ps *cur; TRACE("%s, %s\n", debugstr_guid(riid), debugstr_guid(rclsid)); if (!InternalIsProcessInitialized()) { ERR("apartment not initialised\n"); return CO_E_NOTINITIALIZED; } EnterCriticalSection(&cs_registered_ps); LIST_FOR_EACH_ENTRY(cur, &registered_proxystubs, struct registered_ps, entry) { if (IsEqualIID(&cur->iid, riid)) { cur->clsid = *rclsid; LeaveCriticalSection(&cs_registered_ps); return S_OK; } } cur = heap_alloc(sizeof(*cur)); if (!cur) { LeaveCriticalSection(&cs_registered_ps); return E_OUTOFMEMORY; } cur->iid = *riid; cur->clsid = *rclsid; list_add_head(&registered_proxystubs, &cur->entry); LeaveCriticalSection(&cs_registered_ps); return S_OK; } struct thread_context { IComThreadingInfo IComThreadingInfo_iface; IContextCallback IContextCallback_iface; IObjContext IObjContext_iface; LONG refcount; }; static inline struct thread_context *impl_from_IComThreadingInfo(IComThreadingInfo *iface) { return CONTAINING_RECORD(iface, struct thread_context, IComThreadingInfo_iface); } static inline struct thread_context *impl_from_IContextCallback(IContextCallback *iface) { return CONTAINING_RECORD(iface, struct thread_context, IContextCallback_iface); } static inline struct thread_context *impl_from_IObjContext(IObjContext *iface) { return CONTAINING_RECORD(iface, struct thread_context, IObjContext_iface); } static HRESULT WINAPI thread_context_info_QueryInterface(IComThreadingInfo *iface, REFIID riid, void **obj) { struct thread_context *context = impl_from_IComThreadingInfo(iface); *obj = NULL; if (IsEqualIID(riid, &IID_IComThreadingInfo) || IsEqualIID(riid, &IID_IUnknown)) { *obj = &context->IComThreadingInfo_iface; } else if (IsEqualIID(riid, &IID_IContextCallback)) { *obj = &context->IContextCallback_iface; } else if (IsEqualIID(riid, &IID_IObjContext)) { *obj = &context->IObjContext_iface; } if (*obj) { IUnknown_AddRef((IUnknown *)*obj); return S_OK; } FIXME("interface not implemented %s\n", debugstr_guid(riid)); return E_NOINTERFACE; } static ULONG WINAPI thread_context_info_AddRef(IComThreadingInfo *iface) { struct thread_context *context = impl_from_IComThreadingInfo(iface); return InterlockedIncrement(&context->refcount); } static ULONG WINAPI thread_context_info_Release(IComThreadingInfo *iface) { struct thread_context *context = impl_from_IComThreadingInfo(iface); /* Context instance is initially created with CoGetContextToken() with refcount set to 0, releasing context while refcount is at 0 destroys it. */ if (!context->refcount) { heap_free(context); return 0; } return InterlockedDecrement(&context->refcount); } static HRESULT WINAPI thread_context_info_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype) { APTTYPEQUALIFIER qualifier; TRACE("%p\n", apttype); return CoGetApartmentType(apttype, &qualifier); } static HRESULT WINAPI thread_context_info_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype) { APTTYPEQUALIFIER qualifier; APTTYPE apttype; HRESULT hr; hr = CoGetApartmentType(&apttype, &qualifier); if (FAILED(hr)) return hr; TRACE("%p\n", thdtype); switch (apttype) { case APTTYPE_STA: case APTTYPE_MAINSTA: *thdtype = THDTYPE_PROCESSMESSAGES; break; default: *thdtype = THDTYPE_BLOCKMESSAGES; break; } return S_OK; } static HRESULT WINAPI thread_context_info_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id) { TRACE("%p\n", logical_thread_id); return CoGetCurrentLogicalThreadId(logical_thread_id); } static HRESULT WINAPI thread_context_info_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id) { FIXME("%s stub\n", debugstr_guid(logical_thread_id)); return E_NOTIMPL; } static const IComThreadingInfoVtbl thread_context_info_vtbl = { thread_context_info_QueryInterface, thread_context_info_AddRef, thread_context_info_Release, thread_context_info_GetCurrentApartmentType, thread_context_info_GetCurrentThreadType, thread_context_info_GetCurrentLogicalThreadId, thread_context_info_SetCurrentLogicalThreadId }; static HRESULT WINAPI thread_context_callback_QueryInterface(IContextCallback *iface, REFIID riid, void **obj) { struct thread_context *context = impl_from_IContextCallback(iface); return IComThreadingInfo_QueryInterface(&context->IComThreadingInfo_iface, riid, obj); } static ULONG WINAPI thread_context_callback_AddRef(IContextCallback *iface) { struct thread_context *context = impl_from_IContextCallback(iface); return IComThreadingInfo_AddRef(&context->IComThreadingInfo_iface); } static ULONG WINAPI thread_context_callback_Release(IContextCallback *iface) { struct thread_context *context = impl_from_IContextCallback(iface); return IComThreadingInfo_Release(&context->IComThreadingInfo_iface); } static HRESULT WINAPI thread_context_callback_ContextCallback(IContextCallback *iface, PFNCONTEXTCALL callback, ComCallData *param, REFIID riid, int method, IUnknown *punk) { FIXME("%p, %p, %p, %s, %d, %p\n", iface, callback, param, debugstr_guid(riid), method, punk); return E_NOTIMPL; } static const IContextCallbackVtbl thread_context_callback_vtbl = { thread_context_callback_QueryInterface, thread_context_callback_AddRef, thread_context_callback_Release, thread_context_callback_ContextCallback }; static HRESULT WINAPI thread_object_context_QueryInterface(IObjContext *iface, REFIID riid, void **obj) { struct thread_context *context = impl_from_IObjContext(iface); return IComThreadingInfo_QueryInterface(&context->IComThreadingInfo_iface, riid, obj); } static ULONG WINAPI thread_object_context_AddRef(IObjContext *iface) { struct thread_context *context = impl_from_IObjContext(iface); return IComThreadingInfo_AddRef(&context->IComThreadingInfo_iface); } static ULONG WINAPI thread_object_context_Release(IObjContext *iface) { struct thread_context *context = impl_from_IObjContext(iface); return IComThreadingInfo_Release(&context->IComThreadingInfo_iface); } static HRESULT WINAPI thread_object_context_SetProperty(IObjContext *iface, REFGUID propid, CPFLAGS flags, IUnknown *punk) { FIXME("%p, %s, %x, %p\n", iface, debugstr_guid(propid), flags, punk); return E_NOTIMPL; } static HRESULT WINAPI thread_object_context_RemoveProperty(IObjContext *iface, REFGUID propid) { FIXME("%p, %s\n", iface, debugstr_guid(propid)); return E_NOTIMPL; } static HRESULT WINAPI thread_object_context_GetProperty(IObjContext *iface, REFGUID propid, CPFLAGS *flags, IUnknown **punk) { FIXME("%p, %s, %p, %p\n", iface, debugstr_guid(propid), flags, punk); return E_NOTIMPL; } static HRESULT WINAPI thread_object_context_EnumContextProps(IObjContext *iface, IEnumContextProps **props) { FIXME("%p, %p\n", iface, props); return E_NOTIMPL; } static void WINAPI thread_object_context_Reserved1(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved2(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved3(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved4(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved5(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved6(IObjContext *iface) { FIXME("%p\n", iface); } static void WINAPI thread_object_context_Reserved7(IObjContext *iface) { FIXME("%p\n", iface); } static const IObjContextVtbl thread_object_context_vtbl = { thread_object_context_QueryInterface, thread_object_context_AddRef, thread_object_context_Release, thread_object_context_SetProperty, thread_object_context_RemoveProperty, thread_object_context_GetProperty, thread_object_context_EnumContextProps, thread_object_context_Reserved1, thread_object_context_Reserved2, thread_object_context_Reserved3, thread_object_context_Reserved4, thread_object_context_Reserved5, thread_object_context_Reserved6, thread_object_context_Reserved7 }; /*********************************************************************** * CoGetContextToken (combase.@) */ HRESULT WINAPI CoGetContextToken(ULONG_PTR *token) { struct tlsdata *tlsdata; HRESULT hr; TRACE("%p\n", token); if (!InternalIsProcessInitialized()) { ERR("apartment not initialised\n"); return CO_E_NOTINITIALIZED; } if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (!token) return E_POINTER; if (!tlsdata->context_token) { struct thread_context *context; context = heap_alloc_zero(sizeof(*context)); if (!context) return E_OUTOFMEMORY; context->IComThreadingInfo_iface.lpVtbl = &thread_context_info_vtbl; context->IContextCallback_iface.lpVtbl = &thread_context_callback_vtbl; context->IObjContext_iface.lpVtbl = &thread_object_context_vtbl; /* Context token does not take a reference, it's always zero until the interface is explicitly requested with CoGetObjectContext(). */ context->refcount = 0; tlsdata->context_token = &context->IObjContext_iface; } *token = (ULONG_PTR)tlsdata->context_token; TRACE("context_token %p\n", tlsdata->context_token); return S_OK; } /*********************************************************************** * CoGetCurrentLogicalThreadId (combase.@) */ HRESULT WINAPI CoGetCurrentLogicalThreadId(GUID *id) { struct tlsdata *tlsdata; HRESULT hr; if (!id) return E_INVALIDARG; if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (IsEqualGUID(&tlsdata->causality_id, &GUID_NULL)) CoCreateGuid(&tlsdata->causality_id); *id = tlsdata->causality_id; return S_OK; } /****************************************************************************** * CoGetCurrentProcess (combase.@) */ DWORD WINAPI CoGetCurrentProcess(void) { struct tlsdata *tlsdata; if (FAILED(com_get_tlsdata(&tlsdata))) return 0; if (!tlsdata->thread_seqid) rpcss_get_next_seqid(&tlsdata->thread_seqid); return tlsdata->thread_seqid; } /*********************************************************************** * CoFreeUnusedLibrariesEx (combase.@) */ void WINAPI DECLSPEC_HOTPATCH CoFreeUnusedLibrariesEx(DWORD unload_delay, DWORD reserved) { struct apartment *apt = com_get_current_apt(); if (!apt) { ERR("apartment not initialised\n"); return; } apartment_freeunusedlibraries(apt, unload_delay); } /* * When locked, don't modify list (unless we add a new head), so that it's * safe to iterate it. Freeing of list entries is delayed and done on unlock. */ static inline void lock_init_spies(struct tlsdata *tlsdata) { tlsdata->spies_lock++; } static void unlock_init_spies(struct tlsdata *tlsdata) { struct init_spy *spy, *next; if (--tlsdata->spies_lock) return; LIST_FOR_EACH_ENTRY_SAFE(spy, next, &tlsdata->spies, struct init_spy, entry) { if (spy->spy) continue; list_remove(&spy->entry); heap_free(spy); } } /****************************************************************************** * CoInitializeEx (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoInitializeEx(void *reserved, DWORD model) { struct tlsdata *tlsdata; struct init_spy *cursor; HRESULT hr; TRACE("%p, %#x\n", reserved, model); if (reserved) WARN("Unexpected reserved argument %p\n", reserved); if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (InterlockedExchangeAdd(&com_lockcount, 1) == 0) TRACE("Initializing the COM libraries\n"); lock_init_spies(tlsdata); LIST_FOR_EACH_ENTRY(cursor, &tlsdata->spies, struct init_spy, entry) { if (cursor->spy) IInitializeSpy_PreInitialize(cursor->spy, model, tlsdata->inits); } unlock_init_spies(tlsdata); hr = enter_apartment(tlsdata, model); lock_init_spies(tlsdata); LIST_FOR_EACH_ENTRY(cursor, &tlsdata->spies, struct init_spy, entry) { if (cursor->spy) hr = IInitializeSpy_PostInitialize(cursor->spy, hr, model, tlsdata->inits); } unlock_init_spies(tlsdata); return hr; } /*********************************************************************** * CoUninitialize (combase.@) */ void WINAPI DECLSPEC_HOTPATCH CoUninitialize(void) { struct tlsdata *tlsdata; struct init_spy *cursor, *next; LONG lockcount; TRACE("\n"); if (FAILED(com_get_tlsdata(&tlsdata))) return; lock_init_spies(tlsdata); LIST_FOR_EACH_ENTRY_SAFE(cursor, next, &tlsdata->spies, struct init_spy, entry) { if (cursor->spy) IInitializeSpy_PreUninitialize(cursor->spy, tlsdata->inits); } unlock_init_spies(tlsdata); /* sanity check */ if (!tlsdata->inits) { ERR("Mismatched CoUninitialize\n"); lock_init_spies(tlsdata); LIST_FOR_EACH_ENTRY_SAFE(cursor, next, &tlsdata->spies, struct init_spy, entry) { if (cursor->spy) IInitializeSpy_PostUninitialize(cursor->spy, tlsdata->inits); } unlock_init_spies(tlsdata); return; } leave_apartment(tlsdata); /* * Decrease the reference count. * If we are back to 0 locks on the COM library, make sure we free * all the associated data structures. */ lockcount = InterlockedExchangeAdd(&com_lockcount, -1); if (lockcount == 1) { TRACE("Releasing the COM libraries\n"); com_revoke_all_ps_clsids(); DestroyRunningObjectTable(); } else if (lockcount < 1) { ERR("Unbalanced lock count %d\n", lockcount); InterlockedExchangeAdd(&com_lockcount, 1); } lock_init_spies(tlsdata); LIST_FOR_EACH_ENTRY(cursor, &tlsdata->spies, struct init_spy, entry) { if (cursor->spy) IInitializeSpy_PostUninitialize(cursor->spy, tlsdata->inits); } unlock_init_spies(tlsdata); } /*********************************************************************** * CoIncrementMTAUsage (combase.@) */ HRESULT WINAPI CoIncrementMTAUsage(CO_MTA_USAGE_COOKIE *cookie) { TRACE("%p\n", cookie); return apartment_increment_mta_usage(cookie); } /*********************************************************************** * CoDecrementMTAUsage (combase.@) */ HRESULT WINAPI CoDecrementMTAUsage(CO_MTA_USAGE_COOKIE cookie) { TRACE("%p\n", cookie); apartment_decrement_mta_usage(cookie); return S_OK; } /*********************************************************************** * CoGetApartmentType (combase.@) */ HRESULT WINAPI CoGetApartmentType(APTTYPE *type, APTTYPEQUALIFIER *qualifier) { struct tlsdata *tlsdata; struct apartment *apt; HRESULT hr; TRACE("%p, %p\n", type, qualifier); if (!type || !qualifier) return E_INVALIDARG; if (FAILED(hr = com_get_tlsdata(&tlsdata))) return hr; if (!tlsdata->apt) *type = APTTYPE_CURRENT; else if (tlsdata->apt->multi_threaded) *type = APTTYPE_MTA; else if (tlsdata->apt->main) *type = APTTYPE_MAINSTA; else *type = APTTYPE_STA; *qualifier = APTTYPEQUALIFIER_NONE; if (!tlsdata->apt && (apt = apartment_get_mta())) { apartment_release(apt); *type = APTTYPE_MTA; *qualifier = APTTYPEQUALIFIER_IMPLICIT_MTA; return S_OK; } return tlsdata->apt ? S_OK : CO_E_NOTINITIALIZED; } /****************************************************************************** * CoRegisterClassObject (combase.@) * BUGS * MSDN claims that multiple interface registrations are legal, but we * can't do that with our current implementation. */ HRESULT WINAPI CoRegisterClassObject(REFCLSID rclsid, IUnknown *object, DWORD clscontext, DWORD flags, DWORD *cookie) { static LONG next_cookie; struct registered_class *newclass; IUnknown *found_object; struct apartment *apt; HRESULT hr = S_OK; TRACE("%s, %p, %#x, %#x, %p\n", debugstr_guid(rclsid), object, clscontext, flags, cookie); if (!cookie || !object) return E_INVALIDARG; if (!(apt = apartment_get_current_or_mta())) { ERR("COM was not initialized\n"); return CO_E_NOTINITIALIZED; } *cookie = 0; /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what * differentiates the flag from REGCLS_MULTI_SEPARATE. */ if (flags & REGCLS_MULTIPLEUSE) clscontext |= CLSCTX_INPROC_SERVER; /* * First, check if the class is already registered. * If it is, this should cause an error. */ if ((found_object = com_get_registered_class_object(apt, rclsid, clscontext))) { if (flags & REGCLS_MULTIPLEUSE) { if (clscontext & CLSCTX_LOCAL_SERVER) hr = CoLockObjectExternal(found_object, TRUE, FALSE); IUnknown_Release(found_object); apartment_release(apt); return hr; } IUnknown_Release(found_object); ERR("object already registered for class %s\n", debugstr_guid(rclsid)); apartment_release(apt); return CO_E_OBJISREG; } newclass = heap_alloc(sizeof(*newclass)); if (!newclass) { apartment_release(apt); return E_OUTOFMEMORY; } newclass->clsid = *rclsid; newclass->apartment_id = apt->oxid; newclass->clscontext = clscontext; newclass->flags = flags; newclass->RpcRegistration = NULL; if (!(newclass->cookie = InterlockedIncrement(&next_cookie))) newclass->cookie = InterlockedIncrement(&next_cookie); newclass->object = object; IUnknown_AddRef(newclass->object); EnterCriticalSection(&registered_classes_cs); list_add_tail(&registered_classes, &newclass->entry); LeaveCriticalSection(&registered_classes_cs); *cookie = newclass->cookie; if (clscontext & CLSCTX_LOCAL_SERVER) { IStream *marshal_stream; hr = apartment_get_local_server_stream(apt, &marshal_stream); if(FAILED(hr)) { apartment_release(apt); return hr; } hr = rpc_start_local_server(&newclass->clsid, marshal_stream, flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE), &newclass->RpcRegistration); IStream_Release(marshal_stream); } apartment_release(apt); return S_OK; } static void com_revoke_class_object(struct registered_class *entry) { list_remove(&entry->entry); if (entry->clscontext & CLSCTX_LOCAL_SERVER) rpc_stop_local_server(entry->RpcRegistration); IUnknown_Release(entry->object); heap_free(entry); } void apartment_revoke_all_classes(const struct apartment *apt) { struct registered_class *cur, *cur2; EnterCriticalSection(&registered_classes_cs); LIST_FOR_EACH_ENTRY_SAFE(cur, cur2, &registered_classes, struct registered_class, entry) { if (cur->apartment_id == apt->oxid) com_revoke_class_object(cur); } LeaveCriticalSection(&registered_classes_cs); } /*********************************************************************** * CoRevokeClassObject (combase.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH CoRevokeClassObject(DWORD cookie) { HRESULT hr = E_INVALIDARG; struct registered_class *cur; struct apartment *apt; TRACE("%#x\n", cookie); if (!(apt = apartment_get_current_or_mta())) { ERR("COM was not initialized\n"); return CO_E_NOTINITIALIZED; } EnterCriticalSection(&registered_classes_cs); LIST_FOR_EACH_ENTRY(cur, &registered_classes, struct registered_class, entry) { if (cur->cookie != cookie) continue; if (cur->apartment_id == apt->oxid) { com_revoke_class_object(cur); hr = S_OK; } else { ERR("called from wrong apartment, should be called from %s\n", wine_dbgstr_longlong(cur->apartment_id)); hr = RPC_E_WRONG_THREAD; } break; } LeaveCriticalSection(&registered_classes_cs); apartment_release(apt); return hr; } /*********************************************************************** * CoAddRefServerProcess (combase.@) */ ULONG WINAPI CoAddRefServerProcess(void) { ULONG refs; TRACE("\n"); EnterCriticalSection(&registered_classes_cs); refs = ++com_server_process_refcount; LeaveCriticalSection(&registered_classes_cs); TRACE("refs before: %d\n", refs - 1); return refs; } /*********************************************************************** * CoReleaseServerProcess [OLE32.@] */ ULONG WINAPI CoReleaseServerProcess(void) { ULONG refs; TRACE("\n"); EnterCriticalSection(&registered_classes_cs); refs = --com_server_process_refcount; /* FIXME: suspend objects */ LeaveCriticalSection(&registered_classes_cs); TRACE("refs after: %d\n", refs); return refs; } /*********************************************************************** * DllMain (combase.@) */ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD reason, LPVOID reserved) { TRACE("%p 0x%x %p\n", hinstDLL, reason, reserved); switch (reason) { case DLL_PROCESS_ATTACH: hProxyDll = hinstDLL; break; case DLL_PROCESS_DETACH: if (reserved) break; apartment_global_cleanup(); DeleteCriticalSection(&registered_classes_cs); break; case DLL_THREAD_DETACH: com_cleanup_tlsdata(); break; } return TRUE; }
1002251.c
/** * PSA API key derivation demonstration * * This program calculates a key ladder: a chain of secret material, each * derived from the previous one in a deterministic way based on a label. * Two keys are identical if and only if they are derived from the same key * using the same label. * * The initial key is called the master key. The master key is normally * randomly generated, but it could itself be derived from another key. * * This program derives a series of keys called intermediate keys. * The first intermediate key is derived from the master key using the * first label passed on the command line. Each subsequent intermediate * key is derived from the previous one using the next label passed * on the command line. * * This program has four modes of operation: * * - "generate": generate a random master key. * - "wrap": derive a wrapping key from the last intermediate key, * and use that key to encrypt-and-authenticate some data. * - "unwrap": derive a wrapping key from the last intermediate key, * and use that key to decrypt-and-authenticate some * ciphertext created by wrap mode. * - "save": save the last intermediate key so that it can be reused as * the master key in another run of the program. * * See the usage() output for the command line usage. See the file * `key_ladder_demo.sh` for an example run. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* First include Mbed TLS headers to get the Mbed TLS configuration and * platform definitions that we'll use in this program. Also include * standard C headers for functions we'll use here. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize #include "psa/crypto.h" /* If the build options we need are not enabled, compile a placeholder. */ #if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \ !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \ !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) int main( void ) { printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or " "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or " "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO " "not defined.\n"); return( 0 ); } #else /* The real program starts here. */ /* Run a system function and bail out if it fails. */ #define SYS_CHECK( expr ) \ do \ { \ if( ! ( expr ) ) \ { \ perror( #expr ); \ status = DEMO_ERROR; \ goto exit; \ } \ } \ while( 0 ) /* Run a PSA function and bail out if it fails. */ #define PSA_CHECK( expr ) \ do \ { \ status = ( expr ); \ if( status != PSA_SUCCESS ) \ { \ printf( "Error %d at line %d: %s\n", \ (int) status, \ __LINE__, \ #expr ); \ goto exit; \ } \ } \ while( 0 ) /* To report operational errors in this program, use an error code that is * different from every PSA error code. */ #define DEMO_ERROR 120 /* The maximum supported key ladder depth. */ #define MAX_LADDER_DEPTH 10 /* Salt to use when deriving an intermediate key. */ #define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" ) #define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) ) /* Salt to use when deriving a wrapping key. */ #define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" ) #define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) ) /* Size of the key derivation keys (applies both to the master key and * to intermediate keys). */ #define KEY_SIZE_BYTES 40 /* Algorithm for key derivation. */ #define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 ) /* Type and size of the key used to wrap data. */ #define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES #define WRAPPING_KEY_BITS 128 /* Cipher mode used to wrap data. */ #define WRAPPING_ALG PSA_ALG_CCM /* Nonce size used to wrap data. */ #define WRAPPING_IV_SIZE 13 /* Header used in files containing wrapped data. We'll save this header * directly without worrying about data representation issues such as * integer sizes and endianness, because the data is meant to be read * back by the same program on the same machine. */ #define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte #define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) ) typedef struct { char magic[WRAPPED_DATA_MAGIC_LENGTH]; size_t ad_size; /* Size of the additional data, which is this header. */ size_t payload_size; /* Size of the encrypted data. */ /* Store the IV inside the additional data. It's convenient. */ uint8_t iv[WRAPPING_IV_SIZE]; } wrapped_data_header_t; /* The modes that this program can operate in (see usage). */ enum program_mode { MODE_GENERATE, MODE_SAVE, MODE_UNWRAP, MODE_WRAP }; /* Save a key to a file. In the real world, you may want to export a derived * key sometimes, to share it with another party. */ static psa_status_t save_key( psa_key_handle_t key_handle, const char *output_file_name ) { psa_status_t status = PSA_SUCCESS; uint8_t key_data[KEY_SIZE_BYTES]; size_t key_size; FILE *key_file = NULL; PSA_CHECK( psa_export_key( key_handle, key_data, sizeof( key_data ), &key_size ) ); SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL ); SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size ); SYS_CHECK( fclose( key_file ) == 0 ); key_file = NULL; exit: if( key_file != NULL) fclose( key_file ); return( status ); } /* Generate a master key for use in this demo. * * Normally a master key would be non-exportable. For the purpose of this * demo, we want to save it to a file, to avoid relying on the keystore * capability of the PSA crypto library. */ static psa_status_t generate( const char *key_file_name ) { psa_status_t status = PSA_SUCCESS; psa_key_handle_t key_handle = 0; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT ); psa_set_key_algorithm( &attributes, KDF_ALG ); psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE ); psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) ); PSA_CHECK( psa_generate_key( &attributes, &key_handle ) ); PSA_CHECK( save_key( key_handle, key_file_name ) ); exit: (void) psa_destroy_key( key_handle ); return( status ); } /* Load the master key from a file. * * In the real world, this master key would be stored in an internal memory * and the storage would be managed by the keystore capability of the PSA * crypto library. */ static psa_status_t import_key_from_file( psa_key_usage_t usage, psa_algorithm_t alg, const char *key_file_name, psa_key_handle_t *master_key_handle ) { psa_status_t status = PSA_SUCCESS; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; uint8_t key_data[KEY_SIZE_BYTES]; size_t key_size; FILE *key_file = NULL; unsigned char extra_byte; *master_key_handle = 0; SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL ); SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ), key_file ) ) != 0 ); if( fread( &extra_byte, 1, 1, key_file ) != 0 ) { printf( "Key file too large (max: %u).\n", (unsigned) sizeof( key_data ) ); status = DEMO_ERROR; goto exit; } SYS_CHECK( fclose( key_file ) == 0 ); key_file = NULL; psa_set_key_usage_flags( &attributes, usage ); psa_set_key_algorithm( &attributes, alg ); psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE ); PSA_CHECK( psa_import_key( &attributes, key_data, key_size, master_key_handle ) ); exit: if( key_file != NULL ) fclose( key_file ); mbedtls_platform_zeroize( key_data, sizeof( key_data ) ); if( status != PSA_SUCCESS ) { /* If the key creation hasn't happened yet or has failed, * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do * nothing and return PSA_ERROR_INVALID_HANDLE. */ (void) psa_destroy_key( *master_key_handle ); *master_key_handle = 0; } return( status ); } /* Derive the intermediate keys, using the list of labels provided on * the command line. On input, *key_handle is a handle to the master key. * This function closes the master key. On successful output, *key_handle * is a handle to the final derived key. */ static psa_status_t derive_key_ladder( const char *ladder[], size_t ladder_depth, psa_key_handle_t *key_handle ) { psa_status_t status = PSA_SUCCESS; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; size_t i; psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT ); psa_set_key_algorithm( &attributes, KDF_ALG ); psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE ); psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) ); /* For each label in turn, ... */ for( i = 0; i < ladder_depth; i++ ) { /* Start deriving material from the master key (if i=0) or from * the current intermediate key (if i>0). */ PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) ); PSA_CHECK( psa_key_derivation_input_bytes( &operation, PSA_KEY_DERIVATION_INPUT_SALT, DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH ) ); PSA_CHECK( psa_key_derivation_input_key( &operation, PSA_KEY_DERIVATION_INPUT_SECRET, *key_handle ) ); PSA_CHECK( psa_key_derivation_input_bytes( &operation, PSA_KEY_DERIVATION_INPUT_INFO, (uint8_t*) ladder[i], strlen( ladder[i] ) ) ); /* When the parent key is not the master key, destroy it, * since it is no longer needed. */ PSA_CHECK( psa_close_key( *key_handle ) ); *key_handle = 0; /* Derive the next intermediate key from the parent key. */ PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation, key_handle ) ); PSA_CHECK( psa_key_derivation_abort( &operation ) ); } exit: psa_key_derivation_abort( &operation ); if( status != PSA_SUCCESS ) { psa_close_key( *key_handle ); *key_handle = 0; } return( status ); } /* Derive a wrapping key from the last intermediate key. */ static psa_status_t derive_wrapping_key( psa_key_usage_t usage, psa_key_handle_t derived_key_handle, psa_key_handle_t *wrapping_key_handle ) { psa_status_t status = PSA_SUCCESS; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; *wrapping_key_handle = 0; /* Set up a key derivation operation from the key derived from * the master key. */ PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) ); PSA_CHECK( psa_key_derivation_input_bytes( &operation, PSA_KEY_DERIVATION_INPUT_SALT, WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH ) ); PSA_CHECK( psa_key_derivation_input_key( &operation, PSA_KEY_DERIVATION_INPUT_SECRET, derived_key_handle ) ); PSA_CHECK( psa_key_derivation_input_bytes( &operation, PSA_KEY_DERIVATION_INPUT_INFO, NULL, 0 ) ); /* Create the wrapping key. */ psa_set_key_usage_flags( &attributes, usage ); psa_set_key_algorithm( &attributes, WRAPPING_ALG ); psa_set_key_type( &attributes, PSA_KEY_TYPE_AES ); psa_set_key_bits( &attributes, WRAPPING_KEY_BITS ); PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation, wrapping_key_handle ) ); exit: psa_key_derivation_abort( &operation ); return( status ); } static psa_status_t wrap_data( const char *input_file_name, const char *output_file_name, psa_key_handle_t wrapping_key_handle ) { psa_status_t status; FILE *input_file = NULL; FILE *output_file = NULL; long input_position; size_t input_size; size_t buffer_size = 0; unsigned char *buffer = NULL; size_t ciphertext_size; wrapped_data_header_t header; /* Find the size of the data to wrap. */ SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL ); SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 ); SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 ); #if LONG_MAX > SIZE_MAX if( input_position > SIZE_MAX ) { printf( "Input file too large.\n" ); status = DEMO_ERROR; goto exit; } #endif input_size = input_position; buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size ); /* Check for integer overflow. */ if( buffer_size < input_size ) { printf( "Input file too large.\n" ); status = DEMO_ERROR; goto exit; } /* Load the data to wrap. */ SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 ); SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL ); SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size ); SYS_CHECK( fclose( input_file ) == 0 ); input_file = NULL; /* Construct a header. */ memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH ); header.ad_size = sizeof( header ); header.payload_size = input_size; /* Wrap the data. */ PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) ); PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG, header.iv, WRAPPING_IV_SIZE, (uint8_t *) &header, sizeof( header ), buffer, input_size, buffer, buffer_size, &ciphertext_size ) ); /* Write the output. */ SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL ); SYS_CHECK( fwrite( &header, 1, sizeof( header ), output_file ) == sizeof( header ) ); SYS_CHECK( fwrite( buffer, 1, ciphertext_size, output_file ) == ciphertext_size ); SYS_CHECK( fclose( output_file ) == 0 ); output_file = NULL; exit: if( input_file != NULL ) fclose( input_file ); if( output_file != NULL ) fclose( output_file ); if( buffer != NULL ) mbedtls_platform_zeroize( buffer, buffer_size ); free( buffer ); return( status ); } static psa_status_t unwrap_data( const char *input_file_name, const char *output_file_name, psa_key_handle_t wrapping_key_handle ) { psa_status_t status; FILE *input_file = NULL; FILE *output_file = NULL; unsigned char *buffer = NULL; size_t ciphertext_size = 0; size_t plaintext_size; wrapped_data_header_t header; unsigned char extra_byte; /* Load and validate the header. */ SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL ); SYS_CHECK( fread( &header, 1, sizeof( header ), input_file ) == sizeof( header ) ); if( memcmp( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH ) != 0 ) { printf( "The input does not start with a valid magic header.\n" ); status = DEMO_ERROR; goto exit; } if( header.ad_size != sizeof( header ) ) { printf( "The header size is not correct.\n" ); status = DEMO_ERROR; goto exit; } ciphertext_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size ); /* Check for integer overflow. */ if( ciphertext_size < header.payload_size ) { printf( "Input file too large.\n" ); status = DEMO_ERROR; goto exit; } /* Load the payload data. */ SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL ); SYS_CHECK( fread( buffer, 1, ciphertext_size, input_file ) == ciphertext_size ); if( fread( &extra_byte, 1, 1, input_file ) != 0 ) { printf( "Extra garbage after ciphertext\n" ); status = DEMO_ERROR; goto exit; } SYS_CHECK( fclose( input_file ) == 0 ); input_file = NULL; /* Unwrap the data. */ PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG, header.iv, WRAPPING_IV_SIZE, (uint8_t *) &header, sizeof( header ), buffer, ciphertext_size, buffer, ciphertext_size, &plaintext_size ) ); if( plaintext_size != header.payload_size ) { printf( "Incorrect payload size in the header.\n" ); status = DEMO_ERROR; goto exit; } /* Write the output. */ SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL ); SYS_CHECK( fwrite( buffer, 1, plaintext_size, output_file ) == plaintext_size ); SYS_CHECK( fclose( output_file ) == 0 ); output_file = NULL; exit: if( input_file != NULL ) fclose( input_file ); if( output_file != NULL ) fclose( output_file ); if( buffer != NULL ) mbedtls_platform_zeroize( buffer, ciphertext_size ); free( buffer ); return( status ); } static psa_status_t run( enum program_mode mode, const char *key_file_name, const char *ladder[], size_t ladder_depth, const char *input_file_name, const char *output_file_name ) { psa_status_t status = PSA_SUCCESS; psa_key_handle_t derivation_key_handle = 0; psa_key_handle_t wrapping_key_handle = 0; /* Initialize the PSA crypto library. */ PSA_CHECK( psa_crypto_init( ) ); /* Generate mode is unlike the others. Generate the master key and exit. */ if( mode == MODE_GENERATE ) return( generate( key_file_name ) ); /* Read the master key. */ PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT, KDF_ALG, key_file_name, &derivation_key_handle ) ); /* Calculate the derived key for this session. */ PSA_CHECK( derive_key_ladder( ladder, ladder_depth, &derivation_key_handle ) ); switch( mode ) { case MODE_SAVE: PSA_CHECK( save_key( derivation_key_handle, output_file_name ) ); break; case MODE_UNWRAP: PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT, derivation_key_handle, &wrapping_key_handle ) ); PSA_CHECK( unwrap_data( input_file_name, output_file_name, wrapping_key_handle ) ); break; case MODE_WRAP: PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT, derivation_key_handle, &wrapping_key_handle ) ); PSA_CHECK( wrap_data( input_file_name, output_file_name, wrapping_key_handle ) ); break; default: /* Unreachable but some compilers don't realize it. */ break; } exit: /* Close any remaining key. Deinitializing the crypto library would do * this anyway, but explicitly closing handles makes the code easier * to reuse. */ (void) psa_close_key( derivation_key_handle ); (void) psa_close_key( wrapping_key_handle ); /* Deinitialize the PSA crypto library. */ mbedtls_psa_crypto_free( ); return( status ); } static void usage( void ) { printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" ); printf( "Demonstrate the usage of a key derivation ladder.\n" ); printf( "\n" ); printf( "Modes:\n" ); printf( " generate Generate the master key\n" ); printf( " save Save the derived key\n" ); printf( " unwrap Unwrap (decrypt) input with the derived key\n" ); printf( " wrap Wrap (encrypt) input with the derived key\n" ); printf( "\n" ); printf( "Options:\n" ); printf( " input=FILENAME Input file (required for wrap/unwrap)\n" ); printf( " master=FILENAME File containing the master key (default: master.key)\n" ); printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" ); printf( " label=TEXT Label for the key derivation.\n" ); printf( " This may be repeated multiple times.\n" ); printf( " To get the same key, you must use the same master key\n" ); printf( " and the same sequence of labels.\n" ); } #if defined(MBEDTLS_CHECK_PARAMS) #include "mbedtls/platform_util.h" void mbedtls_param_failed( const char *failure_condition, const char *file, int line ) { printf( "%s:%i: Input param failed - %s\n", file, line, failure_condition ); exit( EXIT_FAILURE ); } #endif int main( int argc, char *argv[] ) { const char *key_file_name = "master.key"; const char *input_file_name = NULL; const char *output_file_name = NULL; const char *ladder[MAX_LADDER_DEPTH]; size_t ladder_depth = 0; int i; enum program_mode mode; psa_status_t status; if( argc <= 1 || strcmp( argv[1], "help" ) == 0 || strcmp( argv[1], "-help" ) == 0 || strcmp( argv[1], "--help" ) == 0 ) { usage( ); return( EXIT_SUCCESS ); } for( i = 2; i < argc; i++ ) { char *q = strchr( argv[i], '=' ); if( q == NULL ) { printf( "Missing argument to option %s\n", argv[i] ); goto usage_failure; } *q = 0; ++q; if( strcmp( argv[i], "input" ) == 0 ) input_file_name = q; else if( strcmp( argv[i], "label" ) == 0 ) { if( ladder_depth == MAX_LADDER_DEPTH ) { printf( "Maximum ladder depth %u exceeded.\n", (unsigned) MAX_LADDER_DEPTH ); return( EXIT_FAILURE ); } ladder[ladder_depth] = q; ++ladder_depth; } else if( strcmp( argv[i], "master" ) == 0 ) key_file_name = q; else if( strcmp( argv[i], "output" ) == 0 ) output_file_name = q; else { printf( "Unknown option: %s\n", argv[i] ); goto usage_failure; } } if( strcmp( argv[1], "generate" ) == 0 ) mode = MODE_GENERATE; else if( strcmp( argv[1], "save" ) == 0 ) mode = MODE_SAVE; else if( strcmp( argv[1], "unwrap" ) == 0 ) mode = MODE_UNWRAP; else if( strcmp( argv[1], "wrap" ) == 0 ) mode = MODE_WRAP; else { printf( "Unknown action: %s\n", argv[1] ); goto usage_failure; } if( input_file_name == NULL && ( mode == MODE_WRAP || mode == MODE_UNWRAP ) ) { printf( "Required argument missing: input\n" ); return( DEMO_ERROR ); } if( output_file_name == NULL && ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) ) { printf( "Required argument missing: output\n" ); return( DEMO_ERROR ); } status = run( mode, key_file_name, ladder, ladder_depth, input_file_name, output_file_name ); return( status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE ); usage_failure: usage( ); return( EXIT_FAILURE ); } #endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */
599766.c
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*----------------------------------------------------------------------------- * Sorted set API *----------------------------------------------------------------------------*/ /* ZSETs are ordered sets using two data structures to hold the same elements * in order to get O(log(N)) INSERT and REMOVE operations into a sorted * data structure. * * The elements are added to a hash table mapping Redis objects to scores. * At the same time the elements are added to a skip list mapping scores * to Redis objects (so objects are sorted by scores in this "view"). */ /* This skiplist implementation is almost a C translation of the original * algorithm described by William Pugh in "Skip Lists: A Probabilistic * Alternative to Balanced Trees", modified in three ways: * a) this implementation allows for repeated scores. * b) the comparison is not just by key (our 'score') but by satellite data. * c) there is a back pointer, so it's a doubly linked list with the back * pointers being only at "level 1". This allows to traverse the list * from tail to head, useful for ZREVRANGE. */ /* Sorted set 的具体实现(31~33行的注释这么说的) */ #include "redis.h" #include <math.h> static int zslLexValueGteMin(robj *value, zlexrangespec *spec); static int zslLexValueLteMax(robj *value, zlexrangespec *spec); /* 创建一个"跳跃表"节点(skipNode) */ zskiplistNode *zslCreateNode(int level, double score, robj *obj) { zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel)); zn->score = score; zn->obj = obj; return zn; } /* 创建一个"跳跃表"skipList */ zskiplist *zslCreate(void) { int j; zskiplist *zsl; zsl = zmalloc(sizeof(*zsl)); zsl->level = 1; zsl->length = 0; zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL); // 创建一个层级数组长度为32的sNode /* 初始化层级数组 */ for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) { zsl->header->level[j].forward = NULL; zsl->header->level[j].span = 0; } zsl->header->backward = NULL; zsl->tail = NULL; return zsl; } /* 释放(销毁)一个skipNode对象 */ void zslFreeNode(zskiplistNode *node) { decrRefCount(node->obj); // 单独释放node中的数据(redis object) zfree(node); // 释放node } /* 释放(销毁)一个skipList对象 */ void zslFree(zskiplist *zsl) { zskiplistNode *node = zsl->header->level[0].forward, *next; zfree(zsl->header); while(node) { next = node->level[0].forward; // 是否能保证通过一个节点向前遍历就能遍历完整个"跳跃表"? zslFreeNode(node); node = next; } zfree(zsl); } /* Returns a random level for the new skiplist node we are going to create. * The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL * (both inclusive), with a powerlaw-alike distribution where higher * levels are less likely to be returned. */ /* 随机获取一个层级(level),返回高层级的可能性比较低,最小值为1 */ /* zsl结构如下 */ //level2: (forward )6<----------------------------------------------------------(forward )header //level1: (forward )8<--------------(forward )6<---------------------------(forward )2<-------------------(forward )header //level0: (forward )8<-(forward )7<-(forward )6<-(forward )5<-(forward )3<-(forward )2<-(forward )1<------(forward )header //zsl: 8(backward)->7(backward)->6(backward)->5(backward)->3(backward)->2(backward)->1(backward)->NULL header(backward) // tail^ int zslRandomLevel(void) { int level = 1; /* ZSKIPLIST_P=0.25 这个循环每次都有75%的概率跳出循环 */ while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF) && level<ZSKIPLIST_MAXLEVEL) level += 1; /* 这里保证了返回结果最大不会超过ZSKIPLIST_MAXLEVEL的大小,ZSKIPLIST_MAXLEVEL的大小为32 */ return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL; } /* 往skip list中添加一个skip node */ zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) { zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; unsigned int rank[ZSKIPLIST_MAXLEVEL]; // 不同层级的rank,层级越低rank越高 int i, level; redisAssert(!isnan(score)); x = zsl->header; /* skip list中的数据排列都是有序的 */ /* 从顶层往底层遍历 */ for (i = zsl->level-1; i >= 0; i--) { /* store rank that is crossed to reach the insert position */ rank[i] = i == (zsl->level-1) ? 0 : rank[i+1]; /* 遍历当前层级的所有元素,直到遇到第一个分数(score)小于等于于要插入节点的元素的分数或没有下一个节点为止 */ /* 分数相同时直接比较obj的大小 */ /* x保存的是最后一个分数比新节点小的节点 */ while (x->level[i].forward && (x->level[i].forward->score < score || (x->level[i].forward->score == score && compareStringObjects(x->level[i].forward->obj,obj) < 0))) { rank[i] += x->level[i].span; // 节点的level数组中每个元素的forward字段指向当前层级的此元素的后继节点的地址(每一层的当前节点的后继节点一般都不是同一个) x = x->level[i].forward; } update[i] = x; // 记录每一层由于新插入节点的关系,可能需要产生变更(update)的节点 } /* we assume the key is not already inside, since we allow duplicated * scores, and the re-insertion of score and redis object should never * happen since the caller of zslInsert() should test in the hash table * if the element is already inside or not. */ /* * 我们假设密钥不在内部,因为我们允许重复分数,并且重新插入得分和redis对象应该永远不会发生, * 因为zslInsert()的调用者应该在哈希表中测试元素是否已经在内部. */ // 随机获取新节点要连续插入的层数(类似“抛硬币”的原理,只不过这里是先把所有的硬币一次性抛完) level = zslRandomLevel(); // 如果层级增加,则将所有新增的层级的待修改(update)元素置为header元素,span置为跳表的长度 if (level > zsl->level) { for (i = zsl->level; i < level; i++) { rank[i] = 0; update[i] = zsl->header; update[i]->level[i].span = zsl->length; } zsl->level = level; } // 创建zslNode x = zslCreateNode(level,score,obj); // 将新的zslNode插到每个层级对应的位置 for (i = 0; i < level; i++) { x->level[i].forward = update[i]->level[i].forward; update[i]->level[i].forward = x; /* update span covered by update[i] as x is inserted here */ x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]); update[i]->level[i].span = (rank[0] - rank[i]) + 1; } /* increment span for untouched levels */ for (i = level; i < zsl->level; i++) { update[i]->level[i].span++; } // 将新节点的后继节点设置为update[0]中的节点,如果update[0]中的节点是header则表示没有比新节点小的节点,直接作为尾节点,即新节点的backward // 为NULL,因为header节点不保存任何元素,只是作为起始节点 x->backward = (update[0] == zsl->header) ? NULL : update[0]; // level[0]是全元素的集合 if (x->level[0].forward) x->level[0].forward->backward = x; else zsl->tail = x; zsl->length++; return x; } /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */ /* zslDelete, zslDeleteByScore 和 zslDeleteByRank 这三个函数使用的内部函数 */ /* 注意,调用这个函数的函数需要保证zsl中真实存在要删除的元素,否则zsl的数据会混乱;比如lenght,在这个方法结束后必减1,若元素不存在,则会导致lenght属性和真实长度对不上 */ /* 此方法只负责删除节点,不负责释放节点占用的堆内存 */ void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) { int i; for (i = 0; i < zsl->level; i++) { // 把每一层都遍历一遍,把每一层的参数x所代表的元素的复制(其实只有指针)都删除 if (update[i]->level[i].forward == x) { update[i]->level[i].span += x->level[i].span - 1; // 由于删除了一个元素,导致前一个元素到下一个元素覆盖的真实元素的范围增加了,所以修改一下覆盖范围 update[i]->level[i].forward = x->level[i].forward; } else { update[i]->level[i].span -= 1; // 如果当前层没有要删除的元素的复制,那么由于少了一个元素,所以覆盖范围减1 } } if (x->level[0].forward) { x->level[0].forward->backward = x->backward; } else { zsl->tail = x->backward; } // 清空没有元素的层 while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL) zsl->level--; zsl->length--; } /* Delete an element with matching score/object from the skiplist. */ /* 从skiplist中删除score和object都与参数相同的元素 */ int zslDelete(zskiplist *zsl, double score, robj *obj) { zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; int i; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { while (x->level[i].forward && (x->level[i].forward->score < score || (x->level[i].forward->score == score && compareStringObjects(x->level[i].forward->obj,obj) < 0))) x = x->level[i].forward; update[i] = x; } /* We may have multiple elements with the same score, what we need * is to find the element with both the right score and object. */ x = x->level[0].forward; if (x && score == x->score && equalStringObjects(x->obj,obj)) { zslDeleteNode(zsl, x, update); zslFreeNode(x); return 1; } // 没找到对应的元素返回0 return 0; /* not found */ } // 内部方法start // Gte:大于等于 static int zslValueGteMin(double value, zrangespec *spec) { return spec->minex ? (value > spec->min) : (value >= spec->min); } // Lte:小于等于 static int zslValueLteMax(double value, zrangespec *spec) { return spec->maxex ? (value < spec->max) : (value <= spec->max); } // 内部方法end /* Returns if there is a part of the zset is in range. */ /* 判断zsl是不是又一部分包含在range内,如果zsl的一部分在range内则返回1否则返回0 */ int zslIsInRange(zskiplist *zsl, zrangespec *range) { zskiplistNode *x; /* Test for ranges that will always be empty. */ /* 判断错误的情况,min大于max */ if (range->min > range->max || (range->min == range->max && (range->minex || range->maxex))) return 0; x = zsl->tail; // score最大的元素 // 最大的元素都没range中最小的元素大,返回0(false) if (x == NULL || !zslValueGteMin(x->score,range)) return 0; x = zsl->header->level[0].forward; // 最小的元素都没range中最大的元素小,返回0(false) if (x == NULL || !zslValueLteMax(x->score,range)) return 0; return 1; } /* Find the first node that is contained in the specified range. * Returns NULL when no element is contained in the range. */ // 获取zsl中第一个在range中的节点(顺序从小到大),不存在时返回NULL zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) { zskiplistNode *x; int i; /* If everything is out of range, return early. */ // 判断整个zsl有没有一部分在range中的元素,如果整个zsl都不在range中则直接返回(通过zsl的边界值进行判断) if (!zslIsInRange(zsl,range)) return NULL; x = zsl->header; // 从顶层往下遍历 for (i = zsl->level-1; i >= 0; i--) { /* Go forward while *OUT* of range. */ // 获取当前层最后一个score小于(或小于等于)range最小值的节点 while (x->level[i].forward && !zslValueGteMin(x->level[i].forward->score,range)) x = x->level[i].forward; } /* This is an inner range, so the next node cannot be NULL. */ // 第0层包含所有节点,第0层最后一个score小于(或小于等于)range最小值的节点,其前驱节点"可能"就是第一个包含在range中的节点 x = x->level[0].forward; redisAssert(x != NULL); /* Check if score <= max. */ // 上面说"可能"就是第一个包含在range中的节点,是因为这里还需要判断这个节点是不是小于range中的最大值节点,如果不是,则不是包含在range中的节点 if (!zslValueLteMax(x->score,range)) return NULL; return x; } /* Find the last node that is contained in the specified range. * Returns NULL when no element is contained in the range. */ // 返回zsl中最后一个在range中的节点(顺序从小到大) zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) { zskiplistNode *x; int i; /* If everything is out of range, return early. */ if (!zslIsInRange(zsl,range)) return NULL; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { /* Go forward while *IN* range. */ // 获取当前层最后一个score小于(或小于等于)range最大值的节点,这个节点可能就是最后一个包含在range中的元素 while (x->level[i].forward && zslValueLteMax(x->level[i].forward->score,range)) x = x->level[i].forward; } /* This is an inner range, so this node cannot be NULL. */ redisAssert(x != NULL); /* Check if score >= min. */ // 判断这个元素是不是大于range中的最小元素 if (!zslValueGteMin(x->score,range)) return NULL; return x; } /* Delete all the elements with score between min and max from the skiplist. * Min and max are inclusive, so a score >= min || score <= max is deleted. * Note that this function takes the reference to the hash table view of the * sorted set, in order to remove the elements from the hash table too. */ // 删除zsl中所有score在range中的节点 unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) { zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; unsigned long removed = 0; int i; x = zsl->header; // 找到zsl中最后一个小于range.min的节点 for (i = zsl->level-1; i >= 0; i--) { while (x->level[i].forward && (range->minex ? x->level[i].forward->score <= range->min : x->level[i].forward->score < range->min)) x = x->level[i].forward; update[i] = x; } /* Current node is the last with score < or <= min. */ // zsl中最后一个小于range.min的节点的前一个节点可能在range中,以此作为'初始节点'从此节点开始遍历后面的节点 x = x->level[0].forward; /* Delete nodes while in range. */ // 从'初始节点'开始往后遍历,如果节点的score小于range.max,则将x指向下一个节点,并删除此节点 while (x && (range->maxex ? x->score < range->max : x->score <= range->max)) { zskiplistNode *next = x->level[0].forward; zslDeleteNode(zsl,x,update); dictDelete(dict,x->obj); // 这里暂时不能理解,大概是在dict中保存了一份这个obj的指针的复制 zslFreeNode(x); removed++; x = next; } return removed; } // Lex(lexis):词 // 删除zsl中obj字段值在range范围中的节点,obj的内容一般是字符串,对应redis的Zremrangebylex命令 unsigned long zslDeleteRangeByLex(zskiplist *zsl, zlexrangespec *range, dict *dict) { zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; unsigned long removed = 0; int i; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { while (x->level[i].forward && !zslLexValueGteMin(x->level[i].forward->obj,range)) x = x->level[i].forward; update[i] = x; } /* Current node is the last with score < or <= min. */ x = x->level[0].forward; /* Delete nodes while in range. */ // 确定node的obj字段小于range的最大值(也就是在range范围内) while (x && zslLexValueLteMax(x->obj,range)) { zskiplistNode *next = x->level[0].forward; zslDeleteNode(zsl,x,update); dictDelete(dict,x->obj); zslFreeNode(x); removed++; x = next; } return removed; } /* Delete all the elements with rank between start and end from the skiplist. * Start and end are inclusive. Note that start and end need to be 1-based */ // 删除zsl按照score排序后index在start~end之间的元素,下标(index)从1开始(下标0是header节点,这个节点不存放任何数据) // 返回值为删除元素的个数 unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) { zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; unsigned long traversed = 0, removed = 0; int i; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { // 从顶层向下层找到每个层级最后一个“在原链表中对应的index”小于start的元素 while (x->level[i].forward && (traversed + x->level[i].span) < start) { traversed += x->level[i].span; x = x->level[i].forward; } update[i] = x; } traversed++; x = x->level[0].forward; // 确保x小于end,即确认x在start与end之间 while (x && traversed <= end) { zskiplistNode *next = x->level[0].forward; zslDeleteNode(zsl,x,update); dictDelete(dict,x->obj); zslFreeNode(x); removed++; traversed++; x = next; } return removed; } /* Find the rank for an element by both score and key. * Returns 0 when the element cannot be found, rank otherwise. * Note that the rank is 1-based due to the span of zsl->header to the * first element. */ // 通过key和分数获取下标(排名/Rank) zsl中排名(Rank) == 下标,若找不到则返回0 // 注意score只是用来快速定位用的,不是必须保证参数score和o都满足才返回,只要满足节点score >= 参数score,且节点obj == o则返回Rank unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) { zskiplistNode *x; unsigned long rank = 0; int i; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { // 从顶向下逐层查找,直到找到score和和obj与参数相同的节点,在循环查找的同时,记录index while (x->level[i].forward && (x->level[i].forward->score < score || (x->level[i].forward->score == score && compareStringObjects(x->level[i].forward->obj,o) <= 0))) { rank += x->level[i].span; x = x->level[i].forward; } /* x might be equal to zsl->header, so test if obj is non-NULL */ if (x->obj && equalStringObjects(x->obj,o)) { return rank; } } return 0; } /* Finds an element by its rank. The rank argument needs to be 1-based. */ // 返回zsl中指定Rank(index)的元素(节点) zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) { zskiplistNode *x; unsigned long traversed = 0; // 用于记录当前节点的index int i; x = zsl->header; // 还是从顶向下逐层查找,由于有span属性,使得从顶向下遍历速度会快很多 for (i = zsl->level-1; i >= 0; i--) { while (x->level[i].forward && (traversed + x->level[i].span) <= rank) { traversed += x->level[i].span; x = x->level[i].forward; } if (traversed == rank) { return x; } } return NULL; } /* Populate the rangespec according to the objects min and max. */ // zrangespec解析函数,根据具体的min和max设置参数spec表示的range和左右的开闭区间 // 大小判断使用数字序 // parse:解析 static int zslParseRange(robj *min, robj *max, zrangespec *spec) { char *eptr; spec->minex = spec->maxex = 0; /* Parse the min-max interval. If one of the values is prefixed * by the "(" character, it's considered "open". For instance * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */ // 判断range对于min和max是开区间还是闭区间 // 以ZRANGEBYSCORE举例,若命令格式为ZRANGEBYSCORE zset (1.5 (2.5 则为开区间 15 < x < 2.5 // 若命令格式为ZRANGEBYSCORE zset 1.5 2.5 则为闭区间 15 <= x <= 2.5,区别在于min数字前是否有小括号 // 若编码类型是int则直接使用 if (min->encoding == REDIS_ENCODING_INT) { spec->min = (long)min->ptr; } // 否则判断是否打头有"(",有则为开区间,并赋上range的min值 else { if (((char*)min->ptr)[0] == '(') { spec->min = strtod((char*)min->ptr+1,&eptr); if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR; spec->minex = 1; } else { spec->min = strtod((char*)min->ptr,&eptr); if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR; } } // 操作同上,为range的max赋值 if (max->encoding == REDIS_ENCODING_INT) { spec->max = (long)max->ptr; } else { if (((char*)max->ptr)[0] == '(') { spec->max = strtod((char*)max->ptr+1,&eptr); if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR; spec->maxex = 1; } else { spec->max = strtod((char*)max->ptr,&eptr); if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR; } } return REDIS_OK; } /* ------------------------ Lexicographic ranges ---------------------------- */ /* ------ 字典 ranges ------ */ /* Parse max or min argument of ZRANGEBYLEX. * (foo means foo (open interval) * [foo means foo (closed interval) * - means the min string possible * + means the max string possible * * If the string is valid the *dest pointer is set to the redis object * that will be used for the comparision, and ex will be set to 0 or 1 * respectively if the item is exclusive or inclusive. REDIS_OK will be * returned. * * If the string is not a valid range REDIS_ERR is returned, and the value * of *dest and *ex is undefined. */ // 解析词典序的单个range项,"单个range项"指的是命令 ZRANGEBYLEX zset min max中的min或max // item参数代表待解析的项; dest代表解析完的项; ex代表是否为闭区间,-和+永远是开区间 // min的可能格式: -(减号) 、(${单词}、[${单词} // -(减号):代表最小的字符串;'('后面接单词代表开区间;'['后面接单词代表闭区间 // max的可能格式: +(加号) 、(${单词}、[${单词} // +(加号):代表最大的字符串;'('后面接单词代表开区间;'['后面接单词代表闭区间 int zslParseLexRangeItem(robj *item, robj **dest, int *ex) { char *c = item->ptr; switch(c[0]) { case '+': if (c[1] != '\0') return REDIS_ERR; *ex = 0; *dest = shared.maxstring; // 对shared.maxstring的引用计数器进行自增操作 incrRefCount(shared.maxstring); return REDIS_OK; case '-': if (c[1] != '\0') return REDIS_ERR; *ex = 0; *dest = shared.minstring; // 对shared.minstring的引用计数器进行自增操作 incrRefCount(shared.minstring); return REDIS_OK; case '(': *ex = 1; // 构建string类型的redisObject对象 *dest = createStringObject(c+1,sdslen(c)-1); return REDIS_OK; case '[': *ex = 0; *dest = createStringObject(c+1,sdslen(c)-1); return REDIS_OK; default: return REDIS_ERR; } } /* Populate the rangespec according to the objects min and max. * * Return REDIS_OK on success. On error REDIS_ERR is returned. * When OK is returned the structure must be freed with zslFreeLexRange(), * otherwise no release is needed. */ // zrangespec解析函数,根据具体的min和max设置参数spec表示的range和左右的开闭区间 // 大小判断使用字典序 static int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec) { /* The range can't be valid if objects are integer encoded. * Every item must start with ( or [. */ // 如果min获取max是int编码类型则直接返回错误,字典序的range必须有'('或'[' if (min->encoding == REDIS_ENCODING_INT || max->encoding == REDIS_ENCODING_INT) return REDIS_ERR; spec->min = spec->max = NULL; // 使用zslParseLexRangeItem()方法为zlexrangespec的所有字段赋值 if (zslParseLexRangeItem(min, &spec->min, &spec->minex) == REDIS_ERR || zslParseLexRangeItem(max, &spec->max, &spec->maxex) == REDIS_ERR) { // 引用自减操作,这里会直接自减至0然后被free掉 if (spec->min) decrRefCount(spec->min); if (spec->max) decrRefCount(spec->max); return REDIS_ERR; } else { return REDIS_OK; } } /* Free a lex range structure, must be called only after zelParseLexRange() * populated the structure with success (REDIS_OK returned). */ // 释放zlexrangespec的min和max,调用前必须保证min和max有数据 void zslFreeLexRange(zlexrangespec *spec) { decrRefCount(spec->min); decrRefCount(spec->max); } /* This is just a wrapper to compareStringObjects() that is able to * handle shared.minstring and shared.maxstring as the equivalent of * -inf and +inf for strings */ // 按字典序进行String比较的方法,只是compareStringObjects()方法的一个包装, // 对shared.minstring和shared.maxstring进行情况进行了特殊的判断 int compareStringObjectsForLexRange(robj *a, robj *b) { if (a == b) return 0; /* This makes sure that we handle inf,inf and -inf,-inf ASAP. One special case less. */ // 对shared.minstring和shared.maxstring的特殊判断,若a是maxstring则永远都返回1,a是minstring则永远都返回-1 // 若b是maxstring则永远都返回-1,b是minstring则永远都返回1 if (a == shared.minstring || b == shared.maxstring) return -1; if (a == shared.maxstring || b == shared.minstring) return 1; return compareStringObjects(a,b); } // 根据字典序进行判断,value与spec->min的关系,在minex为1时判断value是否大于spec->min,在minex为0时判断value是否大于等于spec->min // minex代表是不是开区间,1代表是,0代表不是 static int zslLexValueGteMin(robj *value, zlexrangespec *spec) { return spec->minex ? (compareStringObjectsForLexRange(value,spec->min) > 0) : (compareStringObjectsForLexRange(value,spec->min) >= 0); } // 根据字典序进行判断,value与spec->max的关系,在maxex为1时判断value是否小于spec->max,在minex为0时判断value是否小于等于spec->max // maxex代表是不是开区间,1代表是,0代表不是 static int zslLexValueLteMax(robj *value, zlexrangespec *spec) { return spec->maxex ? (compareStringObjectsForLexRange(value,spec->max) < 0) : (compareStringObjectsForLexRange(value,spec->max) <= 0); } /* Returns if there is a part of the zset is in the lex range. */ // 根据字典序,判断zsl是否有含在range中的部分,流程与zslIsInRange()方法类似 int zslIsInLexRange(zskiplist *zsl, zlexrangespec *range) { zskiplistNode *x; /* Test for ranges that will always be empty. */ if (compareStringObjectsForLexRange(range->min,range->max) > 1 || (compareStringObjects(range->min,range->max) == 0 && (range->minex || range->maxex))) return 0; x = zsl->tail; if (x == NULL || !zslLexValueGteMin(x->obj,range)) return 0; x = zsl->header->level[0].forward; if (x == NULL || !zslLexValueLteMax(x->obj,range)) return 0; return 1; } /* Find the first node that is contained in the specified lex range. * Returns NULL when no element is contained in the range. */ // 根据字典序获取zsl中第一个包含在range中的节点 zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range) { zskiplistNode *x; int i; /* If everything is out of range, return early. */ if (!zslIsInLexRange(zsl,range)) return NULL; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { /* Go forward while *OUT* of range. */ while (x->level[i].forward && !zslLexValueGteMin(x->level[i].forward->obj,range)) x = x->level[i].forward; } /* This is an inner range, so the next node cannot be NULL. */ x = x->level[0].forward; redisAssert(x != NULL); /* Check if score <= max. */ if (!zslLexValueLteMax(x->obj,range)) return NULL; return x; } /* Find the last node that is contained in the specified range. * Returns NULL when no element is contained in the range. */ // 根据字典序获取zsl中最后一个包含在range中的节点 zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range) { zskiplistNode *x; int i; /* If everything is out of range, return early. */ if (!zslIsInLexRange(zsl,range)) return NULL; x = zsl->header; for (i = zsl->level-1; i >= 0; i--) { /* Go forward while *IN* range. */ while (x->level[i].forward && zslLexValueLteMax(x->level[i].forward->obj,range)) x = x->level[i].forward; } /* This is an inner range, so this node cannot be NULL. */ redisAssert(x != NULL); /* Check if score >= min. */ if (!zslLexValueGteMin(x->obj,range)) return NULL; return x; } /*----------------------------------------------------------------------------- * Ziplist-backed sorted set API *----------------------------------------------------------------------------*/ /* 看完ziplist再回来看 */ double zzlGetScore(unsigned char *sptr) { unsigned char *vstr; unsigned int vlen; long long vlong; char buf[128]; double score; redisAssert(sptr != NULL); redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong)); if (vstr) { memcpy(buf,vstr,vlen); buf[vlen] = '\0'; score = strtod(buf,NULL); } else { score = vlong; } return score; } /* Return a ziplist element as a Redis string object. * This simple abstraction can be used to simplifies some code at the * cost of some performance. */ robj *ziplistGetObject(unsigned char *sptr) { unsigned char *vstr; unsigned int vlen; long long vlong; redisAssert(sptr != NULL); redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong)); if (vstr) { return createStringObject((char*)vstr,vlen); } else { return createStringObjectFromLongLong(vlong); } } /* Compare element in sorted set with given element. */ int zzlCompareElements(unsigned char *eptr, unsigned char *cstr, unsigned int clen) { unsigned char *vstr; unsigned int vlen; long long vlong; unsigned char vbuf[32]; int minlen, cmp; redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong)); if (vstr == NULL) { /* Store string representation of long long in buf. */ vlen = ll2string((char*)vbuf,sizeof(vbuf),vlong); vstr = vbuf; } minlen = (vlen < clen) ? vlen : clen; cmp = memcmp(vstr,cstr,minlen); if (cmp == 0) return vlen-clen; return cmp; } unsigned int zzlLength(unsigned char *zl) { return ziplistLen(zl)/2; } /* Move to next entry based on the values in eptr and sptr. Both are set to * NULL when there is no next entry. */ void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) { unsigned char *_eptr, *_sptr; redisAssert(*eptr != NULL && *sptr != NULL); _eptr = ziplistNext(zl,*sptr); if (_eptr != NULL) { _sptr = ziplistNext(zl,_eptr); redisAssert(_sptr != NULL); } else { /* No next entry. */ _sptr = NULL; } *eptr = _eptr; *sptr = _sptr; } /* Move to the previous entry based on the values in eptr and sptr. Both are * set to NULL when there is no next entry. */ void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) { unsigned char *_eptr, *_sptr; redisAssert(*eptr != NULL && *sptr != NULL); _sptr = ziplistPrev(zl,*eptr); if (_sptr != NULL) { _eptr = ziplistPrev(zl,_sptr); redisAssert(_eptr != NULL); } else { /* No previous entry. */ _eptr = NULL; } *eptr = _eptr; *sptr = _sptr; } /* Returns if there is a part of the zset is in range. Should only be used * internally by zzlFirstInRange and zzlLastInRange. */ int zzlIsInRange(unsigned char *zl, zrangespec *range) { unsigned char *p; double score; /* Test for ranges that will always be empty. */ if (range->min > range->max || (range->min == range->max && (range->minex || range->maxex))) return 0; p = ziplistIndex(zl,-1); /* Last score. */ if (p == NULL) return 0; /* Empty sorted set */ score = zzlGetScore(p); if (!zslValueGteMin(score,range)) return 0; p = ziplistIndex(zl,1); /* First score. */ redisAssert(p != NULL); score = zzlGetScore(p); if (!zslValueLteMax(score,range)) return 0; return 1; } /* Find pointer to the first element contained in the specified range. * Returns NULL when no element is contained in the range. */ unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range) { unsigned char *eptr = ziplistIndex(zl,0), *sptr; double score; /* If everything is out of range, return early. */ if (!zzlIsInRange(zl,range)) return NULL; while (eptr != NULL) { sptr = ziplistNext(zl,eptr); redisAssert(sptr != NULL); score = zzlGetScore(sptr); if (zslValueGteMin(score,range)) { /* Check if score <= max. */ if (zslValueLteMax(score,range)) return eptr; return NULL; } /* Move to next element. */ eptr = ziplistNext(zl,sptr); } return NULL; } /* Find pointer to the last element contained in the specified range. * Returns NULL when no element is contained in the range. */ unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range) { unsigned char *eptr = ziplistIndex(zl,-2), *sptr; double score; /* If everything is out of range, return early. */ if (!zzlIsInRange(zl,range)) return NULL; while (eptr != NULL) { sptr = ziplistNext(zl,eptr); redisAssert(sptr != NULL); score = zzlGetScore(sptr); if (zslValueLteMax(score,range)) { /* Check if score >= min. */ if (zslValueGteMin(score,range)) return eptr; return NULL; } /* Move to previous element by moving to the score of previous element. * When this returns NULL, we know there also is no element. */ sptr = ziplistPrev(zl,eptr); if (sptr != NULL) redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL); else eptr = NULL; } return NULL; } static int zzlLexValueGteMin(unsigned char *p, zlexrangespec *spec) { robj *value = ziplistGetObject(p); int res = zslLexValueGteMin(value,spec); decrRefCount(value); return res; } static int zzlLexValueLteMax(unsigned char *p, zlexrangespec *spec) { robj *value = ziplistGetObject(p); int res = zslLexValueLteMax(value,spec); decrRefCount(value); return res; } /* Returns if there is a part of the zset is in range. Should only be used * internally by zzlFirstInRange and zzlLastInRange. */ int zzlIsInLexRange(unsigned char *zl, zlexrangespec *range) { unsigned char *p; /* Test for ranges that will always be empty. */ if (compareStringObjectsForLexRange(range->min,range->max) > 1 || (compareStringObjects(range->min,range->max) == 0 && (range->minex || range->maxex))) return 0; p = ziplistIndex(zl,-2); /* Last element. */ if (p == NULL) return 0; if (!zzlLexValueGteMin(p,range)) return 0; p = ziplistIndex(zl,0); /* First element. */ redisAssert(p != NULL); if (!zzlLexValueLteMax(p,range)) return 0; return 1; } /* Find pointer to the first element contained in the specified lex range. * Returns NULL when no element is contained in the range. */ unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range) { unsigned char *eptr = ziplistIndex(zl,0), *sptr; /* If everything is out of range, return early. */ if (!zzlIsInLexRange(zl,range)) return NULL; while (eptr != NULL) { if (zzlLexValueGteMin(eptr,range)) { /* Check if score <= max. */ if (zzlLexValueLteMax(eptr,range)) return eptr; return NULL; } /* Move to next element. */ sptr = ziplistNext(zl,eptr); /* This element score. Skip it. */ redisAssert(sptr != NULL); eptr = ziplistNext(zl,sptr); /* Next element. */ } return NULL; } /* Find pointer to the last element contained in the specified lex range. * Returns NULL when no element is contained in the range. */ unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range) { unsigned char *eptr = ziplistIndex(zl,-2), *sptr; /* If everything is out of range, return early. */ if (!zzlIsInLexRange(zl,range)) return NULL; while (eptr != NULL) { if (zzlLexValueLteMax(eptr,range)) { /* Check if score >= min. */ if (zzlLexValueGteMin(eptr,range)) return eptr; return NULL; } /* Move to previous element by moving to the score of previous element. * When this returns NULL, we know there also is no element. */ sptr = ziplistPrev(zl,eptr); if (sptr != NULL) redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL); else eptr = NULL; } return NULL; } unsigned char *zzlFind(unsigned char *zl, robj *ele, double *score) { unsigned char *eptr = ziplistIndex(zl,0), *sptr; ele = getDecodedObject(ele); while (eptr != NULL) { sptr = ziplistNext(zl,eptr); redisAssertWithInfo(NULL,ele,sptr != NULL); if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) { /* Matching element, pull out score. */ if (score != NULL) *score = zzlGetScore(sptr); decrRefCount(ele); return eptr; } /* Move to next element. */ eptr = ziplistNext(zl,sptr); } decrRefCount(ele); return NULL; } /* Delete (element,score) pair from ziplist. Use local copy of eptr because we * don't want to modify the one given as argument. */ unsigned char *zzlDelete(unsigned char *zl, unsigned char *eptr) { unsigned char *p = eptr; /* TODO: add function to ziplist API to delete N elements from offset. */ zl = ziplistDelete(zl,&p); zl = ziplistDelete(zl,&p); return zl; } unsigned char *zzlInsertAt(unsigned char *zl, unsigned char *eptr, robj *ele, double score) { unsigned char *sptr; char scorebuf[128]; int scorelen; size_t offset; redisAssertWithInfo(NULL,ele,ele->encoding == REDIS_ENCODING_RAW); scorelen = d2string(scorebuf,sizeof(scorebuf),score); if (eptr == NULL) { zl = ziplistPush(zl,ele->ptr,sdslen(ele->ptr),ZIPLIST_TAIL); zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL); } else { /* Keep offset relative to zl, as it might be re-allocated. */ offset = eptr-zl; zl = ziplistInsert(zl,eptr,ele->ptr,sdslen(ele->ptr)); eptr = zl+offset; /* Insert score after the element. */ redisAssertWithInfo(NULL,ele,(sptr = ziplistNext(zl,eptr)) != NULL); zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen); } return zl; } /* Insert (element,score) pair in ziplist. This function assumes the element is * not yet present in the list. */ unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score) { unsigned char *eptr = ziplistIndex(zl,0), *sptr; double s; ele = getDecodedObject(ele); while (eptr != NULL) { sptr = ziplistNext(zl,eptr); redisAssertWithInfo(NULL,ele,sptr != NULL); s = zzlGetScore(sptr); if (s > score) { /* First element with score larger than score for element to be * inserted. This means we should take its spot in the list to * maintain ordering. */ zl = zzlInsertAt(zl,eptr,ele,score); break; } else if (s == score) { /* Ensure lexicographical ordering for elements. */ if (zzlCompareElements(eptr,ele->ptr,sdslen(ele->ptr)) > 0) { zl = zzlInsertAt(zl,eptr,ele,score); break; } } /* Move to next element. */ eptr = ziplistNext(zl,sptr); } /* Push on tail of list when it was not yet inserted. */ if (eptr == NULL) zl = zzlInsertAt(zl,NULL,ele,score); decrRefCount(ele); return zl; } unsigned char *zzlDeleteRangeByScore(unsigned char *zl, zrangespec *range, unsigned long *deleted) { unsigned char *eptr, *sptr; double score; unsigned long num = 0; if (deleted != NULL) *deleted = 0; eptr = zzlFirstInRange(zl,range); if (eptr == NULL) return zl; /* When the tail of the ziplist is deleted, eptr will point to the sentinel * byte and ziplistNext will return NULL. */ while ((sptr = ziplistNext(zl,eptr)) != NULL) { score = zzlGetScore(sptr); if (zslValueLteMax(score,range)) { /* Delete both the element and the score. */ zl = ziplistDelete(zl,&eptr); zl = ziplistDelete(zl,&eptr); num++; } else { /* No longer in range. */ break; } } if (deleted != NULL) *deleted = num; return zl; } unsigned char *zzlDeleteRangeByLex(unsigned char *zl, zlexrangespec *range, unsigned long *deleted) { unsigned char *eptr, *sptr; unsigned long num = 0; if (deleted != NULL) *deleted = 0; eptr = zzlFirstInLexRange(zl,range); if (eptr == NULL) return zl; /* When the tail of the ziplist is deleted, eptr will point to the sentinel * byte and ziplistNext will return NULL. */ while ((sptr = ziplistNext(zl,eptr)) != NULL) { if (zzlLexValueLteMax(eptr,range)) { /* Delete both the element and the score. */ zl = ziplistDelete(zl,&eptr); zl = ziplistDelete(zl,&eptr); num++; } else { /* No longer in range. */ break; } } if (deleted != NULL) *deleted = num; return zl; } /* Delete all the elements with rank between start and end from the skiplist. * Start and end are inclusive. Note that start and end need to be 1-based */ unsigned char *zzlDeleteRangeByRank(unsigned char *zl, unsigned int start, unsigned int end, unsigned long *deleted) { unsigned int num = (end-start)+1; if (deleted) *deleted = num; zl = ziplistDeleteRange(zl,2*(start-1),2*num); return zl; } /*----------------------------------------------------------------------------- * Common sorted set API *----------------------------------------------------------------------------*/ unsigned int zsetLength(robj *zobj) { int length = -1; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { length = zzlLength(zobj->ptr); } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { length = ((zset*)zobj->ptr)->zsl->length; } else { redisPanic("Unknown sorted set encoding"); } return length; } void zsetConvert(robj *zobj, int encoding) { zset *zs; zskiplistNode *node, *next; robj *ele; double score; if (zobj->encoding == encoding) return; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; unsigned char *vstr; unsigned int vlen; long long vlong; if (encoding != REDIS_ENCODING_SKIPLIST) redisPanic("Unknown target encoding"); zs = zmalloc(sizeof(*zs)); zs->dict = dictCreate(&zsetDictType,NULL); zs->zsl = zslCreate(); eptr = ziplistIndex(zl,0); redisAssertWithInfo(NULL,zobj,eptr != NULL); sptr = ziplistNext(zl,eptr); redisAssertWithInfo(NULL,zobj,sptr != NULL); while (eptr != NULL) { score = zzlGetScore(sptr); redisAssertWithInfo(NULL,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong)); if (vstr == NULL) ele = createStringObjectFromLongLong(vlong); else ele = createStringObject((char*)vstr,vlen); /* Has incremented refcount since it was just created. */ node = zslInsert(zs->zsl,score,ele); redisAssertWithInfo(NULL,zobj,dictAdd(zs->dict,ele,&node->score) == DICT_OK); incrRefCount(ele); /* Added to dictionary. */ zzlNext(zl,&eptr,&sptr); } zfree(zobj->ptr); zobj->ptr = zs; zobj->encoding = REDIS_ENCODING_SKIPLIST; } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { unsigned char *zl = ziplistNew(); if (encoding != REDIS_ENCODING_ZIPLIST) redisPanic("Unknown target encoding"); /* Approach similar to zslFree(), since we want to free the skiplist at * the same time as creating the ziplist. */ zs = zobj->ptr; dictRelease(zs->dict); node = zs->zsl->header->level[0].forward; zfree(zs->zsl->header); zfree(zs->zsl); while (node) { ele = getDecodedObject(node->obj); zl = zzlInsertAt(zl,NULL,ele,node->score); decrRefCount(ele); next = node->level[0].forward; zslFreeNode(node); node = next; } zfree(zs); zobj->ptr = zl; zobj->encoding = REDIS_ENCODING_ZIPLIST; } else { redisPanic("Unknown sorted set encoding"); } } /*----------------------------------------------------------------------------- * Sorted set commands *----------------------------------------------------------------------------*/ /* This generic command implements both ZADD and ZINCRBY. */ void zaddGenericCommand(redisClient *c, int incr) { static char *nanerr = "resulting score is not a number (NaN)"; robj *key = c->argv[1]; robj *ele; robj *zobj; robj *curobj; double score = 0, *scores = NULL, curscore = 0.0; int j, elements = (c->argc-2)/2; int added = 0, updated = 0; if (c->argc % 2) { addReply(c,shared.syntaxerr); return; } /* Start parsing all the scores, we need to emit any syntax error * before executing additions to the sorted set, as the command should * either execute fully or nothing at all. */ scores = zmalloc(sizeof(double)*elements); for (j = 0; j < elements; j++) { if (getDoubleFromObjectOrReply(c,c->argv[2+j*2],&scores[j],NULL) != REDIS_OK) goto cleanup; } /* Lookup the key and create the sorted set if does not exist. */ zobj = lookupKeyWrite(c->db,key); if (zobj == NULL) { if (server.zset_max_ziplist_entries == 0 || server.zset_max_ziplist_value < sdslen(c->argv[3]->ptr)) { zobj = createZsetObject(); } else { zobj = createZsetZiplistObject(); } dbAdd(c->db,key,zobj); } else { if (zobj->type != REDIS_ZSET) { addReply(c,shared.wrongtypeerr); goto cleanup; } } for (j = 0; j < elements; j++) { score = scores[j]; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *eptr; /* Prefer non-encoded element when dealing with ziplists. */ ele = c->argv[3+j*2]; if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) { if (incr) { score += curscore; if (isnan(score)) { addReplyError(c,nanerr); goto cleanup; } } /* Remove and re-insert when score changed. */ if (score != curscore) { zobj->ptr = zzlDelete(zobj->ptr,eptr); zobj->ptr = zzlInsert(zobj->ptr,ele,score); server.dirty++; updated++; } } else { /* Optimize: check if the element is too large or the list * becomes too long *before* executing zzlInsert. */ zobj->ptr = zzlInsert(zobj->ptr,ele,score); if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries) zsetConvert(zobj,REDIS_ENCODING_SKIPLIST); if (sdslen(ele->ptr) > server.zset_max_ziplist_value) zsetConvert(zobj,REDIS_ENCODING_SKIPLIST); server.dirty++; added++; } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplistNode *znode; dictEntry *de; ele = c->argv[3+j*2] = tryObjectEncoding(c->argv[3+j*2]); de = dictFind(zs->dict,ele); if (de != NULL) { curobj = dictGetKey(de); curscore = *(double*)dictGetVal(de); if (incr) { score += curscore; if (isnan(score)) { addReplyError(c,nanerr); /* Don't need to check if the sorted set is empty * because we know it has at least one element. */ goto cleanup; } } /* Remove and re-insert when score changed. We can safely * delete the key object from the skiplist, since the * dictionary still has a reference to it. */ if (score != curscore) { redisAssertWithInfo(c,curobj,zslDelete(zs->zsl,curscore,curobj)); znode = zslInsert(zs->zsl,score,curobj); incrRefCount(curobj); /* Re-inserted in skiplist. */ dictGetVal(de) = &znode->score; /* Update score ptr. */ server.dirty++; updated++; } } else { znode = zslInsert(zs->zsl,score,ele); incrRefCount(ele); /* Inserted in skiplist. */ redisAssertWithInfo(c,NULL,dictAdd(zs->dict,ele,&znode->score) == DICT_OK); incrRefCount(ele); /* Added to dictionary. */ server.dirty++; added++; } } else { redisPanic("Unknown sorted set encoding"); } } if (incr) /* ZINCRBY */ addReplyDouble(c,score); else /* ZADD */ addReplyLongLong(c,added); cleanup: zfree(scores); if (added || updated) { signalModifiedKey(c->db,key); notifyKeyspaceEvent(REDIS_NOTIFY_ZSET, incr ? "zincr" : "zadd", key, c->db->id); } } void zaddCommand(redisClient *c) { zaddGenericCommand(c,0); } void zincrbyCommand(redisClient *c) { zaddGenericCommand(c,1); } void zremCommand(redisClient *c) { robj *key = c->argv[1]; robj *zobj; int deleted = 0, keyremoved = 0, j; if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *eptr; for (j = 2; j < c->argc; j++) { if ((eptr = zzlFind(zobj->ptr,c->argv[j],NULL)) != NULL) { deleted++; zobj->ptr = zzlDelete(zobj->ptr,eptr); if (zzlLength(zobj->ptr) == 0) { dbDelete(c->db,key); keyremoved = 1; break; } } } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; dictEntry *de; double score; for (j = 2; j < c->argc; j++) { de = dictFind(zs->dict,c->argv[j]); if (de != NULL) { deleted++; /* Delete from the skiplist */ score = *(double*)dictGetVal(de); redisAssertWithInfo(c,c->argv[j],zslDelete(zs->zsl,score,c->argv[j])); /* Delete from the hash table */ dictDelete(zs->dict,c->argv[j]); if (htNeedsResize(zs->dict)) dictResize(zs->dict); if (dictSize(zs->dict) == 0) { dbDelete(c->db,key); keyremoved = 1; break; } } } } else { redisPanic("Unknown sorted set encoding"); } if (deleted) { notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,"zrem",key,c->db->id); if (keyremoved) notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id); signalModifiedKey(c->db,key); server.dirty += deleted; } addReplyLongLong(c,deleted); } /* Implements ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX commands. */ #define ZRANGE_RANK 0 #define ZRANGE_SCORE 1 #define ZRANGE_LEX 2 void zremrangeGenericCommand(redisClient *c, int rangetype) { robj *key = c->argv[1]; robj *zobj; int keyremoved = 0; unsigned long deleted; zrangespec range; zlexrangespec lexrange; long start, end, llen; /* Step 1: Parse the range. */ if (rangetype == ZRANGE_RANK) { if ((getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK) || (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK)) return; } else if (rangetype == ZRANGE_SCORE) { if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) { addReplyError(c,"min or max is not a float"); return; } } else if (rangetype == ZRANGE_LEX) { if (zslParseLexRange(c->argv[2],c->argv[3],&lexrange) != REDIS_OK) { addReplyError(c,"min or max not valid string range item"); return; } } /* Step 2: Lookup & range sanity checks if needed. */ if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL || checkType(c,zobj,REDIS_ZSET)) goto cleanup; if (rangetype == ZRANGE_RANK) { /* Sanitize indexes. */ llen = zsetLength(zobj); if (start < 0) start = llen+start; if (end < 0) end = llen+end; if (start < 0) start = 0; /* Invariant: start >= 0, so this test will be true when end < 0. * The range is empty when start > end or start >= length. */ if (start > end || start >= llen) { addReply(c,shared.czero); goto cleanup; } if (end >= llen) end = llen-1; } /* Step 3: Perform the range deletion operation. */ if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { switch(rangetype) { case ZRANGE_RANK: zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted); break; case ZRANGE_SCORE: zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,&range,&deleted); break; case ZRANGE_LEX: zobj->ptr = zzlDeleteRangeByLex(zobj->ptr,&lexrange,&deleted); break; } if (zzlLength(zobj->ptr) == 0) { dbDelete(c->db,key); keyremoved = 1; } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; switch(rangetype) { case ZRANGE_RANK: deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict); break; case ZRANGE_SCORE: deleted = zslDeleteRangeByScore(zs->zsl,&range,zs->dict); break; case ZRANGE_LEX: deleted = zslDeleteRangeByLex(zs->zsl,&lexrange,zs->dict); break; } if (htNeedsResize(zs->dict)) dictResize(zs->dict); if (dictSize(zs->dict) == 0) { dbDelete(c->db,key); keyremoved = 1; } } else { redisPanic("Unknown sorted set encoding"); } /* Step 4: Notifications and reply. */ if (deleted) { char *event[3] = {"zremrangebyrank","zremrangebyscore","zremrangebylex"}; signalModifiedKey(c->db,key); notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,event[rangetype],key,c->db->id); if (keyremoved) notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id); } server.dirty += deleted; addReplyLongLong(c,deleted); cleanup: if (rangetype == ZRANGE_LEX) zslFreeLexRange(&lexrange); } void zremrangebyrankCommand(redisClient *c) { zremrangeGenericCommand(c,ZRANGE_RANK); } void zremrangebyscoreCommand(redisClient *c) { zremrangeGenericCommand(c,ZRANGE_SCORE); } void zremrangebylexCommand(redisClient *c) { zremrangeGenericCommand(c,ZRANGE_LEX); } typedef struct { robj *subject; int type; /* Set, sorted set */ int encoding; double weight; union { /* Set iterators. */ union _iterset { struct { intset *is; int ii; } is; struct { dict *dict; dictIterator *di; dictEntry *de; } ht; } set; /* Sorted set iterators. */ union _iterzset { struct { unsigned char *zl; unsigned char *eptr, *sptr; } zl; struct { zset *zs; zskiplistNode *node; } sl; } zset; } iter; } zsetopsrc; /* Use dirty flags for pointers that need to be cleaned up in the next * iteration over the zsetopval. The dirty flag for the long long value is * special, since long long values don't need cleanup. Instead, it means that * we already checked that "ell" holds a long long, or tried to convert another * representation into a long long value. When this was successful, * OPVAL_VALID_LL is set as well. */ #define OPVAL_DIRTY_ROBJ 1 #define OPVAL_DIRTY_LL 2 #define OPVAL_VALID_LL 4 /* Store value retrieved from the iterator. */ typedef struct { int flags; unsigned char _buf[32]; /* Private buffer. */ robj *ele; unsigned char *estr; unsigned int elen; long long ell; double score; } zsetopval; typedef union _iterset iterset; typedef union _iterzset iterzset; void zuiInitIterator(zsetopsrc *op) { if (op->subject == NULL) return; if (op->type == REDIS_SET) { iterset *it = &op->iter.set; if (op->encoding == REDIS_ENCODING_INTSET) { it->is.is = op->subject->ptr; it->is.ii = 0; } else if (op->encoding == REDIS_ENCODING_HT) { it->ht.dict = op->subject->ptr; it->ht.di = dictGetIterator(op->subject->ptr); it->ht.de = dictNext(it->ht.di); } else { redisPanic("Unknown set encoding"); } } else if (op->type == REDIS_ZSET) { iterzset *it = &op->iter.zset; if (op->encoding == REDIS_ENCODING_ZIPLIST) { it->zl.zl = op->subject->ptr; it->zl.eptr = ziplistIndex(it->zl.zl,0); if (it->zl.eptr != NULL) { it->zl.sptr = ziplistNext(it->zl.zl,it->zl.eptr); redisAssert(it->zl.sptr != NULL); } } else if (op->encoding == REDIS_ENCODING_SKIPLIST) { it->sl.zs = op->subject->ptr; it->sl.node = it->sl.zs->zsl->header->level[0].forward; } else { redisPanic("Unknown sorted set encoding"); } } else { redisPanic("Unsupported type"); } } void zuiClearIterator(zsetopsrc *op) { if (op->subject == NULL) return; if (op->type == REDIS_SET) { iterset *it = &op->iter.set; if (op->encoding == REDIS_ENCODING_INTSET) { REDIS_NOTUSED(it); /* skip */ } else if (op->encoding == REDIS_ENCODING_HT) { dictReleaseIterator(it->ht.di); } else { redisPanic("Unknown set encoding"); } } else if (op->type == REDIS_ZSET) { iterzset *it = &op->iter.zset; if (op->encoding == REDIS_ENCODING_ZIPLIST) { REDIS_NOTUSED(it); /* skip */ } else if (op->encoding == REDIS_ENCODING_SKIPLIST) { REDIS_NOTUSED(it); /* skip */ } else { redisPanic("Unknown sorted set encoding"); } } else { redisPanic("Unsupported type"); } } int zuiLength(zsetopsrc *op) { if (op->subject == NULL) return 0; if (op->type == REDIS_SET) { if (op->encoding == REDIS_ENCODING_INTSET) { return intsetLen(op->subject->ptr); } else if (op->encoding == REDIS_ENCODING_HT) { dict *ht = op->subject->ptr; return dictSize(ht); } else { redisPanic("Unknown set encoding"); } } else if (op->type == REDIS_ZSET) { if (op->encoding == REDIS_ENCODING_ZIPLIST) { return zzlLength(op->subject->ptr); } else if (op->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = op->subject->ptr; return zs->zsl->length; } else { redisPanic("Unknown sorted set encoding"); } } else { redisPanic("Unsupported type"); } } /* Check if the current value is valid. If so, store it in the passed structure * and move to the next element. If not valid, this means we have reached the * end of the structure and can abort. */ int zuiNext(zsetopsrc *op, zsetopval *val) { if (op->subject == NULL) return 0; if (val->flags & OPVAL_DIRTY_ROBJ) decrRefCount(val->ele); memset(val,0,sizeof(zsetopval)); if (op->type == REDIS_SET) { iterset *it = &op->iter.set; if (op->encoding == REDIS_ENCODING_INTSET) { int64_t ell; if (!intsetGet(it->is.is,it->is.ii,&ell)) return 0; val->ell = ell; val->score = 1.0; /* Move to next element. */ it->is.ii++; } else if (op->encoding == REDIS_ENCODING_HT) { if (it->ht.de == NULL) return 0; val->ele = dictGetKey(it->ht.de); val->score = 1.0; /* Move to next element. */ it->ht.de = dictNext(it->ht.di); } else { redisPanic("Unknown set encoding"); } } else if (op->type == REDIS_ZSET) { iterzset *it = &op->iter.zset; if (op->encoding == REDIS_ENCODING_ZIPLIST) { /* No need to check both, but better be explicit. */ if (it->zl.eptr == NULL || it->zl.sptr == NULL) return 0; redisAssert(ziplistGet(it->zl.eptr,&val->estr,&val->elen,&val->ell)); val->score = zzlGetScore(it->zl.sptr); /* Move to next element. */ zzlNext(it->zl.zl,&it->zl.eptr,&it->zl.sptr); } else if (op->encoding == REDIS_ENCODING_SKIPLIST) { if (it->sl.node == NULL) return 0; val->ele = it->sl.node->obj; val->score = it->sl.node->score; /* Move to next element. */ it->sl.node = it->sl.node->level[0].forward; } else { redisPanic("Unknown sorted set encoding"); } } else { redisPanic("Unsupported type"); } return 1; } int zuiLongLongFromValue(zsetopval *val) { if (!(val->flags & OPVAL_DIRTY_LL)) { val->flags |= OPVAL_DIRTY_LL; if (val->ele != NULL) { if (val->ele->encoding == REDIS_ENCODING_INT) { val->ell = (long)val->ele->ptr; val->flags |= OPVAL_VALID_LL; } else if (val->ele->encoding == REDIS_ENCODING_RAW) { if (string2ll(val->ele->ptr,sdslen(val->ele->ptr),&val->ell)) val->flags |= OPVAL_VALID_LL; } else { redisPanic("Unsupported element encoding"); } } else if (val->estr != NULL) { if (string2ll((char*)val->estr,val->elen,&val->ell)) val->flags |= OPVAL_VALID_LL; } else { /* The long long was already set, flag as valid. */ val->flags |= OPVAL_VALID_LL; } } return val->flags & OPVAL_VALID_LL; } robj *zuiObjectFromValue(zsetopval *val) { if (val->ele == NULL) { if (val->estr != NULL) { val->ele = createStringObject((char*)val->estr,val->elen); } else { val->ele = createStringObjectFromLongLong(val->ell); } val->flags |= OPVAL_DIRTY_ROBJ; } return val->ele; } int zuiBufferFromValue(zsetopval *val) { if (val->estr == NULL) { if (val->ele != NULL) { if (val->ele->encoding == REDIS_ENCODING_INT) { val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),(long)val->ele->ptr); val->estr = val->_buf; } else if (val->ele->encoding == REDIS_ENCODING_RAW) { val->elen = sdslen(val->ele->ptr); val->estr = val->ele->ptr; } else { redisPanic("Unsupported element encoding"); } } else { val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),val->ell); val->estr = val->_buf; } } return 1; } /* Find value pointed to by val in the source pointer to by op. When found, * return 1 and store its score in target. Return 0 otherwise. */ int zuiFind(zsetopsrc *op, zsetopval *val, double *score) { if (op->subject == NULL) return 0; if (op->type == REDIS_SET) { if (op->encoding == REDIS_ENCODING_INTSET) { if (zuiLongLongFromValue(val) && intsetFind(op->subject->ptr,val->ell)) { *score = 1.0; return 1; } else { return 0; } } else if (op->encoding == REDIS_ENCODING_HT) { dict *ht = op->subject->ptr; zuiObjectFromValue(val); if (dictFind(ht,val->ele) != NULL) { *score = 1.0; return 1; } else { return 0; } } else { redisPanic("Unknown set encoding"); } } else if (op->type == REDIS_ZSET) { zuiObjectFromValue(val); if (op->encoding == REDIS_ENCODING_ZIPLIST) { if (zzlFind(op->subject->ptr,val->ele,score) != NULL) { /* Score is already set by zzlFind. */ return 1; } else { return 0; } } else if (op->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = op->subject->ptr; dictEntry *de; if ((de = dictFind(zs->dict,val->ele)) != NULL) { *score = *(double*)dictGetVal(de); return 1; } else { return 0; } } else { redisPanic("Unknown sorted set encoding"); } } else { redisPanic("Unsupported type"); } } int zuiCompareByCardinality(const void *s1, const void *s2) { return zuiLength((zsetopsrc*)s1) - zuiLength((zsetopsrc*)s2); } #define REDIS_AGGR_SUM 1 #define REDIS_AGGR_MIN 2 #define REDIS_AGGR_MAX 3 #define zunionInterDictValue(_e) (dictGetVal(_e) == NULL ? 1.0 : *(double*)dictGetVal(_e)) inline static void zunionInterAggregate(double *target, double val, int aggregate) { if (aggregate == REDIS_AGGR_SUM) { *target = *target + val; /* The result of adding two doubles is NaN when one variable * is +inf and the other is -inf. When these numbers are added, * we maintain the convention of the result being 0.0. */ if (isnan(*target)) *target = 0.0; } else if (aggregate == REDIS_AGGR_MIN) { *target = val < *target ? val : *target; } else if (aggregate == REDIS_AGGR_MAX) { *target = val > *target ? val : *target; } else { /* safety net */ redisPanic("Unknown ZUNION/INTER aggregate type"); } } void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) { int i, j; long setnum; int aggregate = REDIS_AGGR_SUM; zsetopsrc *src; zsetopval zval; robj *tmp; unsigned int maxelelen = 0; robj *dstobj; zset *dstzset; zskiplistNode *znode; int touched = 0; /* expect setnum input keys to be given */ if ((getLongFromObjectOrReply(c, c->argv[2], &setnum, NULL) != REDIS_OK)) return; if (setnum < 1) { addReplyError(c, "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE"); return; } /* test if the expected number of keys would overflow */ if (setnum > c->argc-3) { addReply(c,shared.syntaxerr); return; } /* read keys to be used for input */ src = zcalloc(sizeof(zsetopsrc) * setnum); for (i = 0, j = 3; i < setnum; i++, j++) { robj *obj = lookupKeyWrite(c->db,c->argv[j]); if (obj != NULL) { if (obj->type != REDIS_ZSET && obj->type != REDIS_SET) { zfree(src); addReply(c,shared.wrongtypeerr); return; } src[i].subject = obj; src[i].type = obj->type; src[i].encoding = obj->encoding; } else { src[i].subject = NULL; } /* Default all weights to 1. */ src[i].weight = 1.0; } /* parse optional extra arguments */ if (j < c->argc) { int remaining = c->argc - j; while (remaining) { if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) { j++; remaining--; for (i = 0; i < setnum; i++, j++, remaining--) { if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight, "weight value is not a float") != REDIS_OK) { zfree(src); return; } } } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) { j++; remaining--; if (!strcasecmp(c->argv[j]->ptr,"sum")) { aggregate = REDIS_AGGR_SUM; } else if (!strcasecmp(c->argv[j]->ptr,"min")) { aggregate = REDIS_AGGR_MIN; } else if (!strcasecmp(c->argv[j]->ptr,"max")) { aggregate = REDIS_AGGR_MAX; } else { zfree(src); addReply(c,shared.syntaxerr); return; } j++; remaining--; } else { zfree(src); addReply(c,shared.syntaxerr); return; } } } /* sort sets from the smallest to largest, this will improve our * algorithm's performance */ qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality); dstobj = createZsetObject(); dstzset = dstobj->ptr; memset(&zval, 0, sizeof(zval)); if (op == REDIS_OP_INTER) { /* Skip everything if the smallest input is empty. */ if (zuiLength(&src[0]) > 0) { /* Precondition: as src[0] is non-empty and the inputs are ordered * by size, all src[i > 0] are non-empty too. */ zuiInitIterator(&src[0]); while (zuiNext(&src[0],&zval)) { double score, value; score = src[0].weight * zval.score; if (isnan(score)) score = 0; for (j = 1; j < setnum; j++) { /* It is not safe to access the zset we are * iterating, so explicitly check for equal object. */ if (src[j].subject == src[0].subject) { value = zval.score*src[j].weight; zunionInterAggregate(&score,value,aggregate); } else if (zuiFind(&src[j],&zval,&value)) { value *= src[j].weight; zunionInterAggregate(&score,value,aggregate); } else { break; } } /* Only continue when present in every input. */ if (j == setnum) { tmp = zuiObjectFromValue(&zval); znode = zslInsert(dstzset->zsl,score,tmp); incrRefCount(tmp); /* added to skiplist */ dictAdd(dstzset->dict,tmp,&znode->score); incrRefCount(tmp); /* added to dictionary */ if (tmp->encoding == REDIS_ENCODING_RAW) if (sdslen(tmp->ptr) > maxelelen) maxelelen = sdslen(tmp->ptr); } } zuiClearIterator(&src[0]); } } else if (op == REDIS_OP_UNION) { dict *accumulator = dictCreate(&setDictType,NULL); dictIterator *di; dictEntry *de; double score; if (setnum) { /* Our union is at least as large as the largest set. * Resize the dictionary ASAP to avoid useless rehashing. */ dictExpand(accumulator,zuiLength(&src[setnum-1])); } /* Step 1: Create a dictionary of elements -> aggregated-scores * by iterating one sorted set after the other. */ for (i = 0; i < setnum; i++) { if (zuiLength(&src[i]) == 0) continue; zuiInitIterator(&src[i]); while (zuiNext(&src[i],&zval)) { /* Initialize value */ score = src[i].weight * zval.score; if (isnan(score)) score = 0; /* Search for this element in the accumulating dictionary. */ de = dictFind(accumulator,zuiObjectFromValue(&zval)); /* If we don't have it, we need to create a new entry. */ if (de == NULL) { tmp = zuiObjectFromValue(&zval); /* Remember the longest single element encountered, * to understand if it's possible to convert to ziplist * at the end. */ if (tmp->encoding == REDIS_ENCODING_RAW) { if (sdslen(tmp->ptr) > maxelelen) maxelelen = sdslen(tmp->ptr); } /* Add the element with its initial score. */ de = dictAddRaw(accumulator,tmp); incrRefCount(tmp); dictSetDoubleVal(de,score); } else { /* Update the score with the score of the new instance * of the element found in the current sorted set. * * Here we access directly the dictEntry double * value inside the union as it is a big speedup * compared to using the getDouble/setDouble API. */ zunionInterAggregate(&de->v.d,score,aggregate); } } zuiClearIterator(&src[i]); } /* Step 2: convert the dictionary into the final sorted set. */ di = dictGetIterator(accumulator); /* We now are aware of the final size of the resulting sorted set, * let's resize the dictionary embedded inside the sorted set to the * right size, in order to save rehashing time. */ dictExpand(dstzset->dict,dictSize(accumulator)); while((de = dictNext(di)) != NULL) { robj *ele = dictGetKey(de); score = dictGetDoubleVal(de); znode = zslInsert(dstzset->zsl,score,ele); incrRefCount(ele); /* added to skiplist */ dictAdd(dstzset->dict,ele,&znode->score); incrRefCount(ele); /* added to dictionary */ } dictReleaseIterator(di); /* We can free the accumulator dictionary now. */ dictRelease(accumulator); } else { redisPanic("Unknown operator"); } if (dbDelete(c->db,dstkey)) { signalModifiedKey(c->db,dstkey); touched = 1; server.dirty++; } if (dstzset->zsl->length) { /* Convert to ziplist when in limits. */ if (dstzset->zsl->length <= server.zset_max_ziplist_entries && maxelelen <= server.zset_max_ziplist_value) zsetConvert(dstobj,REDIS_ENCODING_ZIPLIST); dbAdd(c->db,dstkey,dstobj); addReplyLongLong(c,zsetLength(dstobj)); if (!touched) signalModifiedKey(c->db,dstkey); notifyKeyspaceEvent(REDIS_NOTIFY_ZSET, (op == REDIS_OP_UNION) ? "zunionstore" : "zinterstore", dstkey,c->db->id); server.dirty++; } else { decrRefCount(dstobj); addReply(c,shared.czero); if (touched) notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",dstkey,c->db->id); } zfree(src); } void zunionstoreCommand(redisClient *c) { zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION); } void zinterstoreCommand(redisClient *c) { zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER); } void zrangeGenericCommand(redisClient *c, int reverse) { robj *key = c->argv[1]; robj *zobj; int withscores = 0; long start; long end; int llen; int rangelen; if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) || (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return; if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) { withscores = 1; } else if (c->argc >= 5) { addReply(c,shared.syntaxerr); return; } if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; /* Sanitize indexes. */ llen = zsetLength(zobj); if (start < 0) start = llen+start; if (end < 0) end = llen+end; if (start < 0) start = 0; /* Invariant: start >= 0, so this test will be true when end < 0. * The range is empty when start > end or start >= length. */ if (start > end || start >= llen) { addReply(c,shared.emptymultibulk); return; } if (end >= llen) end = llen-1; rangelen = (end-start)+1; /* Return the result in form of a multi-bulk reply */ addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen); if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; unsigned char *vstr; unsigned int vlen; long long vlong; if (reverse) eptr = ziplistIndex(zl,-2-(2*start)); else eptr = ziplistIndex(zl,2*start); redisAssertWithInfo(c,zobj,eptr != NULL); sptr = ziplistNext(zl,eptr); while (rangelen--) { redisAssertWithInfo(c,zobj,eptr != NULL && sptr != NULL); redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong)); if (vstr == NULL) addReplyBulkLongLong(c,vlong); else addReplyBulkCBuffer(c,vstr,vlen); if (withscores) addReplyDouble(c,zzlGetScore(sptr)); if (reverse) zzlPrev(zl,&eptr,&sptr); else zzlNext(zl,&eptr,&sptr); } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *ln; robj *ele; /* Check if starting point is trivial, before doing log(N) lookup. */ if (reverse) { ln = zsl->tail; if (start > 0) ln = zslGetElementByRank(zsl,llen-start); } else { ln = zsl->header->level[0].forward; if (start > 0) ln = zslGetElementByRank(zsl,start+1); } while(rangelen--) { redisAssertWithInfo(c,zobj,ln != NULL); ele = ln->obj; addReplyBulk(c,ele); if (withscores) addReplyDouble(c,ln->score); ln = reverse ? ln->backward : ln->level[0].forward; } } else { redisPanic("Unknown sorted set encoding"); } } void zrangeCommand(redisClient *c) { zrangeGenericCommand(c,0); } void zrevrangeCommand(redisClient *c) { zrangeGenericCommand(c,1); } /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */ void genericZrangebyscoreCommand(redisClient *c, int reverse) { zrangespec range; robj *key = c->argv[1]; robj *zobj; long offset = 0, limit = -1; int withscores = 0; unsigned long rangelen = 0; void *replylen = NULL; int minidx, maxidx; /* Parse the range arguments. */ if (reverse) { /* Range is given as [max,min] */ maxidx = 2; minidx = 3; } else { /* Range is given as [min,max] */ minidx = 2; maxidx = 3; } if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) { addReplyError(c,"min or max is not a float"); return; } /* Parse optional extra arguments. Note that ZCOUNT will exactly have * 4 arguments, so we'll never enter the following code path. */ if (c->argc > 4) { int remaining = c->argc - 4; int pos = 4; while (remaining) { if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) { pos++; remaining--; withscores = 1; } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) { if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) || (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return; pos += 3; remaining -= 3; } else { addReply(c,shared.syntaxerr); return; } } } /* Ok, lookup the key and get the range */ if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; unsigned char *vstr; unsigned int vlen; long long vlong; double score; /* If reversed, get the last node in range as starting point. */ if (reverse) { eptr = zzlLastInRange(zl,&range); } else { eptr = zzlFirstInRange(zl,&range); } /* No "first" element in the specified interval. */ if (eptr == NULL) { addReply(c, shared.emptymultibulk); return; } /* Get score pointer for the first element. */ redisAssertWithInfo(c,zobj,eptr != NULL); sptr = ziplistNext(zl,eptr); /* We don't know in advance how many matching elements there are in the * list, so we push this object that will represent the multi-bulk * length in the output buffer, and will "fix" it later */ replylen = addDeferredMultiBulkLength(c); /* If there is an offset, just traverse the number of elements without * checking the score because that is done in the next loop. */ while (eptr && offset--) { if (reverse) { zzlPrev(zl,&eptr,&sptr); } else { zzlNext(zl,&eptr,&sptr); } } while (eptr && limit--) { score = zzlGetScore(sptr); /* Abort when the node is no longer in range. */ if (reverse) { if (!zslValueGteMin(score,&range)) break; } else { if (!zslValueLteMax(score,&range)) break; } /* We know the element exists, so ziplistGet should always succeed */ redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong)); rangelen++; if (vstr == NULL) { addReplyBulkLongLong(c,vlong); } else { addReplyBulkCBuffer(c,vstr,vlen); } if (withscores) { addReplyDouble(c,score); } /* Move to next node */ if (reverse) { zzlPrev(zl,&eptr,&sptr); } else { zzlNext(zl,&eptr,&sptr); } } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *ln; /* If reversed, get the last node in range as starting point. */ if (reverse) { ln = zslLastInRange(zsl,&range); } else { ln = zslFirstInRange(zsl,&range); } /* No "first" element in the specified interval. */ if (ln == NULL) { addReply(c, shared.emptymultibulk); return; } /* We don't know in advance how many matching elements there are in the * list, so we push this object that will represent the multi-bulk * length in the output buffer, and will "fix" it later */ replylen = addDeferredMultiBulkLength(c); /* If there is an offset, just traverse the number of elements without * checking the score because that is done in the next loop. */ while (ln && offset--) { if (reverse) { ln = ln->backward; } else { ln = ln->level[0].forward; } } while (ln && limit--) { /* Abort when the node is no longer in range. */ if (reverse) { if (!zslValueGteMin(ln->score,&range)) break; } else { if (!zslValueLteMax(ln->score,&range)) break; } rangelen++; addReplyBulk(c,ln->obj); if (withscores) { addReplyDouble(c,ln->score); } /* Move to next node */ if (reverse) { ln = ln->backward; } else { ln = ln->level[0].forward; } } } else { redisPanic("Unknown sorted set encoding"); } if (withscores) { rangelen *= 2; } setDeferredMultiBulkLength(c, replylen, rangelen); } void zrangebyscoreCommand(redisClient *c) { genericZrangebyscoreCommand(c,0); } void zrevrangebyscoreCommand(redisClient *c) { genericZrangebyscoreCommand(c,1); } void zcountCommand(redisClient *c) { robj *key = c->argv[1]; robj *zobj; zrangespec range; int count = 0; /* Parse the range arguments */ if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) { addReplyError(c,"min or max is not a float"); return; } /* Lookup the sorted set */ if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL || checkType(c, zobj, REDIS_ZSET)) return; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; double score; /* Use the first element in range as the starting point */ eptr = zzlFirstInRange(zl,&range); /* No "first" element */ if (eptr == NULL) { addReply(c, shared.czero); return; } /* First element is in range */ sptr = ziplistNext(zl,eptr); score = zzlGetScore(sptr); redisAssertWithInfo(c,zobj,zslValueLteMax(score,&range)); /* Iterate over elements in range */ while (eptr) { score = zzlGetScore(sptr); /* Abort when the node is no longer in range. */ if (!zslValueLteMax(score,&range)) { break; } else { count++; zzlNext(zl,&eptr,&sptr); } } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *zn; unsigned long rank; /* Find first element in range */ zn = zslFirstInRange(zsl, &range); /* Use rank of first element, if any, to determine preliminary count */ if (zn != NULL) { rank = zslGetRank(zsl, zn->score, zn->obj); count = (zsl->length - (rank - 1)); /* Find last element in range */ zn = zslLastInRange(zsl, &range); /* Use rank of last element, if any, to determine the actual count */ if (zn != NULL) { rank = zslGetRank(zsl, zn->score, zn->obj); count -= (zsl->length - rank); } } } else { redisPanic("Unknown sorted set encoding"); } addReplyLongLong(c, count); } void zlexcountCommand(redisClient *c) { robj *key = c->argv[1]; robj *zobj; zlexrangespec range; int count = 0; /* Parse the range arguments */ if (zslParseLexRange(c->argv[2],c->argv[3],&range) != REDIS_OK) { addReplyError(c,"min or max not valid string range item"); return; } /* Lookup the sorted set */ if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL || checkType(c, zobj, REDIS_ZSET)) { zslFreeLexRange(&range); return; } if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; /* Use the first element in range as the starting point */ eptr = zzlFirstInLexRange(zl,&range); /* No "first" element */ if (eptr == NULL) { zslFreeLexRange(&range); addReply(c, shared.czero); return; } /* First element is in range */ sptr = ziplistNext(zl,eptr); redisAssertWithInfo(c,zobj,zzlLexValueLteMax(eptr,&range)); /* Iterate over elements in range */ while (eptr) { /* Abort when the node is no longer in range. */ if (!zzlLexValueLteMax(eptr,&range)) { break; } else { count++; zzlNext(zl,&eptr,&sptr); } } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *zn; unsigned long rank; /* Find first element in range */ zn = zslFirstInLexRange(zsl, &range); /* Use rank of first element, if any, to determine preliminary count */ if (zn != NULL) { rank = zslGetRank(zsl, zn->score, zn->obj); count = (zsl->length - (rank - 1)); /* Find last element in range */ zn = zslLastInLexRange(zsl, &range); /* Use rank of last element, if any, to determine the actual count */ if (zn != NULL) { rank = zslGetRank(zsl, zn->score, zn->obj); count -= (zsl->length - rank); } } } else { redisPanic("Unknown sorted set encoding"); } zslFreeLexRange(&range); addReplyLongLong(c, count); } /* This command implements ZRANGEBYLEX, ZREVRANGEBYLEX. */ void genericZrangebylexCommand(redisClient *c, int reverse) { zlexrangespec range; robj *key = c->argv[1]; robj *zobj; long offset = 0, limit = -1; unsigned long rangelen = 0; void *replylen = NULL; int minidx, maxidx; /* Parse the range arguments. */ if (reverse) { /* Range is given as [max,min] */ maxidx = 2; minidx = 3; } else { /* Range is given as [min,max] */ minidx = 2; maxidx = 3; } if (zslParseLexRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) { addReplyError(c,"min or max not valid string range item"); return; } /* Parse optional extra arguments. Note that ZCOUNT will exactly have * 4 arguments, so we'll never enter the following code path. */ if (c->argc > 4) { int remaining = c->argc - 4; int pos = 4; while (remaining) { if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) { if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) || (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return; pos += 3; remaining -= 3; } else { zslFreeLexRange(&range); addReply(c,shared.syntaxerr); return; } } } /* Ok, lookup the key and get the range */ if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL || checkType(c,zobj,REDIS_ZSET)) { zslFreeLexRange(&range); return; } if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; unsigned char *vstr; unsigned int vlen; long long vlong; /* If reversed, get the last node in range as starting point. */ if (reverse) { eptr = zzlLastInLexRange(zl,&range); } else { eptr = zzlFirstInLexRange(zl,&range); } /* No "first" element in the specified interval. */ if (eptr == NULL) { addReply(c, shared.emptymultibulk); zslFreeLexRange(&range); return; } /* Get score pointer for the first element. */ redisAssertWithInfo(c,zobj,eptr != NULL); sptr = ziplistNext(zl,eptr); /* We don't know in advance how many matching elements there are in the * list, so we push this object that will represent the multi-bulk * length in the output buffer, and will "fix" it later */ replylen = addDeferredMultiBulkLength(c); /* If there is an offset, just traverse the number of elements without * checking the score because that is done in the next loop. */ while (eptr && offset--) { if (reverse) { zzlPrev(zl,&eptr,&sptr); } else { zzlNext(zl,&eptr,&sptr); } } while (eptr && limit--) { /* Abort when the node is no longer in range. */ if (reverse) { if (!zzlLexValueGteMin(eptr,&range)) break; } else { if (!zzlLexValueLteMax(eptr,&range)) break; } /* We know the element exists, so ziplistGet should always * succeed. */ redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong)); rangelen++; if (vstr == NULL) { addReplyBulkLongLong(c,vlong); } else { addReplyBulkCBuffer(c,vstr,vlen); } /* Move to next node */ if (reverse) { zzlPrev(zl,&eptr,&sptr); } else { zzlNext(zl,&eptr,&sptr); } } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *ln; /* If reversed, get the last node in range as starting point. */ if (reverse) { ln = zslLastInLexRange(zsl,&range); } else { ln = zslFirstInLexRange(zsl,&range); } /* No "first" element in the specified interval. */ if (ln == NULL) { addReply(c, shared.emptymultibulk); zslFreeLexRange(&range); return; } /* We don't know in advance how many matching elements there are in the * list, so we push this object that will represent the multi-bulk * length in the output buffer, and will "fix" it later */ replylen = addDeferredMultiBulkLength(c); /* If there is an offset, just traverse the number of elements without * checking the score because that is done in the next loop. */ while (ln && offset--) { if (reverse) { ln = ln->backward; } else { ln = ln->level[0].forward; } } while (ln && limit--) { /* Abort when the node is no longer in range. */ if (reverse) { if (!zslLexValueGteMin(ln->obj,&range)) break; } else { if (!zslLexValueLteMax(ln->obj,&range)) break; } rangelen++; addReplyBulk(c,ln->obj); /* Move to next node */ if (reverse) { ln = ln->backward; } else { ln = ln->level[0].forward; } } } else { redisPanic("Unknown sorted set encoding"); } zslFreeLexRange(&range); setDeferredMultiBulkLength(c, replylen, rangelen); } void zrangebylexCommand(redisClient *c) { genericZrangebylexCommand(c,0); } void zrevrangebylexCommand(redisClient *c) { genericZrangebylexCommand(c,1); } void zcardCommand(redisClient *c) { robj *key = c->argv[1]; robj *zobj; if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; addReplyLongLong(c,zsetLength(zobj)); } void zscoreCommand(redisClient *c) { robj *key = c->argv[1]; robj *zobj; double score; if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { if (zzlFind(zobj->ptr,c->argv[2],&score) != NULL) addReplyDouble(c,score); else addReply(c,shared.nullbulk); } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; dictEntry *de; c->argv[2] = tryObjectEncoding(c->argv[2]); de = dictFind(zs->dict,c->argv[2]); if (de != NULL) { score = *(double*)dictGetVal(de); addReplyDouble(c,score); } else { addReply(c,shared.nullbulk); } } else { redisPanic("Unknown sorted set encoding"); } } void zrankGenericCommand(redisClient *c, int reverse) { robj *key = c->argv[1]; robj *ele = c->argv[2]; robj *zobj; unsigned long llen; unsigned long rank; if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL || checkType(c,zobj,REDIS_ZSET)) return; llen = zsetLength(zobj); redisAssertWithInfo(c,ele,ele->encoding == REDIS_ENCODING_RAW); if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { unsigned char *zl = zobj->ptr; unsigned char *eptr, *sptr; eptr = ziplistIndex(zl,0); redisAssertWithInfo(c,zobj,eptr != NULL); sptr = ziplistNext(zl,eptr); redisAssertWithInfo(c,zobj,sptr != NULL); rank = 1; while(eptr != NULL) { if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) break; rank++; zzlNext(zl,&eptr,&sptr); } if (eptr != NULL) { if (reverse) addReplyLongLong(c,llen-rank); else addReplyLongLong(c,rank-1); } else { addReply(c,shared.nullbulk); } } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) { zset *zs = zobj->ptr; zskiplist *zsl = zs->zsl; dictEntry *de; double score; ele = c->argv[2] = tryObjectEncoding(c->argv[2]); de = dictFind(zs->dict,ele); if (de != NULL) { score = *(double*)dictGetVal(de); rank = zslGetRank(zsl,score,ele); redisAssertWithInfo(c,ele,rank); /* Existing elements always have a rank. */ if (reverse) addReplyLongLong(c,llen-rank); else addReplyLongLong(c,rank-1); } else { addReply(c,shared.nullbulk); } } else { redisPanic("Unknown sorted set encoding"); } } void zrankCommand(redisClient *c) { zrankGenericCommand(c, 0); } void zrevrankCommand(redisClient *c) { zrankGenericCommand(c, 1); } void zscanCommand(redisClient *c) { robj *o; unsigned long cursor; if (parseScanCursorOrReply(c,c->argv[2],&cursor) == REDIS_ERR) return; if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL || checkType(c,o,REDIS_ZSET)) return; scanGenericCommand(c,o,cursor); }
511862.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" int32_t x2 = INT32_MAX; volatile uint16_t x5 = 22119U; uint16_t x6 = 7U; uint8_t x9 = 33U; int64_t x12 = -1LL; uint64_t x18 = 31643857LLU; uint32_t x20 = 15672U; static volatile int32_t x21 = INT32_MAX; uint8_t x34 = 12U; static int64_t x38 = -2559LL; int32_t x40 = 984; volatile int8_t x43 = INT8_MIN; int32_t t10 = 1; static volatile uint32_t t11 = 2976U; static int32_t x51 = INT32_MIN; uint16_t x57 = 114U; int16_t x63 = INT16_MIN; uint16_t x65 = UINT16_MAX; int32_t x70 = 0; uint64_t x71 = 2112091406670874529LLU; int8_t x74 = INT8_MIN; int8_t x75 = -1; volatile int64_t t19 = 787792529043381014LL; static uint8_t x82 = 0U; static volatile int64_t t20 = -20LL; static int64_t x86 = -1LL; int8_t x89 = 0; int64_t x92 = INT64_MIN; volatile int8_t x97 = -8; int32_t t24 = -59275; int32_t x101 = INT32_MIN; int64_t t26 = 1154210413382272LL; int16_t x110 = 5; int16_t x114 = -1; uint64_t x115 = 1529874511455431LLU; int64_t x119 = INT64_MIN; static volatile uint32_t t30 = 11654685U; int16_t x133 = -1; volatile int64_t t35 = -3817358340161996LL; int16_t x145 = INT16_MAX; int64_t t37 = -26LL; int8_t x153 = INT8_MAX; int16_t x166 = 1997; int32_t x168 = -1; volatile int16_t x169 = -1; uint64_t x170 = 21274481257846466LLU; volatile uint32_t t42 = 29928U; int32_t t43 = 700; uint64_t x178 = 31206LLU; uint16_t x185 = UINT16_MAX; int8_t x200 = INT8_MIN; static uint16_t x203 = 41U; volatile int64_t t51 = 20816539891LL; int16_t x209 = INT16_MIN; static int8_t x211 = INT8_MIN; static uint16_t x219 = 31U; int8_t x228 = -4; uint32_t t56 = 4U; uint64_t x230 = 35492374LLU; static volatile int32_t t57 = 56; static int64_t x234 = INT64_MIN; volatile int32_t x242 = -351039; static uint32_t t63 = UINT32_MAX; int32_t x257 = 40654; static int64_t x258 = -1LL; int64_t x276 = INT64_MIN; int64_t t67 = -63761LL; int16_t x277 = INT16_MIN; volatile int64_t x278 = -8488678041LL; int32_t x284 = -1; int8_t x289 = INT8_MIN; volatile int32_t t71 = 9; uint32_t x295 = 7U; int32_t x296 = -1197; int32_t x300 = -1; int64_t t75 = -678685880722204LL; static int16_t x313 = INT16_MIN; volatile int8_t x314 = INT8_MIN; uint64_t x317 = 14107412195198LLU; volatile int32_t t78 = 26; int32_t x331 = INT32_MIN; uint64_t x332 = UINT64_MAX; uint64_t x349 = 6271184958416421LLU; uint32_t x350 = 161U; volatile int8_t x352 = -1; static int32_t x359 = INT32_MIN; static uint32_t x360 = UINT32_MAX; int16_t x361 = 644; int8_t x366 = -1; int16_t x368 = INT16_MAX; uint8_t x372 = 24U; int32_t x373 = 0; int8_t x379 = 0; int64_t x384 = 4383LL; int32_t t95 = 2659197; int64_t x394 = INT64_MIN; int8_t x400 = 48; uint64_t t98 = 1353960636501LLU; int8_t x407 = INT8_MIN; int32_t t100 = -254247302; int32_t x421 = 8577; static uint64_t x429 = UINT64_MAX; int64_t x436 = INT64_MIN; volatile uint16_t x438 = 12U; uint32_t t108 = 237143U; int32_t x443 = INT32_MIN; static uint64_t x448 = 88719335LLU; volatile int16_t x455 = -108; int64_t x456 = INT64_MIN; volatile int64_t t112 = -520518868608LL; static volatile int32_t x457 = INT32_MAX; static int8_t x460 = INT8_MIN; static int64_t x461 = 20313710LL; uint8_t x462 = 8U; uint32_t x465 = 181U; int32_t x466 = 46; static volatile uint64_t x468 = 13913389668971772LLU; volatile int16_t x484 = -1; int16_t x490 = 2985; volatile int32_t t120 = -2879; int64_t x497 = 547071780477152LL; int64_t x499 = INT64_MIN; volatile int32_t t123 = -246357; volatile uint64_t t125 = 3706342LLU; int32_t t127 = 3; uint32_t x530 = 970145U; uint64_t x538 = 5LLU; volatile uint32_t t132 = 104U; int64_t x541 = -1LL; static int16_t x544 = INT16_MIN; static uint32_t x545 = UINT32_MAX; int64_t x548 = -1LL; int64_t x552 = 111958075963695344LL; static int64_t t135 = -74LL; volatile int32_t t136 = 106111; volatile uint8_t x561 = 51U; int64_t x566 = -1LL; static int16_t x568 = -1; int64_t t139 = 41644823934214348LL; volatile uint64_t x578 = UINT64_MAX; static volatile uint64_t x581 = 4405762LLU; uint64_t t143 = 41674LLU; uint64_t x594 = 149973141090LLU; volatile int32_t t146 = -52222861; volatile uint16_t x601 = UINT16_MAX; int8_t x605 = INT8_MIN; int16_t x606 = INT16_MAX; volatile uint64_t x610 = UINT64_MAX; uint8_t x617 = 29U; volatile uint64_t x619 = 1197627466540LLU; static uint64_t t152 = 43659131LLU; int16_t x623 = -981; int8_t x624 = -2; int32_t t153 = -170403606; int64_t x629 = INT64_MIN; int16_t x631 = INT16_MIN; static int16_t x641 = -1; uint32_t x643 = 3430533U; volatile int16_t x648 = 4019; volatile int32_t t158 = -179; uint64_t t160 = 2LLU; int32_t x659 = INT32_MAX; volatile int8_t x671 = -1; int32_t t164 = 79424453; int8_t x675 = -1; int16_t x688 = -1; int8_t x689 = INT8_MIN; static int64_t x693 = INT64_MAX; int16_t x703 = 44; static int32_t x712 = INT32_MIN; int64_t t175 = INT64_MIN; int8_t x717 = -1; volatile uint8_t x724 = 3U; uint8_t x725 = 1U; volatile uint8_t x727 = 3U; int32_t x728 = -15278; uint64_t x729 = 1897067317832LLU; uint64_t x734 = 2904959057976LLU; volatile uint32_t t180 = UINT32_MAX; static int8_t x738 = INT8_MIN; int32_t t181 = INT32_MAX; uint32_t x743 = UINT32_MAX; int16_t x744 = INT16_MIN; int8_t x746 = INT8_MIN; int32_t t189 = 385521; int8_t x778 = INT8_MAX; volatile int8_t x784 = -1; volatile uint64_t t194 = UINT64_MAX; uint32_t x793 = 897U; uint8_t x799 = UINT8_MAX; int16_t x804 = -1; static int64_t x807 = INT64_MIN; void f0(void) { int8_t x1 = -1; uint8_t x3 = UINT8_MAX; volatile int8_t x4 = -1; volatile int32_t t0 = 1427; t0 = ((x1>x2)+(x3|x4)); if (t0 != -1) { NG(); } else { ; } } void f1(void) { volatile int16_t x7 = INT16_MAX; static int64_t x8 = INT64_MIN; volatile int64_t t1 = -4LL; t1 = ((x5>x6)+(x7|x8)); if (t1 != -9223372036854743040LL) { NG(); } else { ; } } void f2(void) { uint16_t x10 = 1U; volatile int64_t x11 = -3504LL; volatile int64_t t2 = -3967023076921LL; t2 = ((x9>x10)+(x11|x12)); if (t2 != 0LL) { NG(); } else { ; } } void f3(void) { volatile int16_t x13 = INT16_MIN; int64_t x14 = INT64_MIN; volatile int32_t x15 = INT32_MIN; uint16_t x16 = UINT16_MAX; volatile int32_t t3 = -684; t3 = ((x13>x14)+(x15|x16)); if (t3 != -2147418112) { NG(); } else { ; } } void f4(void) { volatile uint8_t x17 = 96U; volatile int8_t x19 = 15; uint32_t t4 = 1U; t4 = ((x17>x18)+(x19|x20)); if (t4 != 15679U) { NG(); } else { ; } } void f5(void) { int16_t x22 = 50; int32_t x23 = INT32_MIN; int64_t x24 = INT64_MAX; int64_t t5 = -120478869349223760LL; t5 = ((x21>x22)+(x23|x24)); if (t5 != 0LL) { NG(); } else { ; } } void f6(void) { volatile uint8_t x25 = UINT8_MAX; uint16_t x26 = 1481U; uint32_t x27 = 25U; int8_t x28 = 5; uint32_t t6 = 44558U; t6 = ((x25>x26)+(x27|x28)); if (t6 != 29U) { NG(); } else { ; } } void f7(void) { static int8_t x29 = INT8_MIN; uint8_t x30 = UINT8_MAX; volatile int64_t x31 = INT64_MIN; volatile int32_t x32 = -784433923; volatile int64_t t7 = 1LL; t7 = ((x29>x30)+(x31|x32)); if (t7 != -784433923LL) { NG(); } else { ; } } void f8(void) { uint64_t x33 = UINT64_MAX; int16_t x35 = 2; static int16_t x36 = INT16_MIN; int32_t t8 = 845218480; t8 = ((x33>x34)+(x35|x36)); if (t8 != -32765) { NG(); } else { ; } } void f9(void) { static int64_t x37 = INT64_MIN; volatile uint16_t x39 = 5537U; int32_t t9 = -55364; t9 = ((x37>x38)+(x39|x40)); if (t9 != 6137) { NG(); } else { ; } } void f10(void) { volatile uint32_t x41 = 1952857U; uint16_t x42 = UINT16_MAX; int8_t x44 = INT8_MAX; t10 = ((x41>x42)+(x43|x44)); if (t10 != 0) { NG(); } else { ; } } void f11(void) { static int64_t x45 = 183119777LL; int32_t x46 = INT32_MAX; int32_t x47 = 47203487; uint32_t x48 = 6601272U; t11 = ((x45>x46)+(x47|x48)); if (t11 != 49610431U) { NG(); } else { ; } } void f12(void) { uint16_t x49 = 1005U; int64_t x50 = 250LL; int32_t x52 = INT32_MIN; volatile int32_t t12 = 25; t12 = ((x49>x50)+(x51|x52)); if (t12 != -2147483647) { NG(); } else { ; } } void f13(void) { static int8_t x53 = 0; uint64_t x54 = 42207969LLU; static int64_t x55 = -1LL; int16_t x56 = 1; static volatile int64_t t13 = -17481945158677907LL; t13 = ((x53>x54)+(x55|x56)); if (t13 != -1LL) { NG(); } else { ; } } void f14(void) { int32_t x58 = 2; uint64_t x59 = 241277416639LLU; int16_t x60 = -52; uint64_t t14 = 7997436LLU; t14 = ((x57>x58)+(x59|x60)); if (t14 != 0LLU) { NG(); } else { ; } } void f15(void) { int32_t x61 = -1; static int16_t x62 = INT16_MAX; volatile int8_t x64 = INT8_MIN; int32_t t15 = 55; t15 = ((x61>x62)+(x63|x64)); if (t15 != -128) { NG(); } else { ; } } void f16(void) { static uint8_t x66 = 13U; uint8_t x67 = UINT8_MAX; int8_t x68 = INT8_MAX; volatile int32_t t16 = 5; t16 = ((x65>x66)+(x67|x68)); if (t16 != 256) { NG(); } else { ; } } void f17(void) { int16_t x69 = INT16_MAX; int64_t x72 = 1LL; volatile uint64_t t17 = 471866957LLU; t17 = ((x69>x70)+(x71|x72)); if (t17 != 2112091406670874530LLU) { NG(); } else { ; } } void f18(void) { static uint16_t x73 = UINT16_MAX; volatile int32_t x76 = INT32_MIN; int32_t t18 = 15950; t18 = ((x73>x74)+(x75|x76)); if (t18 != 0) { NG(); } else { ; } } void f19(void) { uint16_t x77 = 12101U; volatile uint16_t x78 = UINT16_MAX; int8_t x79 = INT8_MIN; int64_t x80 = 8104LL; t19 = ((x77>x78)+(x79|x80)); if (t19 != -88LL) { NG(); } else { ; } } void f20(void) { uint32_t x81 = 41346U; static volatile int64_t x83 = INT64_MIN; int8_t x84 = -1; t20 = ((x81>x82)+(x83|x84)); if (t20 != 0LL) { NG(); } else { ; } } void f21(void) { volatile int16_t x85 = -14054; static uint8_t x87 = 14U; int32_t x88 = 4; static volatile int32_t t21 = 2; t21 = ((x85>x86)+(x87|x88)); if (t21 != 14) { NG(); } else { ; } } void f22(void) { int16_t x90 = -8; int16_t x91 = 14; static volatile int64_t t22 = 2276689385485481827LL; t22 = ((x89>x90)+(x91|x92)); if (t22 != -9223372036854775793LL) { NG(); } else { ; } } void f23(void) { int32_t x93 = INT32_MIN; uint64_t x94 = 4181499878248262467LLU; uint64_t x95 = 56603045994LLU; volatile uint64_t x96 = 2292231LLU; uint64_t t23 = 7015527LLU; t23 = ((x93>x94)+(x95|x96)); if (t23 != 56605276784LLU) { NG(); } else { ; } } void f24(void) { int32_t x98 = 819; int8_t x99 = INT8_MAX; volatile int16_t x100 = 2; t24 = ((x97>x98)+(x99|x100)); if (t24 != 127) { NG(); } else { ; } } void f25(void) { volatile int32_t x102 = -1; int8_t x103 = INT8_MIN; int16_t x104 = INT16_MIN; volatile int32_t t25 = -11485693; t25 = ((x101>x102)+(x103|x104)); if (t25 != -128) { NG(); } else { ; } } void f26(void) { static uint32_t x105 = 29523U; int64_t x106 = INT64_MIN; int64_t x107 = INT64_MAX; int16_t x108 = -1045; t26 = ((x105>x106)+(x107|x108)); if (t26 != 0LL) { NG(); } else { ; } } void f27(void) { volatile int16_t x109 = -10194; int32_t x111 = -1143788; uint64_t x112 = 6LLU; uint64_t t27 = 84012LLU; t27 = ((x109>x110)+(x111|x112)); if (t27 != 18446744073708407830LLU) { NG(); } else { ; } } void f28(void) { uint64_t x113 = 109983LLU; static int16_t x116 = INT16_MIN; uint64_t t28 = 665696901LLU; t28 = ((x113>x114)+(x115|x116)); if (t28 != 18446744073709544647LLU) { NG(); } else { ; } } void f29(void) { int64_t x117 = -1LL; int16_t x118 = INT16_MIN; int32_t x120 = INT32_MIN; volatile int64_t t29 = -6611930554947LL; t29 = ((x117>x118)+(x119|x120)); if (t29 != -2147483647LL) { NG(); } else { ; } } void f30(void) { int8_t x121 = INT8_MAX; uint8_t x122 = 121U; static uint32_t x123 = 1U; int32_t x124 = 6623; t30 = ((x121>x122)+(x123|x124)); if (t30 != 6624U) { NG(); } else { ; } } void f31(void) { uint16_t x125 = 101U; uint64_t x126 = UINT64_MAX; int16_t x127 = -1; int8_t x128 = INT8_MIN; static volatile int32_t t31 = -389064496; t31 = ((x125>x126)+(x127|x128)); if (t31 != -1) { NG(); } else { ; } } void f32(void) { int64_t x129 = INT64_MIN; int16_t x130 = -1; volatile int64_t x131 = -112169932879LL; static int16_t x132 = 1; static int64_t t32 = -233864888372172LL; t32 = ((x129>x130)+(x131|x132)); if (t32 != -112169932879LL) { NG(); } else { ; } } void f33(void) { uint8_t x134 = UINT8_MAX; volatile int64_t x135 = INT64_MIN; uint32_t x136 = 687683329U; int64_t t33 = -235LL; t33 = ((x133>x134)+(x135|x136)); if (t33 != -9223372036167092479LL) { NG(); } else { ; } } void f34(void) { static volatile int16_t x137 = INT16_MAX; int64_t x138 = -24LL; int8_t x139 = INT8_MIN; static int8_t x140 = -1; int32_t t34 = -4107; t34 = ((x137>x138)+(x139|x140)); if (t34 != 0) { NG(); } else { ; } } void f35(void) { int16_t x141 = 1; int16_t x142 = INT16_MAX; int16_t x143 = 6756; int64_t x144 = -1LL; t35 = ((x141>x142)+(x143|x144)); if (t35 != -1LL) { NG(); } else { ; } } void f36(void) { volatile uint64_t x146 = 5904530622451976573LLU; int16_t x147 = -1; int8_t x148 = -1; int32_t t36 = 25125951; t36 = ((x145>x146)+(x147|x148)); if (t36 != -1) { NG(); } else { ; } } void f37(void) { static int16_t x149 = INT16_MIN; uint32_t x150 = 4167149U; int64_t x151 = -3LL; int32_t x152 = INT32_MAX; t37 = ((x149>x150)+(x151|x152)); if (t37 != 0LL) { NG(); } else { ; } } void f38(void) { volatile uint16_t x154 = 240U; uint16_t x155 = 1212U; volatile int64_t x156 = -1LL; volatile int64_t t38 = 0LL; t38 = ((x153>x154)+(x155|x156)); if (t38 != -1LL) { NG(); } else { ; } } void f39(void) { uint64_t x157 = 58312917652LLU; static int8_t x158 = 1; int8_t x159 = INT8_MAX; volatile int8_t x160 = INT8_MIN; volatile int32_t t39 = -183546425; t39 = ((x157>x158)+(x159|x160)); if (t39 != 0) { NG(); } else { ; } } void f40(void) { static volatile int32_t x161 = INT32_MIN; int16_t x162 = -7982; static int8_t x163 = -3; static uint8_t x164 = 3U; volatile int32_t t40 = 14585857; t40 = ((x161>x162)+(x163|x164)); if (t40 != -1) { NG(); } else { ; } } void f41(void) { int32_t x165 = -1; int64_t x167 = INT64_MIN; int64_t t41 = -3898283372696869LL; t41 = ((x165>x166)+(x167|x168)); if (t41 != -1LL) { NG(); } else { ; } } void f42(void) { volatile int8_t x171 = INT8_MIN; static volatile uint32_t x172 = 2783U; t42 = ((x169>x170)+(x171|x172)); if (t42 != 4294967264U) { NG(); } else { ; } } void f43(void) { uint64_t x173 = 9863340195722940LLU; volatile int64_t x174 = -3726804LL; static int8_t x175 = -3; uint8_t x176 = UINT8_MAX; t43 = ((x173>x174)+(x175|x176)); if (t43 != -1) { NG(); } else { ; } } void f44(void) { uint8_t x177 = UINT8_MAX; volatile int16_t x179 = 19; uint32_t x180 = 46604109U; volatile uint32_t t44 = 25822U; t44 = ((x177>x178)+(x179|x180)); if (t44 != 46604127U) { NG(); } else { ; } } void f45(void) { volatile uint8_t x181 = UINT8_MAX; static uint8_t x182 = UINT8_MAX; int64_t x183 = INT64_MIN; uint32_t x184 = 1665695741U; static volatile int64_t t45 = -12752LL; t45 = ((x181>x182)+(x183|x184)); if (t45 != -9223372035189080067LL) { NG(); } else { ; } } void f46(void) { int16_t x186 = -1; static uint8_t x187 = 2U; volatile uint32_t x188 = 6U; volatile uint32_t t46 = 27U; t46 = ((x185>x186)+(x187|x188)); if (t46 != 7U) { NG(); } else { ; } } void f47(void) { uint8_t x189 = 58U; int32_t x190 = INT32_MIN; int16_t x191 = 7; volatile uint64_t x192 = UINT64_MAX; uint64_t t47 = 11LLU; t47 = ((x189>x190)+(x191|x192)); if (t47 != 0LLU) { NG(); } else { ; } } void f48(void) { volatile int32_t x193 = -1; int32_t x194 = -11623; uint32_t x195 = UINT32_MAX; uint64_t x196 = UINT64_MAX; uint64_t t48 = 20395597LLU; t48 = ((x193>x194)+(x195|x196)); if (t48 != 0LLU) { NG(); } else { ; } } void f49(void) { int16_t x197 = 6033; int32_t x198 = 34; volatile int64_t x199 = 1LL; int64_t t49 = -853153907952389422LL; t49 = ((x197>x198)+(x199|x200)); if (t49 != -126LL) { NG(); } else { ; } } void f50(void) { int8_t x201 = INT8_MIN; static uint16_t x202 = 0U; int8_t x204 = -1; static int32_t t50 = -6273; t50 = ((x201>x202)+(x203|x204)); if (t50 != -1) { NG(); } else { ; } } void f51(void) { int64_t x205 = INT64_MAX; int8_t x206 = INT8_MIN; static uint8_t x207 = 12U; int64_t x208 = INT64_MIN; t51 = ((x205>x206)+(x207|x208)); if (t51 != -9223372036854775795LL) { NG(); } else { ; } } void f52(void) { int64_t x210 = INT64_MIN; uint16_t x212 = 1U; volatile int32_t t52 = 4; t52 = ((x209>x210)+(x211|x212)); if (t52 != -126) { NG(); } else { ; } } void f53(void) { int32_t x213 = INT32_MIN; int8_t x214 = 1; static uint64_t x215 = 16894284994LLU; volatile uint32_t x216 = 1998U; static uint64_t t53 = 128748028LLU; t53 = ((x213>x214)+(x215|x216)); if (t53 != 16894285774LLU) { NG(); } else { ; } } void f54(void) { int32_t x217 = INT32_MIN; int16_t x218 = INT16_MIN; int32_t x220 = 5798; volatile int32_t t54 = -1765; t54 = ((x217>x218)+(x219|x220)); if (t54 != 5823) { NG(); } else { ; } } void f55(void) { uint64_t x221 = 1404157972LLU; static int16_t x222 = INT16_MAX; static uint16_t x223 = 9U; uint32_t x224 = UINT32_MAX; uint32_t t55 = 13U; t55 = ((x221>x222)+(x223|x224)); if (t55 != 0U) { NG(); } else { ; } } void f56(void) { int8_t x225 = -1; volatile uint8_t x226 = 82U; uint32_t x227 = 58445U; t56 = ((x225>x226)+(x227|x228)); if (t56 != 4294967293U) { NG(); } else { ; } } void f57(void) { uint32_t x229 = 347U; volatile int16_t x231 = INT16_MIN; uint16_t x232 = UINT16_MAX; t57 = ((x229>x230)+(x231|x232)); if (t57 != -1) { NG(); } else { ; } } void f58(void) { uint32_t x233 = 17690U; volatile uint16_t x235 = UINT16_MAX; uint8_t x236 = 28U; static volatile int32_t t58 = 193994337; t58 = ((x233>x234)+(x235|x236)); if (t58 != 65536) { NG(); } else { ; } } void f59(void) { static int16_t x237 = INT16_MIN; volatile uint16_t x238 = 373U; volatile int32_t x239 = 118; volatile int64_t x240 = INT64_MAX; int64_t t59 = INT64_MAX; t59 = ((x237>x238)+(x239|x240)); if (t59 != INT64_MAX) { NG(); } else { ; } } void f60(void) { volatile int8_t x241 = -1; volatile int8_t x243 = -1; static volatile int16_t x244 = INT16_MAX; volatile int32_t t60 = 415004439; t60 = ((x241>x242)+(x243|x244)); if (t60 != 0) { NG(); } else { ; } } void f61(void) { uint8_t x245 = 3U; int8_t x246 = -7; volatile int16_t x247 = INT16_MIN; static int16_t x248 = -11628; volatile int32_t t61 = 7; t61 = ((x245>x246)+(x247|x248)); if (t61 != -11627) { NG(); } else { ; } } void f62(void) { int32_t x249 = INT32_MAX; uint32_t x250 = 44U; static uint64_t x251 = UINT64_MAX; volatile uint8_t x252 = 26U; volatile uint64_t t62 = 47133389LLU; t62 = ((x249>x250)+(x251|x252)); if (t62 != 0LLU) { NG(); } else { ; } } void f63(void) { int16_t x253 = INT16_MIN; int32_t x254 = INT32_MAX; volatile uint32_t x255 = UINT32_MAX; int8_t x256 = INT8_MIN; t63 = ((x253>x254)+(x255|x256)); if (t63 != UINT32_MAX) { NG(); } else { ; } } void f64(void) { uint32_t x259 = 0U; volatile uint8_t x260 = UINT8_MAX; uint32_t t64 = 803450494U; t64 = ((x257>x258)+(x259|x260)); if (t64 != 256U) { NG(); } else { ; } } void f65(void) { int16_t x261 = -1; int8_t x262 = INT8_MIN; uint64_t x263 = 156832772509LLU; static volatile uint32_t x264 = 3855443U; volatile uint64_t t65 = 215884301LLU; t65 = ((x261>x262)+(x263|x264)); if (t65 != 156833347040LLU) { NG(); } else { ; } } void f66(void) { static int64_t x265 = INT64_MIN; volatile uint16_t x266 = UINT16_MAX; int64_t x267 = -15043720195741LL; uint32_t x268 = 1232983U; volatile int64_t t66 = -1510981963972836508LL; t66 = ((x265>x266)+(x267|x268)); if (t66 != -15043719147145LL) { NG(); } else { ; } } void f67(void) { int64_t x273 = -1LL; static int16_t x274 = INT16_MIN; static int64_t x275 = -21612629LL; t67 = ((x273>x274)+(x275|x276)); if (t67 != -21612628LL) { NG(); } else { ; } } void f68(void) { volatile uint8_t x279 = 59U; int16_t x280 = INT16_MAX; static volatile int32_t t68 = 26648153; t68 = ((x277>x278)+(x279|x280)); if (t68 != 32768) { NG(); } else { ; } } void f69(void) { uint8_t x281 = 22U; static uint64_t x282 = UINT64_MAX; int64_t x283 = 852461063LL; volatile int64_t t69 = -1029037165LL; t69 = ((x281>x282)+(x283|x284)); if (t69 != -1LL) { NG(); } else { ; } } void f70(void) { volatile uint8_t x285 = 1U; volatile int8_t x286 = INT8_MAX; uint16_t x287 = 10844U; static uint64_t x288 = UINT64_MAX; volatile uint64_t t70 = UINT64_MAX; t70 = ((x285>x286)+(x287|x288)); if (t70 != UINT64_MAX) { NG(); } else { ; } } void f71(void) { uint16_t x290 = 40U; volatile int16_t x291 = -4; static uint8_t x292 = 58U; t71 = ((x289>x290)+(x291|x292)); if (t71 != -2) { NG(); } else { ; } } void f72(void) { volatile int64_t x293 = 4218425336LL; uint32_t x294 = UINT32_MAX; static uint32_t t72 = 0U; t72 = ((x293>x294)+(x295|x296)); if (t72 != 4294966103U) { NG(); } else { ; } } void f73(void) { int16_t x297 = INT16_MIN; static int64_t x298 = INT64_MAX; volatile int32_t x299 = INT32_MIN; volatile int32_t t73 = 1039195; t73 = ((x297>x298)+(x299|x300)); if (t73 != -1) { NG(); } else { ; } } void f74(void) { int8_t x301 = INT8_MIN; int16_t x302 = INT16_MAX; uint16_t x303 = 7U; int8_t x304 = INT8_MIN; volatile int32_t t74 = -17645; t74 = ((x301>x302)+(x303|x304)); if (t74 != -121) { NG(); } else { ; } } void f75(void) { int8_t x305 = INT8_MAX; static uint8_t x306 = 0U; int8_t x307 = INT8_MIN; static volatile int64_t x308 = INT64_MIN; t75 = ((x305>x306)+(x307|x308)); if (t75 != -127LL) { NG(); } else { ; } } void f76(void) { static uint64_t x309 = UINT64_MAX; uint8_t x310 = 9U; uint8_t x311 = 96U; static int16_t x312 = -1; volatile int32_t t76 = 284282137; t76 = ((x309>x310)+(x311|x312)); if (t76 != 0) { NG(); } else { ; } } void f77(void) { uint32_t x315 = 423U; int16_t x316 = INT16_MIN; static volatile uint32_t t77 = 0U; t77 = ((x313>x314)+(x315|x316)); if (t77 != 4294934951U) { NG(); } else { ; } } void f78(void) { int64_t x318 = -3LL; volatile uint16_t x319 = UINT16_MAX; static uint16_t x320 = UINT16_MAX; t78 = ((x317>x318)+(x319|x320)); if (t78 != 65535) { NG(); } else { ; } } void f79(void) { int16_t x321 = INT16_MIN; int32_t x322 = -23; int64_t x323 = 1383318688279348214LL; uint8_t x324 = UINT8_MAX; int64_t t79 = -15899602574959LL; t79 = ((x321>x322)+(x323|x324)); if (t79 != 1383318688279348223LL) { NG(); } else { ; } } void f80(void) { int32_t x325 = INT32_MAX; uint16_t x326 = UINT16_MAX; uint16_t x327 = 2U; static int8_t x328 = INT8_MAX; int32_t t80 = 51; t80 = ((x325>x326)+(x327|x328)); if (t80 != 128) { NG(); } else { ; } } void f81(void) { volatile int8_t x329 = -3; static volatile int16_t x330 = -6313; volatile uint64_t t81 = 6406504LLU; t81 = ((x329>x330)+(x331|x332)); if (t81 != 0LLU) { NG(); } else { ; } } void f82(void) { uint64_t x333 = UINT64_MAX; uint32_t x334 = 145U; int64_t x335 = 181484757773329LL; int64_t x336 = INT64_MIN; int64_t t82 = -116811437LL; t82 = ((x333>x334)+(x335|x336)); if (t82 != -9223190552097002478LL) { NG(); } else { ; } } void f83(void) { volatile int64_t x337 = INT64_MIN; int32_t x338 = INT32_MAX; int32_t x339 = INT32_MIN; volatile int8_t x340 = INT8_MAX; int32_t t83 = 37; t83 = ((x337>x338)+(x339|x340)); if (t83 != -2147483521) { NG(); } else { ; } } void f84(void) { int64_t x341 = INT64_MIN; int64_t x342 = INT64_MAX; int32_t x343 = INT32_MAX; static uint64_t x344 = UINT64_MAX; volatile uint64_t t84 = UINT64_MAX; t84 = ((x341>x342)+(x343|x344)); if (t84 != UINT64_MAX) { NG(); } else { ; } } void f85(void) { static int16_t x345 = INT16_MIN; int32_t x346 = -1; volatile int8_t x347 = -1; uint64_t x348 = 673973LLU; uint64_t t85 = UINT64_MAX; t85 = ((x345>x346)+(x347|x348)); if (t85 != UINT64_MAX) { NG(); } else { ; } } void f86(void) { uint32_t x351 = UINT32_MAX; uint32_t t86 = 53213U; t86 = ((x349>x350)+(x351|x352)); if (t86 != 0U) { NG(); } else { ; } } void f87(void) { static uint8_t x353 = 3U; int8_t x354 = -16; uint8_t x355 = 58U; static uint16_t x356 = 195U; volatile int32_t t87 = -1068673960; t87 = ((x353>x354)+(x355|x356)); if (t87 != 252) { NG(); } else { ; } } void f88(void) { int64_t x357 = -1LL; static uint16_t x358 = 6U; uint32_t t88 = UINT32_MAX; t88 = ((x357>x358)+(x359|x360)); if (t88 != UINT32_MAX) { NG(); } else { ; } } void f89(void) { volatile int8_t x362 = INT8_MAX; int8_t x363 = INT8_MAX; uint16_t x364 = UINT16_MAX; volatile int32_t t89 = 178; t89 = ((x361>x362)+(x363|x364)); if (t89 != 65536) { NG(); } else { ; } } void f90(void) { uint32_t x365 = 21309431U; int8_t x367 = -1; volatile int32_t t90 = 908699017; t90 = ((x365>x366)+(x367|x368)); if (t90 != -1) { NG(); } else { ; } } void f91(void) { static int8_t x369 = INT8_MIN; uint32_t x370 = UINT32_MAX; int16_t x371 = INT16_MIN; volatile int32_t t91 = 70704065; t91 = ((x369>x370)+(x371|x372)); if (t91 != -32744) { NG(); } else { ; } } void f92(void) { uint8_t x374 = 0U; static int32_t x375 = 210174; int16_t x376 = INT16_MIN; static volatile int32_t t92 = 73; t92 = ((x373>x374)+(x375|x376)); if (t92 != -19202) { NG(); } else { ; } } void f93(void) { int8_t x377 = INT8_MIN; uint32_t x378 = 6840022U; int64_t x380 = INT64_MIN; static volatile int64_t t93 = -12606146667864497LL; t93 = ((x377>x378)+(x379|x380)); if (t93 != -9223372036854775807LL) { NG(); } else { ; } } void f94(void) { volatile int64_t x381 = 14426LL; static uint8_t x382 = UINT8_MAX; uint32_t x383 = UINT32_MAX; volatile int64_t t94 = -3841890LL; t94 = ((x381>x382)+(x383|x384)); if (t94 != 4294967296LL) { NG(); } else { ; } } void f95(void) { int8_t x385 = INT8_MAX; uint8_t x386 = 1U; int16_t x387 = 2; static volatile int8_t x388 = INT8_MIN; t95 = ((x385>x386)+(x387|x388)); if (t95 != -125) { NG(); } else { ; } } void f96(void) { static volatile int16_t x389 = INT16_MAX; int16_t x390 = INT16_MIN; int8_t x391 = 2; volatile int32_t x392 = -1; static volatile int32_t t96 = 2150; t96 = ((x389>x390)+(x391|x392)); if (t96 != 0) { NG(); } else { ; } } void f97(void) { int16_t x393 = INT16_MAX; uint64_t x395 = UINT64_MAX; int8_t x396 = -13; volatile uint64_t t97 = 16LLU; t97 = ((x393>x394)+(x395|x396)); if (t97 != 0LLU) { NG(); } else { ; } } void f98(void) { uint8_t x397 = 9U; static int16_t x398 = INT16_MIN; uint64_t x399 = 118382983407761904LLU; t98 = ((x397>x398)+(x399|x400)); if (t98 != 118382983407761905LLU) { NG(); } else { ; } } void f99(void) { volatile uint8_t x401 = 22U; uint32_t x402 = 63194290U; int8_t x403 = INT8_MAX; int16_t x404 = INT16_MAX; int32_t t99 = -29099; t99 = ((x401>x402)+(x403|x404)); if (t99 != 32767) { NG(); } else { ; } } void f100(void) { static int16_t x405 = -1; static volatile int8_t x406 = INT8_MAX; int32_t x408 = -531748; t100 = ((x405>x406)+(x407|x408)); if (t100 != -36) { NG(); } else { ; } } void f101(void) { static uint64_t x409 = UINT64_MAX; static volatile int16_t x410 = INT16_MAX; uint8_t x411 = 0U; uint32_t x412 = 1970017963U; uint32_t t101 = 1520068906U; t101 = ((x409>x410)+(x411|x412)); if (t101 != 1970017964U) { NG(); } else { ; } } void f102(void) { int32_t x413 = -1; int64_t x414 = INT64_MAX; int16_t x415 = 23; static uint8_t x416 = 3U; static volatile int32_t t102 = -244287; t102 = ((x413>x414)+(x415|x416)); if (t102 != 23) { NG(); } else { ; } } void f103(void) { int64_t x417 = INT64_MIN; volatile int8_t x418 = -1; int16_t x419 = -180; int64_t x420 = -63787933LL; volatile int64_t t103 = 7759433104611LL; t103 = ((x417>x418)+(x419|x420)); if (t103 != -145LL) { NG(); } else { ; } } void f104(void) { int32_t x422 = -2326133; static int8_t x423 = -1; static int8_t x424 = INT8_MAX; static volatile int32_t t104 = 62573; t104 = ((x421>x422)+(x423|x424)); if (t104 != 0) { NG(); } else { ; } } void f105(void) { int16_t x425 = INT16_MIN; int32_t x426 = INT32_MIN; volatile uint64_t x427 = 112388299758LLU; int16_t x428 = INT16_MIN; volatile uint64_t t105 = 86233968008LLU; t105 = ((x425>x426)+(x427|x428)); if (t105 != 18446744073709542383LLU) { NG(); } else { ; } } void f106(void) { int64_t x430 = INT64_MAX; static int16_t x431 = INT16_MIN; static volatile uint32_t x432 = 18662860U; static volatile uint32_t t106 = 2703039U; t106 = ((x429>x430)+(x431|x432)); if (t106 != 4294952397U) { NG(); } else { ; } } void f107(void) { volatile uint64_t x433 = 104948LLU; static int32_t x434 = 7278; static int64_t x435 = INT64_MIN; volatile int64_t t107 = 60LL; t107 = ((x433>x434)+(x435|x436)); if (t107 != -9223372036854775807LL) { NG(); } else { ; } } void f108(void) { uint64_t x437 = UINT64_MAX; static int8_t x439 = INT8_MAX; uint32_t x440 = 128317U; t108 = ((x437>x438)+(x439|x440)); if (t108 != 128384U) { NG(); } else { ; } } void f109(void) { int64_t x441 = 0LL; int16_t x442 = INT16_MIN; int16_t x444 = -1; volatile int32_t t109 = -755150011; t109 = ((x441>x442)+(x443|x444)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { static uint64_t x445 = 12202398956LLU; static volatile int8_t x446 = INT8_MIN; volatile int32_t x447 = INT32_MIN; uint64_t t110 = 66702391LLU; t110 = ((x445>x446)+(x447|x448)); if (t110 != 18446744071650787303LLU) { NG(); } else { ; } } void f111(void) { int32_t x449 = INT32_MAX; volatile int32_t x450 = INT32_MIN; uint64_t x451 = 0LLU; uint32_t x452 = 117U; volatile uint64_t t111 = 1008462119LLU; t111 = ((x449>x450)+(x451|x452)); if (t111 != 118LLU) { NG(); } else { ; } } void f112(void) { static int32_t x453 = INT32_MIN; int32_t x454 = 5925; t112 = ((x453>x454)+(x455|x456)); if (t112 != -108LL) { NG(); } else { ; } } void f113(void) { volatile int64_t x458 = INT64_MAX; int32_t x459 = INT32_MIN; volatile int32_t t113 = -226301362; t113 = ((x457>x458)+(x459|x460)); if (t113 != -128) { NG(); } else { ; } } void f114(void) { static uint64_t x463 = 415LLU; int32_t x464 = 10478; uint64_t t114 = 0LLU; t114 = ((x461>x462)+(x463|x464)); if (t114 != 10752LLU) { NG(); } else { ; } } void f115(void) { uint32_t x467 = 103789U; volatile uint64_t t115 = 5117338LLU; t115 = ((x465>x466)+(x467|x468)); if (t115 != 13913389669004798LLU) { NG(); } else { ; } } void f116(void) { uint8_t x469 = UINT8_MAX; int64_t x470 = INT64_MIN; uint64_t x471 = 4777710LLU; int32_t x472 = -1; uint64_t t116 = 5814032046440057808LLU; t116 = ((x469>x470)+(x471|x472)); if (t116 != 0LLU) { NG(); } else { ; } } void f117(void) { volatile uint8_t x473 = 126U; volatile int8_t x474 = INT8_MAX; int16_t x475 = INT16_MIN; uint16_t x476 = 18U; static int32_t t117 = -1869; t117 = ((x473>x474)+(x475|x476)); if (t117 != -32750) { NG(); } else { ; } } void f118(void) { int8_t x481 = 0; int32_t x482 = INT32_MAX; static int64_t x483 = 121785LL; int64_t t118 = 0LL; t118 = ((x481>x482)+(x483|x484)); if (t118 != -1LL) { NG(); } else { ; } } void f119(void) { uint8_t x485 = 0U; int8_t x486 = INT8_MIN; volatile int64_t x487 = INT64_MAX; volatile int8_t x488 = INT8_MIN; static int64_t t119 = -7734641759LL; t119 = ((x485>x486)+(x487|x488)); if (t119 != 0LL) { NG(); } else { ; } } void f120(void) { static volatile int16_t x489 = 122; static int16_t x491 = -1; uint8_t x492 = UINT8_MAX; t120 = ((x489>x490)+(x491|x492)); if (t120 != -1) { NG(); } else { ; } } void f121(void) { int8_t x493 = 4; int32_t x494 = INT32_MIN; int8_t x495 = -1; int16_t x496 = -2; volatile int32_t t121 = -258618305; t121 = ((x493>x494)+(x495|x496)); if (t121 != 0) { NG(); } else { ; } } void f122(void) { int8_t x498 = -1; uint16_t x500 = UINT16_MAX; int64_t t122 = -144LL; t122 = ((x497>x498)+(x499|x500)); if (t122 != -9223372036854710272LL) { NG(); } else { ; } } void f123(void) { volatile uint64_t x501 = UINT64_MAX; static uint32_t x502 = 718440669U; volatile int16_t x503 = INT16_MAX; uint8_t x504 = 5U; t123 = ((x501>x502)+(x503|x504)); if (t123 != 32768) { NG(); } else { ; } } void f124(void) { int32_t x505 = -1; int32_t x506 = -159; volatile uint32_t x507 = 6U; static int16_t x508 = INT16_MIN; volatile uint32_t t124 = 6262U; t124 = ((x505>x506)+(x507|x508)); if (t124 != 4294934535U) { NG(); } else { ; } } void f125(void) { volatile uint8_t x509 = UINT8_MAX; int32_t x510 = INT32_MIN; static int16_t x511 = INT16_MAX; uint64_t x512 = UINT64_MAX; t125 = ((x509>x510)+(x511|x512)); if (t125 != 0LLU) { NG(); } else { ; } } void f126(void) { uint64_t x513 = UINT64_MAX; int16_t x514 = -1; static uint16_t x515 = UINT16_MAX; int64_t x516 = INT64_MIN; static int64_t t126 = 1805033223525LL; t126 = ((x513>x514)+(x515|x516)); if (t126 != -9223372036854710273LL) { NG(); } else { ; } } void f127(void) { volatile int32_t x517 = INT32_MIN; int8_t x518 = -50; int8_t x519 = -1; volatile uint16_t x520 = 27535U; t127 = ((x517>x518)+(x519|x520)); if (t127 != -1) { NG(); } else { ; } } void f128(void) { volatile uint16_t x521 = 1290U; int32_t x522 = -12613; int32_t x523 = -18856015; int64_t x524 = INT64_MAX; volatile int64_t t128 = 646LL; t128 = ((x521>x522)+(x523|x524)); if (t128 != 0LL) { NG(); } else { ; } } void f129(void) { volatile uint8_t x525 = 7U; volatile uint16_t x526 = 283U; uint64_t x527 = 2811106991145792LLU; int8_t x528 = -7; volatile uint64_t t129 = 157379829295057226LLU; t129 = ((x525>x526)+(x527|x528)); if (t129 != 18446744073709551609LLU) { NG(); } else { ; } } void f130(void) { int16_t x529 = INT16_MAX; volatile uint16_t x531 = 0U; static int8_t x532 = INT8_MIN; volatile int32_t t130 = -3559; t130 = ((x529>x530)+(x531|x532)); if (t130 != -128) { NG(); } else { ; } } void f131(void) { uint32_t x533 = UINT32_MAX; volatile int16_t x534 = -1; volatile uint64_t x535 = 64645244501115020LLU; int16_t x536 = 4006; uint64_t t131 = 114631LLU; t131 = ((x533>x534)+(x535|x536)); if (t131 != 64645244501118894LLU) { NG(); } else { ; } } void f132(void) { uint8_t x537 = 1U; uint32_t x539 = 5687719U; static int8_t x540 = 0; t132 = ((x537>x538)+(x539|x540)); if (t132 != 5687719U) { NG(); } else { ; } } void f133(void) { int8_t x542 = INT8_MAX; int16_t x543 = -8707; volatile int32_t t133 = 315406; t133 = ((x541>x542)+(x543|x544)); if (t133 != -8707) { NG(); } else { ; } } void f134(void) { int8_t x546 = INT8_MAX; volatile int8_t x547 = 24; volatile int64_t t134 = 6585LL; t134 = ((x545>x546)+(x547|x548)); if (t134 != 0LL) { NG(); } else { ; } } void f135(void) { uint16_t x549 = 5U; volatile int8_t x550 = -1; static int16_t x551 = INT16_MIN; t135 = ((x549>x550)+(x551|x552)); if (t135 != -7951LL) { NG(); } else { ; } } void f136(void) { int32_t x553 = -7434262; static volatile int8_t x554 = -3; int16_t x555 = -1; int8_t x556 = -1; t136 = ((x553>x554)+(x555|x556)); if (t136 != -1) { NG(); } else { ; } } void f137(void) { int16_t x557 = INT16_MIN; uint64_t x558 = 491LLU; static uint64_t x559 = 151LLU; static uint16_t x560 = 36U; static uint64_t t137 = 13935040937LLU; t137 = ((x557>x558)+(x559|x560)); if (t137 != 184LLU) { NG(); } else { ; } } void f138(void) { static uint8_t x562 = UINT8_MAX; int32_t x563 = INT32_MIN; int16_t x564 = INT16_MIN; static volatile int32_t t138 = -783033; t138 = ((x561>x562)+(x563|x564)); if (t138 != -32768) { NG(); } else { ; } } void f139(void) { int32_t x565 = INT32_MIN; int64_t x567 = 22105372LL; t139 = ((x565>x566)+(x567|x568)); if (t139 != -1LL) { NG(); } else { ; } } void f140(void) { int64_t x569 = -237518408906117832LL; int16_t x570 = INT16_MIN; int64_t x571 = -1LL; int64_t x572 = -1LL; volatile int64_t t140 = -11510611LL; t140 = ((x569>x570)+(x571|x572)); if (t140 != -1LL) { NG(); } else { ; } } void f141(void) { uint32_t x573 = UINT32_MAX; static int32_t x574 = -1734604; int64_t x575 = -3709304392654LL; int8_t x576 = 0; static int64_t t141 = 1172768605674479LL; t141 = ((x573>x574)+(x575|x576)); if (t141 != -3709304392653LL) { NG(); } else { ; } } void f142(void) { int16_t x577 = INT16_MIN; int16_t x579 = -1; int8_t x580 = INT8_MIN; volatile int32_t t142 = 3; t142 = ((x577>x578)+(x579|x580)); if (t142 != -1) { NG(); } else { ; } } void f143(void) { uint32_t x582 = UINT32_MAX; uint64_t x583 = 6LLU; static int64_t x584 = -6877LL; t143 = ((x581>x582)+(x583|x584)); if (t143 != 18446744073709544743LLU) { NG(); } else { ; } } void f144(void) { uint32_t x585 = 3276U; uint8_t x586 = UINT8_MAX; int8_t x587 = INT8_MIN; volatile int8_t x588 = -1; volatile int32_t t144 = -2500; t144 = ((x585>x586)+(x587|x588)); if (t144 != 0) { NG(); } else { ; } } void f145(void) { int64_t x589 = -2128480LL; volatile int64_t x590 = INT64_MIN; uint8_t x591 = 79U; volatile int16_t x592 = -8692; int32_t t145 = -8228131; t145 = ((x589>x590)+(x591|x592)); if (t145 != -8624) { NG(); } else { ; } } void f146(void) { static int64_t x593 = INT64_MIN; int32_t x595 = -1; volatile uint16_t x596 = UINT16_MAX; t146 = ((x593>x594)+(x595|x596)); if (t146 != 0) { NG(); } else { ; } } void f147(void) { static uint64_t x597 = UINT64_MAX; static int16_t x598 = INT16_MAX; volatile int32_t x599 = -1; uint8_t x600 = 111U; static volatile int32_t t147 = -58538; t147 = ((x597>x598)+(x599|x600)); if (t147 != 0) { NG(); } else { ; } } void f148(void) { volatile int16_t x602 = INT16_MIN; int8_t x603 = -11; int32_t x604 = 107201368; int32_t t148 = 33497091; t148 = ((x601>x602)+(x603|x604)); if (t148 != -2) { NG(); } else { ; } } void f149(void) { int32_t x607 = INT32_MIN; int8_t x608 = 3; int32_t t149 = 2; t149 = ((x605>x606)+(x607|x608)); if (t149 != -2147483645) { NG(); } else { ; } } void f150(void) { static uint8_t x609 = 44U; int32_t x611 = INT32_MIN; int16_t x612 = 4165; volatile int32_t t150 = 1; t150 = ((x609>x610)+(x611|x612)); if (t150 != -2147479483) { NG(); } else { ; } } void f151(void) { static volatile uint8_t x613 = UINT8_MAX; int64_t x614 = -324104373LL; uint64_t x615 = 11173014667853LLU; uint32_t x616 = 3763U; uint64_t t151 = 368675LLU; t151 = ((x613>x614)+(x615|x616)); if (t151 != 11173014671104LLU) { NG(); } else { ; } } void f152(void) { int16_t x618 = -1; static int16_t x620 = INT16_MIN; t152 = ((x617>x618)+(x619|x620)); if (t152 != 18446744073709544237LLU) { NG(); } else { ; } } void f153(void) { volatile int32_t x621 = -1; static int8_t x622 = INT8_MIN; t153 = ((x621>x622)+(x623|x624)); if (t153 != 0) { NG(); } else { ; } } void f154(void) { int8_t x630 = INT8_MIN; int64_t x632 = INT64_MAX; int64_t t154 = 9LL; t154 = ((x629>x630)+(x631|x632)); if (t154 != -1LL) { NG(); } else { ; } } void f155(void) { int8_t x633 = INT8_MIN; int16_t x634 = INT16_MIN; int16_t x635 = -1781; volatile uint32_t x636 = 7893U; uint32_t t155 = 31559085U; t155 = ((x633>x634)+(x635|x636)); if (t155 != 4294967264U) { NG(); } else { ; } } void f156(void) { static int32_t x637 = INT32_MAX; static int16_t x638 = 8012; int32_t x639 = -1; uint64_t x640 = 309764136697692LLU; uint64_t t156 = 16994727LLU; t156 = ((x637>x638)+(x639|x640)); if (t156 != 0LLU) { NG(); } else { ; } } void f157(void) { uint16_t x642 = 218U; uint8_t x644 = UINT8_MAX; volatile uint32_t t157 = 669495223U; t157 = ((x641>x642)+(x643|x644)); if (t157 != 3430655U) { NG(); } else { ; } } void f158(void) { uint16_t x645 = 386U; uint32_t x646 = 6U; int32_t x647 = INT32_MIN; t158 = ((x645>x646)+(x647|x648)); if (t158 != -2147479628) { NG(); } else { ; } } void f159(void) { static uint8_t x649 = 0U; int32_t x650 = -8466; volatile int8_t x651 = -59; volatile int16_t x652 = -1; int32_t t159 = -11401336; t159 = ((x649>x650)+(x651|x652)); if (t159 != 0) { NG(); } else { ; } } void f160(void) { int16_t x653 = -1; volatile int64_t x654 = INT64_MIN; uint64_t x655 = UINT64_MAX; static int32_t x656 = 930391525; t160 = ((x653>x654)+(x655|x656)); if (t160 != 0LLU) { NG(); } else { ; } } void f161(void) { static volatile int8_t x657 = -1; int64_t x658 = -2526259498905452LL; volatile int8_t x660 = INT8_MIN; int32_t t161 = 0; t161 = ((x657>x658)+(x659|x660)); if (t161 != 0) { NG(); } else { ; } } void f162(void) { volatile int32_t x661 = INT32_MIN; static int64_t x662 = INT64_MIN; volatile uint32_t x663 = UINT32_MAX; int16_t x664 = INT16_MAX; volatile uint32_t t162 = 88U; t162 = ((x661>x662)+(x663|x664)); if (t162 != 0U) { NG(); } else { ; } } void f163(void) { int16_t x665 = -1; uint64_t x666 = 112386LLU; int32_t x667 = 3599302; int64_t x668 = INT64_MIN; volatile int64_t t163 = 3171299855720LL; t163 = ((x665>x666)+(x667|x668)); if (t163 != -9223372036851176505LL) { NG(); } else { ; } } void f164(void) { volatile uint64_t x669 = 1768LLU; int64_t x670 = INT64_MIN; uint16_t x672 = UINT16_MAX; t164 = ((x669>x670)+(x671|x672)); if (t164 != -1) { NG(); } else { ; } } void f165(void) { static uint8_t x673 = 2U; uint16_t x674 = 24U; int64_t x676 = INT64_MIN; static int64_t t165 = -9968LL; t165 = ((x673>x674)+(x675|x676)); if (t165 != -1LL) { NG(); } else { ; } } void f166(void) { uint16_t x677 = UINT16_MAX; int16_t x678 = INT16_MAX; volatile int8_t x679 = INT8_MIN; int64_t x680 = 7330438111LL; int64_t t166 = 0LL; t166 = ((x677>x678)+(x679|x680)); if (t166 != -32LL) { NG(); } else { ; } } void f167(void) { uint32_t x681 = UINT32_MAX; static uint32_t x682 = 1100708U; uint64_t x683 = UINT64_MAX; int32_t x684 = INT32_MIN; volatile uint64_t t167 = 2136378384162297LLU; t167 = ((x681>x682)+(x683|x684)); if (t167 != 0LLU) { NG(); } else { ; } } void f168(void) { static int64_t x685 = -1LL; static int32_t x686 = 283921; uint16_t x687 = 2U; static volatile int32_t t168 = 60; t168 = ((x685>x686)+(x687|x688)); if (t168 != -1) { NG(); } else { ; } } void f169(void) { static uint64_t x690 = 986LLU; volatile int64_t x691 = 434128553875209LL; static volatile int64_t x692 = INT64_MIN; int64_t t169 = -123918000LL; t169 = ((x689>x690)+(x691|x692)); if (t169 != -9222937908300900598LL) { NG(); } else { ; } } void f170(void) { int16_t x694 = -1; volatile int32_t x695 = -1; static uint64_t x696 = 41582416844481LLU; volatile uint64_t t170 = 1850629621LLU; t170 = ((x693>x694)+(x695|x696)); if (t170 != 0LLU) { NG(); } else { ; } } void f171(void) { int32_t x697 = INT32_MAX; uint32_t x698 = 29U; int8_t x699 = INT8_MIN; volatile uint32_t x700 = 4242341U; uint32_t t171 = 0U; t171 = ((x697>x698)+(x699|x700)); if (t171 != 4294967206U) { NG(); } else { ; } } void f172(void) { int8_t x701 = INT8_MAX; uint16_t x702 = UINT16_MAX; static int8_t x704 = INT8_MIN; int32_t t172 = 1; t172 = ((x701>x702)+(x703|x704)); if (t172 != -84) { NG(); } else { ; } } void f173(void) { static volatile int16_t x705 = INT16_MIN; int8_t x706 = INT8_MAX; static uint8_t x707 = 5U; volatile int16_t x708 = INT16_MIN; int32_t t173 = -724; t173 = ((x705>x706)+(x707|x708)); if (t173 != -32763) { NG(); } else { ; } } void f174(void) { int8_t x709 = 3; uint8_t x710 = 24U; volatile int16_t x711 = INT16_MIN; volatile int32_t t174 = 743442; t174 = ((x709>x710)+(x711|x712)); if (t174 != -32768) { NG(); } else { ; } } void f175(void) { static uint8_t x713 = 12U; uint64_t x714 = 364279572487LLU; static int64_t x715 = INT64_MIN; int64_t x716 = INT64_MIN; t175 = ((x713>x714)+(x715|x716)); if (t175 != INT64_MIN) { NG(); } else { ; } } void f176(void) { int32_t x718 = -234244; static int64_t x719 = INT64_MIN; static int64_t x720 = -1546668238351409LL; int64_t t176 = 45738LL; t176 = ((x717>x718)+(x719|x720)); if (t176 != -1546668238351408LL) { NG(); } else { ; } } void f177(void) { uint16_t x721 = 2U; int32_t x722 = INT32_MAX; uint16_t x723 = 2U; static int32_t t177 = -180; t177 = ((x721>x722)+(x723|x724)); if (t177 != 3) { NG(); } else { ; } } void f178(void) { int32_t x726 = -14106; int32_t t178 = -59572; t178 = ((x725>x726)+(x727|x728)); if (t178 != -15276) { NG(); } else { ; } } void f179(void) { volatile int32_t x730 = -1; uint16_t x731 = 1491U; int16_t x732 = -1; int32_t t179 = 1569712; t179 = ((x729>x730)+(x731|x732)); if (t179 != -1) { NG(); } else { ; } } void f180(void) { uint16_t x733 = 17538U; uint32_t x735 = UINT32_MAX; volatile int16_t x736 = INT16_MIN; t180 = ((x733>x734)+(x735|x736)); if (t180 != UINT32_MAX) { NG(); } else { ; } } void f181(void) { int32_t x737 = INT32_MIN; volatile int32_t x739 = INT32_MAX; uint8_t x740 = 1U; t181 = ((x737>x738)+(x739|x740)); if (t181 != INT32_MAX) { NG(); } else { ; } } void f182(void) { uint8_t x741 = UINT8_MAX; int16_t x742 = -1; static uint32_t t182 = 0U; t182 = ((x741>x742)+(x743|x744)); if (t182 != 0U) { NG(); } else { ; } } void f183(void) { int8_t x745 = 7; int32_t x747 = -107822; int8_t x748 = INT8_MIN; volatile int32_t t183 = -178881335; t183 = ((x745>x746)+(x747|x748)); if (t183 != -45) { NG(); } else { ; } } void f184(void) { static int8_t x749 = -1; volatile int8_t x750 = INT8_MIN; uint16_t x751 = 18228U; static int16_t x752 = INT16_MIN; int32_t t184 = 29268590; t184 = ((x749>x750)+(x751|x752)); if (t184 != -14539) { NG(); } else { ; } } void f185(void) { volatile uint8_t x753 = UINT8_MAX; static uint16_t x754 = 6U; int8_t x755 = 16; int8_t x756 = INT8_MAX; int32_t t185 = 7789783; t185 = ((x753>x754)+(x755|x756)); if (t185 != 128) { NG(); } else { ; } } void f186(void) { volatile int32_t x757 = INT32_MIN; volatile int16_t x758 = INT16_MIN; int32_t x759 = INT32_MAX; int8_t x760 = -23; static int32_t t186 = -2; t186 = ((x757>x758)+(x759|x760)); if (t186 != -1) { NG(); } else { ; } } void f187(void) { int32_t x761 = INT32_MIN; static int32_t x762 = INT32_MIN; static int16_t x763 = 30; volatile int8_t x764 = INT8_MAX; int32_t t187 = 1; t187 = ((x761>x762)+(x763|x764)); if (t187 != 127) { NG(); } else { ; } } void f188(void) { static volatile uint32_t x765 = 8209436U; static int64_t x766 = INT64_MIN; int16_t x767 = 341; int16_t x768 = INT16_MIN; static volatile int32_t t188 = -49411; t188 = ((x765>x766)+(x767|x768)); if (t188 != -32426) { NG(); } else { ; } } void f189(void) { static uint8_t x769 = 1U; volatile int16_t x770 = INT16_MIN; uint8_t x771 = 4U; uint16_t x772 = UINT16_MAX; t189 = ((x769>x770)+(x771|x772)); if (t189 != 65536) { NG(); } else { ; } } void f190(void) { volatile int8_t x773 = -38; volatile uint8_t x774 = 50U; static volatile uint8_t x775 = 34U; volatile int8_t x776 = 5; int32_t t190 = 8206828; t190 = ((x773>x774)+(x775|x776)); if (t190 != 39) { NG(); } else { ; } } void f191(void) { uint16_t x777 = UINT16_MAX; int64_t x779 = INT64_MIN; volatile int8_t x780 = 8; int64_t t191 = -174LL; t191 = ((x777>x778)+(x779|x780)); if (t191 != -9223372036854775799LL) { NG(); } else { ; } } void f192(void) { int32_t x781 = INT32_MIN; uint32_t x782 = 400912U; static int16_t x783 = -10; static volatile int32_t t192 = 1053; t192 = ((x781>x782)+(x783|x784)); if (t192 != 0) { NG(); } else { ; } } void f193(void) { volatile int16_t x785 = 11044; volatile int8_t x786 = INT8_MIN; int16_t x787 = INT16_MIN; volatile uint8_t x788 = 94U; static int32_t t193 = 60865; t193 = ((x785>x786)+(x787|x788)); if (t193 != -32673) { NG(); } else { ; } } void f194(void) { static int16_t x789 = INT16_MIN; int8_t x790 = -1; int64_t x791 = -270640453972LL; volatile uint64_t x792 = UINT64_MAX; t194 = ((x789>x790)+(x791|x792)); if (t194 != UINT64_MAX) { NG(); } else { ; } } void f195(void) { static volatile int16_t x794 = INT16_MAX; volatile uint8_t x795 = 29U; uint32_t x796 = 1039939166U; volatile uint32_t t195 = 16683U; t195 = ((x793>x794)+(x795|x796)); if (t195 != 1039939167U) { NG(); } else { ; } } void f196(void) { static int16_t x797 = INT16_MIN; int32_t x798 = 215506957; int8_t x800 = INT8_MIN; int32_t t196 = -4120730; t196 = ((x797>x798)+(x799|x800)); if (t196 != -1) { NG(); } else { ; } } void f197(void) { int16_t x801 = INT16_MIN; int8_t x802 = INT8_MIN; volatile int16_t x803 = 61; volatile int32_t t197 = 181447517; t197 = ((x801>x802)+(x803|x804)); if (t197 != -1) { NG(); } else { ; } } void f198(void) { volatile int64_t x805 = INT64_MAX; int32_t x806 = INT32_MIN; uint32_t x808 = 68U; static volatile int64_t t198 = -9487LL; t198 = ((x805>x806)+(x807|x808)); if (t198 != -9223372036854775739LL) { NG(); } else { ; } } void f199(void) { static int8_t x809 = INT8_MIN; uint8_t x810 = 98U; static int64_t x811 = -1LL; uint16_t x812 = UINT16_MAX; volatile int64_t t199 = 1925728961679000535LL; t199 = ((x809>x810)+(x811|x812)); if (t199 != -1LL) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
66812.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup edutil */ #include "MEM_guardedalloc.h" #include "BLI_math.h" #include "BLI_string.h" #include "BLI_string_cursor_utf8.h" #include "BLI_string_utf8.h" #include "BLI_utildefines.h" #include "BLT_translation.h" #include "BKE_context.h" #include "BKE_scene.h" #include "BKE_unit.h" #include "DNA_scene_types.h" #include "WM_api.h" #include "WM_types.h" #ifdef WITH_PYTHON # include "BPY_extern_run.h" #endif #include "ED_numinput.h" #include "UI_interface.h" /* Numeric input which isn't allowing full numeric editing. */ #define USE_FAKE_EDIT /** * #NumInput.flag * (1 << 8) and below are reserved for public flags! */ enum { /** Enable full editing, with units and math operators support. */ NUM_EDIT_FULL = (1 << 9), #ifdef USE_FAKE_EDIT /** Fake edited state (temp, avoids issue with backspace). */ NUM_FAKE_EDITED = (1 << 10), #endif }; /* NumInput.val_flag[] */ enum { /* (1 << 8) and below are reserved for public flags! */ /** User has edited this value somehow. */ NUM_EDITED = (1 << 9), /** Current expression for this value is invalid. */ NUM_INVALID = (1 << 10), #ifdef USE_FAKE_EDIT /** Current expression's result has to be negated. */ NUM_NEGATE = (1 << 11), /** Current expression's result has to be inverted. */ NUM_INVERSE = (1 << 12), #endif }; /* ************************** Functions *************************** */ /* ************************** NUMINPUT **************************** */ void initNumInput(NumInput *n) { n->idx_max = 0; n->unit_sys = USER_UNIT_NONE; copy_vn_i(n->unit_type, NUM_MAX_ELEMENTS, B_UNIT_NONE); n->unit_use_radians = false; n->flag = 0; copy_vn_short(n->val_flag, NUM_MAX_ELEMENTS, 0); zero_v3(n->val); copy_vn_fl(n->val_org, NUM_MAX_ELEMENTS, 0.0f); copy_vn_fl(n->val_inc, NUM_MAX_ELEMENTS, 1.0f); n->idx = 0; n->str[0] = '\0'; n->str_cur = 0; } /* str must be NUM_STR_REP_LEN * (idx_max + 1) length. */ void outputNumInput(NumInput *n, char *str, UnitSettings *unit_settings) { short j; const int ln = NUM_STR_REP_LEN; int prec = 2; /* draw-only, and avoids too much issues with radian->degrees conversion. */ for (j = 0; j <= n->idx_max; j++) { /* if AFFECTALL and no number typed and cursor not on number, use first number */ const short i = (n->flag & NUM_AFFECT_ALL && n->idx != j && !(n->val_flag[j] & NUM_EDITED)) ? 0 : j; /* Use scale_length if needed! */ const float fac = (float)BKE_scene_unit_scale(unit_settings, n->unit_type[j], 1.0); if (n->val_flag[i] & NUM_EDITED) { /* Get the best precision, allows us to draw '10.0001' as '10' instead! */ prec = UI_calc_float_precision(prec, (double)n->val[i]); if (i == n->idx) { const char *heading_exp = "", *trailing_exp = ""; char before_cursor[NUM_STR_REP_LEN]; char val[16]; #ifdef USE_FAKE_EDIT if (n->val_flag[i] & NUM_NEGATE) { heading_exp = (n->val_flag[i] & NUM_INVERSE) ? "-1/(" : "-("; trailing_exp = ")"; } else if (n->val_flag[i] & NUM_INVERSE) { heading_exp = "1/("; trailing_exp = ")"; } #endif if (n->val_flag[i] & NUM_INVALID) { BLI_strncpy(val, "Invalid", sizeof(val)); } else { bUnit_AsString(val, sizeof(val), (double)(n->val[i] * fac), prec, n->unit_sys, n->unit_type[i], true, false); } /* +1 because of trailing '\0' */ BLI_strncpy(before_cursor, n->str, n->str_cur + 1); BLI_snprintf(&str[j * ln], ln, "[%s%s|%s%s] = %s", heading_exp, before_cursor, &n->str[n->str_cur], trailing_exp, val); } else { const char *cur = (i == n->idx) ? "|" : ""; if (n->unit_use_radians && n->unit_type[i] == B_UNIT_ROTATION) { /* Radian exception... */ BLI_snprintf(&str[j * ln], ln, "%s%.6gr%s", cur, n->val[i], cur); } else { char tstr[NUM_STR_REP_LEN]; bUnit_AsString( tstr, ln, (double)n->val[i], prec, n->unit_sys, n->unit_type[i], true, false); BLI_snprintf(&str[j * ln], ln, "%s%s%s", cur, tstr, cur); } } } else { const char *cur = (i == n->idx) ? "|" : ""; BLI_snprintf(&str[j * ln], ln, "%sNONE%s", cur, cur); } /* We might have cut some multi-bytes utf8 chars * (e.g. trailing '°' of degrees values can become only 'A')... */ BLI_utf8_invalid_strip(&str[j * ln], strlen(&str[j * ln])); } } bool hasNumInput(const NumInput *n) { short i; #ifdef USE_FAKE_EDIT if (n->flag & NUM_FAKE_EDITED) { return true; } #endif for (i = 0; i <= n->idx_max; i++) { if (n->val_flag[i] & NUM_EDITED) { return true; } } return false; } /** * \warning \a vec must be set beforehand otherwise we risk uninitialized vars. */ bool applyNumInput(NumInput *n, float *vec) { short i, j; float val; if (hasNumInput(n)) { for (j = 0; j <= n->idx_max; j++) { #ifdef USE_FAKE_EDIT if (n->flag & NUM_FAKE_EDITED) { val = n->val[j]; } else #endif { /* if AFFECTALL and no number typed and cursor not on number, use first number */ i = (n->flag & NUM_AFFECT_ALL && n->idx != j && !(n->val_flag[j] & NUM_EDITED)) ? 0 : j; val = (!(n->val_flag[i] & NUM_EDITED) && n->val_flag[i] & NUM_NULL_ONE) ? 1.0f : n->val[i]; if (n->val_flag[i] & NUM_NO_NEGATIVE && val < 0.0f) { val = 0.0f; } if (n->val_flag[i] & NUM_NO_FRACTION && val != floorf(val)) { val = floorf(val + 0.5f); if (n->val_flag[i] & NUM_NO_ZERO && val == 0.0f) { val = 1.0f; } } else if (n->val_flag[i] & NUM_NO_ZERO && val == 0.0f) { val = 0.0001f; } } vec[j] = val; } #ifdef USE_FAKE_EDIT n->flag &= ~NUM_FAKE_EDITED; #endif return true; } /* Else, we set the 'org' values for numinput! */ for (j = 0; j <= n->idx_max; j++) { n->val[j] = n->val_org[j] = vec[j]; } return false; } static void value_to_editstr(NumInput *n, int idx) { const int prec = 6; /* editing, higher precision needed. */ n->str_cur = bUnit_AsString(n->str, NUM_STR_REP_LEN, (double)n->val[idx], prec, n->unit_sys, n->unit_type[idx], true, false); } static bool editstr_insert_at_cursor(NumInput *n, const char *buf, const int buf_len) { int cur = n->str_cur; int len = strlen(&n->str[cur]) + 1; /* +1 for the trailing '\0'. */ int n_cur = cur + buf_len; if (n_cur + len >= NUM_STR_REP_LEN) { return false; } memmove(&n->str[n_cur], &n->str[cur], len); memcpy(&n->str[cur], buf, sizeof(char) * buf_len); n->str_cur = n_cur; return true; } bool user_string_to_number(bContext *C, const char *str, const UnitSettings *unit, int type, const char *error_prefix, double *r_value) { #ifdef WITH_PYTHON double unit_scale = BKE_scene_unit_scale(unit, type, 1.0); if (bUnit_ContainsUnit(str, type)) { char str_unit_convert[256]; BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert)); bUnit_ReplaceString( str_unit_convert, sizeof(str_unit_convert), str, unit_scale, unit->system, type); return BPY_run_string_as_number(C, NULL, str_unit_convert, error_prefix, r_value); } int success = BPY_run_string_as_number(C, NULL, str, error_prefix, r_value); *r_value *= bUnit_PreferredInputUnitScalar(unit, type); *r_value /= unit_scale; return success; #else UNUSED_VARS(C, unit, type); *r_value = atof(str); return true; #endif } static bool editstr_is_simple_numinput(const char ascii) { if (ascii >= '0' && ascii <= '9') { return true; } if (ascii == '.') { return true; } return false; } bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event) { const char *utf8_buf = NULL; char ascii[2] = {'\0', '\0'}; bool updated = false; short idx = n->idx, idx_max = n->idx_max; short dir = STRCUR_DIR_NEXT, mode = STRCUR_JUMP_NONE; int cur; #ifdef USE_FAKE_EDIT if (U.flag & USER_FLAG_NUMINPUT_ADVANCED) #endif { if ((event->ctrl == 0) && (event->alt == 0) && (event->ascii != '\0') && strchr("01234567890@%^&*-+/{}()[]<>.|", event->ascii)) { if (!(n->flag & NUM_EDIT_FULL)) { n->flag |= NUM_EDITED; n->flag |= NUM_EDIT_FULL; n->val_flag[idx] |= NUM_EDITED; } } } #ifdef USE_FAKE_EDIT /* XXX Hack around keyboards without direct access to '=' nor '*'... */ if (ELEM(event->ascii, '=', '*')) { if (!(n->flag & NUM_EDIT_FULL)) { n->flag |= NUM_EDIT_FULL; n->val_flag[idx] |= NUM_EDITED; return true; } if (event->ctrl) { n->flag &= ~NUM_EDIT_FULL; return true; } } #endif switch (event->type) { case EVT_MODAL_MAP: if (ELEM(event->val, NUM_MODAL_INCREMENT_UP, NUM_MODAL_INCREMENT_DOWN)) { n->val[idx] += (event->val == NUM_MODAL_INCREMENT_UP) ? n->val_inc[idx] : -n->val_inc[idx]; value_to_editstr(n, idx); n->val_flag[idx] |= NUM_EDITED; updated = true; } else { /* might be a char too... */ utf8_buf = event->utf8_buf; ascii[0] = event->ascii; } break; case EVT_BACKSPACEKEY: /* Part specific to backspace... */ if (!(n->val_flag[idx] & NUM_EDITED)) { copy_v3_v3(n->val, n->val_org); n->val_flag[0] &= ~NUM_EDITED; n->val_flag[1] &= ~NUM_EDITED; n->val_flag[2] &= ~NUM_EDITED; #ifdef USE_FAKE_EDIT n->flag |= NUM_FAKE_EDITED; #else n->flag |= NUM_EDIT_FULL; #endif updated = true; break; } else if (event->shift || !n->str[0]) { n->val[idx] = n->val_org[idx]; n->val_flag[idx] &= ~NUM_EDITED; n->str[0] = '\0'; n->str_cur = 0; updated = true; break; } /* Else, common behavior with DELKEY, * only difference is remove char(s) before/after the cursor. */ dir = STRCUR_DIR_PREV; ATTR_FALLTHROUGH; case EVT_DELKEY: if ((n->val_flag[idx] & NUM_EDITED) && n->str[0]) { int t_cur = cur = n->str_cur; if (event->ctrl) { mode = STRCUR_JUMP_DELIM; } BLI_str_cursor_step_utf8(n->str, strlen(n->str), &t_cur, dir, mode, true); if (t_cur != cur) { if (t_cur < cur) { SWAP(int, t_cur, cur); n->str_cur = cur; } /* +1 for trailing '\0'. */ memmove(&n->str[cur], &n->str[t_cur], strlen(&n->str[t_cur]) + 1); updated = true; } if (!n->str[0]) { n->val[idx] = n->val_org[idx]; } } else { return false; } break; case EVT_LEFTARROWKEY: dir = STRCUR_DIR_PREV; ATTR_FALLTHROUGH; case EVT_RIGHTARROWKEY: cur = n->str_cur; if (event->ctrl) { mode = STRCUR_JUMP_DELIM; } BLI_str_cursor_step_utf8(n->str, strlen(n->str), &cur, dir, mode, true); if (cur != n->str_cur) { n->str_cur = cur; return true; } return false; case EVT_HOMEKEY: if (n->str[0]) { n->str_cur = 0; return true; } return false; case EVT_ENDKEY: if (n->str[0]) { n->str_cur = strlen(n->str); return true; } return false; case EVT_TABKEY: #ifdef USE_FAKE_EDIT n->val_flag[idx] &= ~(NUM_NEGATE | NUM_INVERSE); #endif idx = (idx + idx_max + (event->ctrl ? 0 : 2)) % (idx_max + 1); n->idx = idx; if (n->val_flag[idx] & NUM_EDITED) { value_to_editstr(n, idx); } else { n->str[0] = '\0'; n->str_cur = 0; } return true; case EVT_PADPERIOD: case EVT_PERIODKEY: /* Force numdot, some OSs/countries generate a comma char in this case, * sic... (T37992) */ ascii[0] = '.'; utf8_buf = ascii; break; #if 0 /* Those keys are not directly accessible in all layouts, * preventing to generate matching events. * So we use a hack (ascii value) instead, see below. */ case EQUALKEY: case PADASTERKEY: if (!(n->flag & NUM_EDIT_FULL)) { n->flag |= NUM_EDIT_FULL; n->val_flag[idx] |= NUM_EDITED; return true; } else if (event->ctrl) { n->flag &= ~NUM_EDIT_FULL; return true; } break; #endif #ifdef USE_FAKE_EDIT case EVT_PADMINUS: case EVT_MINUSKEY: if (event->ctrl || !(n->flag & NUM_EDIT_FULL)) { n->val_flag[idx] ^= NUM_NEGATE; updated = true; } break; case EVT_PADSLASHKEY: case EVT_SLASHKEY: if (event->ctrl || !(n->flag & NUM_EDIT_FULL)) { n->val_flag[idx] ^= NUM_INVERSE; updated = true; } break; #endif case EVT_CKEY: if (event->ctrl) { /* Copy current str to the copypaste buffer. */ WM_clipboard_text_set(n->str, 0); updated = true; } break; case EVT_VKEY: if (event->ctrl) { /* extract the first line from the clipboard */ int pbuf_len; char *pbuf = WM_clipboard_text_get_firstline(false, &pbuf_len); if (pbuf) { const bool success = editstr_insert_at_cursor(n, pbuf, pbuf_len); MEM_freeN(pbuf); if (!success) { return false; } n->val_flag[idx] |= NUM_EDITED; } updated = true; } break; default: break; } if (!updated && !utf8_buf && (event->utf8_buf[0] || event->ascii)) { utf8_buf = event->utf8_buf; ascii[0] = event->ascii; } /* Up to this point, if we have a ctrl modifier, skip. * This allows to still access most of modals' shortcuts even in numinput mode. */ if (!updated && event->ctrl) { return false; } if ((!utf8_buf || !utf8_buf[0]) && ascii[0]) { /* Fallback to ascii. */ utf8_buf = ascii; } if (utf8_buf && utf8_buf[0]) { if (!(n->flag & NUM_EDIT_FULL)) { /* In simple edit mode, we only keep a few chars as valid! */ /* no need to decode unicode, ascii is first char only */ if (!editstr_is_simple_numinput(utf8_buf[0])) { return false; } } if (!editstr_insert_at_cursor(n, utf8_buf, BLI_str_utf8_size(utf8_buf))) { return false; } n->val_flag[idx] |= NUM_EDITED; } else if (!updated) { return false; } /* At this point, our value has changed, try to interpret it with python * (if str is not empty!). */ if (n->str[0]) { const float val_prev = n->val[idx]; Scene *sce = CTX_data_scene(C); double val; int success = user_string_to_number( C, n->str, &sce->unit, n->unit_type[idx], IFACE_("Numeric input evaluation"), &val); if (success) { n->val[idx] = (float)val; n->val_flag[idx] &= ~NUM_INVALID; } else { n->val_flag[idx] |= NUM_INVALID; } #ifdef USE_FAKE_EDIT if (n->val_flag[idx] & NUM_NEGATE) { n->val[idx] = -n->val[idx]; } if (n->val_flag[idx] & NUM_INVERSE) { val = n->val[idx]; /* If we invert on radians when user is in degrees, * you get unexpected results... See T53463. */ if (!n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION) { val = RAD2DEG(val); } val = 1.0 / val; if (!n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION) { val = DEG2RAD(val); } n->val[idx] = (float)val; } #endif if (UNLIKELY(!isfinite(n->val[idx]))) { n->val[idx] = val_prev; n->val_flag[idx] |= NUM_INVALID; } } /* REDRAW SINCE NUMBERS HAVE CHANGED */ return true; }
470255.c
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <limits.h> #include "azure_c_shared_utility/gballoc.h" #include "azure_c_shared_utility/httpheaders.h" #include "azure_c_shared_utility/crt_abstractions.h" #include "azure_c_shared_utility/xlogging.h" #include "azure_c_shared_utility/xio.h" #include "azure_c_shared_utility/platform.h" #include "azure_c_shared_utility/tlsio.h" #include "azure_c_shared_utility/threadapi.h" #include "azure_c_shared_utility/shared_util_options.h" #include "azure_c_shared_utility/http_proxy_io.h" #ifdef _MSC_VER #define snprintf _snprintf #endif /*Codes_SRS_HTTPAPI_COMPACT_21_001: [ The httpapi_compact shall implement the methods defined by the httpapi.h. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_002: [ The httpapi_compact shall support the http requests. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_003: [ The httpapi_compact shall return error codes defined by HTTPAPI_RESULT. ]*/ #include "azure_c_shared_utility/httpapi.h" #define MAX_HOSTNAME 64 #define TEMP_BUFFER_SIZE 1024 /*Codes_SRS_HTTPAPI_COMPACT_21_077: [ The HTTPAPI_ExecuteRequest shall wait, at least, 10 seconds for the SSL open process. ]*/ #define MAX_OPEN_RETRY 100 /*Codes_SRS_HTTPAPI_COMPACT_21_084: [ The HTTPAPI_CloseConnection shall wait, at least, 10 seconds for the SSL close process. ]*/ #define MAX_CLOSE_RETRY 100 /*Codes_SRS_HTTPAPI_COMPACT_21_079: [ The HTTPAPI_ExecuteRequest shall wait, at least, 20 seconds to send a buffer using the SSL connection. ]*/ #define MAX_SEND_RETRY 200 /*Codes_SRS_HTTPAPI_COMPACT_21_081: [ The HTTPAPI_ExecuteRequest shall try to read the message with the response up to 20 seconds. ]*/ #define MAX_RECEIVE_RETRY 200 /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ #define RETRY_INTERVAL_IN_MICROSECONDS 100 MU_DEFINE_ENUM_STRINGS(HTTPAPI_RESULT, HTTPAPI_RESULT_VALUES) typedef struct HTTP_HANDLE_DATA_TAG { char* hostName; char* certificate; char* x509ClientCertificate; char* x509ClientPrivateKey; const char* proxy_host; int proxy_port; const char* proxy_username; const char* proxy_password; XIO_HANDLE xio_handle; size_t received_bytes_count; unsigned char* received_bytes; unsigned int is_io_error : 1; unsigned int is_connected : 1; unsigned int send_completed : 1; } HTTP_HANDLE_DATA; /*the following function does the same as sscanf(pos2, "%d", &sec)*/ /*this function only exists because some of platforms do not have sscanf. */ static int ParseStringToDecimal(const char *src, int* dst) { int result; char* next; long num = strtol(src, &next, 0); if (src == next || num < INT_MIN || num > INT_MAX) { result = EOF; } else { result = 1; } if (num < INT_MIN) num = INT_MIN; if (num > INT_MAX) num = INT_MAX; *dst = (int)num; return result; } /*the following function does the same as sscanf(pos2, "%x", &sec)*/ /*this function only exists because some of platforms do not have sscanf. This is not a full implementation; it only works with well-defined x numbers. */ #define HEXA_DIGIT_VAL(c) (((c>='0') && (c<='9')) ? (c-'0') : ((c>='a') && (c<='f')) ? (c-'a'+10) : ((c>='A') && (c<='F')) ? (c-'A'+10) : -1) static int ParseStringToHexadecimal(const char *src, size_t* dst) { int result; int digitVal; if (src == NULL) { result = EOF; } else if (HEXA_DIGIT_VAL(*src) == -1) { result = EOF; } else { (*dst) = 0; while ((digitVal = HEXA_DIGIT_VAL(*src)) != -1) { (*dst) *= 0x10; (*dst) += (size_t)digitVal; src++; } result = 1; } return result; } /*the following function does the same as sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &ret) */ /*this function only exists because some of platforms do not have sscanf. This is not a full implementation; it only works with well-defined HTTP response. */ static int ParseHttpResponse(const char* src, int* dst) { int result; static const char HTTPPrefix[] = "HTTP/"; bool fail; const char* runPrefix; if ((src == NULL) || (dst == NULL)) { result = EOF; } else { fail = false; runPrefix = HTTPPrefix; while((*runPrefix) != '\0') { if ((*runPrefix) != (*src)) { fail = true; break; } src++; runPrefix++; } if (!fail) { while ((*src) != '.') { if ((*src) == '\0') { fail = true; break; } src++; } } if (!fail) { while ((*src) != ' ') { if ((*src) == '\0') { fail = true; break; } src++; } } if (fail) { result = EOF; } else { result = ParseStringToDecimal(src, dst); } } return result; } HTTPAPI_RESULT HTTPAPI_Init(void) { /*Codes_SRS_HTTPAPI_COMPACT_21_004: [ The HTTPAPI_Init shall allocate all memory to control the http protocol. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_007: [ If there is not enough memory to control the http protocol, the HTTPAPI_Init shall return HTTPAPI_ALLOC_FAILED. ]*/ /** * No memory is necessary. */ /*Codes_SRS_HTTPAPI_COMPACT_21_006: [ If HTTPAPI_Init succeed allocating all the needed memory, it shall return HTTPAPI_OK. ]*/ return HTTPAPI_OK; } void HTTPAPI_Deinit(void) { /*Codes_SRS_HTTPAPI_COMPACT_21_009: [ The HTTPAPI_Init shall release all memory allocated by the httpapi_compact. ]*/ /** * No memory was necessary. */ } /*Codes_SRS_HTTPAPI_COMPACT_21_011: [ The HTTPAPI_CreateConnection shall create an http connection to the host specified by the hostName parameter. ]*/ HTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName) { HTTP_HANDLE_DATA* http_instance; if (hostName == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_014: [ If the hostName is NULL, the HTTPAPI_CreateConnection shall return NULL as the handle. ]*/ LogError("Invalid host name. Null hostName parameter."); http_instance = NULL; } else if (*hostName == '\0') { /*Codes_SRS_HTTPAPI_COMPACT_21_015: [ If the hostName is empty, the HTTPAPI_CreateConnection shall return NULL as the handle. ]*/ LogError("Invalid host name. Empty string."); http_instance = NULL; } else { http_instance = (HTTP_HANDLE_DATA*)malloc(sizeof(HTTP_HANDLE_DATA)); /*Codes_SRS_HTTPAPI_COMPACT_21_013: [ If there is not enough memory to control the http connection, the HTTPAPI_CreateConnection shall return NULL as the handle. ]*/ if (http_instance == NULL) { LogError("There is no memory to control the http connection"); } else if(mallocAndStrcpy_s((char**)&(http_instance->hostName), hostName) != 0) { LogError("failure allocate host name"); free(http_instance); http_instance = NULL; } else { http_instance->xio_handle = NULL; http_instance->is_connected = 0; http_instance->is_io_error = 0; http_instance->received_bytes_count = 0; http_instance->received_bytes = NULL; http_instance->certificate = NULL; http_instance->x509ClientCertificate = NULL; http_instance->x509ClientPrivateKey = NULL; http_instance->proxy_host = NULL; http_instance->proxy_port = 0; http_instance->proxy_username = NULL; http_instance->proxy_password = NULL; } } /*Codes_SRS_HTTPAPI_COMPACT_21_012: [ The HTTPAPI_CreateConnection shall return a non-NULL handle on success. ]*/ return (HTTP_HANDLE)http_instance; } static void on_io_close_complete(void* context) { HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)context; if (http_instance != NULL) { http_instance->is_connected = 0; } } void HTTPAPI_CloseConnection(HTTP_HANDLE handle) { HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)handle; /*Codes_SRS_HTTPAPI_COMPACT_21_020: [ If the connection handle is NULL, the HTTPAPI_CloseConnection shall not do anything. ]*/ if (http_instance != NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_019: [ If there is no previous connection, the HTTPAPI_CloseConnection shall not do anything. ]*/ if (http_instance->xio_handle != NULL) { http_instance->is_io_error = 0; /*Codes_SRS_HTTPAPI_COMPACT_21_017: [ The HTTPAPI_CloseConnection shall close the connection previously created in HTTPAPI_ExecuteRequest. ]*/ if (xio_close(http_instance->xio_handle, on_io_close_complete, http_instance) != 0) { LogError("The SSL got error closing the connection"); /*Codes_SRS_HTTPAPI_COMPACT_21_087: [ If the xio return anything different than 0, the HTTPAPI_CloseConnection shall destroy the connection anyway. ]*/ http_instance->is_connected = 0; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_084: [ The HTTPAPI_CloseConnection shall wait, at least, 10 seconds for the SSL close process. ]*/ int countRetry = MAX_CLOSE_RETRY; while (http_instance->is_connected == 1) { xio_dowork(http_instance->xio_handle); if ((countRetry--) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_085: [ If the HTTPAPI_CloseConnection retries 10 seconds to close the connection without success, it shall destroy the connection anyway. ]*/ LogError("Close timeout. The SSL didn't close the connection"); http_instance->is_connected = 0; } else if (http_instance->is_io_error == 1) { LogError("The SSL got error closing the connection"); http_instance->is_connected = 0; } else if (http_instance->is_connected == 1) { LogInfo("Waiting for TLS close connection"); /*Codes_SRS_HTTPAPI_COMPACT_21_086: [ The HTTPAPI_CloseConnection shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } } } /*Codes_SRS_HTTPAPI_COMPACT_21_076: [ After close the connection, The HTTPAPI_CloseConnection shall destroy the connection previously created in HTTPAPI_CreateConnection. ]*/ xio_destroy(http_instance->xio_handle); } if (http_instance->hostName != NULL) { free((void*)http_instance->hostName); } #ifndef DO_NOT_COPY_TRUSTED_CERTS_STRING /*Codes_SRS_HTTPAPI_COMPACT_21_018: [ If there is a certificate associated to this connection, the HTTPAPI_CloseConnection shall free all allocated memory for the certificate. ]*/ if (http_instance->certificate) { free(http_instance->certificate); } #endif /*Codes_SRS_HTTPAPI_COMPACT_06_001: [ If there is a x509 client certificate associated to this connection, the HTTAPI_CloseConnection shall free all allocated memory for the certificate. ]*/ if (http_instance->x509ClientCertificate) { free(http_instance->x509ClientCertificate); } /*Codes_SRS_HTTPAPI_COMPACT_06_002: [ If there is a x509 client private key associated to this connection, then HTTP_CloseConnection shall free all the allocated memory for the private key. ]*/ if (http_instance->x509ClientPrivateKey) { free(http_instance->x509ClientPrivateKey); } if (http_instance->proxy_host != NULL) { free((void*)http_instance->proxy_host); } if (http_instance->proxy_username != NULL) { free((void*)http_instance->proxy_username); } if (http_instance->proxy_password != NULL) { free((void*)http_instance->proxy_password); } free(http_instance); } } static void on_io_open_complete(void* context, IO_OPEN_RESULT open_result) { HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)context; if (http_instance != NULL) { if (open_result == IO_OPEN_OK) { http_instance->is_connected = 1; http_instance->is_io_error = 0; } else { http_instance->is_io_error = 1; } } } static void on_send_complete(void* context, IO_SEND_RESULT send_result) { HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)context; if (http_instance != NULL) { if (send_result == IO_SEND_OK) { http_instance->send_completed = 1; http_instance->is_io_error = 0; } else { http_instance->is_io_error = 1; } } } #define TOLOWER(c) (((c>='A') && (c<='Z'))?c-'A'+'a':c) static int InternStrnicmp(const char* s1, const char* s2, size_t n) { int result; if (s1 == NULL) result = -1; else if (s2 == NULL) result = 1; else { result = 0; while(n-- && result == 0) { if (*s1 == 0) result = -1; else if (*s2 == 0) result = 1; else { result = TOLOWER(*s1) - TOLOWER(*s2); ++s1; ++s2; } } } return result; } static void on_bytes_received(void* context, const unsigned char* buffer, size_t size) { unsigned char* new_received_bytes; HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)context; if (http_instance != NULL) { if (buffer == NULL) { http_instance->is_io_error = 1; LogError("NULL pointer error"); } else { /* Here we got some bytes so we'll buffer them so the receive functions can consumer it */ new_received_bytes = (unsigned char*)realloc(http_instance->received_bytes, http_instance->received_bytes_count + size); if (new_received_bytes == NULL) { http_instance->is_io_error = 1; LogError("Error allocating memory for received data"); } else { http_instance->received_bytes = new_received_bytes; if (memcpy(http_instance->received_bytes + http_instance->received_bytes_count, buffer, size) == NULL) { http_instance->is_io_error = 1; LogError("Error copping received data to the HTTP bufffer"); } else { http_instance->received_bytes_count += size; } } } } } static void on_io_error(void* context) { HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)context; if (http_instance != NULL) { http_instance->is_io_error = 1; LogError("Error signalled by underlying IO"); } } static int conn_receive(HTTP_HANDLE_DATA* http_instance, char* buffer, int count) { int result; if ((http_instance == NULL) || (buffer == NULL) || (count < 0)) { LogError("conn_receive: %s", ((http_instance == NULL) ? "Invalid HTTP instance" : "Invalid HTTP buffer")); result = -1; } else { result = 0; while (result < count) { xio_dowork(http_instance->xio_handle); /* if any error was detected while receiving then simply break and report it */ if (http_instance->is_io_error != 0) { LogError("xio reported error on dowork"); result = -1; break; } if (http_instance->received_bytes_count >= (size_t)count) { /* Consuming bytes from the receive buffer */ (void)memcpy(buffer, http_instance->received_bytes, count); (void)memmove(http_instance->received_bytes, http_instance->received_bytes + count, http_instance->received_bytes_count - count); http_instance->received_bytes_count -= count; /* we're not reallocating at each consumption so that we don't trash due to byte by byte consumption */ if (http_instance->received_bytes_count == 0) { free(http_instance->received_bytes); http_instance->received_bytes = NULL; } result = count; break; } /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } } return result; } static void conn_receive_discard_buffer(HTTP_HANDLE_DATA* http_instance) { if (http_instance != NULL) { if (http_instance->received_bytes != NULL) { free(http_instance->received_bytes); http_instance->received_bytes = NULL; } http_instance->received_bytes_count = 0; } } static int readLine(HTTP_HANDLE_DATA* http_instance, char* buf, const size_t maxBufSize) { int resultLineSize; if ((http_instance == NULL) || (buf == NULL) || (maxBufSize == 0)) { LogError("%s", ((http_instance == NULL) ? "Invalid HTTP instance" : "Invalid HTTP buffer")); resultLineSize = -1; } else { char* destByte = buf; /*Codes_SRS_HTTPAPI_COMPACT_21_081: [ The HTTPAPI_ExecuteRequest shall try to read the message with the response up to 20 seconds. ]*/ int countRetry = MAX_RECEIVE_RETRY; bool endOfSearch = false; resultLineSize = -1; while (!endOfSearch) { xio_dowork(http_instance->xio_handle); /* if any error was detected while receiving then simply break and report it */ if (http_instance->is_io_error != 0) { LogError("xio reported error on dowork"); endOfSearch = true; } else { unsigned char* receivedByte = http_instance->received_bytes; while (receivedByte < (http_instance->received_bytes + http_instance->received_bytes_count)) { if ((*receivedByte) != '\r') { (*destByte) = (*receivedByte); destByte++; receivedByte++; if (destByte >= (buf + maxBufSize - 1)) { LogError("Received message is bigger than the http buffer"); receivedByte = http_instance->received_bytes + http_instance->received_bytes_count; endOfSearch = true; break; } } else { receivedByte++; if ((receivedByte < (http_instance->received_bytes + http_instance->received_bytes_count)) && ((*receivedByte) == '\n')) { receivedByte++; } (*destByte) = '\0'; resultLineSize = (int)(destByte - buf); endOfSearch = true; break; } } http_instance->received_bytes_count -= (receivedByte - http_instance->received_bytes); if (http_instance->received_bytes_count != 0) { (void)memmove(http_instance->received_bytes, receivedByte, http_instance->received_bytes_count); } else { conn_receive_discard_buffer(http_instance); } } if (!endOfSearch) { if ((countRetry--) > 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ LogError("Receive timeout. The HTTP request is incomplete"); endOfSearch = true; } } } } return resultLineSize; } static int readChunk(HTTP_HANDLE_DATA* http_instance, char* buf, size_t size) { int cur, offset; // read content with specified length, even if it is received // only in chunks due to fragmentation in the networking layer. // returns -1 in case of error. offset = 0; while (size > (size_t)0) { cur = conn_receive(http_instance, buf + offset, (int)size); // end of stream reached if (cur == 0) { break; } // read cur bytes (might be less than requested) size -= (size_t)cur; offset += cur; } return offset; } static int skipN(HTTP_HANDLE_DATA* http_instance, size_t n) { // read and abandon response content with specified length // returns -1 in case of error. int result; if (http_instance == NULL) { LogError("Invalid HTTP instance"); result = -1; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_081: [ The HTTPAPI_ExecuteRequest shall try to read the message with the response up to 20 seconds. ]*/ int countRetry = MAX_RECEIVE_RETRY; result = (int)n; while (n > 0) { xio_dowork(http_instance->xio_handle); /* if any error was detected while receiving then simply break and report it */ if (http_instance->is_io_error != 0) { LogError("xio reported error on dowork"); result = -1; n = 0; } else { if (http_instance->received_bytes_count <= n) { n -= http_instance->received_bytes_count; http_instance->received_bytes_count = 0; } else { http_instance->received_bytes_count -= n; (void)memmove(http_instance->received_bytes, http_instance->received_bytes + n, http_instance->received_bytes_count); n = 0; } if (n > 0) { if ((countRetry--) > 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ LogError("Receive timeout. The HTTP request is incomplete"); n = 0; result = -1; } } } } } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_021: [ The HTTPAPI_ExecuteRequest shall execute the http communtication with the provided host, sending a request and reciving the response. ]*/ static HTTPAPI_RESULT OpenXIOConnection(HTTP_HANDLE_DATA* http_instance) { HTTPAPI_RESULT result; TLSIO_CONFIG tlsio_config; HTTP_PROXY_IO_CONFIG http_proxy_io_config; if (http_instance->is_connected != 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; } else { http_instance->is_io_error = 0; tlsio_config.hostname = http_instance->hostName; tlsio_config.port = 443; if (http_instance->proxy_host != NULL) { tlsio_config.underlying_io_interface = http_proxy_io_get_interface_description(); } else { tlsio_config.underlying_io_interface = NULL; } if (tlsio_config.underlying_io_interface != NULL) { tlsio_config.underlying_io_parameters = (void*)&http_proxy_io_config; http_proxy_io_config.proxy_hostname = http_instance->proxy_host; http_proxy_io_config.proxy_port = http_instance->proxy_port; http_proxy_io_config.username = http_instance->proxy_username; http_proxy_io_config.password = http_instance->proxy_password; http_proxy_io_config.hostname = http_instance->hostName; http_proxy_io_config.port = 443; } else { tlsio_config.underlying_io_parameters = NULL; } http_instance->xio_handle = xio_create(platform_get_default_tlsio(), (void*)&tlsio_config); if (http_instance->xio_handle == NULL) { LogError("Create connection failed"); free(http_instance); http_instance = NULL; } /*Codes_SRS_HTTPAPI_COMPACT_21_022: [ If a Certificate was provided, the HTTPAPI_ExecuteRequest shall set this option on the transport layer. ]*/ else if ((http_instance->certificate != NULL) && (xio_setoption(http_instance->xio_handle, OPTION_TRUSTED_CERT, http_instance->certificate) != 0)) { /*Codes_SRS_HTTPAPI_COMPACT_21_023: [ If the transport failed setting the Certificate, the HTTPAPI_ExecuteRequest shall not send any request and return HTTPAPI_SET_OPTION_FAILED. ]*/ result = HTTPAPI_SET_OPTION_FAILED; LogInfo("Could not load certificate"); } /*Codes_SRS_HTTPAPI_COMPACT_06_003: [ If the x509 client certificate is provided, the HTTPAPI_ExecuteRequest shall set this option on the transport layer. ]*/ else if ((http_instance->x509ClientCertificate != NULL) && (xio_setoption(http_instance->xio_handle, SU_OPTION_X509_CERT, http_instance->x509ClientCertificate) != 0)) { /*Codes_SRS_HTTPAPI_COMPACT_06_005: [ If the transport failed setting the client certificate, the HTTPAPI_ExecuteRequest shall not send any request and return HTTPAPI_SET_OPTION_FAILED. ]*/ result = HTTPAPI_SET_OPTION_FAILED; LogInfo("Could not load the client certificate"); } else if ((http_instance->x509ClientPrivateKey != NULL) && (xio_setoption(http_instance->xio_handle, SU_OPTION_X509_PRIVATE_KEY, http_instance->x509ClientPrivateKey) != 0)) { /*Codes_SRS_HTTPAPI_COMPACT_06_006: [ If the transport failed setting the client certificate private key, the HTTPAPI_ExecuteRequest shall not send any request and return HTTPAPI_SET_OPTION_FAILED. ] */ result = HTTPAPI_SET_OPTION_FAILED; LogInfo("Could not load the client certificate private key"); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_024: [ The HTTPAPI_ExecuteRequest shall open the transport connection with the host to send the request. ]*/ if (xio_open(http_instance->xio_handle, on_io_open_complete, http_instance, on_bytes_received, http_instance, on_io_error, http_instance) != 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_025: [ If the open process failed, the HTTPAPI_ExecuteRequest shall not send any request and return HTTPAPI_OPEN_REQUEST_FAILED. ]*/ result = HTTPAPI_OPEN_REQUEST_FAILED; } else { int countRetry; /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; /*Codes_SRS_HTTPAPI_COMPACT_21_077: [ The HTTPAPI_ExecuteRequest shall wait, at least, 10 seconds for the SSL open process. ]*/ countRetry = MAX_OPEN_RETRY; while ((http_instance->is_connected == 0) && (http_instance->is_io_error == 0)) { xio_dowork(http_instance->xio_handle); //LogInfo("Waiting for TLS connection"); if ((countRetry--) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_078: [ If the HTTPAPI_ExecuteRequest cannot open the connection in 10 seconds, it shall fail and return HTTPAPI_OPEN_REQUEST_FAILED. ]*/ LogError("Open timeout. The HTTP request is incomplete"); result = HTTPAPI_OPEN_REQUEST_FAILED; break; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } } } } } if ((http_instance->is_io_error != 0) && (result == HTTPAPI_OK)) { /*Codes_SRS_HTTPAPI_COMPACT_21_025: [ If the open process failed, the HTTPAPI_ExecuteRequest shall not send any request and return HTTPAPI_OPEN_REQUEST_FAILED. ]*/ result = HTTPAPI_OPEN_REQUEST_FAILED; } return result; } static HTTPAPI_RESULT conn_send_all(HTTP_HANDLE_DATA* http_instance, const unsigned char* buf, size_t bufLen) { HTTPAPI_RESULT result; http_instance->send_completed = 0; http_instance->is_io_error = 0; if (xio_send(http_instance->xio_handle, buf, bufLen, on_send_complete, http_instance) != 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_028: [ If the HTTPAPI_ExecuteRequest cannot send the request header, it shall return HTTPAPI_HTTP_HEADERS_FAILED. ]*/ result = HTTPAPI_SEND_REQUEST_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_079: [ The HTTPAPI_ExecuteRequest shall wait, at least, 20 seconds to send a buffer using the SSL connection. ]*/ int countRetry = MAX_SEND_RETRY; /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; while ((http_instance->send_completed == 0) && (result == HTTPAPI_OK)) { xio_dowork(http_instance->xio_handle); if (http_instance->is_io_error != 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_028: [ If the HTTPAPI_ExecuteRequest cannot send the request header, it shall return HTTPAPI_HTTP_HEADERS_FAILED. ]*/ result = HTTPAPI_SEND_REQUEST_FAILED; } else if ((countRetry--) <= 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_080: [ If the HTTPAPI_ExecuteRequest retries to send the message for 20 seconds without success, it shall fail and return HTTPAPI_SEND_REQUEST_FAILED. ]*/ LogError("Send timeout. The HTTP request is incomplete"); /*Codes_SRS_HTTPAPI_COMPACT_21_028: [ If the HTTPAPI_ExecuteRequest cannot send the request header, it shall return HTTPAPI_HTTP_HEADERS_FAILED. ]*/ result = HTTPAPI_SEND_REQUEST_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_083: [ The HTTPAPI_ExecuteRequest shall wait, at least, 100 milliseconds between retries. ]*/ ThreadAPI_Sleep(RETRY_INTERVAL_IN_MICROSECONDS); } } } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_035: [ The HTTPAPI_ExecuteRequest shall execute resquest for types GET, POST, PUT, DELETE, PATCH, HEAD. ]*/ const char httpapiRequestString[6][7] = { "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD" }; const char* get_request_type(HTTPAPI_REQUEST_TYPE requestType) { return (const char*)httpapiRequestString[requestType]; } /*Codes_SRS_HTTPAPI_COMPACT_21_026: [ If the open process succeed, the HTTPAPI_ExecuteRequest shall send the request message to the host. ]*/ static HTTPAPI_RESULT SendHeadsToXIO(HTTP_HANDLE_DATA* http_instance, HTTPAPI_REQUEST_TYPE requestType, const char* relativePath, HTTP_HEADERS_HANDLE httpHeadersHandle, size_t headersCount) { HTTPAPI_RESULT result; char buf[TEMP_BUFFER_SIZE]; int ret; //Send request /*Codes_SRS_HTTPAPI_COMPACT_21_038: [ The HTTPAPI_ExecuteRequest shall execute the resquest for the path in relativePath parameter. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_036: [ The request type shall be provided in the parameter requestType. ]*/ if (((ret = snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\n", get_request_type(requestType), relativePath)) < 0) || ((size_t)ret >= sizeof(buf))) { /*Codes_SRS_HTTPAPI_COMPACT_21_027: [ If the HTTPAPI_ExecuteRequest cannot create a buffer to send the request, it shall not send any request and return HTTPAPI_STRING_PROCESSING_ERROR. ]*/ result = HTTPAPI_STRING_PROCESSING_ERROR; } /*Codes_SRS_HTTPAPI_COMPACT_21_028: [ If the HTTPAPI_ExecuteRequest cannot send the request header, it shall return HTTPAPI_HTTP_HEADERS_FAILED. ]*/ else if ((result = conn_send_all(http_instance, (const unsigned char*)buf, strlen(buf))) == HTTPAPI_OK) { size_t i; //Send default headers /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ for (i = 0; ((i < headersCount) && (result == HTTPAPI_OK)); i++) { char* header; if (HTTPHeaders_GetHeader(httpHeadersHandle, i, &header) != HTTP_HEADERS_OK) { /*Codes_SRS_HTTPAPI_COMPACT_21_027: [ If the HTTPAPI_ExecuteRequest cannot create a buffer to send the request, it shall not send any request and return HTTPAPI_STRING_PROCESSING_ERROR. ]*/ result = HTTPAPI_STRING_PROCESSING_ERROR; } else { if ((result = conn_send_all(http_instance, (const unsigned char*)header, strlen(header))) == HTTPAPI_OK) { result = conn_send_all(http_instance, (const unsigned char*)"\r\n", (size_t)2); } free(header); } } //Close headers if (result == HTTPAPI_OK) { result = conn_send_all(http_instance, (const unsigned char*)"\r\n", (size_t)2); } } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_042: [ The request can contain the a content message, provided in content parameter. ]*/ static HTTPAPI_RESULT SendContentToXIO(HTTP_HANDLE_DATA* http_instance, const unsigned char* content, size_t contentLength) { HTTPAPI_RESULT result; //Send data (if available) /*Codes_SRS_HTTPAPI_COMPACT_21_045: [ If the contentLength is lower than one, the HTTPAPI_ExecuteRequest shall send the request without content. ]*/ if (content && contentLength > 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_044: [ If the content is not NULL, the number of bytes in the content shall be provided in contentLength parameter. ]*/ result = conn_send_all(http_instance, content, contentLength); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_043: [ If the content is NULL, the HTTPAPI_ExecuteRequest shall send the request without content. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_030: [ At the end of the transmission, the HTTPAPI_ExecuteRequest shall receive the response from the host. ]*/ static HTTPAPI_RESULT ReceiveHeaderFromXIO(HTTP_HANDLE_DATA* http_instance, unsigned int* statusCode) { HTTPAPI_RESULT result; char buf[TEMP_BUFFER_SIZE]; int ret; http_instance->is_io_error = 0; //Receive response if (readLine(http_instance, buf, TEMP_BUFFER_SIZE) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } //Parse HTTP response else if (ParseHttpResponse(buf, &ret) != 1) { //Cannot match string, error /*Codes_SRS_HTTPAPI_COMPACT_21_055: [ If the HTTPAPI_ExecuteRequest cannot parser the received message, it shall return HTTPAPI_RECEIVE_RESPONSE_FAILED. ]*/ LogInfo("Not a correct HTTP answer"); result = HTTPAPI_RECEIVE_RESPONSE_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_046: [ The HTTPAPI_ExecuteRequest shall return the http status reported by the host in the received response. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_048: [ If the statusCode is NULL, the HTTPAPI_ExecuteRequest shall report not report any status. ]*/ if (statusCode) { /*Codes_SRS_HTTPAPI_COMPACT_21_047: [ The HTTPAPI_ExecuteRequest shall report the status in the statusCode parameter. ]*/ *statusCode = ret; } /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; } return result; } static HTTPAPI_RESULT ReceiveContentInfoFromXIO(HTTP_HANDLE_DATA* http_instance, HTTP_HEADERS_HANDLE responseHeadersHandle, size_t* bodyLength, bool* chunked) { HTTPAPI_RESULT result; char buf[TEMP_BUFFER_SIZE]; const char* substr; char* whereIsColon; int lengthInMsg; const char ContentLength[] = "content-length:"; const size_t ContentLengthSize = sizeof(ContentLength) - 1; const char TransferEncoding[] = "transfer-encoding:"; const size_t TransferEncodingSize = sizeof(TransferEncoding) - 1; const char Chunked[] = "chunked"; const size_t ChunkedSize = sizeof(Chunked) - 1; http_instance->is_io_error = 0; //Read HTTP response headers if (readLine(http_instance, buf, sizeof(buf)) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; while (*buf && (result == HTTPAPI_OK)) { if (InternStrnicmp(buf, ContentLength, ContentLengthSize) == 0) { substr = buf + ContentLengthSize; if (ParseStringToDecimal(substr, &lengthInMsg) != 1) { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } else { (*bodyLength) = (size_t)lengthInMsg; } } else if (InternStrnicmp(buf, TransferEncoding, TransferEncodingSize) == 0) { substr = buf + TransferEncodingSize; while (isspace(*substr)) substr++; if (InternStrnicmp(substr, Chunked, ChunkedSize) == 0) { (*chunked) = true; } } if (result == HTTPAPI_OK) { whereIsColon = strchr((char*)buf, ':'); /*Codes_SRS_HTTPAPI_COMPACT_21_049: [ If responseHeadersHandle is provide, the HTTPAPI_ExecuteRequest shall prepare a Response Header usign the HTTPHeaders_AddHeaderNameValuePair. ]*/ if (whereIsColon && (responseHeadersHandle != NULL)) { *whereIsColon = '\0'; HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, buf, whereIsColon + 1); } if (readLine(http_instance, buf, sizeof(buf)) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } } } } return result; } static HTTPAPI_RESULT ReadHTTPResponseBodyFromXIO(HTTP_HANDLE_DATA* http_instance, size_t bodyLength, bool chunked, BUFFER_HANDLE responseContent) { HTTPAPI_RESULT result; char buf[TEMP_BUFFER_SIZE]; const unsigned char* receivedContent; http_instance->is_io_error = 0; //Read HTTP response body if (!chunked) { if (bodyLength) { if (responseContent != NULL) { if (BUFFER_pre_build(responseContent, bodyLength) != 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_052: [ If any memory allocation get fail, the HTTPAPI_ExecuteRequest shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else if (BUFFER_content(responseContent, &receivedContent) != 0) { (void)BUFFER_unbuild(responseContent); /*Codes_SRS_HTTPAPI_COMPACT_21_052: [ If any memory allocation get fail, the HTTPAPI_ExecuteRequest shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else if (readChunk(http_instance, (char*)receivedContent, bodyLength) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; } } else { /*Codes_SRS_HTTPAPI_COMPACT_21_051: [ If the responseContent is NULL, the HTTPAPI_ExecuteRequest shall ignore any content in the response. ]*/ if (skipN(http_instance, bodyLength) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } else { result = HTTPAPI_OK; } } } else { /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; } } else { size_t size = 0; /*Codes_SRS_HTTPAPI_COMPACT_21_033: [ If the whole process succeed, the HTTPAPI_ExecuteRequest shall retur HTTPAPI_OK. ]*/ result = HTTPAPI_OK; while (result == HTTPAPI_OK) { size_t chunkSize; if (readLine(http_instance, buf, sizeof(buf)) < 0) // read [length in hex]/r/n { /*Codes_SRS_HTTPAPI_COMPACT_21_032: [ If the HTTPAPI_ExecuteRequest cannot read the message with the request result, it shall return HTTPAPI_READ_DATA_FAILED. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } else if (ParseStringToHexadecimal(buf, &chunkSize) != 1) // chunkSize is length of next line (/r/n is not counted) { //Cannot match string, error /*Codes_SRS_HTTPAPI_COMPACT_21_055: [ If the HTTPAPI_ExecuteRequest cannot parser the received message, it shall return HTTPAPI_RECEIVE_RESPONSE_FAILED. ]*/ result = HTTPAPI_RECEIVE_RESPONSE_FAILED; } else if (chunkSize == 0) { // 0 length means next line is just '\r\n' and end of chunks if (readChunk(http_instance, (char*)buf, (size_t)2) < 0 || buf[0] != '\r' || buf[1] != '\n') // skip /r/n { (void)BUFFER_unbuild(responseContent); result = HTTPAPI_READ_DATA_FAILED; } break; } else { if (responseContent != NULL) { if (BUFFER_enlarge(responseContent, chunkSize) != 0) { (void)BUFFER_unbuild(responseContent); /*Codes_SRS_HTTPAPI_COMPACT_21_052: [ If any memory allocation get fail, the HTTPAPI_ExecuteRequest shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else if (BUFFER_content(responseContent, &receivedContent) != 0) { (void)BUFFER_unbuild(responseContent); /*Codes_SRS_HTTPAPI_COMPACT_21_052: [ If any memory allocation get fail, the HTTPAPI_ExecuteRequest shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else if (readChunk(http_instance, (char*)receivedContent + size, chunkSize) < 0) { result = HTTPAPI_READ_DATA_FAILED; } } else { /*Codes_SRS_HTTPAPI_COMPACT_21_051: [ If the responseContent is NULL, the HTTPAPI_ExecuteRequest shall ignore any content in the response. ]*/ if (skipN(http_instance, chunkSize) < 0) { /*Codes_SRS_HTTPAPI_COMPACT_21_082: [ If the HTTPAPI_ExecuteRequest retries 20 seconds to receive the message without success, it shall fail and return HTTPAPI_READ_DATA_FAILED. ]*/ result = HTTPAPI_READ_DATA_FAILED; } } if (result == HTTPAPI_OK) { if (readChunk(http_instance, (char*)buf, (size_t)2) < 0 || buf[0] != '\r' || buf[1] != '\n') // skip /r/n { result = HTTPAPI_READ_DATA_FAILED; } size += chunkSize; } } } } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_037: [ If the request type is unknown, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ static bool validRequestType(HTTPAPI_REQUEST_TYPE requestType) { bool result; if ((requestType == HTTPAPI_REQUEST_GET) || (requestType == HTTPAPI_REQUEST_POST) || (requestType == HTTPAPI_REQUEST_PUT) || (requestType == HTTPAPI_REQUEST_DELETE) || (requestType == HTTPAPI_REQUEST_PATCH) || (requestType == HTTPAPI_REQUEST_HEAD)) { result = true; } else { result = false; } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_021: [ The HTTPAPI_ExecuteRequest shall execute the http communtication with the provided host, sending a request and reciving the response. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_050: [ If there is a content in the response, the HTTPAPI_ExecuteRequest shall copy it in the responseContent buffer. ]*/ //Note: This function assumes that "Host:" and "Content-Length:" headers are setup // by the caller of HTTPAPI_ExecuteRequest() (which is true for httptransport.c). HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, HTTPAPI_REQUEST_TYPE requestType, const char* relativePath, HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content, size_t contentLength, unsigned int* statusCode, HTTP_HEADERS_HANDLE responseHeadersHandle, BUFFER_HANDLE responseContent) { HTTPAPI_RESULT result = HTTPAPI_ERROR; size_t headersCount; size_t bodyLength = 0; bool chunked = false; HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)handle; /*Codes_SRS_HTTPAPI_COMPACT_21_034: [ If there is no previous connection, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_037: [ If the request type is unknown, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_039: [ If the relativePath is NULL or invalid, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_041: [ If the httpHeadersHandle is NULL or invalid, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_053: [ The HTTPAPI_ExecuteRequest shall produce a set of http header to send to the host. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_040: [ The request shall contain the http header provided in httpHeadersHandle parameter. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_054: [ If Http header maker cannot provide the number of headers, the HTTPAPI_ExecuteRequest shall return HTTPAPI_INVALID_ARG. ]*/ if (http_instance == NULL || relativePath == NULL || httpHeadersHandle == NULL || !validRequestType(requestType) || HTTPHeaders_GetHeaderCount(httpHeadersHandle, &headersCount) != HTTP_HEADERS_OK) { result = HTTPAPI_INVALID_ARG; LogError("(result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_21_024: [ The HTTPAPI_ExecuteRequest shall open the transport connection with the host to send the request. ]*/ else if ((result = OpenXIOConnection(http_instance)) != HTTPAPI_OK) { LogError("Open HTTP connection failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_21_026: [ If the open process succeed, the HTTPAPI_ExecuteRequest shall send the request message to the host. ]*/ else if ((result = SendHeadsToXIO(http_instance, requestType, relativePath, httpHeadersHandle, headersCount)) != HTTPAPI_OK) { LogError("Send heads to HTTP failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_21_042: [ The request can contain the a content message, provided in content parameter. ]*/ else if ((result = SendContentToXIO(http_instance, content, contentLength)) != HTTPAPI_OK) { LogError("Send content to HTTP failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_21_030: [ At the end of the transmission, the HTTPAPI_ExecuteRequest shall receive the response from the host. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_073: [ The message received by the HTTPAPI_ExecuteRequest shall starts with a valid header. ]*/ else if ((result = ReceiveHeaderFromXIO(http_instance, statusCode)) != HTTPAPI_OK) { LogError("Receive header from HTTP failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_21_074: [ After the header, the message received by the HTTPAPI_ExecuteRequest can contain addition information about the content. ]*/ else if ((result = ReceiveContentInfoFromXIO(http_instance, responseHeadersHandle, &bodyLength, &chunked)) != HTTPAPI_OK) { LogError("Receive content information from HTTP failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } /*Codes_SRS_HTTPAPI_COMPACT_42_084: [ The message received by the HTTPAPI_ExecuteRequest should not contain http body. ]*/ else if (requestType != HTTPAPI_REQUEST_HEAD) { /*Codes_SRS_HTTPAPI_COMPACT_21_075: [ The message received by the HTTPAPI_ExecuteRequest can contain a body with the message content. ]*/ if ((result = ReadHTTPResponseBodyFromXIO(http_instance, bodyLength, chunked, responseContent)) != HTTPAPI_OK) { LogError("Read HTTP response body from HTTP failed (result = %s)", MU_ENUM_TO_STRING(HTTPAPI_RESULT, result)); } } conn_receive_discard_buffer(http_instance); return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_056: [ The HTTPAPI_SetOption shall change the HTTP options. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_057: [ The HTTPAPI_SetOption shall receive a handle that identiry the HTTP connection. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_058: [ The HTTPAPI_SetOption shall receive the option as a pair optionName/value. ]*/ HTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName, const void* value) { HTTPAPI_RESULT result; HTTP_HANDLE_DATA* http_instance = (HTTP_HANDLE_DATA*)handle; if ( (http_instance == NULL) || (optionName == NULL) || (value == NULL) ) { /*Codes_SRS_HTTPAPI_COMPACT_21_059: [ If the handle is NULL, the HTTPAPI_SetOption shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_060: [ If the optionName is NULL, the HTTPAPI_SetOption shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_061: [ If the value is NULL, the HTTPAPI_SetOption shall return HTTPAPI_INVALID_ARG. ]*/ result = HTTPAPI_INVALID_ARG; } else if (strcmp(OPTION_TRUSTED_CERT, optionName) == 0) { #ifdef DO_NOT_COPY_TRUSTED_CERTS_STRING result = HTTPAPI_OK; http_instance->certificate = (char*)value; #else int len; if (http_instance->certificate) { free(http_instance->certificate); } len = (int)strlen((char*)value); http_instance->certificate = (char*)malloc((len + 1) * sizeof(char)); if (http_instance->certificate == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; LogInfo("unable to allocate memory for the certificate in HTTPAPI_SetOption"); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_064: [ If the HTTPAPI_SetOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(http_instance->certificate, (const char*)value); result = HTTPAPI_OK; } #endif // DO_NOT_COPY_TRUSTED_CERTS_STRING } else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0) { int len; if (http_instance->x509ClientCertificate) { free(http_instance->x509ClientCertificate); } len = (int)strlen((char*)value); http_instance->x509ClientCertificate = (char*)malloc((len + 1) * sizeof(char)); if (http_instance->x509ClientCertificate == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; LogInfo("unable to allocate memory for the client certificate in HTTPAPI_SetOption"); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_064: [ If the HTTPAPI_SetOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(http_instance->x509ClientCertificate, (const char*)value); result = HTTPAPI_OK; } } else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0) { int len; if (http_instance->x509ClientPrivateKey) { free(http_instance->x509ClientPrivateKey); } len = (int)strlen((char*)value); http_instance->x509ClientPrivateKey = (char*)malloc((len + 1) * sizeof(char)); if (http_instance->x509ClientPrivateKey == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; LogInfo("unable to allocate memory for the client private key in HTTPAPI_SetOption"); } else { /*Codes_SRS_HTTPAPI_COMPACT_21_064: [ If the HTTPAPI_SetOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(http_instance->x509ClientPrivateKey, (const char*)value); result = HTTPAPI_OK; } } else if (strcmp(OPTION_HTTP_PROXY, optionName) == 0) { HTTP_PROXY_OPTIONS* proxy_data = (HTTP_PROXY_OPTIONS*)value; if (proxy_data->host_address == NULL || proxy_data->port <= 0) { LogError("invalid proxy_data values ( host_address = %p, port = %d)", proxy_data->host_address, proxy_data->port); result = HTTPAPI_ERROR; } else { if(http_instance->proxy_host != NULL) { free((void*)http_instance->proxy_host); http_instance->proxy_host = NULL; } if(mallocAndStrcpy_s((char**)&(http_instance->proxy_host), (const char*)proxy_data->host_address) != 0) { LogError("failure allocate proxy host"); result = HTTPAPI_ERROR; } else { http_instance->proxy_port = proxy_data->port; if (proxy_data->username != NULL && proxy_data->password != NULL) { if(http_instance->proxy_username != NULL) { free((void*)http_instance->proxy_username); http_instance->proxy_username = NULL; } if(mallocAndStrcpy_s((char**)&(http_instance->proxy_username), (const char*)proxy_data->username) != 0) { LogError("failure allocate proxy username"); free((void*)http_instance->proxy_host); http_instance->proxy_host = NULL; result = HTTPAPI_ERROR; } else { if(http_instance->proxy_password != NULL) { free((void*)http_instance->proxy_password); http_instance->proxy_password = NULL; } if(mallocAndStrcpy_s((char**)&(http_instance->proxy_password), (const char*)proxy_data->password) != 0) { LogError("failure allocate proxy password"); free((void*)http_instance->proxy_host); http_instance->proxy_host = NULL; free((void*)http_instance->proxy_username); http_instance->proxy_username = NULL; result = HTTPAPI_ERROR; } else { result = HTTPAPI_OK; } } } else { result = HTTPAPI_OK; } } } } else { /*Codes_SRS_HTTPAPI_COMPACT_21_063: [ If the HTTP do not support the optionName, the HTTPAPI_SetOption shall return HTTPAPI_INVALID_ARG. ]*/ result = HTTPAPI_INVALID_ARG; LogInfo("unknown option %s", optionName); } return result; } /*Codes_SRS_HTTPAPI_COMPACT_21_065: [ The HTTPAPI_CloneOption shall provide the means to clone the HTTP option. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_066: [ The HTTPAPI_CloneOption shall return a clone of the value identified by the optionName. ]*/ HTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value, const void** savedValue) { HTTPAPI_RESULT result; size_t certLen; char* tempCert; if ( (optionName == NULL) || (value == NULL) || (savedValue == NULL) ) { /*Codes_SRS_HTTPAPI_COMPACT_21_067: [ If the optionName is NULL, the HTTPAPI_CloneOption shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_068: [ If the value is NULL, the HTTPAPI_CloneOption shall return HTTPAPI_INVALID_ARG. ]*/ /*Codes_SRS_HTTPAPI_COMPACT_21_069: [ If the savedValue is NULL, the HTTPAPI_CloneOption shall return HTTPAPI_INVALID_ARG. ]*/ result = HTTPAPI_INVALID_ARG; } else if (strcmp(OPTION_TRUSTED_CERT, optionName) == 0) { #ifdef DO_NOT_COPY_TRUSTED_CERTS_STRING *savedValue = (const void*)value; result = HTTPAPI_OK; #else certLen = strlen((const char*)value); tempCert = (char*)malloc((certLen + 1) * sizeof(char)); if (tempCert == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_072: [ If the HTTPAPI_CloneOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(tempCert, (const char*)value); *savedValue = tempCert; result = HTTPAPI_OK; } #endif // DO_NOT_COPY_TRUSTED_CERTS_STRING } else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0) { certLen = strlen((const char*)value); tempCert = (char*)malloc((certLen + 1) * sizeof(char)); if (tempCert == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_072: [ If the HTTPAPI_CloneOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(tempCert, (const char*)value); *savedValue = tempCert; result = HTTPAPI_OK; } } else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0) { certLen = strlen((const char*)value); tempCert = (char*)malloc((certLen + 1) * sizeof(char)); if (tempCert == NULL) { /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/ result = HTTPAPI_ALLOC_FAILED; } else { /*Codes_SRS_HTTPAPI_COMPACT_21_072: [ If the HTTPAPI_CloneOption get success setting the option, it shall return HTTPAPI_OK. ]*/ (void)strcpy(tempCert, (const char*)value); *savedValue = tempCert; result = HTTPAPI_OK; } } else if (strcmp(OPTION_HTTP_PROXY, optionName) == 0) { HTTP_PROXY_OPTIONS* proxy_data = (HTTP_PROXY_OPTIONS*)value; HTTP_PROXY_OPTIONS* new_proxy_info = malloc(sizeof(HTTP_PROXY_OPTIONS)); if (new_proxy_info == NULL) { LogError("unable to allocate proxy option information"); result = HTTPAPI_ERROR; } else { new_proxy_info->host_address = proxy_data->host_address; new_proxy_info->port = proxy_data->port; new_proxy_info->password = proxy_data->password; new_proxy_info->username = proxy_data->username; *savedValue = new_proxy_info; result = HTTPAPI_OK; } } else { /*Codes_SRS_HTTPAPI_COMPACT_21_071: [ If the HTTP do not support the optionName, the HTTPAPI_CloneOption shall return HTTPAPI_INVALID_ARG. ]*/ result = HTTPAPI_INVALID_ARG; LogInfo("unknown option %s", optionName); } return result; }
171980.c
/** * reader.c * * ADIOS is freely available under the terms of the BSD license described * in the COPYING file in the top level directory of this source distribution. * * Copyright (c) 2008 - 2009. UT-BATTELLE, LLC. All rights reserved. * * Created on: Jul 1, 2013 * Author: Magda Slawinska aka Magic Magg magg dot gatech at gmail.com * * The process reads an integer scalar. It should be equal to its rank. * Excessive processes (if rank > the number of writers) quit. It is recommended, * however, to run as many readers as writers. */ #include "mpi.h" #include "adios.h" #include "adios_read.h" #include "misc.h" #include "utils.h" #include "test_common.h" #include "cfg.h" #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> int main (int argc, char **argv){ int rank =0, size =0; int my_scalar = -1; // this will hold what I got from the writer MPI_Comm comm = MPI_COMM_WORLD; diag_t diag = DIAG_OK; // to store the diagnostic information struct test_info test_result = { TEST_PASSED, "scalar" }; struct err_counts err = { 0, 0}; struct adios_tsprt_opts adios_opts; GET_ENTRY_OPTIONS(adios_opts, "Runs readers. It is recommended to run as many readers as writers."); // adios read initialization MPI_Init( &argc, &argv); MPI_Comm_rank (comm, &rank); // choose the right method depending on the method SET_ERROR_IF_NOT_ZERO(adios_read_init_method(adios_opts.method, comm, adios_opts.adios_options), err.adios); RET_IF_ERROR(err.adios, rank); // I will be working with streams so the lock mode is necessary, // return immediately if the stream unavailable ADIOS_FILE *adios_handle = adios_read_open(FILE_NAME, adios_opts.method, comm, ADIOS_LOCKMODE_NONE, 0.0); if ( !adios_handle){ p_error("Quitting ... (%d) %s\n", adios_errno, adios_errmsg()); return DIAG_ERR; } // define portions of data how they will be read ADIOS_SELECTION *sel = NULL; ADIOS_VARINFO *avi = NULL; // read how many processors wrote that array avi = adios_inq_var (adios_handle, "size"); if (!avi){ p_error("rank %d: Quitting ... (%d) %s\n", rank, adios_errno, adios_errmsg()); diag = DIAG_ERR; goto close_adios; } size = *((int*)avi->value); adios_free_varinfo(avi); avi = NULL; // if I run more readers than writers; just release // the excessive readers if (rank >= size){ p_info("rank %d: I am an excessive rank. Nothing to read ...\n", rank); // diag should be DIAG_OK goto close_adios; } // this is the index of the written block sel = adios_selection_writeblock(rank); if( !sel ){ p_error("rank %d: Quitting ... (%d) %s\n", rank, adios_errno, adios_errmsg()); diag = DIAG_ERR; goto close_adios; } // TODO as of 2013-07-08, I was told that err_end_of_stream doesn't work // as it supposed to work //while(adios_errno != err_end_of_stream){ if (adios_schedule_read(adios_handle, sel, "lucky_scalar",0,1,&my_scalar) != 0){ p_error("rank %d: Quitting ...(%d) %s\n", rank, adios_errno, adios_errmsg()); adios_selection_delete(sel); sel = NULL; CLOSE_ADIOS_READER(adios_handle, adios_opts.method); return DIAG_ERR; } // not sure if this assumption is correct; difficult to find in the ADIOS sources if (adios_perform_reads(adios_handle, 1) != 0){ p_error("rank %d: Quitting ...(%d) %s\n", rank, adios_errno, adios_errmsg()); adios_selection_delete(sel); sel = NULL; CLOSE_ADIOS_READER(adios_handle, adios_opts.method); return DIAG_ERR; } if( rank == my_scalar){ p_test_passed("%s: rank %d\n", test_result.name, rank); test_result.result = TEST_PASSED; } else { p_test_failed("%s: rank %d: my_scalar=%d. (rank != my_scalar)\n", test_result.name, rank, my_scalar); test_result.result = TEST_FAILED; } //} // clean everything adios_selection_delete(sel); sel = NULL; close_adios: CLOSE_ADIOS_READER(adios_handle, adios_opts.method); return diag; }
457513.c
/**************************************************************************** * * ftsynth.c * * FreeType synthesizing code for emboldening and slanting (body). * * Copyright (C) 2000-2020 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <ft2build.h> #include FT_SYNTHESIS_H #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_OBJECTS_H #include FT_OUTLINE_H #include FT_BITMAP_H /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT synth /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** EXPERIMENTAL OBLIQUING SUPPORT ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /* documentation is in ftsynth.h */ FT_EXPORT_DEF( void ) FT_GlyphSlot_Oblique( FT_GlyphSlot slot ) { FT_Matrix transform; FT_Outline* outline; if ( !slot ) return; outline = &slot->outline; /* only oblique outline glyphs */ if ( slot->format != FT_GLYPH_FORMAT_OUTLINE ) return; /* we don't touch the advance width */ /* For italic, simply apply a shear transform, with an angle */ /* of about 12 degrees. */ transform.xx = 0x10000L; transform.yx = 0x00000L; transform.xy = 0x0366AL; transform.yy = 0x10000L; FT_Outline_Transform( outline, &transform ); } /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** EXPERIMENTAL EMBOLDENING SUPPORT ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /* documentation is in ftsynth.h */ FT_EXPORT_DEF( void ) FT_GlyphSlot_Embolden( FT_GlyphSlot slot ) { FT_Library library; FT_Face face; FT_Error error; FT_Pos xstr, ystr; if ( !slot ) return; library = slot->library; face = slot->face; if ( slot->format != FT_GLYPH_FORMAT_OUTLINE && slot->format != FT_GLYPH_FORMAT_BITMAP ) return; /* some reasonable strength */ xstr = FT_MulFix( face->units_per_EM, face->size->metrics.y_scale ) / 24; ystr = xstr; if ( slot->format == FT_GLYPH_FORMAT_OUTLINE ) FT_Outline_EmboldenXY( &slot->outline, xstr, ystr ); else /* slot->format == FT_GLYPH_FORMAT_BITMAP */ { /* round to full pixels */ xstr &= ~63; if ( xstr == 0 ) xstr = 1 << 6; ystr &= ~63; /* * XXX: overflow check for 16-bit system, for compatibility * with FT_GlyphSlot_Embolden() since FreeType 2.1.10. * unfortunately, this function return no informations * about the cause of error. */ if ( ( ystr >> 6 ) > FT_INT_MAX || ( ystr >> 6 ) < FT_INT_MIN ) { FT_TRACE1(( "FT_GlyphSlot_Embolden:" )); FT_TRACE1(( "too strong emboldening parameter ystr=%d\n", ystr )); return; } error = FT_GlyphSlot_Own_Bitmap( slot ); if ( error ) return; error = FT_Bitmap_Embolden( library, &slot->bitmap, xstr, ystr ); if ( error ) return; } if ( slot->advance.x ) slot->advance.x += xstr; if ( slot->advance.y ) slot->advance.y += ystr; slot->metrics.width += xstr; slot->metrics.height += ystr; slot->metrics.horiAdvance += xstr; slot->metrics.vertAdvance += ystr; slot->metrics.horiBearingY += ystr; /* XXX: 16-bit overflow case must be excluded before here */ if ( slot->format == FT_GLYPH_FORMAT_BITMAP ) slot->bitmap_top += (FT_Int)( ystr >> 6 ); } /* END */
358218.c
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2013 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007-2014 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2018 Amazon.com, Inc. or its affiliates. All Rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ /* * Buffer safe printf functions for portability to archaic platforms. */ #include "opal_config.h" #include "opal/util/output.h" #include "opal/util/printf.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef HAVE_VASPRINTF /* * Make a good guess about how long a printf-style varargs formatted * string will be once all the % escapes are filled in. We don't * handle every % escape here, but we handle enough, and then add a * fudge factor in at the end. */ static int guess_strlen(const char *fmt, va_list ap) { # if HAVE_VSNPRINTF char dummy[1]; /* vsnprintf() returns the number of bytes that would have been copied if the provided buffer were infinite. */ return 1 + vsnprintf(dummy, sizeof(dummy), fmt, ap); # else char *sarg, carg; double darg; float farg; size_t i; int iarg; int len; long larg; /* Start off with a fudge factor of 128 to handle the % escapes that we aren't calculating here */ len = (int) strlen(fmt) + 128; for (i = 0; i < strlen(fmt); ++i) { if ('%' == fmt[i] && i + 1 < strlen(fmt) && '%' != fmt[i + 1]) { ++i; switch (fmt[i]) { case 'c': carg = va_arg(ap, int); len += 1; /* let's suppose it's a printable char */ (void) carg; /* prevent compiler from complaining about set but not used variables */ break; case 's': sarg = va_arg(ap, char *); /* If there's an arg, get the strlen, otherwise we'll * use (null) */ if (NULL != sarg) { len += (int) strlen(sarg); } else { # if OPAL_ENABLE_DEBUG opal_output(0, "OPAL DEBUG WARNING: Got a NULL argument to opal_vasprintf!\n"); # endif len += 5; } break; case 'd': case 'i': iarg = va_arg(ap, int); /* Alloc for minus sign */ if (iarg < 0) ++len; /* Now get the log10 */ do { ++len; iarg /= 10; } while (0 != iarg); break; case 'x': case 'X': iarg = va_arg(ap, int); /* Now get the log16 */ do { ++len; iarg /= 16; } while (0 != iarg); break; case 'f': farg = (float) va_arg(ap, int); /* Alloc for minus sign */ if (farg < 0) { ++len; farg = -farg; } /* Alloc for 3 decimal places + '.' */ len += 4; /* Now get the log10 */ do { ++len; farg /= 10.0; } while (0 != farg); break; case 'g': darg = va_arg(ap, int); /* Alloc for minus sign */ if (darg < 0) { ++len; darg = -darg; } /* Alloc for 3 decimal places + '.' */ len += 4; /* Now get the log10 */ do { ++len; darg /= 10.0; } while (0 != darg); break; case 'l': /* Get %ld %lx %lX %lf */ if (i + 1 < strlen(fmt)) { ++i; switch (fmt[i]) { case 'x': case 'X': larg = va_arg(ap, int); /* Now get the log16 */ do { ++len; larg /= 16; } while (0 != larg); break; case 'f': darg = va_arg(ap, int); /* Alloc for minus sign */ if (darg < 0) { ++len; darg = -darg; } /* Alloc for 3 decimal places + '.' */ len += 4; /* Now get the log10 */ do { ++len; darg /= 10.0; } while (0 != darg); break; case 'd': default: larg = va_arg(ap, int); /* Now get the log10 */ do { ++len; larg /= 10; } while (0 != larg); break; } } default: break; } } } return len; # endif } #endif /* #ifndef HAVE_VASPRINTF */ int opal_asprintf(char **ptr, const char *fmt, ...) { int length; va_list ap; va_start(ap, fmt); /* opal_vasprintf guarantees that *ptr is set to NULL on error */ length = opal_vasprintf(ptr, fmt, ap); va_end(ap); return length; } int opal_vasprintf(char **ptr, const char *fmt, va_list ap) { #ifdef HAVE_VASPRINTF int length; length = vasprintf(ptr, fmt, ap); if (length < 0) { *ptr = NULL; } return length; #else int length; va_list ap2; /* va_list might have pointer to internal state and using it twice is a bad idea. So make a copy for the second use. Copy order taken from Autoconf docs. */ # if OPAL_HAVE_VA_COPY va_copy(ap2, ap); # elif OPAL_HAVE_UNDERSCORE_VA_COPY __va_copy(ap2, ap); # else memcpy(&ap2, &ap, sizeof(va_list)); # endif /* guess the size */ length = guess_strlen(fmt, ap); /* allocate a buffer */ *ptr = (char *) malloc((size_t) length + 1); if (NULL == *ptr) { errno = ENOMEM; va_end(ap2); return -1; } /* fill the buffer */ length = vsprintf(*ptr, fmt, ap2); # if OPAL_HAVE_VA_COPY || OPAL_HAVE_UNDERSCORE_VA_COPY va_end(ap2); # endif /* OPAL_HAVE_VA_COPY || OPAL_HAVE_UNDERSCORE_VA_COPY */ /* realloc */ *ptr = (char *) realloc(*ptr, (size_t) length + 1); if (NULL == *ptr) { errno = ENOMEM; return -1; } return length; #endif } int opal_snprintf(char *str, size_t size, const char *fmt, ...) { int length; va_list ap; va_start(ap, fmt); length = opal_vsnprintf(str, size, fmt, ap); va_end(ap); return length; } int opal_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) { int length; char *buf; length = opal_vasprintf(&buf, fmt, ap); if (length < 0) { return length; } /* return the length when given a null buffer (C99) */ if (str) { if ((size_t) length < size) { strcpy(str, buf); } else { memcpy(str, buf, size - 1); str[size] = '\0'; } } /* free allocated buffer */ free(buf); return length; } #ifdef TEST int main(int argc, char *argv[]) { char a[10]; char b[173]; char *s; int length; puts("test for NULL buffer in snprintf:"); length = opal_snprintf(NULL, 0, "this is a string %d", 1004); printf("length = %d\n", length); puts("test of snprintf to an undersize buffer:"); length = opal_snprintf(a, sizeof(a), "this is a string %d", 1004); printf("string = %s\n", a); printf("length = %d\n", length); printf("strlen = %d\n", (int) strlen(a)); puts("test of snprintf to an oversize buffer:"); length = opal_snprintf(b, sizeof(b), "this is a string %d", 1004); printf("string = %s\n", b); printf("length = %d\n", length); printf("strlen = %d\n", (int) strlen(b)); puts("test of asprintf:"); length = opal_asprintf(&s, "this is a string %d", 1004); printf("string = %s\n", s); printf("length = %d\n", length); printf("strlen = %d\n", (int) strlen(s)); free(s); return 0; } #endif
617741.c
// SPDX-License-Identifier: GPL-2.0 /* * lib/locking-selftest.c * * Testsuite for various locking APIs: spinlocks, rwlocks, * mutexes and rw-semaphores. * * It is checking both false positives and false negatives. * * Started by Ingo Molnar: * * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <[email protected]> */ #include <linux/rwsem.h> #include <linux/mutex.h> #include <linux/ww_mutex.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/lockdep.h> #include <linux/spinlock.h> #include <linux/kallsyms.h> #include <linux/interrupt.h> #include <linux/debug_locks.h> #include <linux/irqflags.h> #include <linux/rtmutex.h> /* * Change this to 1 if you want to see the failure printouts: */ static unsigned int debug_locks_verbose; static DEFINE_WD_CLASS(ww_lockdep); static int __init setup_debug_locks_verbose(char *str) { get_option(&str, &debug_locks_verbose); return 1; } __setup("debug_locks_verbose=", setup_debug_locks_verbose); #define FAILURE 0 #define SUCCESS 1 #define LOCKTYPE_SPIN 0x1 #define LOCKTYPE_RWLOCK 0x2 #define LOCKTYPE_MUTEX 0x4 #define LOCKTYPE_RWSEM 0x8 #define LOCKTYPE_WW 0x10 #define LOCKTYPE_RTMUTEX 0x20 static struct ww_acquire_ctx t, t2; static struct ww_mutex o, o2, o3; /* * Normal standalone locks, for the circular and irq-context * dependency tests: */ static DEFINE_RAW_SPINLOCK(lock_A); static DEFINE_RAW_SPINLOCK(lock_B); static DEFINE_RAW_SPINLOCK(lock_C); static DEFINE_RAW_SPINLOCK(lock_D); static DEFINE_RWLOCK(rwlock_A); static DEFINE_RWLOCK(rwlock_B); static DEFINE_RWLOCK(rwlock_C); static DEFINE_RWLOCK(rwlock_D); static DEFINE_MUTEX(mutex_A); static DEFINE_MUTEX(mutex_B); static DEFINE_MUTEX(mutex_C); static DEFINE_MUTEX(mutex_D); static DECLARE_RWSEM(rwsem_A); static DECLARE_RWSEM(rwsem_B); static DECLARE_RWSEM(rwsem_C); static DECLARE_RWSEM(rwsem_D); #ifdef CONFIG_RT_MUTEXES static DEFINE_RT_MUTEX(rtmutex_A); static DEFINE_RT_MUTEX(rtmutex_B); static DEFINE_RT_MUTEX(rtmutex_C); static DEFINE_RT_MUTEX(rtmutex_D); #endif /* * Locks that we initialize dynamically as well so that * e.g. X1 and X2 becomes two instances of the same class, * but X* and Y* are different classes. We do this so that * we do not trigger a real lockup: */ static DEFINE_RAW_SPINLOCK(lock_X1); static DEFINE_RAW_SPINLOCK(lock_X2); static DEFINE_RAW_SPINLOCK(lock_Y1); static DEFINE_RAW_SPINLOCK(lock_Y2); static DEFINE_RAW_SPINLOCK(lock_Z1); static DEFINE_RAW_SPINLOCK(lock_Z2); static DEFINE_RWLOCK(rwlock_X1); static DEFINE_RWLOCK(rwlock_X2); static DEFINE_RWLOCK(rwlock_Y1); static DEFINE_RWLOCK(rwlock_Y2); static DEFINE_RWLOCK(rwlock_Z1); static DEFINE_RWLOCK(rwlock_Z2); static DEFINE_MUTEX(mutex_X1); static DEFINE_MUTEX(mutex_X2); static DEFINE_MUTEX(mutex_Y1); static DEFINE_MUTEX(mutex_Y2); static DEFINE_MUTEX(mutex_Z1); static DEFINE_MUTEX(mutex_Z2); static DECLARE_RWSEM(rwsem_X1); static DECLARE_RWSEM(rwsem_X2); static DECLARE_RWSEM(rwsem_Y1); static DECLARE_RWSEM(rwsem_Y2); static DECLARE_RWSEM(rwsem_Z1); static DECLARE_RWSEM(rwsem_Z2); #ifdef CONFIG_RT_MUTEXES static DEFINE_RT_MUTEX(rtmutex_X1); static DEFINE_RT_MUTEX(rtmutex_X2); static DEFINE_RT_MUTEX(rtmutex_Y1); static DEFINE_RT_MUTEX(rtmutex_Y2); static DEFINE_RT_MUTEX(rtmutex_Z1); static DEFINE_RT_MUTEX(rtmutex_Z2); #endif /* * non-inlined runtime initializers, to let separate locks share * the same lock-class: */ #define INIT_CLASS_FUNC(class) \ static noinline void \ init_class_##class(raw_spinlock_t *lock, rwlock_t *rwlock, \ struct mutex *mutex, struct rw_semaphore *rwsem)\ { \ raw_spin_lock_init(lock); \ rwlock_init(rwlock); \ mutex_init(mutex); \ init_rwsem(rwsem); \ } INIT_CLASS_FUNC(X) INIT_CLASS_FUNC(Y) INIT_CLASS_FUNC(Z) static void init_shared_classes(void) { #ifdef CONFIG_RT_MUTEXES static struct lock_class_key rt_X, rt_Y, rt_Z; __rt_mutex_init(&rtmutex_X1, __func__, &rt_X); __rt_mutex_init(&rtmutex_X2, __func__, &rt_X); __rt_mutex_init(&rtmutex_Y1, __func__, &rt_Y); __rt_mutex_init(&rtmutex_Y2, __func__, &rt_Y); __rt_mutex_init(&rtmutex_Z1, __func__, &rt_Z); __rt_mutex_init(&rtmutex_Z2, __func__, &rt_Z); #endif init_class_X(&lock_X1, &rwlock_X1, &mutex_X1, &rwsem_X1); init_class_X(&lock_X2, &rwlock_X2, &mutex_X2, &rwsem_X2); init_class_Y(&lock_Y1, &rwlock_Y1, &mutex_Y1, &rwsem_Y1); init_class_Y(&lock_Y2, &rwlock_Y2, &mutex_Y2, &rwsem_Y2); init_class_Z(&lock_Z1, &rwlock_Z1, &mutex_Z1, &rwsem_Z1); init_class_Z(&lock_Z2, &rwlock_Z2, &mutex_Z2, &rwsem_Z2); } /* * For spinlocks and rwlocks we also do hardirq-safe / softirq-safe tests. * The following functions use a lock from a simulated hardirq/softirq * context, causing the locks to be marked as hardirq-safe/softirq-safe: */ #define HARDIRQ_DISABLE local_irq_disable #define HARDIRQ_ENABLE local_irq_enable #define HARDIRQ_ENTER() \ local_irq_disable(); \ __irq_enter(); \ WARN_ON(!in_irq()); #define HARDIRQ_EXIT() \ __irq_exit(); \ local_irq_enable(); #define SOFTIRQ_DISABLE local_bh_disable #define SOFTIRQ_ENABLE local_bh_enable #define SOFTIRQ_ENTER() \ local_bh_disable(); \ local_irq_disable(); \ lockdep_softirq_enter(); \ WARN_ON(!in_softirq()); #define SOFTIRQ_EXIT() \ lockdep_softirq_exit(); \ local_irq_enable(); \ local_bh_enable(); /* * Shortcuts for lock/unlock API variants, to keep * the testcases compact: */ #define L(x) raw_spin_lock(&lock_##x) #define U(x) raw_spin_unlock(&lock_##x) #define LU(x) L(x); U(x) #define SI(x) raw_spin_lock_init(&lock_##x) #define WL(x) write_lock(&rwlock_##x) #define WU(x) write_unlock(&rwlock_##x) #define WLU(x) WL(x); WU(x) #define RL(x) read_lock(&rwlock_##x) #define RU(x) read_unlock(&rwlock_##x) #define RLU(x) RL(x); RU(x) #define RWI(x) rwlock_init(&rwlock_##x) #define ML(x) mutex_lock(&mutex_##x) #define MU(x) mutex_unlock(&mutex_##x) #define MI(x) mutex_init(&mutex_##x) #define RTL(x) rt_mutex_lock(&rtmutex_##x) #define RTU(x) rt_mutex_unlock(&rtmutex_##x) #define RTI(x) rt_mutex_init(&rtmutex_##x) #define WSL(x) down_write(&rwsem_##x) #define WSU(x) up_write(&rwsem_##x) #define RSL(x) down_read(&rwsem_##x) #define RSU(x) up_read(&rwsem_##x) #define RWSI(x) init_rwsem(&rwsem_##x) #ifndef CONFIG_DEBUG_WW_MUTEX_SLOWPATH #define WWAI(x) ww_acquire_init(x, &ww_lockdep) #else #define WWAI(x) do { ww_acquire_init(x, &ww_lockdep); (x)->deadlock_inject_countdown = ~0U; } while (0) #endif #define WWAD(x) ww_acquire_done(x) #define WWAF(x) ww_acquire_fini(x) #define WWL(x, c) ww_mutex_lock(x, c) #define WWT(x) ww_mutex_trylock(x) #define WWL1(x) ww_mutex_lock(x, NULL) #define WWU(x) ww_mutex_unlock(x) #define LOCK_UNLOCK_2(x,y) LOCK(x); LOCK(y); UNLOCK(y); UNLOCK(x) /* * Generate different permutations of the same testcase, using * the same basic lock-dependency/state events: */ #define GENERATE_TESTCASE(name) \ \ static void name(void) { E(); } #define GENERATE_PERMUTATIONS_2_EVENTS(name) \ \ static void name##_12(void) { E1(); E2(); } \ static void name##_21(void) { E2(); E1(); } #define GENERATE_PERMUTATIONS_3_EVENTS(name) \ \ static void name##_123(void) { E1(); E2(); E3(); } \ static void name##_132(void) { E1(); E3(); E2(); } \ static void name##_213(void) { E2(); E1(); E3(); } \ static void name##_231(void) { E2(); E3(); E1(); } \ static void name##_312(void) { E3(); E1(); E2(); } \ static void name##_321(void) { E3(); E2(); E1(); } /* * AA deadlock: */ #define E() \ \ LOCK(X1); \ LOCK(X2); /* this one should fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(AA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(AA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(AA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(AA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(AA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(AA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(AA_rtmutex); #endif #undef E /* * Special-case for read-locking, they are * allowed to recurse on the same lock class: */ static void rlock_AA1(void) { RL(X1); RL(X1); // this one should NOT fail } static void rlock_AA1B(void) { RL(X1); RL(X2); // this one should NOT fail } static void rsem_AA1(void) { RSL(X1); RSL(X1); // this one should fail } static void rsem_AA1B(void) { RSL(X1); RSL(X2); // this one should fail } /* * The mixing of read and write locks is not allowed: */ static void rlock_AA2(void) { RL(X1); WL(X2); // this one should fail } static void rsem_AA2(void) { RSL(X1); WSL(X2); // this one should fail } static void rlock_AA3(void) { WL(X1); RL(X2); // this one should fail } static void rsem_AA3(void) { WSL(X1); RSL(X2); // this one should fail } /* * read_lock(A) * spin_lock(B) * spin_lock(B) * write_lock(A) */ static void rlock_ABBA1(void) { RL(X1); L(Y1); U(Y1); RU(X1); L(Y1); WL(X1); WU(X1); U(Y1); // should fail } static void rwsem_ABBA1(void) { RSL(X1); ML(Y1); MU(Y1); RSU(X1); ML(Y1); WSL(X1); WSU(X1); MU(Y1); // should fail } /* * read_lock(A) * spin_lock(B) * spin_lock(B) * read_lock(A) */ static void rlock_ABBA2(void) { RL(X1); L(Y1); U(Y1); RU(X1); L(Y1); RL(X1); RU(X1); U(Y1); // should NOT fail } static void rwsem_ABBA2(void) { RSL(X1); ML(Y1); MU(Y1); RSU(X1); ML(Y1); RSL(X1); RSU(X1); MU(Y1); // should fail } /* * write_lock(A) * spin_lock(B) * spin_lock(B) * write_lock(A) */ static void rlock_ABBA3(void) { WL(X1); L(Y1); U(Y1); WU(X1); L(Y1); WL(X1); WU(X1); U(Y1); // should fail } static void rwsem_ABBA3(void) { WSL(X1); ML(Y1); MU(Y1); WSU(X1); ML(Y1); WSL(X1); WSU(X1); MU(Y1); // should fail } /* * ABBA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBA_rtmutex); #endif #undef E /* * AB BC CA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(C, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBCCA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBCCA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBCCA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBCCA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBCCA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBCCA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBCCA_rtmutex); #endif #undef E /* * AB CA BC deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, A); \ LOCK_UNLOCK_2(B, C); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCABC_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCABC_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCABC_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCABC_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCABC_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCABC_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCABC_rtmutex); #endif #undef E /* * AB BC CD DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBCCDDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBCCDDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBCCDDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBCCDDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBCCDDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBCCDDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBCCDDA_rtmutex); #endif #undef E /* * AB CD BD DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(B, D); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCDBDDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCDBDDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCDBDDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCDBDDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCDBDDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCDBDDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCDBDDA_rtmutex); #endif #undef E /* * AB CD BC DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCDBCDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCDBCDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCDBCDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCDBCDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCDBCDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCDBCDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCDBCDA_rtmutex); #endif #undef E /* * Double unlock: */ #define E() \ \ LOCK(A); \ UNLOCK(A); \ UNLOCK(A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(double_unlock_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(double_unlock_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(double_unlock_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(double_unlock_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(double_unlock_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(double_unlock_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(double_unlock_rtmutex); #endif #undef E /* * initializing a held lock: */ #define E() \ \ LOCK(A); \ INIT(A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(init_held_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(init_held_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(init_held_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(init_held_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(init_held_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(init_held_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(init_held_rtmutex); #endif #undef E /* * locking an irq-safe lock with irqs enabled: */ #define E1() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); #define E2() \ \ LOCK(A); \ UNLOCK(A); /* * Generate 24 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_wlock) #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_wlock) #undef E1 #undef E2 /* * Enabling hardirqs with a softirq-safe lock held: */ #define E1() \ \ SOFTIRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ SOFTIRQ_EXIT(); #define E2() \ \ HARDIRQ_DISABLE(); \ LOCK(A); \ HARDIRQ_ENABLE(); \ UNLOCK(A); /* * Generate 12 testcases: */ #include "locking-selftest-spin.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_spin) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_wlock) #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_rlock) #undef E1 #undef E2 /* * Enabling irqs with an irq-safe lock held: */ #define E1() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); #define E2() \ \ IRQ_DISABLE(); \ LOCK(A); \ IRQ_ENABLE(); \ UNLOCK(A); /* * Generate 24 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_wlock) #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_wlock) #undef E1 #undef E2 /* * Acquiring a irq-unsafe lock while holding an irq-safe-lock: */ #define E1() \ \ LOCK(A); \ LOCK(B); \ UNLOCK(B); \ UNLOCK(A); \ #define E2() \ \ LOCK(B); \ UNLOCK(B); #define E3() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_wlock) #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_wlock) #undef E1 #undef E2 #undef E3 /* * If a lock turns into softirq-safe, but earlier it took * a softirq-unsafe lock: */ #define E1() \ IRQ_DISABLE(); \ LOCK(A); \ LOCK(B); \ UNLOCK(B); \ UNLOCK(A); \ IRQ_ENABLE(); #define E2() \ LOCK(B); \ UNLOCK(B); #define E3() \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_wlock) #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_wlock) #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock irq inversion. * * Deadlock scenario: * * CPU#1 is at #1, i.e. it has write-locked A, but has not * taken B yet. * * CPU#2 is at #2, i.e. it has locked B. * * Hardirq hits CPU#2 at point #2 and is trying to read-lock A. * * The deadlock occurs because CPU#1 will spin on B, and CPU#2 * will spin on A. */ #define E1() \ \ IRQ_DISABLE(); \ WL(A); \ LOCK(B); \ UNLOCK(B); \ WU(A); \ IRQ_ENABLE(); #define E2() \ \ LOCK(B); \ UNLOCK(B); #define E3() \ \ IRQ_ENTER(); \ RL(A); \ RU(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_wlock) #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_wlock) #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock recursion that is actually safe. */ #define E1() \ \ IRQ_DISABLE(); \ WL(A); \ WU(A); \ IRQ_ENABLE(); #define E2() \ \ RL(A); \ RU(A); \ #define E3() \ \ IRQ_ENTER(); \ RL(A); \ L(B); \ U(B); \ RU(A); \ IRQ_EXIT(); /* * Generate 12 testcases: */ #include "locking-selftest-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_hard) #include "locking-selftest-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_soft) #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock recursion that is unsafe. */ #define E1() \ \ IRQ_DISABLE(); \ L(B); \ WL(A); \ WU(A); \ U(B); \ IRQ_ENABLE(); #define E2() \ \ RL(A); \ RU(A); \ #define E3() \ \ IRQ_ENTER(); \ L(B); \ U(B); \ IRQ_EXIT(); /* * Generate 12 testcases: */ #include "locking-selftest-hardirq.h" // GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_hard) #include "locking-selftest-softirq.h" // GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_soft) #ifdef CONFIG_DEBUG_LOCK_ALLOC # define I_SPINLOCK(x) lockdep_reset_lock(&lock_##x.dep_map) # define I_RWLOCK(x) lockdep_reset_lock(&rwlock_##x.dep_map) # define I_MUTEX(x) lockdep_reset_lock(&mutex_##x.dep_map) # define I_RWSEM(x) lockdep_reset_lock(&rwsem_##x.dep_map) # define I_WW(x) lockdep_reset_lock(&x.dep_map) #ifdef CONFIG_RT_MUTEXES # define I_RTMUTEX(x) lockdep_reset_lock(&rtmutex_##x.dep_map) #endif #else # define I_SPINLOCK(x) # define I_RWLOCK(x) # define I_MUTEX(x) # define I_RWSEM(x) # define I_WW(x) #endif #ifndef I_RTMUTEX # define I_RTMUTEX(x) #endif #ifdef CONFIG_RT_MUTEXES #define I2_RTMUTEX(x) rt_mutex_init(&rtmutex_##x) #else #define I2_RTMUTEX(x) #endif #define I1(x) \ do { \ I_SPINLOCK(x); \ I_RWLOCK(x); \ I_MUTEX(x); \ I_RWSEM(x); \ I_RTMUTEX(x); \ } while (0) #define I2(x) \ do { \ raw_spin_lock_init(&lock_##x); \ rwlock_init(&rwlock_##x); \ mutex_init(&mutex_##x); \ init_rwsem(&rwsem_##x); \ I2_RTMUTEX(x); \ } while (0) static void reset_locks(void) { local_irq_disable(); lockdep_free_key_range(&ww_lockdep.acquire_key, 1); lockdep_free_key_range(&ww_lockdep.mutex_key, 1); I1(A); I1(B); I1(C); I1(D); I1(X1); I1(X2); I1(Y1); I1(Y2); I1(Z1); I1(Z2); I_WW(t); I_WW(t2); I_WW(o.base); I_WW(o2.base); I_WW(o3.base); lockdep_reset(); I2(A); I2(B); I2(C); I2(D); init_shared_classes(); ww_mutex_init(&o, &ww_lockdep); ww_mutex_init(&o2, &ww_lockdep); ww_mutex_init(&o3, &ww_lockdep); memset(&t, 0, sizeof(t)); memset(&t2, 0, sizeof(t2)); memset(&ww_lockdep.acquire_key, 0, sizeof(ww_lockdep.acquire_key)); memset(&ww_lockdep.mutex_key, 0, sizeof(ww_lockdep.mutex_key)); local_irq_enable(); } #undef I static int testcase_total; static int testcase_successes; static int expected_testcase_failures; static int unexpected_testcase_failures; static void dotest(void (*testcase_fn)(void), int expected, int lockclass_mask) { unsigned long saved_preempt_count = preempt_count(); WARN_ON(irqs_disabled()); testcase_fn(); /* * Filter out expected failures: */ #ifndef CONFIG_PROVE_LOCKING if (expected == FAILURE && debug_locks) { expected_testcase_failures++; pr_cont("failed|"); } else #endif if (debug_locks != expected) { unexpected_testcase_failures++; pr_cont("FAILED|"); } else { testcase_successes++; pr_cont(" ok |"); } testcase_total++; if (debug_locks_verbose) pr_cont(" lockclass mask: %x, debug_locks: %d, expected: %d\n", lockclass_mask, debug_locks, expected); /* * Some tests (e.g. double-unlock) might corrupt the preemption * count, so restore it: */ preempt_count_set(saved_preempt_count); #ifdef CONFIG_TRACE_IRQFLAGS if (softirq_count()) current->softirqs_enabled = 0; else current->softirqs_enabled = 1; #endif reset_locks(); } #ifdef CONFIG_RT_MUTEXES #define dotest_rt(fn, e, m) dotest((fn), (e), (m)) #else #define dotest_rt(fn, e, m) #endif static inline void print_testname(const char *testname) { printk("%33s:", testname); } #define DO_TESTCASE_1(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_1B(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_##nr, FAILURE, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_3(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_3RW(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN|LOCKTYPE_RWLOCK);\ dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_6(desc, name) \ print_testname(desc); \ dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \ dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \ dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, FAILURE, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); #define DO_TESTCASE_6_SUCCESS(desc, name) \ print_testname(desc); \ dotest(name##_spin, SUCCESS, LOCKTYPE_SPIN); \ dotest(name##_wlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, SUCCESS, LOCKTYPE_MUTEX); \ dotest(name##_wsem, SUCCESS, LOCKTYPE_RWSEM); \ dotest(name##_rsem, SUCCESS, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, SUCCESS, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); /* * 'read' variant: rlocks must not trigger. */ #define DO_TESTCASE_6R(desc, name) \ print_testname(desc); \ dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \ dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \ dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, FAILURE, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); #define DO_TESTCASE_2I(desc, name, nr) \ DO_TESTCASE_1("hard-"desc, name##_hard, nr); \ DO_TESTCASE_1("soft-"desc, name##_soft, nr); #define DO_TESTCASE_2IB(desc, name, nr) \ DO_TESTCASE_1B("hard-"desc, name##_hard, nr); \ DO_TESTCASE_1B("soft-"desc, name##_soft, nr); #define DO_TESTCASE_6I(desc, name, nr) \ DO_TESTCASE_3("hard-"desc, name##_hard, nr); \ DO_TESTCASE_3("soft-"desc, name##_soft, nr); #define DO_TESTCASE_6IRW(desc, name, nr) \ DO_TESTCASE_3RW("hard-"desc, name##_hard, nr); \ DO_TESTCASE_3RW("soft-"desc, name##_soft, nr); #define DO_TESTCASE_2x3(desc, name) \ DO_TESTCASE_3(desc, name, 12); \ DO_TESTCASE_3(desc, name, 21); #define DO_TESTCASE_2x6(desc, name) \ DO_TESTCASE_6I(desc, name, 12); \ DO_TESTCASE_6I(desc, name, 21); #define DO_TESTCASE_6x2(desc, name) \ DO_TESTCASE_2I(desc, name, 123); \ DO_TESTCASE_2I(desc, name, 132); \ DO_TESTCASE_2I(desc, name, 213); \ DO_TESTCASE_2I(desc, name, 231); \ DO_TESTCASE_2I(desc, name, 312); \ DO_TESTCASE_2I(desc, name, 321); #define DO_TESTCASE_6x2B(desc, name) \ DO_TESTCASE_2IB(desc, name, 123); \ DO_TESTCASE_2IB(desc, name, 132); \ DO_TESTCASE_2IB(desc, name, 213); \ DO_TESTCASE_2IB(desc, name, 231); \ DO_TESTCASE_2IB(desc, name, 312); \ DO_TESTCASE_2IB(desc, name, 321); #define DO_TESTCASE_6x6(desc, name) \ DO_TESTCASE_6I(desc, name, 123); \ DO_TESTCASE_6I(desc, name, 132); \ DO_TESTCASE_6I(desc, name, 213); \ DO_TESTCASE_6I(desc, name, 231); \ DO_TESTCASE_6I(desc, name, 312); \ DO_TESTCASE_6I(desc, name, 321); #define DO_TESTCASE_6x6RW(desc, name) \ DO_TESTCASE_6IRW(desc, name, 123); \ DO_TESTCASE_6IRW(desc, name, 132); \ DO_TESTCASE_6IRW(desc, name, 213); \ DO_TESTCASE_6IRW(desc, name, 231); \ DO_TESTCASE_6IRW(desc, name, 312); \ DO_TESTCASE_6IRW(desc, name, 321); static void ww_test_fail_acquire(void) { int ret; WWAI(&t); t.stamp++; ret = WWL(&o, &t); if (WARN_ON(!o.ctx) || WARN_ON(ret)) return; /* No lockdep test, pure API */ ret = WWL(&o, &t); WARN_ON(ret != -EALREADY); ret = WWT(&o); WARN_ON(ret); t2 = t; t2.stamp++; ret = WWL(&o, &t2); WARN_ON(ret != -EDEADLK); WWU(&o); if (WWT(&o)) WWU(&o); #ifdef CONFIG_DEBUG_LOCK_ALLOC else DEBUG_LOCKS_WARN_ON(1); #endif } static void ww_test_normal(void) { int ret; WWAI(&t); /* * None of the ww_mutex codepaths should be taken in the 'normal' * mutex calls. The easiest way to verify this is by using the * normal mutex calls, and making sure o.ctx is unmodified. */ /* mutex_lock (and indirectly, mutex_lock_nested) */ o.ctx = (void *)~0UL; mutex_lock(&o.base); mutex_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); /* mutex_lock_interruptible (and *_nested) */ o.ctx = (void *)~0UL; ret = mutex_lock_interruptible(&o.base); if (!ret) mutex_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* mutex_lock_killable (and *_nested) */ o.ctx = (void *)~0UL; ret = mutex_lock_killable(&o.base); if (!ret) mutex_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* trylock, succeeding */ o.ctx = (void *)~0UL; ret = mutex_trylock(&o.base); WARN_ON(!ret); if (ret) mutex_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* trylock, failing */ o.ctx = (void *)~0UL; mutex_lock(&o.base); ret = mutex_trylock(&o.base); WARN_ON(ret); mutex_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); /* nest_lock */ o.ctx = (void *)~0UL; mutex_lock_nest_lock(&o.base, &t); mutex_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); } static void ww_test_two_contexts(void) { WWAI(&t); WWAI(&t2); } static void ww_test_diff_class(void) { WWAI(&t); #ifdef CONFIG_DEBUG_MUTEXES t.ww_class = NULL; #endif WWL(&o, &t); } static void ww_test_context_done_twice(void) { WWAI(&t); WWAD(&t); WWAD(&t); WWAF(&t); } static void ww_test_context_unlock_twice(void) { WWAI(&t); WWAD(&t); WWAF(&t); WWAF(&t); } static void ww_test_context_fini_early(void) { WWAI(&t); WWL(&o, &t); WWAD(&t); WWAF(&t); } static void ww_test_context_lock_after_done(void) { WWAI(&t); WWAD(&t); WWL(&o, &t); } static void ww_test_object_unlock_twice(void) { WWL1(&o); WWU(&o); WWU(&o); } static void ww_test_object_lock_unbalanced(void) { WWAI(&t); WWL(&o, &t); t.acquired = 0; WWU(&o); WWAF(&t); } static void ww_test_object_lock_stale_context(void) { WWAI(&t); o.ctx = &t2; WWL(&o, &t); } static void ww_test_edeadlk_normal(void) { int ret; mutex_lock(&o2.base); o2.ctx = &t2; mutex_release(&o2.base.dep_map, 1, _THIS_IP_); WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); mutex_unlock(&o2.base); WWU(&o); WWL(&o2, &t); } static void ww_test_edeadlk_normal_slow(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); mutex_unlock(&o2.base); WWU(&o); ww_mutex_lock_slow(&o2, &t); } static void ww_test_edeadlk_no_unlock(void) { int ret; mutex_lock(&o2.base); o2.ctx = &t2; mutex_release(&o2.base.dep_map, 1, _THIS_IP_); WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); mutex_unlock(&o2.base); WWL(&o2, &t); } static void ww_test_edeadlk_no_unlock_slow(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); mutex_unlock(&o2.base); ww_mutex_lock_slow(&o2, &t); } static void ww_test_edeadlk_acquire_more(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ret = WWL(&o3, &t); } static void ww_test_edeadlk_acquire_more_slow(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ww_mutex_lock_slow(&o3, &t); } static void ww_test_edeadlk_acquire_more_edeadlk(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; mutex_lock(&o3.base); mutex_release(&o3.base.dep_map, 1, _THIS_IP_); o3.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ret = WWL(&o3, &t); WARN_ON(ret != -EDEADLK); } static void ww_test_edeadlk_acquire_more_edeadlk_slow(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; mutex_lock(&o3.base); mutex_release(&o3.base.dep_map, 1, _THIS_IP_); o3.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ww_mutex_lock_slow(&o3, &t); } static void ww_test_edeadlk_acquire_wrong(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); if (!ret) WWU(&o2); WWU(&o); ret = WWL(&o3, &t); } static void ww_test_edeadlk_acquire_wrong_slow(void) { int ret; mutex_lock(&o2.base); mutex_release(&o2.base.dep_map, 1, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); if (!ret) WWU(&o2); WWU(&o); ww_mutex_lock_slow(&o3, &t); } static void ww_test_spin_nest_unlocked(void) { raw_spin_lock_nest_lock(&lock_A, &o.base); U(A); } static void ww_test_unneeded_slow(void) { WWAI(&t); ww_mutex_lock_slow(&o, &t); } static void ww_test_context_block(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); WWL1(&o2); } static void ww_test_context_try(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); ret = WWT(&o2); WARN_ON(!ret); WWU(&o2); WWU(&o); } static void ww_test_context_context(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret); WWU(&o2); WWU(&o); } static void ww_test_try_block(void) { bool ret; ret = WWT(&o); WARN_ON(!ret); WWL1(&o2); WWU(&o2); WWU(&o); } static void ww_test_try_try(void) { bool ret; ret = WWT(&o); WARN_ON(!ret); ret = WWT(&o2); WARN_ON(!ret); WWU(&o2); WWU(&o); } static void ww_test_try_context(void) { int ret; ret = WWT(&o); WARN_ON(!ret); WWAI(&t); ret = WWL(&o2, &t); WARN_ON(ret); } static void ww_test_block_block(void) { WWL1(&o); WWL1(&o2); } static void ww_test_block_try(void) { bool ret; WWL1(&o); ret = WWT(&o2); WARN_ON(!ret); } static void ww_test_block_context(void) { int ret; WWL1(&o); WWAI(&t); ret = WWL(&o2, &t); WARN_ON(ret); } static void ww_test_spin_block(void) { L(A); U(A); WWL1(&o); L(A); U(A); WWU(&o); L(A); WWL1(&o); WWU(&o); U(A); } static void ww_test_spin_try(void) { bool ret; L(A); U(A); ret = WWT(&o); WARN_ON(!ret); L(A); U(A); WWU(&o); L(A); ret = WWT(&o); WARN_ON(!ret); WWU(&o); U(A); } static void ww_test_spin_context(void) { int ret; L(A); U(A); WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); L(A); U(A); WWU(&o); L(A); ret = WWL(&o, &t); WARN_ON(ret); WWU(&o); U(A); } static void ww_tests(void) { printk(" --------------------------------------------------------------------------\n"); printk(" | Wound/wait tests |\n"); printk(" ---------------------\n"); print_testname("ww api failures"); dotest(ww_test_fail_acquire, SUCCESS, LOCKTYPE_WW); dotest(ww_test_normal, SUCCESS, LOCKTYPE_WW); dotest(ww_test_unneeded_slow, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("ww contexts mixing"); dotest(ww_test_two_contexts, FAILURE, LOCKTYPE_WW); dotest(ww_test_diff_class, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("finishing ww context"); dotest(ww_test_context_done_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_unlock_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_fini_early, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_lock_after_done, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("locking mismatches"); dotest(ww_test_object_unlock_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_object_lock_unbalanced, FAILURE, LOCKTYPE_WW); dotest(ww_test_object_lock_stale_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("EDEADLK handling"); dotest(ww_test_edeadlk_normal, SUCCESS, LOCKTYPE_WW); dotest(ww_test_edeadlk_normal_slow, SUCCESS, LOCKTYPE_WW); dotest(ww_test_edeadlk_no_unlock, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_no_unlock_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_edeadlk, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_edeadlk_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_wrong, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_wrong_slow, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("spinlock nest unlocked"); dotest(ww_test_spin_nest_unlocked, FAILURE, LOCKTYPE_WW); pr_cont("\n"); printk(" -----------------------------------------------------\n"); printk(" |block | try |context|\n"); printk(" -----------------------------------------------------\n"); print_testname("context"); dotest(ww_test_context_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_context_context, SUCCESS, LOCKTYPE_WW); pr_cont("\n"); print_testname("try"); dotest(ww_test_try_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_try_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_try_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("block"); dotest(ww_test_block_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_block_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_block_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("spinlock"); dotest(ww_test_spin_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_spin_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_spin_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); } void locking_selftest(void) { /* * Got a locking failure before the selftest ran? */ if (!debug_locks) { printk("----------------------------------\n"); printk("| Locking API testsuite disabled |\n"); printk("----------------------------------\n"); return; } /* * Run the testsuite: */ printk("------------------------\n"); printk("| Locking API testsuite:\n"); printk("----------------------------------------------------------------------------\n"); printk(" | spin |wlock |rlock |mutex | wsem | rsem |\n"); printk(" --------------------------------------------------------------------------\n"); init_shared_classes(); debug_locks_silent = !debug_locks_verbose; DO_TESTCASE_6R("A-A deadlock", AA); DO_TESTCASE_6R("A-B-B-A deadlock", ABBA); DO_TESTCASE_6R("A-B-B-C-C-A deadlock", ABBCCA); DO_TESTCASE_6R("A-B-C-A-B-C deadlock", ABCABC); DO_TESTCASE_6R("A-B-B-C-C-D-D-A deadlock", ABBCCDDA); DO_TESTCASE_6R("A-B-C-D-B-D-D-A deadlock", ABCDBDDA); DO_TESTCASE_6R("A-B-C-D-B-C-D-A deadlock", ABCDBCDA); DO_TESTCASE_6("double unlock", double_unlock); DO_TESTCASE_6("initialize held", init_held); printk(" --------------------------------------------------------------------------\n"); print_testname("recursive read-lock"); pr_cont(" |"); dotest(rlock_AA1, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA1, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("recursive read-lock #2"); pr_cont(" |"); dotest(rlock_AA1B, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA1B, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed read-write-lock"); pr_cont(" |"); dotest(rlock_AA2, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA2, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed write-read-lock"); pr_cont(" |"); dotest(rlock_AA3, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA3, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed read-lock/lock-write ABBA"); pr_cont(" |"); dotest(rlock_ABBA1, FAILURE, LOCKTYPE_RWLOCK); #ifdef CONFIG_PROVE_LOCKING /* * Lockdep does indeed fail here, but there's nothing we can do about * that now. Don't kill lockdep for it. */ unexpected_testcase_failures--; #endif pr_cont(" |"); dotest(rwsem_ABBA1, FAILURE, LOCKTYPE_RWSEM); print_testname("mixed read-lock/lock-read ABBA"); pr_cont(" |"); dotest(rlock_ABBA2, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rwsem_ABBA2, FAILURE, LOCKTYPE_RWSEM); print_testname("mixed write-lock/lock-write ABBA"); pr_cont(" |"); dotest(rlock_ABBA3, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rwsem_ABBA3, FAILURE, LOCKTYPE_RWSEM); printk(" --------------------------------------------------------------------------\n"); /* * irq-context testcases: */ DO_TESTCASE_2x6("irqs-on + irq-safe-A", irqsafe1); DO_TESTCASE_2x3("sirq-safe-A => hirqs-on", irqsafe2A); DO_TESTCASE_2x6("safe-A + irqs-on", irqsafe2B); DO_TESTCASE_6x6("safe-A + unsafe-B #1", irqsafe3); DO_TESTCASE_6x6("safe-A + unsafe-B #2", irqsafe4); DO_TESTCASE_6x6RW("irq lock-inversion", irq_inversion); DO_TESTCASE_6x2("irq read-recursion", irq_read_recursion); // DO_TESTCASE_6x2B("irq read-recursion #2", irq_read_recursion2); ww_tests(); if (unexpected_testcase_failures) { printk("-----------------------------------------------------------------\n"); debug_locks = 0; printk("BUG: %3d unexpected failures (out of %3d) - debugging disabled! |\n", unexpected_testcase_failures, testcase_total); printk("-----------------------------------------------------------------\n"); } else if (expected_testcase_failures && testcase_successes) { printk("--------------------------------------------------------\n"); printk("%3d out of %3d testcases failed, as expected. |\n", expected_testcase_failures, testcase_total); printk("----------------------------------------------------\n"); debug_locks = 1; } else if (expected_testcase_failures && !testcase_successes) { printk("--------------------------------------------------------\n"); printk("All %3d testcases failed, as expected. |\n", expected_testcase_failures); printk("----------------------------------------\n"); debug_locks = 1; } else { printk("-------------------------------------------------------\n"); printk("Good, all %3d testcases passed! |\n", testcase_successes); printk("---------------------------------\n"); debug_locks = 1; } debug_locks_silent = 0; }
630007.c
/* * Copyright (C) 2012-2018, Netronome Systems, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file lib/nfp/_c/mem_bulk.c * @brief NFP memory bulk interface */ #include <assert.h> #include <nfp.h> #include <types.h> #include <nfp6000/nfp_me.h> #include <nfp/mem_bulk.h> #define _MEM_CMD(cmdname, data, addr, size, max_size, sync, sig, shift) \ do { \ struct nfp_mecsr_prev_alu ind; \ unsigned int count = (size >> shift); \ unsigned int max_count = (max_size >> shift); \ unsigned int addr_hi, addr_lo; \ \ ctassert(__is_ct_const(sync)); \ try_ctassert(size != 0); \ ctassert(sync == sig_done || sync == ctx_swap); \ \ /* This code is inefficient if addr is >256B aligned, */ \ /* but will work for 40bit or 32bit pointers. */ \ \ addr_hi = ((unsigned long long int)addr >> 8) & 0xff000000; \ addr_lo = (unsigned long long int)addr & 0xffffffff; \ \ if (__is_ct_const(size)) { \ if (count <= 8) { \ if (sync == sig_done) { \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(count)], sig_done[*sig] } \ } else { \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(count)], ctx_swap[*sig] } \ } \ } else { \ /* Setup length in PrevAlu for the indirect */ \ ind.__raw = 0; \ ind.ov_len = 1; \ ind.length = count - 1; \ \ if (sync == sig_done) { \ __asm { alu[--, --, B, ind.__raw] } \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(count)], sig_done[*sig], \ indirect_ref } \ } else { \ __asm { alu[--, --, B, ind.__raw] } \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(count)], ctx_swap[*sig], \ indirect_ref } \ } \ } \ } else { \ /* Setup length in PrevAlu for the indirect */ \ ind.__raw = 0; \ ind.ov_len = 1; \ ind.length = count - 1; \ \ if (sync == sig_done) { \ __asm { alu[--, --, B, ind.__raw] } \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(max_count)], sig_done[*sig], \ indirect_ref } \ } else { \ __asm { alu[--, --, B, ind.__raw] } \ __asm { mem[cmdname, *data, addr_hi, <<8, addr_lo, \ __ct_const_val(max_count)], ctx_swap[*sig], \ indirect_ref } \ } \ } \ } while (0) __intrinsic void __mem_read64(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(read, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_read64(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read64(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read64_le(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(read_le, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_read64_le(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read64_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read64_swap(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(read_swap, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_read64_swap(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read64_swap(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read64_swap_le(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(read_swap_le, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_read64_swap_le(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read64_swap_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read32(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(read32, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_read32(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read32(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read32_le(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(read32_le, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_read32_le(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read32_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read32_swap(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(read32_swap, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_read32_swap(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read32_swap(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read32_swap_le(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(read32_swap_le, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_read32_swap_le(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read32_swap_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_read8(__xread void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_read_reg(data)); try_ctassert(size <= 32); _MEM_CMD(read8, data, addr, size, max_size, sync, sig, 0); } __intrinsic void mem_read8(__xread void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_read8(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write64(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(write, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_write64(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write64(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write64_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(write_le, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_write64_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write64_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write64_swap(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(write_swap, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_write64_swap(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write64_swap(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write64_swap_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 8)); try_ctassert(size <= 128); _MEM_CMD(write_swap_le, data, addr, size, max_size, sync, sig, 3); } __intrinsic void mem_write64_swap_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write64_swap_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write32(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(write32, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_write32(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write32(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write32_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(write32_le, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_write32_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write32_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write32_swap(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(write32_swap, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_write32_swap(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write32_swap(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write32_swap_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(__is_aligned(size, 4)); try_ctassert(size <= 128); _MEM_CMD(write32_swap_le, data, addr, size, max_size, sync, sig, 2); } __intrinsic void mem_write32_swap_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write32_swap_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write8(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(size <= 32); _MEM_CMD(write8, data, addr, size, max_size, sync, sig, 0); } __intrinsic void mem_write8(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write8(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write8_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(size <= 32); _MEM_CMD(write8_le, data, addr, size, max_size, sync, sig, 0); } __intrinsic void mem_write8_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write8_le(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write8_swap(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(size <= 32); _MEM_CMD(write8_swap, data, addr, size, max_size, sync, sig, 0); } __intrinsic void mem_write8_swap(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write8_swap(data, addr, size, size, ctx_swap, &sig); } __intrinsic void __mem_write8_swap_le(__xwrite void *data, __mem40 void *addr, size_t size, const size_t max_size, sync_t sync, SIGNAL *sig) { ctassert(__is_write_reg(data)); try_ctassert(size <= 32); _MEM_CMD(write8_swap_le, data, addr, size, max_size, sync, sig, 0); } __intrinsic void mem_write8_swap_le(__xwrite void *data, __mem40 void *addr, const size_t size) { SIGNAL sig; __mem_write8_swap_le(data, addr, size, size, ctx_swap, &sig); }
796830.c
// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-compatibility enum ENUM1; // expected-warning {{forward references to 'enum' types are a Microsoft extension}} enum ENUM1 var1 = 3; enum ENUM1* var2 = 0; enum ENUM2 { ENUM2_a = (enum ENUM2) 4, ENUM2_b = 0x9FFFFFFF, // expected-warning {{enumerator value is not representable in the underlying type 'int'}} ENUM2_c = 0x100000000 // expected-warning {{enumerator value is not representable in the underlying type 'int'}} }; __declspec(noreturn) void f6( void ) { return; // expected-warning {{function 'f6' declared 'noreturn' should not return}} } __declspec(align(32768)) struct S1 { int a; } s; /* expected-error {{requested alignment must be 8192 bytes or smaller}} */ struct __declspec(aligned) S2 {}; /* expected-warning {{__declspec attribute 'aligned' is not supported}} */ struct __declspec(appdomain) S3 {}; /* expected-warning {{__declspec attribute 'appdomain' is not supported}} */ __declspec(__noreturn__) void f7(void); /* expected-warning {{__declspec attribute '__noreturn__' is not supported}} */ size_t x;
739072.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <emscripten.h> EM_JS(void,showAdminPassword,(),{ alert("Secret Password!"); }); int main() { char user[] = "guest"; char input[5]; memset(input, '\0', 5); strcpy(input,"BBBBBBadmin"); printf("input address: %p\n", &input); printf("input: %s\n", input); printf("user address: %p\n", &user); printf("user: %s\n", user); if(strcmp(user, "admin") == 0) { showAdminPassword(0); return 0; } }
579220.c
/* * Copyright (C) 2004-2008 Christos Tsantilas * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. */ #include "common.h" #include "c-icap.h" #include <stdio.h> #include <stdarg.h> #include <time.h> #include "log.h" #include "util.h" #include "access.h" #include "module.h" #include "cfg_param.h" #include "debug.h" #include "txt_format.h" #include "acl.h" #include "proc_threads_queues.h" #include "commands.h" #include <errno.h> #include <assert.h> logger_module_t *default_logger = NULL; void logformat_release(); int log_open() { if (default_logger) return default_logger->log_open(); return 0; } void log_close() { if (default_logger) { default_logger->log_close(); } } void log_reset() { logformat_release(); default_logger = NULL; } void log_access(ci_request_t * req, int status) { /*req can not be NULL */ if (!req) return; if (default_logger) default_logger->log_access(req); } extern process_pid_t MY_PROC_PID; void log_server(ci_request_t * req, const char *format, ...) { /*req can be NULL......... */ va_list ap; char prefix[64]; va_start(ap, format); if (default_logger) { if (MY_PROC_PID) snprintf(prefix, 64, "%u/%u", (unsigned int)MY_PROC_PID, (unsigned int)ci_thread_self()); else /*probably the main process*/ strcpy(prefix, "main proc"); default_logger->log_server(prefix, format, ap); /*First argument must be changed..... */ } va_end(ap); } void vlog_server(ci_request_t * req, const char *format, va_list ap) { if (default_logger) default_logger->log_server("", format, ap); } /*************************************************************/ /* logformat */ /* Maybe logformat manipulation functions should moved to the c-icap library, because some platforms (eg. MS-WINDOWS) can not use functions and objects defined in main executable. At this time ony the sys_logger.c module uses these functions which make sense on unix platforms (where there is not a such problem). Moreover the sys_logger can be compiled inside c-icap main executable to avoid such problems. */ struct logformat { char *name; char *fmt; struct logformat *next; }; struct logformat *LOGFORMATS = NULL; int logformat_add(const char *name, const char *format) { struct logformat *lf, *tmp; lf = malloc(sizeof(struct logformat)); if (!lf) { ci_debug_printf(1, "Error allocating memory in add_logformat\n"); return 0; } lf->name = strdup(name); lf->fmt = strdup(format); if (!lf->name || !lf->fmt) { ci_debug_printf(1, "Error strduping in add_logformat\n"); free(lf); return 0; } lf->next = NULL; if (LOGFORMATS==NULL) { LOGFORMATS = lf; return 1; } tmp = LOGFORMATS; while (tmp->next != NULL) tmp = tmp->next; tmp->next = lf; return 1; } void logformat_release() { struct logformat *cur, *tmp; if (!(tmp = LOGFORMATS)) return; do { cur = tmp; tmp = tmp->next; free(cur->name); free(cur->fmt); free(cur); } while (tmp); LOGFORMATS = NULL; } char *logformat_fmt(const char *name) { struct logformat *tmp; if (!(tmp = LOGFORMATS)) return NULL; while (tmp) { if (strcmp(tmp->name, name) == 0) return tmp->fmt; tmp = tmp->next; } return NULL; } /******************************************************************/ /* file_logger implementation. This is the default logger */ /* */ int file_log_open(); void file_log_close(); void file_log_access(ci_request_t *req); void file_log_server(const char *server, const char *format, va_list ap); void file_log_relog(const char *name, int type, const char **argv); /*char *LOGS_DIR = LOGDIR;*/ char *SERVER_LOG_FILE = LOGDIR "/cicap-server.log"; /*char *ACCESS_LOG_FILE = LOGDIR "/cicap-access.log";*/ struct logfile { char *file; FILE *access_log; const char *log_fmt; ci_access_entry_t *access_list; ci_thread_rwlock_t rwlock; struct logfile *next; }; struct logfile *ACCESS_LOG_FILES = NULL; static ci_thread_rwlock_t systemlog_rwlock; logger_module_t file_logger = { "file_logger", NULL, file_log_open, file_log_close, file_log_access, file_log_server, NULL /*NULL configuration table */ }; FILE *server_log = NULL; const char *DEFAULT_LOG_FORMAT = "%tl, %la %a %im %iu %is"; FILE *logfile_open(const char *fname) { FILE *f = fopen(fname, "a+"); if (f) setvbuf(f, NULL, _IONBF, 0); return f; } int file_log_open() { int error = 0, ret = 0; struct logfile *lf; assert(ret == 0); register_command("relog", MONITOR_PROC_CMD | CHILDS_PROC_CMD, file_log_relog); for (lf = ACCESS_LOG_FILES; lf != NULL; lf = lf->next) { if (!lf->file) { ci_debug_printf (1, "This is a bug! lf->file==NULL\n"); continue; } if (lf->log_fmt == NULL) lf->log_fmt = (char *)DEFAULT_LOG_FORMAT; if (ci_thread_rwlock_init(&(lf->rwlock)) != 0) { ci_debug_printf (1, "WARNING! Can not initialize structures for log file: %s\n", lf->file); continue; } lf->access_log = logfile_open(lf->file); if (!lf->access_log) { error = 1; ci_debug_printf (1, "WARNING! Can not open log file: %s\n", lf->file); } } ret = ci_thread_rwlock_init(&systemlog_rwlock); if (ret != 0) return 0; server_log = logfile_open(SERVER_LOG_FILE); if (!server_log) return 0; if (error) return 0; else return 1; } void file_log_close() { struct logfile *lf, *tmp; lf = ACCESS_LOG_FILES; while (lf != NULL) { if (lf->access_log) fclose(lf->access_log); free(lf->file); if (lf->access_list) ci_access_entry_release(lf->access_list); ci_thread_rwlock_destroy(&(lf->rwlock)); // Initialize logfile::rwlock tmp = lf; lf = lf->next; ACCESS_LOG_FILES = lf; free(tmp); } if (server_log) fclose(server_log); server_log = NULL; ci_thread_rwlock_destroy(&systemlog_rwlock); // destroy rwlock } void file_log_relog(const char *name, int type, const char **argv) { struct logfile *lf; /* This code should match the appropriate code from file_log_close */ for (lf = ACCESS_LOG_FILES; lf != NULL; lf = lf->next) { ci_thread_rwlock_wrlock(&(lf->rwlock)); /*obtain a write lock. When this function returns all file_log_access will block until write unlock*/ if (lf->access_log) fclose(lf->access_log); lf->access_log = logfile_open(lf->file); ci_thread_rwlock_unlock(&(lf->rwlock)); if (!lf->access_log) ci_debug_printf (1, "WARNING! Can not open log file: %s\n", lf->file); } ci_thread_rwlock_wrlock(&systemlog_rwlock); if (server_log) fclose(server_log); server_log = logfile_open(SERVER_LOG_FILE); ci_thread_rwlock_unlock(&systemlog_rwlock); /*if !server_log ???*/ } void file_log_access(ci_request_t *req) { struct logfile *lf; char logline[4096]; for (lf = ACCESS_LOG_FILES; lf != NULL; lf = lf->next) { if (lf->access_list && !(ci_access_entry_match_request(lf->access_list, req) == CI_ACCESS_ALLOW)) { ci_debug_printf(6, "access log file %s does not match, skiping\n", lf->file); continue; } ci_debug_printf(6, "Log request to access log file %s\n", lf->file); ci_format_text(req, lf->log_fmt, logline, sizeof(logline), NULL); ci_thread_rwlock_rdlock(&lf->rwlock); /*obtain a read lock*/ if (lf->access_log) fprintf(lf->access_log,"%s\n", logline); ci_thread_rwlock_unlock(&lf->rwlock); /*obtain a read lock*/ } } void file_log_server(const char *server, const char *format, va_list ap) { char buf[1024]; if (!server_log) return; ci_strtime(buf); /* requires STR_TIME_SIZE=64 bytes size */ const size_t len = strlen(buf); const size_t written = snprintf(buf + len, sizeof(buf) - len, ", %s, %s", server, format); assert(written < sizeof(buf) - len); ci_thread_rwlock_rdlock(&systemlog_rwlock); /*obtain a read lock*/ vfprintf(server_log, buf, ap); ci_thread_rwlock_unlock(&systemlog_rwlock); /*release a read lock*/ } int file_log_addlogfile(const char *file, const char *format, const char **acls) { char *access_log_file, *access_log_format; const char *acl_name; struct logfile *lf, *newlf; int i; access_log_file = strdup(file); if (!access_log_file) return 0; if (format) { /*the folowing return format txt or NULL. It is OK*/ access_log_format = logformat_fmt(format); } else access_log_format = NULL; newlf = malloc(sizeof(struct logfile)); newlf->file = access_log_file; newlf->log_fmt = (access_log_format != NULL? access_log_format : DEFAULT_LOG_FORMAT); newlf->access_log = NULL; newlf->access_list = NULL; newlf->next = NULL; if (acls != NULL && acls[0] != NULL) { if (ci_access_entry_new(&(newlf->access_list), CI_ACCESS_ALLOW) == NULL) { ci_debug_printf(1, "Error creating access list for access log file %s!\n", newlf->file); free(newlf->file); free(newlf); return 0; } for (i = 0; acls[i] != NULL; i++) { acl_name = acls[i]; if (!ci_access_entry_add_acl_by_name(newlf->access_list, acl_name)) { ci_debug_printf(1, "Error addind acl %s to access list for access log file %s!\n", acl_name, newlf->file); ci_access_entry_release(newlf->access_list); free(newlf->file); free(newlf); return 0; } } } if (!ACCESS_LOG_FILES) { ACCESS_LOG_FILES = newlf; } else { for (lf = ACCESS_LOG_FILES; lf->next != NULL; lf = lf->next) { if (strcmp(lf->file, newlf->file)==0) { ci_debug_printf(1, "Access log file %s already defined!\n", newlf->file); if (newlf->access_list) ci_access_entry_release(newlf->access_list); free(newlf->file); free(newlf); return 0; } } lf->next = newlf; } return 1; }
29516.c
/* * Copyright (c) 2002 Michael Shalayeff. All rights reserved. * Copyright (c) 2003 Ryan McBride. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /* * $FreeBSD: src/sys/netinet/ip_carp.c,v 1.48 2007/02/02 09:39:09 glebius Exp $ */ #include "opt_carp.h" #include "opt_inet.h" #include "opt_inet6.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/in_cksum.h> #include <sys/limits.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <sys/msgport2.h> #include <sys/time.h> #include <sys/proc.h> #include <sys/priv.h> #include <sys/sockio.h> #include <sys/socket.h> #include <sys/sysctl.h> #include <sys/syslog.h> #include <sys/thread.h> #include <machine/stdarg.h> #include <crypto/sha1.h> #include <net/bpf.h> #include <net/ethernet.h> #include <net/if.h> #include <net/if_dl.h> #include <net/if_types.h> #include <net/route.h> #include <net/if_clone.h> #include <net/if_var.h> #include <net/ifq_var.h> #include <net/netmsg2.h> #include <net/netisr2.h> #ifdef INET #include <netinet/in.h> #include <netinet/in_var.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_var.h> #include <netinet/if_ether.h> #endif #ifdef INET6 #include <netinet/icmp6.h> #include <netinet/ip6.h> #include <netinet6/ip6_var.h> #include <netinet6/scope6_var.h> #include <netinet6/nd6.h> #endif #include <netinet/ip_carp.h> /* * Note about carp's MP safe approach: * * Brief: carp_softc (softc), carp_softc_container (scc) * * - All configuration operation, e.g. ioctl, add/delete inet addresses * is serialized by netisr0; not by carp's serializer * * - Backing interface's if_carp and carp_softc's relationship: * * +---------+ * if_carp -->| carp_if | * +---------+ * | * | * V +---------+ * +-----+ | | * | scc |-->| softc | * +-----+ | | * | +---------+ * | * V +---------+ * +-----+ | | * | scc |-->| softc | * +-----+ | | * +---------+ * * - if_carp creation, modification and deletion all happen in netisr0, * as stated previously. Since if_carp is accessed by multiple netisrs, * the modification to if_carp is conducted in the following way: * * Adding carp_softc: * * 1) Duplicate the old carp_if to new carp_if (ncif), and insert the * to-be-added carp_softc to the new carp_if (ncif): * * if_carp ncif * | | * V V * +---------+ +---------+ * | carp_if | | carp_if | * +---------+ +---------+ * | | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * | +-------+ | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * +-------+ | * | * +-------+ V * | | +-----+ * | softc |<----| scc | * | | +-----+ * +-------+ * * 2) Switch save if_carp into ocif and switch if_carp to ncif: * * ocif if_carp * | | * V V * +---------+ +---------+ * | carp_if | | carp_if | * +---------+ +---------+ * | | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * | +-------+ | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * +-------+ | * | * +-------+ V * | | +-----+ * | softc |<----| scc | * | | +-----+ * +-------+ * * 3) Run netmsg_service_sync(), which will make sure that * ocif is no longer accessed (all network operations * are happened only in network threads). * 4) Free ocif -- only carp_if and scc are freed. * * * Removing carp_softc: * * 1) Duplicate the old carp_if to new carp_if (ncif); the to-be-deleted * carp_softc will not be duplicated. * * if_carp ncif * | | * V V * +---------+ +---------+ * | carp_if | | carp_if | * +---------+ +---------+ * | | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * | +-------+ | * | | * V +-------+ | * +-----+ | | | * | scc |---->| softc | | * +-----+ | | | * | +-------+ | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * +-------+ * * 2) Switch save if_carp into ocif and switch if_carp to ncif: * * ocif if_carp * | | * V V * +---------+ +---------+ * | carp_if | | carp_if | * +---------+ +---------+ * | | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * | +-------+ | * | | * V +-------+ | * +-----+ | | | * | scc |---->| softc | | * +-----+ | | | * | +-------+ | * | | * V +-------+ V * +-----+ | | +-----+ * | scc |---->| softc |<----| scc | * +-----+ | | +-----+ * +-------+ * * 3) Run netmsg_service_sync(), which will make sure that * ocif is no longer accessed (all network operations * are happened only in network threads). * 4) Free ocif -- only carp_if and scc are freed. * * - if_carp accessing: * The accessing code should cache the if_carp in a local temporary * variable and accessing the temporary variable along the code path * instead of accessing if_carp later on. */ #define CARP_IFNAME "carp" #define CARP_IS_RUNNING(ifp) \ (((ifp)->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING)) struct carp_softc; struct carp_vhaddr { uint32_t vha_flags; /* CARP_VHAF_ */ struct in_ifaddr *vha_ia; /* carp address */ struct in_ifaddr *vha_iaback; /* backing address */ TAILQ_ENTRY(carp_vhaddr) vha_link; }; TAILQ_HEAD(carp_vhaddr_list, carp_vhaddr); struct netmsg_carp { struct netmsg_base base; struct ifnet *nc_carpdev; struct carp_softc *nc_softc; void *nc_data; size_t nc_datalen; }; struct carp_softc { struct arpcom arpcom; struct ifnet *sc_carpdev; /* parent interface */ struct carp_vhaddr_list sc_vha_list; /* virtual addr list */ const struct in_ifaddr *sc_ia; /* primary iface address v4 */ struct ip_moptions sc_imo; #ifdef INET6 struct in6_ifaddr *sc_ia6; /* primary iface address v6 */ struct ip6_moptions sc_im6o; #endif /* INET6 */ enum { INIT = 0, BACKUP, MASTER } sc_state; boolean_t sc_dead; int sc_suppress; int sc_sendad_errors; #define CARP_SENDAD_MAX_ERRORS 3 int sc_sendad_success; #define CARP_SENDAD_MIN_SUCCESS 3 int sc_vhid; int sc_advskew; int sc_naddrs; /* actually used IPv4 vha */ int sc_naddrs6; int sc_advbase; /* seconds */ int sc_init_counter; uint64_t sc_counter; /* authentication */ #define CARP_HMAC_PAD 64 unsigned char sc_key[CARP_KEY_LEN]; unsigned char sc_pad[CARP_HMAC_PAD]; SHA1_CTX sc_sha1; struct callout sc_ad_tmo; /* advertisement timeout */ struct netmsg_carp sc_ad_msg; /* adv timeout netmsg */ struct callout sc_md_tmo; /* ip4 master down timeout */ struct callout sc_md6_tmo; /* ip6 master down timeout */ struct netmsg_carp sc_md_msg; /* master down timeout netmsg */ LIST_ENTRY(carp_softc) sc_next; /* Interface clue */ }; #define sc_if arpcom.ac_if struct carp_softc_container { TAILQ_ENTRY(carp_softc_container) scc_link; struct carp_softc *scc_softc; }; TAILQ_HEAD(carp_if, carp_softc_container); SYSCTL_DECL(_net_inet_carp); static int carp_opts[CARPCTL_MAXID] = { 0, 1, 0, 1, 0, 0 }; /* XXX for now */ SYSCTL_INT(_net_inet_carp, CARPCTL_ALLOW, allow, CTLFLAG_RW, &carp_opts[CARPCTL_ALLOW], 0, "Accept incoming CARP packets"); SYSCTL_INT(_net_inet_carp, CARPCTL_PREEMPT, preempt, CTLFLAG_RW, &carp_opts[CARPCTL_PREEMPT], 0, "high-priority backup preemption mode"); SYSCTL_INT(_net_inet_carp, CARPCTL_LOG, log, CTLFLAG_RW, &carp_opts[CARPCTL_LOG], 0, "log bad carp packets"); SYSCTL_INT(_net_inet_carp, CARPCTL_ARPBALANCE, arpbalance, CTLFLAG_RW, &carp_opts[CARPCTL_ARPBALANCE], 0, "balance arp responses"); static int carp_suppress_preempt = 0; SYSCTL_INT(_net_inet_carp, OID_AUTO, suppress_preempt, CTLFLAG_RD, &carp_suppress_preempt, 0, "Preemption is suppressed"); static struct carpstats carpstats; SYSCTL_STRUCT(_net_inet_carp, CARPCTL_STATS, stats, CTLFLAG_RW, &carpstats, carpstats, "CARP statistics (struct carpstats, netinet/ip_carp.h)"); #define CARP_LOG(...) do { \ if (carp_opts[CARPCTL_LOG] > 0) \ log(LOG_INFO, __VA_ARGS__); \ } while (0) #define CARP_DEBUG(...) do { \ if (carp_opts[CARPCTL_LOG] > 1) \ log(LOG_DEBUG, __VA_ARGS__); \ } while (0) static struct lwkt_token carp_listtok = LWKT_TOKEN_INITIALIZER(carp_list_token); static void carp_hmac_prepare(struct carp_softc *); static void carp_hmac_generate(struct carp_softc *, uint32_t *, unsigned char *); static int carp_hmac_verify(struct carp_softc *, uint32_t *, unsigned char *); static void carp_setroute(struct carp_softc *, int); static void carp_proto_input_c(struct carp_softc *, struct mbuf *, struct carp_header *, sa_family_t); static int carp_clone_create(struct if_clone *, int, caddr_t); static int carp_clone_destroy(struct ifnet *); static void carp_detach(struct carp_softc *, boolean_t, boolean_t); static void carp_prepare_ad(struct carp_softc *, struct carp_header *); static void carp_send_ad_all(void); static void carp_send_ad_timeout(void *); static void carp_send_ad(struct carp_softc *); static void carp_send_arp(struct carp_softc *); static void carp_master_down_timeout(void *); static void carp_master_down(struct carp_softc *); static void carp_setrun(struct carp_softc *, sa_family_t); static void carp_set_state(struct carp_softc *, int); static struct ifnet *carp_forus(struct carp_if *, const uint8_t *); static void carp_init(void *); static int carp_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *); static int carp_output(struct ifnet *, struct mbuf *, struct sockaddr *, struct rtentry *); static void carp_start(struct ifnet *, struct ifaltq_subque *); static void carp_multicast_cleanup(struct carp_softc *); static void carp_add_addr(struct carp_softc *, struct ifaddr *); static void carp_del_addr(struct carp_softc *, struct ifaddr *); static void carp_config_addr(struct carp_softc *, struct ifaddr *); static void carp_link_addrs(struct carp_softc *, struct ifnet *, struct ifaddr *); static void carp_unlink_addrs(struct carp_softc *, struct ifnet *, struct ifaddr *); static void carp_update_addrs(struct carp_softc *, struct ifaddr *); static int carp_config_vhaddr(struct carp_softc *, struct carp_vhaddr *, struct in_ifaddr *); static int carp_activate_vhaddr(struct carp_softc *, struct carp_vhaddr *, struct ifnet *, struct in_ifaddr *, int); static void carp_deactivate_vhaddr(struct carp_softc *, struct carp_vhaddr *, boolean_t); static int carp_addroute_vhaddr(struct carp_softc *, struct carp_vhaddr *); static void carp_delroute_vhaddr(struct carp_softc *, struct carp_vhaddr *, boolean_t); #ifdef foo static void carp_sc_state(struct carp_softc *); #endif #ifdef INET6 static void carp_send_na(struct carp_softc *); #ifdef notyet static int carp_set_addr6(struct carp_softc *, struct sockaddr_in6 *); static int carp_del_addr6(struct carp_softc *, struct sockaddr_in6 *); #endif static void carp_multicast6_cleanup(struct carp_softc *); #endif static void carp_stop(struct carp_softc *, boolean_t); static void carp_suspend(struct carp_softc *, boolean_t); static void carp_ioctl_stop(struct carp_softc *); static int carp_ioctl_setvh(struct carp_softc *, void *, struct ucred *); static int carp_ioctl_getvh(struct carp_softc *, void *, struct ucred *); static int carp_ioctl_getdevname(struct carp_softc *, struct ifdrv *); static int carp_ioctl_getvhaddr(struct carp_softc *, struct ifdrv *); static struct carp_if *carp_if_remove(struct carp_if *, struct carp_softc *); static struct carp_if *carp_if_insert(struct carp_if *, struct carp_softc *); static void carp_if_free(struct carp_if *); static void carp_ifaddr(void *, struct ifnet *, enum ifaddr_event, struct ifaddr *); static void carp_ifdetach(void *, struct ifnet *); static void carp_ifdetach_dispatch(netmsg_t); static void carp_clone_destroy_dispatch(netmsg_t); static void carp_init_dispatch(netmsg_t); static void carp_ioctl_stop_dispatch(netmsg_t); static void carp_ioctl_setvh_dispatch(netmsg_t); static void carp_ioctl_getvh_dispatch(netmsg_t); static void carp_ioctl_getdevname_dispatch(netmsg_t); static void carp_ioctl_getvhaddr_dispatch(netmsg_t); static void carp_send_ad_timeout_dispatch(netmsg_t); static void carp_master_down_timeout_dispatch(netmsg_t); static MALLOC_DEFINE(M_CARP, "CARP", "CARP interfaces"); static LIST_HEAD(, carp_softc) carpif_list; static struct if_clone carp_cloner = IF_CLONE_INITIALIZER(CARP_IFNAME, carp_clone_create, carp_clone_destroy, 0, IF_MAXUNIT); static uint8_t carp_etheraddr[ETHER_ADDR_LEN] = { 0, 0, 0x5e, 0, 1, 0 }; static eventhandler_tag carp_ifdetach_event; static eventhandler_tag carp_ifaddr_event; static __inline void carp_insert_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha_new) { struct carp_vhaddr *vha; u_long new_addr, addr; KKASSERT((vha_new->vha_flags & CARP_VHAF_ONLIST) == 0); /* * Virtual address list is sorted; smaller one first */ new_addr = ntohl(vha_new->vha_ia->ia_addr.sin_addr.s_addr); TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { addr = ntohl(vha->vha_ia->ia_addr.sin_addr.s_addr); if (addr > new_addr) break; } if (vha == NULL) TAILQ_INSERT_TAIL(&sc->sc_vha_list, vha_new, vha_link); else TAILQ_INSERT_BEFORE(vha, vha_new, vha_link); vha_new->vha_flags |= CARP_VHAF_ONLIST; } static __inline void carp_remove_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha) { KKASSERT(vha->vha_flags & CARP_VHAF_ONLIST); vha->vha_flags &= ~CARP_VHAF_ONLIST; TAILQ_REMOVE(&sc->sc_vha_list, vha, vha_link); } static void carp_hmac_prepare(struct carp_softc *sc) { uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT; uint8_t vhid = sc->sc_vhid & 0xff; int i; #ifdef INET6 struct ifaddr_container *ifac; struct in6_addr in6; #endif #ifdef INET struct carp_vhaddr *vha; #endif /* XXX: possible race here */ /* compute ipad from key */ bzero(sc->sc_pad, sizeof(sc->sc_pad)); bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key)); for (i = 0; i < sizeof(sc->sc_pad); i++) sc->sc_pad[i] ^= 0x36; /* precompute first part of inner hash */ SHA1Init(&sc->sc_sha1); SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad)); SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version)); SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type)); SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid)); #ifdef INET TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { SHA1Update(&sc->sc_sha1, (const uint8_t *)&vha->vha_ia->ia_addr.sin_addr, sizeof(struct in_addr)); } #endif /* INET */ #ifdef INET6 TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) { struct ifaddr *ifa = ifac->ifa; if (ifa->ifa_addr->sa_family == AF_INET6) { in6 = ifatoia6(ifa)->ia_addr.sin6_addr; in6_clearscope(&in6); SHA1Update(&sc->sc_sha1, (void *)&in6, sizeof(in6)); } } #endif /* INET6 */ /* convert ipad to opad */ for (i = 0; i < sizeof(sc->sc_pad); i++) sc->sc_pad[i] ^= 0x36 ^ 0x5c; } static void carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2], unsigned char md[20]) { SHA1_CTX sha1ctx; /* fetch first half of inner hash */ bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx)); SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter)); SHA1Final(md, &sha1ctx); /* outer hash */ SHA1Init(&sha1ctx); SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad)); SHA1Update(&sha1ctx, md, 20); SHA1Final(md, &sha1ctx); } static int carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2], unsigned char md[20]) { unsigned char md2[20]; carp_hmac_generate(sc, counter, md2); return (bcmp(md, md2, sizeof(md2))); } static void carp_setroute(struct carp_softc *sc, int cmd) { #ifdef INET6 struct ifaddr_container *ifac; #endif struct carp_vhaddr *vha; KKASSERT(cmd == RTM_DELETE || cmd == RTM_ADD); TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { if (vha->vha_iaback == NULL) continue; if (cmd == RTM_DELETE) carp_delroute_vhaddr(sc, vha, FALSE); else carp_addroute_vhaddr(sc, vha); } #ifdef INET6 TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) { struct ifaddr *ifa = ifac->ifa; if (ifa->ifa_addr->sa_family == AF_INET6) { if (cmd == RTM_ADD) in6_ifaddloop(ifa); else in6_ifremloop(ifa); } } #endif /* INET6 */ } static int carp_clone_create(struct if_clone *ifc, int unit, caddr_t param __unused) { struct carp_softc *sc; struct ifnet *ifp; sc = kmalloc(sizeof(*sc), M_CARP, M_WAITOK | M_ZERO); ifp = &sc->sc_if; sc->sc_suppress = 0; sc->sc_advbase = CARP_DFLTINTV; sc->sc_vhid = -1; /* required setting */ sc->sc_advskew = 0; sc->sc_init_counter = 1; sc->sc_naddrs = 0; sc->sc_naddrs6 = 0; TAILQ_INIT(&sc->sc_vha_list); #ifdef INET6 sc->sc_im6o.im6o_multicast_hlim = CARP_DFLTTL; #endif callout_init_mp(&sc->sc_ad_tmo); netmsg_init(&sc->sc_ad_msg.base, NULL, &netisr_adone_rport, MSGF_DROPABLE | MSGF_PRIORITY, carp_send_ad_timeout_dispatch); sc->sc_ad_msg.nc_softc = sc; callout_init_mp(&sc->sc_md_tmo); callout_init_mp(&sc->sc_md6_tmo); netmsg_init(&sc->sc_md_msg.base, NULL, &netisr_adone_rport, MSGF_DROPABLE | MSGF_PRIORITY, carp_master_down_timeout_dispatch); sc->sc_md_msg.nc_softc = sc; if_initname(ifp, CARP_IFNAME, unit); ifp->if_softc = sc; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = carp_init; ifp->if_ioctl = carp_ioctl; ifp->if_start = carp_start; ifq_set_maxlen(&ifp->if_snd, ifqmaxlen); ifq_set_ready(&ifp->if_snd); ether_ifattach(ifp, carp_etheraddr, NULL); ifp->if_type = IFT_CARP; ifp->if_output = carp_output; lwkt_gettoken(&carp_listtok); LIST_INSERT_HEAD(&carpif_list, sc, sc_next); lwkt_reltoken(&carp_listtok); return (0); } static void carp_clone_destroy_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; sc->sc_dead = TRUE; carp_detach(sc, TRUE, FALSE); callout_stop_sync(&sc->sc_ad_tmo); callout_stop_sync(&sc->sc_md_tmo); callout_stop_sync(&sc->sc_md6_tmo); crit_enter(); lwkt_dropmsg(&sc->sc_ad_msg.base.lmsg); lwkt_dropmsg(&sc->sc_md_msg.base.lmsg); crit_exit(); lwkt_replymsg(&cmsg->base.lmsg, 0); } static int carp_clone_destroy(struct ifnet *ifp) { struct carp_softc *sc = ifp->if_softc; struct netmsg_carp cmsg; bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_clone_destroy_dispatch); cmsg.nc_softc = sc; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); lwkt_gettoken(&carp_listtok); LIST_REMOVE(sc, sc_next); lwkt_reltoken(&carp_listtok); bpfdetach(ifp); if_detach(ifp); KASSERT(sc->sc_naddrs == 0, ("certain inet address is still active")); kfree(sc, M_CARP); return 0; } static struct carp_if * carp_if_remove(struct carp_if *ocif, struct carp_softc *sc) { struct carp_softc_container *oscc, *scc; struct carp_if *cif; int count = 0; #ifdef INVARIANTS int found = 0; #endif TAILQ_FOREACH(oscc, ocif, scc_link) { ++count; #ifdef INVARIANTS if (oscc->scc_softc == sc) found = 1; #endif } KASSERT(found, ("%s carp_softc is not on carp_if", __func__)); if (count == 1) { /* Last one is going to be unlinked */ return NULL; } cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO); TAILQ_INIT(cif); TAILQ_FOREACH(oscc, ocif, scc_link) { if (oscc->scc_softc == sc) continue; scc = kmalloc(sizeof(*scc), M_CARP, M_WAITOK | M_ZERO); scc->scc_softc = oscc->scc_softc; TAILQ_INSERT_TAIL(cif, scc, scc_link); } return cif; } static struct carp_if * carp_if_insert(struct carp_if *ocif, struct carp_softc *sc) { struct carp_softc_container *oscc; int onlist; onlist = 0; if (ocif != NULL) { TAILQ_FOREACH(oscc, ocif, scc_link) { if (oscc->scc_softc == sc) onlist = 1; } } #ifdef INVARIANTS if (sc->sc_carpdev != NULL) { KASSERT(onlist, ("%s is not on %s carp list", sc->sc_if.if_xname, sc->sc_carpdev->if_xname)); } else { KASSERT(!onlist, ("%s is already on carp list", sc->sc_if.if_xname)); } #endif if (!onlist) { struct carp_if *cif; struct carp_softc_container *new_scc, *scc; int inserted = 0; cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO); TAILQ_INIT(cif); new_scc = kmalloc(sizeof(*new_scc), M_CARP, M_WAITOK | M_ZERO); new_scc->scc_softc = sc; if (ocif != NULL) { TAILQ_FOREACH(oscc, ocif, scc_link) { if (!inserted && oscc->scc_softc->sc_vhid > sc->sc_vhid) { TAILQ_INSERT_TAIL(cif, new_scc, scc_link); inserted = 1; } scc = kmalloc(sizeof(*scc), M_CARP, M_WAITOK | M_ZERO); scc->scc_softc = oscc->scc_softc; TAILQ_INSERT_TAIL(cif, scc, scc_link); } } if (!inserted) TAILQ_INSERT_TAIL(cif, new_scc, scc_link); return cif; } else { return ocif; } } static void carp_if_free(struct carp_if *cif) { struct carp_softc_container *scc; while ((scc = TAILQ_FIRST(cif)) != NULL) { TAILQ_REMOVE(cif, scc, scc_link); kfree(scc, M_CARP); } kfree(cif, M_CARP); } static void carp_detach(struct carp_softc *sc, boolean_t detach, boolean_t del_iaback) { carp_suspend(sc, detach); carp_multicast_cleanup(sc); #ifdef INET6 carp_multicast6_cleanup(sc); #endif if (!sc->sc_dead && detach) { struct carp_vhaddr *vha; TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) carp_deactivate_vhaddr(sc, vha, del_iaback); KKASSERT(sc->sc_naddrs == 0); } if (sc->sc_carpdev != NULL) { struct ifnet *ifp = sc->sc_carpdev; struct carp_if *ocif = ifp->if_carp; ifp->if_carp = carp_if_remove(ocif, sc); KASSERT(ifp->if_carp != ocif, ("%s carp_if_remove failed", __func__)); sc->sc_carpdev = NULL; sc->sc_ia = NULL; /* * Make sure that all protocol threads see the * sc_carpdev and if_carp changes */ netmsg_service_sync(); if (ifp->if_carp == NULL) { /* * No more carp interfaces using * ifp as the backing interface, * move it out of promiscous mode. */ ifpromisc(ifp, 0); } /* * The old carp list could be safely free now, * since no one can access it. */ carp_if_free(ocif); } } static void carp_ifdetach_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct ifnet *ifp = cmsg->nc_carpdev; while (ifp->if_carp) { struct carp_softc_container *scc; scc = TAILQ_FIRST((struct carp_if *)(ifp->if_carp)); carp_detach(scc->scc_softc, TRUE, TRUE); } lwkt_replymsg(&cmsg->base.lmsg, 0); } /* Detach an interface from the carp. */ static void carp_ifdetach(void *arg __unused, struct ifnet *ifp) { struct netmsg_carp cmsg; ASSERT_IFNET_NOT_SERIALIZED_ALL(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ifdetach_dispatch); cmsg.nc_carpdev = ifp; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); } /* * process input packet. * we have rearranged checks order compared to the rfc, * but it seems more efficient this way or not possible otherwise. */ int carp_proto_input(struct mbuf **mp, int *offp, int proto) { struct mbuf *m = *mp; struct ip *ip = mtod(m, struct ip *); struct ifnet *ifp = m->m_pkthdr.rcvif; struct carp_header *ch; struct carp_softc *sc; int len, iphlen; iphlen = *offp; *mp = NULL; carpstats.carps_ipackets++; if (!carp_opts[CARPCTL_ALLOW]) { m_freem(m); goto back; } /* Check if received on a valid carp interface */ if (ifp->if_type != IFT_CARP) { carpstats.carps_badif++; CARP_LOG("carp_proto_input: packet received on non-carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } if (!CARP_IS_RUNNING(ifp)) { carpstats.carps_badif++; CARP_LOG("carp_proto_input: packet received on stopped carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } sc = ifp->if_softc; if (sc->sc_carpdev == NULL) { carpstats.carps_badif++; CARP_LOG("carp_proto_input: packet received on defunc carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) { carpstats.carps_badif++; CARP_LOG("carp_proto_input: non-mcast packet on " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } /* Verify that the IP TTL is CARP_DFLTTL. */ if (ip->ip_ttl != CARP_DFLTTL) { carpstats.carps_badttl++; CARP_LOG("carp_proto_input: received ttl %d != %d on %s\n", ip->ip_ttl, CARP_DFLTTL, ifp->if_xname); m_freem(m); goto back; } /* Minimal CARP packet size */ len = iphlen + sizeof(*ch); /* * Verify that the received packet length is * not less than the CARP header */ if (m->m_pkthdr.len < len) { carpstats.carps_badlen++; CARP_LOG("packet too short %d on %s\n", m->m_pkthdr.len, ifp->if_xname); m_freem(m); goto back; } /* Make sure that CARP header is contiguous */ if (len > m->m_len) { m = m_pullup(m, len); if (m == NULL) { carpstats.carps_hdrops++; CARP_LOG("carp_proto_input: m_pullup failed\n"); goto back; } ip = mtod(m, struct ip *); } ch = (struct carp_header *)((uint8_t *)ip + iphlen); /* Verify the CARP checksum */ if (in_cksum_skip(m, len, iphlen)) { carpstats.carps_badsum++; CARP_LOG("carp_proto_input: checksum failed on %s\n", ifp->if_xname); m_freem(m); goto back; } carp_proto_input_c(sc, m, ch, AF_INET); back: return(IPPROTO_DONE); } #ifdef INET6 int carp6_proto_input(struct mbuf **mp, int *offp, int proto) { struct mbuf *m = *mp; struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); struct ifnet *ifp = m->m_pkthdr.rcvif; struct carp_header *ch; struct carp_softc *sc; u_int len; carpstats.carps_ipackets6++; if (!carp_opts[CARPCTL_ALLOW]) { m_freem(m); goto back; } /* check if received on a valid carp interface */ if (ifp->if_type != IFT_CARP) { carpstats.carps_badif++; CARP_LOG("carp6_proto_input: packet received on non-carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } if (!CARP_IS_RUNNING(ifp)) { carpstats.carps_badif++; CARP_LOG("carp_proto_input: packet received on stopped carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } sc = ifp->if_softc; if (sc->sc_carpdev == NULL) { carpstats.carps_badif++; CARP_LOG("carp6_proto_input: packet received on defunc-carp " "interface: %s\n", ifp->if_xname); m_freem(m); goto back; } /* verify that the IP TTL is 255 */ if (ip6->ip6_hlim != CARP_DFLTTL) { carpstats.carps_badttl++; CARP_LOG("carp6_proto_input: received ttl %d != 255 on %s\n", ip6->ip6_hlim, ifp->if_xname); m_freem(m); goto back; } /* verify that we have a complete carp packet */ len = m->m_len; IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch)); if (ch == NULL) { carpstats.carps_badlen++; CARP_LOG("carp6_proto_input: packet size %u too small\n", len); goto back; } /* verify the CARP checksum */ if (in_cksum_range(m, 0, *offp, sizeof(*ch))) { carpstats.carps_badsum++; CARP_LOG("carp6_proto_input: checksum failed, on %s\n", ifp->if_xname); m_freem(m); goto back; } carp_proto_input_c(sc, m, ch, AF_INET6); back: return (IPPROTO_DONE); } #endif /* INET6 */ static void carp_proto_input_c(struct carp_softc *sc, struct mbuf *m, struct carp_header *ch, sa_family_t af) { struct ifnet *cifp; uint64_t tmp_counter; struct timeval sc_tv, ch_tv; if (sc->sc_vhid != ch->carp_vhid) { /* * CARP uses multicast, however, multicast packets * are tapped to all CARP interfaces on the physical * interface receiving the CARP packets, so we don't * update any stats here. */ m_freem(m); return; } cifp = &sc->sc_if; /* verify the CARP version. */ if (ch->carp_version != CARP_VERSION) { carpstats.carps_badver++; CARP_LOG("%s; invalid version %d\n", cifp->if_xname, ch->carp_version); m_freem(m); return; } /* verify the hash */ if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) { carpstats.carps_badauth++; CARP_LOG("%s: incorrect hash\n", cifp->if_xname); m_freem(m); return; } tmp_counter = ntohl(ch->carp_counter[0]); tmp_counter = tmp_counter<<32; tmp_counter += ntohl(ch->carp_counter[1]); /* XXX Replay protection goes here */ sc->sc_init_counter = 0; sc->sc_counter = tmp_counter; sc_tv.tv_sec = sc->sc_advbase; if (carp_suppress_preempt && sc->sc_advskew < 240) sc_tv.tv_usec = 240 * 1000000 / 256; else sc_tv.tv_usec = sc->sc_advskew * 1000000 / 256; ch_tv.tv_sec = ch->carp_advbase; ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256; switch (sc->sc_state) { case INIT: break; case MASTER: /* * If we receive an advertisement from a master who's going to * be more frequent than us, go into BACKUP state. */ if (timevalcmp(&sc_tv, &ch_tv, >) || timevalcmp(&sc_tv, &ch_tv, ==)) { callout_stop(&sc->sc_ad_tmo); CARP_DEBUG("%s: MASTER -> BACKUP " "(more frequent advertisement received)\n", cifp->if_xname); carp_set_state(sc, BACKUP); carp_setrun(sc, 0); carp_setroute(sc, RTM_DELETE); } break; case BACKUP: /* * If we're pre-empting masters who advertise slower than us, * and this one claims to be slower, treat him as down. */ if (carp_opts[CARPCTL_PREEMPT] && timevalcmp(&sc_tv, &ch_tv, <)) { CARP_DEBUG("%s: BACKUP -> MASTER " "(preempting a slower master)\n", cifp->if_xname); carp_master_down(sc); break; } /* * If the master is going to advertise at such a low frequency * that he's guaranteed to time out, we'd might as well just * treat him as timed out now. */ sc_tv.tv_sec = sc->sc_advbase * 3; if (timevalcmp(&sc_tv, &ch_tv, <)) { CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n", cifp->if_xname); carp_master_down(sc); break; } /* * Otherwise, we reset the counter and wait for the next * advertisement. */ carp_setrun(sc, af); break; } m_freem(m); } struct mbuf * carp_input(void *v, struct mbuf *m) { struct carp_if *cif = v; struct ether_header *eh; struct carp_softc_container *scc; struct ifnet *ifp; eh = mtod(m, struct ether_header *); ifp = carp_forus(cif, eh->ether_dhost); if (ifp != NULL) { ether_reinput_oncpu(ifp, m, REINPUT_RUNBPF); return NULL; } if ((m->m_flags & (M_BCAST | M_MCAST)) == 0) return m; /* * XXX Should really check the list of multicast addresses * for each CARP interface _before_ copying. */ TAILQ_FOREACH(scc, cif, scc_link) { struct carp_softc *sc = scc->scc_softc; struct mbuf *m0; if ((sc->sc_if.if_flags & IFF_UP) == 0) continue; m0 = m_dup(m, MB_DONTWAIT); if (m0 == NULL) continue; ether_reinput_oncpu(&sc->sc_if, m0, REINPUT_RUNBPF); } return m; } static void carp_prepare_ad(struct carp_softc *sc, struct carp_header *ch) { if (sc->sc_init_counter) { /* this could also be seconds since unix epoch */ sc->sc_counter = karc4random(); sc->sc_counter = sc->sc_counter << 32; sc->sc_counter += karc4random(); } else { sc->sc_counter++; } ch->carp_counter[0] = htonl((sc->sc_counter >> 32) & 0xffffffff); ch->carp_counter[1] = htonl(sc->sc_counter & 0xffffffff); carp_hmac_generate(sc, ch->carp_counter, ch->carp_md); } static void carp_send_ad_all(void) { struct carp_softc *sc; LIST_FOREACH(sc, &carpif_list, sc_next) { if (sc->sc_carpdev == NULL) continue; if (CARP_IS_RUNNING(&sc->sc_if) && sc->sc_state == MASTER) carp_send_ad(sc); } } static void carp_send_ad_timeout(void *xsc) { struct carp_softc *sc = xsc; struct netmsg_carp *cmsg = &sc->sc_ad_msg; KASSERT(mycpuid == 0, ("%s not on cpu0 but on cpu%d", __func__, mycpuid)); crit_enter(); if (cmsg->base.lmsg.ms_flags & MSGF_DONE) lwkt_sendmsg(netisr_cpuport(0), &cmsg->base.lmsg); crit_exit(); } static void carp_send_ad_timeout_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; /* Reply ASAP */ crit_enter(); lwkt_replymsg(&cmsg->base.lmsg, 0); crit_exit(); carp_send_ad(sc); } static void carp_send_ad(struct carp_softc *sc) { struct ifnet *cifp = &sc->sc_if; struct carp_header ch; struct timeval tv; struct carp_header *ch_ptr; struct mbuf *m; int len, advbase, advskew; if (!CARP_IS_RUNNING(cifp)) { /* Bow out */ advbase = 255; advskew = 255; } else { advbase = sc->sc_advbase; if (!carp_suppress_preempt || sc->sc_advskew > 240) advskew = sc->sc_advskew; else advskew = 240; tv.tv_sec = advbase; tv.tv_usec = advskew * 1000000 / 256; } ch.carp_version = CARP_VERSION; ch.carp_type = CARP_ADVERTISEMENT; ch.carp_vhid = sc->sc_vhid; ch.carp_advbase = advbase; ch.carp_advskew = advskew; ch.carp_authlen = 7; /* XXX DEFINE */ ch.carp_pad1 = 0; /* must be zero */ ch.carp_cksum = 0; #ifdef INET if (sc->sc_ia != NULL) { struct ip *ip; MGETHDR(m, MB_DONTWAIT, MT_HEADER); if (m == NULL) { IFNET_STAT_INC(cifp, oerrors, 1); carpstats.carps_onomem++; /* XXX maybe less ? */ if (advbase != 255 || advskew != 255) callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv), carp_send_ad_timeout, sc); return; } len = sizeof(*ip) + sizeof(ch); m->m_pkthdr.len = len; m->m_pkthdr.rcvif = NULL; m->m_len = len; MH_ALIGN(m, m->m_len); m->m_flags |= M_MCAST; ip = mtod(m, struct ip *); ip->ip_v = IPVERSION; ip->ip_hl = sizeof(*ip) >> 2; ip->ip_tos = IPTOS_LOWDELAY; ip->ip_len = len; ip->ip_id = ip_newid(); ip->ip_off = IP_DF; ip->ip_ttl = CARP_DFLTTL; ip->ip_p = IPPROTO_CARP; ip->ip_sum = 0; ip->ip_src = sc->sc_ia->ia_addr.sin_addr; ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP); ch_ptr = (struct carp_header *)(&ip[1]); bcopy(&ch, ch_ptr, sizeof(ch)); carp_prepare_ad(sc, ch_ptr); ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip)); getmicrotime(&cifp->if_lastchange); IFNET_STAT_INC(cifp, opackets, 1); IFNET_STAT_INC(cifp, obytes, len); carpstats.carps_opackets++; if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL)) { IFNET_STAT_INC(cifp, oerrors, 1); if (sc->sc_sendad_errors < INT_MAX) sc->sc_sendad_errors++; if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) { carp_suppress_preempt++; if (carp_suppress_preempt == 1) { carp_send_ad_all(); } } sc->sc_sendad_success = 0; } else { if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) { if (++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) { carp_suppress_preempt--; sc->sc_sendad_errors = 0; } } else { sc->sc_sendad_errors = 0; } } } #endif /* INET */ #ifdef INET6 if (sc->sc_ia6) { struct ip6_hdr *ip6; MGETHDR(m, MB_DONTWAIT, MT_HEADER); if (m == NULL) { IFNET_STAT_INC(cifp, oerrors, 1); carpstats.carps_onomem++; /* XXX maybe less ? */ if (advbase != 255 || advskew != 255) callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv), carp_send_ad_timeout, sc); return; } len = sizeof(*ip6) + sizeof(ch); m->m_pkthdr.len = len; m->m_pkthdr.rcvif = NULL; m->m_len = len; MH_ALIGN(m, m->m_len); m->m_flags |= M_MCAST; ip6 = mtod(m, struct ip6_hdr *); bzero(ip6, sizeof(*ip6)); ip6->ip6_vfc |= IPV6_VERSION; ip6->ip6_hlim = CARP_DFLTTL; ip6->ip6_nxt = IPPROTO_CARP; bcopy(&sc->sc_ia6->ia_addr.sin6_addr, &ip6->ip6_src, sizeof(struct in6_addr)); /* set the multicast destination */ ip6->ip6_dst.s6_addr16[0] = htons(0xff02); ip6->ip6_dst.s6_addr8[15] = 0x12; if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) { IFNET_STAT_INC(cifp, oerrors, 1); m_freem(m); CARP_LOG("%s: in6_setscope failed\n", __func__); return; } ch_ptr = (struct carp_header *)(&ip6[1]); bcopy(&ch, ch_ptr, sizeof(ch)); carp_prepare_ad(sc, ch_ptr); ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip6)); getmicrotime(&cifp->if_lastchange); IFNET_STAT_INC(cifp, opackets, 1); IFNET_STAT_INC(cifp, obytes, len); carpstats.carps_opackets6++; if (ip6_output(m, NULL, NULL, 0, &sc->sc_im6o, NULL, NULL)) { IFNET_STAT_INC(cifp, oerrors, 1); if (sc->sc_sendad_errors < INT_MAX) sc->sc_sendad_errors++; if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) { carp_suppress_preempt++; if (carp_suppress_preempt == 1) { carp_send_ad_all(); } } sc->sc_sendad_success = 0; } else { if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) { if (++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) { carp_suppress_preempt--; sc->sc_sendad_errors = 0; } } else { sc->sc_sendad_errors = 0; } } } #endif /* INET6 */ if (advbase != 255 || advskew != 255) callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv), carp_send_ad_timeout, sc); } /* * Broadcast a gratuitous ARP request containing * the virtual router MAC address for each IP address * associated with the virtual router. */ static void carp_send_arp(struct carp_softc *sc) { const struct carp_vhaddr *vha; TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { if (vha->vha_iaback == NULL) continue; arp_gratuitous(&sc->sc_if, &vha->vha_ia->ia_ifa); } } #ifdef INET6 static void carp_send_na(struct carp_softc *sc) { struct ifaddr_container *ifac; struct in6_addr *in6; static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT; TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) { struct ifaddr *ifa = ifac->ifa; if (ifa->ifa_addr->sa_family != AF_INET6) continue; in6 = &ifatoia6(ifa)->ia_addr.sin6_addr; nd6_na_output(sc->sc_carpdev, &mcast, in6, ND_NA_FLAG_OVERRIDE, 1, NULL); DELAY(1000); /* XXX */ } } #endif /* INET6 */ static __inline const struct carp_vhaddr * carp_find_addr(const struct carp_softc *sc, const struct in_addr *addr) { struct carp_vhaddr *vha; TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { if (vha->vha_iaback == NULL) continue; if (vha->vha_ia->ia_addr.sin_addr.s_addr == addr->s_addr) return vha; } return NULL; } #ifdef notyet static int carp_iamatch_balance(const struct carp_if *cif, const struct in_addr *itaddr, const struct in_addr *isaddr, uint8_t **enaddr) { const struct carp_softc *vh; int index, count = 0; /* * XXX proof of concept implementation. * We use the source ip to decide which virtual host should * handle the request. If we're master of that virtual host, * then we respond, otherwise, just drop the arp packet on * the floor. */ TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) { if (!CARP_IS_RUNNING(&vh->sc_if)) continue; if (carp_find_addr(vh, itaddr) != NULL) count++; } if (count == 0) return 0; /* this should be a hash, like pf_hash() */ index = ntohl(isaddr->s_addr) % count; count = 0; TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) { if (!CARP_IS_RUNNING(&vh->sc_if)) continue; if (carp_find_addr(vh, itaddr) == NULL) continue; if (count == index) { if (vh->sc_state == MASTER) { *enaddr = IF_LLADDR(&vh->sc_if); return 1; } else { return 0; } } count++; } return 0; } #endif int carp_iamatch(const struct in_ifaddr *ia) { const struct carp_softc *sc = ia->ia_ifp->if_softc; KASSERT(&curthread->td_msgport == netisr_cpuport(0), ("not in netisr0")); #ifdef notyet if (carp_opts[CARPCTL_ARPBALANCE]) return carp_iamatch_balance(cif, itaddr, isaddr, enaddr); #endif if (!CARP_IS_RUNNING(&sc->sc_if) || sc->sc_state != MASTER) return 0; return 1; } #ifdef INET6 struct ifaddr * carp_iamatch6(void *v, struct in6_addr *taddr) { #ifdef foo struct carp_if *cif = v; struct carp_softc *vh; TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) { struct ifaddr_container *ifac; TAILQ_FOREACH(ifac, &vh->sc_if.if_addrheads[mycpuid], ifa_link) { struct ifaddr *ifa = ifac->ifa; if (IN6_ARE_ADDR_EQUAL(taddr, &ifatoia6(ifa)->ia_addr.sin6_addr) && CARP_IS_RUNNING(&vh->sc_if) && vh->sc_state == MASTER) { return (ifa); } } } #endif return (NULL); } void * carp_macmatch6(void *v, struct mbuf *m, const struct in6_addr *taddr) { #ifdef foo struct m_tag *mtag; struct carp_if *cif = v; struct carp_softc *sc; TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) { struct ifaddr_container *ifac; TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) { struct ifaddr *ifa = ifac->ifa; if (IN6_ARE_ADDR_EQUAL(taddr, &ifatoia6(ifa)->ia_addr.sin6_addr) && CARP_IS_RUNNING(&sc->sc_if)) { struct ifnet *ifp = &sc->sc_if; mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct ifnet *), MB_DONTWAIT); if (mtag == NULL) { /* better a bit than nothing */ return (IF_LLADDR(ifp)); } bcopy(&ifp, (caddr_t)(mtag + 1), sizeof(struct ifnet *)); m_tag_prepend(m, mtag); return (IF_LLADDR(ifp)); } } } #endif return (NULL); } #endif static struct ifnet * carp_forus(struct carp_if *cif, const uint8_t *dhost) { struct carp_softc_container *scc; if (memcmp(dhost, carp_etheraddr, ETHER_ADDR_LEN - 1) != 0) return NULL; TAILQ_FOREACH(scc, cif, scc_link) { struct carp_softc *sc = scc->scc_softc; struct ifnet *ifp = &sc->sc_if; if (CARP_IS_RUNNING(ifp) && sc->sc_state == MASTER && !bcmp(dhost, IF_LLADDR(ifp), ETHER_ADDR_LEN)) return ifp; } return NULL; } static void carp_master_down_timeout(void *xsc) { struct carp_softc *sc = xsc; struct netmsg_carp *cmsg = &sc->sc_md_msg; KASSERT(mycpuid == 0, ("%s not on cpu0 but on cpu%d", __func__, mycpuid)); crit_enter(); if (cmsg->base.lmsg.ms_flags & MSGF_DONE) lwkt_sendmsg(netisr_cpuport(0), &cmsg->base.lmsg); crit_exit(); } static void carp_master_down_timeout_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; /* Reply ASAP */ crit_enter(); lwkt_replymsg(&cmsg->base.lmsg, 0); crit_exit(); CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n", sc->sc_if.if_xname); carp_master_down(sc); } static void carp_master_down(struct carp_softc *sc) { switch (sc->sc_state) { case INIT: kprintf("%s: master_down event in INIT state\n", sc->sc_if.if_xname); break; case MASTER: break; case BACKUP: carp_set_state(sc, MASTER); carp_send_ad(sc); carp_send_arp(sc); #ifdef INET6 carp_send_na(sc); #endif /* INET6 */ carp_setrun(sc, 0); carp_setroute(sc, RTM_ADD); break; } } /* * When in backup state, af indicates whether to reset the master down timer * for v4 or v6. If it's set to zero, reset the ones which are already pending. */ static void carp_setrun(struct carp_softc *sc, sa_family_t af) { struct ifnet *cifp = &sc->sc_if; struct timeval tv; if (sc->sc_carpdev == NULL) { carp_set_state(sc, INIT); return; } if ((cifp->if_flags & IFF_RUNNING) && sc->sc_vhid > 0 && (sc->sc_naddrs || sc->sc_naddrs6)) { /* Nothing */ } else { carp_setroute(sc, RTM_DELETE); return; } switch (sc->sc_state) { case INIT: if (carp_opts[CARPCTL_PREEMPT] && !carp_suppress_preempt) { carp_send_ad(sc); carp_send_arp(sc); #ifdef INET6 carp_send_na(sc); #endif /* INET6 */ CARP_DEBUG("%s: INIT -> MASTER (preempting)\n", cifp->if_xname); carp_set_state(sc, MASTER); carp_setroute(sc, RTM_ADD); } else { CARP_DEBUG("%s: INIT -> BACKUP\n", cifp->if_xname); carp_set_state(sc, BACKUP); carp_setroute(sc, RTM_DELETE); carp_setrun(sc, 0); } break; case BACKUP: callout_stop(&sc->sc_ad_tmo); tv.tv_sec = 3 * sc->sc_advbase; tv.tv_usec = sc->sc_advskew * 1000000 / 256; switch (af) { #ifdef INET case AF_INET: callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv), carp_master_down_timeout, sc); break; #endif /* INET */ #ifdef INET6 case AF_INET6: callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv), carp_master_down_timeout, sc); break; #endif /* INET6 */ default: if (sc->sc_naddrs) callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv), carp_master_down_timeout, sc); if (sc->sc_naddrs6) callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv), carp_master_down_timeout, sc); break; } break; case MASTER: tv.tv_sec = sc->sc_advbase; tv.tv_usec = sc->sc_advskew * 1000000 / 256; callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv), carp_send_ad_timeout, sc); break; } } static void carp_multicast_cleanup(struct carp_softc *sc) { struct ip_moptions *imo = &sc->sc_imo; if (imo->imo_num_memberships == 0) return; KKASSERT(imo->imo_num_memberships == 1); in_delmulti(imo->imo_membership[0]); imo->imo_membership[0] = NULL; imo->imo_num_memberships = 0; imo->imo_multicast_ifp = NULL; } #ifdef INET6 static void carp_multicast6_cleanup(struct carp_softc *sc) { struct ip6_moptions *im6o = &sc->sc_im6o; while (!LIST_EMPTY(&im6o->im6o_memberships)) { struct in6_multi_mship *imm = LIST_FIRST(&im6o->im6o_memberships); LIST_REMOVE(imm, i6mm_chain); in6_leavegroup(imm); } im6o->im6o_multicast_ifp = NULL; } #endif static void carp_ioctl_getvhaddr_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; const struct carp_vhaddr *vha; struct ifcarpvhaddr *carpa, *carpa0; int count, len, error = 0; count = 0; TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) ++count; if (cmsg->nc_datalen == 0) { cmsg->nc_datalen = count * sizeof(*carpa); goto back; } else if (count == 0 || cmsg->nc_datalen < sizeof(*carpa)) { cmsg->nc_datalen = 0; goto back; } len = min(cmsg->nc_datalen, sizeof(*carpa) * count); KKASSERT(len >= sizeof(*carpa)); carpa0 = carpa = kmalloc(len, M_TEMP, M_WAITOK | M_NULLOK | M_ZERO); if (carpa == NULL) { error = ENOMEM; goto back; } count = 0; TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { if (len < sizeof(*carpa)) break; carpa->carpa_flags = vha->vha_flags; carpa->carpa_addr.sin_family = AF_INET; carpa->carpa_addr.sin_addr = vha->vha_ia->ia_addr.sin_addr; carpa->carpa_baddr.sin_family = AF_INET; if (vha->vha_iaback == NULL) { carpa->carpa_baddr.sin_addr.s_addr = INADDR_ANY; } else { carpa->carpa_baddr.sin_addr = vha->vha_iaback->ia_addr.sin_addr; } ++carpa; ++count; len -= sizeof(*carpa); } cmsg->nc_datalen = sizeof(*carpa) * count; KKASSERT(cmsg->nc_datalen > 0); cmsg->nc_data = carpa0; back: lwkt_replymsg(&cmsg->base.lmsg, error); } static int carp_ioctl_getvhaddr(struct carp_softc *sc, struct ifdrv *ifd) { struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; int error; ASSERT_IFNET_SERIALIZED_ALL(ifp); ifnet_deserialize_all(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ioctl_getvhaddr_dispatch); cmsg.nc_softc = sc; cmsg.nc_datalen = ifd->ifd_len; error = lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); if (!error) { if (cmsg.nc_data != NULL) { error = copyout(cmsg.nc_data, ifd->ifd_data, cmsg.nc_datalen); kfree(cmsg.nc_data, M_TEMP); } ifd->ifd_len = cmsg.nc_datalen; } else { KASSERT(cmsg.nc_data == NULL, ("%s temp vhaddr is alloc upon error", __func__)); } ifnet_serialize_all(ifp); return error; } static int carp_config_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha, struct in_ifaddr *ia_del) { struct ifnet *ifp; struct in_ifaddr *ia_if; const struct in_ifaddr *ia_vha; struct in_ifaddr_container *iac; int own, ia_match_carpdev; KKASSERT(vha->vha_ia != NULL); ia_vha = vha->vha_ia; ia_if = NULL; own = 0; ia_match_carpdev = 0; TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) { struct in_ifaddr *ia = iac->ia; if (ia == ia_del) continue; if (ia->ia_ifp->if_type == IFT_CARP) continue; if ((ia->ia_ifp->if_flags & IFF_UP) == 0) continue; /* and, yeah, we need a multicast-capable iface too */ if ((ia->ia_ifp->if_flags & IFF_MULTICAST) == 0) continue; if (ia_vha->ia_subnetmask == ia->ia_subnetmask && ia_vha->ia_subnet == ia->ia_subnet) { if (ia_vha->ia_addr.sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr) own = 1; if (ia_if == NULL) { ia_if = ia; } else if (sc->sc_carpdev != NULL && sc->sc_carpdev == ia->ia_ifp) { ia_if = ia; if (ia_if->ia_flags & IFA_ROUTE) { /* * Address with prefix route * is prefered */ break; } ia_match_carpdev = 1; } else if (!ia_match_carpdev) { if (ia->ia_flags & IFA_ROUTE) { /* * Address with prefix route * is prefered over others. */ ia_if = ia; } } } } carp_deactivate_vhaddr(sc, vha, FALSE); if (!ia_if) return ENOENT; ifp = ia_if->ia_ifp; /* XXX Don't allow parent iface to be changed */ if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp) return EEXIST; return carp_activate_vhaddr(sc, vha, ifp, ia_if, own); } static void carp_add_addr(struct carp_softc *sc, struct ifaddr *carp_ifa) { struct carp_vhaddr *vha_new; struct in_ifaddr *carp_ia; #ifdef INVARIANTS struct carp_vhaddr *vha; #endif KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET); carp_ia = ifatoia(carp_ifa); #ifdef INVARIANTS TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) KKASSERT(vha->vha_ia != NULL && vha->vha_ia != carp_ia); #endif vha_new = kmalloc(sizeof(*vha_new), M_CARP, M_WAITOK | M_ZERO); vha_new->vha_ia = carp_ia; carp_insert_vhaddr(sc, vha_new); if (carp_config_vhaddr(sc, vha_new, NULL) != 0) { /* * If the above configuration fails, it may only mean * that the new address is problematic. However, the * carp(4) interface may already have several working * addresses. Since the expected behaviour of * SIOC[AS]IFADDR is to put the NIC into working state, * we try starting the state machine manually here with * the hope that the carp(4)'s previously working * addresses still could be brought up. */ carp_hmac_prepare(sc); carp_set_state(sc, INIT); carp_setrun(sc, 0); } } static void carp_del_addr(struct carp_softc *sc, struct ifaddr *carp_ifa) { struct carp_vhaddr *vha; struct in_ifaddr *carp_ia; KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET); carp_ia = ifatoia(carp_ifa); TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { KKASSERT(vha->vha_ia != NULL); if (vha->vha_ia == carp_ia) break; } KASSERT(vha != NULL, ("no corresponding vhaddr %p", carp_ifa)); /* * Remove the vhaddr from the list before deactivating * the vhaddr, so that the HMAC could be correctly * updated in carp_deactivate_vhaddr() */ carp_remove_vhaddr(sc, vha); carp_deactivate_vhaddr(sc, vha, FALSE); kfree(vha, M_CARP); } static void carp_config_addr(struct carp_softc *sc, struct ifaddr *carp_ifa) { struct carp_vhaddr *vha; struct in_ifaddr *carp_ia; KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET); carp_ia = ifatoia(carp_ifa); TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { KKASSERT(vha->vha_ia != NULL); if (vha->vha_ia == carp_ia) break; } KASSERT(vha != NULL, ("no corresponding vhaddr %p", carp_ifa)); /* Remove then reinsert, to keep the vhaddr list sorted */ carp_remove_vhaddr(sc, vha); carp_insert_vhaddr(sc, vha); if (carp_config_vhaddr(sc, vha, NULL) != 0) { /* See the comment in carp_add_addr() */ carp_hmac_prepare(sc); carp_set_state(sc, INIT); carp_setrun(sc, 0); } } #ifdef notyet #ifdef INET6 static int carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6) { struct ifnet *ifp; struct carp_if *cif; struct in6_ifaddr *ia, *ia_if; struct ip6_moptions *im6o = &sc->sc_im6o; struct in6_multi_mship *imm; struct in6_addr in6; int own, error; if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) { carp_setrun(sc, 0); return (0); } /* we have to do it by hands to check we won't match on us */ ia_if = NULL; own = 0; for (ia = in6_ifaddr; ia; ia = ia->ia_next) { int i; for (i = 0; i < 4; i++) { if ((sin6->sin6_addr.s6_addr32[i] & ia->ia_prefixmask.sin6_addr.s6_addr32[i]) != (ia->ia_addr.sin6_addr.s6_addr32[i] & ia->ia_prefixmask.sin6_addr.s6_addr32[i])) break; } /* and, yeah, we need a multicast-capable iface too */ if (ia->ia_ifp != &sc->sc_if && (ia->ia_ifp->if_flags & IFF_MULTICAST) && (i == 4)) { if (!ia_if) ia_if = ia; if (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr, &ia->ia_addr.sin6_addr)) own++; } } if (!ia_if) return (EADDRNOTAVAIL); ia = ia_if; ifp = ia->ia_ifp; if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0 || (im6o->im6o_multicast_ifp && im6o->im6o_multicast_ifp != ifp)) return (EADDRNOTAVAIL); if (!sc->sc_naddrs6) { im6o->im6o_multicast_ifp = ifp; /* join CARP multicast address */ bzero(&in6, sizeof(in6)); in6.s6_addr16[0] = htons(0xff02); in6.s6_addr8[15] = 0x12; if (in6_setscope(&in6, ifp, NULL) != 0) goto cleanup; if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL) goto cleanup; LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain); /* join solicited multicast address */ bzero(&in6, sizeof(in6)); in6.s6_addr16[0] = htons(0xff02); in6.s6_addr32[1] = 0; in6.s6_addr32[2] = htonl(1); in6.s6_addr32[3] = sin6->sin6_addr.s6_addr32[3]; in6.s6_addr8[12] = 0xff; if (in6_setscope(&in6, ifp, NULL) != 0) goto cleanup; if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL) goto cleanup; LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain); } #ifdef foo if (!ifp->if_carp) { cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO); if ((error = ifpromisc(ifp, 1))) { kfree(cif, M_CARP); goto cleanup; } TAILQ_INIT(&cif->vhif_vrs); ifp->if_carp = cif; } else { struct carp_softc *vr; cif = ifp->if_carp; TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) { if (vr != sc && vr->sc_vhid == sc->sc_vhid) { error = EINVAL; goto cleanup; } } } #endif sc->sc_ia6 = ia; sc->sc_carpdev = ifp; #ifdef foo { /* XXX prevent endless loop if already in queue */ struct carp_softc *vr, *after = NULL; int myself = 0; cif = ifp->if_carp; TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) { if (vr == sc) myself = 1; if (vr->sc_vhid < sc->sc_vhid) after = vr; } if (!myself) { /* We're trying to keep things in order */ if (after == NULL) TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list); else TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list); } } #endif sc->sc_naddrs6++; if (own) sc->sc_advskew = 0; carp_sc_state(sc); carp_setrun(sc, 0); return (0); cleanup: /* clean up multicast memberships */ if (!sc->sc_naddrs6) { while (!LIST_EMPTY(&im6o->im6o_memberships)) { imm = LIST_FIRST(&im6o->im6o_memberships); LIST_REMOVE(imm, i6mm_chain); in6_leavegroup(imm); } } return (error); } static int carp_del_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6) { int error = 0; if (!--sc->sc_naddrs6) { struct carp_if *cif = sc->sc_carpdev->if_carp; struct ip6_moptions *im6o = &sc->sc_im6o; callout_stop(&sc->sc_ad_tmo); sc->sc_vhid = -1; while (!LIST_EMPTY(&im6o->im6o_memberships)) { struct in6_multi_mship *imm = LIST_FIRST(&im6o->im6o_memberships); LIST_REMOVE(imm, i6mm_chain); in6_leavegroup(imm); } im6o->im6o_multicast_ifp = NULL; #ifdef foo TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list); if (TAILQ_EMPTY(&cif->vhif_vrs)) { sc->sc_carpdev->if_carp = NULL; kfree(cif, M_IFADDR); } #endif } return (error); } #endif /* INET6 */ #endif static int carp_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr, struct ucred *cr) { struct carp_softc *sc = ifp->if_softc; struct ifreq *ifr = (struct ifreq *)addr; struct ifdrv *ifd = (struct ifdrv *)addr; int error = 0; ASSERT_IFNET_SERIALIZED_ALL(ifp); switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if ((ifp->if_flags & IFF_RUNNING) == 0) carp_init(sc); } else if (ifp->if_flags & IFF_RUNNING) { carp_ioctl_stop(sc); } break; case SIOCSVH: error = carp_ioctl_setvh(sc, ifr->ifr_data, cr); break; case SIOCGVH: error = carp_ioctl_getvh(sc, ifr->ifr_data, cr); break; case SIOCGDRVSPEC: switch (ifd->ifd_cmd) { case CARPGDEVNAME: error = carp_ioctl_getdevname(sc, ifd); break; case CARPGVHADDR: error = carp_ioctl_getvhaddr(sc, ifd); break; default: error = EINVAL; break; } break; default: error = ether_ioctl(ifp, cmd, addr); break; } return error; } static void carp_ioctl_stop_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; carp_stop(sc, FALSE); lwkt_replymsg(&cmsg->base.lmsg, 0); } static void carp_ioctl_stop(struct carp_softc *sc) { struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; ASSERT_IFNET_SERIALIZED_ALL(ifp); ifnet_deserialize_all(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ioctl_stop_dispatch); cmsg.nc_softc = sc; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); ifnet_serialize_all(ifp); } static void carp_ioctl_setvh_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; struct ifnet *ifp = &sc->arpcom.ac_if; const struct carpreq *carpr = cmsg->nc_data; int error; error = 1; if ((ifp->if_flags & IFF_RUNNING) && sc->sc_state != INIT && carpr->carpr_state != sc->sc_state) { switch (carpr->carpr_state) { case BACKUP: callout_stop(&sc->sc_ad_tmo); carp_set_state(sc, BACKUP); carp_setrun(sc, 0); carp_setroute(sc, RTM_DELETE); break; case MASTER: carp_master_down(sc); break; default: break; } } if (carpr->carpr_vhid > 0) { if (carpr->carpr_vhid > 255) { error = EINVAL; goto back; } if (sc->sc_carpdev) { struct carp_if *cif = sc->sc_carpdev->if_carp; struct carp_softc_container *scc; TAILQ_FOREACH(scc, cif, scc_link) { struct carp_softc *vr = scc->scc_softc; if (vr != sc && vr->sc_vhid == carpr->carpr_vhid) { error = EEXIST; goto back; } } } sc->sc_vhid = carpr->carpr_vhid; IF_LLADDR(ifp)[5] = sc->sc_vhid; bcopy(IF_LLADDR(ifp), sc->arpcom.ac_enaddr, ETHER_ADDR_LEN); error--; } if (carpr->carpr_advbase > 0 || carpr->carpr_advskew > 0) { if (carpr->carpr_advskew >= 255) { error = EINVAL; goto back; } if (carpr->carpr_advbase > 255) { error = EINVAL; goto back; } sc->sc_advbase = carpr->carpr_advbase; sc->sc_advskew = carpr->carpr_advskew; error--; } bcopy(carpr->carpr_key, sc->sc_key, sizeof(sc->sc_key)); if (error > 0) { error = EINVAL; } else { error = 0; carp_setrun(sc, 0); } back: carp_hmac_prepare(sc); lwkt_replymsg(&cmsg->base.lmsg, error); } static int carp_ioctl_setvh(struct carp_softc *sc, void *udata, struct ucred *cr) { struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; struct carpreq carpr; int error; ASSERT_IFNET_SERIALIZED_ALL(ifp); ifnet_deserialize_all(ifp); error = priv_check_cred(cr, PRIV_ROOT, NULL_CRED_OKAY); if (error) goto back; error = copyin(udata, &carpr, sizeof(carpr)); if (error) goto back; bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ioctl_setvh_dispatch); cmsg.nc_softc = sc; cmsg.nc_data = &carpr; error = lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); back: ifnet_serialize_all(ifp); return error; } static void carp_ioctl_getvh_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; struct carpreq *carpr = cmsg->nc_data; carpr->carpr_state = sc->sc_state; carpr->carpr_vhid = sc->sc_vhid; carpr->carpr_advbase = sc->sc_advbase; carpr->carpr_advskew = sc->sc_advskew; bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key)); lwkt_replymsg(&cmsg->base.lmsg, 0); } static int carp_ioctl_getvh(struct carp_softc *sc, void *udata, struct ucred *cr) { struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; struct carpreq carpr; int error; ASSERT_IFNET_SERIALIZED_ALL(ifp); ifnet_deserialize_all(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ioctl_getvh_dispatch); cmsg.nc_softc = sc; cmsg.nc_data = &carpr; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); error = priv_check_cred(cr, PRIV_ROOT, NULL_CRED_OKAY); if (error) bzero(carpr.carpr_key, sizeof(carpr.carpr_key)); error = copyout(&carpr, udata, sizeof(carpr)); ifnet_serialize_all(ifp); return error; } static void carp_ioctl_getdevname_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; char *devname = cmsg->nc_data; bzero(devname, IFNAMSIZ); if (sc->sc_carpdev != NULL) strlcpy(devname, sc->sc_carpdev->if_xname, IFNAMSIZ); lwkt_replymsg(&cmsg->base.lmsg, 0); } static int carp_ioctl_getdevname(struct carp_softc *sc, struct ifdrv *ifd) { struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; char devname[IFNAMSIZ]; int error; ASSERT_IFNET_SERIALIZED_ALL(ifp); if (ifd->ifd_len != sizeof(devname)) return EINVAL; ifnet_deserialize_all(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_ioctl_getdevname_dispatch); cmsg.nc_softc = sc; cmsg.nc_data = devname; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); error = copyout(devname, ifd->ifd_data, sizeof(devname)); ifnet_serialize_all(ifp); return error; } static void carp_init_dispatch(netmsg_t msg) { struct netmsg_carp *cmsg = (struct netmsg_carp *)msg; struct carp_softc *sc = cmsg->nc_softc; sc->sc_if.if_flags |= IFF_RUNNING; carp_hmac_prepare(sc); carp_set_state(sc, INIT); carp_setrun(sc, 0); lwkt_replymsg(&cmsg->base.lmsg, 0); } static void carp_init(void *xsc) { struct carp_softc *sc = xsc; struct ifnet *ifp = &sc->arpcom.ac_if; struct netmsg_carp cmsg; ASSERT_IFNET_SERIALIZED_ALL(ifp); ifnet_deserialize_all(ifp); bzero(&cmsg, sizeof(cmsg)); netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0, carp_init_dispatch); cmsg.nc_softc = sc; lwkt_domsg(netisr_cpuport(0), &cmsg.base.lmsg, 0); ifnet_serialize_all(ifp); } static int carp_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst, struct rtentry *rt) { struct carp_softc *sc = ifp->if_softc; struct ifnet *carpdev; int error = 0; carpdev = sc->sc_carpdev; if (carpdev != NULL) { /* * NOTE: * CARP's ifp is passed to backing device's * if_output method. */ carpdev->if_output(ifp, m, dst, rt); } else { m_freem(m); error = ENETUNREACH; } return error; } /* * Start output on carp interface. This function should never be called. */ static void carp_start(struct ifnet *ifp, struct ifaltq_subque *ifsq __unused) { panic("%s: start called", ifp->if_xname); } static void carp_set_state(struct carp_softc *sc, int state) { struct ifnet *cifp = &sc->sc_if; if (sc->sc_state == state) return; sc->sc_state = state; switch (sc->sc_state) { case BACKUP: cifp->if_link_state = LINK_STATE_DOWN; break; case MASTER: cifp->if_link_state = LINK_STATE_UP; break; default: cifp->if_link_state = LINK_STATE_UNKNOWN; break; } rt_ifmsg(cifp); } void carp_group_demote_adj(struct ifnet *ifp, int adj) { struct ifg_list *ifgl; int *dm; TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) { if (!strcmp(ifgl->ifgl_group->ifg_group, IFG_ALL)) continue; dm = &ifgl->ifgl_group->ifg_carp_demoted; if (*dm + adj >= 0) *dm += adj; else *dm = 0; if (adj > 0 && *dm == 1) carp_send_ad_all(); CARP_LOG("%s demoted group %s to %d", ifp->if_xname, ifgl->ifgl_group->ifg_group, *dm); } } #ifdef foo void carp_carpdev_state(void *v) { struct carp_if *cif = v; struct carp_softc *sc; TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) carp_sc_state(sc); } static void carp_sc_state(struct carp_softc *sc) { if (!(sc->sc_carpdev->if_flags & IFF_UP)) { callout_stop(&sc->sc_ad_tmo); callout_stop(&sc->sc_md_tmo); callout_stop(&sc->sc_md6_tmo); carp_set_state(sc, INIT); carp_setrun(sc, 0); if (!sc->sc_suppress) { carp_suppress_preempt++; if (carp_suppress_preempt == 1) carp_send_ad_all(); } sc->sc_suppress = 1; } else { carp_set_state(sc, INIT); carp_setrun(sc, 0); if (sc->sc_suppress) carp_suppress_preempt--; sc->sc_suppress = 0; } } #endif static void carp_stop(struct carp_softc *sc, boolean_t detach) { sc->sc_if.if_flags &= ~IFF_RUNNING; callout_stop(&sc->sc_ad_tmo); callout_stop(&sc->sc_md_tmo); callout_stop(&sc->sc_md6_tmo); if (!detach && sc->sc_state == MASTER) carp_send_ad(sc); if (sc->sc_suppress) carp_suppress_preempt--; sc->sc_suppress = 0; if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) carp_suppress_preempt--; sc->sc_sendad_errors = 0; sc->sc_sendad_success = 0; carp_set_state(sc, INIT); carp_setrun(sc, 0); } static void carp_suspend(struct carp_softc *sc, boolean_t detach) { struct ifnet *cifp = &sc->sc_if; carp_stop(sc, detach); /* Retain the running state, if we are not dead yet */ if (!sc->sc_dead && (cifp->if_flags & IFF_UP)) cifp->if_flags |= IFF_RUNNING; } static int carp_activate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha, struct ifnet *ifp, struct in_ifaddr *ia_if, int own) { struct ip_moptions *imo = &sc->sc_imo; struct carp_if *ocif = ifp->if_carp; int error; KKASSERT(vha->vha_ia != NULL); KASSERT(ia_if != NULL, ("NULL backing address")); KASSERT(vha->vha_iaback == NULL, ("%p is already activated", vha)); KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0, ("inactive vhaddr %p is the address owner", vha)); KASSERT(sc->sc_carpdev == NULL || sc->sc_carpdev == ifp, ("%s is already on %s", sc->sc_if.if_xname, sc->sc_carpdev->if_xname)); if (ocif == NULL) { KASSERT(sc->sc_carpdev == NULL, ("%s is already on %s", sc->sc_if.if_xname, sc->sc_carpdev->if_xname)); error = ifpromisc(ifp, 1); if (error) return error; } else { struct carp_softc_container *scc; TAILQ_FOREACH(scc, ocif, scc_link) { struct carp_softc *vr = scc->scc_softc; if (vr != sc && vr->sc_vhid == sc->sc_vhid) return EINVAL; } } ifp->if_carp = carp_if_insert(ocif, sc); KASSERT(ifp->if_carp != NULL, ("%s carp_if_insert failed", __func__)); sc->sc_ia = ia_if; sc->sc_carpdev = ifp; /* * Make sure that all protocol threads see the sc_carpdev and * if_carp changes */ netmsg_service_sync(); if (ocif != NULL && ifp->if_carp != ocif) { /* * The old carp list could be safely free now, * since no one can access it. */ carp_if_free(ocif); } vha->vha_iaback = ia_if; sc->sc_naddrs++; if (own) { vha->vha_flags |= CARP_VHAF_OWNER; /* XXX save user configured advskew? */ sc->sc_advskew = 0; } carp_addroute_vhaddr(sc, vha); /* * Join the multicast group only after the backing interface * has been hooked with the CARP interface. */ KASSERT(imo->imo_multicast_ifp == NULL || imo->imo_multicast_ifp == &sc->sc_if, ("%s didn't leave mcast group on %s", sc->sc_if.if_xname, imo->imo_multicast_ifp->if_xname)); if (imo->imo_num_memberships == 0) { struct in_addr addr; addr.s_addr = htonl(INADDR_CARP_GROUP); imo->imo_membership[0] = in_addmulti(&addr, &sc->sc_if); if (imo->imo_membership[0] == NULL) { carp_deactivate_vhaddr(sc, vha, FALSE); return ENOBUFS; } imo->imo_num_memberships++; imo->imo_multicast_ifp = &sc->sc_if; imo->imo_multicast_ttl = CARP_DFLTTL; imo->imo_multicast_loop = 0; } carp_hmac_prepare(sc); carp_set_state(sc, INIT); carp_setrun(sc, 0); return 0; } static void carp_deactivate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha, boolean_t del_iaback) { KKASSERT(vha->vha_ia != NULL); carp_hmac_prepare(sc); if (vha->vha_iaback == NULL) { KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0, ("inactive vhaddr %p is the address owner", vha)); return; } vha->vha_flags &= ~CARP_VHAF_OWNER; carp_delroute_vhaddr(sc, vha, del_iaback); KKASSERT(sc->sc_naddrs > 0); vha->vha_iaback = NULL; sc->sc_naddrs--; if (!sc->sc_naddrs) { if (sc->sc_naddrs6) { carp_multicast_cleanup(sc); sc->sc_ia = NULL; } else { carp_detach(sc, FALSE, del_iaback); } } } static void carp_link_addrs(struct carp_softc *sc, struct ifnet *ifp, struct ifaddr *ifa_if) { struct carp_vhaddr *vha; struct in_ifaddr *ia_if; KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET); ia_if = ifatoia(ifa_if); /* * Test each inactive vhaddr against the newly added address. * If the newly added address could be the backing address, * then activate the matching vhaddr. */ TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { const struct in_ifaddr *ia; int own; if (vha->vha_iaback != NULL) continue; ia = vha->vha_ia; if (ia->ia_subnetmask != ia_if->ia_subnetmask || ia->ia_subnet != ia_if->ia_subnet) continue; own = 0; if (ia->ia_addr.sin_addr.s_addr == ia_if->ia_addr.sin_addr.s_addr) own = 1; carp_activate_vhaddr(sc, vha, ifp, ia_if, own); } } static void carp_unlink_addrs(struct carp_softc *sc, struct ifnet *ifp, struct ifaddr *ifa_if) { struct carp_vhaddr *vha; struct in_ifaddr *ia_if; KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET); ia_if = ifatoia(ifa_if); /* * Ad src address is deleted; set it to NULL. * Following loop will try pick up a new ad src address * if one of the vhaddr could retain its backing address. */ if (sc->sc_ia == ia_if) sc->sc_ia = NULL; /* * Test each active vhaddr against the deleted address. * If the deleted address is vhaddr address's backing * address, then deactivate the vhaddr. */ TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) { if (vha->vha_iaback == NULL) continue; if (vha->vha_iaback == ia_if) carp_deactivate_vhaddr(sc, vha, TRUE); else if (sc->sc_ia == NULL) sc->sc_ia = vha->vha_iaback; } } static void carp_update_addrs(struct carp_softc *sc, struct ifaddr *ifa_del) { struct carp_vhaddr *vha; KKASSERT(sc->sc_carpdev == NULL); TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) carp_config_vhaddr(sc, vha, ifatoia(ifa_del)); } static void carp_ifaddr(void *arg __unused, struct ifnet *ifp, enum ifaddr_event event, struct ifaddr *ifa) { struct carp_softc *sc; if (ifa->ifa_addr->sa_family != AF_INET) return; KASSERT(&curthread->td_msgport == netisr_cpuport(0), ("not in netisr0")); if (ifp->if_type == IFT_CARP) { /* * Address is changed on carp(4) interface */ switch (event) { case IFADDR_EVENT_ADD: carp_add_addr(ifp->if_softc, ifa); break; case IFADDR_EVENT_CHANGE: carp_config_addr(ifp->if_softc, ifa); break; case IFADDR_EVENT_DELETE: carp_del_addr(ifp->if_softc, ifa); break; } return; } /* * Address is changed on non-carp(4) interface */ if ((ifp->if_flags & IFF_MULTICAST) == 0) return; LIST_FOREACH(sc, &carpif_list, sc_next) { if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp) { /* Not the parent iface; skip */ continue; } switch (event) { case IFADDR_EVENT_ADD: carp_link_addrs(sc, ifp, ifa); break; case IFADDR_EVENT_DELETE: if (sc->sc_carpdev != NULL) { carp_unlink_addrs(sc, ifp, ifa); if (sc->sc_carpdev == NULL) { /* * We no longer have the parent * interface, however, certain * virtual addresses, which are * not used because they can't * match the previous parent * interface's addresses, may now * match different interface's * addresses. */ carp_update_addrs(sc, ifa); } } else { /* * The carp(4) interface didn't have a * parent iface, so it is not possible * that it will contain any address to * be unlinked. */ } break; case IFADDR_EVENT_CHANGE: if (sc->sc_carpdev == NULL) { /* * The carp(4) interface didn't have a * parent iface, so it is not possible * that it will contain any address to * be updated. */ carp_link_addrs(sc, ifp, ifa); } else { /* * First try breaking tie with the old * address. Then see whether we could * link certain vhaddr to the new address. * If that fails, i.e. carpdev is NULL, * we try a global update. * * NOTE: The above order is critical. */ carp_unlink_addrs(sc, ifp, ifa); carp_link_addrs(sc, ifp, ifa); if (sc->sc_carpdev == NULL) { /* * See the comment in the above * IFADDR_EVENT_DELETE block. */ carp_update_addrs(sc, NULL); } } break; } } } void carp_proto_ctlinput(netmsg_t msg) { int cmd = msg->ctlinput.nm_cmd; struct sockaddr *sa = msg->ctlinput.nm_arg; struct in_ifaddr_container *iac; TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) { struct in_ifaddr *ia = iac->ia; struct ifnet *ifp = ia->ia_ifp; if (ifp->if_type == IFT_CARP) continue; if (ia->ia_ifa.ifa_addr == sa) { if (cmd == PRC_IFDOWN) { carp_ifaddr(NULL, ifp, IFADDR_EVENT_DELETE, &ia->ia_ifa); } else if (cmd == PRC_IFUP) { carp_ifaddr(NULL, ifp, IFADDR_EVENT_ADD, &ia->ia_ifa); } break; } } lwkt_replymsg(&msg->lmsg, 0); } struct ifnet * carp_parent(struct ifnet *cifp) { struct carp_softc *sc; KKASSERT(cifp->if_type == IFT_CARP); sc = cifp->if_softc; return sc->sc_carpdev; } #define rtinitflags(x) \ (((x)->ia_ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) \ ? RTF_HOST : 0) static int carp_addroute_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha) { struct in_ifaddr *ia, *iaback; if (sc->sc_state != MASTER) return 0; ia = vha->vha_ia; KKASSERT(ia != NULL); iaback = vha->vha_iaback; KKASSERT(iaback != NULL); return rtchange(&iaback->ia_ifa, &ia->ia_ifa); } static void carp_delroute_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha, boolean_t del_iaback) { struct in_ifaddr *ia, *iaback; ia = vha->vha_ia; KKASSERT(ia != NULL); iaback = vha->vha_iaback; KKASSERT(iaback != NULL); if (!del_iaback && (iaback->ia_ifp->if_flags & IFF_UP)) { rtchange(&ia->ia_ifa, &iaback->ia_ifa); return; } rtinit(&ia->ia_ifa, RTM_DELETE, rtinitflags(ia)); in_ifadown_force(&ia->ia_ifa, 1); ia->ia_flags &= ~IFA_ROUTE; } static int carp_modevent(module_t mod, int type, void *data) { switch (type) { case MOD_LOAD: LIST_INIT(&carpif_list); carp_ifdetach_event = EVENTHANDLER_REGISTER(ifnet_detach_event, carp_ifdetach, NULL, EVENTHANDLER_PRI_ANY); carp_ifaddr_event = EVENTHANDLER_REGISTER(ifaddr_event, carp_ifaddr, NULL, EVENTHANDLER_PRI_FIRST); if_clone_attach(&carp_cloner); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(ifnet_detach_event, carp_ifdetach_event); EVENTHANDLER_DEREGISTER(ifaddr_event, carp_ifaddr_event); if_clone_detach(&carp_cloner); break; default: return (EINVAL); } return (0); } static moduledata_t carp_mod = { "carp", carp_modevent, 0 }; DECLARE_MODULE(carp, carp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
93391.c
// ---------------------------------------------------------------------------- // Test case for probabilistic symbolic simulation. add.c // Created by Ferhat Erata <[email protected]> on November 09, 2020. // Copyright (c) 2020 Yale University. All rights reserved. // ----------------------------------------------------------------------------- int add(int x) { //#pragma distribution parameter "x <- 5" #pragma distribution parameter "x <- DiscreteDistribution(supp = 0:100)" //#pragma distribution parameter "x <- Unif(0,100)" //#pragma distribution parameter "x <- Norm(100,10)" int result = x; for (int i = 0; i <= 1000; ++i) { result = result + i; } return result; }
871799.c
#include<stdio.h> #include<string.h> int main() { char inp[10],opt[10]; printf("Enter the encrypted code\n"); scanf("%s",inp); int i; for(i=0;i<strlen(inp);i++) { int alpha = inp[i]-97; printf("alpha = %d\n",alpha); int k = alpha - 4; if(k<0) k+=26; printf("k = %d\n",k); int j ; for(j=0;j<strlen(inp);j++) { opt[j]=(inp[j]-97-k)%26; if(opt[j]<0) opt[j]+=123; else opt[j]+=97; } int m; printf("for i = %d\n",i); for(m=0;m<strlen(inp);m++) printf("%c",opt[m]); printf("\n"); } return 0; }
890157.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memcmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lprior <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/22 15:29:11 by lprior #+# #+# */ /* Updated: 2017/09/25 14:18:29 by lprior ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int ft_memcmp(const void *s1, const void *s2, size_t n) { if (!n) return (0); while (--n && (*(unsigned char *)s1 == *(unsigned char *)s2)) { s1++; s2++; } return (*(unsigned char *)s1 - *(unsigned char *)s2); }
55219.c
/* * The authors of this software are Rob Pike and Ken Thompson. * Copyright (c) 2002 by Lucent Technologies. * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE * ANY REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */ #include <stdarg.h> #include <string.h> #include "plan9.h" #include "utf.h" int runestrcmp(const Rune *s1, const Rune *s2) { Rune c1, c2; for(;;) { c1 = *s1++; c2 = *s2++; if(c1 != c2) { if(c1 > c2) return 1; return -1; } if(c1 == 0) return 0; } }
522269.c
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0 /****************************************************************************** * * Module Name: exoparg2 - AML execution - opcodes with 2 arguments * * Copyright (C) 2000 - 2018, Intel Corp. * *****************************************************************************/ #include <acpi/acpi.h> #include "accommon.h" #include "acparser.h" #include "acinterp.h" #include "acevents.h" #include "amlcode.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME("exoparg2") /*! * Naming convention for AML interpreter execution routines. * * The routines that begin execution of AML opcodes are named with a common * convention based upon the number of arguments, the number of target operands, * and whether or not a value is returned: * * AcpiExOpcode_xA_yT_zR * * Where: * * xA - ARGUMENTS: The number of arguments (input operands) that are * required for this opcode type (1 through 6 args). * yT - TARGETS: The number of targets (output operands) that are required * for this opcode type (0, 1, or 2 targets). * zR - RETURN VALUE: Indicates whether this opcode type returns a value * as the function return (0 or 1). * * The AcpiExOpcode* functions are called via the Dispatcher component with * fully resolved operands. !*/ /******************************************************************************* * * FUNCTION: acpi_ex_opcode_2A_0T_0R * * PARAMETERS: walk_state - Current walk state * * RETURN: Status * * DESCRIPTION: Execute opcode with two arguments, no target, and no return * value. * * ALLOCATION: Deletes both operands * ******************************************************************************/ acpi_status acpi_ex_opcode_2A_0T_0R(struct acpi_walk_state *walk_state) { union acpi_operand_object **operand = &walk_state->operands[0]; struct acpi_namespace_node *node; u32 value; acpi_status status = AE_OK; ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_0T_0R, acpi_ps_get_opcode_name(walk_state->opcode)); /* Examine the opcode */ switch (walk_state->opcode) { case AML_NOTIFY_OP: /* Notify (notify_object, notify_value) */ /* The first operand is a namespace node */ node = (struct acpi_namespace_node *)operand[0]; /* Second value is the notify value */ value = (u32) operand[1]->integer.value; /* Are notifies allowed on this object? */ if (!acpi_ev_is_notify_object(node)) { ACPI_ERROR((AE_INFO, "Unexpected notify object type [%s]", acpi_ut_get_type_name(node->type))); status = AE_AML_OPERAND_TYPE; break; } /* * Dispatch the notify to the appropriate handler * NOTE: the request is queued for execution after this method * completes. The notify handlers are NOT invoked synchronously * from this thread -- because handlers may in turn run other * control methods. */ status = acpi_ev_queue_notify_request(node, value); break; default: ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X", walk_state->opcode)); status = AE_AML_BAD_OPCODE; } return_ACPI_STATUS(status); } /******************************************************************************* * * FUNCTION: acpi_ex_opcode_2A_2T_1R * * PARAMETERS: walk_state - Current walk state * * RETURN: Status * * DESCRIPTION: Execute a dyadic operator (2 operands) with 2 output targets * and one implicit return value. * ******************************************************************************/ acpi_status acpi_ex_opcode_2A_2T_1R(struct acpi_walk_state *walk_state) { union acpi_operand_object **operand = &walk_state->operands[0]; union acpi_operand_object *return_desc1 = NULL; union acpi_operand_object *return_desc2 = NULL; acpi_status status; ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_2T_1R, acpi_ps_get_opcode_name(walk_state->opcode)); /* Execute the opcode */ switch (walk_state->opcode) { case AML_DIVIDE_OP: /* Divide (Dividend, Divisor, remainder_result quotient_result) */ return_desc1 = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER); if (!return_desc1) { status = AE_NO_MEMORY; goto cleanup; } return_desc2 = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER); if (!return_desc2) { status = AE_NO_MEMORY; goto cleanup; } /* Quotient to return_desc1, remainder to return_desc2 */ status = acpi_ut_divide(operand[0]->integer.value, operand[1]->integer.value, &return_desc1->integer.value, &return_desc2->integer.value); if (ACPI_FAILURE(status)) { goto cleanup; } break; default: ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X", walk_state->opcode)); status = AE_AML_BAD_OPCODE; goto cleanup; } /* Store the results to the target reference operands */ status = acpi_ex_store(return_desc2, operand[2], walk_state); if (ACPI_FAILURE(status)) { goto cleanup; } status = acpi_ex_store(return_desc1, operand[3], walk_state); if (ACPI_FAILURE(status)) { goto cleanup; } cleanup: /* * Since the remainder is not returned indirectly, remove a reference to * it. Only the quotient is returned indirectly. */ acpi_ut_remove_reference(return_desc2); if (ACPI_FAILURE(status)) { /* Delete the return object */ acpi_ut_remove_reference(return_desc1); } /* Save return object (the remainder) on success */ else { walk_state->result_obj = return_desc1; } return_ACPI_STATUS(status); } /******************************************************************************* * * FUNCTION: acpi_ex_opcode_2A_1T_1R * * PARAMETERS: walk_state - Current walk state * * RETURN: Status * * DESCRIPTION: Execute opcode with two arguments, one target, and a return * value. * ******************************************************************************/ acpi_status acpi_ex_opcode_2A_1T_1R(struct acpi_walk_state *walk_state) { union acpi_operand_object **operand = &walk_state->operands[0]; union acpi_operand_object *return_desc = NULL; u64 index; acpi_status status = AE_OK; acpi_size length = 0; ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_1T_1R, acpi_ps_get_opcode_name(walk_state->opcode)); /* Execute the opcode */ if (walk_state->op_info->flags & AML_MATH) { /* All simple math opcodes (add, etc.) */ return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER); if (!return_desc) { status = AE_NO_MEMORY; goto cleanup; } return_desc->integer.value = acpi_ex_do_math_op(walk_state->opcode, operand[0]->integer.value, operand[1]->integer.value); goto store_result_to_target; } switch (walk_state->opcode) { case AML_MOD_OP: /* Mod (Dividend, Divisor, remainder_result (ACPI 2.0) */ return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER); if (!return_desc) { status = AE_NO_MEMORY; goto cleanup; } /* return_desc will contain the remainder */ status = acpi_ut_divide(operand[0]->integer.value, operand[1]->integer.value, NULL, &return_desc->integer.value); break; case AML_CONCATENATE_OP: /* Concatenate (Data1, Data2, Result) */ status = acpi_ex_do_concatenate(operand[0], operand[1], &return_desc, walk_state); break; case AML_TO_STRING_OP: /* to_string (Buffer, Length, Result) (ACPI 2.0) */ /* * Input object is guaranteed to be a buffer at this point (it may have * been converted.) Copy the raw buffer data to a new object of * type String. */ /* * Get the length of the new string. It is the smallest of: * 1) Length of the input buffer * 2) Max length as specified in the to_string operator * 3) Length of input buffer up to a zero byte (null terminator) * * NOTE: A length of zero is ok, and will create a zero-length, null * terminated string. */ while ((length < operand[0]->buffer.length) && (length < operand[1]->integer.value) && (operand[0]->buffer.pointer[length])) { length++; } /* Allocate a new string object */ return_desc = acpi_ut_create_string_object(length); if (!return_desc) { status = AE_NO_MEMORY; goto cleanup; } /* * Copy the raw buffer data with no transform. * (NULL terminated already) */ memcpy(return_desc->string.pointer, operand[0]->buffer.pointer, length); break; case AML_CONCATENATE_TEMPLATE_OP: /* concatenate_res_template (Buffer, Buffer, Result) (ACPI 2.0) */ status = acpi_ex_concat_template(operand[0], operand[1], &return_desc, walk_state); break; case AML_INDEX_OP: /* Index (Source Index Result) */ /* Create the internal return object */ return_desc = acpi_ut_create_internal_object(ACPI_TYPE_LOCAL_REFERENCE); if (!return_desc) { status = AE_NO_MEMORY; goto cleanup; } /* Initialize the Index reference object */ index = operand[1]->integer.value; return_desc->reference.value = (u32) index; return_desc->reference.class = ACPI_REFCLASS_INDEX; /* * At this point, the Source operand is a String, Buffer, or Package. * Verify that the index is within range. */ switch ((operand[0])->common.type) { case ACPI_TYPE_STRING: if (index >= operand[0]->string.length) { length = operand[0]->string.length; status = AE_AML_STRING_LIMIT; } return_desc->reference.target_type = ACPI_TYPE_BUFFER_FIELD; return_desc->reference.index_pointer = &(operand[0]->buffer.pointer[index]); break; case ACPI_TYPE_BUFFER: if (index >= operand[0]->buffer.length) { length = operand[0]->buffer.length; status = AE_AML_BUFFER_LIMIT; } return_desc->reference.target_type = ACPI_TYPE_BUFFER_FIELD; return_desc->reference.index_pointer = &(operand[0]->buffer.pointer[index]); break; case ACPI_TYPE_PACKAGE: if (index >= operand[0]->package.count) { length = operand[0]->package.count; status = AE_AML_PACKAGE_LIMIT; } return_desc->reference.target_type = ACPI_TYPE_PACKAGE; return_desc->reference.where = &operand[0]->package.elements[index]; break; default: ACPI_ERROR((AE_INFO, "Invalid object type: %X", (operand[0])->common.type)); status = AE_AML_INTERNAL; goto cleanup; } /* Failure means that the Index was beyond the end of the object */ if (ACPI_FAILURE(status)) { ACPI_EXCEPTION((AE_INFO, status, "Index (0x%X%8.8X) is beyond end of object (length 0x%X)", ACPI_FORMAT_UINT64(index), (u32)length)); goto cleanup; } /* * Save the target object and add a reference to it for the life * of the index */ return_desc->reference.object = operand[0]; acpi_ut_add_reference(operand[0]); /* Store the reference to the Target */ status = acpi_ex_store(return_desc, operand[2], walk_state); /* Return the reference */ walk_state->result_obj = return_desc; goto cleanup; default: ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X", walk_state->opcode)); status = AE_AML_BAD_OPCODE; break; } store_result_to_target: if (ACPI_SUCCESS(status)) { /* * Store the result of the operation (which is now in return_desc) into * the Target descriptor. */ status = acpi_ex_store(return_desc, operand[2], walk_state); if (ACPI_FAILURE(status)) { goto cleanup; } if (!walk_state->result_obj) { walk_state->result_obj = return_desc; } } cleanup: /* Delete return object on error */ if (ACPI_FAILURE(status)) { acpi_ut_remove_reference(return_desc); walk_state->result_obj = NULL; } return_ACPI_STATUS(status); } /******************************************************************************* * * FUNCTION: acpi_ex_opcode_2A_0T_1R * * PARAMETERS: walk_state - Current walk state * * RETURN: Status * * DESCRIPTION: Execute opcode with 2 arguments, no target, and a return value * ******************************************************************************/ acpi_status acpi_ex_opcode_2A_0T_1R(struct acpi_walk_state *walk_state) { union acpi_operand_object **operand = &walk_state->operands[0]; union acpi_operand_object *return_desc = NULL; acpi_status status = AE_OK; u8 logical_result = FALSE; ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_0T_1R, acpi_ps_get_opcode_name(walk_state->opcode)); /* Create the internal return object */ return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER); if (!return_desc) { status = AE_NO_MEMORY; goto cleanup; } /* Execute the Opcode */ if (walk_state->op_info->flags & AML_LOGICAL_NUMERIC) { /* logical_op (Operand0, Operand1) */ status = acpi_ex_do_logical_numeric_op(walk_state->opcode, operand[0]->integer. value, operand[1]->integer. value, &logical_result); goto store_logical_result; } else if (walk_state->op_info->flags & AML_LOGICAL) { /* logical_op (Operand0, Operand1) */ status = acpi_ex_do_logical_op(walk_state->opcode, operand[0], operand[1], &logical_result); goto store_logical_result; } switch (walk_state->opcode) { case AML_ACQUIRE_OP: /* Acquire (mutex_object, Timeout) */ status = acpi_ex_acquire_mutex(operand[1], operand[0], walk_state); if (status == AE_TIME) { logical_result = TRUE; /* TRUE = Acquire timed out */ status = AE_OK; } break; case AML_WAIT_OP: /* Wait (event_object, Timeout) */ status = acpi_ex_system_wait_event(operand[1], operand[0]); if (status == AE_TIME) { logical_result = TRUE; /* TRUE, Wait timed out */ status = AE_OK; } break; default: ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X", walk_state->opcode)); status = AE_AML_BAD_OPCODE; goto cleanup; } store_logical_result: /* * Set return value to according to logical_result. logical TRUE (all ones) * Default is FALSE (zero) */ if (logical_result) { return_desc->integer.value = ACPI_UINT64_MAX; } cleanup: /* Delete return object on error */ if (ACPI_FAILURE(status)) { acpi_ut_remove_reference(return_desc); } /* Save return object on success */ else { walk_state->result_obj = return_desc; } return_ACPI_STATUS(status); }
936960.c
// File created with /daemon/persistent_room_d.c #include <std.h> inherit "/cmds/avatar/avatar_room.c"; void create() { ::create(); set_name("crypt_hall_west1"); set_property("indoors",1); set_property("light",0); set_property("no teleport",1); set_terrain("ruins"); set_travel("decayed floor"); set_climate("temperate"); set_short("%^BOLD%^%^BLACK%^D%^RESET%^%^MAGENTA%^a%^BOLD%^%^BLACK%^rk%^WHITE%^e%^BLACK%^ned H%^RESET%^%^MAGENTA%^a%^BOLD%^%^BLACK%^llw%^WHITE%^a%^BLACK%^y%^RESET%^"); set_long("%^BOLD%^%^BLACK%^You stand in a darkened hallway of what must be a %^RESET%^%^MAGENTA%^c%^BLUE%^r%^MAGENTA%^ypt%^BOLD%^%^BLACK%^. The roof overhead is fractured with cracks and bits of stone drop ever" "y now and then. C%^WHITE%^o%^BLACK%^f%^WHITE%^f%^BLACK%^ins are tucked away in bricked openings that line the walls. A deep %^RESET%^%^MAGENTA%^gloom%^BOLD%^%^BLACK%^ permeates the claustrophobic pass" "ageways that seems more than meer %^BLUE%^darkness.%^RESET%^ " ); set_smell("default"," %^BOLD%^%^BLACK%^A m%^YELLOW%^u%^BOLD%^%^BLACK%^sky scent of %^GREEN%^mold%^BOLD%^%^BLACK%^ and ancient st%^WHITE%^o%^BOLD%^%^BLACK%^ne pervades the room.%^RESET%^"); set_listen("default","%^BOLD%^%^BLACK%^The only sound is that of your own footsteps.%^RESET%^"); set_exits(([ "east" : "/d/av_rooms/myrkul/crypt_clinic", "northwest" : "/d/av_rooms/myrkul/crypt_hall_west2", ])); }
303251.c
/* See LICENSE file for copyright and license details. */ #include "libred.h" #include <errno.h> #include <math.h> #include <string.h> #include <stdio.h> #if defined(__GNUC__) # pragma GCC diagnostic ignored "-Wfloat-equal" # pragma GCC diagnostic ignored "-Wunsuffixed-float-constants" #endif /** * Colour temperatures in CIE xy (xyY without Y) */ static struct xy {double x, y;} xy_table[] = { #include "10deg-xy.i" }; /* define ciexyy_to_srgb() and adjust_luma() */ #define LIBRED_COMPILING_PARSER #include "blackbody.c" int main(void) { long int temp = LIBRED_LOWEST_TEMPERATURE; size_t i, n = sizeof(xy_table) / sizeof(*xy_table); double r, g, b; for (i = 0; i < n; i++, temp += LIBRED_DELTA_TEMPERATURE) { if (temp == 6500) r = g = b = 1; else ciexyy_to_srgb(xy_table[i].x, xy_table[i].y, 1, &r, &g, &b); printf("{%a, %a, %a}%s\n", r, g, b, i + 1 == n ? "" : ","); } if (fflush(stdout) || ferror(stdout) || fclose(stdout)) { perror(NULL); return -1; } return 0; }
999122.c
/* * Helpers for lazy condition code handling * * Copyright (c) 2003-2005 Fabrice Bellard * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include "cpu.h" #include "exec/helper-proto.h" static uint32_t compute_all_flags(CPUSPARCState *env) { return env->psr & PSR_ICC; } static uint32_t compute_C_flags(CPUSPARCState *env) { return env->psr & PSR_CARRY; } static inline uint32_t get_NZ_icc(int32_t dst) { uint32_t ret = 0; if (dst == 0) { ret = PSR_ZERO; } else if (dst < 0) { ret = PSR_NEG; } return ret; } #ifdef TARGET_SPARC64 static uint32_t compute_all_flags_xcc(CPUSPARCState *env) { return env->xcc & PSR_ICC; } static uint32_t compute_C_flags_xcc(CPUSPARCState *env) { return env->xcc & PSR_CARRY; } static inline uint32_t get_NZ_xcc(target_long dst) { uint32_t ret = 0; if (!dst) { ret = PSR_ZERO; } else if (dst < 0) { ret = PSR_NEG; } return ret; } #endif static inline uint32_t get_V_div_icc(target_ulong src2) { uint32_t ret = 0; if (src2 != 0) { ret = PSR_OVF; } return ret; } static uint32_t compute_all_div(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_V_div_icc(CC_SRC2); return ret; } static uint32_t compute_C_div(CPUSPARCState *env) { return 0; } static inline uint32_t get_C_add_icc(uint32_t dst, uint32_t src1) { uint32_t ret = 0; if (dst < src1) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_C_addx_icc(uint32_t dst, uint32_t src1, uint32_t src2) { uint32_t ret = 0; if (((src1 & src2) | (~dst & (src1 | src2))) & (1U << 31)) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_V_add_icc(uint32_t dst, uint32_t src1, uint32_t src2) { uint32_t ret = 0; if (((src1 ^ src2 ^ -1) & (src1 ^ dst)) & (1U << 31)) { ret = PSR_OVF; } return ret; } #ifdef TARGET_SPARC64 static inline uint32_t get_C_add_xcc(target_ulong dst, target_ulong src1) { uint32_t ret = 0; if (dst < src1) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_C_addx_xcc(target_ulong dst, target_ulong src1, target_ulong src2) { uint32_t ret = 0; if (((src1 & src2) | (~dst & (src1 | src2))) & (1ULL << 63)) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_V_add_xcc(target_ulong dst, target_ulong src1, target_ulong src2) { uint32_t ret = 0; if (((src1 ^ src2 ^ -1) & (src1 ^ dst)) & (1ULL << 63)) { ret = PSR_OVF; } return ret; } static uint32_t compute_all_add_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_xcc(CC_DST); ret |= get_C_add_xcc(CC_DST, CC_SRC); ret |= get_V_add_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_add_xcc(CPUSPARCState *env) { return get_C_add_xcc(CC_DST, CC_SRC); } #endif static uint32_t compute_all_add(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_add_icc(CC_DST, CC_SRC); ret |= get_V_add_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_add(CPUSPARCState *env) { return get_C_add_icc(CC_DST, CC_SRC); } #ifdef TARGET_SPARC64 static uint32_t compute_all_addx_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_xcc(CC_DST); ret |= get_C_addx_xcc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_add_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_addx_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_C_addx_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } #endif static uint32_t compute_all_addx(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_addx_icc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_add_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_addx(CPUSPARCState *env) { uint32_t ret; ret = get_C_addx_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static inline uint32_t get_V_tag_icc(target_ulong src1, target_ulong src2) { uint32_t ret = 0; if ((src1 | src2) & 0x3) { ret = PSR_OVF; } return ret; } static uint32_t compute_all_tadd(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_add_icc(CC_DST, CC_SRC); ret |= get_V_add_icc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_tag_icc(CC_SRC, CC_SRC2); return ret; } static uint32_t compute_all_taddtv(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_add_icc(CC_DST, CC_SRC); return ret; } static inline uint32_t get_C_sub_icc(uint32_t src1, uint32_t src2) { uint32_t ret = 0; if (src1 < src2) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_C_subx_icc(uint32_t dst, uint32_t src1, uint32_t src2) { uint32_t ret = 0; if (((~src1 & src2) | (dst & (~src1 | src2))) & (1U << 31)) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_V_sub_icc(uint32_t dst, uint32_t src1, uint32_t src2) { uint32_t ret = 0; if (((src1 ^ src2) & (src1 ^ dst)) & (1U << 31)) { ret = PSR_OVF; } return ret; } #ifdef TARGET_SPARC64 static inline uint32_t get_C_sub_xcc(target_ulong src1, target_ulong src2) { uint32_t ret = 0; if (src1 < src2) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_C_subx_xcc(target_ulong dst, target_ulong src1, target_ulong src2) { uint32_t ret = 0; if (((~src1 & src2) | (dst & (~src1 | src2))) & (1ULL << 63)) { ret = PSR_CARRY; } return ret; } static inline uint32_t get_V_sub_xcc(target_ulong dst, target_ulong src1, target_ulong src2) { uint32_t ret = 0; if (((src1 ^ src2) & (src1 ^ dst)) & (1ULL << 63)) { ret = PSR_OVF; } return ret; } static uint32_t compute_all_sub_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_xcc(CC_DST); ret |= get_C_sub_xcc(CC_SRC, CC_SRC2); ret |= get_V_sub_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_sub_xcc(CPUSPARCState *env) { return get_C_sub_xcc(CC_SRC, CC_SRC2); } #endif static uint32_t compute_all_sub(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_sub_icc(CC_SRC, CC_SRC2); ret |= get_V_sub_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_sub(CPUSPARCState *env) { return get_C_sub_icc(CC_SRC, CC_SRC2); } #ifdef TARGET_SPARC64 static uint32_t compute_all_subx_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_xcc(CC_DST); ret |= get_C_subx_xcc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_sub_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_subx_xcc(CPUSPARCState *env) { uint32_t ret; ret = get_C_subx_xcc(CC_DST, CC_SRC, CC_SRC2); return ret; } #endif static uint32_t compute_all_subx(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_subx_icc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_sub_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_C_subx(CPUSPARCState *env) { uint32_t ret; ret = get_C_subx_icc(CC_DST, CC_SRC, CC_SRC2); return ret; } static uint32_t compute_all_tsub(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_sub_icc(CC_SRC, CC_SRC2); ret |= get_V_sub_icc(CC_DST, CC_SRC, CC_SRC2); ret |= get_V_tag_icc(CC_SRC, CC_SRC2); return ret; } static uint32_t compute_all_tsubtv(CPUSPARCState *env) { uint32_t ret; ret = get_NZ_icc(CC_DST); ret |= get_C_sub_icc(CC_SRC, CC_SRC2); return ret; } static uint32_t compute_all_logic(CPUSPARCState *env) { return get_NZ_icc(CC_DST); } static uint32_t compute_C_logic(CPUSPARCState *env) { return 0; } #ifdef TARGET_SPARC64 static uint32_t compute_all_logic_xcc(CPUSPARCState *env) { return get_NZ_xcc(CC_DST); } #endif typedef struct CCTable { uint32_t (*compute_all)(CPUSPARCState *env); /* return all the flags */ uint32_t (*compute_c)(CPUSPARCState *env); /* return the C flag */ } CCTable; static const CCTable icc_table[CC_OP_NB] = { /* CC_OP_DYNAMIC should never happen */ [CC_OP_FLAGS] = { compute_all_flags, compute_C_flags }, [CC_OP_DIV] = { compute_all_div, compute_C_div }, [CC_OP_ADD] = { compute_all_add, compute_C_add }, [CC_OP_ADDX] = { compute_all_addx, compute_C_addx }, [CC_OP_TADD] = { compute_all_tadd, compute_C_add }, [CC_OP_TADDTV] = { compute_all_taddtv, compute_C_add }, [CC_OP_SUB] = { compute_all_sub, compute_C_sub }, [CC_OP_SUBX] = { compute_all_subx, compute_C_subx }, [CC_OP_TSUB] = { compute_all_tsub, compute_C_sub }, [CC_OP_TSUBTV] = { compute_all_tsubtv, compute_C_sub }, [CC_OP_LOGIC] = { compute_all_logic, compute_C_logic }, }; #ifdef TARGET_SPARC64 static const CCTable xcc_table[CC_OP_NB] = { /* CC_OP_DYNAMIC should never happen */ [CC_OP_FLAGS] = { compute_all_flags_xcc, compute_C_flags_xcc }, [CC_OP_DIV] = { compute_all_logic_xcc, compute_C_logic }, [CC_OP_ADD] = { compute_all_add_xcc, compute_C_add_xcc }, [CC_OP_ADDX] = { compute_all_addx_xcc, compute_C_addx_xcc }, [CC_OP_TADD] = { compute_all_add_xcc, compute_C_add_xcc }, [CC_OP_TADDTV] = { compute_all_add_xcc, compute_C_add_xcc }, [CC_OP_SUB] = { compute_all_sub_xcc, compute_C_sub_xcc }, [CC_OP_SUBX] = { compute_all_subx_xcc, compute_C_subx_xcc }, [CC_OP_TSUB] = { compute_all_sub_xcc, compute_C_sub_xcc }, [CC_OP_TSUBTV] = { compute_all_sub_xcc, compute_C_sub_xcc }, [CC_OP_LOGIC] = { compute_all_logic_xcc, compute_C_logic }, }; #endif void helper_compute_psr(CPUSPARCState *env) { uint32_t new_psr; new_psr = icc_table[CC_OP].compute_all(env); env->psr = new_psr; #ifdef TARGET_SPARC64 new_psr = xcc_table[CC_OP].compute_all(env); env->xcc = new_psr; #endif CC_OP = CC_OP_FLAGS; } uint32_t helper_compute_C_icc(CPUSPARCState *env) { uint32_t ret; ret = icc_table[CC_OP].compute_c(env) >> PSR_CARRY_SHIFT; return ret; }
602984.c
#include "types.h" #include "stat.h" #include "user.h" char buf[512]; void wc(int fd, char *name) { int i, n; int l, w, c, inword; l = w = c = 0; inword = 0; while ((n = read(fd, buf, sizeof(buf))) > 0) { for (i = 0; i < n; i++) { c++; if (buf[i] == '\n') l++; if (strchr(" \r\t\n\v", buf[i])) inword = 0; else if (!inword) { w++; inword = 1; } } } if (n < 0) { printf(1, "wc: read error\n"); exit(); } printf(1, "%d %d %d %s\n", l, w, c, name); } int main(int argc, char *argv[]) { int fd, i; if (argc <= 1) { wc(0, ""); exit(); } for (i = 1; i < argc; i++) { if ((fd = open(argv[i], 0)) < 0) { printf(1, "wc: cannot open %s\n", argv[i]); exit(); } wc(fd, argv[i]); close(fd); } exit(); }
324517.c
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "runtime.h" #include "defs_GOOS_GOARCH.h" #include "os_GOOS.h" #define AT_NULL 0 #define AT_PLATFORM 15 // introduced in at least 2.6.11 #define AT_HWCAP 16 // introduced in at least 2.6.11 #define AT_RANDOM 25 // introduced in 2.6.29 #define HWCAP_VFP (1 << 6) // introduced in at least 2.6.11 #define HWCAP_VFPv3 (1 << 13) // introduced in 2.6.30 static uint32 runtime·randomNumber; uint8 runtime·armArch = 6; // we default to ARMv6 uint32 runtime·hwcap; // set by setup_auxv uint8 runtime·goarm; // set by 5l void runtime·checkgoarm(void) { if(runtime·goarm > 5 && !(runtime·hwcap & HWCAP_VFP)) { runtime·printf("runtime: this CPU has no floating point hardware, so it cannot run\n"); runtime·printf("this GOARM=%d binary. Recompile using GOARM=5.\n", runtime·goarm); runtime·exit(1); } if(runtime·goarm > 6 && !(runtime·hwcap & HWCAP_VFPv3)) { runtime·printf("runtime: this CPU has no VFPv3 floating point hardware, so it cannot run\n"); runtime·printf("this GOARM=%d binary. Recompile using GOARM=6.\n", runtime·goarm); runtime·exit(1); } } #pragma textflag 7 void runtime·setup_auxv(int32 argc, void *argv_list) { byte **argv; byte **envp; byte *rnd; uint32 *auxv; uint32 t; argv = &argv_list; // skip envp to get to ELF auxiliary vector. for(envp = &argv[argc+1]; *envp != nil; envp++) ; envp++; for(auxv=(uint32*)envp; auxv[0] != AT_NULL; auxv += 2) { switch(auxv[0]) { case AT_RANDOM: // kernel provided 16-byte worth of random data if(auxv[1]) { rnd = (byte*)auxv[1]; runtime·randomNumber = rnd[4] | rnd[5]<<8 | rnd[6]<<16 | rnd[7]<<24; } break; case AT_PLATFORM: // v5l, v6l, v7l if(auxv[1]) { t = *(uint8*)(auxv[1]+1); if(t >= '5' && t <= '7') runtime·armArch = t - '0'; } break; case AT_HWCAP: // CPU capability bit flags runtime·hwcap = auxv[1]; break; } } } #pragma textflag 7 int64 runtime·cputicks(void) { // Currently cputicks() is used in blocking profiler and to seed runtime·fastrand1(). // runtime·nanotime() is a poor approximation of CPU ticks that is enough for the profiler. // runtime·randomNumber provides better seeding of fastrand1. return runtime·nanotime() + runtime·randomNumber; }
164745.c
/***************************************************************************** Copyright (c) 1993-2000, Div. Medical and Biological Informatics, Deutsches Krebsforschungszentrum, Heidelberg, Germany All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - All advertising materials mentioning features or use of this software must display the following acknowledgement: "This product includes software developed by the Div. Medical and Biological Informatics, Deutsches Krebsforschungszentrum, Heidelberg, Germany." - Neither the name of the Deutsches Krebsforschungszentrum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE DIVISION MEDICAL AND BIOLOGICAL INFORMATICS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE DIVISION MEDICAL AND BIOLOGICAL INFORMATICS, THE DEUTSCHES KREBSFORSCHUNGSZENTRUM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Send comments and/or bug reports to: [email protected] *****************************************************************************/ /**@file * this function calculates the median of the image data */ /** @brief calculates the median of the image data * * @param pic_old pointer to the image * * @return median of the image data * * AUTHOR & DATE */ /* include files */ #include "mitkIpFuncP.h" mitkIpFloat8_t mitkIpFuncMedI ( mitkIpPicDescriptor *pic_old ); #ifndef DOXYGEN_IGNORE #ifndef lint static char *what = { "@(#)mitkIpFuncMedI\t\tDKFZ (Dept. MBI)\t"__DATE__ }; #endif /* ------------------------------------------------------------------- */ /* ** function mitkIpFuncMedI: */ /* ------------------------------------------------------------------- */ mitkIpFloat8_t mitkIpFuncMedI ( mitkIpPicDescriptor *pic_old ) { mitkIpFloat8_t max_gv; /* max. possible greyvalue */ mitkIpFloat8_t min_gv; /* min. possible greyvalue */ mitkIpUInt4_t *hist; /* greylevel histogram */ mitkIpUInt4_t size_hist; /* no. of elements in histogram */ mitkIpUInt4_t i; /* loop index */ mitkIpUInt4_t sum; /* sum of histogram elements */ mitkIpUInt4_t limit; /* */ mitkIpFloat4_t factor; mitkIpFloat8_t median; /* median of image data */ /* check whether image data are ok */ if ( _mitkIpFuncError ( pic_old ) != mitkIpFuncOK ) return ( mitkIpFuncERROR ); /* calculate max. and min. possible greyvalues */ if ( _mitkIpFuncExtT ( pic_old->type, pic_old->bpe, &min_gv, &max_gv ) == mitkIpFuncERROR ) { return ( mitkIpFuncERROR ); } /* calculate greylevel histogram */ mitkIpFuncHist ( pic_old, min_gv, max_gv, &hist, &size_hist ); if ( hist == 0 ) { return ( mitkIpFuncERROR ); } /* factor to calculate the greyvalue belonging to an histogram index */ if ( pic_old->type == mitkIpPicFloat ) factor = 0.001; else if ( pic_old->type == mitkIpPicInt || pic_old->type == mitkIpPicUInt ) factor = 1.; else { free ( hist ); _mitkIpFuncSetErrno ( mitkIpFuncTYPE_ERROR ); return ( mitkIpFuncERROR ); } /* find median */ limit = _mitkIpPicElements ( pic_old ) / 2; for ( i = 0, sum = 0; sum < limit; i++ ) sum = sum + hist [i]; median = i * factor - fabs ( min_gv ); free ( hist ); return ( median ); } #endif
143003.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" int16_t x2 = INT16_MAX; int32_t t1 = 77; volatile int32_t x11 = -1; volatile int8_t x20 = -1; int16_t x34 = -242; volatile int32_t t8 = -278164; volatile int32_t x43 = INT32_MIN; static volatile int32_t t9 = 1; int16_t x46 = 87; int64_t x65 = -1LL; int16_t x68 = INT16_MIN; uint64_t x75 = 2051083290543989140LLU; int64_t x79 = -13577059224924LL; int32_t x84 = -19511318; int16_t x87 = 0; static volatile int16_t x88 = -1; int32_t x97 = INT32_MAX; int8_t x98 = -1; int64_t x100 = 256LL; int32_t t22 = 18473; int64_t x101 = -1LL; int32_t x103 = INT32_MAX; uint64_t x109 = UINT64_MAX; int64_t x110 = 1LL; volatile int32_t t25 = 158210; int32_t x113 = INT32_MIN; static int32_t t26 = 4692; static uint16_t x119 = 10U; uint16_t x122 = UINT16_MAX; int64_t x126 = INT64_MIN; int64_t x131 = INT64_MIN; int8_t x133 = -1; int32_t x145 = INT32_MIN; int64_t x146 = 134262LL; int32_t t35 = -1; static int16_t x153 = INT16_MAX; uint8_t x167 = 36U; static int8_t x168 = INT8_MIN; int32_t x170 = 3; volatile uint8_t x172 = 48U; static volatile int32_t t40 = -522; int16_t x192 = -1; int16_t x194 = -1; uint16_t x195 = UINT16_MAX; int32_t t46 = -481283; int32_t t47 = 0; volatile int64_t x205 = -1LL; int64_t x206 = 2688866575429831605LL; int32_t x207 = INT32_MIN; volatile int8_t x216 = -3; static volatile uint16_t x221 = 1U; volatile int16_t x223 = INT16_MAX; uint8_t x226 = 3U; static int64_t x236 = 15342825440509LL; int8_t x237 = INT8_MIN; int8_t x248 = INT8_MIN; int64_t x252 = INT64_MIN; int8_t x257 = -1; uint16_t x260 = 2824U; uint16_t x261 = UINT16_MAX; static uint64_t x262 = UINT64_MAX; int32_t t63 = -3192373; int32_t x278 = 9; static int32_t t66 = 38300244; static uint64_t x281 = 81760LLU; int8_t x288 = -1; static int64_t x290 = INT64_MAX; static uint16_t x292 = UINT16_MAX; uint16_t x293 = UINT16_MAX; uint8_t x294 = 6U; static int64_t x295 = -16744725LL; int8_t x303 = INT8_MIN; static uint32_t x306 = 59106U; int32_t x307 = 792584; uint64_t x308 = UINT64_MAX; uint64_t x314 = 30444171221LLU; volatile int8_t x315 = -21; int32_t t75 = -937; static volatile uint32_t x318 = 793774606U; int64_t x324 = -4502094180LL; int32_t t78 = 562654; uint32_t x330 = 1788104U; int8_t x341 = INT8_MAX; static int32_t t82 = 9; volatile int8_t x345 = -1; uint8_t x346 = 4U; uint64_t x347 = 127365106336535LLU; uint8_t x351 = UINT8_MAX; volatile int32_t t86 = -32436; static int8_t x371 = INT8_MIN; uint32_t x377 = UINT32_MAX; int8_t x378 = INT8_MAX; int8_t x382 = INT8_MAX; int16_t x386 = INT16_MAX; static int32_t x387 = 4019210; volatile int32_t t93 = -6475055; int64_t x390 = INT64_MIN; int32_t t94 = 1; int64_t x395 = 24193485214987LL; int16_t x396 = -12492; volatile int32_t x400 = INT32_MIN; int8_t x414 = INT8_MIN; int32_t x420 = INT32_MAX; int32_t t102 = 531; uint8_t x425 = 7U; static int64_t x427 = INT64_MIN; uint32_t x428 = 22978U; uint32_t x436 = 3284U; volatile uint16_t x440 = UINT16_MAX; static int16_t x443 = 1; uint16_t x444 = UINT16_MAX; int32_t t106 = -891874434; uint32_t x445 = UINT32_MAX; uint64_t x450 = 1369373225LLU; static int8_t x452 = 50; int64_t x455 = INT64_MIN; static uint64_t x456 = 854879668380811LLU; volatile int64_t x458 = -2080903855598LL; uint16_t x468 = 214U; static int16_t x469 = 1611; int16_t x471 = -1; volatile int8_t x473 = INT8_MAX; uint16_t x475 = 35U; uint16_t x476 = 56U; int8_t x486 = INT8_MIN; int32_t t117 = -8356738; static volatile int64_t x492 = -1LL; int8_t x494 = INT8_MAX; int64_t x496 = INT64_MAX; int8_t x497 = -1; int8_t x504 = 1; static volatile int16_t x512 = INT16_MIN; int32_t t123 = -2620743; volatile uint64_t x525 = 29LLU; static int16_t x529 = 93; int32_t t127 = 10666; int16_t x541 = -1; int32_t t130 = -411090; uint16_t x545 = UINT16_MAX; uint16_t x546 = 4097U; int8_t x548 = INT8_MAX; static uint16_t x550 = 1297U; int64_t x554 = INT64_MIN; static volatile int32_t x557 = 459; int64_t x558 = 459383030LL; int16_t x562 = 15469; int8_t x566 = INT8_MAX; int8_t x571 = INT8_MAX; volatile int32_t t137 = -1519; volatile int32_t x574 = INT32_MIN; static int8_t x576 = INT8_MAX; int32_t t138 = -4454; int32_t x578 = -450; int8_t x581 = -1; volatile uint8_t x583 = UINT8_MAX; uint8_t x589 = 0U; static int32_t t143 = 3187852; int32_t x608 = -1156; int16_t x628 = -14; int16_t x634 = INT16_MIN; int32_t x636 = INT32_MIN; volatile int16_t x641 = -39; volatile int32_t t155 = -839418; int8_t x653 = 3; uint8_t x654 = 4U; int16_t x655 = 122; int8_t x663 = -1; int32_t t158 = -3694691; int32_t x666 = -1; int32_t t159 = -29; int16_t x684 = INT16_MIN; volatile uint64_t x692 = UINT64_MAX; uint32_t x693 = 564970U; uint64_t x694 = UINT64_MAX; int32_t x696 = -1; static volatile int32_t t166 = 15458; volatile int64_t x699 = 608384119352LL; int64_t x700 = INT64_MIN; static volatile int32_t t167 = -74; int32_t x704 = INT32_MIN; uint16_t x707 = 2187U; int32_t t169 = 30; int8_t x709 = 0; uint8_t x711 = 11U; int32_t x713 = INT32_MIN; volatile int32_t x719 = -80; int64_t x727 = 33317120431085485LL; int32_t x734 = 1; volatile int8_t x745 = INT8_MIN; int8_t x750 = 14; volatile uint64_t x752 = 54925474704LLU; static volatile int8_t x753 = 0; int64_t x759 = -1LL; int32_t t181 = 1; volatile int32_t t182 = -1; int16_t x777 = INT16_MAX; static int64_t x781 = -4139729513066210LL; uint32_t x788 = 1525U; static volatile int32_t t188 = 59; int32_t t190 = 42201842; volatile int64_t x797 = INT64_MIN; volatile uint16_t x802 = UINT16_MAX; uint16_t x812 = 0U; static uint32_t x816 = 11U; int8_t x821 = INT8_MIN; volatile uint16_t x824 = 926U; uint16_t x832 = UINT16_MAX; static uint8_t x835 = 99U; void f0(void) { int16_t x1 = -1; uint32_t x3 = 3843351U; int8_t x4 = -3; volatile int32_t t0 = 6; t0 = ((x1/x2)==(x3^x4)); if (t0 != 0) { NG(); } else { ; } } void f1(void) { int16_t x5 = -5120; static int64_t x6 = INT64_MIN; uint8_t x7 = 1U; uint8_t x8 = 2U; t1 = ((x5/x6)==(x7^x8)); if (t1 != 0) { NG(); } else { ; } } void f2(void) { int16_t x9 = INT16_MIN; int8_t x10 = 14; static int32_t x12 = INT32_MAX; int32_t t2 = 2025869; t2 = ((x9/x10)==(x11^x12)); if (t2 != 0) { NG(); } else { ; } } void f3(void) { static volatile int64_t x17 = -54747LL; uint32_t x18 = 8766U; int16_t x19 = -1; int32_t t3 = 14; t3 = ((x17/x18)==(x19^x20)); if (t3 != 0) { NG(); } else { ; } } void f4(void) { int64_t x21 = INT64_MAX; int64_t x22 = -1LL; uint64_t x23 = 29717LLU; volatile int8_t x24 = 3; static volatile int32_t t4 = 142; t4 = ((x21/x22)==(x23^x24)); if (t4 != 0) { NG(); } else { ; } } void f5(void) { uint16_t x25 = 2U; int64_t x26 = -1LL; static int16_t x27 = -1; static volatile int16_t x28 = INT16_MIN; static volatile int32_t t5 = 47; t5 = ((x25/x26)==(x27^x28)); if (t5 != 0) { NG(); } else { ; } } void f6(void) { uint16_t x29 = 19477U; static int8_t x30 = -2; int64_t x31 = -1LL; volatile int8_t x32 = -1; int32_t t6 = 236472788; t6 = ((x29/x30)==(x31^x32)); if (t6 != 0) { NG(); } else { ; } } void f7(void) { volatile uint8_t x33 = UINT8_MAX; uint8_t x35 = 5U; int32_t x36 = 12; static int32_t t7 = 1; t7 = ((x33/x34)==(x35^x36)); if (t7 != 0) { NG(); } else { ; } } void f8(void) { int64_t x37 = INT64_MAX; uint16_t x38 = 63U; int16_t x39 = INT16_MIN; int64_t x40 = -1LL; t8 = ((x37/x38)==(x39^x40)); if (t8 != 0) { NG(); } else { ; } } void f9(void) { static int64_t x41 = INT64_MAX; uint16_t x42 = UINT16_MAX; int8_t x44 = -6; t9 = ((x41/x42)==(x43^x44)); if (t9 != 0) { NG(); } else { ; } } void f10(void) { static int8_t x45 = -50; uint32_t x47 = 1101224055U; static int64_t x48 = -1LL; int32_t t10 = -31934902; t10 = ((x45/x46)==(x47^x48)); if (t10 != 0) { NG(); } else { ; } } void f11(void) { volatile uint32_t x49 = 54113932U; volatile int64_t x50 = -5639LL; int8_t x51 = INT8_MIN; uint8_t x52 = UINT8_MAX; int32_t t11 = 7; t11 = ((x49/x50)==(x51^x52)); if (t11 != 0) { NG(); } else { ; } } void f12(void) { static int16_t x53 = INT16_MIN; static uint32_t x54 = UINT32_MAX; static int64_t x55 = -1LL; uint64_t x56 = 485LLU; int32_t t12 = 3; t12 = ((x53/x54)==(x55^x56)); if (t12 != 0) { NG(); } else { ; } } void f13(void) { int16_t x57 = INT16_MIN; int16_t x58 = INT16_MIN; int16_t x59 = -1; int16_t x60 = INT16_MAX; int32_t t13 = 1; t13 = ((x57/x58)==(x59^x60)); if (t13 != 0) { NG(); } else { ; } } void f14(void) { volatile int16_t x66 = INT16_MIN; int16_t x67 = -1; volatile int32_t t14 = 7; t14 = ((x65/x66)==(x67^x68)); if (t14 != 0) { NG(); } else { ; } } void f15(void) { static int32_t x69 = INT32_MIN; static uint8_t x70 = 1U; int32_t x71 = INT32_MAX; uint64_t x72 = 13473699335LLU; int32_t t15 = 1; t15 = ((x69/x70)==(x71^x72)); if (t15 != 0) { NG(); } else { ; } } void f16(void) { static volatile int64_t x73 = INT64_MIN; static volatile int32_t x74 = -125920439; static int32_t x76 = INT32_MAX; static volatile int32_t t16 = 2; t16 = ((x73/x74)==(x75^x76)); if (t16 != 0) { NG(); } else { ; } } void f17(void) { int32_t x77 = -1016; static uint16_t x78 = 3526U; int32_t x80 = INT32_MIN; static volatile int32_t t17 = -6815760; t17 = ((x77/x78)==(x79^x80)); if (t17 != 0) { NG(); } else { ; } } void f18(void) { static int64_t x81 = INT64_MIN; static uint32_t x82 = UINT32_MAX; int64_t x83 = INT64_MIN; volatile int32_t t18 = 5; t18 = ((x81/x82)==(x83^x84)); if (t18 != 0) { NG(); } else { ; } } void f19(void) { uint32_t x85 = UINT32_MAX; uint32_t x86 = 814U; int32_t t19 = -139; t19 = ((x85/x86)==(x87^x88)); if (t19 != 0) { NG(); } else { ; } } void f20(void) { volatile uint64_t x89 = 10LLU; volatile uint16_t x90 = 30954U; volatile int32_t x91 = INT32_MAX; int8_t x92 = INT8_MIN; volatile int32_t t20 = 477; t20 = ((x89/x90)==(x91^x92)); if (t20 != 0) { NG(); } else { ; } } void f21(void) { int16_t x93 = -4782; uint16_t x94 = 4U; int8_t x95 = INT8_MIN; uint16_t x96 = 13069U; volatile int32_t t21 = 53; t21 = ((x93/x94)==(x95^x96)); if (t21 != 0) { NG(); } else { ; } } void f22(void) { uint8_t x99 = 0U; t22 = ((x97/x98)==(x99^x100)); if (t22 != 0) { NG(); } else { ; } } void f23(void) { int16_t x102 = INT16_MIN; static int32_t x104 = -1; int32_t t23 = -11796; t23 = ((x101/x102)==(x103^x104)); if (t23 != 0) { NG(); } else { ; } } void f24(void) { int8_t x105 = 0; static int32_t x106 = -1; uint64_t x107 = UINT64_MAX; static int64_t x108 = INT64_MAX; volatile int32_t t24 = 2; t24 = ((x105/x106)==(x107^x108)); if (t24 != 0) { NG(); } else { ; } } void f25(void) { static uint8_t x111 = 2U; volatile int64_t x112 = -74661274LL; t25 = ((x109/x110)==(x111^x112)); if (t25 != 0) { NG(); } else { ; } } void f26(void) { uint16_t x114 = 1852U; int32_t x115 = 3839; volatile uint64_t x116 = 204101LLU; t26 = ((x113/x114)==(x115^x116)); if (t26 != 0) { NG(); } else { ; } } void f27(void) { int64_t x117 = -113537061725LL; volatile uint16_t x118 = UINT16_MAX; static uint32_t x120 = 37391U; volatile int32_t t27 = -14229; t27 = ((x117/x118)==(x119^x120)); if (t27 != 0) { NG(); } else { ; } } void f28(void) { int8_t x121 = 0; static int64_t x123 = INT64_MAX; static int16_t x124 = INT16_MIN; volatile int32_t t28 = -1; t28 = ((x121/x122)==(x123^x124)); if (t28 != 0) { NG(); } else { ; } } void f29(void) { int32_t x125 = -114347816; int32_t x127 = -1; uint64_t x128 = 1580642364660784LLU; volatile int32_t t29 = -47351; t29 = ((x125/x126)==(x127^x128)); if (t29 != 0) { NG(); } else { ; } } void f30(void) { int64_t x129 = INT64_MAX; static int64_t x130 = INT64_MAX; int32_t x132 = -1; int32_t t30 = 1; t30 = ((x129/x130)==(x131^x132)); if (t30 != 0) { NG(); } else { ; } } void f31(void) { int16_t x134 = -9; volatile int32_t x135 = INT32_MIN; int64_t x136 = -1LL; volatile int32_t t31 = 437; t31 = ((x133/x134)==(x135^x136)); if (t31 != 0) { NG(); } else { ; } } void f32(void) { volatile uint16_t x137 = 90U; int8_t x138 = INT8_MIN; uint64_t x139 = 31415414935922208LLU; static int32_t x140 = INT32_MIN; int32_t t32 = 181751; t32 = ((x137/x138)==(x139^x140)); if (t32 != 0) { NG(); } else { ; } } void f33(void) { int64_t x141 = -5057536156520304LL; int64_t x142 = -1LL; uint16_t x143 = 2U; volatile int32_t x144 = INT32_MAX; volatile int32_t t33 = 1292404; t33 = ((x141/x142)==(x143^x144)); if (t33 != 0) { NG(); } else { ; } } void f34(void) { volatile uint64_t x147 = 7LLU; volatile uint32_t x148 = 1401629U; volatile int32_t t34 = 22; t34 = ((x145/x146)==(x147^x148)); if (t34 != 0) { NG(); } else { ; } } void f35(void) { int16_t x149 = INT16_MIN; int32_t x150 = INT32_MIN; volatile uint16_t x151 = 378U; static uint64_t x152 = 1040089825337049066LLU; t35 = ((x149/x150)==(x151^x152)); if (t35 != 0) { NG(); } else { ; } } void f36(void) { int32_t x154 = 307; uint64_t x155 = UINT64_MAX; uint16_t x156 = 181U; static volatile int32_t t36 = -987563; t36 = ((x153/x154)==(x155^x156)); if (t36 != 0) { NG(); } else { ; } } void f37(void) { int16_t x157 = 1; int32_t x158 = INT32_MIN; uint64_t x159 = UINT64_MAX; int64_t x160 = -1LL; int32_t t37 = -17715; t37 = ((x157/x158)==(x159^x160)); if (t37 != 1) { NG(); } else { ; } } void f38(void) { int32_t x161 = 2; uint32_t x162 = UINT32_MAX; uint8_t x163 = 23U; int64_t x164 = -1LL; int32_t t38 = -59; t38 = ((x161/x162)==(x163^x164)); if (t38 != 0) { NG(); } else { ; } } void f39(void) { int32_t x165 = 86871; volatile uint64_t x166 = 63825690592743046LLU; int32_t t39 = 12503879; t39 = ((x165/x166)==(x167^x168)); if (t39 != 0) { NG(); } else { ; } } void f40(void) { volatile int8_t x169 = -1; int32_t x171 = -1; t40 = ((x169/x170)==(x171^x172)); if (t40 != 0) { NG(); } else { ; } } void f41(void) { uint64_t x173 = 5586150LLU; static uint8_t x174 = UINT8_MAX; static int32_t x175 = INT32_MIN; static uint16_t x176 = 781U; int32_t t41 = 9629; t41 = ((x173/x174)==(x175^x176)); if (t41 != 0) { NG(); } else { ; } } void f42(void) { int8_t x177 = -25; volatile int32_t x178 = -3303; volatile int32_t x179 = INT32_MAX; static uint16_t x180 = 9041U; volatile int32_t t42 = -7; t42 = ((x177/x178)==(x179^x180)); if (t42 != 0) { NG(); } else { ; } } void f43(void) { uint16_t x181 = 3U; uint8_t x182 = 75U; uint8_t x183 = UINT8_MAX; volatile int32_t x184 = INT32_MIN; int32_t t43 = 176469560; t43 = ((x181/x182)==(x183^x184)); if (t43 != 0) { NG(); } else { ; } } void f44(void) { uint32_t x185 = UINT32_MAX; uint32_t x186 = 411220706U; int64_t x187 = INT64_MIN; static int16_t x188 = -61; volatile int32_t t44 = 50; t44 = ((x185/x186)==(x187^x188)); if (t44 != 0) { NG(); } else { ; } } void f45(void) { int64_t x189 = -1LL; volatile int64_t x190 = INT64_MIN; volatile uint8_t x191 = UINT8_MAX; int32_t t45 = -7; t45 = ((x189/x190)==(x191^x192)); if (t45 != 0) { NG(); } else { ; } } void f46(void) { int8_t x193 = -1; static int8_t x196 = 7; t46 = ((x193/x194)==(x195^x196)); if (t46 != 0) { NG(); } else { ; } } void f47(void) { int8_t x197 = -2; int16_t x198 = INT16_MIN; int64_t x199 = INT64_MIN; int64_t x200 = INT64_MAX; t47 = ((x197/x198)==(x199^x200)); if (t47 != 0) { NG(); } else { ; } } void f48(void) { int64_t x201 = INT64_MIN; uint64_t x202 = 2976301LLU; int64_t x203 = INT64_MAX; int8_t x204 = INT8_MIN; int32_t t48 = 1065; t48 = ((x201/x202)==(x203^x204)); if (t48 != 0) { NG(); } else { ; } } void f49(void) { volatile int32_t x208 = INT32_MIN; int32_t t49 = -8032; t49 = ((x205/x206)==(x207^x208)); if (t49 != 1) { NG(); } else { ; } } void f50(void) { static int16_t x209 = 0; static uint32_t x210 = UINT32_MAX; uint64_t x211 = 224811641253LLU; static volatile uint32_t x212 = 78044U; volatile int32_t t50 = 1700449; t50 = ((x209/x210)==(x211^x212)); if (t50 != 0) { NG(); } else { ; } } void f51(void) { uint64_t x213 = UINT64_MAX; static int32_t x214 = INT32_MIN; static uint32_t x215 = UINT32_MAX; int32_t t51 = 96715; t51 = ((x213/x214)==(x215^x216)); if (t51 != 0) { NG(); } else { ; } } void f52(void) { uint8_t x222 = UINT8_MAX; volatile int8_t x224 = 0; volatile int32_t t52 = 306371899; t52 = ((x221/x222)==(x223^x224)); if (t52 != 0) { NG(); } else { ; } } void f53(void) { volatile int16_t x225 = INT16_MIN; uint8_t x227 = 1U; static int64_t x228 = -46860188311612489LL; volatile int32_t t53 = -1; t53 = ((x225/x226)==(x227^x228)); if (t53 != 0) { NG(); } else { ; } } void f54(void) { volatile int32_t x229 = -335973158; static volatile int8_t x230 = INT8_MAX; static int16_t x231 = -243; int16_t x232 = -1; static int32_t t54 = -668424131; t54 = ((x229/x230)==(x231^x232)); if (t54 != 0) { NG(); } else { ; } } void f55(void) { volatile uint16_t x233 = 5U; int16_t x234 = INT16_MIN; int16_t x235 = INT16_MIN; volatile int32_t t55 = 5031379; t55 = ((x233/x234)==(x235^x236)); if (t55 != 0) { NG(); } else { ; } } void f56(void) { static volatile int64_t x238 = INT64_MAX; int32_t x239 = -1; int16_t x240 = INT16_MAX; int32_t t56 = -24587734; t56 = ((x237/x238)==(x239^x240)); if (t56 != 0) { NG(); } else { ; } } void f57(void) { int16_t x241 = 2; static volatile int16_t x242 = 11552; uint16_t x243 = 3462U; uint64_t x244 = UINT64_MAX; volatile int32_t t57 = -193081; t57 = ((x241/x242)==(x243^x244)); if (t57 != 0) { NG(); } else { ; } } void f58(void) { int16_t x245 = -449; uint16_t x246 = UINT16_MAX; uint8_t x247 = 2U; volatile int32_t t58 = 721464; t58 = ((x245/x246)==(x247^x248)); if (t58 != 0) { NG(); } else { ; } } void f59(void) { uint64_t x249 = UINT64_MAX; int16_t x250 = -1; volatile int16_t x251 = -1; int32_t t59 = 3885490; t59 = ((x249/x250)==(x251^x252)); if (t59 != 0) { NG(); } else { ; } } void f60(void) { uint64_t x253 = 31236476677LLU; int8_t x254 = -1; static volatile uint64_t x255 = UINT64_MAX; static int32_t x256 = INT32_MAX; static int32_t t60 = 15851614; t60 = ((x253/x254)==(x255^x256)); if (t60 != 0) { NG(); } else { ; } } void f61(void) { volatile uint32_t x258 = UINT32_MAX; static int64_t x259 = -280LL; int32_t t61 = 19866796; t61 = ((x257/x258)==(x259^x260)); if (t61 != 0) { NG(); } else { ; } } void f62(void) { static volatile uint8_t x263 = UINT8_MAX; int64_t x264 = -1LL; static int32_t t62 = -1291652; t62 = ((x261/x262)==(x263^x264)); if (t62 != 0) { NG(); } else { ; } } void f63(void) { int16_t x265 = -1; static int64_t x266 = INT64_MIN; volatile uint8_t x267 = 7U; int16_t x268 = 61; t63 = ((x265/x266)==(x267^x268)); if (t63 != 0) { NG(); } else { ; } } void f64(void) { volatile int64_t x269 = -4LL; static volatile int32_t x270 = INT32_MIN; uint16_t x271 = UINT16_MAX; volatile int32_t x272 = INT32_MIN; static int32_t t64 = -457310313; t64 = ((x269/x270)==(x271^x272)); if (t64 != 0) { NG(); } else { ; } } void f65(void) { int16_t x273 = INT16_MAX; static uint16_t x274 = 986U; int8_t x275 = 2; uint64_t x276 = 5930258599LLU; static int32_t t65 = 1; t65 = ((x273/x274)==(x275^x276)); if (t65 != 0) { NG(); } else { ; } } void f66(void) { volatile int64_t x277 = -34503LL; volatile int32_t x279 = INT32_MAX; int64_t x280 = 8715301LL; t66 = ((x277/x278)==(x279^x280)); if (t66 != 0) { NG(); } else { ; } } void f67(void) { int16_t x282 = INT16_MAX; static uint32_t x283 = UINT32_MAX; uint64_t x284 = UINT64_MAX; int32_t t67 = -3904431; t67 = ((x281/x282)==(x283^x284)); if (t67 != 0) { NG(); } else { ; } } void f68(void) { int64_t x285 = 11664278LL; int16_t x286 = INT16_MIN; volatile int32_t x287 = INT32_MIN; volatile int32_t t68 = 103; t68 = ((x285/x286)==(x287^x288)); if (t68 != 0) { NG(); } else { ; } } void f69(void) { int64_t x289 = -1LL; volatile int32_t x291 = INT32_MAX; volatile int32_t t69 = -13983; t69 = ((x289/x290)==(x291^x292)); if (t69 != 0) { NG(); } else { ; } } void f70(void) { volatile uint64_t x296 = 427163018090023LLU; static int32_t t70 = -11; t70 = ((x293/x294)==(x295^x296)); if (t70 != 0) { NG(); } else { ; } } void f71(void) { volatile uint64_t x297 = 1905699534LLU; int64_t x298 = 4132647LL; static uint16_t x299 = UINT16_MAX; uint32_t x300 = 486545U; volatile int32_t t71 = -81; t71 = ((x297/x298)==(x299^x300)); if (t71 != 0) { NG(); } else { ; } } void f72(void) { int8_t x301 = INT8_MAX; int32_t x302 = 7; int32_t x304 = INT32_MAX; volatile int32_t t72 = 2; t72 = ((x301/x302)==(x303^x304)); if (t72 != 0) { NG(); } else { ; } } void f73(void) { static int64_t x305 = INT64_MIN; int32_t t73 = 5; t73 = ((x305/x306)==(x307^x308)); if (t73 != 0) { NG(); } else { ; } } void f74(void) { int8_t x309 = -1; static int8_t x310 = INT8_MAX; int16_t x311 = -1; int16_t x312 = INT16_MIN; volatile int32_t t74 = -612684237; t74 = ((x309/x310)==(x311^x312)); if (t74 != 0) { NG(); } else { ; } } void f75(void) { uint32_t x313 = UINT32_MAX; volatile int8_t x316 = 0; t75 = ((x313/x314)==(x315^x316)); if (t75 != 0) { NG(); } else { ; } } void f76(void) { static int8_t x317 = INT8_MIN; static int16_t x319 = INT16_MIN; int8_t x320 = 56; volatile int32_t t76 = 2825442; t76 = ((x317/x318)==(x319^x320)); if (t76 != 0) { NG(); } else { ; } } void f77(void) { uint16_t x321 = 2657U; int16_t x322 = INT16_MIN; static volatile uint32_t x323 = 0U; int32_t t77 = -51; t77 = ((x321/x322)==(x323^x324)); if (t77 != 0) { NG(); } else { ; } } void f78(void) { volatile int32_t x325 = -1; uint8_t x326 = 44U; volatile uint16_t x327 = 6954U; int16_t x328 = -1; t78 = ((x325/x326)==(x327^x328)); if (t78 != 0) { NG(); } else { ; } } void f79(void) { int64_t x329 = INT64_MAX; int8_t x331 = INT8_MIN; uint8_t x332 = 9U; volatile int32_t t79 = -686608; t79 = ((x329/x330)==(x331^x332)); if (t79 != 0) { NG(); } else { ; } } void f80(void) { static volatile int8_t x333 = 0; int16_t x334 = INT16_MIN; uint8_t x335 = 44U; static uint32_t x336 = UINT32_MAX; volatile int32_t t80 = -103; t80 = ((x333/x334)==(x335^x336)); if (t80 != 0) { NG(); } else { ; } } void f81(void) { int32_t x337 = -1; uint32_t x338 = 53601224U; volatile uint32_t x339 = 409464205U; int32_t x340 = -1; int32_t t81 = 7262; t81 = ((x337/x338)==(x339^x340)); if (t81 != 0) { NG(); } else { ; } } void f82(void) { uint16_t x342 = 24425U; int16_t x343 = INT16_MAX; uint64_t x344 = 26852LLU; t82 = ((x341/x342)==(x343^x344)); if (t82 != 0) { NG(); } else { ; } } void f83(void) { int8_t x348 = INT8_MAX; static int32_t t83 = -79; t83 = ((x345/x346)==(x347^x348)); if (t83 != 0) { NG(); } else { ; } } void f84(void) { static int8_t x349 = -1; static uint32_t x350 = UINT32_MAX; int64_t x352 = 5664650147056268LL; int32_t t84 = 175352; t84 = ((x349/x350)==(x351^x352)); if (t84 != 0) { NG(); } else { ; } } void f85(void) { int32_t x353 = -1; uint64_t x354 = 45LLU; static volatile int32_t x355 = -10838; volatile int8_t x356 = 62; static volatile int32_t t85 = -187973880; t85 = ((x353/x354)==(x355^x356)); if (t85 != 0) { NG(); } else { ; } } void f86(void) { int16_t x357 = -12199; volatile int8_t x358 = -1; int16_t x359 = -1; uint32_t x360 = 175U; t86 = ((x357/x358)==(x359^x360)); if (t86 != 0) { NG(); } else { ; } } void f87(void) { int8_t x361 = INT8_MIN; static int16_t x362 = INT16_MIN; int16_t x363 = INT16_MIN; int8_t x364 = INT8_MIN; int32_t t87 = 182330; t87 = ((x361/x362)==(x363^x364)); if (t87 != 0) { NG(); } else { ; } } void f88(void) { volatile int8_t x365 = -1; int32_t x366 = -1; volatile int32_t x367 = -167; uint16_t x368 = 63U; volatile int32_t t88 = 319; t88 = ((x365/x366)==(x367^x368)); if (t88 != 0) { NG(); } else { ; } } void f89(void) { int8_t x369 = INT8_MIN; int32_t x370 = -4206111; int8_t x372 = -1; int32_t t89 = 110209135; t89 = ((x369/x370)==(x371^x372)); if (t89 != 0) { NG(); } else { ; } } void f90(void) { uint8_t x373 = 29U; uint16_t x374 = UINT16_MAX; uint8_t x375 = 46U; volatile uint8_t x376 = UINT8_MAX; int32_t t90 = -8; t90 = ((x373/x374)==(x375^x376)); if (t90 != 0) { NG(); } else { ; } } void f91(void) { static int64_t x379 = -58817794365083LL; int32_t x380 = -2514; int32_t t91 = 3705587; t91 = ((x377/x378)==(x379^x380)); if (t91 != 0) { NG(); } else { ; } } void f92(void) { int16_t x381 = 97; int16_t x383 = 13812; uint32_t x384 = UINT32_MAX; int32_t t92 = 54755; t92 = ((x381/x382)==(x383^x384)); if (t92 != 0) { NG(); } else { ; } } void f93(void) { uint16_t x385 = 15167U; int16_t x388 = -2; t93 = ((x385/x386)==(x387^x388)); if (t93 != 0) { NG(); } else { ; } } void f94(void) { static uint16_t x389 = 1U; int64_t x391 = INT64_MIN; static uint8_t x392 = UINT8_MAX; t94 = ((x389/x390)==(x391^x392)); if (t94 != 0) { NG(); } else { ; } } void f95(void) { static int32_t x393 = INT32_MAX; uint32_t x394 = 1587730U; volatile int32_t t95 = -230; t95 = ((x393/x394)==(x395^x396)); if (t95 != 0) { NG(); } else { ; } } void f96(void) { int32_t x397 = INT32_MIN; int8_t x398 = INT8_MAX; int16_t x399 = 470; volatile int32_t t96 = 15; t96 = ((x397/x398)==(x399^x400)); if (t96 != 0) { NG(); } else { ; } } void f97(void) { int64_t x401 = INT64_MIN; static int32_t x402 = INT32_MIN; uint64_t x403 = 31362618465130LLU; volatile int16_t x404 = -1; volatile int32_t t97 = 101142; t97 = ((x401/x402)==(x403^x404)); if (t97 != 0) { NG(); } else { ; } } void f98(void) { static uint64_t x405 = 561711985641735250LLU; uint32_t x406 = UINT32_MAX; static int16_t x407 = INT16_MIN; static volatile int64_t x408 = INT64_MIN; int32_t t98 = 464490; t98 = ((x405/x406)==(x407^x408)); if (t98 != 0) { NG(); } else { ; } } void f99(void) { uint16_t x409 = UINT16_MAX; int64_t x410 = INT64_MAX; uint16_t x411 = 256U; volatile int64_t x412 = INT64_MIN; volatile int32_t t99 = 52316; t99 = ((x409/x410)==(x411^x412)); if (t99 != 0) { NG(); } else { ; } } void f100(void) { volatile int32_t x413 = INT32_MIN; int32_t x415 = INT32_MAX; uint32_t x416 = 53439U; int32_t t100 = -3709778; t100 = ((x413/x414)==(x415^x416)); if (t100 != 0) { NG(); } else { ; } } void f101(void) { int8_t x417 = 7; int16_t x418 = INT16_MIN; uint16_t x419 = UINT16_MAX; int32_t t101 = 5; t101 = ((x417/x418)==(x419^x420)); if (t101 != 0) { NG(); } else { ; } } void f102(void) { static uint32_t x421 = 144U; volatile int8_t x422 = INT8_MAX; static int8_t x423 = INT8_MAX; int16_t x424 = -11; t102 = ((x421/x422)==(x423^x424)); if (t102 != 0) { NG(); } else { ; } } void f103(void) { static volatile uint32_t x426 = UINT32_MAX; static int32_t t103 = 20805; t103 = ((x425/x426)==(x427^x428)); if (t103 != 0) { NG(); } else { ; } } void f104(void) { volatile int16_t x433 = -1; int16_t x434 = -1; int8_t x435 = 9; volatile int32_t t104 = 10; t104 = ((x433/x434)==(x435^x436)); if (t104 != 0) { NG(); } else { ; } } void f105(void) { static int32_t x437 = 31872559; uint64_t x438 = 6032LLU; volatile int8_t x439 = INT8_MIN; int32_t t105 = 28385400; t105 = ((x437/x438)==(x439^x440)); if (t105 != 0) { NG(); } else { ; } } void f106(void) { uint32_t x441 = UINT32_MAX; int8_t x442 = -1; t106 = ((x441/x442)==(x443^x444)); if (t106 != 0) { NG(); } else { ; } } void f107(void) { int32_t x446 = 37933297; uint8_t x447 = 35U; volatile uint32_t x448 = 9U; static int32_t t107 = -1860062; t107 = ((x445/x446)==(x447^x448)); if (t107 != 0) { NG(); } else { ; } } void f108(void) { uint16_t x449 = UINT16_MAX; static uint16_t x451 = 42U; volatile int32_t t108 = 18; t108 = ((x449/x450)==(x451^x452)); if (t108 != 0) { NG(); } else { ; } } void f109(void) { int64_t x453 = INT64_MIN; uint8_t x454 = 15U; int32_t t109 = -19897; t109 = ((x453/x454)==(x455^x456)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { static uint8_t x457 = UINT8_MAX; int16_t x459 = -1; int64_t x460 = INT64_MIN; static int32_t t110 = -7096; t110 = ((x457/x458)==(x459^x460)); if (t110 != 0) { NG(); } else { ; } } void f111(void) { static volatile uint32_t x461 = UINT32_MAX; int64_t x462 = -1LL; int32_t x463 = -2947975; static uint8_t x464 = 12U; volatile int32_t t111 = 187903221; t111 = ((x461/x462)==(x463^x464)); if (t111 != 0) { NG(); } else { ; } } void f112(void) { static int32_t x465 = INT32_MAX; int16_t x466 = -42; int32_t x467 = INT32_MIN; volatile int32_t t112 = -236019758; t112 = ((x465/x466)==(x467^x468)); if (t112 != 0) { NG(); } else { ; } } void f113(void) { int32_t x470 = INT32_MIN; int16_t x472 = INT16_MIN; volatile int32_t t113 = 5; t113 = ((x469/x470)==(x471^x472)); if (t113 != 0) { NG(); } else { ; } } void f114(void) { int32_t x474 = INT32_MIN; volatile int32_t t114 = 6; t114 = ((x473/x474)==(x475^x476)); if (t114 != 0) { NG(); } else { ; } } void f115(void) { int8_t x477 = INT8_MAX; int64_t x478 = -1LL; uint64_t x479 = 6593691292273LLU; int16_t x480 = 0; static int32_t t115 = 64; t115 = ((x477/x478)==(x479^x480)); if (t115 != 0) { NG(); } else { ; } } void f116(void) { int32_t x481 = -320603115; volatile uint16_t x482 = 10636U; volatile int8_t x483 = 3; static volatile uint32_t x484 = UINT32_MAX; int32_t t116 = 0; t116 = ((x481/x482)==(x483^x484)); if (t116 != 0) { NG(); } else { ; } } void f117(void) { int32_t x485 = -1; int32_t x487 = -1; int16_t x488 = INT16_MIN; t117 = ((x485/x486)==(x487^x488)); if (t117 != 0) { NG(); } else { ; } } void f118(void) { volatile int32_t x489 = INT32_MIN; int32_t x490 = INT32_MIN; int64_t x491 = 102199712878651435LL; volatile int32_t t118 = -143809; t118 = ((x489/x490)==(x491^x492)); if (t118 != 0) { NG(); } else { ; } } void f119(void) { volatile int32_t x493 = INT32_MAX; volatile int64_t x495 = -214095127138LL; int32_t t119 = -4; t119 = ((x493/x494)==(x495^x496)); if (t119 != 0) { NG(); } else { ; } } void f120(void) { uint32_t x498 = UINT32_MAX; uint64_t x499 = 65763044157LLU; static int16_t x500 = INT16_MIN; volatile int32_t t120 = -111; t120 = ((x497/x498)==(x499^x500)); if (t120 != 0) { NG(); } else { ; } } void f121(void) { static int16_t x501 = INT16_MAX; int8_t x502 = INT8_MIN; static int16_t x503 = -1; int32_t t121 = -286; t121 = ((x501/x502)==(x503^x504)); if (t121 != 0) { NG(); } else { ; } } void f122(void) { uint16_t x505 = 0U; int64_t x506 = INT64_MIN; static int8_t x507 = 1; uint8_t x508 = UINT8_MAX; volatile int32_t t122 = 126; t122 = ((x505/x506)==(x507^x508)); if (t122 != 0) { NG(); } else { ; } } void f123(void) { int32_t x509 = INT32_MAX; int16_t x510 = 389; uint8_t x511 = 2U; t123 = ((x509/x510)==(x511^x512)); if (t123 != 0) { NG(); } else { ; } } void f124(void) { static int8_t x517 = INT8_MAX; uint16_t x518 = 662U; uint32_t x519 = 4824U; int32_t x520 = INT32_MIN; volatile int32_t t124 = 66120309; t124 = ((x517/x518)==(x519^x520)); if (t124 != 0) { NG(); } else { ; } } void f125(void) { uint16_t x521 = 14U; int8_t x522 = INT8_MIN; uint8_t x523 = UINT8_MAX; uint16_t x524 = 45U; volatile int32_t t125 = -25110217; t125 = ((x521/x522)==(x523^x524)); if (t125 != 0) { NG(); } else { ; } } void f126(void) { int8_t x526 = 6; static int8_t x527 = -7; uint32_t x528 = 144U; volatile int32_t t126 = -485; t126 = ((x525/x526)==(x527^x528)); if (t126 != 0) { NG(); } else { ; } } void f127(void) { volatile int32_t x530 = -17607345; volatile int32_t x531 = -1; int32_t x532 = INT32_MIN; t127 = ((x529/x530)==(x531^x532)); if (t127 != 0) { NG(); } else { ; } } void f128(void) { static int16_t x533 = INT16_MIN; int32_t x534 = INT32_MIN; uint8_t x535 = 0U; static uint8_t x536 = 8U; int32_t t128 = 4; t128 = ((x533/x534)==(x535^x536)); if (t128 != 0) { NG(); } else { ; } } void f129(void) { int32_t x537 = INT32_MIN; int16_t x538 = INT16_MAX; static uint8_t x539 = UINT8_MAX; int8_t x540 = INT8_MAX; volatile int32_t t129 = 0; t129 = ((x537/x538)==(x539^x540)); if (t129 != 0) { NG(); } else { ; } } void f130(void) { uint8_t x542 = 1U; int16_t x543 = -1; static uint32_t x544 = UINT32_MAX; t130 = ((x541/x542)==(x543^x544)); if (t130 != 0) { NG(); } else { ; } } void f131(void) { int64_t x547 = INT64_MAX; int32_t t131 = 0; t131 = ((x545/x546)==(x547^x548)); if (t131 != 0) { NG(); } else { ; } } void f132(void) { int64_t x549 = INT64_MAX; int8_t x551 = INT8_MIN; static volatile int8_t x552 = INT8_MIN; volatile int32_t t132 = -29902; t132 = ((x549/x550)==(x551^x552)); if (t132 != 0) { NG(); } else { ; } } void f133(void) { volatile int64_t x553 = 439195143391537LL; volatile int32_t x555 = -139100; volatile uint16_t x556 = UINT16_MAX; volatile int32_t t133 = 14; t133 = ((x553/x554)==(x555^x556)); if (t133 != 0) { NG(); } else { ; } } void f134(void) { static uint64_t x559 = 704414910074495681LLU; int32_t x560 = -1; volatile int32_t t134 = -13383; t134 = ((x557/x558)==(x559^x560)); if (t134 != 0) { NG(); } else { ; } } void f135(void) { volatile int32_t x561 = INT32_MAX; int16_t x563 = 3174; uint32_t x564 = 240804461U; int32_t t135 = 13516887; t135 = ((x561/x562)==(x563^x564)); if (t135 != 0) { NG(); } else { ; } } void f136(void) { uint8_t x565 = 2U; int8_t x567 = 31; uint16_t x568 = 16U; int32_t t136 = -190275; t136 = ((x565/x566)==(x567^x568)); if (t136 != 0) { NG(); } else { ; } } void f137(void) { uint8_t x569 = 3U; int8_t x570 = INT8_MIN; uint32_t x572 = UINT32_MAX; t137 = ((x569/x570)==(x571^x572)); if (t137 != 0) { NG(); } else { ; } } void f138(void) { int32_t x573 = -1; int16_t x575 = -19; t138 = ((x573/x574)==(x575^x576)); if (t138 != 0) { NG(); } else { ; } } void f139(void) { static int32_t x577 = -1; int8_t x579 = INT8_MAX; int8_t x580 = INT8_MIN; volatile int32_t t139 = -118117; t139 = ((x577/x578)==(x579^x580)); if (t139 != 0) { NG(); } else { ; } } void f140(void) { static volatile int64_t x582 = INT64_MIN; uint32_t x584 = UINT32_MAX; volatile int32_t t140 = -1; t140 = ((x581/x582)==(x583^x584)); if (t140 != 0) { NG(); } else { ; } } void f141(void) { int8_t x585 = INT8_MAX; uint32_t x586 = UINT32_MAX; static uint64_t x587 = UINT64_MAX; uint16_t x588 = UINT16_MAX; volatile int32_t t141 = -552; t141 = ((x585/x586)==(x587^x588)); if (t141 != 0) { NG(); } else { ; } } void f142(void) { int8_t x590 = INT8_MIN; int32_t x591 = -1; static int64_t x592 = -1LL; static volatile int32_t t142 = -692290375; t142 = ((x589/x590)==(x591^x592)); if (t142 != 1) { NG(); } else { ; } } void f143(void) { int32_t x593 = INT32_MIN; int32_t x594 = INT32_MIN; volatile int64_t x595 = INT64_MIN; int64_t x596 = 2LL; t143 = ((x593/x594)==(x595^x596)); if (t143 != 0) { NG(); } else { ; } } void f144(void) { int16_t x601 = INT16_MIN; static uint64_t x602 = 6898632858LLU; volatile int32_t x603 = INT32_MIN; uint32_t x604 = 48591457U; volatile int32_t t144 = -43; t144 = ((x601/x602)==(x603^x604)); if (t144 != 0) { NG(); } else { ; } } void f145(void) { int8_t x605 = -11; static uint16_t x606 = 119U; volatile uint8_t x607 = 3U; volatile int32_t t145 = 483195; t145 = ((x605/x606)==(x607^x608)); if (t145 != 0) { NG(); } else { ; } } void f146(void) { int8_t x613 = INT8_MIN; static uint16_t x614 = 102U; static int8_t x615 = 1; volatile uint16_t x616 = UINT16_MAX; int32_t t146 = 156456; t146 = ((x613/x614)==(x615^x616)); if (t146 != 0) { NG(); } else { ; } } void f147(void) { uint8_t x617 = UINT8_MAX; int8_t x618 = INT8_MAX; int64_t x619 = -3016443176020LL; volatile int8_t x620 = 39; int32_t t147 = -4233182; t147 = ((x617/x618)==(x619^x620)); if (t147 != 0) { NG(); } else { ; } } void f148(void) { volatile int8_t x621 = 16; int8_t x622 = INT8_MIN; int32_t x623 = -6093918; int16_t x624 = INT16_MIN; int32_t t148 = 218969030; t148 = ((x621/x622)==(x623^x624)); if (t148 != 0) { NG(); } else { ; } } void f149(void) { uint16_t x625 = 1U; int32_t x626 = INT32_MIN; volatile int8_t x627 = -1; static volatile int32_t t149 = -57468; t149 = ((x625/x626)==(x627^x628)); if (t149 != 0) { NG(); } else { ; } } void f150(void) { int16_t x629 = 0; uint16_t x630 = 1948U; int8_t x631 = INT8_MAX; static volatile int32_t x632 = 4924; int32_t t150 = -118; t150 = ((x629/x630)==(x631^x632)); if (t150 != 0) { NG(); } else { ; } } void f151(void) { static int64_t x633 = 1890662398975409LL; int32_t x635 = INT32_MIN; volatile int32_t t151 = 57; t151 = ((x633/x634)==(x635^x636)); if (t151 != 0) { NG(); } else { ; } } void f152(void) { volatile uint8_t x637 = UINT8_MAX; volatile uint16_t x638 = 973U; int32_t x639 = 476503; int16_t x640 = INT16_MIN; volatile int32_t t152 = -439533832; t152 = ((x637/x638)==(x639^x640)); if (t152 != 0) { NG(); } else { ; } } void f153(void) { static int8_t x642 = -1; int16_t x643 = 126; uint32_t x644 = 87U; static int32_t t153 = 4; t153 = ((x641/x642)==(x643^x644)); if (t153 != 0) { NG(); } else { ; } } void f154(void) { int8_t x645 = INT8_MIN; volatile int64_t x646 = INT64_MIN; volatile uint64_t x647 = UINT64_MAX; int8_t x648 = INT8_MIN; int32_t t154 = 1; t154 = ((x645/x646)==(x647^x648)); if (t154 != 0) { NG(); } else { ; } } void f155(void) { volatile int8_t x649 = INT8_MIN; int64_t x650 = 1256724326331LL; uint32_t x651 = UINT32_MAX; int8_t x652 = INT8_MIN; t155 = ((x649/x650)==(x651^x652)); if (t155 != 0) { NG(); } else { ; } } void f156(void) { int32_t x656 = -1; static volatile int32_t t156 = 0; t156 = ((x653/x654)==(x655^x656)); if (t156 != 0) { NG(); } else { ; } } void f157(void) { static volatile int32_t x657 = INT32_MAX; uint32_t x658 = 27U; int32_t x659 = -1; uint16_t x660 = 484U; int32_t t157 = -17058; t157 = ((x657/x658)==(x659^x660)); if (t157 != 0) { NG(); } else { ; } } void f158(void) { int64_t x661 = INT64_MIN; volatile int8_t x662 = 3; int32_t x664 = INT32_MIN; t158 = ((x661/x662)==(x663^x664)); if (t158 != 0) { NG(); } else { ; } } void f159(void) { uint16_t x665 = 67U; int8_t x667 = 2; int16_t x668 = -1; t159 = ((x665/x666)==(x667^x668)); if (t159 != 0) { NG(); } else { ; } } void f160(void) { int64_t x669 = INT64_MIN; int8_t x670 = -58; uint16_t x671 = 35U; volatile int16_t x672 = INT16_MAX; volatile int32_t t160 = 229539253; t160 = ((x669/x670)==(x671^x672)); if (t160 != 0) { NG(); } else { ; } } void f161(void) { volatile int64_t x673 = -1LL; static int16_t x674 = INT16_MIN; uint8_t x675 = 17U; uint32_t x676 = UINT32_MAX; int32_t t161 = 29; t161 = ((x673/x674)==(x675^x676)); if (t161 != 0) { NG(); } else { ; } } void f162(void) { volatile uint32_t x677 = 39315U; static volatile uint64_t x678 = 296123069003027LLU; uint8_t x679 = UINT8_MAX; int16_t x680 = -59; int32_t t162 = -180; t162 = ((x677/x678)==(x679^x680)); if (t162 != 0) { NG(); } else { ; } } void f163(void) { int32_t x681 = 21825115; int32_t x682 = INT32_MAX; static volatile int16_t x683 = -1; volatile int32_t t163 = 317731784; t163 = ((x681/x682)==(x683^x684)); if (t163 != 0) { NG(); } else { ; } } void f164(void) { int8_t x685 = -1; int16_t x686 = -809; uint16_t x687 = 110U; uint64_t x688 = 61LLU; volatile int32_t t164 = -3577621; t164 = ((x685/x686)==(x687^x688)); if (t164 != 0) { NG(); } else { ; } } void f165(void) { uint32_t x689 = 41216U; volatile uint64_t x690 = UINT64_MAX; int64_t x691 = INT64_MIN; static int32_t t165 = 522761303; t165 = ((x689/x690)==(x691^x692)); if (t165 != 0) { NG(); } else { ; } } void f166(void) { static uint16_t x695 = UINT16_MAX; t166 = ((x693/x694)==(x695^x696)); if (t166 != 0) { NG(); } else { ; } } void f167(void) { uint8_t x697 = UINT8_MAX; static uint64_t x698 = UINT64_MAX; t167 = ((x697/x698)==(x699^x700)); if (t167 != 0) { NG(); } else { ; } } void f168(void) { volatile int64_t x701 = INT64_MIN; uint8_t x702 = 1U; volatile uint8_t x703 = 15U; static int32_t t168 = -5697; t168 = ((x701/x702)==(x703^x704)); if (t168 != 0) { NG(); } else { ; } } void f169(void) { volatile int64_t x705 = INT64_MIN; int64_t x706 = 14604150802636588LL; static int16_t x708 = -1; t169 = ((x705/x706)==(x707^x708)); if (t169 != 0) { NG(); } else { ; } } void f170(void) { volatile int64_t x710 = INT64_MIN; uint16_t x712 = 73U; static volatile int32_t t170 = 164; t170 = ((x709/x710)==(x711^x712)); if (t170 != 0) { NG(); } else { ; } } void f171(void) { static uint16_t x714 = UINT16_MAX; int16_t x715 = -1; int16_t x716 = INT16_MAX; int32_t t171 = 392; t171 = ((x713/x714)==(x715^x716)); if (t171 != 1) { NG(); } else { ; } } void f172(void) { int16_t x717 = -2585; int8_t x718 = -1; uint32_t x720 = UINT32_MAX; int32_t t172 = 40; t172 = ((x717/x718)==(x719^x720)); if (t172 != 0) { NG(); } else { ; } } void f173(void) { int32_t x725 = -1; static uint16_t x726 = 12312U; static int8_t x728 = INT8_MAX; volatile int32_t t173 = -71; t173 = ((x725/x726)==(x727^x728)); if (t173 != 0) { NG(); } else { ; } } void f174(void) { volatile int32_t x729 = INT32_MIN; static volatile uint32_t x730 = UINT32_MAX; static int32_t x731 = INT32_MAX; uint64_t x732 = 51900902974608605LLU; int32_t t174 = -10900; t174 = ((x729/x730)==(x731^x732)); if (t174 != 0) { NG(); } else { ; } } void f175(void) { volatile uint32_t x733 = UINT32_MAX; volatile int16_t x735 = INT16_MIN; volatile uint32_t x736 = UINT32_MAX; volatile int32_t t175 = 229; t175 = ((x733/x734)==(x735^x736)); if (t175 != 0) { NG(); } else { ; } } void f176(void) { static int64_t x737 = -1520LL; int16_t x738 = INT16_MIN; static int8_t x739 = INT8_MAX; volatile uint64_t x740 = 15830022LLU; int32_t t176 = 1677; t176 = ((x737/x738)==(x739^x740)); if (t176 != 0) { NG(); } else { ; } } void f177(void) { int64_t x741 = INT64_MAX; uint16_t x742 = UINT16_MAX; uint16_t x743 = 15632U; int64_t x744 = -1LL; volatile int32_t t177 = -38540; t177 = ((x741/x742)==(x743^x744)); if (t177 != 0) { NG(); } else { ; } } void f178(void) { int8_t x746 = -7; volatile uint64_t x747 = UINT64_MAX; int64_t x748 = INT64_MIN; static int32_t t178 = -204863458; t178 = ((x745/x746)==(x747^x748)); if (t178 != 0) { NG(); } else { ; } } void f179(void) { int16_t x749 = -1; static uint32_t x751 = UINT32_MAX; int32_t t179 = 2097043; t179 = ((x749/x750)==(x751^x752)); if (t179 != 0) { NG(); } else { ; } } void f180(void) { static int64_t x754 = INT64_MIN; uint16_t x755 = 3U; uint8_t x756 = UINT8_MAX; int32_t t180 = -6752; t180 = ((x753/x754)==(x755^x756)); if (t180 != 0) { NG(); } else { ; } } void f181(void) { volatile uint16_t x757 = 7869U; int64_t x758 = INT64_MIN; static uint32_t x760 = 1007720U; t181 = ((x757/x758)==(x759^x760)); if (t181 != 0) { NG(); } else { ; } } void f182(void) { int16_t x761 = INT16_MIN; int16_t x762 = -1; uint8_t x763 = 0U; uint16_t x764 = 356U; t182 = ((x761/x762)==(x763^x764)); if (t182 != 0) { NG(); } else { ; } } void f183(void) { int8_t x765 = INT8_MAX; static int16_t x766 = INT16_MIN; int16_t x767 = INT16_MAX; int8_t x768 = INT8_MIN; int32_t t183 = 929261284; t183 = ((x765/x766)==(x767^x768)); if (t183 != 0) { NG(); } else { ; } } void f184(void) { static int16_t x769 = INT16_MIN; int64_t x770 = -1LL; uint8_t x771 = UINT8_MAX; int32_t x772 = INT32_MIN; static volatile int32_t t184 = -42; t184 = ((x769/x770)==(x771^x772)); if (t184 != 0) { NG(); } else { ; } } void f185(void) { uint64_t x773 = 351653LLU; int16_t x774 = -936; static int32_t x775 = INT32_MIN; static int8_t x776 = INT8_MIN; int32_t t185 = -581503; t185 = ((x773/x774)==(x775^x776)); if (t185 != 0) { NG(); } else { ; } } void f186(void) { static volatile int32_t x778 = -1; uint8_t x779 = UINT8_MAX; int8_t x780 = 28; int32_t t186 = 1; t186 = ((x777/x778)==(x779^x780)); if (t186 != 0) { NG(); } else { ; } } void f187(void) { int32_t x782 = -12; uint32_t x783 = 2874223U; static uint16_t x784 = UINT16_MAX; volatile int32_t t187 = 3943; t187 = ((x781/x782)==(x783^x784)); if (t187 != 0) { NG(); } else { ; } } void f188(void) { uint32_t x785 = UINT32_MAX; static int32_t x786 = INT32_MIN; int64_t x787 = -1LL; t188 = ((x785/x786)==(x787^x788)); if (t188 != 0) { NG(); } else { ; } } void f189(void) { volatile int32_t x789 = -194; static int8_t x790 = INT8_MAX; volatile uint64_t x791 = 603108LLU; static uint16_t x792 = 30500U; volatile int32_t t189 = 16; t189 = ((x789/x790)==(x791^x792)); if (t189 != 0) { NG(); } else { ; } } void f190(void) { uint8_t x793 = 5U; int16_t x794 = INT16_MIN; int8_t x795 = -1; volatile int16_t x796 = 1; t190 = ((x793/x794)==(x795^x796)); if (t190 != 0) { NG(); } else { ; } } void f191(void) { uint16_t x798 = 13985U; int8_t x799 = 6; static uint32_t x800 = 78U; int32_t t191 = 12437; t191 = ((x797/x798)==(x799^x800)); if (t191 != 0) { NG(); } else { ; } } void f192(void) { int32_t x801 = INT32_MIN; static volatile int8_t x803 = INT8_MAX; volatile uint8_t x804 = UINT8_MAX; volatile int32_t t192 = -1511896; t192 = ((x801/x802)==(x803^x804)); if (t192 != 0) { NG(); } else { ; } } void f193(void) { volatile uint8_t x805 = UINT8_MAX; volatile int8_t x806 = INT8_MIN; int32_t x807 = INT32_MIN; int16_t x808 = INT16_MAX; int32_t t193 = 127973209; t193 = ((x805/x806)==(x807^x808)); if (t193 != 0) { NG(); } else { ; } } void f194(void) { int64_t x809 = -14506151LL; volatile uint64_t x810 = UINT64_MAX; uint64_t x811 = 749LLU; volatile int32_t t194 = 206145; t194 = ((x809/x810)==(x811^x812)); if (t194 != 0) { NG(); } else { ; } } void f195(void) { static int64_t x813 = INT64_MIN; uint8_t x814 = UINT8_MAX; static int64_t x815 = -217721216LL; volatile int32_t t195 = -2066; t195 = ((x813/x814)==(x815^x816)); if (t195 != 0) { NG(); } else { ; } } void f196(void) { int16_t x817 = 1212; int64_t x818 = 74327LL; static uint8_t x819 = 40U; volatile int16_t x820 = -1; static int32_t t196 = 68812626; t196 = ((x817/x818)==(x819^x820)); if (t196 != 0) { NG(); } else { ; } } void f197(void) { uint32_t x822 = 1688147U; static int8_t x823 = INT8_MIN; int32_t t197 = -2; t197 = ((x821/x822)==(x823^x824)); if (t197 != 0) { NG(); } else { ; } } void f198(void) { volatile int64_t x829 = INT64_MIN; static uint64_t x830 = 4128500597219LLU; int16_t x831 = INT16_MAX; volatile int32_t t198 = 72986; t198 = ((x829/x830)==(x831^x832)); if (t198 != 0) { NG(); } else { ; } } void f199(void) { volatile int64_t x833 = -1LL; int16_t x834 = 32; volatile int16_t x836 = 2; int32_t t199 = -3088; t199 = ((x833/x834)==(x835^x836)); if (t199 != 0) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
54191.c
#include "embedded_event_callback.h" #include <string.h> #include <assert.h> embedded_event_callback_t embedded_event_callback_init(embedded_event_handler_t handler, void *context) { embedded_event_callback_t result = (embedded_event_callback_t)malloc(sizeof(struct embedded_event_callback_struct)); result->handler = handler; result->context = context; result->next = NULL; return result; } void embedded_event_callback_append(embedded_event_callback_t *first, embedded_event_callback_t addition) { // Validate the input if(addition == NULL && first == NULL) return; // Check for an empty list if(*first == NULL) { *first = addition; (*first)->next = NULL; return; } // Iterate through the list embedded_event_callback_t current = *first; embedded_event_callback_t next = NULL; while(current->next != NULL) { assert(current->next != current); next = current->next; current = next; } // Store the addition current->next = addition; } void embedded_event_callback_remove(embedded_event_callback_t *first, embedded_event_callback_t removal) { // Validate the input if(first == NULL || removal == NULL) return; // Check for list of 1 if(*first == removal) { *first = removal->next; return; } embedded_event_callback_t parent = *first; embedded_event_callback_t current = (*first)->next; embedded_event_callback_t next = NULL; while(current != NULL) { // Check for a match if(current == removal) { parent->next = current->next; current->next = NULL; return; } next = current->next; parent = current; current = next; } } void embedded_event_callback_clear(embedded_event_callback_t *first) { if(first == NULL || *first == NULL) return; embedded_event_callback_t current = *first; embedded_event_callback_t next = NULL; do { next = embedded_event_callback_destroy(current); current = next; } while(current != NULL); *first = NULL; } embedded_event_callback_t embedded_event_callback_destroy(embedded_event_callback_t reg) { embedded_event_callback_t result = reg->next; free(reg); return result; }
870411.c
#define _GNU_SOURCE #include <float.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "libnewrelic.h" #include "common.h" static void test_app_attributes(newrelic_txn_t* txn); static void test_app_error(newrelic_txn_t* txn); static void test_app_segments(newrelic_txn_t* txn); static newrelic_app_t* test_app_create_app(const char* license, const char* host, const char* app_name); static void test_app_start_background_transaction(newrelic_app_t* app); static void test_app_custom_events(newrelic_txn_t* txn); static void test_app_custom_metrics(newrelic_txn_t* txn); int main(void) { newrelic_app_t* app = 0; newrelic_txn_t* txn = 0; char* license = get_license_key(); if (!license) { return EXIT_FAILURE; } char* app_name = get_app_name(); if (!app_name) { return EXIT_FAILURE; } // if host isn't defined we just won't assign // it, and the agent will use the default char* host = getenv("NEW_RELIC_HOST"); /* No explicit newrelic_init(); we'll let the defaults work their magic. */ newrelic_configure_log("./c_sdk.log", NEWRELIC_LOG_DEBUG); app = test_app_create_app(license, host, app_name); if (!app) { printf("Error: Could not Create Application, is a daemon running?"); return 1; } /* Start a web transaction */ txn = newrelic_start_web_transaction(app, "veryImportantWebTransaction"); test_app_attributes(txn); test_app_error(txn); test_app_segments(txn); test_app_custom_events(txn); test_app_custom_metrics(txn); /* End web transaction */ newrelic_end_transaction(&txn); test_app_start_background_transaction(app); newrelic_destroy_app(&app); return 0; } static void test_app_attributes(newrelic_txn_t* txn) { /* Add attributes */ newrelic_add_attribute_int(txn, "my_custom_int", INT_MAX); newrelic_add_attribute_string(txn, "my_custom_string", "String String String"); sleep(1); } static void test_app_error(newrelic_txn_t* txn) { int priority = 50; /* Record an error */ newrelic_notice_error(txn, priority, "Meaningful error message", "Error.class"); } static void test_app_segments(newrelic_txn_t* txn) { newrelic_segment_t* segment1 = 0; newrelic_segment_t* segment2 = 0; /* Add segments */ segment1 = newrelic_start_segment(txn, "Stuff", "Custom"); sleep(1); newrelic_end_segment(txn, &segment1); segment2 = newrelic_start_segment(txn, "More Stuff", "Custom"); sleep(1); segment1 = newrelic_start_segment(txn, "Nested Stuff", "Custom"); sleep(1); newrelic_end_segment(txn, &segment1); sleep(1); newrelic_end_segment(txn, &segment2); } static newrelic_app_t* test_app_create_app(const char* license, const char* host, const char* app_name) { newrelic_app_t* app = 0; newrelic_app_config_t* config = 0; config = newrelic_create_app_config(app_name, license); if (NULL != host) { strcpy(config->redirect_collector, host); } config->transaction_tracer.threshold = NEWRELIC_THRESHOLD_IS_OVER_DURATION; config->transaction_tracer.duration_us = 1; /* Wait up to 10 seconds for the SDK to connect to the daemon */ app = newrelic_create_app(config, 10000); newrelic_destroy_app_config(&config); return app; } static void test_app_start_background_transaction(newrelic_app_t* app) { newrelic_txn_t* txn = 0; /* Start and end a non-web transaction */ txn = newrelic_start_non_web_transaction(app, "veryImportantOtherTransaction"); sleep(1); newrelic_end_transaction(&txn); } static void test_app_custom_events(newrelic_txn_t* txn) { newrelic_custom_event_t* custom_event = 0; /* Record a custom event with each type of attribute available in the API */ custom_event = newrelic_create_custom_event("aTypeForYourEvent"); newrelic_custom_event_add_attribute_int(custom_event, "keya", 42); newrelic_custom_event_add_attribute_long(custom_event, "keyb", 84); newrelic_custom_event_add_attribute_double(custom_event, "keyc", 42.42); newrelic_custom_event_add_attribute_string(custom_event, "keyd", "A string"); newrelic_record_custom_event(txn, &custom_event); } static void test_app_custom_metrics(newrelic_txn_t* txn) { /* Record a metric value of 100ms in the transaction txn */ newrelic_record_custom_metric(txn, "Custom/YourMetric/Label", 100); }
92019.c
#include <pthread.h> #include <stdio.h> #include <sys/select.h> #include <string.h> #include <time.h> #include <unistd.h> #include "common.h" #include "device.h" #include "serial.h" int get_name(device_t* ctx, char* name, int name_len) { int sent, ret; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; sent = dvap_write(ctx, DVAP_MSG_HOST_REQ_CTRL_ITEM, DVAP_CTRL_TARGET_NAME, NULL, 0); if (sent <= 0) { debug_print("%s\n", "get_name: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); ret -= 2; ret = (ret <= name_len) ? ret : name_len; strncpy(name, (const char *)&buf[2], ret); return TRUE; } int set_run_state(device_t* ctx, char state) { int sent, ret; unsigned char payload[1]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = state; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_RUN_STATE, payload, 1); if (sent <= 0) { debug_print("%s\n", "set_run_state: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_modulation_type(device_t* ctx, char modulation) { int sent, ret; unsigned char payload[1]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = modulation; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_MODULATION_TYPE, payload, 1); if (sent <= 0) { debug_print("%s\n", "set_modulation_type: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_operation_mode(device_t* ctx, char mode) { int sent, ret; unsigned char payload[1]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = mode; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_OPERATION_MODE, payload, 1); if (sent <= 0) { debug_print("%s\n", "set_operation_mode: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_squelch_threshold(device_t* ctx, int dbm) { int sent, ret; int squelch = dbm; unsigned char payload[1]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; squelch = (dbm < DVAP_SQUELCH_MIN) ? DVAP_SQUELCH_MIN : squelch; squelch = (dbm < DVAP_SQUELCH_MAX) ? DVAP_SQUELCH_MAX : squelch; payload[0] = squelch & 0xFF; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_SQUELCH_THRESH, payload, 1); if (sent <= 0) { debug_print("%s\n", "set_squelch_threshold: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_rx_frequency(device_t* ctx, unsigned int hz) { int sent, ret; unsigned char payload[4]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = hz & 0xFF; payload[1] = (hz >> 8) & 0xFF; payload[2] = (hz >> 16) & 0xFF; payload[3] = (hz >> 24) & 0xFF; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_RX_FREQ, payload, 4); if (sent <= 0) { debug_print("%s\n", "set_rx_frequency: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_tx_frequency(device_t* ctx, unsigned int hz) { int sent, ret; unsigned char payload[4]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = hz & 0xFF; payload[1] = (hz >> 8) & 0xFF; payload[2] = (hz >> 16) & 0xFF; payload[3] = (hz >> 24) & 0xFF; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_TX_FREQ, payload, 4); if (sent <= 0) { debug_print("%s\n", "set_tx_frequency: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_rxtx_frequency(device_t* ctx, unsigned int hz) { int sent, ret; unsigned char payload[4]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; payload[0] = hz & 0xFF; payload[1] = (hz >> 8) & 0xFF; payload[2] = (hz >> 16) & 0xFF; payload[3] = (hz >> 24) & 0xFF; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_TX_RX_FREQ, payload, 4); if (sent <= 0) { debug_print("%s\n", "set_rxtx_frequency: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int set_tx_power(device_t* ctx, int dbm) { int sent, ret; int power; unsigned char payload[2]; unsigned char buf[DVAP_MSG_MAX_BYTES]; if (!ctx) return FALSE; power = (dbm < DVAP_TX_POWER_MIN) ? DVAP_TX_POWER_MIN : dbm; power = (dbm > DVAP_TX_POWER_MAX) ? DVAP_TX_POWER_MAX : dbm; payload[0] = power & 0xFF; payload[1] = (power >> 8) & 0xFF; sent = dvap_write(ctx, DVAP_MSG_HOST_SET_CTRL, DVAP_CTRL_TX_RX_FREQ, payload, 2); if (sent <= 0) { debug_print("%s\n", "set_tx_power: error on dvap_write"); return FALSE; } queue_remove(&(ctx->rxq), buf, &ret); return TRUE; } int dvap_init(device_t* ctx, char* portname, dvap_rx_fptr callback) { int fd; if (!ctx) return FALSE; ctx->callback = callback; // serial port fd = serial_open(portname, DVAP_BAUD); if (fd < 0) { return FALSE; } ctx->fd = fd; // shutdown variables ctx->shutdown = FALSE; pthread_mutex_init(&(ctx->shutdown_mutex), NULL); // transmitter variables pthread_mutex_init(&(ctx->tx_mutex), NULL); pthread_mutex_init(&(ctx->ptt_mutex), NULL); ctx->ptt_active = FALSE; // receive queue queue_init(&(ctx->rxq)); pthread_create(&(ctx->rx_thread), NULL, dvap_read_loop, ctx); return TRUE; } int dvap_start(device_t* ctx) { if (!ctx) return FALSE; if (!set_run_state(ctx, DVAP_RUN_STATE_RUN)) { fprintf(stderr, "Error setting DVAP run state to RUN\n"); return FALSE; } pthread_create(&(ctx->watchdog_thread), NULL, dvap_watchdog_loop, ctx); return TRUE; } void dvap_wait(device_t* ctx) { if (!ctx) return; pthread_join(ctx->rx_thread, NULL); pthread_join(ctx->watchdog_thread, NULL); close(ctx->fd); pthread_mutex_destroy(&(ctx->shutdown_mutex)); pthread_mutex_destroy(&(ctx->tx_mutex)); } int dvap_stop(device_t* ctx) { if (!ctx) return FALSE; if (!set_run_state(ctx, DVAP_RUN_STATE_STOP)) { fprintf(stderr, "Error setting DVAP run state to STOP\n"); return FALSE; } pthread_mutex_lock(&(ctx->shutdown_mutex)); ctx->shutdown = TRUE; pthread_mutex_unlock(&(ctx->shutdown_mutex)); return TRUE; } int dvap_pkt_write(device_t* ctx, unsigned char* buf, int buf_bytes) { int n; int sent_bytes = 0; pthread_mutex_lock(&(ctx->tx_mutex)); while (sent_bytes < buf_bytes) { n = write(ctx->fd, &buf[sent_bytes], buf_bytes-sent_bytes); if (DEBUG) { printf("[%ld] dvap_pkt_write: %d bytes\n", time(NULL), buf_bytes); } if (n <= 0) { pthread_mutex_unlock(&(ctx->tx_mutex)); fprintf(stderr, "dvap_pkt_write - error writing to device\n"); return -1; } sent_bytes += n; } pthread_mutex_unlock(&(ctx->tx_mutex)); return sent_bytes; } int dvap_write(device_t* ctx, char msg_type, int command, unsigned char* payload, int payload_bytes) { int n; int total_sent_bytes = 0; int payload_sent_bytes = 0; unsigned char buf[4]; int pktlen; if (!ctx) return -1; if (payload_bytes > DVAP_MSG_MAX_BYTES-4) { fprintf(stderr, "Error in send_command, payload too long\n"); return -1; } pktlen = 4 + payload_bytes; buf[0] = pktlen & 0xFF; buf[1] = (msg_type << 5) | ((pktlen & 0x1F00) >> 8); buf[2] = command & 0xFF; buf[3] = (command >> 8) & 0xFF; if (DEBUG) { hex_dump("tx", buf, 4); } pthread_mutex_lock(&(ctx->tx_mutex)); while(total_sent_bytes < 4) { n = write(ctx->fd, &buf[total_sent_bytes], 4-total_sent_bytes); if (n <= 0) { pthread_mutex_unlock(&(ctx->tx_mutex)); debug_print("dvap_write - returned %d\n", n); return n; } total_sent_bytes += n; } if (payload) { if (DEBUG) { hex_dump("tx payload", payload, payload_bytes); } while(payload_sent_bytes < payload_bytes) { n = write(ctx->fd, &payload[payload_sent_bytes], payload_bytes-payload_sent_bytes); if (n <= 0) { pthread_mutex_unlock(&(ctx->tx_mutex)); debug_print("dvap_write - returned %d\n", n); return n; } payload_sent_bytes += n; total_sent_bytes += n; } } pthread_mutex_unlock(&(ctx->tx_mutex)); return total_sent_bytes; } int dvap_read(device_t* ctx, char* msg_type, unsigned char* buf, int buf_bytes) { if (!ctx) return -1; return packet_read(ctx->fd, msg_type, buf, buf_bytes); } int dvap_should_shutdown(device_t* ctx) { int shutdown; if (!ctx) return TRUE; pthread_mutex_lock(&(ctx->shutdown_mutex)); shutdown = ctx->shutdown; pthread_mutex_unlock(&(ctx->shutdown_mutex)); return shutdown; } void* dvap_watchdog_loop(void* arg) { device_t* ctx = (device_t *)arg; unsigned char buf[3]; int ptt_active; int counter = DVAP_WATCHDOG_SECS; buf[0] = 0x03; buf[1] = 0x60; buf[2] = 0x00; while (!dvap_should_shutdown(ctx)) { if (counter <= 0) { pthread_mutex_lock(&(ctx->ptt_mutex)); ptt_active = ctx->ptt_active; pthread_mutex_unlock(&(ctx->ptt_mutex)); // Only send watchdog keepalive message if transmitter is not in use if (!ptt_active) { pthread_mutex_lock(&(ctx->tx_mutex)); write(ctx->fd, buf, 3); pthread_mutex_unlock(&(ctx->tx_mutex)); counter = DVAP_WATCHDOG_SECS; if (DEBUG) { hex_dump("watchdog tx", buf, 3); } } } counter -= 1; sleep(1); } return NULL; } void* dvap_read_loop(void* arg) { device_t* ctx = (device_t *)arg; fd_set set; char msg_type; int ret; unsigned char buf[DVAP_MSG_MAX_BYTES]; struct timeval timeout; while(!dvap_should_shutdown(ctx)) { // Check if data is available for reading // Timeout and try again if nothing is available FD_ZERO(&set); FD_SET(ctx->fd, &set); // Linux version of select overwrites timeout, so we set it on each // iteration of the while loop timeout.tv_sec = 0; timeout.tv_usec = DVAP_READ_TIMEOUT_USEC; ret = select(ctx->fd+1, &set, NULL, NULL, &timeout); if (ret < 0) { fprintf(stderr, "Error waiting for data from DVAP\n"); return NULL; } else if (ret == 0) { //debug_print("%s\n", "DVAP select timeout"); continue; } // Read packet ret = dvap_read(ctx, &msg_type, buf, DVAP_MSG_MAX_BYTES); if (ret < 0) { fprintf(stderr, "Error reading from DVAP\n"); return NULL; } else if (ret == 0) { fprintf(stderr, "Timeout while reading from DVAP\n"); return NULL; } // Call appropriate handler depending on message type switch (msg_type) { // Response to a host initiated request case DVAP_MSG_TARGET_ITEM_RESPONSE: case DVAP_MSG_TARGET_RANGE_RESPONSE: queue_insert(&(ctx->rxq), &buf[2], ret-2); if (DEBUG) { hex_dump("rx", buf, ret); } break; // Status message case DVAP_MSG_TARGET_UNSOLICITED: dvap_parse_rx_unsolicited(ctx, &buf[2], ret-2); break; // Ignore target data acks for now case DVAP_MSG_TARGET_DATA_ACK: break; // Radio data case DVAP_MSG_TARGET_DATA_ITEM_0: case DVAP_MSG_TARGET_DATA_ITEM_1: case DVAP_MSG_TARGET_DATA_ITEM_2: case DVAP_MSG_TARGET_DATA_ITEM_3: (ctx->callback)(buf, ret); break; default: fprintf(stderr, "rx: unrecognized response type: %d\n", msg_type); break; } } return NULL; } void dvap_parse_rx_unsolicited(device_t* ctx, unsigned char* buf, int buf_len) { int ctrl_code = (buf[1] << 8) + buf[0]; switch (ctrl_code) { case DVAP_CTRL_OPERATIONAL_STATUS: //dvap_print_operational_status(buf, buf_len); break; case DVAP_CTRL_PTT_STATE: //dvap_print_ptt_state(buf, buf_len); pthread_mutex_lock(&(ctx->ptt_mutex)); if (buf_len >= 3) { if (buf[2] <= 0) { ctx->ptt_active = FALSE; } else { ctx->ptt_active = TRUE; } } pthread_mutex_unlock(&(ctx->ptt_mutex)); break; case DVAP_CTRL_DTMF_MSG: dvap_print_dtmf(buf, buf_len); break; default: if (DEBUG) { hex_dump("rx unsolicited other", buf, buf_len); } break; } } void dvap_print_operational_status(unsigned char* buf, int buf_len) { char rssi, squelch, fifo_free; if (buf_len < 5) return; rssi = buf[2]; squelch = buf[3]; fifo_free = buf[4]; printf("rssi: %04d, squelch: %d, tx fifo free: %03d\n", rssi, squelch, fifo_free); } void dvap_print_ptt_state(unsigned char* buf, int buf_len) { if (buf_len < 3) return; if (buf[2] <= 0) { printf("ptt: receive active\n"); } else { printf("ptt: transmit active\n"); } } void dvap_print_dtmf(unsigned char* buf, int buf_len) { if (buf_len < 3) return; if (buf[2] == 0) { printf("dtmf: release\n"); } else { printf("dtmf: %c\n", buf[2]); } }
262866.c
#include "cache.h" #include "grep.h" #include "userdiff.h" #include "xdiff-interface.h" #include "diff.h" #include "diffcore.h" static int grep_source_load(struct grep_source *gs); static int grep_source_is_binary(struct grep_source *gs); static struct grep_opt grep_defaults; /* * Initialize the grep_defaults template with hardcoded defaults. * We could let the compiler do this, but without C99 initializers * the code gets unwieldy and unreadable, so... */ void init_grep_defaults(void) { struct grep_opt *opt = &grep_defaults; static int run_once; if (run_once) return; run_once++; memset(opt, 0, sizeof(*opt)); opt->relative = 1; opt->pathname = 1; opt->regflags = REG_NEWLINE; opt->max_depth = -1; opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED; opt->extended_regexp_option = 0; strcpy(opt->color_context, ""); strcpy(opt->color_filename, ""); strcpy(opt->color_function, ""); strcpy(opt->color_lineno, ""); strcpy(opt->color_match_context, GIT_COLOR_BOLD_RED); strcpy(opt->color_match_selected, GIT_COLOR_BOLD_RED); strcpy(opt->color_selected, ""); strcpy(opt->color_sep, GIT_COLOR_CYAN); opt->color = -1; } static int parse_pattern_type_arg(const char *opt, const char *arg) { if (!strcmp(arg, "default")) return GREP_PATTERN_TYPE_UNSPECIFIED; else if (!strcmp(arg, "basic")) return GREP_PATTERN_TYPE_BRE; else if (!strcmp(arg, "extended")) return GREP_PATTERN_TYPE_ERE; else if (!strcmp(arg, "fixed")) return GREP_PATTERN_TYPE_FIXED; else if (!strcmp(arg, "perl")) return GREP_PATTERN_TYPE_PCRE; die("bad %s argument: %s", opt, arg); } /* * Read the configuration file once and store it in * the grep_defaults template. */ int grep_config(const char *var, const char *value, void *cb) { struct grep_opt *opt = &grep_defaults; char *color = NULL; if (userdiff_config(var, value) < 0) return -1; if (!strcmp(var, "grep.extendedregexp")) { if (git_config_bool(var, value)) opt->extended_regexp_option = 1; else opt->extended_regexp_option = 0; return 0; } if (!strcmp(var, "grep.patterntype")) { opt->pattern_type_option = parse_pattern_type_arg(var, value); return 0; } if (!strcmp(var, "grep.linenumber")) { opt->linenum = git_config_bool(var, value); return 0; } if (!strcmp(var, "grep.fullname")) { opt->relative = !git_config_bool(var, value); return 0; } if (!strcmp(var, "color.grep")) opt->color = git_config_colorbool(var, value); else if (!strcmp(var, "color.grep.context")) color = opt->color_context; else if (!strcmp(var, "color.grep.filename")) color = opt->color_filename; else if (!strcmp(var, "color.grep.function")) color = opt->color_function; else if (!strcmp(var, "color.grep.linenumber")) color = opt->color_lineno; else if (!strcmp(var, "color.grep.matchcontext")) color = opt->color_match_context; else if (!strcmp(var, "color.grep.matchselected")) color = opt->color_match_selected; else if (!strcmp(var, "color.grep.selected")) color = opt->color_selected; else if (!strcmp(var, "color.grep.separator")) color = opt->color_sep; else if (!strcmp(var, "color.grep.match")) { int rc = 0; if (!value) return config_error_nonbool(var); rc |= color_parse(value, opt->color_match_context); rc |= color_parse(value, opt->color_match_selected); return rc; } if (color) { if (!value) return config_error_nonbool(var); return color_parse(value, color); } return 0; } /* * Initialize one instance of grep_opt and copy the * default values from the template we read the configuration * information in an earlier call to git_config(grep_config). */ void grep_init(struct grep_opt *opt, const char *prefix) { struct grep_opt *def = &grep_defaults; memset(opt, 0, sizeof(*opt)); opt->prefix = prefix; opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0; opt->pattern_tail = &opt->pattern_list; opt->header_tail = &opt->header_list; opt->color = def->color; opt->extended_regexp_option = def->extended_regexp_option; opt->pattern_type_option = def->pattern_type_option; opt->linenum = def->linenum; opt->max_depth = def->max_depth; opt->pathname = def->pathname; opt->regflags = def->regflags; opt->relative = def->relative; strcpy(opt->color_context, def->color_context); strcpy(opt->color_filename, def->color_filename); strcpy(opt->color_function, def->color_function); strcpy(opt->color_lineno, def->color_lineno); strcpy(opt->color_match_context, def->color_match_context); strcpy(opt->color_match_selected, def->color_match_selected); strcpy(opt->color_selected, def->color_selected); strcpy(opt->color_sep, def->color_sep); } void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt) { if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED) grep_set_pattern_type_option(pattern_type, opt); else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED) grep_set_pattern_type_option(opt->pattern_type_option, opt); else if (opt->extended_regexp_option) grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt); } void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt) { switch (pattern_type) { case GREP_PATTERN_TYPE_UNSPECIFIED: /* fall through */ case GREP_PATTERN_TYPE_BRE: opt->fixed = 0; opt->pcre = 0; opt->regflags &= ~REG_EXTENDED; break; case GREP_PATTERN_TYPE_ERE: opt->fixed = 0; opt->pcre = 0; opt->regflags |= REG_EXTENDED; break; case GREP_PATTERN_TYPE_FIXED: opt->fixed = 1; opt->pcre = 0; opt->regflags &= ~REG_EXTENDED; break; case GREP_PATTERN_TYPE_PCRE: opt->fixed = 0; opt->pcre = 1; opt->regflags &= ~REG_EXTENDED; break; } } static struct grep_pat *create_grep_pat(const char *pat, size_t patlen, const char *origin, int no, enum grep_pat_token t, enum grep_header_field field) { struct grep_pat *p = xcalloc(1, sizeof(*p)); p->pattern = xmemdupz(pat, patlen); p->patternlen = patlen; p->origin = origin; p->no = no; p->token = t; p->field = field; return p; } static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p) { **tail = p; *tail = &p->next; p->next = NULL; switch (p->token) { case GREP_PATTERN: /* atom */ case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: for (;;) { struct grep_pat *new_pat; size_t len = 0; char *cp = p->pattern + p->patternlen, *nl = NULL; while (++len <= p->patternlen) { if (*(--cp) == '\n') { nl = cp; break; } } if (!nl) break; new_pat = create_grep_pat(nl + 1, len - 1, p->origin, p->no, p->token, p->field); new_pat->next = p->next; if (!p->next) *tail = &new_pat->next; p->next = new_pat; *nl = '\0'; p->patternlen -= len; } break; default: break; } } void append_header_grep_pattern(struct grep_opt *opt, enum grep_header_field field, const char *pat) { struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0, GREP_PATTERN_HEAD, field); if (field == GREP_HEADER_REFLOG) opt->use_reflog_filter = 1; do_append_grep_pat(&opt->header_tail, p); } void append_grep_pattern(struct grep_opt *opt, const char *pat, const char *origin, int no, enum grep_pat_token t) { append_grep_pat(opt, pat, strlen(pat), origin, no, t); } void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen, const char *origin, int no, enum grep_pat_token t) { struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0); do_append_grep_pat(&opt->pattern_tail, p); } struct grep_opt *grep_opt_dup(const struct grep_opt *opt) { struct grep_pat *pat; struct grep_opt *ret = xmalloc(sizeof(struct grep_opt)); *ret = *opt; ret->pattern_list = NULL; ret->pattern_tail = &ret->pattern_list; for(pat = opt->pattern_list; pat != NULL; pat = pat->next) { if(pat->token == GREP_PATTERN_HEAD) append_header_grep_pattern(ret, pat->field, pat->pattern); else append_grep_pat(ret, pat->pattern, pat->patternlen, pat->origin, pat->no, pat->token); } return ret; } static NORETURN void compile_regexp_failed(const struct grep_pat *p, const char *error) { char where[1024]; if (p->no) sprintf(where, "In '%s' at %d, ", p->origin, p->no); else if (p->origin) sprintf(where, "%s, ", p->origin); else where[0] = 0; die("%s'%s': %s", where, p->pattern, error); } #ifdef USE_LIBPCRE static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt) { const char *error; int erroffset; int options = PCRE_MULTILINE; if (opt->ignore_case) options |= PCRE_CASELESS; p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset, NULL); if (!p->pcre_regexp) compile_regexp_failed(p, error); p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error); if (!p->pcre_extra_info && error) die("%s", error); } static int pcrematch(struct grep_pat *p, const char *line, const char *eol, regmatch_t *match, int eflags) { int ovector[30], ret, flags = 0; if (eflags & REG_NOTBOL) flags |= PCRE_NOTBOL; ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line, 0, flags, ovector, ARRAY_SIZE(ovector)); if (ret < 0 && ret != PCRE_ERROR_NOMATCH) die("pcre_exec failed with error code %d", ret); if (ret > 0) { ret = 0; match->rm_so = ovector[0]; match->rm_eo = ovector[1]; } return ret; } static void free_pcre_regexp(struct grep_pat *p) { pcre_free(p->pcre_regexp); pcre_free(p->pcre_extra_info); } #else /* !USE_LIBPCRE */ static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt) { die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE"); } static int pcrematch(struct grep_pat *p, const char *line, const char *eol, regmatch_t *match, int eflags) { return 1; } static void free_pcre_regexp(struct grep_pat *p) { } #endif /* !USE_LIBPCRE */ static int is_fixed(const char *s, size_t len) { size_t i; /* regcomp cannot accept patterns with NULs so we * consider any pattern containing a NUL fixed. */ if (memchr(s, 0, len)) return 1; for (i = 0; i < len; i++) { if (is_regex_special(s[i])) return 0; } return 1; } static void compile_regexp(struct grep_pat *p, struct grep_opt *opt) { int err; p->word_regexp = opt->word_regexp; p->ignore_case = opt->ignore_case; if (opt->fixed || is_fixed(p->pattern, p->patternlen)) p->fixed = 1; else p->fixed = 0; if (p->fixed) { if (opt->regflags & REG_ICASE || p->ignore_case) p->kws = kwsalloc(tolower_trans_tbl); else p->kws = kwsalloc(NULL); kwsincr(p->kws, p->pattern, p->patternlen); kwsprep(p->kws); return; } if (opt->pcre) { compile_pcre_regexp(p, opt); return; } err = regcomp(&p->regexp, p->pattern, opt->regflags); if (err) { char errbuf[1024]; regerror(err, &p->regexp, errbuf, 1024); regfree(&p->regexp); compile_regexp_failed(p, errbuf); } } static struct grep_expr *compile_pattern_or(struct grep_pat **); static struct grep_expr *compile_pattern_atom(struct grep_pat **list) { struct grep_pat *p; struct grep_expr *x; p = *list; if (!p) return NULL; switch (p->token) { case GREP_PATTERN: /* atom */ case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: x = xcalloc(1, sizeof (struct grep_expr)); x->node = GREP_NODE_ATOM; x->u.atom = p; *list = p->next; return x; case GREP_OPEN_PAREN: *list = p->next; x = compile_pattern_or(list); if (!*list || (*list)->token != GREP_CLOSE_PAREN) die("unmatched parenthesis"); *list = (*list)->next; return x; default: return NULL; } } static struct grep_expr *compile_pattern_not(struct grep_pat **list) { struct grep_pat *p; struct grep_expr *x; p = *list; if (!p) return NULL; switch (p->token) { case GREP_NOT: if (!p->next) die("--not not followed by pattern expression"); *list = p->next; x = xcalloc(1, sizeof (struct grep_expr)); x->node = GREP_NODE_NOT; x->u.unary = compile_pattern_not(list); if (!x->u.unary) die("--not followed by non pattern expression"); return x; default: return compile_pattern_atom(list); } } static struct grep_expr *compile_pattern_and(struct grep_pat **list) { struct grep_pat *p; struct grep_expr *x, *y, *z; x = compile_pattern_not(list); p = *list; if (p && p->token == GREP_AND) { if (!p->next) die("--and not followed by pattern expression"); *list = p->next; y = compile_pattern_and(list); if (!y) die("--and not followed by pattern expression"); z = xcalloc(1, sizeof (struct grep_expr)); z->node = GREP_NODE_AND; z->u.binary.left = x; z->u.binary.right = y; return z; } return x; } static struct grep_expr *compile_pattern_or(struct grep_pat **list) { struct grep_pat *p; struct grep_expr *x, *y, *z; x = compile_pattern_and(list); p = *list; if (x && p && p->token != GREP_CLOSE_PAREN) { y = compile_pattern_or(list); if (!y) die("not a pattern expression %s", p->pattern); z = xcalloc(1, sizeof (struct grep_expr)); z->node = GREP_NODE_OR; z->u.binary.left = x; z->u.binary.right = y; return z; } return x; } static struct grep_expr *compile_pattern_expr(struct grep_pat **list) { return compile_pattern_or(list); } static void indent(int in) { while (in-- > 0) fputc(' ', stderr); } static void dump_grep_pat(struct grep_pat *p) { switch (p->token) { case GREP_AND: fprintf(stderr, "*and*"); break; case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break; case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break; case GREP_NOT: fprintf(stderr, "*not*"); break; case GREP_OR: fprintf(stderr, "*or*"); break; case GREP_PATTERN: fprintf(stderr, "pattern"); break; case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break; case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break; } switch (p->token) { default: break; case GREP_PATTERN_HEAD: fprintf(stderr, "<head %d>", p->field); break; case GREP_PATTERN_BODY: fprintf(stderr, "<body>"); break; } switch (p->token) { default: break; case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: case GREP_PATTERN: fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern); break; } fputc('\n', stderr); } static void dump_grep_expression_1(struct grep_expr *x, int in) { indent(in); switch (x->node) { case GREP_NODE_TRUE: fprintf(stderr, "true\n"); break; case GREP_NODE_ATOM: dump_grep_pat(x->u.atom); break; case GREP_NODE_NOT: fprintf(stderr, "(not\n"); dump_grep_expression_1(x->u.unary, in+1); indent(in); fprintf(stderr, ")\n"); break; case GREP_NODE_AND: fprintf(stderr, "(and\n"); dump_grep_expression_1(x->u.binary.left, in+1); dump_grep_expression_1(x->u.binary.right, in+1); indent(in); fprintf(stderr, ")\n"); break; case GREP_NODE_OR: fprintf(stderr, "(or\n"); dump_grep_expression_1(x->u.binary.left, in+1); dump_grep_expression_1(x->u.binary.right, in+1); indent(in); fprintf(stderr, ")\n"); break; } } static void dump_grep_expression(struct grep_opt *opt) { struct grep_expr *x = opt->pattern_expression; if (opt->all_match) fprintf(stderr, "[all-match]\n"); dump_grep_expression_1(x, 0); fflush(NULL); } static struct grep_expr *grep_true_expr(void) { struct grep_expr *z = xcalloc(1, sizeof(*z)); z->node = GREP_NODE_TRUE; return z; } static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right) { struct grep_expr *z = xcalloc(1, sizeof(*z)); z->node = GREP_NODE_OR; z->u.binary.left = left; z->u.binary.right = right; return z; } static struct grep_expr *prep_header_patterns(struct grep_opt *opt) { struct grep_pat *p; struct grep_expr *header_expr; struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]); enum grep_header_field fld; if (!opt->header_list) return NULL; for (p = opt->header_list; p; p = p->next) { if (p->token != GREP_PATTERN_HEAD) die("bug: a non-header pattern in grep header list."); if (p->field < GREP_HEADER_FIELD_MIN || GREP_HEADER_FIELD_MAX <= p->field) die("bug: unknown header field %d", p->field); compile_regexp(p, opt); } for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) header_group[fld] = NULL; for (p = opt->header_list; p; p = p->next) { struct grep_expr *h; struct grep_pat *pp = p; h = compile_pattern_atom(&pp); if (!h || pp != p->next) die("bug: malformed header expr"); if (!header_group[p->field]) { header_group[p->field] = h; continue; } header_group[p->field] = grep_or_expr(h, header_group[p->field]); } header_expr = NULL; for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) { if (!header_group[fld]) continue; if (!header_expr) header_expr = grep_true_expr(); header_expr = grep_or_expr(header_group[fld], header_expr); } return header_expr; } static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y) { struct grep_expr *z = x; while (x) { assert(x->node == GREP_NODE_OR); if (x->u.binary.right && x->u.binary.right->node == GREP_NODE_TRUE) { x->u.binary.right = y; break; } x = x->u.binary.right; } return z; } static void compile_grep_patterns_real(struct grep_opt *opt) { struct grep_pat *p; struct grep_expr *header_expr = prep_header_patterns(opt); for (p = opt->pattern_list; p; p = p->next) { switch (p->token) { case GREP_PATTERN: /* atom */ case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: compile_regexp(p, opt); break; default: opt->extended = 1; break; } } if (opt->all_match || header_expr) opt->extended = 1; else if (!opt->extended && !opt->debug) return; p = opt->pattern_list; if (p) opt->pattern_expression = compile_pattern_expr(&p); if (p) die("incomplete pattern expression: %s", p->pattern); if (!header_expr) return; if (!opt->pattern_expression) opt->pattern_expression = header_expr; else if (opt->all_match) opt->pattern_expression = grep_splice_or(header_expr, opt->pattern_expression); else opt->pattern_expression = grep_or_expr(opt->pattern_expression, header_expr); opt->all_match = 1; } void compile_grep_patterns(struct grep_opt *opt) { compile_grep_patterns_real(opt); if (opt->debug) dump_grep_expression(opt); } static void free_pattern_expr(struct grep_expr *x) { switch (x->node) { case GREP_NODE_TRUE: case GREP_NODE_ATOM: break; case GREP_NODE_NOT: free_pattern_expr(x->u.unary); break; case GREP_NODE_AND: case GREP_NODE_OR: free_pattern_expr(x->u.binary.left); free_pattern_expr(x->u.binary.right); break; } free(x); } void free_grep_patterns(struct grep_opt *opt) { struct grep_pat *p, *n; for (p = opt->pattern_list; p; p = n) { n = p->next; switch (p->token) { case GREP_PATTERN: /* atom */ case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: if (p->kws) kwsfree(p->kws); else if (p->pcre_regexp) free_pcre_regexp(p); else regfree(&p->regexp); free(p->pattern); break; default: break; } free(p); } if (!opt->extended) return; free_pattern_expr(opt->pattern_expression); } static char *end_of_line(char *cp, unsigned long *left) { unsigned long l = *left; while (l && *cp != '\n') { l--; cp++; } *left = l; return cp; } static int word_char(char ch) { return isalnum(ch) || ch == '_'; } static void output_color(struct grep_opt *opt, const void *data, size_t size, const char *color) { if (want_color(opt->color) && color && color[0]) { opt->output(opt, color, strlen(color)); opt->output(opt, data, size); opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET)); } else opt->output(opt, data, size); } static void output_sep(struct grep_opt *opt, char sign) { if (opt->null_following_name) opt->output(opt, "\0", 1); else output_color(opt, &sign, 1, opt->color_sep); } static void show_name(struct grep_opt *opt, const char *name) { output_color(opt, name, strlen(name), opt->color_filename); opt->output(opt, opt->null_following_name ? "\0" : "\n", 1); } static int fixmatch(struct grep_pat *p, char *line, char *eol, regmatch_t *match) { struct kwsmatch kwsm; size_t offset = kwsexec(p->kws, line, eol - line, &kwsm); if (offset == -1) { match->rm_so = match->rm_eo = -1; return REG_NOMATCH; } else { match->rm_so = offset; match->rm_eo = match->rm_so + kwsm.size[0]; return 0; } } static int regmatch(const regex_t *preg, char *line, char *eol, regmatch_t *match, int eflags) { #ifdef REG_STARTEND match->rm_so = 0; match->rm_eo = eol - line; eflags |= REG_STARTEND; #endif return regexec(preg, line, 1, match, eflags); } static int patmatch(struct grep_pat *p, char *line, char *eol, regmatch_t *match, int eflags) { int hit; if (p->fixed) hit = !fixmatch(p, line, eol, match); else if (p->pcre_regexp) hit = !pcrematch(p, line, eol, match, eflags); else hit = !regmatch(&p->regexp, line, eol, match, eflags); return hit; } static int strip_timestamp(char *bol, char **eol_p) { char *eol = *eol_p; int ch; while (bol < --eol) { if (*eol != '>') continue; *eol_p = ++eol; ch = *eol; *eol = '\0'; return ch; } return 0; } static struct { const char *field; size_t len; } header_field[] = { { "author ", 7 }, { "committer ", 10 }, { "reflog ", 7 }, }; static int match_one_pattern(struct grep_pat *p, char *bol, char *eol, enum grep_context ctx, regmatch_t *pmatch, int eflags) { int hit = 0; int saved_ch = 0; const char *start = bol; if ((p->token != GREP_PATTERN) && ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD))) return 0; if (p->token == GREP_PATTERN_HEAD) { const char *field; size_t len; assert(p->field < ARRAY_SIZE(header_field)); field = header_field[p->field].field; len = header_field[p->field].len; if (strncmp(bol, field, len)) return 0; bol += len; switch (p->field) { case GREP_HEADER_AUTHOR: case GREP_HEADER_COMMITTER: saved_ch = strip_timestamp(bol, &eol); break; default: break; } } again: hit = patmatch(p, bol, eol, pmatch, eflags); if (hit && p->word_regexp) { if ((pmatch[0].rm_so < 0) || (eol - bol) < pmatch[0].rm_so || (pmatch[0].rm_eo < 0) || (eol - bol) < pmatch[0].rm_eo) die("regexp returned nonsense"); /* Match beginning must be either beginning of the * line, or at word boundary (i.e. the last char must * not be a word char). Similarly, match end must be * either end of the line, or at word boundary * (i.e. the next char must not be a word char). */ if ( ((pmatch[0].rm_so == 0) || !word_char(bol[pmatch[0].rm_so-1])) && ((pmatch[0].rm_eo == (eol-bol)) || !word_char(bol[pmatch[0].rm_eo])) ) ; else hit = 0; /* Words consist of at least one character. */ if (pmatch->rm_so == pmatch->rm_eo) hit = 0; if (!hit && pmatch[0].rm_so + bol + 1 < eol) { /* There could be more than one match on the * line, and the first match might not be * strict word match. But later ones could be! * Forward to the next possible start, i.e. the * next position following a non-word char. */ bol = pmatch[0].rm_so + bol + 1; while (word_char(bol[-1]) && bol < eol) bol++; eflags |= REG_NOTBOL; if (bol < eol) goto again; } } if (p->token == GREP_PATTERN_HEAD && saved_ch) *eol = saved_ch; if (hit) { pmatch[0].rm_so += bol - start; pmatch[0].rm_eo += bol - start; } return hit; } static int match_expr_eval(struct grep_expr *x, char *bol, char *eol, enum grep_context ctx, int collect_hits) { int h = 0; regmatch_t match; if (!x) die("Not a valid grep expression"); switch (x->node) { case GREP_NODE_TRUE: h = 1; break; case GREP_NODE_ATOM: h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0); break; case GREP_NODE_NOT: h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0); break; case GREP_NODE_AND: if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0)) return 0; h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0); break; case GREP_NODE_OR: if (!collect_hits) return (match_expr_eval(x->u.binary.left, bol, eol, ctx, 0) || match_expr_eval(x->u.binary.right, bol, eol, ctx, 0)); h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0); x->u.binary.left->hit |= h; h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1); break; default: die("Unexpected node type (internal error) %d", x->node); } if (collect_hits) x->hit |= h; return h; } static int match_expr(struct grep_opt *opt, char *bol, char *eol, enum grep_context ctx, int collect_hits) { struct grep_expr *x = opt->pattern_expression; return match_expr_eval(x, bol, eol, ctx, collect_hits); } static int match_line(struct grep_opt *opt, char *bol, char *eol, enum grep_context ctx, int collect_hits) { struct grep_pat *p; regmatch_t match; if (opt->extended) return match_expr(opt, bol, eol, ctx, collect_hits); /* we do not call with collect_hits without being extended */ for (p = opt->pattern_list; p; p = p->next) { if (match_one_pattern(p, bol, eol, ctx, &match, 0)) return 1; } return 0; } static int match_next_pattern(struct grep_pat *p, char *bol, char *eol, enum grep_context ctx, regmatch_t *pmatch, int eflags) { regmatch_t match; if (!match_one_pattern(p, bol, eol, ctx, &match, eflags)) return 0; if (match.rm_so < 0 || match.rm_eo < 0) return 0; if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) { if (match.rm_so > pmatch->rm_so) return 1; if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo) return 1; } pmatch->rm_so = match.rm_so; pmatch->rm_eo = match.rm_eo; return 1; } static int next_match(struct grep_opt *opt, char *bol, char *eol, enum grep_context ctx, regmatch_t *pmatch, int eflags) { struct grep_pat *p; int hit = 0; pmatch->rm_so = pmatch->rm_eo = -1; if (bol < eol) { for (p = opt->pattern_list; p; p = p->next) { switch (p->token) { case GREP_PATTERN: /* atom */ case GREP_PATTERN_HEAD: case GREP_PATTERN_BODY: hit |= match_next_pattern(p, bol, eol, ctx, pmatch, eflags); break; default: break; } } } return hit; } static void show_line(struct grep_opt *opt, char *bol, char *eol, const char *name, unsigned lno, char sign) { int rest = eol - bol; const char *match_color, *line_color = NULL; if (opt->file_break && opt->last_shown == 0) { if (opt->show_hunk_mark) opt->output(opt, "\n", 1); } else if (opt->pre_context || opt->post_context || opt->funcbody) { if (opt->last_shown == 0) { if (opt->show_hunk_mark) { output_color(opt, "--", 2, opt->color_sep); opt->output(opt, "\n", 1); } } else if (lno > opt->last_shown + 1) { output_color(opt, "--", 2, opt->color_sep); opt->output(opt, "\n", 1); } } if (opt->heading && opt->last_shown == 0) { output_color(opt, name, strlen(name), opt->color_filename); opt->output(opt, "\n", 1); } opt->last_shown = lno; if (!opt->heading && opt->pathname) { output_color(opt, name, strlen(name), opt->color_filename); output_sep(opt, sign); } if (opt->linenum) { char buf[32]; snprintf(buf, sizeof(buf), "%d", lno); output_color(opt, buf, strlen(buf), opt->color_lineno); output_sep(opt, sign); } if (opt->color) { regmatch_t match; enum grep_context ctx = GREP_CONTEXT_BODY; int ch = *eol; int eflags = 0; if (sign == ':') match_color = opt->color_match_selected; else match_color = opt->color_match_context; if (sign == ':') line_color = opt->color_selected; else if (sign == '-') line_color = opt->color_context; else if (sign == '=') line_color = opt->color_function; *eol = '\0'; while (next_match(opt, bol, eol, ctx, &match, eflags)) { if (match.rm_so == match.rm_eo) break; output_color(opt, bol, match.rm_so, line_color); output_color(opt, bol + match.rm_so, match.rm_eo - match.rm_so, match_color); bol += match.rm_eo; rest -= match.rm_eo; eflags = REG_NOTBOL; } *eol = ch; } output_color(opt, bol, rest, line_color); opt->output(opt, "\n", 1); } #ifndef NO_PTHREADS int grep_use_locks; /* * This lock protects access to the gitattributes machinery, which is * not thread-safe. */ pthread_mutex_t grep_attr_mutex; static inline void grep_attr_lock(void) { if (grep_use_locks) pthread_mutex_lock(&grep_attr_mutex); } static inline void grep_attr_unlock(void) { if (grep_use_locks) pthread_mutex_unlock(&grep_attr_mutex); } /* * Same as git_attr_mutex, but protecting the thread-unsafe object db access. */ pthread_mutex_t grep_read_mutex; #else #define grep_attr_lock() #define grep_attr_unlock() #endif static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol) { xdemitconf_t *xecfg = opt->priv; if (xecfg && !xecfg->find_func) { grep_source_load_driver(gs); if (gs->driver->funcname.pattern) { const struct userdiff_funcname *pe = &gs->driver->funcname; xdiff_set_find_func(xecfg, pe->pattern, pe->cflags); } else { xecfg = opt->priv = NULL; } } if (xecfg) { char buf[1]; return xecfg->find_func(bol, eol - bol, buf, 1, xecfg->find_func_priv) >= 0; } if (bol == eol) return 0; if (isalpha(*bol) || *bol == '_' || *bol == '$') return 1; return 0; } static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs, char *bol, unsigned lno) { while (bol > gs->buf) { char *eol = --bol; while (bol > gs->buf && bol[-1] != '\n') bol--; lno--; if (lno <= opt->last_shown) break; if (match_funcname(opt, gs, bol, eol)) { show_line(opt, bol, eol, gs->name, lno, '='); break; } } } static void show_pre_context(struct grep_opt *opt, struct grep_source *gs, char *bol, char *end, unsigned lno) { unsigned cur = lno, from = 1, funcname_lno = 0; int funcname_needed = !!opt->funcname; if (opt->funcbody && !match_funcname(opt, gs, bol, end)) funcname_needed = 2; if (opt->pre_context < lno) from = lno - opt->pre_context; if (from <= opt->last_shown) from = opt->last_shown + 1; /* Rewind. */ while (bol > gs->buf && cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) { char *eol = --bol; while (bol > gs->buf && bol[-1] != '\n') bol--; cur--; if (funcname_needed && match_funcname(opt, gs, bol, eol)) { funcname_lno = cur; funcname_needed = 0; } } /* We need to look even further back to find a function signature. */ if (opt->funcname && funcname_needed) show_funcname_line(opt, gs, bol, cur); /* Back forward. */ while (cur < lno) { char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-'; while (*eol != '\n') eol++; show_line(opt, bol, eol, gs->name, cur, sign); bol = eol + 1; cur++; } } static int should_lookahead(struct grep_opt *opt) { struct grep_pat *p; if (opt->extended) return 0; /* punt for too complex stuff */ if (opt->invert) return 0; for (p = opt->pattern_list; p; p = p->next) { if (p->token != GREP_PATTERN) return 0; /* punt for "header only" and stuff */ } return 1; } static int look_ahead(struct grep_opt *opt, unsigned long *left_p, unsigned *lno_p, char **bol_p) { unsigned lno = *lno_p; char *bol = *bol_p; struct grep_pat *p; char *sp, *last_bol; regoff_t earliest = -1; for (p = opt->pattern_list; p; p = p->next) { int hit; regmatch_t m; hit = patmatch(p, bol, bol + *left_p, &m, 0); if (!hit || m.rm_so < 0 || m.rm_eo < 0) continue; if (earliest < 0 || m.rm_so < earliest) earliest = m.rm_so; } if (earliest < 0) { *bol_p = bol + *left_p; *left_p = 0; return 1; } for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--) ; /* find the beginning of the line */ last_bol = sp; for (sp = bol; sp < last_bol; sp++) { if (*sp == '\n') lno++; } *left_p -= last_bol - bol; *bol_p = last_bol; *lno_p = lno; return 0; } static void std_output(struct grep_opt *opt, const void *buf, size_t size) { fwrite(buf, size, 1, stdout); } static int fill_textconv_grep(struct userdiff_driver *driver, struct grep_source *gs) { struct diff_filespec *df; char *buf; size_t size; if (!driver || !driver->textconv) return grep_source_load(gs); /* * The textconv interface is intimately tied to diff_filespecs, so we * have to pretend to be one. If we could unify the grep_source * and diff_filespec structs, this mess could just go away. */ df = alloc_filespec(gs->path); switch (gs->type) { case GREP_SOURCE_SHA1: fill_filespec(df, gs->identifier, 1, 0100644); break; case GREP_SOURCE_FILE: fill_filespec(df, null_sha1, 0, 0100644); break; default: die("BUG: attempt to textconv something without a path?"); } /* * fill_textconv is not remotely thread-safe; it may load objects * behind the scenes, and it modifies the global diff tempfile * structure. */ grep_read_lock(); size = fill_textconv(driver, df, &buf); grep_read_unlock(); free_filespec(df); /* * The normal fill_textconv usage by the diff machinery would just keep * the textconv'd buf separate from the diff_filespec. But much of the * grep code passes around a grep_source and assumes that its "buf" * pointer is the beginning of the thing we are searching. So let's * install our textconv'd version into the grep_source, taking care not * to leak any existing buffer. */ grep_source_clear_data(gs); gs->buf = buf; gs->size = size; return 0; } static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits) { char *bol; unsigned long left; unsigned lno = 1; unsigned last_hit = 0; int binary_match_only = 0; unsigned count = 0; int try_lookahead = 0; int show_function = 0; struct userdiff_driver *textconv = NULL; enum grep_context ctx = GREP_CONTEXT_HEAD; xdemitconf_t xecfg; if (!opt->output) opt->output = std_output; if (opt->pre_context || opt->post_context || opt->file_break || opt->funcbody) { /* Show hunk marks, except for the first file. */ if (opt->last_shown) opt->show_hunk_mark = 1; /* * If we're using threads then we can't easily identify * the first file. Always put hunk marks in that case * and skip the very first one later in work_done(). */ if (opt->output != std_output) opt->show_hunk_mark = 1; } opt->last_shown = 0; if (opt->allow_textconv) { grep_source_load_driver(gs); /* * We might set up the shared textconv cache data here, which * is not thread-safe. */ grep_attr_lock(); textconv = userdiff_get_textconv(gs->driver); grep_attr_unlock(); } /* * We know the result of a textconv is text, so we only have to care * about binary handling if we are not using it. */ if (!textconv) { switch (opt->binary) { case GREP_BINARY_DEFAULT: if (grep_source_is_binary(gs)) binary_match_only = 1; break; case GREP_BINARY_NOMATCH: if (grep_source_is_binary(gs)) return 0; /* Assume unmatch */ break; case GREP_BINARY_TEXT: break; default: die("bug: unknown binary handling mode"); } } memset(&xecfg, 0, sizeof(xecfg)); opt->priv = &xecfg; try_lookahead = should_lookahead(opt); if (fill_textconv_grep(textconv, gs) < 0) return 0; bol = gs->buf; left = gs->size; while (left) { char *eol, ch; int hit; /* * look_ahead() skips quickly to the line that possibly * has the next hit; don't call it if we need to do * something more than just skipping the current line * in response to an unmatch for the current line. E.g. * inside a post-context window, we will show the current * line as a context around the previous hit when it * doesn't hit. */ if (try_lookahead && !(last_hit && (show_function || lno <= last_hit + opt->post_context)) && look_ahead(opt, &left, &lno, &bol)) break; eol = end_of_line(bol, &left); ch = *eol; *eol = 0; if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol)) ctx = GREP_CONTEXT_BODY; hit = match_line(opt, bol, eol, ctx, collect_hits); *eol = ch; if (collect_hits) goto next_line; /* "grep -v -e foo -e bla" should list lines * that do not have either, so inversion should * be done outside. */ if (opt->invert) hit = !hit; if (opt->unmatch_name_only) { if (hit) return 0; goto next_line; } if (hit) { count++; if (opt->status_only) return 1; if (opt->name_only) { show_name(opt, gs->name); return 1; } if (opt->count) goto next_line; if (binary_match_only) { opt->output(opt, "Binary file ", 12); output_color(opt, gs->name, strlen(gs->name), opt->color_filename); opt->output(opt, " matches\n", 9); return 1; } /* Hit at this line. If we haven't shown the * pre-context lines, we would need to show them. */ if (opt->pre_context || opt->funcbody) show_pre_context(opt, gs, bol, eol, lno); else if (opt->funcname) show_funcname_line(opt, gs, bol, lno); show_line(opt, bol, eol, gs->name, lno, ':'); last_hit = lno; if (opt->funcbody) show_function = 1; goto next_line; } if (show_function && match_funcname(opt, gs, bol, eol)) show_function = 0; if (show_function || (last_hit && lno <= last_hit + opt->post_context)) { /* If the last hit is within the post context, * we need to show this line. */ show_line(opt, bol, eol, gs->name, lno, '-'); } next_line: bol = eol + 1; if (!left) break; left--; lno++; } if (collect_hits) return 0; if (opt->status_only) return 0; if (opt->unmatch_name_only) { /* We did not see any hit, so we want to show this */ show_name(opt, gs->name); return 1; } xdiff_clear_find_func(&xecfg); opt->priv = NULL; /* NEEDSWORK: * The real "grep -c foo *.c" gives many "bar.c:0" lines, * which feels mostly useless but sometimes useful. Maybe * make it another option? For now suppress them. */ if (opt->count && count) { char buf[32]; if (opt->pathname) { output_color(opt, gs->name, strlen(gs->name), opt->color_filename); output_sep(opt, ':'); } snprintf(buf, sizeof(buf), "%u\n", count); opt->output(opt, buf, strlen(buf)); return 1; } return !!last_hit; } static void clr_hit_marker(struct grep_expr *x) { /* All-hit markers are meaningful only at the very top level * OR node. */ while (1) { x->hit = 0; if (x->node != GREP_NODE_OR) return; x->u.binary.left->hit = 0; x = x->u.binary.right; } } static int chk_hit_marker(struct grep_expr *x) { /* Top level nodes have hit markers. See if they all are hits */ while (1) { if (x->node != GREP_NODE_OR) return x->hit; if (!x->u.binary.left->hit) return 0; x = x->u.binary.right; } } int grep_source(struct grep_opt *opt, struct grep_source *gs) { /* * we do not have to do the two-pass grep when we do not check * buffer-wide "all-match". */ if (!opt->all_match) return grep_source_1(opt, gs, 0); /* Otherwise the toplevel "or" terms hit a bit differently. * We first clear hit markers from them. */ clr_hit_marker(opt->pattern_expression); grep_source_1(opt, gs, 1); if (!chk_hit_marker(opt->pattern_expression)) return 0; return grep_source_1(opt, gs, 0); } int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size) { struct grep_source gs; int r; grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL); gs.buf = buf; gs.size = size; r = grep_source(opt, &gs); grep_source_clear(&gs); return r; } void grep_source_init(struct grep_source *gs, enum grep_source_type type, const char *name, const char *path, const void *identifier) { gs->type = type; gs->name = name ? xstrdup(name) : NULL; gs->path = path ? xstrdup(path) : NULL; gs->buf = NULL; gs->size = 0; gs->driver = NULL; switch (type) { case GREP_SOURCE_FILE: gs->identifier = xstrdup(identifier); break; case GREP_SOURCE_SHA1: gs->identifier = xmalloc(20); hashcpy(gs->identifier, identifier); break; case GREP_SOURCE_BUF: gs->identifier = NULL; } } void grep_source_clear(struct grep_source *gs) { free(gs->name); gs->name = NULL; free(gs->path); gs->path = NULL; free(gs->identifier); gs->identifier = NULL; grep_source_clear_data(gs); } void grep_source_clear_data(struct grep_source *gs) { switch (gs->type) { case GREP_SOURCE_FILE: case GREP_SOURCE_SHA1: free(gs->buf); gs->buf = NULL; gs->size = 0; break; case GREP_SOURCE_BUF: /* leave user-provided buf intact */ break; } } static int grep_source_load_sha1(struct grep_source *gs) { enum object_type type; grep_read_lock(); gs->buf = read_sha1_file(gs->identifier, &type, &gs->size); grep_read_unlock(); if (!gs->buf) return error(_("'%s': unable to read %s"), gs->name, sha1_to_hex(gs->identifier)); return 0; } static int grep_source_load_file(struct grep_source *gs) { const char *filename = gs->identifier; struct stat st; char *data; size_t size; int i; if (lstat(filename, &st) < 0) { err_ret: if (errno != ENOENT) error(_("'%s': %s"), filename, strerror(errno)); return -1; } if (!S_ISREG(st.st_mode)) return -1; size = xsize_t(st.st_size); i = open(filename, O_RDONLY); if (i < 0) goto err_ret; data = xmalloc(size + 1); if (st.st_size != read_in_full(i, data, size)) { error(_("'%s': short read %s"), filename, strerror(errno)); close(i); free(data); return -1; } close(i); data[size] = 0; gs->buf = data; gs->size = size; return 0; } static int grep_source_load(struct grep_source *gs) { if (gs->buf) return 0; switch (gs->type) { case GREP_SOURCE_FILE: return grep_source_load_file(gs); case GREP_SOURCE_SHA1: return grep_source_load_sha1(gs); case GREP_SOURCE_BUF: return gs->buf ? 0 : -1; } die("BUG: invalid grep_source type"); } void grep_source_load_driver(struct grep_source *gs) { if (gs->driver) return; grep_attr_lock(); if (gs->path) gs->driver = userdiff_find_by_path(gs->path); if (!gs->driver) gs->driver = userdiff_find_by_name("default"); grep_attr_unlock(); } static int grep_source_is_binary(struct grep_source *gs) { grep_source_load_driver(gs); if (gs->driver->binary != -1) return gs->driver->binary; if (!grep_source_load(gs)) return buffer_is_binary(gs->buf, gs->size); return 0; }
857357.c
/****************************************************************************** * * Copyright (C) 1999-2012 Broadcom Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * * This file contains functions for the SMP L2Cap interface * ******************************************************************************/ #include "common/bt_target.h" #include "osi/allocator.h" #if SMP_INCLUDED == TRUE #include <string.h> #include "stack/btm_ble_api.h" #include "stack/l2c_api.h" #include "smp_int.h" static void smp_tx_complete_callback(UINT16 cid, UINT16 num_pkt); static void smp_connect_callback(UINT16 channel, BD_ADDR bd_addr, BOOLEAN connected, UINT16 reason, tBT_TRANSPORT transport); static void smp_data_received(UINT16 channel, BD_ADDR bd_addr, BT_HDR *p_buf); #if (CLASSIC_BT_INCLUDED == TRUE) static void smp_br_connect_callback(UINT16 channel, BD_ADDR bd_addr, BOOLEAN connected, UINT16 reason, tBT_TRANSPORT transport); static void smp_br_data_received(UINT16 channel, BD_ADDR bd_addr, BT_HDR *p_buf); #endif ///CLASSIC_BT_INCLUDED == TRUE /******************************************************************************* ** ** Function smp_l2cap_if_init ** ** Description This function is called during the SMP task startup ** to register interface functions with L2CAP. ** *******************************************************************************/ void smp_l2cap_if_init (void) { tL2CAP_FIXED_CHNL_REG fixed_reg; SMP_TRACE_EVENT ("SMDBG l2c %s", __func__); fixed_reg.fixed_chnl_opts.mode = L2CAP_FCR_BASIC_MODE; fixed_reg.fixed_chnl_opts.max_transmit = 0; fixed_reg.fixed_chnl_opts.rtrans_tout = 0; fixed_reg.fixed_chnl_opts.mon_tout = 0; fixed_reg.fixed_chnl_opts.mps = 0; fixed_reg.fixed_chnl_opts.tx_win_sz = 0; fixed_reg.pL2CA_FixedConn_Cb = smp_connect_callback; fixed_reg.pL2CA_FixedData_Cb = smp_data_received; fixed_reg.pL2CA_FixedTxComplete_Cb = smp_tx_complete_callback; fixed_reg.pL2CA_FixedCong_Cb = NULL; /* do not handle congestion on this channel */ fixed_reg.default_idle_tout = 0; /* set 0 seconds timeout, 0xffff default idle timeout. This timeout is used to wait for the end of the pairing and then make a disconnect request, setting a larger value will cause the disconnect event to go back up for a long time. Set to 0 will be disconnected directly, and it will come up pairing failure, so it will not cause adverse effects. */ L2CA_RegisterFixedChannel (L2CAP_SMP_CID, &fixed_reg); #if (CLASSIC_BT_INCLUDED == TRUE) fixed_reg.pL2CA_FixedConn_Cb = smp_br_connect_callback; fixed_reg.pL2CA_FixedData_Cb = smp_br_data_received; L2CA_RegisterFixedChannel (L2CAP_SMP_BR_CID, &fixed_reg); #endif ///CLASSIC_BT_INCLUDED == TRUE } /******************************************************************************* ** ** Function smp_connect_callback ** ** Description This callback function is called by L2CAP to indicate that ** SMP channel is ** connected (conn = TRUE)/disconnected (conn = FALSE). ** *******************************************************************************/ static void smp_connect_callback (UINT16 channel, BD_ADDR bd_addr, BOOLEAN connected, UINT16 reason, tBT_TRANSPORT transport) { tSMP_CB *p_cb = &smp_cb; tSMP_INT_DATA int_data; BD_ADDR dummy_bda = {0}; SMP_TRACE_EVENT ("SMDBG l2c %s\n", __FUNCTION__); if (transport == BT_TRANSPORT_BR_EDR || memcmp(bd_addr, dummy_bda, BD_ADDR_LEN) == 0) { return; } if(!connected && &p_cb->rsp_timer_ent) { //free timer btu_free_timer(&p_cb->rsp_timer_ent); } if (memcmp(bd_addr, p_cb->pairing_bda, BD_ADDR_LEN) == 0) { SMP_TRACE_EVENT ("%s() for pairing BDA: %08x%04x Event: %s\n", __FUNCTION__, (bd_addr[0] << 24) + (bd_addr[1] << 16) + (bd_addr[2] << 8) + bd_addr[3], (bd_addr[4] << 8) + bd_addr[5], (connected) ? "connected" : "disconnected"); if (connected) { if (!p_cb->connect_initialized) { p_cb->connect_initialized = TRUE; /* initiating connection established */ p_cb->role = L2CA_GetBleConnRole(bd_addr); /* initialize local i/r key to be default keys */ p_cb->local_r_key = p_cb->local_i_key = SMP_SEC_DEFAULT_KEY; p_cb->loc_auth_req = p_cb->peer_auth_req = SMP_DEFAULT_AUTH_REQ; p_cb->cb_evt = SMP_IO_CAP_REQ_EVT; smp_sm_event(p_cb, SMP_L2CAP_CONN_EVT, NULL); } } else { int_data.reason = reason; /* Disconnected while doing security */ smp_sm_event(p_cb, SMP_L2CAP_DISCONN_EVT, &int_data); } } } /******************************************************************************* ** ** Function smp_data_received ** ** Description This function is called when data is received from L2CAP on ** SMP channel. ** ** ** Returns void ** *******************************************************************************/ static void smp_data_received(UINT16 channel, BD_ADDR bd_addr, BT_HDR *p_buf) { tSMP_CB *p_cb = &smp_cb; UINT8 *p = (UINT8 *)(p_buf + 1) + p_buf->offset; UINT8 cmd ; SMP_TRACE_EVENT ("\nSMDBG l2c %s\n", __FUNCTION__); STREAM_TO_UINT8(cmd, p); /* sanity check */ if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) { SMP_TRACE_WARNING( "Ignore received command with RESERVED code 0x%02x\n", cmd); osi_free (p_buf); return; } /* reject the pairing request if there is an on-going SMP pairing */ if (SMP_OPCODE_PAIRING_REQ == cmd || SMP_OPCODE_SEC_REQ == cmd) { if ((p_cb->state == SMP_STATE_IDLE) && (p_cb->br_state == SMP_BR_STATE_IDLE) && !(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { p_cb->role = L2CA_GetBleConnRole(bd_addr); memcpy(&p_cb->pairing_bda[0], bd_addr, BD_ADDR_LEN); } else if (memcmp(&bd_addr[0], p_cb->pairing_bda, BD_ADDR_LEN)) { osi_free (p_buf); smp_reject_unexpected_pairing_command(bd_addr); return; } /* else, out of state pairing request/security request received, passed into SM */ } if (memcmp(&bd_addr[0], p_cb->pairing_bda, BD_ADDR_LEN) == 0) { btu_stop_timer (&p_cb->rsp_timer_ent); btu_start_timer (&p_cb->rsp_timer_ent, BTU_TTYPE_SMP_PAIRING_CMD, SMP_WAIT_FOR_RSP_TOUT); if (cmd == SMP_OPCODE_CONFIRM) { SMP_TRACE_DEBUG ("in %s cmd = 0x%02x, peer_auth_req = 0x%02x," "loc_auth_req = 0x%02x\n", __FUNCTION__, cmd, p_cb->peer_auth_req, p_cb->loc_auth_req); if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) { cmd = SMP_OPCODE_PAIR_COMMITM; } } p_cb->rcvd_cmd_code = cmd; p_cb->rcvd_cmd_len = (UINT8) p_buf->len; smp_sm_event(p_cb, cmd, p); } osi_free (p_buf); } /******************************************************************************* ** ** Function smp_tx_complete_callback ** ** Description SMP channel tx complete callback ** *******************************************************************************/ static void smp_tx_complete_callback (UINT16 cid, UINT16 num_pkt) { tSMP_CB *p_cb = &smp_cb; if (p_cb->total_tx_unacked >= num_pkt) { p_cb->total_tx_unacked -= num_pkt; } else { SMP_TRACE_ERROR("Unexpected %s: num_pkt = %d", __func__, num_pkt); } UINT8 reason = SMP_SUCCESS; if (p_cb->total_tx_unacked == 0 && p_cb->wait_for_authorization_complete) { if (cid == L2CAP_SMP_CID) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); } else { smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &reason); } } } /******************************************************************************* ** ** Function smp_br_connect_callback ** ** Description This callback function is called by L2CAP to indicate that ** SMP BR channel is ** connected (conn = TRUE)/disconnected (conn = FALSE). ** *******************************************************************************/ #if (CLASSIC_BT_INCLUDED == TRUE) static void smp_br_connect_callback(UINT16 channel, BD_ADDR bd_addr, BOOLEAN connected, UINT16 reason, tBT_TRANSPORT transport) { tSMP_CB *p_cb = &smp_cb; tSMP_INT_DATA int_data; SMP_TRACE_EVENT ("%s", __func__); if (transport != BT_TRANSPORT_BR_EDR) { SMP_TRACE_EVENT ("%s is called on unexpected transport %d\n", __func__, transport); return; } if (!(memcmp(bd_addr, p_cb->pairing_bda, BD_ADDR_LEN) == 0)) { return; } SMP_TRACE_EVENT ("%s for pairing BDA: %08x%04x Event: %s\n", __func__, (bd_addr[0] << 24) + (bd_addr[1] << 16) + (bd_addr[2] << 8) + bd_addr[3], (bd_addr[4] << 8) + bd_addr[5], (connected) ? "connected" : "disconnected"); if (connected) { if (!p_cb->connect_initialized) { p_cb->connect_initialized = TRUE; /* initialize local i/r key to be default keys */ p_cb->local_r_key = p_cb->local_i_key = SMP_BR_SEC_DEFAULT_KEY; p_cb->loc_auth_req = p_cb->peer_auth_req = 0; p_cb->cb_evt = SMP_BR_KEYS_REQ_EVT; smp_br_state_machine_event(p_cb, SMP_BR_L2CAP_CONN_EVT, NULL); } } else { int_data.reason = reason; /* Disconnected while doing security */ smp_br_state_machine_event(p_cb, SMP_BR_L2CAP_DISCONN_EVT, &int_data); } } /******************************************************************************* ** ** Function smp_br_data_received ** ** Description This function is called when data is received from L2CAP on ** SMP BR channel. ** ** Returns void ** *******************************************************************************/ static void smp_br_data_received(UINT16 channel, BD_ADDR bd_addr, BT_HDR *p_buf) { tSMP_CB *p_cb = &smp_cb; UINT8 *p = (UINT8 *)(p_buf + 1) + p_buf->offset; UINT8 cmd ; SMP_TRACE_EVENT ("SMDBG l2c %s\n", __func__); STREAM_TO_UINT8(cmd, p); /* sanity check */ if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) { SMP_TRACE_WARNING( "Ignore received command with RESERVED code 0x%02x", cmd); osi_free(p_buf); return; } /* reject the pairing request if there is an on-going SMP pairing */ if (SMP_OPCODE_PAIRING_REQ == cmd) { if ((p_cb->state == SMP_STATE_IDLE) && (p_cb->br_state == SMP_BR_STATE_IDLE)) { p_cb->role = HCI_ROLE_SLAVE; p_cb->smp_over_br = TRUE; memcpy(&p_cb->pairing_bda[0], bd_addr, BD_ADDR_LEN); } else if (memcmp(&bd_addr[0], p_cb->pairing_bda, BD_ADDR_LEN)) { osi_free (p_buf); smp_reject_unexpected_pairing_command(bd_addr); return; } /* else, out of state pairing request received, passed into State Machine */ } if (memcmp(&bd_addr[0], p_cb->pairing_bda, BD_ADDR_LEN) == 0) { btu_stop_timer (&p_cb->rsp_timer_ent); btu_start_timer (&p_cb->rsp_timer_ent, BTU_TTYPE_SMP_PAIRING_CMD, SMP_WAIT_FOR_RSP_TOUT); p_cb->rcvd_cmd_code = cmd; p_cb->rcvd_cmd_len = (UINT8) p_buf->len; smp_br_state_machine_event(p_cb, cmd, p); } osi_free (p_buf); } #endif /* CLASSIC_BT_INCLUDED == TRUE */ #endif /* SMP_INCLUDED == TRUE */
979464.c
/** @file * @brief Modem receiver driver * * A modem receiver driver allowing application to handle all * aspects of received protocol data. */ /* * Copyright (c) 2018 Foundries.io * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/kernel.h> #include <zephyr/init.h> #include <zephyr/drivers/uart.h> #include <zephyr/pm/device.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(mdm_receiver, CONFIG_MODEM_LOG_LEVEL); #include "modem_receiver.h" #define MAX_MDM_CTX CONFIG_MODEM_RECEIVER_MAX_CONTEXTS #define MAX_READ_SIZE 128 static struct mdm_receiver_context *contexts[MAX_MDM_CTX]; /** * @brief Finds receiver context which manages provided device. * * @param *dev: device used by the receiver context. * * @retval Receiver context or NULL. */ static struct mdm_receiver_context *context_from_dev(const struct device *dev) { int i; for (i = 0; i < MAX_MDM_CTX; i++) { if (contexts[i] && contexts[i]->uart_dev == dev) { return contexts[i]; } } return NULL; } /** * @brief Persists receiver context if there is a free place. * * @note Amount of stored receiver contexts is determined by * MAX_MDM_CTX. * * @param *ctx: receiver context to persist. * * @retval 0 if ok, < 0 if error. */ static int mdm_receiver_get(struct mdm_receiver_context *ctx) { int i; for (i = 0; i < MAX_MDM_CTX; i++) { if (!contexts[i]) { contexts[i] = ctx; return 0; } } return -ENOMEM; } /** * @brief Drains UART. * * @note Discards remaining data. * * @param *ctx: receiver context. * * @retval None. */ static void mdm_receiver_flush(struct mdm_receiver_context *ctx) { uint8_t c; __ASSERT(ctx, "invalid ctx"); __ASSERT(ctx->uart_dev, "invalid ctx device"); while (uart_fifo_read(ctx->uart_dev, &c, 1) > 0) { continue; } } /** * @brief Receiver UART interrupt handler. * * @note Fills contexts ring buffer with received data. * When ring buffer is full the data is discarded. * * @param *uart_dev: uart device. * * @retval None. */ static void mdm_receiver_isr(const struct device *uart_dev, void *user_data) { struct mdm_receiver_context *ctx; int rx, ret; static uint8_t read_buf[MAX_READ_SIZE]; ARG_UNUSED(user_data); /* lookup the device */ ctx = context_from_dev(uart_dev); if (!ctx) { return; } /* get all of the data off UART as fast as we can */ while (uart_irq_update(ctx->uart_dev) && uart_irq_rx_ready(ctx->uart_dev)) { rx = uart_fifo_read(ctx->uart_dev, read_buf, sizeof(read_buf)); if (rx > 0) { ret = ring_buf_put(&ctx->rx_rb, read_buf, rx); if (ret != rx) { LOG_ERR("Rx buffer doesn't have enough space. " "Bytes pending: %d, written: %d", rx, ret); mdm_receiver_flush(ctx); k_sem_give(&ctx->rx_sem); break; } k_sem_give(&ctx->rx_sem); } } } /** * @brief Configures receiver context and assigned device. * * @param *ctx: receiver context. * * @retval None. */ static void mdm_receiver_setup(struct mdm_receiver_context *ctx) { __ASSERT(ctx, "invalid ctx"); uart_irq_rx_disable(ctx->uart_dev); uart_irq_tx_disable(ctx->uart_dev); mdm_receiver_flush(ctx); uart_irq_callback_set(ctx->uart_dev, mdm_receiver_isr); uart_irq_rx_enable(ctx->uart_dev); } struct mdm_receiver_context *mdm_receiver_context_from_id(int id) { if (id >= 0 && id < MAX_MDM_CTX) { return contexts[id]; } else { return NULL; } } int mdm_receiver_recv(struct mdm_receiver_context *ctx, uint8_t *buf, size_t size, size_t *bytes_read) { if (!ctx) { return -EINVAL; } if (size == 0) { *bytes_read = 0; return 0; } *bytes_read = ring_buf_get(&ctx->rx_rb, buf, size); return 0; } int mdm_receiver_send(struct mdm_receiver_context *ctx, const uint8_t *buf, size_t size) { if (!ctx) { return -EINVAL; } if (size == 0) { return 0; } do { uart_poll_out(ctx->uart_dev, *buf++); } while (--size); return 0; } int mdm_receiver_sleep(struct mdm_receiver_context *ctx) { uart_irq_rx_disable(ctx->uart_dev); #ifdef CONFIG_PM_DEVICE pm_device_action_run(ctx->uart_dev, PM_DEVICE_ACTION_SUSPEND); #endif return 0; } int mdm_receiver_wake(struct mdm_receiver_context *ctx) { #ifdef CONFIG_PM_DEVICE pm_device_action_run(ctx->uart_dev, PM_DEVICE_ACTION_SUSPEND); #endif uart_irq_rx_enable(ctx->uart_dev); return 0; } int mdm_receiver_register(struct mdm_receiver_context *ctx, const struct device *uart_dev, uint8_t *buf, size_t size) { int ret; if ((!ctx) || (size == 0)) { return -EINVAL; } if (!device_is_ready(uart_dev)) { LOG_ERR("Device is not ready: %s", uart_dev ? uart_dev->name : "<null>"); return -ENODEV; } ctx->uart_dev = uart_dev; ring_buf_init(&ctx->rx_rb, size, buf); k_sem_init(&ctx->rx_sem, 0, 1); ret = mdm_receiver_get(ctx); if (ret < 0) { return ret; } mdm_receiver_setup(ctx); return 0; }
184203.c
/* Copyright (c) 1997-1999 Miller Puckette. * For information on usage and redistribution, and for a DISCLAIMER OF ALL * WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #include <stdlib.h> #include <string.h> #include <stdio.h> /* for read/write to files */ #include "m_pd.h" #include "g_canvas.h" #include <math.h> /* jsarlo { */ #define ARRAYPAGESIZE 1000 /* this should match the page size in u_main.tk */ /* } jsarlo */ /* --------- "pure" arrays with scalars for elements. --------------- */ /* Pure arrays have no a priori graphical capabilities. They are instantiated by "garrays" below or can be elements of other scalars (g_scalar.c); their graphical behavior is defined accordingly. */ t_array *array_new(t_symbol *templatesym, t_gpointer *parent) { t_array *x = (t_array *)getbytes(sizeof (*x)); t_template *template; template = template_findbyname(templatesym); x->a_templatesym = templatesym; x->a_n = 1; x->a_elemsize = sizeof(t_word) * template->t_n; x->a_vec = (char *)getbytes(x->a_elemsize); /* note here we blithely copy a gpointer instead of "setting" a new one; this gpointer isn't accounted for and needn't be since we'll be deleted before the thing pointed to gets deleted anyway; see array_free. */ x->a_gp = *parent; x->a_stub = gstub_new(0, x); word_init((t_word *)(x->a_vec), template, parent); return (x); } /* jsarlo { */ void garray_arrayviewlist_close(t_garray *x); /* } jsarlo */ void array_resize(t_array *x, int n) { int elemsize, oldn; char *tmp; t_template *template = template_findbyname(x->a_templatesym); if (n < 1) n = 1; oldn = x->a_n; elemsize = sizeof(t_word) * template->t_n; tmp = (char *)resizebytes(x->a_vec, oldn * elemsize, n * elemsize); if (!tmp) return; x->a_vec = tmp; x->a_n = n; if (n > oldn) { char *cp = x->a_vec + elemsize * oldn; int i = n - oldn; for (; i--; cp += elemsize) { t_word *wp = (t_word *)cp; word_init(wp, template, &x->a_gp); } } x->a_valid = ++glist_valid; } void array_resize_and_redraw(t_array *array, t_glist *glist, int n) { t_array *a2 = array; int vis = glist_isvisible(glist); while (a2->a_gp.gp_stub->gs_which == GP_ARRAY) a2 = a2->a_gp.gp_stub->gs_un.gs_array; if (vis) gobj_vis(&a2->a_gp.gp_un.gp_scalar->sc_gobj, glist, 0); array_resize(array, n); if (vis) gobj_vis(&a2->a_gp.gp_un.gp_scalar->sc_gobj, glist, 1); } void word_free(t_word *wp, t_template *template); void array_free(t_array *x) { int i; t_template *scalartemplate = template_findbyname(x->a_templatesym); gstub_cutoff(x->a_stub); for (i = 0; i < x->a_n; i++) { t_word *wp = (t_word *)(x->a_vec + x->a_elemsize * i); word_free(wp, scalartemplate); } freebytes(x->a_vec, x->a_elemsize * x->a_n); freebytes(x, sizeof *x); } /* --------------------- graphical arrays (garrays) ------------------- */ t_class *garray_class; struct _garray { t_gobj x_gobj; t_scalar *x_scalar; /* scalar "containing" the array */ t_glist *x_glist; /* containing glist */ t_symbol *x_name; /* unexpanded name (possibly with leading '$') */ t_symbol *x_realname; /* expanded name (symbol we're bound to) */ char x_usedindsp; /* true if some DSP routine is using this */ char x_saveit; /* true if we should save this with parent */ char x_listviewing; /* true if list view window is open */ char x_hidename; /* don't print name above graph */ }; static t_pd *garray_arraytemplatecanvas; /* written at setup w/ global lock */ static const char garray_arraytemplatefile[] = "\ canvas 0 0 458 153 10;\n\ #X obj 43 31 struct float-array array z float float style\n\ float linewidth float color;\n\ #X obj 43 70 plot z color linewidth 0 0 1 style;\n\ "; static const char garray_floattemplatefile[] = "\ canvas 0 0 458 153 10;\n\ #X obj 39 26 struct float float y;\n\ "; /* create invisible, built-in canvases to supply templates for floats and float-arrays. */ void garray_init(void) { t_binbuf *b; b = binbuf_new(); glob_setfilename(0, gensym("_float_template"), gensym(".")); binbuf_text(b, garray_floattemplatefile, strlen(garray_floattemplatefile)); binbuf_eval(b, &pd_canvasmaker, 0, 0); vmess(s__X.s_thing, gensym("pop"), "i", 0); glob_setfilename(0, gensym("_float_array_template"), gensym(".")); binbuf_text(b, garray_arraytemplatefile, strlen(garray_arraytemplatefile)); binbuf_eval(b, &pd_canvasmaker, 0, 0); garray_arraytemplatecanvas = s__X.s_thing; vmess(s__X.s_thing, gensym("pop"), "i", 0); glob_setfilename(0, &s_, &s_); binbuf_free(b); } /* create a new scalar attached to a symbol. Used to make floating-point arrays (the scalar will be of type "float-array"). Currently this is always called by graph_array() below; but when we make a more general way to save and create arrays this might get called more directly. */ static t_garray *graph_scalar(t_glist *gl, t_symbol *s, t_symbol *templatesym, int saveit) { t_garray *x; if (!template_findbyname(templatesym)) return (0); x = (t_garray *)pd_new(garray_class); x->x_scalar = scalar_new(gl, templatesym); x->x_name = s; x->x_realname = canvas_realizedollar(gl, s); pd_bind(&x->x_gobj.g_pd, x->x_realname); x->x_usedindsp = 0; x->x_saveit = saveit; x->x_listviewing = 0; glist_add(gl, &x->x_gobj); x->x_glist = gl; return (x); } /* get a garray's "array" structure. */ t_array *garray_getarray(t_garray *x) { int zonset, ztype; t_symbol *zarraytype; t_scalar *sc = x->x_scalar; t_symbol *templatesym = sc->sc_template; t_template *template = template_findbyname(templatesym); if (!template) { error("array: couldn't find template %s", templatesym->s_name); return (0); } if (!template_find_field(template, gensym("z"), &zonset, &ztype, &zarraytype)) { error("array: template %s has no 'z' field", templatesym->s_name); return (0); } if (ztype != DT_ARRAY) { error("array: template %s, 'z' field is not an array", templatesym->s_name); return (0); } return (sc->sc_vec[zonset].w_array); } /* get the "array" structure and furthermore check it's float */ static t_array *garray_getarray_floatonly(t_garray *x, int *yonsetp, int *elemsizep) { t_array *a = garray_getarray(x); int yonset, type; t_symbol *arraytype; t_template *template = template_findbyname(a->a_templatesym); if (!template_find_field(template, gensym("y"), &yonset, &type, &arraytype) || type != DT_FLOAT) return (0); *yonsetp = yonset; *elemsizep = a->a_elemsize; return (a); } /* get the array's name. Return nonzero if it should be hidden */ int garray_getname(t_garray *x, t_symbol **namep) { *namep = x->x_name; return (x->x_hidename); } /* get a garray's containing glist */ t_glist *garray_getglist(t_garray *x) { return (x->x_glist); } /* get a garray's associated scalar */ t_scalar *garray_getscalar(t_garray *x) { return (x->x_scalar); } /* if there is one garray in a graph, reset the graph's coordinates to fit a new size and style for the garray */ static void garray_fittograph(t_garray *x, int n, int style) { t_array *array = garray_getarray(x); t_glist *gl = x->x_glist; if (gl->gl_list == &x->x_gobj && !x->x_gobj.g_next) { vmess(&gl->gl_pd, gensym("bounds"), "ffff", 0., gl->gl_y1, (double) (style == PLOTSTYLE_POINTS || n == 1 ? n : n-1), gl->gl_y2); /* hack - if the xlabels seem to want to be from 0 to table size-1, update the second label */ if (gl->gl_nxlabels == 2 && !strcmp(gl->gl_xlabel[0]->s_name, "0")) { t_atom a; SETFLOAT(&a, n-1); gl->gl_xlabel[1] = atom_gensym(&a); glist_redraw(gl); } /* close any dialogs that might have the wrong info now... */ gfxstub_deleteforkey(gl); } } /* handle "array" message to glists; call graph_scalar above with an appropriate template; then set size and flags. This is called from the menu and in the file format for patches. LATER replace this by a more coherent (and general) invocation. */ t_garray *graph_array(t_glist *gl, t_symbol *s, t_symbol *templateargsym, t_floatarg fsize, t_floatarg fflags) { int n = fsize, zonset, ztype, saveit; t_symbol *zarraytype, *asym = gensym("#A"); t_garray *x; t_template *template, *ztemplate; t_symbol *templatesym; int flags = fflags; int filestyle = ((flags & 6) >> 1); int style = (filestyle == 0 ? PLOTSTYLE_POLY : (filestyle == 1 ? PLOTSTYLE_POINTS : filestyle)); if (templateargsym != &s_float) { error("array %s: only 'float' type understood", templateargsym->s_name); return (0); } templatesym = gensym("pd-float-array"); template = template_findbyname(templatesym); if (!template) { error("array: couldn't find template %s", templatesym->s_name); return (0); } if (!template_find_field(template, gensym("z"), &zonset, &ztype, &zarraytype)) { error("array: template %s has no 'z' field", templatesym->s_name); return (0); } if (ztype != DT_ARRAY) { error("array: template %s, 'z' field is not an array", templatesym->s_name); return (0); } if (!(ztemplate = template_findbyname(zarraytype))) { error("array: no template of type %s", zarraytype->s_name); return (0); } saveit = ((flags & 1) != 0); x = graph_scalar(gl, s, templatesym, saveit); x->x_hidename = ((flags & 8) >> 3); if (n <= 0) n = 100; array_resize(x->x_scalar->sc_vec[zonset].w_array, n); template_setfloat(template, gensym("style"), x->x_scalar->sc_vec, style, 1); template_setfloat(template, gensym("linewidth"), x->x_scalar->sc_vec, ((style == PLOTSTYLE_POINTS) ? 2 : 1), 1); /* bashily unbind #A -- this would create garbage if #A were multiply bound but we believe in this context it's at most bound to whichever textobj or array was created most recently */ asym->s_thing = 0; /* and now bind #A to us to receive following messages in the saved file or copy buffer */ pd_bind(&x->x_gobj.g_pd, asym); garray_redraw(x); canvas_update_dsp(); return (x); } /* called from array menu item to create a new one */ void canvas_menuarray(t_glist *canvas) { t_glist *x = (t_glist *)canvas; int gcount; char cmdbuf[200], arraybuf[80]; for (gcount = 1; gcount < 1000; gcount++) { sprintf(arraybuf, "array%d", gcount); if (!pd_findbyclass(gensym(arraybuf), garray_class)) break; } sprintf(cmdbuf, "pdtk_array_dialog %%s array%d 100 3 1\n", gcount); gfxstub_new(&x->gl_pd, x, cmdbuf); } /* called from graph_dialog to set properties */ void garray_properties(t_garray *x) { char cmdbuf[200]; t_array *a = garray_getarray(x); t_scalar *sc = x->x_scalar; int style = template_getfloat(template_findbyname(sc->sc_template), gensym("style"), x->x_scalar->sc_vec, 1); int filestyle = (style == 0 ? PLOTSTYLE_POLY : (style == 1 ? PLOTSTYLE_POINTS : style)); if (!a) return; gfxstub_deleteforkey(x); /* create dialog window. LATER fix this to escape '$' properly; right now we just detect a leading '$' and escape it. There should be a systematic way of doing this. */ sprintf(cmdbuf, "pdtk_array_dialog %%s %s %d %d 0\n", iemgui_dollar2raute(x->x_name)->s_name, a->a_n, x->x_saveit + 2 * filestyle); gfxstub_new(&x->x_gobj.g_pd, x, cmdbuf); } /* this is called back from the dialog window to create a garray. The otherflag requests that we find an existing graph to put it in. */ void glist_arraydialog(t_glist *parent, t_symbol *name, t_floatarg size, t_floatarg fflags, t_floatarg otherflag) { t_glist *gl; t_garray *a; int flags = fflags; if (size < 1) size = 1; if (otherflag == 0 || (!(gl = glist_findgraph(parent)))) gl = glist_addglist(parent, &s_, 0, 1, size, -1, 0, 0, 0, 0); a = graph_array(gl, iemgui_raute2dollar(name), &s_float, size, flags); canvas_dirty(parent, 1); } /* this is called from the properties dialog window for an existing array */ void garray_arraydialog(t_garray *x, t_symbol *name, t_floatarg fsize, t_floatarg fflags, t_floatarg deleteit) { int flags = fflags; int saveit = ((flags & 1) != 0); int filestyle = ((flags & 6) >> 1); int style = (filestyle == 0 ? PLOTSTYLE_POLY : (filestyle == 1 ? PLOTSTYLE_POINTS : filestyle)); t_float stylewas = template_getfloat( template_findbyname(x->x_scalar->sc_template), gensym("style"), x->x_scalar->sc_vec, 1); if (deleteit != 0) { int wasused = x->x_usedindsp; glist_delete(x->x_glist, &x->x_gobj); if (wasused) canvas_update_dsp(); } else { long size; t_symbol *argname = iemgui_raute2dollar(name); t_array *a = garray_getarray(x); t_template *scalartemplate; if (!a) { pd_error(x, "can't find array\n"); return; } if (!(scalartemplate = template_findbyname(x->x_scalar->sc_template))) { error("array: no template of type %s", x->x_scalar->sc_template->s_name); return; } if (argname != x->x_name) { /* jsarlo { */ if (x->x_listviewing) { garray_arrayviewlist_close(x); } /* } jsarlo */ x->x_name = argname; pd_unbind(&x->x_gobj.g_pd, x->x_realname); x->x_realname = canvas_realizedollar(x->x_glist, argname); pd_bind(&x->x_gobj.g_pd, x->x_realname); /* redraw the whole glist, just so the name change shows up */ if (x->x_glist->gl_havewindow) canvas_redraw(x->x_glist); else if (glist_isvisible(x->x_glist->gl_owner)) { gobj_vis(&x->x_glist->gl_gobj, x->x_glist->gl_owner, 0); gobj_vis(&x->x_glist->gl_gobj, x->x_glist->gl_owner, 1); } canvas_update_dsp(); } size = fsize; if (size < 1) size = 1; if (size != a->a_n) garray_resize_long(x, size); else if (style != stylewas) garray_fittograph(x, (int)size, style); template_setfloat(scalartemplate, gensym("style"), x->x_scalar->sc_vec, (t_float)style, 0); garray_setsaveit(x, (saveit != 0)); garray_redraw(x); canvas_dirty(x->x_glist, 1); } } /* jsarlo { */ void garray_arrayviewlist_new(t_garray *x) { int i, yonset=0, elemsize=0; t_float yval; char cmdbuf[200]; t_array *a = garray_getarray_floatonly(x, &yonset, &elemsize); if (!a) { /* FIXME */ error("error in garray_arrayviewlist_new()"); } x->x_listviewing = 1; sprintf(cmdbuf, "pdtk_array_listview_new %%s %s %d\n", x->x_realname->s_name, 0); gfxstub_new(&x->x_gobj.g_pd, x, cmdbuf); for (i = 0; i < ARRAYPAGESIZE && i < a->a_n; i++) { yval = *(t_float *)(a->a_vec + elemsize * i + yonset); sys_vgui(".%sArrayWindow.lb insert %d {%d) %g}\n", x->x_realname->s_name, i, i, yval); } } void garray_arrayviewlist_fillpage(t_garray *x, t_float page, t_float fTopItem) { int i, yonset=0, elemsize=0, topItem; t_float yval; t_array *a = garray_getarray_floatonly(x, &yonset, &elemsize); topItem = (int)fTopItem; if (!a) { /* FIXME */ error("error in garray_arrayviewlist_new()"); } if (page < 0) { page = 0; sys_vgui("pdtk_array_listview_setpage %s %d\n", x->x_realname->s_name, (int)page); } else if ((page * ARRAYPAGESIZE) >= a->a_n) { page = (int)(((int)a->a_n - 1)/ (int)ARRAYPAGESIZE); sys_vgui("pdtk_array_listview_setpage %s %d\n", x->x_realname->s_name, (int)page); } sys_vgui(".%sArrayWindow.lb delete 0 %d\n", x->x_realname->s_name, ARRAYPAGESIZE - 1); for (i = page * ARRAYPAGESIZE; (i < (page + 1) * ARRAYPAGESIZE && i < a->a_n); i++) { yval = *(t_float *)(a->a_vec + \ elemsize * i + yonset); sys_vgui(".%sArrayWindow.lb insert %d {%d) %g}\n", x->x_realname->s_name, i % ARRAYPAGESIZE, i, yval); } sys_vgui(".%sArrayWindow.lb yview %d\n", x->x_realname->s_name, topItem); } void garray_arrayviewlist_close(t_garray *x) { x->x_listviewing = 0; sys_vgui("pdtk_array_listview_closeWindow %s\n", x->x_realname->s_name); } /* } jsarlo */ static void garray_free(t_garray *x) { t_pd *x2; sys_unqueuegui(&x->x_gobj); /* jsarlo { */ if (x->x_listviewing) { garray_arrayviewlist_close(x); } /* } jsarlo */ gfxstub_deleteforkey(x); pd_unbind(&x->x_gobj.g_pd, x->x_realname); /* just in case we're still bound to #A from loading... */ while ((x2 = pd_findbyclass(gensym("#A"), garray_class))) pd_unbind(x2, gensym("#A")); pd_free(&x->x_scalar->sc_gobj.g_pd); } /* ------------- code used by both array and plot widget functions ---- */ void array_redraw(t_array *a, t_glist *glist) { while (a->a_gp.gp_stub->gs_which == GP_ARRAY) a = a->a_gp.gp_stub->gs_un.gs_array; scalar_redraw(a->a_gp.gp_un.gp_scalar, glist); } /* routine to get screen coordinates of a point in an array */ void array_getcoordinate(t_glist *glist, char *elem, int xonset, int yonset, int wonset, int indx, t_float basex, t_float basey, t_float xinc, t_fielddesc *xfielddesc, t_fielddesc *yfielddesc, t_fielddesc *wfielddesc, t_float *xp, t_float *yp, t_float *wp) { t_float xval, yval, ypix, wpix; if (xonset >= 0) xval = *(t_float *)(elem + xonset); else xval = indx * xinc; if (yonset >= 0) yval = *(t_float *)(elem + yonset); else yval = 0; ypix = glist_ytopixels(glist, basey + fielddesc_cvttocoord(yfielddesc, yval)); if (wonset >= 0) { /* found "w" field which controls linewidth. */ t_float wval = *(t_float *)(elem + wonset); wpix = glist_ytopixels(glist, basey + fielddesc_cvttocoord(yfielddesc, yval) + fielddesc_cvttocoord(wfielddesc, wval)) - ypix; if (wpix < 0) wpix = -wpix; } else wpix = 1; *xp = glist_xtopixels(glist, basex + fielddesc_cvttocoord(xfielddesc, xval)); *yp = ypix; *wp = wpix; } static void array_getrect(t_array *array, t_glist *glist, int *xp1, int *yp1, int *xp2, int *yp2) { t_float x1 = 0x7fffffff, y1 = 0x7fffffff, x2 = -0x7fffffff, y2 = -0x7fffffff; t_canvas *elemtemplatecanvas; t_template *elemtemplate; int elemsize, yonset, wonset, xonset, i; if (!array_getfields(array->a_templatesym, &elemtemplatecanvas, &elemtemplate, &elemsize, 0, 0, 0, &xonset, &yonset, &wonset)) { int incr; /* if it has more than 2000 points, just check 300 of them. */ if (array->a_n < 2000) incr = 1; else incr = array->a_n / 300; for (i = 0; i < array->a_n; i += incr) { t_float pxpix, pypix, pwpix; array_getcoordinate(glist, (char *)(array->a_vec) + i * elemsize, xonset, yonset, wonset, i, 0, 0, 1, 0, 0, 0, &pxpix, &pypix, &pwpix); if (pwpix < 2) pwpix = 2; if (pxpix < x1) x1 = pxpix; if (pxpix > x2) x2 = pxpix; if (pypix - pwpix < y1) y1 = pypix - pwpix; if (pypix + pwpix > y2) y2 = pypix + pwpix; } } *xp1 = x1; *yp1 = y1; *xp2 = x2; *yp2 = y2; } /* -------------------- widget behavior for garray ------------ */ static void garray_getrect(t_gobj *z, t_glist *glist, int *xp1, int *yp1, int *xp2, int *yp2) { t_garray *x = (t_garray *)z; gobj_getrect(&x->x_scalar->sc_gobj, glist, xp1, yp1, xp2, yp2); } static void garray_displace(t_gobj *z, t_glist *glist, int dx, int dy) { /* refuse */ } static void garray_select(t_gobj *z, t_glist *glist, int state) { t_garray *x = (t_garray *)z; /* fill in later */ } static void garray_activate(t_gobj *z, t_glist *glist, int state) { } static void garray_delete(t_gobj *z, t_glist *glist) { /* nothing to do */ } static void garray_vis(t_gobj *z, t_glist *glist, int vis) { t_garray *x = (t_garray *)z; gobj_vis(&x->x_scalar->sc_gobj, glist, vis); } static int garray_click(t_gobj *z, t_glist *glist, int xpix, int ypix, int shift, int alt, int dbl, int doit) { t_garray *x = (t_garray *)z; return (gobj_click(&x->x_scalar->sc_gobj, glist, xpix, ypix, shift, alt, dbl, doit)); } #define ARRAYWRITECHUNKSIZE 1000 void garray_savecontentsto(t_garray *x, t_binbuf *b) { if (x->x_saveit) { t_array *array = garray_getarray(x); int n = array->a_n, n2 = 0; if (n > 200000) post("warning: I'm saving an array with %d points!\n", n); while (n2 < n) { int chunk = n - n2, i; if (chunk > ARRAYWRITECHUNKSIZE) chunk = ARRAYWRITECHUNKSIZE; binbuf_addv(b, "si", gensym("#A"), n2); for (i = 0; i < chunk; i++) binbuf_addv(b, "f", ((t_word *)(array->a_vec))[n2+i].w_float); binbuf_addv(b, ";"); n2 += chunk; } } } static void garray_save(t_gobj *z, t_binbuf *b) { int style, filestyle; t_garray *x = (t_garray *)z; t_array *array = garray_getarray(x); t_template *scalartemplate; if (x->x_scalar->sc_template != gensym("pd-float-array")) { /* LATER "save" the scalar as such */ pd_error(x, "can't save arrays of type %s yet", x->x_scalar->sc_template->s_name); return; } if (!(scalartemplate = template_findbyname(x->x_scalar->sc_template))) { error("array: no template of type %s", x->x_scalar->sc_template->s_name); return; } style = template_getfloat(scalartemplate, gensym("style"), x->x_scalar->sc_vec, 0); filestyle = (style == PLOTSTYLE_POINTS ? 1 : (style == PLOTSTYLE_POLY ? 0 : style)); binbuf_addv(b, "sssisi;", gensym("#X"), gensym("array"), x->x_name, array->a_n, &s_float, x->x_saveit + 2 * filestyle + 8*x->x_hidename); garray_savecontentsto(x, b); } const t_widgetbehavior garray_widgetbehavior = { garray_getrect, garray_displace, garray_select, garray_activate, garray_delete, garray_vis, garray_click, }; /* ----------------------- public functions -------------------- */ void garray_usedindsp(t_garray *x) { x->x_usedindsp = 1; } static void garray_doredraw(t_gobj *client, t_glist *glist) { t_garray *x = (t_garray *)client; if (glist_isvisible(x->x_glist) && gobj_shouldvis(client, glist)) { garray_vis(&x->x_gobj, x->x_glist, 0); garray_vis(&x->x_gobj, x->x_glist, 1); } } void garray_redraw(t_garray *x) { if (glist_isvisible(x->x_glist)) sys_queuegui(&x->x_gobj, x->x_glist, garray_doredraw); /* jsarlo { */ /* this happens in garray_vis() when array is visible for performance reasons */ else { if (x->x_listviewing) sys_vgui("pdtk_array_listview_fillpage %s\n", x->x_realname->s_name); } /* } jsarlo */ } /* This functiopn gets the template of an array; if we can't figure out what template an array's elements belong to we're in grave trouble when it's time to free or resize it. */ t_template *garray_template(t_garray *x) { t_array *array = garray_getarray(x); t_template *template = (array ? template_findbyname(array->a_templatesym) : 0); if (!template) bug("garray_template"); return (template); } int garray_npoints(t_garray *x) /* get the length */ { t_array *array = garray_getarray(x); return (array->a_n); } char *garray_vec(t_garray *x) /* get the contents */ { t_array *array = garray_getarray(x); return ((char *)(array->a_vec)); } /* routine that checks if we're just an array of floats and if so returns the goods */ int garray_getfloatwords(t_garray *x, int *size, t_word **vec) { int yonset, elemsize; t_array *a = garray_getarray_floatonly(x, &yonset, &elemsize); if (!a) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return (0); } else if (elemsize != sizeof(t_word)) { error("%s: has more than one field", x->x_realname->s_name); return (0); } *size = garray_npoints(x); *vec = (t_word *)garray_vec(x); return (1); } /* older, non-64-bit safe version, supplied for older externs */ int garray_getfloatarray(t_garray *x, int *size, t_float **vec) { if (sizeof(t_word) != sizeof(t_float)) { t_symbol *patchname; if (x->x_glist->gl_owner) patchname = x->x_glist->gl_owner->gl_name; else patchname = x->x_glist->gl_name; error("an operation on the array '%s' in the patch '%s'", x->x_name->s_name, patchname->s_name); error("failed since it uses garray_getfloatarray while running 64-bit"); } return (garray_getfloatwords(x, size, (t_word **)vec)); } /* set the "saveit" flag */ void garray_setsaveit(t_garray *x, int saveit) { if (x->x_saveit && !saveit) post("warning: array %s: clearing save-in-patch flag", x->x_name->s_name); x->x_saveit = saveit; } /*------------------- Pd messages ------------------------ */ static void garray_const(t_garray *x, t_floatarg g) { int yonset, i, elemsize; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) error("%s: needs floating-point 'y' field", x->x_realname->s_name); else for (i = 0; i < array->a_n; i++) *((t_float *)((char *)array->a_vec + elemsize * i) + yonset) = g; garray_redraw(x); } /* sum of Fourier components; called from routines below */ static void garray_dofo(t_garray *x, long npoints, t_float dcval, int nsin, t_float *vsin, int sineflag) { double phase, phaseincr, fj; int yonset, i, j, elemsize; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return; } if (npoints == 0) npoints = 512; /* dunno what a good default would be... */ if (npoints != (1 << ilog2((int)npoints))) post("%s: rounding to %d points", array->a_templatesym->s_name, (npoints = (1<<ilog2((int)npoints)))); garray_resize_long(x, npoints + 3); phaseincr = 2. * 3.14159 / npoints; for (i = 0, phase = -phaseincr; i < array->a_n; i++, phase += phaseincr) { double sum = dcval; if (sineflag) for (j = 0, fj = phase; j < nsin; j++, fj += phase) sum += vsin[j] * sin(fj); else for (j = 0, fj = 0; j < nsin; j++, fj += phase) sum += vsin[j] * cos(fj); *((t_float *)((array->a_vec + elemsize * i)) + yonset) = sum; } garray_redraw(x); } static void garray_sinesum(t_garray *x, t_symbol *s, int argc, t_atom *argv) { t_float *svec; long npoints; int i; if (argc < 2) { error("sinesum: %s: need number of points and partial strengths", x->x_realname->s_name); return; } npoints = atom_getfloatarg(0, argc, argv); argv++, argc--; svec = (t_float *)t_getbytes(sizeof(t_float) * argc); if (!svec) return; for (i = 0; i < argc; i++) svec[i] = atom_getfloatarg(i, argc, argv); garray_dofo(x, npoints, 0, argc, svec, 1); t_freebytes(svec, sizeof(t_float) * argc); } static void garray_cosinesum(t_garray *x, t_symbol *s, int argc, t_atom *argv) { t_float *svec; long npoints; int i; if (argc < 2) { error("sinesum: %s: need number of points and partial strengths", x->x_realname->s_name); return; } npoints = atom_getfloatarg(0, argc, argv); argv++, argc--; svec = (t_float *)t_getbytes(sizeof(t_float) * argc); if (!svec) return; for (i = 0; i < argc; i++) svec[i] = atom_getfloatarg(i, argc, argv); garray_dofo(x, npoints, 0, argc, svec, 0); t_freebytes(svec, sizeof(t_float) * argc); } static void garray_normalize(t_garray *x, t_float f) { int i; double maxv, renormer; int yonset, elemsize; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return; } if (f <= 0) f = 1; for (i = 0, maxv = 0; i < array->a_n; i++) { double v = *((t_float *)(array->a_vec + elemsize * i) + yonset); if (v > maxv) maxv = v; if (-v > maxv) maxv = -v; } if (maxv > 0) { renormer = f / maxv; for (i = 0; i < array->a_n; i++) *((t_float *)(array->a_vec + elemsize * i) + yonset) *= renormer; } garray_redraw(x); } /* list -- the first value is an index; subsequent values are put in the "y" slot of the array. This generalizes Max's "table", sort of. */ static void garray_list(t_garray *x, t_symbol *s, int argc, t_atom *argv) { int i; int yonset, elemsize; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return; } if (argc < 2) return; else { int firstindex = atom_getfloat(argv); argc--; argv++; /* drop negative x values */ if (firstindex < 0) { argc += firstindex; argv -= firstindex; firstindex = 0; if (argc <= 0) return; } if (argc + firstindex > array->a_n) { argc = array->a_n - firstindex; if (argc <= 0) return; } for (i = 0; i < argc; i++) *((t_float *)(array->a_vec + elemsize * (i + firstindex)) + yonset) = atom_getfloat(argv + i); } garray_redraw(x); } /* forward a "bounds" message to the owning graph */ static void garray_bounds(t_garray *x, t_floatarg x1, t_floatarg y1, t_floatarg x2, t_floatarg y2) { vmess(&x->x_glist->gl_pd, gensym("bounds"), "ffff", x1, y1, x2, y2); } /* same for "xticks", etc */ static void garray_xticks(t_garray *x, t_floatarg point, t_floatarg inc, t_floatarg f) { vmess(&x->x_glist->gl_pd, gensym("xticks"), "fff", point, inc, f); } static void garray_yticks(t_garray *x, t_floatarg point, t_floatarg inc, t_floatarg f) { vmess(&x->x_glist->gl_pd, gensym("yticks"), "fff", point, inc, f); } static void garray_xlabel(t_garray *x, t_symbol *s, int argc, t_atom *argv) { typedmess(&x->x_glist->gl_pd, s, argc, argv); } static void garray_ylabel(t_garray *x, t_symbol *s, int argc, t_atom *argv) { typedmess(&x->x_glist->gl_pd, s, argc, argv); } /* change the name of a garray. */ static void garray_rename(t_garray *x, t_symbol *s) { /* jsarlo { */ if (x->x_listviewing) { garray_arrayviewlist_close(x); } /* } jsarlo */ pd_unbind(&x->x_gobj.g_pd, x->x_realname); pd_bind(&x->x_gobj.g_pd, x->x_realname = x->x_name = s); garray_redraw(x); } static void garray_read(t_garray *x, t_symbol *filename) { int nelem, filedesc, i; FILE *fd; char buf[MAXPDSTRING], *bufptr; int yonset, elemsize; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return; } nelem = array->a_n; if ((filedesc = canvas_open(glist_getcanvas(x->x_glist), filename->s_name, "", buf, &bufptr, MAXPDSTRING, 0)) < 0 || !(fd = fdopen(filedesc, "r"))) { error("%s: can't open", filename->s_name); return; } for (i = 0; i < nelem; i++) { double f; if (!fscanf(fd, "%lf", &f)) { post("%s: read %d elements into table of size %d", filename->s_name, i, nelem); break; } else *((t_float *)(array->a_vec + elemsize * i) + yonset) = f; } while (i < nelem) *((t_float *)(array->a_vec + elemsize * i) + yonset) = 0, i++; fclose(fd); garray_redraw(x); } static void garray_write(t_garray *x, t_symbol *filename) { FILE *fd; char buf[MAXPDSTRING]; int yonset, elemsize, i; t_array *array = garray_getarray_floatonly(x, &yonset, &elemsize); if (!array) { error("%s: needs floating-point 'y' field", x->x_realname->s_name); return; } canvas_makefilename(glist_getcanvas(x->x_glist), filename->s_name, buf, MAXPDSTRING); if (!(fd = sys_fopen(buf, "w"))) { error("%s: can't create", buf); return; } for (i = 0; i < array->a_n; i++) { if (fprintf(fd, "%g\n", *(t_float *)(((array->a_vec + sizeof(t_word) * i)) + yonset)) < 1) { post("%s: write error", filename->s_name); break; } } fclose(fd); } /* this should be renamed and moved... */ int garray_ambigendian(void) { unsigned short s = 1; unsigned char c = *(char *)(&s); return (c==0); } void garray_resize_long(t_garray *x, long n) { t_array *array = garray_getarray(x); if (n < 1) n = 1; if (n == array->a_n) return; garray_fittograph(x, (int)n, template_getfloat( template_findbyname(x->x_scalar->sc_template), gensym("style"), x->x_scalar->sc_vec, 1)); array_resize_and_redraw(array, x->x_glist, (int)n); if (x->x_usedindsp) canvas_update_dsp(); } /* float version to use as Pd method */ void garray_resize(t_garray *x, t_floatarg f) { garray_resize_long(x, f); } /* ignore zoom for now */ static void garray_zoom(t_garray *x, t_floatarg f) { } static void garray_print(t_garray *x) { t_array *array = garray_getarray(x); post("garray %s: template %s, length %d", x->x_realname->s_name, array->a_templatesym->s_name, array->a_n); } void g_array_setup(void) { garray_class = class_new(gensym("array"), 0, (t_method)garray_free, sizeof(t_garray), CLASS_GOBJ, 0); class_setwidget(garray_class, &garray_widgetbehavior); class_addmethod(garray_class, (t_method)garray_const, gensym("const"), A_DEFFLOAT, A_NULL); class_addlist(garray_class, garray_list); class_addmethod(garray_class, (t_method)garray_bounds, gensym("bounds"), A_FLOAT, A_FLOAT, A_FLOAT, A_FLOAT, A_NULL); class_addmethod(garray_class, (t_method)garray_xticks, gensym("xticks"), A_FLOAT, A_FLOAT, A_FLOAT, 0); class_addmethod(garray_class, (t_method)garray_xlabel, gensym("xlabel"), A_GIMME, 0); class_addmethod(garray_class, (t_method)garray_yticks, gensym("yticks"), A_FLOAT, A_FLOAT, A_FLOAT, 0); class_addmethod(garray_class, (t_method)garray_ylabel, gensym("ylabel"), A_GIMME, 0); class_addmethod(garray_class, (t_method)garray_rename, gensym("rename"), A_SYMBOL, 0); class_addmethod(garray_class, (t_method)garray_read, gensym("read"), A_SYMBOL, A_NULL); class_addmethod(garray_class, (t_method)garray_write, gensym("write"), A_SYMBOL, A_NULL); class_addmethod(garray_class, (t_method)garray_resize, gensym("resize"), A_FLOAT, A_NULL); class_addmethod(garray_class, (t_method)garray_zoom, gensym("zoom"), A_FLOAT, 0); class_addmethod(garray_class, (t_method)garray_print, gensym("print"), A_NULL); class_addmethod(garray_class, (t_method)garray_sinesum, gensym("sinesum"), A_GIMME, 0); class_addmethod(garray_class, (t_method)garray_cosinesum, gensym("cosinesum"), A_GIMME, 0); class_addmethod(garray_class, (t_method)garray_normalize, gensym("normalize"), A_DEFFLOAT, 0); class_addmethod(garray_class, (t_method)garray_arraydialog, gensym("arraydialog"), A_SYMBOL, A_FLOAT, A_FLOAT, A_FLOAT, A_NULL); /* jsarlo { */ class_addmethod(garray_class, (t_method)garray_arrayviewlist_new, gensym("arrayviewlistnew"), A_NULL); class_addmethod(garray_class, (t_method)garray_arrayviewlist_fillpage, gensym("arrayviewlistfillpage"), A_FLOAT, A_DEFFLOAT, A_NULL); class_addmethod(garray_class, (t_method)garray_arrayviewlist_close, gensym("arrayviewclose"), A_NULL); /* } jsarlo */ class_setsavefn(garray_class, garray_save); }
849193.c
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; static doublereal c_b5 = 1.; static doublereal c_b7 = 0.; /* > \brief \b DGEQRT2 computes a QR factorization of a general real or complex matrix using the compact WY re presentation of Q. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DGEQRT2 + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dgeqrt2 .f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dgeqrt2 .f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dgeqrt2 .f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DGEQRT2( M, N, A, LDA, T, LDT, INFO ) */ /* INTEGER INFO, LDA, LDT, M, N */ /* DOUBLE PRECISION A( LDA, * ), T( LDT, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > DGEQRT2 computes a QR factorization of a real M-by-N matrix A, */ /* > using the compact WY representation of Q. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the matrix A. M >= N. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] A */ /* > \verbatim */ /* > A is DOUBLE PRECISION array, dimension (LDA,N) */ /* > On entry, the real M-by-N matrix A. On exit, the elements on and */ /* > above the diagonal contain the N-by-N upper triangular matrix R; the */ /* > elements below the diagonal are the columns of V. See below for */ /* > further details. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= f2cmax(1,M). */ /* > \endverbatim */ /* > */ /* > \param[out] T */ /* > \verbatim */ /* > T is DOUBLE PRECISION array, dimension (LDT,N) */ /* > The N-by-N upper triangular factor of the block reflector. */ /* > The elements on and above the diagonal contain the block */ /* > reflector T; the elements below the diagonal are not used. */ /* > See below for further details. */ /* > \endverbatim */ /* > */ /* > \param[in] LDT */ /* > \verbatim */ /* > LDT is INTEGER */ /* > The leading dimension of the array T. LDT >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup doubleGEcomputational */ /* > \par Further Details: */ /* ===================== */ /* > */ /* > \verbatim */ /* > */ /* > The matrix V stores the elementary reflectors H(i) in the i-th column */ /* > below the diagonal. For example, if M=5 and N=3, the matrix V is */ /* > */ /* > V = ( 1 ) */ /* > ( v1 1 ) */ /* > ( v1 v2 1 ) */ /* > ( v1 v2 v3 ) */ /* > ( v1 v2 v3 ) */ /* > */ /* > where the vi's represent the vectors which define H(i), which are returned */ /* > in the matrix A. The 1's along the diagonal of V are not stored in A. The */ /* > block reflector H is then given by */ /* > */ /* > H = I - V * T * V**T */ /* > */ /* > where V**T is the transpose of V. */ /* > \endverbatim */ /* > */ /* ===================================================================== */ /* Subroutine */ int dgeqrt2_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *t, integer *ldt, integer *info) { /* System generated locals */ integer a_dim1, a_offset, t_dim1, t_offset, i__1, i__2, i__3; /* Local variables */ extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); integer i__, k; doublereal alpha; extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dtrmv_(char *, char *, char *, integer *, doublereal *, integer *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *, ftnlen); doublereal aii; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1 * 1; t -= t_offset; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < f2cmax(1,*m)) { *info = -4; } else if (*ldt < f2cmax(1,*n)) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEQRT2", &i__1, (ftnlen)7); return 0; } k = f2cmin(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elem. refl. H(i) to annihilate A(i+1:m,i), tau(I) -> T(I,1) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[f2cmin(i__3,*m) + i__ * a_dim1] , &c__1, &t[i__ + t_dim1]); if (i__ < *n) { /* Apply H(i) to A(I:M,I+1:N) from the left */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; /* W(1:N-I) := A(I:M,I+1:N)^H * A(I:M,I) [W = T(:,N)] */ i__2 = *m - i__ + 1; i__3 = *n - i__; dgemv_("T", &i__2, &i__3, &c_b5, &a[i__ + (i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b7, &t[*n * t_dim1 + 1], &c__1); /* A(I:M,I+1:N) = A(I:m,I+1:N) + alpha*A(I:M,I)*W(1:N-1)^H */ alpha = -t[i__ + t_dim1]; i__2 = *m - i__ + 1; i__3 = *n - i__; dger_(&i__2, &i__3, &alpha, &a[i__ + i__ * a_dim1], &c__1, &t[*n * t_dim1 + 1], &c__1, &a[i__ + (i__ + 1) * a_dim1], lda); a[i__ + i__ * a_dim1] = aii; } } i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; /* T(1:I-1,I) := alpha * A(I:M,1:I-1)**T * A(I:M,I) */ alpha = -t[i__ + t_dim1]; i__2 = *m - i__ + 1; i__3 = i__ - 1; dgemv_("T", &i__2, &i__3, &alpha, &a[i__ + a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b7, &t[i__ * t_dim1 + 1], &c__1); a[i__ + i__ * a_dim1] = aii; /* T(1:I-1,I) := T(1:I-1,1:I-1) * T(1:I-1,I) */ i__2 = i__ - 1; dtrmv_("U", "N", "N", &i__2, &t[t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); /* T(I,I) = tau(I) */ t[i__ + i__ * t_dim1] = t[i__ + t_dim1]; t[i__ + t_dim1] = 0.; } /* End of DGEQRT2 */ return 0; } /* dgeqrt2_ */
215368.c
// SPDX-License-Identifier: MIT OR BSD-3-Clause #define posit_WITH_MPFR #include "posit.h" #define posit_WITH_MPFR #include "enumerate_implementations.h" static int g_had_disagreement; static int g_crash_on_disagree; int allimpls_had_disagreement() { return g_had_disagreement; } void allimpls_crash_on_disagree() { g_crash_on_disagree = 1; } void allimpls_register() { static int isregged; if (isregged) { return; } isregged = 1; #include "implementations.h" } #include <stdio.h> #include <string.h> #include <stdlib.h> #define DEBUG(...) //printf(__VA_ARGS__) static char arg1 = '\0'; static uint8_t* g_arg1p = (uint8_t*) &arg1; #define posit_FUNC(__name__,__args__,__rett__,__argdef__) \ __rett__ posit__GLUE(__name__,_all)__argdef__ { \ allimpls_register(); \ DEBUG("running %s", STRING(__name__)); \ __rett__ posit__GLUE(__name__,_slow)__argdef__; \ __rett__ slowout = posit__GLUE(__name__,_slow)__args__; \ allimpls_func_t* func = &posit__GLUE3(g_, __name__, _func); \ allimpls_impl_t* impl = func->impls; \ for (; impl; impl = impl->next) { \ DEBUG(" %s", impl->name); \ posit__GLUE(__name__, _impl_t)* realimpl = (posit__GLUE(__name__, _impl_t)*) impl; \ if (realimpl->call == posit__GLUE(__name__,_slow)) { continue; } \ __rett__ implout = realimpl->call __args__; \ if (memcmp(&implout, &slowout, sizeof(__rett__))) { \ g_had_disagreement = 1; \ uint8_t* so = (uint8_t*) &slowout; \ uint8_t* io = (uint8_t*) &implout; \ uint8_t* _a = (uint8_t*) &arg0; \ uint8_t* _b = (uint8_t*) &arg1; \ printf("function %s: slow and [%s] disagree\nslow : ", func->name, impl->name); \ for (int i = (int)sizeof(__rett__) - 1; i >= 0; i--) { printf("%02x", so[i]); } \ printf("\n : "); \ for (int i = (int)sizeof(__rett__) - 1; i >= 0; i-- ) { printf("%02x", io[i]); } \ printf("\n arg0: "); \ for (int i = (int)(sizeof arg0) - 1; i >= 0; i-- ) { printf("%02x", _a[i]); } \ if (_b != g_arg1p) { \ printf("\n arg1: "); \ for (int i = (int)(sizeof arg1) - 1; i >= 0; i-- ) { printf("%02x", _b[i]); } \ } \ printf("\n"); \ if (g_crash_on_disagree) { abort(); } \ } \ } \ DEBUG("\n"); \ return slowout; \ } #define posit_VFUNC(__name__,__args__,__argdef__) #define STRING(x) _STRING(x) #define _STRING(x) #x #pragma GCC diagnostic ignored "-Wsizeof-array-argument" #define posit_WITH_MPFR #include "positgen.h"
820859.c
/* Support for the generic parts of PE/PEI; the common executable parts. Copyright (C) 1995-2021 Free Software Foundation, Inc. Written by Cygnus Solutions. This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* Most of this hacked by Steve Chamberlain <[email protected]>. PE/PEI rearrangement (and code added): Donn Terry Softway Systems, Inc. */ /* Hey look, some documentation [and in a place you expect to find it]! The main reference for the pei format is "Microsoft Portable Executable and Common Object File Format Specification 4.1". Get it if you need to do some serious hacking on this code. Another reference: "Peering Inside the PE: A Tour of the Win32 Portable Executable File Format", MSJ 1994, Volume 9. The PE/PEI format is also used by .NET. ECMA-335 describes this: "Standard ECMA-335 Common Language Infrastructure (CLI)", 6th Edition, June 2012. This is also available at https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf. The *sole* difference between the pe format and the pei format is that the latter has an MSDOS 2.0 .exe header on the front that prints the message "This app must be run under Windows." (or some such). (FIXME: Whether that statement is *really* true or not is unknown. Are there more subtle differences between pe and pei formats? For now assume there aren't. If you find one, then for God sakes document it here!) The Microsoft docs use the word "image" instead of "executable" because the former can also refer to a DLL (shared library). Confusion can arise because the `i' in `pei' also refers to "image". The `pe' format can also create images (i.e. executables), it's just that to run on a win32 system you need to use the pei format. FIXME: Please add more docs here so the next poor fool that has to hack on this code has a chance of getting something accomplished without wasting too much time. */ /* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64 depending on whether we're compiling for straight PE or PE+. */ #define COFF_WITH_XX #include "sysdep.h" #include "bfd.h" #include "libbfd.h" #include "coff/internal.h" #include "bfdver.h" #include "libiberty.h" #include <wchar.h> #include <wctype.h> /* NOTE: it's strange to be including an architecture specific header in what's supposed to be general (to PE/PEI) code. However, that's where the definitions are, and they don't vary per architecture within PE/PEI, so we get them from there. FIXME: The lack of variance is an assumption which may prove to be incorrect if new PE/PEI targets are created. */ #if defined COFF_WITH_pex64 # include "coff/x86_64.h" #elif defined COFF_WITH_pep # include "coff/ia64.h" #else # include "coff/i386.h" #endif #include "coff/pe.h" #include "libcoff.h" #include "libpei.h" #include "safe-ctype.h" #if defined COFF_WITH_pep || defined COFF_WITH_pex64 # undef AOUTSZ # define AOUTSZ PEPAOUTSZ # define PEAOUTHDR PEPAOUTHDR #endif #define HighBitSet(val) ((val) & 0x80000000) #define SetHighBit(val) ((val) | 0x80000000) #define WithoutHighBit(val) ((val) & 0x7fffffff) void _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1) { SYMENT *ext = (SYMENT *) ext1; struct internal_syment *in = (struct internal_syment *) in1; if (ext->e.e_name[0] == 0) { in->_n._n_n._n_zeroes = 0; in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset); } else memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN); in->n_value = H_GET_32 (abfd, ext->e_value); in->n_scnum = (short) H_GET_16 (abfd, ext->e_scnum); if (sizeof (ext->e_type) == 2) in->n_type = H_GET_16 (abfd, ext->e_type); else in->n_type = H_GET_32 (abfd, ext->e_type); in->n_sclass = H_GET_8 (abfd, ext->e_sclass); in->n_numaux = H_GET_8 (abfd, ext->e_numaux); #ifndef STRICT_PE_FORMAT /* This is for Gnu-created DLLs. */ /* The section symbols for the .idata$ sections have class 0x68 (C_SECTION), which MS documentation indicates is a section symbol. Unfortunately, the value field in the symbol is simply a copy of the .idata section's flags rather than something useful. When these symbols are encountered, change the value to 0 so that they will be handled somewhat correctly in the bfd code. */ if (in->n_sclass == C_SECTION) { char namebuf[SYMNMLEN + 1]; const char *name = NULL; in->n_value = 0x0; /* Create synthetic empty sections as needed. DJ */ if (in->n_scnum == 0) { asection *sec; name = _bfd_coff_internal_syment_name (abfd, in, namebuf); if (name == NULL) { _bfd_error_handler (_("%pB: unable to find name for empty section"), abfd); bfd_set_error (bfd_error_invalid_target); return; } sec = bfd_get_section_by_name (abfd, name); if (sec != NULL) in->n_scnum = sec->target_index; } if (in->n_scnum == 0) { int unused_section_number = 0; asection *sec; flagword flags; size_t name_len; char *sec_name; for (sec = abfd->sections; sec; sec = sec->next) if (unused_section_number <= sec->target_index) unused_section_number = sec->target_index + 1; name_len = strlen (name) + 1; sec_name = bfd_alloc (abfd, name_len); if (sec_name == NULL) { _bfd_error_handler (_("%pB: out of memory creating name " "for empty section"), abfd); return; } memcpy (sec_name, name, name_len); flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD; sec = bfd_make_section_anyway_with_flags (abfd, sec_name, flags); if (sec == NULL) { _bfd_error_handler (_("%pB: unable to create fake empty section"), abfd); return; } sec->vma = 0; sec->lma = 0; sec->size = 0; sec->filepos = 0; sec->rel_filepos = 0; sec->reloc_count = 0; sec->line_filepos = 0; sec->lineno_count = 0; sec->userdata = NULL; sec->next = NULL; sec->alignment_power = 2; sec->target_index = unused_section_number; in->n_scnum = unused_section_number; } in->n_sclass = C_STAT; } #endif } static bool abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data) { bfd_vma abs_val = * (bfd_vma *) data; return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val); } unsigned int _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp) { struct internal_syment *in = (struct internal_syment *) inp; SYMENT *ext = (SYMENT *) extp; if (in->_n._n_name[0] == 0) { H_PUT_32 (abfd, 0, ext->e.e.e_zeroes); H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset); } else memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN); /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a symbol. This is a problem on 64-bit targets where we can generate absolute symbols with values >= 1^32. We try to work around this problem by finding a section whose base address is sufficient to reduce the absolute value to < 1^32, and then transforming the symbol into a section relative symbol. This of course is a hack. */ if (sizeof (in->n_value) > 4 /* The strange computation of the shift amount is here in order to avoid a compile time warning about the comparison always being false. It does not matter if this test fails to work as expected as the worst that can happen is that some absolute symbols are needlessly converted into section relative symbols. */ && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1) && in->n_scnum == N_ABS) { asection * sec; sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value); if (sec) { in->n_value -= sec->vma; in->n_scnum = sec->target_index; } /* else: FIXME: The value is outside the range of any section. This happens for __image_base__ and __ImageBase and maybe some other symbols as well. We should find a way to handle these values. */ } H_PUT_32 (abfd, in->n_value, ext->e_value); H_PUT_16 (abfd, in->n_scnum, ext->e_scnum); if (sizeof (ext->e_type) == 2) H_PUT_16 (abfd, in->n_type, ext->e_type); else H_PUT_32 (abfd, in->n_type, ext->e_type); H_PUT_8 (abfd, in->n_sclass, ext->e_sclass); H_PUT_8 (abfd, in->n_numaux, ext->e_numaux); return SYMESZ; } void _bfd_XXi_swap_aux_in (bfd * abfd, void * ext1, int type, int in_class, int indx ATTRIBUTE_UNUSED, int numaux ATTRIBUTE_UNUSED, void * in1) { AUXENT *ext = (AUXENT *) ext1; union internal_auxent *in = (union internal_auxent *) in1; /* PR 17521: Make sure that all fields in the aux structure are initialised. */ memset (in, 0, sizeof * in); switch (in_class) { case C_FILE: if (ext->x_file.x_fname[0] == 0) { in->x_file.x_n.x_zeroes = 0; in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset); } else memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN); return; case C_STAT: case C_LEAFSTAT: case C_HIDDEN: if (type == T_NULL) { in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext); in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext); in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext); in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum); in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated); in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat); return; } break; } in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx); in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx); if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type) || ISTAG (in_class)) { in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext); in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext); } else { in->x_sym.x_fcnary.x_ary.x_dimen[0] = H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]); in->x_sym.x_fcnary.x_ary.x_dimen[1] = H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]); in->x_sym.x_fcnary.x_ary.x_dimen[2] = H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]); in->x_sym.x_fcnary.x_ary.x_dimen[3] = H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]); } if (ISFCN (type)) { in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize); } else { in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext); in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext); } } unsigned int _bfd_XXi_swap_aux_out (bfd * abfd, void * inp, int type, int in_class, int indx ATTRIBUTE_UNUSED, int numaux ATTRIBUTE_UNUSED, void * extp) { union internal_auxent *in = (union internal_auxent *) inp; AUXENT *ext = (AUXENT *) extp; memset (ext, 0, AUXESZ); switch (in_class) { case C_FILE: if (in->x_file.x_fname[0] == 0) { H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes); H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset); } else memcpy (ext->x_file.x_fname, in->x_file.x_fname, sizeof (ext->x_file.x_fname)); return AUXESZ; case C_STAT: case C_LEAFSTAT: case C_HIDDEN: if (type == T_NULL) { PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext); PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext); PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext); H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum); H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated); H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat); return AUXESZ; } break; } H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx); H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx); if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type) || ISTAG (in_class)) { PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr, ext); PUT_FCN_ENDNDX (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext); } else { H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0], ext->x_sym.x_fcnary.x_ary.x_dimen[0]); H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1], ext->x_sym.x_fcnary.x_ary.x_dimen[1]); H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2], ext->x_sym.x_fcnary.x_ary.x_dimen[2]); H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3], ext->x_sym.x_fcnary.x_ary.x_dimen[3]); } if (ISFCN (type)) H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize); else { PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext); PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext); } return AUXESZ; } void _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1) { LINENO *ext = (LINENO *) ext1; struct internal_lineno *in = (struct internal_lineno *) in1; in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx); in->l_lnno = GET_LINENO_LNNO (abfd, ext); } unsigned int _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp) { struct internal_lineno *in = (struct internal_lineno *) inp; struct external_lineno *ext = (struct external_lineno *) outp; H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx); PUT_LINENO_LNNO (abfd, in->l_lnno, ext); return LINESZ; } void _bfd_XXi_swap_aouthdr_in (bfd * abfd, void * aouthdr_ext1, void * aouthdr_int1) { PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1; AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1; struct internal_aouthdr *aouthdr_int = (struct internal_aouthdr *) aouthdr_int1; struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe; aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic); aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp); aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize); aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize); aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize); aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry); aouthdr_int->text_start = GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start); #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) /* PE32+ does not have data_start member! */ aouthdr_int->data_start = GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start); a->BaseOfData = aouthdr_int->data_start; #endif a->Magic = aouthdr_int->magic; a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp); a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1); a->SizeOfCode = aouthdr_int->tsize ; a->SizeOfInitializedData = aouthdr_int->dsize ; a->SizeOfUninitializedData = aouthdr_int->bsize ; a->AddressOfEntryPoint = aouthdr_int->entry; a->BaseOfCode = aouthdr_int->text_start; a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase); a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment); a->FileAlignment = H_GET_32 (abfd, src->FileAlignment); a->MajorOperatingSystemVersion = H_GET_16 (abfd, src->MajorOperatingSystemVersion); a->MinorOperatingSystemVersion = H_GET_16 (abfd, src->MinorOperatingSystemVersion); a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion); a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion); a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion); a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion); a->Reserved1 = H_GET_32 (abfd, src->Reserved1); a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage); a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders); a->CheckSum = H_GET_32 (abfd, src->CheckSum); a->Subsystem = H_GET_16 (abfd, src->Subsystem); a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics); a->SizeOfStackReserve = GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve); a->SizeOfStackCommit = GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit); a->SizeOfHeapReserve = GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve); a->SizeOfHeapCommit = GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit); a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags); a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes); { unsigned idx; /* PR 17512: Corrupt PE binaries can cause seg-faults. */ if (a->NumberOfRvaAndSizes > IMAGE_NUMBEROF_DIRECTORY_ENTRIES) { /* xgettext:c-format */ _bfd_error_handler (_("%pB: aout header specifies an invalid number of" " data-directory entries: %u"), abfd, a->NumberOfRvaAndSizes); bfd_set_error (bfd_error_bad_value); /* Paranoia: If the number is corrupt, then assume that the actual entries themselves might be corrupt as well. */ a->NumberOfRvaAndSizes = 0; } for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++) { /* If data directory is empty, rva also should be 0. */ int size = H_GET_32 (abfd, src->DataDirectory[idx][1]); a->DataDirectory[idx].Size = size; if (size) a->DataDirectory[idx].VirtualAddress = H_GET_32 (abfd, src->DataDirectory[idx][0]); else a->DataDirectory[idx].VirtualAddress = 0; } while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES) { a->DataDirectory[idx].Size = 0; a->DataDirectory[idx].VirtualAddress = 0; idx ++; } } if (aouthdr_int->entry) { aouthdr_int->entry += a->ImageBase; #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) aouthdr_int->entry &= 0xffffffff; #endif } if (aouthdr_int->tsize) { aouthdr_int->text_start += a->ImageBase; #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) aouthdr_int->text_start &= 0xffffffff; #endif } #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) /* PE32+ does not have data_start member! */ if (aouthdr_int->dsize) { aouthdr_int->data_start += a->ImageBase; aouthdr_int->data_start &= 0xffffffff; } #endif } /* A support function for below. */ static void add_data_entry (bfd * abfd, struct internal_extra_pe_aouthdr *aout, int idx, char *name, bfd_vma base) { asection *sec = bfd_get_section_by_name (abfd, name); /* Add import directory information if it exists. */ if ((sec != NULL) && (coff_section_data (abfd, sec) != NULL) && (pei_section_data (abfd, sec) != NULL)) { /* If data directory is empty, rva also should be 0. */ int size = pei_section_data (abfd, sec)->virt_size; aout->DataDirectory[idx].Size = size; if (size) { aout->DataDirectory[idx].VirtualAddress = (sec->vma - base) & 0xffffffff; sec->flags |= SEC_DATA; } } } unsigned int _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out) { struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in; pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr; PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out; bfd_vma sa, fa, ib; IMAGE_DATA_DIRECTORY idata2, idata5, tls; sa = extra->SectionAlignment; fa = extra->FileAlignment; ib = extra->ImageBase; idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE]; idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE]; tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE]; if (aouthdr_in->tsize) { aouthdr_in->text_start -= ib; #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) aouthdr_in->text_start &= 0xffffffff; #endif } if (aouthdr_in->dsize) { aouthdr_in->data_start -= ib; #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) aouthdr_in->data_start &= 0xffffffff; #endif } if (aouthdr_in->entry) { aouthdr_in->entry -= ib; #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) aouthdr_in->entry &= 0xffffffff; #endif } #define FA(x) (((x) + fa -1 ) & (- fa)) #define SA(x) (((x) + sa -1 ) & (- sa)) /* We like to have the sizes aligned. */ aouthdr_in->bsize = FA (aouthdr_in->bsize); extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; add_data_entry (abfd, extra, PE_EXPORT_TABLE, ".edata", ib); add_data_entry (abfd, extra, PE_RESOURCE_TABLE, ".rsrc", ib); add_data_entry (abfd, extra, PE_EXCEPTION_TABLE, ".pdata", ib); /* In theory we do not need to call add_data_entry for .idata$2 or .idata$5. It will be done in bfd_coff_final_link where all the required information is available. If however, we are not going to perform a final link, eg because we have been invoked by objcopy or strip, then we need to make sure that these Data Directory entries are initialised properly. So - we copy the input values into the output values, and then, if a final link is going to be performed, it can overwrite them. */ extra->DataDirectory[PE_IMPORT_TABLE] = idata2; extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5; extra->DataDirectory[PE_TLS_TABLE] = tls; if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0) /* Until other .idata fixes are made (pending patch), the entry for .idata is needed for backwards compatibility. FIXME. */ add_data_entry (abfd, extra, PE_IMPORT_TABLE, ".idata", ib); /* For some reason, the virtual size (which is what's set by add_data_entry) for .reloc is not the same as the size recorded in this slot by MSVC; it doesn't seem to cause problems (so far), but since it's the best we've got, use it. It does do the right thing for .pdata. */ if (pe->has_reloc_section) add_data_entry (abfd, extra, PE_BASE_RELOCATION_TABLE, ".reloc", ib); { asection *sec; bfd_vma hsize = 0; bfd_vma dsize = 0; bfd_vma isize = 0; bfd_vma tsize = 0; for (sec = abfd->sections; sec; sec = sec->next) { int rounded = FA (sec->size); if (rounded == 0) continue; /* The first non-zero section filepos is the header size. Sections without contents will have a filepos of 0. */ if (hsize == 0) hsize = sec->filepos; if (sec->flags & SEC_DATA) dsize += rounded; if (sec->flags & SEC_CODE) tsize += rounded; /* The image size is the total VIRTUAL size (which is what is in the virt_size field). Files have been seen (from MSVC 5.0 link.exe) where the file size of the .data segment is quite small compared to the virtual size. Without this fix, strip munges the file. FIXME: We need to handle holes between sections, which may happpen when we covert from another format. We just use the virtual address and virtual size of the last section for the image size. */ if (coff_section_data (abfd, sec) != NULL && pei_section_data (abfd, sec) != NULL) isize = (sec->vma - extra->ImageBase + SA (FA (pei_section_data (abfd, sec)->virt_size))); } aouthdr_in->dsize = dsize; aouthdr_in->tsize = tsize; extra->SizeOfHeaders = hsize; extra->SizeOfImage = isize; } H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic); /* e.g. 219510000 is linker version 2.19 */ #define LINKER_VERSION ((short) (BFD_VERSION / 1000000)) /* This piece of magic sets the "linker version" field to LINKER_VERSION. */ H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256), aouthdr_out->standard.vstamp); PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize); PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize); PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize); PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry); PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start, aouthdr_out->standard.text_start); #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) /* PE32+ does not have data_start member! */ PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start, aouthdr_out->standard.data_start); #endif PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase); H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment); H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment); H_PUT_16 (abfd, extra->MajorOperatingSystemVersion, aouthdr_out->MajorOperatingSystemVersion); H_PUT_16 (abfd, extra->MinorOperatingSystemVersion, aouthdr_out->MinorOperatingSystemVersion); H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion); H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion); H_PUT_16 (abfd, extra->MajorSubsystemVersion, aouthdr_out->MajorSubsystemVersion); H_PUT_16 (abfd, extra->MinorSubsystemVersion, aouthdr_out->MinorSubsystemVersion); H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1); H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage); H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders); H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum); H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem); H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics); PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve, aouthdr_out->SizeOfStackReserve); PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit, aouthdr_out->SizeOfStackCommit); PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve, aouthdr_out->SizeOfHeapReserve); PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit, aouthdr_out->SizeOfHeapCommit); H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags); H_PUT_32 (abfd, extra->NumberOfRvaAndSizes, aouthdr_out->NumberOfRvaAndSizes); { int idx; for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++) { H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress, aouthdr_out->DataDirectory[idx][0]); H_PUT_32 (abfd, extra->DataDirectory[idx].Size, aouthdr_out->DataDirectory[idx][1]); } } return AOUTSZ; } unsigned int _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out) { int idx; struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in; struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out; if (pe_data (abfd)->has_reloc_section || pe_data (abfd)->dont_strip_reloc) filehdr_in->f_flags &= ~F_RELFLG; if (pe_data (abfd)->dll) filehdr_in->f_flags |= F_DLL; filehdr_in->pe.e_magic = IMAGE_DOS_SIGNATURE; filehdr_in->pe.e_cblp = 0x90; filehdr_in->pe.e_cp = 0x3; filehdr_in->pe.e_crlc = 0x0; filehdr_in->pe.e_cparhdr = 0x4; filehdr_in->pe.e_minalloc = 0x0; filehdr_in->pe.e_maxalloc = 0xffff; filehdr_in->pe.e_ss = 0x0; filehdr_in->pe.e_sp = 0xb8; filehdr_in->pe.e_csum = 0x0; filehdr_in->pe.e_ip = 0x0; filehdr_in->pe.e_cs = 0x0; filehdr_in->pe.e_lfarlc = 0x40; filehdr_in->pe.e_ovno = 0x0; for (idx = 0; idx < 4; idx++) filehdr_in->pe.e_res[idx] = 0x0; filehdr_in->pe.e_oemid = 0x0; filehdr_in->pe.e_oeminfo = 0x0; for (idx = 0; idx < 10; idx++) filehdr_in->pe.e_res2[idx] = 0x0; filehdr_in->pe.e_lfanew = 0x80; /* This next collection of data are mostly just characters. It appears to be constant within the headers put on NT exes. */ memcpy (filehdr_in->pe.dos_message, pe_data (abfd)->dos_message, sizeof (filehdr_in->pe.dos_message)); filehdr_in->pe.nt_signature = IMAGE_NT_SIGNATURE; H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic); H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns); /* Use a real timestamp by default, unless the no-insert-timestamp option was chosen. */ if ((pe_data (abfd)->timestamp) == -1) H_PUT_32 (abfd, time (0), filehdr_out->f_timdat); else H_PUT_32 (abfd, pe_data (abfd)->timestamp, filehdr_out->f_timdat); PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr); H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms); H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr); H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags); /* Put in extra dos header stuff. This data remains essentially constant, it just has to be tacked on to the beginning of all exes for NT. */ H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic); H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp); H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp); H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc); H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr); H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc); H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc); H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss); H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp); H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum); H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip); H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs); H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc); H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno); for (idx = 0; idx < 4; idx++) H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]); H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid); H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo); for (idx = 0; idx < 10; idx++) H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]); H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew); for (idx = 0; idx < 16; idx++) H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx], filehdr_out->dos_message[idx]); /* Also put in the NT signature. */ H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature); return FILHSZ; } unsigned int _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out) { struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in; FILHDR *filehdr_out = (FILHDR *) out; H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic); H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns); H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat); PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr); H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms); H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr); H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags); return FILHSZ; } unsigned int _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out) { struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in; SCNHDR *scnhdr_ext = (SCNHDR *) out; unsigned int ret = SCNHSZ; bfd_vma ps; bfd_vma ss; memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name)); ss = scnhdr_int->s_vaddr - pe_data (abfd)->pe_opthdr.ImageBase; if (scnhdr_int->s_vaddr < pe_data (abfd)->pe_opthdr.ImageBase) _bfd_error_handler (_("%pB:%.8s: section below image base"), abfd, scnhdr_int->s_name); else if(ss != (ss & 0xffffffff)) _bfd_error_handler (_("%pB:%.8s: RVA truncated"), abfd, scnhdr_int->s_name); PUT_SCNHDR_VADDR (abfd, ss & 0xffffffff, scnhdr_ext->s_vaddr); /* NT wants the size data to be rounded up to the next NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss, sometimes). */ if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0) { if (bfd_pei_p (abfd)) { ps = scnhdr_int->s_size; ss = 0; } else { ps = 0; ss = scnhdr_int->s_size; } } else { if (bfd_pei_p (abfd)) ps = scnhdr_int->s_paddr; else ps = 0; ss = scnhdr_int->s_size; } PUT_SCNHDR_SIZE (abfd, ss, scnhdr_ext->s_size); /* s_paddr in PE is really the virtual size. */ PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr); PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr, scnhdr_ext->s_scnptr); PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr, scnhdr_ext->s_relptr); PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr, scnhdr_ext->s_lnnoptr); { /* Extra flags must be set when dealing with PE. All sections should also have the IMAGE_SCN_MEM_READ (0x40000000) flag set. In addition, the .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set (this is especially important when dealing with the .idata section since the addresses for routines from .dlls must be overwritten). If .reloc section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE (0x02000000). Also, the resource data should also be read and writable. */ /* FIXME: Alignment is also encoded in this field, at least on ARM-WINCE. Although - how do we get the original alignment field back ? */ typedef struct { char section_name[SCNNMLEN]; unsigned long must_have; } pe_required_section_flags; pe_required_section_flags known_sections [] = { { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES }, { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE }, { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE }, { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA }, { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE }, { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA }, { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA }, { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE }, { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE }, { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE }, { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE }, { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA }, }; pe_required_section_flags * p; /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now we know exactly what this specific section wants so we remove it and then allow the must_have field to add it back in if necessary. However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the default WP_TEXT file flag has been cleared. WP_TEXT may be cleared by ld --enable-auto-import (if auto-import is actually needed), by ld --omagic, or by obcopy --writable-text. */ for (p = known_sections; p < known_sections + ARRAY_SIZE (known_sections); p++) if (memcmp (scnhdr_int->s_name, p->section_name, SCNNMLEN) == 0) { if (memcmp (scnhdr_int->s_name, ".text", sizeof ".text") || (bfd_get_file_flags (abfd) & WP_TEXT)) scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE; scnhdr_int->s_flags |= p->must_have; break; } H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags); } if (coff_data (abfd)->link_info && ! bfd_link_relocatable (coff_data (abfd)->link_info) && ! bfd_link_pic (coff_data (abfd)->link_info) && memcmp (scnhdr_int->s_name, ".text", sizeof ".text") == 0) { /* By inference from looking at MS output, the 32 bit field which is the combination of the number_of_relocs and number_of_linenos is used for the line number count in executables. A 16-bit field won't do for cc1. The MS document says that the number of relocs is zero for executables, but the 17-th bit has been observed to be there. Overflow is not an issue: a 4G-line program will overflow a bunch of other fields long before this! */ H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno); H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc); } else { if (scnhdr_int->s_nlnno <= 0xffff) H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno); else { /* xgettext:c-format */ _bfd_error_handler (_("%pB: line number overflow: 0x%lx > 0xffff"), abfd, scnhdr_int->s_nlnno); bfd_set_error (bfd_error_file_truncated); H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno); ret = 0; } /* Although we could encode 0xffff relocs here, we do not, to be consistent with other parts of bfd. Also it lets us warn, as we should never see 0xffff here w/o having the overflow flag set. */ if (scnhdr_int->s_nreloc < 0xffff) H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc); else { /* PE can deal with large #s of relocs, but not here. */ H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc); scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL; H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags); } } return ret; } void _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1) { struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1; struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1; in->Characteristics = H_GET_32(abfd, ext->Characteristics); in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp); in->MajorVersion = H_GET_16(abfd, ext->MajorVersion); in->MinorVersion = H_GET_16(abfd, ext->MinorVersion); in->Type = H_GET_32(abfd, ext->Type); in->SizeOfData = H_GET_32(abfd, ext->SizeOfData); in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData); in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData); } unsigned int _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp) { struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp; struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp; H_PUT_32(abfd, in->Characteristics, ext->Characteristics); H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp); H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion); H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion); H_PUT_32(abfd, in->Type, ext->Type); H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData); H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData); H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData); return sizeof (struct external_IMAGE_DEBUG_DIRECTORY); } CODEVIEW_INFO * _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo) { char buffer[256+1]; bfd_size_type nread; if (bfd_seek (abfd, where, SEEK_SET) != 0) return NULL; if (length <= sizeof (CV_INFO_PDB70) && length <= sizeof (CV_INFO_PDB20)) return NULL; if (length > 256) length = 256; nread = bfd_bread (buffer, length, abfd); if (length != nread) return NULL; /* Ensure null termination of filename. */ memset (buffer + nread, 0, sizeof (buffer) - nread); cvinfo->CVSignature = H_GET_32 (abfd, buffer); cvinfo->Age = 0; if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE) && (length > sizeof (CV_INFO_PDB70))) { CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer); cvinfo->Age = H_GET_32(abfd, cvinfo70->Age); /* A GUID consists of 4,2,2 byte values in little-endian order, followed by 8 single bytes. Byte swap them so we can conveniently treat the GUID as 16 bytes in big-endian order. */ bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature); bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4])); bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6])); memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8); cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH; /* cvinfo->PdbFileName = cvinfo70->PdbFileName; */ return cvinfo; } else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE) && (length > sizeof (CV_INFO_PDB20))) { CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer); cvinfo->Age = H_GET_32(abfd, cvinfo20->Age); memcpy (cvinfo->Signature, cvinfo20->Signature, 4); cvinfo->SignatureLength = 4; /* cvinfo->PdbFileName = cvinfo20->PdbFileName; */ return cvinfo; } return NULL; } unsigned int _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo) { const bfd_size_type size = sizeof (CV_INFO_PDB70) + 1; bfd_size_type written; CV_INFO_PDB70 *cvinfo70; char * buffer; if (bfd_seek (abfd, where, SEEK_SET) != 0) return 0; buffer = bfd_malloc (size); if (buffer == NULL) return 0; cvinfo70 = (CV_INFO_PDB70 *) buffer; H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature); /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values in little-endian order, followed by 8 single bytes. */ bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature); bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4])); bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6])); memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8); H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age); cvinfo70->PdbFileName[0] = '\0'; written = bfd_bwrite (buffer, size, abfd); free (buffer); return written == size ? size : 0; } static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] = { N_("Export Directory [.edata (or where ever we found it)]"), N_("Import Directory [parts of .idata]"), N_("Resource Directory [.rsrc]"), N_("Exception Directory [.pdata]"), N_("Security Directory"), N_("Base Relocation Directory [.reloc]"), N_("Debug Directory"), N_("Description Directory"), N_("Special Directory"), N_("Thread Storage Directory [.tls]"), N_("Load Configuration Directory"), N_("Bound Import Directory"), N_("Import Address Table Directory"), N_("Delay Import Directory"), N_("CLR Runtime Header"), N_("Reserved") }; static bool pe_print_idata (bfd * abfd, void * vfile) { FILE *file = (FILE *) vfile; bfd_byte *data; asection *section; bfd_signed_vma adj; bfd_size_type datasize = 0; bfd_size_type dataoff; bfd_size_type i; int onaline = 20; pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr; bfd_vma addr; addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress; if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0) { /* Maybe the extra header isn't there. Look for the section. */ section = bfd_get_section_by_name (abfd, ".idata"); if (section == NULL) return true; addr = section->vma; datasize = section->size; if (datasize == 0) return true; } else { addr += extra->ImageBase; for (section = abfd->sections; section != NULL; section = section->next) { datasize = section->size; if (addr >= section->vma && addr < section->vma + datasize) break; } if (section == NULL) { fprintf (file, _("\nThere is an import table, but the section containing it could not be found\n")); return true; } else if (!(section->flags & SEC_HAS_CONTENTS)) { fprintf (file, _("\nThere is an import table in %s, but that section has no contents\n"), section->name); return true; } } /* xgettext:c-format */ fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"), section->name, (unsigned long) addr); dataoff = addr - section->vma; fprintf (file, _("\nThe Import Tables (interpreted %s section contents)\n"), section->name); fprintf (file, _("\ vma: Hint Time Forward DLL First\n\ Table Stamp Chain Name Thunk\n")); /* Read the whole section. Some of the fields might be before dataoff. */ if (!bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } adj = section->vma - extra->ImageBase; /* Print all image import descriptors. */ for (i = dataoff; i + onaline <= datasize; i += onaline) { bfd_vma hint_addr; bfd_vma time_stamp; bfd_vma forward_chain; bfd_vma dll_name; bfd_vma first_thunk; int idx = 0; bfd_size_type j; char *dll; /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */ fprintf (file, " %08lx\t", (unsigned long) (i + adj)); hint_addr = bfd_get_32 (abfd, data + i); time_stamp = bfd_get_32 (abfd, data + i + 4); forward_chain = bfd_get_32 (abfd, data + i + 8); dll_name = bfd_get_32 (abfd, data + i + 12); first_thunk = bfd_get_32 (abfd, data + i + 16); fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n", (unsigned long) hint_addr, (unsigned long) time_stamp, (unsigned long) forward_chain, (unsigned long) dll_name, (unsigned long) first_thunk); if (hint_addr == 0 && first_thunk == 0) break; if (dll_name - adj >= section->size) break; dll = (char *) data + dll_name - adj; /* PR 17512 file: 078-12277-0.004. */ bfd_size_type maxlen = (char *)(data + datasize) - dll - 1; fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll); /* PR 21546: When the Hint Address is zero, we try the First Thunk instead. */ if (hint_addr == 0) hint_addr = first_thunk; if (hint_addr != 0 && hint_addr - adj < datasize) { bfd_byte *ft_data; asection *ft_section; bfd_vma ft_addr; bfd_size_type ft_datasize; int ft_idx; int ft_allocated; fprintf (file, _("\tvma: Hint/Ord Member-Name Bound-To\n")); idx = hint_addr - adj; ft_addr = first_thunk + extra->ImageBase; ft_idx = first_thunk - adj; ft_data = data + ft_idx; ft_datasize = datasize - ft_idx; ft_allocated = 0; if (first_thunk != hint_addr) { /* Find the section which contains the first thunk. */ for (ft_section = abfd->sections; ft_section != NULL; ft_section = ft_section->next) { if (ft_addr >= ft_section->vma && ft_addr < ft_section->vma + ft_section->size) break; } if (ft_section == NULL) { fprintf (file, _("\nThere is a first thunk, but the section containing it could not be found\n")); continue; } /* Now check to see if this section is the same as our current section. If it is not then we will have to load its data in. */ if (ft_section != section) { ft_idx = first_thunk - (ft_section->vma - extra->ImageBase); ft_datasize = ft_section->size - ft_idx; ft_data = (bfd_byte *) bfd_malloc (ft_datasize); if (ft_data == NULL) continue; /* Read ft_datasize bytes starting at offset ft_idx. */ if (!bfd_get_section_contents (abfd, ft_section, ft_data, (bfd_vma) ft_idx, ft_datasize)) { free (ft_data); continue; } ft_allocated = 1; } } /* Print HintName vector entries. */ #ifdef COFF_WITH_pex64 for (j = 0; idx + j + 8 <= datasize; j += 8) { bfd_size_type amt; unsigned long member = bfd_get_32 (abfd, data + idx + j); unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4); if (!member && !member_high) break; amt = member - adj; if (HighBitSet (member_high)) fprintf (file, "\t%lx%08lx\t %4lx%08lx <none>", member_high, member, WithoutHighBit (member_high), member); /* PR binutils/17512: Handle corrupt PE data. */ else if (amt >= datasize || amt + 2 >= datasize) fprintf (file, _("\t<corrupt: 0x%04lx>"), member); else { int ordinal; char *member_name; ordinal = bfd_get_16 (abfd, data + amt); member_name = (char *) data + amt + 2; fprintf (file, "\t%04lx\t %4d %.*s",member, ordinal, (int) (datasize - (amt + 2)), member_name); } /* If the time stamp is not zero, the import address table holds actual addresses. */ if (time_stamp != 0 && first_thunk != 0 && first_thunk != hint_addr && j + 4 <= ft_datasize) fprintf (file, "\t%04lx", (unsigned long) bfd_get_32 (abfd, ft_data + j)); fprintf (file, "\n"); } #else for (j = 0; idx + j + 4 <= datasize; j += 4) { bfd_size_type amt; unsigned long member = bfd_get_32 (abfd, data + idx + j); /* Print single IMAGE_IMPORT_BY_NAME vector. */ if (member == 0) break; amt = member - adj; if (HighBitSet (member)) fprintf (file, "\t%04lx\t %4lu <none>", member, WithoutHighBit (member)); /* PR binutils/17512: Handle corrupt PE data. */ else if (amt >= datasize || amt + 2 >= datasize) fprintf (file, _("\t<corrupt: 0x%04lx>"), member); else { int ordinal; char *member_name; ordinal = bfd_get_16 (abfd, data + amt); member_name = (char *) data + amt + 2; fprintf (file, "\t%04lx\t %4d %.*s", member, ordinal, (int) (datasize - (amt + 2)), member_name); } /* If the time stamp is not zero, the import address table holds actual addresses. */ if (time_stamp != 0 && first_thunk != 0 && first_thunk != hint_addr && j + 4 <= ft_datasize) fprintf (file, "\t%04lx", (unsigned long) bfd_get_32 (abfd, ft_data + j)); fprintf (file, "\n"); } #endif if (ft_allocated) free (ft_data); } fprintf (file, "\n"); } free (data); return true; } static bool pe_print_edata (bfd * abfd, void * vfile) { FILE *file = (FILE *) vfile; bfd_byte *data; asection *section; bfd_size_type datasize = 0; bfd_size_type dataoff; bfd_size_type i; bfd_vma adj; struct EDT_type { long export_flags; /* Reserved - should be zero. */ long time_stamp; short major_ver; short minor_ver; bfd_vma name; /* RVA - relative to image base. */ long base; /* Ordinal base. */ unsigned long num_functions;/* Number in the export address table. */ unsigned long num_names; /* Number in the name pointer table. */ bfd_vma eat_addr; /* RVA to the export address table. */ bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */ bfd_vma ot_addr; /* RVA to the Ordinal Table. */ } edt; pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr; bfd_vma addr; addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress; if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0) { /* Maybe the extra header isn't there. Look for the section. */ section = bfd_get_section_by_name (abfd, ".edata"); if (section == NULL) return true; addr = section->vma; dataoff = 0; datasize = section->size; if (datasize == 0) return true; } else { addr += extra->ImageBase; for (section = abfd->sections; section != NULL; section = section->next) if (addr >= section->vma && addr < section->vma + section->size) break; if (section == NULL) { fprintf (file, _("\nThere is an export table, but the section containing it could not be found\n")); return true; } else if (!(section->flags & SEC_HAS_CONTENTS)) { fprintf (file, _("\nThere is an export table in %s, but that section has no contents\n"), section->name); return true; } dataoff = addr - section->vma; datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size; if (dataoff > section->size || datasize > section->size - dataoff) { fprintf (file, _("\nThere is an export table in %s, but it does not fit into that section\n"), section->name); return true; } } /* PR 17512: Handle corrupt PE binaries. */ if (datasize < 40) { fprintf (file, /* xgettext:c-format */ _("\nThere is an export table in %s, but it is too small (%d)\n"), section->name, (int) datasize); return true; } /* xgettext:c-format */ fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"), section->name, (unsigned long) addr); data = (bfd_byte *) bfd_malloc (datasize); if (data == NULL) return false; if (! bfd_get_section_contents (abfd, section, data, (file_ptr) dataoff, datasize)) return false; /* Go get Export Directory Table. */ edt.export_flags = bfd_get_32 (abfd, data + 0); edt.time_stamp = bfd_get_32 (abfd, data + 4); edt.major_ver = bfd_get_16 (abfd, data + 8); edt.minor_ver = bfd_get_16 (abfd, data + 10); edt.name = bfd_get_32 (abfd, data + 12); edt.base = bfd_get_32 (abfd, data + 16); edt.num_functions = bfd_get_32 (abfd, data + 20); edt.num_names = bfd_get_32 (abfd, data + 24); edt.eat_addr = bfd_get_32 (abfd, data + 28); edt.npt_addr = bfd_get_32 (abfd, data + 32); edt.ot_addr = bfd_get_32 (abfd, data + 36); adj = section->vma - extra->ImageBase + dataoff; /* Dump the EDT first. */ fprintf (file, _("\nThe Export Tables (interpreted %s section contents)\n\n"), section->name); fprintf (file, _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags); fprintf (file, _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp); fprintf (file, /* xgettext:c-format */ _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver); fprintf (file, _("Name \t\t\t\t")); bfd_fprintf_vma (abfd, file, edt.name); if ((edt.name >= adj) && (edt.name < adj + datasize)) fprintf (file, " %.*s\n", (int) (datasize - (edt.name - adj)), data + edt.name - adj); else fprintf (file, "(outside .edata section)\n"); fprintf (file, _("Ordinal Base \t\t\t%ld\n"), edt.base); fprintf (file, _("Number in:\n")); fprintf (file, _("\tExport Address Table \t\t%08lx\n"), edt.num_functions); fprintf (file, _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names); fprintf (file, _("Table Addresses\n")); fprintf (file, _("\tExport Address Table \t\t")); bfd_fprintf_vma (abfd, file, edt.eat_addr); fprintf (file, "\n"); fprintf (file, _("\tName Pointer Table \t\t")); bfd_fprintf_vma (abfd, file, edt.npt_addr); fprintf (file, "\n"); fprintf (file, _("\tOrdinal Table \t\t\t")); bfd_fprintf_vma (abfd, file, edt.ot_addr); fprintf (file, "\n"); /* The next table to find is the Export Address Table. It's basically a list of pointers that either locate a function in this dll, or forward the call to another dll. Something like: typedef union { long export_rva; long forwarder_rva; } export_address_table_entry; */ fprintf (file, _("\nExport Address Table -- Ordinal Base %ld\n"), edt.base); /* PR 17512: Handle corrupt PE binaries. */ /* PR 17512 file: 140-165018-0.004. */ if (edt.eat_addr - adj >= datasize /* PR 17512: file: 092b1829 */ || (edt.num_functions + 1) * 4 < edt.num_functions || edt.eat_addr - adj + (edt.num_functions + 1) * 4 > datasize) fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"), (long) edt.eat_addr, (long) edt.num_functions); else for (i = 0; i < edt.num_functions; ++i) { bfd_vma eat_member = bfd_get_32 (abfd, data + edt.eat_addr + (i * 4) - adj); if (eat_member == 0) continue; if (eat_member - adj <= datasize) { /* This rva is to a name (forwarding function) in our section. */ /* Should locate a function descriptor. */ fprintf (file, "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n", (long) i, (long) (i + edt.base), (unsigned long) eat_member, _("Forwarder RVA"), (int)(datasize - (eat_member - adj)), data + eat_member - adj); } else { /* Should locate a function descriptor in the reldata section. */ fprintf (file, "\t[%4ld] +base[%4ld] %04lx %s\n", (long) i, (long) (i + edt.base), (unsigned long) eat_member, _("Export RVA")); } } /* The Export Name Pointer Table is paired with the Export Ordinal Table. */ /* Dump them in parallel for clarity. */ fprintf (file, _("\n[Ordinal/Name Pointer] Table\n")); /* PR 17512: Handle corrupt PE binaries. */ if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize /* PR 17512: file: bb68816e. */ || edt.num_names * 4 < edt.num_names || (data + edt.npt_addr - adj) < data) /* xgettext:c-format */ fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"), (long) edt.npt_addr, (long) edt.num_names); /* PR 17512: file: 140-147171-0.004. */ else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize || data + edt.ot_addr - adj < data) /* xgettext:c-format */ fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"), (long) edt.ot_addr, (long) edt.num_names); else for (i = 0; i < edt.num_names; ++i) { bfd_vma name_ptr; bfd_vma ord; ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj); name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj); if ((name_ptr - adj) >= datasize) { /* xgettext:c-format */ fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"), (long) ord, (long) name_ptr); } else { char * name = (char *) data + name_ptr - adj; fprintf (file, "\t[%4ld] %.*s\n", (long) ord, (int)((char *)(data + datasize) - name), name); } } free (data); return true; } /* This really is architecture dependent. On IA-64, a .pdata entry consists of three dwords containing relative virtual addresses that specify the start and end address of the code range the entry covers and the address of the corresponding unwind info data. On ARM and SH-4, a compressed PDATA structure is used : _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY. See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx . This is the version for uncompressed data. */ static bool pe_print_pdata (bfd * abfd, void * vfile) { #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) # define PDATA_ROW_SIZE (3 * 8) #else # define PDATA_ROW_SIZE (5 * 4) #endif FILE *file = (FILE *) vfile; bfd_byte *data = 0; asection *section = bfd_get_section_by_name (abfd, ".pdata"); bfd_size_type datasize = 0; bfd_size_type i; bfd_size_type start, stop; int onaline = PDATA_ROW_SIZE; if (section == NULL || coff_section_data (abfd, section) == NULL || pei_section_data (abfd, section) == NULL) return true; stop = pei_section_data (abfd, section)->virt_size; if ((stop % onaline) != 0) fprintf (file, /* xgettext:c-format */ _("warning, .pdata section size (%ld) is not a multiple of %d\n"), (long) stop, onaline); fprintf (file, _("\nThe Function Table (interpreted .pdata section contents)\n")); #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) fprintf (file, _(" vma:\t\t\tBegin Address End Address Unwind Info\n")); #else fprintf (file, _("\ vma:\t\tBegin End EH EH PrologEnd Exception\n\ \t\tAddress Address Handler Data Address Mask\n")); #endif datasize = section->size; if (datasize == 0) return true; /* PR 17512: file: 002-193900-0.004. */ if (datasize < stop) { /* xgettext:c-format */ fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"), (long) stop, (long) datasize); return false; } if (! bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } start = 0; for (i = start; i < stop; i += onaline) { bfd_vma begin_addr; bfd_vma end_addr; bfd_vma eh_handler; bfd_vma eh_data; bfd_vma prolog_end_addr; #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) int em_data; #endif if (i + PDATA_ROW_SIZE > stop) break; begin_addr = GET_PDATA_ENTRY (abfd, data + i ); end_addr = GET_PDATA_ENTRY (abfd, data + i + 4); eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8); eh_data = GET_PDATA_ENTRY (abfd, data + i + 12); prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16); if (begin_addr == 0 && end_addr == 0 && eh_handler == 0 && eh_data == 0 && prolog_end_addr == 0) /* We are probably into the padding of the section now. */ break; #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3); #endif eh_handler &= ~(bfd_vma) 0x3; prolog_end_addr &= ~(bfd_vma) 0x3; fputc (' ', file); bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file); bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file); bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file); bfd_fprintf_vma (abfd, file, eh_handler); #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64) fputc (' ', file); bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file); bfd_fprintf_vma (abfd, file, prolog_end_addr); fprintf (file, " %x", em_data); #endif fprintf (file, "\n"); } free (data); return true; #undef PDATA_ROW_SIZE } typedef struct sym_cache { int symcount; asymbol ** syms; } sym_cache; static asymbol ** slurp_symtab (bfd *abfd, sym_cache *psc) { asymbol ** sy = NULL; long storage; if (!(bfd_get_file_flags (abfd) & HAS_SYMS)) { psc->symcount = 0; return NULL; } storage = bfd_get_symtab_upper_bound (abfd); if (storage < 0) return NULL; if (storage) { sy = (asymbol **) bfd_malloc (storage); if (sy == NULL) return NULL; } psc->symcount = bfd_canonicalize_symtab (abfd, sy); if (psc->symcount < 0) return NULL; return sy; } static const char * my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc) { int i; if (psc->syms == 0) psc->syms = slurp_symtab (abfd, psc); for (i = 0; i < psc->symcount; i++) { if (psc->syms[i]->section->vma + psc->syms[i]->value == func) return psc->syms[i]->name; } return NULL; } static void cleanup_syms (sym_cache *psc) { psc->symcount = 0; free (psc->syms); psc->syms = NULL; } /* This is the version for "compressed" pdata. */ bool _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile) { # define PDATA_ROW_SIZE (2 * 4) FILE *file = (FILE *) vfile; bfd_byte *data = NULL; asection *section = bfd_get_section_by_name (abfd, ".pdata"); bfd_size_type datasize = 0; bfd_size_type i; bfd_size_type start, stop; int onaline = PDATA_ROW_SIZE; struct sym_cache cache = {0, 0} ; if (section == NULL || coff_section_data (abfd, section) == NULL || pei_section_data (abfd, section) == NULL) return true; stop = pei_section_data (abfd, section)->virt_size; if ((stop % onaline) != 0) fprintf (file, /* xgettext:c-format */ _("warning, .pdata section size (%ld) is not a multiple of %d\n"), (long) stop, onaline); fprintf (file, _("\nThe Function Table (interpreted .pdata section contents)\n")); fprintf (file, _("\ vma:\t\tBegin Prolog Function Flags Exception EH\n\ \t\tAddress Length Length 32b exc Handler Data\n")); datasize = section->size; if (datasize == 0) return true; if (! bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } start = 0; for (i = start; i < stop; i += onaline) { bfd_vma begin_addr; bfd_vma other_data; bfd_vma prolog_length, function_length; int flag32bit, exception_flag; asection *tsection; if (i + PDATA_ROW_SIZE > stop) break; begin_addr = GET_PDATA_ENTRY (abfd, data + i ); other_data = GET_PDATA_ENTRY (abfd, data + i + 4); if (begin_addr == 0 && other_data == 0) /* We are probably into the padding of the section now. */ break; prolog_length = (other_data & 0x000000FF); function_length = (other_data & 0x3FFFFF00) >> 8; flag32bit = (int)((other_data & 0x40000000) >> 30); exception_flag = (int)((other_data & 0x80000000) >> 31); fputc (' ', file); bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file); bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file); bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file); bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file); fprintf (file, "%2d %2d ", flag32bit, exception_flag); /* Get the exception handler's address and the data passed from the .text section. This is really the data that belongs with the .pdata but got "compressed" out for the ARM and SH4 architectures. */ tsection = bfd_get_section_by_name (abfd, ".text"); if (tsection && coff_section_data (abfd, tsection) && pei_section_data (abfd, tsection)) { bfd_vma eh_off = (begin_addr - 8) - tsection->vma; bfd_byte *tdata; tdata = (bfd_byte *) bfd_malloc (8); if (tdata) { if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8)) { bfd_vma eh, eh_data; eh = bfd_get_32 (abfd, tdata); eh_data = bfd_get_32 (abfd, tdata + 4); fprintf (file, "%08x ", (unsigned int) eh); fprintf (file, "%08x", (unsigned int) eh_data); if (eh != 0) { const char *s = my_symbol_for_address (abfd, eh, &cache); if (s) fprintf (file, " (%s) ", s); } } free (tdata); } } fprintf (file, "\n"); } free (data); cleanup_syms (& cache); return true; #undef PDATA_ROW_SIZE } #define IMAGE_REL_BASED_HIGHADJ 4 static const char * const tbl[] = { "ABSOLUTE", "HIGH", "LOW", "HIGHLOW", "HIGHADJ", "MIPS_JMPADDR", "SECTION", "REL32", "RESERVED1", "MIPS_JMPADDR16", "DIR64", "HIGH3ADJ", "UNKNOWN", /* MUST be last. */ }; static bool pe_print_reloc (bfd * abfd, void * vfile) { FILE *file = (FILE *) vfile; bfd_byte *data = 0; asection *section = bfd_get_section_by_name (abfd, ".reloc"); bfd_byte *p, *end; if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS)) return true; fprintf (file, _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n")); if (! bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } p = data; end = data + section->size; while (p + 8 <= end) { int j; bfd_vma virtual_address; unsigned long number, size; bfd_byte *chunk_end; /* The .reloc section is a sequence of blocks, with a header consisting of two 32 bit quantities, followed by a number of 16 bit entries. */ virtual_address = bfd_get_32 (abfd, p); size = bfd_get_32 (abfd, p + 4); p += 8; number = (size - 8) / 2; if (size == 0) break; fprintf (file, /* xgettext:c-format */ _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"), (unsigned long) virtual_address, size, size, number); chunk_end = p - 8 + size; if (chunk_end > end) chunk_end = end; j = 0; while (p + 2 <= chunk_end) { unsigned short e = bfd_get_16 (abfd, p); unsigned int t = (e & 0xF000) >> 12; int off = e & 0x0FFF; if (t >= sizeof (tbl) / sizeof (tbl[0])) t = (sizeof (tbl) / sizeof (tbl[0])) - 1; fprintf (file, /* xgettext:c-format */ _("\treloc %4d offset %4x [%4lx] %s"), j, off, (unsigned long) (off + virtual_address), tbl[t]); p += 2; j++; /* HIGHADJ takes an argument, - the next record *is* the low 16 bits of addend. */ if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end) { fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p)); p += 2; j++; } fprintf (file, "\n"); } } free (data); return true; } /* A data structure describing the regions of a .rsrc section. Some fields are filled in as the section is parsed. */ typedef struct rsrc_regions { bfd_byte * section_start; bfd_byte * section_end; bfd_byte * strings_start; bfd_byte * resource_start; } rsrc_regions; static bfd_byte * rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *, rsrc_regions *, bfd_vma); /* Print the resource entry at DATA, with the text indented by INDENT. Recusively calls rsrc_print_resource_directory to print the contents of directory entries. Returns the address of the end of the data associated with the entry or section_end + 1 upon failure. */ static bfd_byte * rsrc_print_resource_entries (FILE *file, bfd *abfd, unsigned int indent, bool is_name, bfd_byte *data, rsrc_regions *regions, bfd_vma rva_bias) { unsigned long entry, addr, size; bfd_byte * leaf; if (data + 8 >= regions->section_end) return regions->section_end + 1; /* xgettext:c-format */ fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " "); entry = (unsigned long) bfd_get_32 (abfd, data); if (is_name) { bfd_byte * name; /* Note - the documentation says that this field is an RVA value but windres appears to produce a section relative offset with the top bit set. Support both styles for now. */ if (HighBitSet (entry)) name = regions->section_start + WithoutHighBit (entry); else name = regions->section_start + entry - rva_bias; if (name + 2 < regions->section_end && name > regions->section_start) { unsigned int len; if (regions->strings_start == NULL) regions->strings_start = name; len = bfd_get_16 (abfd, name); fprintf (file, _("name: [val: %08lx len %d]: "), entry, len); if (name + 2 + len * 2 < regions->section_end) { /* This strange loop is to cope with multibyte characters. */ while (len --) { char c; name += 2; c = * name; /* Avoid printing control characters. */ if (c > 0 && c < 32) fprintf (file, "^%c", c + 64); else fprintf (file, "%.1s", name); } } else { fprintf (file, _("<corrupt string length: %#x>\n"), len); /* PR binutils/17512: Do not try to continue decoding a corrupted resource section. It is likely to end up with reams of extraneous output. FIXME: We could probably continue if we disable the printing of strings... */ return regions->section_end + 1; } } else { fprintf (file, _("<corrupt string offset: %#lx>\n"), entry); return regions->section_end + 1; } } else fprintf (file, _("ID: %#08lx"), entry); entry = (long) bfd_get_32 (abfd, data + 4); fprintf (file, _(", Value: %#08lx\n"), entry); if (HighBitSet (entry)) { data = regions->section_start + WithoutHighBit (entry); if (data <= regions->section_start || data > regions->section_end) return regions->section_end + 1; /* FIXME: PR binutils/17512: A corrupt file could contain a loop in the resource table. We need some way to detect this. */ return rsrc_print_resource_directory (file, abfd, indent + 1, data, regions, rva_bias); } leaf = regions->section_start + entry; if (leaf + 16 >= regions->section_end /* PR 17512: file: 055dff7e. */ || leaf < regions->section_start) return regions->section_end + 1; /* xgettext:c-format */ fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"), (int) (entry), indent, " ", addr = (long) bfd_get_32 (abfd, leaf), size = (long) bfd_get_32 (abfd, leaf + 4), (int) bfd_get_32 (abfd, leaf + 8)); /* Check that the reserved entry is 0. */ if (bfd_get_32 (abfd, leaf + 12) != 0 /* And that the data address/size is valid too. */ || (regions->section_start + (addr - rva_bias) + size > regions->section_end)) return regions->section_end + 1; if (regions->resource_start == NULL) regions->resource_start = regions->section_start + (addr - rva_bias); return regions->section_start + (addr - rva_bias) + size; } #define max(a,b) ((a) > (b) ? (a) : (b)) #define min(a,b) ((a) < (b) ? (a) : (b)) static bfd_byte * rsrc_print_resource_directory (FILE * file, bfd * abfd, unsigned int indent, bfd_byte * data, rsrc_regions * regions, bfd_vma rva_bias) { unsigned int num_names, num_ids; bfd_byte * highest_data = data; if (data + 16 >= regions->section_end) return regions->section_end + 1; fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " "); switch (indent) { case 0: fprintf (file, "Type"); break; case 2: fprintf (file, "Name"); break; case 4: fprintf (file, "Language"); break; default: fprintf (file, _("<unknown directory type: %d>\n"), indent); /* FIXME: For now we end the printing here. If in the future more directory types are added to the RSRC spec then we will need to change this. */ return regions->section_end + 1; } /* xgettext:c-format */ fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"), (int) bfd_get_32 (abfd, data), (long) bfd_get_32 (abfd, data + 4), (int) bfd_get_16 (abfd, data + 8), (int) bfd_get_16 (abfd, data + 10), num_names = (int) bfd_get_16 (abfd, data + 12), num_ids = (int) bfd_get_16 (abfd, data + 14)); data += 16; while (num_names --) { bfd_byte * entry_end; entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, true, data, regions, rva_bias); data += 8; highest_data = max (highest_data, entry_end); if (entry_end >= regions->section_end) return entry_end; } while (num_ids --) { bfd_byte * entry_end; entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, false, data, regions, rva_bias); data += 8; highest_data = max (highest_data, entry_end); if (entry_end >= regions->section_end) return entry_end; } return max (highest_data, data); } /* Display the contents of a .rsrc section. We do not try to reproduce the resources, windres does that. Instead we dump the tables in a human readable format. */ static bool rsrc_print_section (bfd * abfd, void * vfile) { bfd_vma rva_bias; pe_data_type * pe; FILE * file = (FILE *) vfile; bfd_size_type datasize; asection * section; bfd_byte * data; rsrc_regions regions; pe = pe_data (abfd); if (pe == NULL) return true; section = bfd_get_section_by_name (abfd, ".rsrc"); if (section == NULL) return true; if (!(section->flags & SEC_HAS_CONTENTS)) return true; datasize = section->size; if (datasize == 0) return true; rva_bias = section->vma - pe->pe_opthdr.ImageBase; if (! bfd_malloc_and_get_section (abfd, section, & data)) { free (data); return false; } regions.section_start = data; regions.section_end = data + datasize; regions.strings_start = NULL; regions.resource_start = NULL; fflush (file); fprintf (file, "\nThe .rsrc Resource Directory section:\n"); while (data < regions.section_end) { bfd_byte * p = data; data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias); if (data == regions.section_end + 1) fprintf (file, _("Corrupt .rsrc section detected!\n")); else { /* Align data before continuing. */ int align = (1 << section->alignment_power) - 1; data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align); rva_bias += data - p; /* For reasons that are unclear .rsrc sections are sometimes created aligned to a 1^3 boundary even when their alignment is set at 1^2. Catch that case here before we issue a spurious warning message. */ if (data == (regions.section_end - 4)) data = regions.section_end; else if (data < regions.section_end) { /* If the extra data is all zeros then do not complain. This is just padding so that the section meets the page size requirements. */ while (++ data < regions.section_end) if (*data != 0) break; if (data < regions.section_end) fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n")); } } } if (regions.strings_start != NULL) fprintf (file, _(" String table starts at offset: %#03x\n"), (int) (regions.strings_start - regions.section_start)); if (regions.resource_start != NULL) fprintf (file, _(" Resources start at offset: %#03x\n"), (int) (regions.resource_start - regions.section_start)); free (regions.section_start); return true; } #define IMAGE_NUMBEROF_DEBUG_TYPES 17 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] = { "Unknown", "COFF", "CodeView", "FPO", "Misc", "Exception", "Fixup", "OMAP-to-SRC", "OMAP-from-SRC", "Borland", "Reserved", "CLSID", "Feature", "CoffGrp", "ILTCG", "MPX", "Repro", }; static bool pe_print_debugdata (bfd * abfd, void * vfile) { FILE *file = (FILE *) vfile; pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr; asection *section; bfd_byte *data = 0; bfd_size_type dataoff; unsigned int i, j; bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress; bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size; if (size == 0) return true; addr += extra->ImageBase; for (section = abfd->sections; section != NULL; section = section->next) { if ((addr >= section->vma) && (addr < (section->vma + section->size))) break; } if (section == NULL) { fprintf (file, _("\nThere is a debug directory, but the section containing it could not be found\n")); return true; } else if (!(section->flags & SEC_HAS_CONTENTS)) { fprintf (file, _("\nThere is a debug directory in %s, but that section has no contents\n"), section->name); return true; } else if (section->size < size) { fprintf (file, _("\nError: section %s contains the debug data starting address but it is too small\n"), section->name); return false; } fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"), section->name, (unsigned long) addr); dataoff = addr - section->vma; if (size > (section->size - dataoff)) { fprintf (file, _("The debug data size field in the data directory is too big for the section")); return false; } fprintf (file, _("Type Size Rva Offset\n")); /* Read the whole section. */ if (!bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++) { const char *type_name; struct external_IMAGE_DEBUG_DIRECTORY *ext = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i]; struct internal_IMAGE_DEBUG_DIRECTORY idd; _bfd_XXi_swap_debugdir_in (abfd, ext, &idd); if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES) type_name = debug_type_names[0]; else type_name = debug_type_names[idd.Type]; fprintf (file, " %2ld %14s %08lx %08lx %08lx\n", idd.Type, type_name, idd.SizeOfData, idd.AddressOfRawData, idd.PointerToRawData); if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW) { char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1]; /* PR 17512: file: 065-29434-0.001:0.1 We need to use a 32-bit aligned buffer to safely read in a codeview record. */ char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO); CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer; /* The debug entry doesn't have to have to be in a section, in which case AddressOfRawData is 0, so always use PointerToRawData. */ if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData, idd.SizeOfData, cvinfo)) continue; for (j = 0; j < cvinfo->SignatureLength; j++) sprintf (&signature[j*2], "%02x", cvinfo->Signature[j] & 0xff); /* xgettext:c-format */ fprintf (file, _("(format %c%c%c%c signature %s age %ld)\n"), buffer[0], buffer[1], buffer[2], buffer[3], signature, cvinfo->Age); } } free(data); if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0) fprintf (file, _("The debug directory size is not a multiple of the debug directory entry size\n")); return true; } static bool pe_is_repro (bfd * abfd) { pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr; asection *section; bfd_byte *data = 0; bfd_size_type dataoff; unsigned int i; bool res = false; bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress; bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size; if (size == 0) return false; addr += extra->ImageBase; for (section = abfd->sections; section != NULL; section = section->next) { if ((addr >= section->vma) && (addr < (section->vma + section->size))) break; } if ((section == NULL) || (!(section->flags & SEC_HAS_CONTENTS)) || (section->size < size)) { return false; } dataoff = addr - section->vma; if (size > (section->size - dataoff)) { return false; } if (!bfd_malloc_and_get_section (abfd, section, &data)) { free (data); return false; } for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++) { struct external_IMAGE_DEBUG_DIRECTORY *ext = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i]; struct internal_IMAGE_DEBUG_DIRECTORY idd; _bfd_XXi_swap_debugdir_in (abfd, ext, &idd); if (idd.Type == PE_IMAGE_DEBUG_TYPE_REPRO) { res = true; break; } } free(data); return res; } /* Print out the program headers. */ bool _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile) { FILE *file = (FILE *) vfile; int j; pe_data_type *pe = pe_data (abfd); struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr; const char *subsystem_name = NULL; const char *name; /* The MS dumpbin program reportedly ands with 0xff0f before printing the characteristics field. Not sure why. No reason to emulate it here. */ fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags); #undef PF #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); } PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped"); PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable"); PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped"); PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped"); PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware"); PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian"); PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words"); PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed"); PF (IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "copy to swap file if on removable media"); PF (IMAGE_FILE_NET_RUN_FROM_SWAP, "copy to swap file if on network media"); PF (IMAGE_FILE_SYSTEM, "system file"); PF (IMAGE_FILE_DLL, "DLL"); PF (IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine"); PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian"); #undef PF /* If a PE_IMAGE_DEBUG_TYPE_REPRO entry is present in the debug directory, the timestamp is to be interpreted as the hash of a reproducible build. */ if (pe_is_repro (abfd)) { fprintf (file, "\nTime/Date\t\t%08lx", pe->coff.timestamp); fprintf (file, "\t(This is a reproducible build file hash, not a timestamp)\n"); } else { /* ctime implies '\n'. */ time_t t = pe->coff.timestamp; fprintf (file, "\nTime/Date\t\t%s", ctime (&t)); } #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b #endif #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #endif #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107 #endif switch (i->Magic) { case IMAGE_NT_OPTIONAL_HDR_MAGIC: name = "PE32"; break; case IMAGE_NT_OPTIONAL_HDR64_MAGIC: name = "PE32+"; break; case IMAGE_NT_OPTIONAL_HDRROM_MAGIC: name = "ROM"; break; default: name = NULL; break; } fprintf (file, "Magic\t\t\t%04x", i->Magic); if (name) fprintf (file, "\t(%s)",name); fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion); fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion); fprintf (file, "SizeOfCode\t\t"); bfd_fprintf_vma (abfd, file, i->SizeOfCode); fprintf (file, "\nSizeOfInitializedData\t"); bfd_fprintf_vma (abfd, file, i->SizeOfInitializedData); fprintf (file, "\nSizeOfUninitializedData\t"); bfd_fprintf_vma (abfd, file, i->SizeOfUninitializedData); fprintf (file, "\nAddressOfEntryPoint\t"); bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint); fprintf (file, "\nBaseOfCode\t\t"); bfd_fprintf_vma (abfd, file, i->BaseOfCode); #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) /* PE32+ does not have BaseOfData member! */ fprintf (file, "\nBaseOfData\t\t"); bfd_fprintf_vma (abfd, file, i->BaseOfData); #endif fprintf (file, "\nImageBase\t\t"); bfd_fprintf_vma (abfd, file, i->ImageBase); fprintf (file, "\nSectionAlignment\t%08x\n", i->SectionAlignment); fprintf (file, "FileAlignment\t\t%08x\n", i->FileAlignment); fprintf (file, "MajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion); fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion); fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion); fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion); fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion); fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion); fprintf (file, "Win32Version\t\t%08x\n", i->Reserved1); fprintf (file, "SizeOfImage\t\t%08x\n", i->SizeOfImage); fprintf (file, "SizeOfHeaders\t\t%08x\n", i->SizeOfHeaders); fprintf (file, "CheckSum\t\t%08x\n", i->CheckSum); switch (i->Subsystem) { case IMAGE_SUBSYSTEM_UNKNOWN: subsystem_name = "unspecified"; break; case IMAGE_SUBSYSTEM_NATIVE: subsystem_name = "NT native"; break; case IMAGE_SUBSYSTEM_WINDOWS_GUI: subsystem_name = "Windows GUI"; break; case IMAGE_SUBSYSTEM_WINDOWS_CUI: subsystem_name = "Windows CUI"; break; case IMAGE_SUBSYSTEM_POSIX_CUI: subsystem_name = "POSIX CUI"; break; case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: subsystem_name = "Wince CUI"; break; /* These are from UEFI Platform Initialization Specification 1.1. */ case IMAGE_SUBSYSTEM_EFI_APPLICATION: subsystem_name = "EFI application"; break; case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: subsystem_name = "EFI boot service driver"; break; case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: subsystem_name = "EFI runtime driver"; break; case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER: subsystem_name = "SAL runtime driver"; break; /* This is from revision 8.0 of the MS PE/COFF spec */ case IMAGE_SUBSYSTEM_XBOX: subsystem_name = "XBOX"; break; /* Added default case for clarity - subsystem_name is NULL anyway. */ default: subsystem_name = NULL; } fprintf (file, "Subsystem\t\t%08x", i->Subsystem); if (subsystem_name) fprintf (file, "\t(%s)", subsystem_name); fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics); if (i->DllCharacteristics) { unsigned short dllch = i->DllCharacteristics; const char *indent = "\t\t\t\t\t"; if (dllch & IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA) fprintf (file, "%sHIGH_ENTROPY_VA\n", indent); if (dllch & IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE) fprintf (file, "%sDYNAMIC_BASE\n", indent); if (dllch & IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY) fprintf (file, "%sFORCE_INTEGRITY\n", indent); if (dllch & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) fprintf (file, "%sNX_COMPAT\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION) fprintf (file, "%sNO_ISOLATION\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_NO_SEH) fprintf (file, "%sNO_SEH\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_NO_BIND) fprintf (file, "%sNO_BIND\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_APPCONTAINER) fprintf (file, "%sAPPCONTAINER\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER) fprintf (file, "%sWDM_DRIVER\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_GUARD_CF) fprintf (file, "%sGUARD_CF\n", indent); if (dllch & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE) fprintf (file, "%sTERMINAL_SERVICE_AWARE\n", indent); } fprintf (file, "SizeOfStackReserve\t"); bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve); fprintf (file, "\nSizeOfStackCommit\t"); bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit); fprintf (file, "\nSizeOfHeapReserve\t"); bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve); fprintf (file, "\nSizeOfHeapCommit\t"); bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit); fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags); fprintf (file, "NumberOfRvaAndSizes\t%08lx\n", (unsigned long) i->NumberOfRvaAndSizes); fprintf (file, "\nThe Data Directory\n"); for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++) { fprintf (file, "Entry %1x ", j); bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress); fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size); fprintf (file, "%s\n", dir_names[j]); } pe_print_idata (abfd, vfile); pe_print_edata (abfd, vfile); if (bfd_coff_have_print_pdata (abfd)) bfd_coff_print_pdata (abfd, vfile); else pe_print_pdata (abfd, vfile); pe_print_reloc (abfd, vfile); pe_print_debugdata (abfd, file); rsrc_print_section (abfd, vfile); return true; } static bool is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj) { bfd_vma addr = * (bfd_vma *) obj; return (addr >= sect->vma) && (addr < (sect->vma + sect->size)); } static asection * find_section_by_vma (bfd *abfd, bfd_vma addr) { return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr); } /* Copy any private info we understand from the input bfd to the output bfd. */ bool _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd) { pe_data_type *ipe, *ope; /* One day we may try to grok other private data. */ if (ibfd->xvec->flavour != bfd_target_coff_flavour || obfd->xvec->flavour != bfd_target_coff_flavour) return true; ipe = pe_data (ibfd); ope = pe_data (obfd); /* pe_opthdr is copied in copy_object. */ ope->dll = ipe->dll; /* Don't copy input subsystem if output is different from input. */ if (obfd->xvec != ibfd->xvec) ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN; /* For strip: if we removed .reloc, we'll make a real mess of things if we don't remove this entry as well. */ if (! pe_data (obfd)->has_reloc_section) { pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0; pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0; } /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED. But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED won't be added. */ if (! pe_data (ibfd)->has_reloc_section && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED)) pe_data (obfd)->dont_strip_reloc = 1; memcpy (ope->dos_message, ipe->dos_message, sizeof (ope->dos_message)); /* The file offsets contained in the debug directory need rewriting. */ if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0) { bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress + ope->pe_opthdr.ImageBase; /* In particular a .buildid section may overlap (in VA space) with whatever section comes ahead of it (largely because of section->size representing s_size, not virt_size). Therefore don't look for the section containing the first byte, but for that covering the last one. */ bfd_vma last = addr + ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size - 1; asection *section = find_section_by_vma (obfd, last); bfd_byte *data; /* PR 17512: file: 0f15796a. */ if (section && addr < section->vma) { /* xgettext:c-format */ _bfd_error_handler (_("%pB: Data Directory (%lx bytes at %" PRIx64 ") " "extends across section boundary at %" PRIx64), obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size, (uint64_t) addr, (uint64_t) section->vma); return false; } if (section && bfd_malloc_and_get_section (obfd, section, &data)) { unsigned int i; struct external_IMAGE_DEBUG_DIRECTORY *dd = (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma)); for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++) { asection *ddsection; struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]); struct internal_IMAGE_DEBUG_DIRECTORY idd; _bfd_XXi_swap_debugdir_in (obfd, edd, &idd); if (idd.AddressOfRawData == 0) continue; /* RVA 0 means only offset is valid, not handled yet. */ ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase); if (!ddsection) continue; /* Not in a section! */ idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData + ope->pe_opthdr.ImageBase) - ddsection->vma; _bfd_XXi_swap_debugdir_out (obfd, &idd, edd); } if (!bfd_set_section_contents (obfd, section, data, 0, section->size)) { _bfd_error_handler (_("failed to update file offsets in debug directory")); free (data); return false; } free (data); } else if (section) { _bfd_error_handler (_("%pB: failed to read debug data section"), obfd); return false; } } return true; } /* Copy private section data. */ bool _bfd_XX_bfd_copy_private_section_data (bfd *ibfd, asection *isec, bfd *obfd, asection *osec) { if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour || bfd_get_flavour (obfd) != bfd_target_coff_flavour) return true; if (coff_section_data (ibfd, isec) != NULL && pei_section_data (ibfd, isec) != NULL) { if (coff_section_data (obfd, osec) == NULL) { size_t amt = sizeof (struct coff_section_tdata); osec->used_by_bfd = bfd_zalloc (obfd, amt); if (osec->used_by_bfd == NULL) return false; } if (pei_section_data (obfd, osec) == NULL) { size_t amt = sizeof (struct pei_section_tdata); coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt); if (coff_section_data (obfd, osec)->tdata == NULL) return false; } pei_section_data (obfd, osec)->virt_size = pei_section_data (ibfd, isec)->virt_size; pei_section_data (obfd, osec)->pe_flags = pei_section_data (ibfd, isec)->pe_flags; } return true; } void _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret) { coff_get_symbol_info (abfd, symbol, ret); } #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64) static int sort_x64_pdata (const void *l, const void *r) { const char *lp = (const char *) l; const char *rp = (const char *) r; bfd_vma vl, vr; vl = bfd_getl32 (lp); vr = bfd_getl32 (rp); if (vl != vr) return (vl < vr ? -1 : 1); /* We compare just begin address. */ return 0; } #endif /* Functions to process a .rsrc section. */ static unsigned int sizeof_leaves; static unsigned int sizeof_strings; static unsigned int sizeof_tables_and_entries; static bfd_byte * rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma); static bfd_byte * rsrc_count_entries (bfd *abfd, bool is_name, bfd_byte *datastart, bfd_byte *data, bfd_byte *dataend, bfd_vma rva_bias) { unsigned long entry, addr, size; if (data + 8 >= dataend) return dataend + 1; if (is_name) { bfd_byte * name; entry = (long) bfd_get_32 (abfd, data); if (HighBitSet (entry)) name = datastart + WithoutHighBit (entry); else name = datastart + entry - rva_bias; if (name + 2 >= dataend || name < datastart) return dataend + 1; unsigned int len = bfd_get_16 (abfd, name); if (len == 0 || len > 256) return dataend + 1; } entry = (long) bfd_get_32 (abfd, data + 4); if (HighBitSet (entry)) { data = datastart + WithoutHighBit (entry); if (data <= datastart || data >= dataend) return dataend + 1; return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias); } if (datastart + entry + 16 >= dataend) return dataend + 1; addr = (long) bfd_get_32 (abfd, datastart + entry); size = (long) bfd_get_32 (abfd, datastart + entry + 4); return datastart + addr - rva_bias + size; } static bfd_byte * rsrc_count_directory (bfd * abfd, bfd_byte * datastart, bfd_byte * data, bfd_byte * dataend, bfd_vma rva_bias) { unsigned int num_entries, num_ids; bfd_byte * highest_data = data; if (data + 16 >= dataend) return dataend + 1; num_entries = (int) bfd_get_16 (abfd, data + 12); num_ids = (int) bfd_get_16 (abfd, data + 14); num_entries += num_ids; data += 16; while (num_entries --) { bfd_byte * entry_end; entry_end = rsrc_count_entries (abfd, num_entries >= num_ids, datastart, data, dataend, rva_bias); data += 8; highest_data = max (highest_data, entry_end); if (entry_end >= dataend) break; } return max (highest_data, data); } typedef struct rsrc_dir_chain { unsigned int num_entries; struct rsrc_entry * first_entry; struct rsrc_entry * last_entry; } rsrc_dir_chain; typedef struct rsrc_directory { unsigned int characteristics; unsigned int time; unsigned int major; unsigned int minor; rsrc_dir_chain names; rsrc_dir_chain ids; struct rsrc_entry * entry; } rsrc_directory; typedef struct rsrc_string { unsigned int len; bfd_byte * string; } rsrc_string; typedef struct rsrc_leaf { unsigned int size; unsigned int codepage; bfd_byte * data; } rsrc_leaf; typedef struct rsrc_entry { bool is_name; union { unsigned int id; struct rsrc_string name; } name_id; bool is_dir; union { struct rsrc_directory * directory; struct rsrc_leaf * leaf; } value; struct rsrc_entry * next_entry; struct rsrc_directory * parent; } rsrc_entry; static bfd_byte * rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *); static bfd_byte * rsrc_parse_entry (bfd *abfd, bool is_name, rsrc_entry *entry, bfd_byte *datastart, bfd_byte * data, bfd_byte *dataend, bfd_vma rva_bias, rsrc_directory *parent) { unsigned long val, addr, size; val = bfd_get_32 (abfd, data); entry->parent = parent; entry->is_name = is_name; if (is_name) { bfd_byte * address; if (HighBitSet (val)) { val = WithoutHighBit (val); address = datastart + val; } else { address = datastart + val - rva_bias; } if (address + 3 > dataend) return dataend; entry->name_id.name.len = bfd_get_16 (abfd, address); entry->name_id.name.string = address + 2; } else entry->name_id.id = val; val = bfd_get_32 (abfd, data + 4); if (HighBitSet (val)) { entry->is_dir = true; entry->value.directory = bfd_malloc (sizeof * entry->value.directory); if (entry->value.directory == NULL) return dataend; return rsrc_parse_directory (abfd, entry->value.directory, datastart, datastart + WithoutHighBit (val), dataend, rva_bias, entry); } entry->is_dir = false; entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf); if (entry->value.leaf == NULL) return dataend; data = datastart + val; if (data < datastart || data >= dataend) return dataend; addr = bfd_get_32 (abfd, data); size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4); entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8); /* FIXME: We assume that the reserved field (data + 12) is OK. */ entry->value.leaf->data = bfd_malloc (size); if (entry->value.leaf->data == NULL) return dataend; memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size); return datastart + (addr - rva_bias) + size; } static bfd_byte * rsrc_parse_entries (bfd *abfd, rsrc_dir_chain *chain, bool is_name, bfd_byte *highest_data, bfd_byte *datastart, bfd_byte *data, bfd_byte *dataend, bfd_vma rva_bias, rsrc_directory *parent) { unsigned int i; rsrc_entry * entry; if (chain->num_entries == 0) { chain->first_entry = chain->last_entry = NULL; return highest_data; } entry = bfd_malloc (sizeof * entry); if (entry == NULL) return dataend; chain->first_entry = entry; for (i = chain->num_entries; i--;) { bfd_byte * entry_end; entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart, data, dataend, rva_bias, parent); data += 8; highest_data = max (entry_end, highest_data); if (entry_end > dataend) return dataend; if (i) { entry->next_entry = bfd_malloc (sizeof * entry); entry = entry->next_entry; if (entry == NULL) return dataend; } else entry->next_entry = NULL; } chain->last_entry = entry; return highest_data; } static bfd_byte * rsrc_parse_directory (bfd * abfd, rsrc_directory * table, bfd_byte * datastart, bfd_byte * data, bfd_byte * dataend, bfd_vma rva_bias, rsrc_entry * entry) { bfd_byte * highest_data = data; if (table == NULL) return dataend; table->characteristics = bfd_get_32 (abfd, data); table->time = bfd_get_32 (abfd, data + 4); table->major = bfd_get_16 (abfd, data + 8); table->minor = bfd_get_16 (abfd, data + 10); table->names.num_entries = bfd_get_16 (abfd, data + 12); table->ids.num_entries = bfd_get_16 (abfd, data + 14); table->entry = entry; data += 16; highest_data = rsrc_parse_entries (abfd, & table->names, true, data, datastart, data, dataend, rva_bias, table); data += table->names.num_entries * 8; highest_data = rsrc_parse_entries (abfd, & table->ids, false, highest_data, datastart, data, dataend, rva_bias, table); data += table->ids.num_entries * 8; return max (highest_data, data); } typedef struct rsrc_write_data { bfd * abfd; bfd_byte * datastart; bfd_byte * next_table; bfd_byte * next_leaf; bfd_byte * next_string; bfd_byte * next_data; bfd_vma rva_bias; } rsrc_write_data; static void rsrc_write_string (rsrc_write_data * data, rsrc_string * string) { bfd_put_16 (data->abfd, string->len, data->next_string); memcpy (data->next_string + 2, string->string, string->len * 2); data->next_string += (string->len + 1) * 2; } static inline unsigned int rsrc_compute_rva (rsrc_write_data * data, bfd_byte * addr) { return (addr - data->datastart) + data->rva_bias; } static void rsrc_write_leaf (rsrc_write_data * data, rsrc_leaf * leaf) { bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data), data->next_leaf); bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4); bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8); bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12); data->next_leaf += 16; memcpy (data->next_data, leaf->data, leaf->size); /* An undocumented feature of Windows resources is that each unit of raw data is 8-byte aligned... */ data->next_data += ((leaf->size + 7) & ~7); } static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *); static void rsrc_write_entry (rsrc_write_data * data, bfd_byte * where, rsrc_entry * entry) { if (entry->is_name) { bfd_put_32 (data->abfd, SetHighBit (data->next_string - data->datastart), where); rsrc_write_string (data, & entry->name_id.name); } else bfd_put_32 (data->abfd, entry->name_id.id, where); if (entry->is_dir) { bfd_put_32 (data->abfd, SetHighBit (data->next_table - data->datastart), where + 4); rsrc_write_directory (data, entry->value.directory); } else { bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4); rsrc_write_leaf (data, entry->value.leaf); } } static void rsrc_compute_region_sizes (rsrc_directory * dir) { struct rsrc_entry * entry; if (dir == NULL) return; sizeof_tables_and_entries += 16; for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry) { sizeof_tables_and_entries += 8; sizeof_strings += (entry->name_id.name.len + 1) * 2; if (entry->is_dir) rsrc_compute_region_sizes (entry->value.directory); else sizeof_leaves += 16; } for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry) { sizeof_tables_and_entries += 8; if (entry->is_dir) rsrc_compute_region_sizes (entry->value.directory); else sizeof_leaves += 16; } } static void rsrc_write_directory (rsrc_write_data * data, rsrc_directory * dir) { rsrc_entry * entry; unsigned int i; bfd_byte * next_entry; bfd_byte * nt; bfd_put_32 (data->abfd, dir->characteristics, data->next_table); bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4); bfd_put_16 (data->abfd, dir->major, data->next_table + 8); bfd_put_16 (data->abfd, dir->minor, data->next_table + 10); bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12); bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14); /* Compute where the entries and the next table will be placed. */ next_entry = data->next_table + 16; data->next_table = next_entry + (dir->names.num_entries * 8) + (dir->ids.num_entries * 8); nt = data->next_table; /* Write the entries. */ for (i = dir->names.num_entries, entry = dir->names.first_entry; i > 0 && entry != NULL; i--, entry = entry->next_entry) { BFD_ASSERT (entry->is_name); rsrc_write_entry (data, next_entry, entry); next_entry += 8; } BFD_ASSERT (i == 0); BFD_ASSERT (entry == NULL); for (i = dir->ids.num_entries, entry = dir->ids.first_entry; i > 0 && entry != NULL; i--, entry = entry->next_entry) { BFD_ASSERT (! entry->is_name); rsrc_write_entry (data, next_entry, entry); next_entry += 8; } BFD_ASSERT (i == 0); BFD_ASSERT (entry == NULL); BFD_ASSERT (nt == next_entry); } #if ! defined __CYGWIN__ && ! defined __MINGW32__ /* Return the length (number of units) of the first character in S, putting its 'ucs4_t' representation in *PUC. */ static unsigned int u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n) { unsigned short c = * s; if (c < 0xd800 || c >= 0xe000) { *puc = c; return 1; } if (c < 0xdc00) { if (n >= 2) { if (s[1] >= 0xdc00 && s[1] < 0xe000) { *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00); return 2; } } else { /* Incomplete multibyte character. */ *puc = 0xfffd; return n; } } /* Invalid multibyte character. */ *puc = 0xfffd; return 1; } #endif /* not Cygwin/Mingw */ /* Perform a comparison of two entries. */ static signed int rsrc_cmp (bool is_name, rsrc_entry * a, rsrc_entry * b) { signed int res; bfd_byte * astring; unsigned int alen; bfd_byte * bstring; unsigned int blen; if (! is_name) return a->name_id.id - b->name_id.id; /* We have to perform a case insenstive, unicode string comparison... */ astring = a->name_id.name.string; alen = a->name_id.name.len; bstring = b->name_id.name.string; blen = b->name_id.name.len; #if defined __CYGWIN__ || defined __MINGW32__ /* Under Windows hosts (both Cygwin and Mingw types), unicode == UTF-16 == wchar_t. The case insensitive string comparison function however goes by different names in the two environments... */ #undef rscpcmp #ifdef __CYGWIN__ #define rscpcmp wcsncasecmp #endif #ifdef __MINGW32__ #define rscpcmp wcsnicmp #endif res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring, min (alen, blen)); #else { unsigned int i; res = 0; for (i = min (alen, blen); i--; astring += 2, bstring += 2) { wint_t awc; wint_t bwc; /* Convert UTF-16 unicode characters into wchar_t characters so that we can then perform a case insensitive comparison. */ unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2); unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2); if (Alen != Blen) return Alen - Blen; awc = towlower (awc); bwc = towlower (bwc); res = awc - bwc; if (res) break; } } #endif if (res == 0) res = alen - blen; return res; } static void rsrc_print_name (char * buffer, rsrc_string string) { unsigned int i; bfd_byte * name = string.string; for (i = string.len; i--; name += 2) sprintf (buffer + strlen (buffer), "%.1s", name); } static const char * rsrc_resource_name (rsrc_entry *entry, rsrc_directory *dir, char *buffer) { bool is_string = false; buffer[0] = 0; if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL && dir->entry->parent->entry != NULL) { strcpy (buffer, "type: "); if (dir->entry->parent->entry->is_name) rsrc_print_name (buffer + strlen (buffer), dir->entry->parent->entry->name_id.name); else { unsigned int id = dir->entry->parent->entry->name_id.id; sprintf (buffer + strlen (buffer), "%x", id); switch (id) { case 1: strcat (buffer, " (CURSOR)"); break; case 2: strcat (buffer, " (BITMAP)"); break; case 3: strcat (buffer, " (ICON)"); break; case 4: strcat (buffer, " (MENU)"); break; case 5: strcat (buffer, " (DIALOG)"); break; case 6: strcat (buffer, " (STRING)"); is_string = true; break; case 7: strcat (buffer, " (FONTDIR)"); break; case 8: strcat (buffer, " (FONT)"); break; case 9: strcat (buffer, " (ACCELERATOR)"); break; case 10: strcat (buffer, " (RCDATA)"); break; case 11: strcat (buffer, " (MESSAGETABLE)"); break; case 12: strcat (buffer, " (GROUP_CURSOR)"); break; case 14: strcat (buffer, " (GROUP_ICON)"); break; case 16: strcat (buffer, " (VERSION)"); break; case 17: strcat (buffer, " (DLGINCLUDE)"); break; case 19: strcat (buffer, " (PLUGPLAY)"); break; case 20: strcat (buffer, " (VXD)"); break; case 21: strcat (buffer, " (ANICURSOR)"); break; case 22: strcat (buffer, " (ANIICON)"); break; case 23: strcat (buffer, " (HTML)"); break; case 24: strcat (buffer, " (MANIFEST)"); break; case 240: strcat (buffer, " (DLGINIT)"); break; case 241: strcat (buffer, " (TOOLBAR)"); break; } } } if (dir != NULL && dir->entry != NULL) { strcat (buffer, " name: "); if (dir->entry->is_name) rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name); else { unsigned int id = dir->entry->name_id.id; sprintf (buffer + strlen (buffer), "%x", id); if (is_string) sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)", (id - 1) << 4, (id << 4) - 1); } } if (entry != NULL) { strcat (buffer, " lang: "); if (entry->is_name) rsrc_print_name (buffer + strlen (buffer), entry->name_id.name); else sprintf (buffer + strlen (buffer), "%x", entry->name_id.id); } return buffer; } /* *sigh* Windows resource strings are special. Only the top 28-bits of their ID is stored in the NAME entry. The bottom four bits are used as an index into unicode string table that makes up the data of the leaf. So identical type-name-lang string resources may not actually be identical at all. This function is called when we have detected two string resources with match top-28-bit IDs. We have to scan the string tables inside the leaves and discover if there are any real collisions. If there are then we report them and return FALSE. Otherwise we copy any strings from B into A and then return TRUE. */ static bool rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED, rsrc_entry * b ATTRIBUTE_UNUSED) { unsigned int copy_needed = 0; unsigned int i; bfd_byte * astring; bfd_byte * bstring; bfd_byte * new_data; bfd_byte * nstring; /* Step one: Find out what we have to do. */ BFD_ASSERT (! a->is_dir); astring = a->value.leaf->data; BFD_ASSERT (! b->is_dir); bstring = b->value.leaf->data; for (i = 0; i < 16; i++) { unsigned int alen = astring[0] + (astring[1] << 8); unsigned int blen = bstring[0] + (bstring[1] << 8); if (alen == 0) { copy_needed += blen * 2; } else if (blen == 0) ; else if (alen != blen) /* FIXME: Should we continue the loop in order to report other duplicates ? */ break; /* alen == blen != 0. We might have two identical strings. If so we can ignore the second one. There is no need for wchar_t vs UTF-16 theatrics here - we are only interested in (case sensitive) equality. */ else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0) break; astring += (alen + 1) * 2; bstring += (blen + 1) * 2; } if (i != 16) { if (a->parent != NULL && a->parent->entry != NULL && !a->parent->entry->is_name) _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"), ((a->parent->entry->name_id.id - 1) << 4) + i); return false; } if (copy_needed == 0) return true; /* If we reach here then A and B must both have non-colliding strings. (We never get string resources with fully empty string tables). We need to allocate an extra COPY_NEEDED bytes in A and then bring in B's strings. */ new_data = bfd_malloc (a->value.leaf->size + copy_needed); if (new_data == NULL) return false; nstring = new_data; astring = a->value.leaf->data; bstring = b->value.leaf->data; for (i = 0; i < 16; i++) { unsigned int alen = astring[0] + (astring[1] << 8); unsigned int blen = bstring[0] + (bstring[1] << 8); if (alen != 0) { memcpy (nstring, astring, (alen + 1) * 2); nstring += (alen + 1) * 2; } else if (blen != 0) { memcpy (nstring, bstring, (blen + 1) * 2); nstring += (blen + 1) * 2; } else { * nstring++ = 0; * nstring++ = 0; } astring += (alen + 1) * 2; bstring += (blen + 1) * 2; } BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed)); free (a->value.leaf->data); a->value.leaf->data = new_data; a->value.leaf->size += copy_needed; return true; } static void rsrc_merge (rsrc_entry *, rsrc_entry *); /* Sort the entries in given part of the directory. We use an old fashioned bubble sort because we are dealing with lists and we want to handle matches specially. */ static void rsrc_sort_entries (rsrc_dir_chain *chain, bool is_name, rsrc_directory *dir) { rsrc_entry * entry; rsrc_entry * next; rsrc_entry ** points_to_entry; bool swapped; if (chain->num_entries < 2) return; do { swapped = false; points_to_entry = & chain->first_entry; entry = * points_to_entry; next = entry->next_entry; do { signed int cmp = rsrc_cmp (is_name, entry, next); if (cmp > 0) { entry->next_entry = next->next_entry; next->next_entry = entry; * points_to_entry = next; points_to_entry = & next->next_entry; next = entry->next_entry; swapped = true; } else if (cmp == 0) { if (entry->is_dir && next->is_dir) { /* When we encounter identical directory entries we have to merge them together. The exception to this rule is for resource manifests - there can only be one of these, even if they differ in language. Zero-language manifests are assumed to be default manifests (provided by the Cygwin/MinGW build system) and these can be silently dropped, unless that would reduce the number of manifests to zero. There should only ever be one non-zero lang manifest - if there are more it is an error. A non-zero lang manifest takes precedence over a default manifest. */ if (!entry->is_name && entry->name_id.id == 1 && dir != NULL && dir->entry != NULL && !dir->entry->is_name && dir->entry->name_id.id == 0x18) { if (next->value.directory->names.num_entries == 0 && next->value.directory->ids.num_entries == 1 && !next->value.directory->ids.first_entry->is_name && next->value.directory->ids.first_entry->name_id.id == 0) /* Fall through so that NEXT is dropped. */ ; else if (entry->value.directory->names.num_entries == 0 && entry->value.directory->ids.num_entries == 1 && !entry->value.directory->ids.first_entry->is_name && entry->value.directory->ids.first_entry->name_id.id == 0) { /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */ entry->next_entry = next->next_entry; next->next_entry = entry; * points_to_entry = next; points_to_entry = & next->next_entry; next = entry->next_entry; swapped = true; } else { _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests")); bfd_set_error (bfd_error_file_truncated); return; } /* Unhook NEXT from the chain. */ /* FIXME: memory loss here. */ entry->next_entry = next->next_entry; chain->num_entries --; if (chain->num_entries < 2) return; next = next->next_entry; } else rsrc_merge (entry, next); } else if (entry->is_dir != next->is_dir) { _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf")); bfd_set_error (bfd_error_file_truncated); return; } else { /* Otherwise with identical leaves we issue an error message - because there should never be duplicates. The exception is Type 18/Name 1/Lang 0 which is the defaul manifest - this can just be dropped. */ if (!entry->is_name && entry->name_id.id == 0 && dir != NULL && dir->entry != NULL && !dir->entry->is_name && dir->entry->name_id.id == 1 && dir->entry->parent != NULL && dir->entry->parent->entry != NULL && !dir->entry->parent->entry->is_name && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */) ; else if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL && dir->entry->parent->entry != NULL && !dir->entry->parent->entry->is_name && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */) { /* Strings need special handling. */ if (! rsrc_merge_string_entries (entry, next)) { /* _bfd_error_handler should have been called inside merge_strings. */ bfd_set_error (bfd_error_file_truncated); return; } } else { if (dir == NULL || dir->entry == NULL || dir->entry->parent == NULL || dir->entry->parent->entry == NULL) _bfd_error_handler (_(".rsrc merge failure: duplicate leaf")); else { char buff[256]; _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"), rsrc_resource_name (entry, dir, buff)); } bfd_set_error (bfd_error_file_truncated); return; } } /* Unhook NEXT from the chain. */ entry->next_entry = next->next_entry; chain->num_entries --; if (chain->num_entries < 2) return; next = next->next_entry; } else { points_to_entry = & entry->next_entry; entry = next; next = next->next_entry; } } while (next); chain->last_entry = entry; } while (swapped); } /* Attach B's chain onto A. */ static void rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain) { if (bchain->num_entries == 0) return; achain->num_entries += bchain->num_entries; if (achain->first_entry == NULL) { achain->first_entry = bchain->first_entry; achain->last_entry = bchain->last_entry; } else { achain->last_entry->next_entry = bchain->first_entry; achain->last_entry = bchain->last_entry; } bchain->num_entries = 0; bchain->first_entry = bchain->last_entry = NULL; } static void rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b) { rsrc_directory * adir; rsrc_directory * bdir; BFD_ASSERT (a->is_dir); BFD_ASSERT (b->is_dir); adir = a->value.directory; bdir = b->value.directory; if (adir->characteristics != bdir->characteristics) { _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics")); bfd_set_error (bfd_error_file_truncated); return; } if (adir->major != bdir->major || adir->minor != bdir->minor) { _bfd_error_handler (_(".rsrc merge failure: differing directory versions")); bfd_set_error (bfd_error_file_truncated); return; } /* Attach B's name chain to A. */ rsrc_attach_chain (& adir->names, & bdir->names); /* Attach B's ID chain to A. */ rsrc_attach_chain (& adir->ids, & bdir->ids); /* Now sort A's entries. */ rsrc_sort_entries (& adir->names, true, adir); rsrc_sort_entries (& adir->ids, false, adir); } /* Check the .rsrc section. If it contains multiple concatenated resources then we must merge them properly. Otherwise Windows will ignore all but the first set. */ static void rsrc_process_section (bfd * abfd, struct coff_final_link_info * pfinfo) { rsrc_directory new_table; bfd_size_type size; asection * sec; pe_data_type * pe; bfd_vma rva_bias; bfd_byte * data; bfd_byte * datastart; bfd_byte * dataend; bfd_byte * new_data; unsigned int num_resource_sets; rsrc_directory * type_tables; rsrc_write_data write_data; unsigned int indx; bfd * input; unsigned int num_input_rsrc = 0; unsigned int max_num_input_rsrc = 4; ptrdiff_t * rsrc_sizes = NULL; new_table.names.num_entries = 0; new_table.ids.num_entries = 0; sec = bfd_get_section_by_name (abfd, ".rsrc"); if (sec == NULL || (size = sec->rawsize) == 0) return; pe = pe_data (abfd); if (pe == NULL) return; rva_bias = sec->vma - pe->pe_opthdr.ImageBase; data = bfd_malloc (size); if (data == NULL) return; datastart = data; if (! bfd_get_section_contents (abfd, sec, data, 0, size)) goto end; /* Step zero: Scan the input bfds looking for .rsrc sections and record their lengths. Note - we rely upon the fact that the linker script does *not* sort the input .rsrc sections, so that the order in the linkinfo list matches the order in the output .rsrc section. We need to know the lengths because each input .rsrc section has padding at the end of a variable amount. (It does not appear to be based upon the section alignment or the file alignment). We need to skip any padding bytes when parsing the input .rsrc sections. */ rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes); if (rsrc_sizes == NULL) goto end; for (input = pfinfo->info->input_bfds; input != NULL; input = input->link.next) { asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc"); /* PR 18372 - skip discarded .rsrc sections. */ if (rsrc_sec != NULL && !discarded_section (rsrc_sec)) { if (num_input_rsrc == max_num_input_rsrc) { max_num_input_rsrc += 10; rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc * sizeof * rsrc_sizes); if (rsrc_sizes == NULL) goto end; } BFD_ASSERT (rsrc_sec->size > 0); rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size; } } if (num_input_rsrc < 2) goto end; /* Step one: Walk the section, computing the size of the tables, leaves and data and decide if we need to do anything. */ dataend = data + size; num_resource_sets = 0; while (data < dataend) { bfd_byte * p = data; data = rsrc_count_directory (abfd, data, data, dataend, rva_bias); if (data > dataend) { /* Corrupted .rsrc section - cannot merge. */ _bfd_error_handler (_("%pB: .rsrc merge failure: corrupt .rsrc section"), abfd); bfd_set_error (bfd_error_file_truncated); goto end; } if ((data - p) > rsrc_sizes [num_resource_sets]) { _bfd_error_handler (_("%pB: .rsrc merge failure: unexpected .rsrc size"), abfd); bfd_set_error (bfd_error_file_truncated); goto end; } /* FIXME: Should we add a check for "data - p" being much smaller than rsrc_sizes[num_resource_sets] ? */ data = p + rsrc_sizes[num_resource_sets]; rva_bias += data - p; ++ num_resource_sets; } BFD_ASSERT (num_resource_sets == num_input_rsrc); /* Step two: Walk the data again, building trees of the resources. */ data = datastart; rva_bias = sec->vma - pe->pe_opthdr.ImageBase; type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables); if (type_tables == NULL) goto end; indx = 0; while (data < dataend) { bfd_byte * p = data; (void) rsrc_parse_directory (abfd, type_tables + indx, data, data, dataend, rva_bias, NULL); data = p + rsrc_sizes[indx]; rva_bias += data - p; ++ indx; } BFD_ASSERT (indx == num_resource_sets); /* Step three: Merge the top level tables (there can be only one). We must ensure that the merged entries are in ascending order. We also thread the top level table entries from the old tree onto the new table, so that they can be pulled off later. */ /* FIXME: Should we verify that all type tables are the same ? */ new_table.characteristics = type_tables[0].characteristics; new_table.time = type_tables[0].time; new_table.major = type_tables[0].major; new_table.minor = type_tables[0].minor; /* Chain the NAME entries onto the table. */ new_table.names.first_entry = NULL; new_table.names.last_entry = NULL; for (indx = 0; indx < num_resource_sets; indx++) rsrc_attach_chain (& new_table.names, & type_tables[indx].names); rsrc_sort_entries (& new_table.names, true, & new_table); /* Chain the ID entries onto the table. */ new_table.ids.first_entry = NULL; new_table.ids.last_entry = NULL; for (indx = 0; indx < num_resource_sets; indx++) rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids); rsrc_sort_entries (& new_table.ids, false, & new_table); /* Step four: Create new contents for the .rsrc section. */ /* Step four point one: Compute the size of each region of the .rsrc section. We do this now, rather than earlier, as the merging above may have dropped some entries. */ sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0; rsrc_compute_region_sizes (& new_table); /* We increment sizeof_strings to make sure that resource data starts on an 8-byte boundary. FIXME: Is this correct ? */ sizeof_strings = (sizeof_strings + 7) & ~ 7; new_data = bfd_zalloc (abfd, size); if (new_data == NULL) goto end; write_data.abfd = abfd; write_data.datastart = new_data; write_data.next_table = new_data; write_data.next_leaf = new_data + sizeof_tables_and_entries; write_data.next_string = write_data.next_leaf + sizeof_leaves; write_data.next_data = write_data.next_string + sizeof_strings; write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase; rsrc_write_directory (& write_data, & new_table); /* Step five: Replace the old contents with the new. We don't recompute the size as it's too late here to shrink section. See PR ld/20193 for more details. */ bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size); sec->size = sec->rawsize = size; end: /* Step six: Free all the memory that we have used. */ /* FIXME: Free the resource tree, if we have one. */ free (datastart); free (rsrc_sizes); } /* Handle the .idata section and other things that need symbol table access. */ bool _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo) { struct coff_link_hash_entry *h1; struct bfd_link_info *info = pfinfo->info; bool result = true; /* There are a few fields that need to be filled in now while we have symbol table access. The .idata subsections aren't directly available as sections, but they are in the symbol table, so get them from there. */ /* The import directory. This is the address of .idata$2, with size of .idata$2 + .idata$3. */ h1 = coff_link_hash_lookup (coff_hash_table (info), ".idata$2", false, false, true); if (h1 != NULL) { /* PR ld/2729: We cannot rely upon all the output sections having been created properly, so check before referencing them. Issue a warning message for any sections tht could not be found. */ if ((h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress = (h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset); else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[1] because .idata$2 is missing"), abfd); result = false; } h1 = coff_link_hash_lookup (coff_hash_table (info), ".idata$4", false, false, true); if (h1 != NULL && (h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size = ((h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset) - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress); else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[1] because .idata$4 is missing"), abfd); result = false; } /* The import address table. This is the size/address of .idata$5. */ h1 = coff_link_hash_lookup (coff_hash_table (info), ".idata$5", false, false, true); if (h1 != NULL && (h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress = (h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset); else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[12] because .idata$5 is missing"), abfd); result = false; } h1 = coff_link_hash_lookup (coff_hash_table (info), ".idata$6", false, false, true); if (h1 != NULL && (h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size = ((h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset) - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress); else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"), abfd); result = false; } } else { h1 = coff_link_hash_lookup (coff_hash_table (info), "__IAT_start__", false, false, true); if (h1 != NULL && (h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) { bfd_vma iat_va; iat_va = (h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset); h1 = coff_link_hash_lookup (coff_hash_table (info), "__IAT_end__", false, false, true); if (h1 != NULL && (h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) { pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size = ((h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset) - iat_va); if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0) pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress = iat_va - pe_data (abfd)->pe_opthdr.ImageBase; } else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]" " because .idata$6 is missing"), abfd); result = false; } } } h1 = coff_link_hash_lookup (coff_hash_table (info), (bfd_get_symbol_leading_char (abfd) != 0 ? "__tls_used" : "_tls_used"), false, false, true); if (h1 != NULL) { if ((h1->root.type == bfd_link_hash_defined || h1->root.type == bfd_link_hash_defweak) && h1->root.u.def.section != NULL && h1->root.u.def.section->output_section != NULL) pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress = (h1->root.u.def.value + h1->root.u.def.section->output_section->vma + h1->root.u.def.section->output_offset - pe_data (abfd)->pe_opthdr.ImageBase); else { _bfd_error_handler (_("%pB: unable to fill in DataDictionary[9] because __tls_used is missing"), abfd); result = false; } /* According to PECOFF sepcifications by Microsoft version 8.2 the TLS data directory consists of 4 pointers, followed by two 4-byte integer. This implies that the total size is different for 32-bit and 64-bit executables. */ #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64) pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18; #else pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28; #endif } /* If there is a .pdata section and we have linked pdata finally, we need to sort the entries ascending. */ #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64) { asection *sec = bfd_get_section_by_name (abfd, ".pdata"); if (sec) { bfd_size_type x = sec->rawsize; bfd_byte *tmp_data = NULL; if (x) tmp_data = bfd_malloc (x); if (tmp_data != NULL) { if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x)) { qsort (tmp_data, (size_t) (x / 12), 12, sort_x64_pdata); bfd_set_section_contents (pfinfo->output_bfd, sec, tmp_data, 0, x); } free (tmp_data); } else result = false; } } #endif rsrc_process_section (abfd, pfinfo); /* If we couldn't find idata$2, we either have an excessively trivial program or are in DEEP trouble; we have to assume trivial program.... */ return result; }
413416.c
/* Mulator - An extensible {e,si}mulator * Copyright 2011-2020 Pat Pannuto <[email protected]> * * Licensed under either of the Apache License, Version 2.0 * or the MIT license, at your option. */ #include "core/isa/opcodes.h" #include "core/isa/decode_helpers.h" #include "core/operations/it.h" // arm-v7-m static void it_t1(uint16_t inst) { uint8_t itstate = inst & 0xff; OP_DECOMPILE("IT{x{y{z}}}<q> <firstcond>", itstate); // IT -> special return it(inst); } __attribute__ ((constructor)) static void register_opcodes_arm_v7_m_it(void) { // it_t1: 1011 1111 xxxx xxxx register_opcode_mask_16_ex(0xbf00, 0x4000, it_t1, 0x0000, 0x000f, 0, 0); }
135885.c
/* This file is part of The New Aspell * Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL * license version 2.0 or 2.1. You should have received a copy of the * LGPL license along with this library if you did not you can find it * at http://www.gnu.org/. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "aspell.h" int main(int argc, const char *argv[]) { AspellConfig * config; AspellDictInfoList * dlist; AspellDictInfoEnumeration * dels; const AspellDictInfo * entry; config = new_aspell_config(); /* the returned pointer should _not_ need to be deleted */ dlist = get_aspell_dict_info_list(config); /* config is no longer needed */ delete_aspell_config(config); dels = aspell_dict_info_list_elements(dlist); printf("%-30s%-8s%-20s%-6s%-10s\n", "NAME", "CODE", "JARGON", "SIZE", "MODULE"); while ( (entry = aspell_dict_info_enumeration_next(dels)) != 0) { printf("%-30s%-8s%-20s%-6s%-10s\n", entry->name, entry->code, entry->jargon, entry->size_str, entry->module->name); } delete_aspell_dict_info_enumeration(dels); return 0; }
434350.c
// SPDX-License-Identifier: GPL-2.0-only /* * i.MX6 OCOTP fusebox driver * * Copyright (c) 2015 Pengutronix, Philipp Zabel <[email protected]> * * Based on the barebox ocotp driver, * Copyright (c) 2010 Baruch Siach <[email protected]>, * Orex Computed Radiography * * Write support based on the fsl_otp driver, * Copyright (C) 2010-2013 Freescale Semiconductor, Inc */ #include <linux/clk.h> #include <linux/device.h> #include <linux/io.h> #include <linux/module.h> #include <linux/nvmem-provider.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/delay.h> #define IMX_OCOTP_OFFSET_B0W0 0x400 /* Offset from base address of the * OTP Bank0 Word0 */ #define IMX_OCOTP_OFFSET_PER_WORD 0x10 /* Offset between the start addr * of two consecutive OTP words. */ #define IMX_OCOTP_ADDR_CTRL 0x0000 #define IMX_OCOTP_ADDR_CTRL_SET 0x0004 #define IMX_OCOTP_ADDR_CTRL_CLR 0x0008 #define IMX_OCOTP_ADDR_TIMING 0x0010 #define IMX_OCOTP_ADDR_DATA0 0x0020 #define IMX_OCOTP_ADDR_DATA1 0x0030 #define IMX_OCOTP_ADDR_DATA2 0x0040 #define IMX_OCOTP_ADDR_DATA3 0x0050 #define IMX_OCOTP_BM_CTRL_ADDR 0x000000FF #define IMX_OCOTP_BM_CTRL_BUSY 0x00000100 #define IMX_OCOTP_BM_CTRL_ERROR 0x00000200 #define IMX_OCOTP_BM_CTRL_REL_SHADOWS 0x00000400 #define TIMING_STROBE_PROG_US 10 /* Min time to blow a fuse */ #define TIMING_STROBE_READ_NS 37 /* Min time before read */ #define TIMING_RELAX_NS 17 #define DEF_FSOURCE 1001 /* > 1000 ns */ #define DEF_STROBE_PROG 10000 /* IPG clocks */ #define IMX_OCOTP_WR_UNLOCK 0x3E770000 #define IMX_OCOTP_READ_LOCKED_VAL 0xBADABADA static DEFINE_MUTEX(ocotp_mutex); struct ocotp_priv { struct device *dev; struct clk *clk; void __iomem *base; const struct ocotp_params *params; struct nvmem_config *config; }; struct ocotp_params { unsigned int nregs; unsigned int bank_address_words; void (*set_timing)(struct ocotp_priv *priv); }; static int imx_ocotp_wait_for_busy(void __iomem *base, u32 flags) { int count; u32 c, mask; mask = IMX_OCOTP_BM_CTRL_BUSY | IMX_OCOTP_BM_CTRL_ERROR | flags; for (count = 10000; count >= 0; count--) { c = readl(base + IMX_OCOTP_ADDR_CTRL); if (!(c & mask)) break; cpu_relax(); } if (count < 0) { /* HW_OCOTP_CTRL[ERROR] will be set under the following * conditions: * - A write is performed to a shadow register during a shadow * reload (essentially, while HW_OCOTP_CTRL[RELOAD_SHADOWS] is * set. In addition, the contents of the shadow register shall * not be updated. * - A write is performed to a shadow register which has been * locked. * - A read is performed to from a shadow register which has * been read locked. * - A program is performed to a fuse word which has been locked * - A read is performed to from a fuse word which has been read * locked. */ if (c & IMX_OCOTP_BM_CTRL_ERROR) return -EPERM; return -ETIMEDOUT; } return 0; } static void imx_ocotp_clr_err_if_set(void __iomem *base) { u32 c; c = readl(base + IMX_OCOTP_ADDR_CTRL); if (!(c & IMX_OCOTP_BM_CTRL_ERROR)) return; writel(IMX_OCOTP_BM_CTRL_ERROR, base + IMX_OCOTP_ADDR_CTRL_CLR); } static int imx_ocotp_read(void *context, unsigned int offset, void *val, size_t bytes) { struct ocotp_priv *priv = context; unsigned int count; u32 *buf = val; int i, ret; u32 index; index = offset >> 2; count = bytes >> 2; if (count > (priv->params->nregs - index)) count = priv->params->nregs - index; mutex_lock(&ocotp_mutex); ret = clk_prepare_enable(priv->clk); if (ret < 0) { mutex_unlock(&ocotp_mutex); dev_err(priv->dev, "failed to prepare/enable ocotp clk\n"); return ret; } ret = imx_ocotp_wait_for_busy(priv->base, 0); if (ret < 0) { dev_err(priv->dev, "timeout during read setup\n"); goto read_end; } for (i = index; i < (index + count); i++) { *buf++ = readl(priv->base + IMX_OCOTP_OFFSET_B0W0 + i * IMX_OCOTP_OFFSET_PER_WORD); /* 47.3.1.2 * For "read locked" registers 0xBADABADA will be returned and * HW_OCOTP_CTRL[ERROR] will be set. It must be cleared by * software before any new write, read or reload access can be * issued */ if (*(buf - 1) == IMX_OCOTP_READ_LOCKED_VAL) imx_ocotp_clr_err_if_set(priv->base); } ret = 0; read_end: clk_disable_unprepare(priv->clk); mutex_unlock(&ocotp_mutex); return ret; } static void imx_ocotp_set_imx6_timing(struct ocotp_priv *priv) { unsigned long clk_rate = 0; unsigned long strobe_read, relax, strobe_prog; u32 timing = 0; /* 47.3.1.3.1 * Program HW_OCOTP_TIMING[STROBE_PROG] and HW_OCOTP_TIMING[RELAX] * fields with timing values to match the current frequency of the * ipg_clk. OTP writes will work at maximum bus frequencies as long * as the HW_OCOTP_TIMING parameters are set correctly. * * Note: there are minimum timings required to ensure an OTP fuse burns * correctly that are independent of the ipg_clk. Those values are not * formally documented anywhere however, working from the minimum * timings given in u-boot we can say: * * - Minimum STROBE_PROG time is 10 microseconds. Intuitively 10 * microseconds feels about right as representative of a minimum time * to physically burn out a fuse. * * - Minimum STROBE_READ i.e. the time to wait post OTP fuse burn before * performing another read is 37 nanoseconds * * - Minimum RELAX timing is 17 nanoseconds. This final RELAX minimum * timing is not entirely clear the documentation says "This * count value specifies the time to add to all default timing * parameters other than the Tpgm and Trd. It is given in number * of ipg_clk periods." where Tpgm and Trd refer to STROBE_PROG * and STROBE_READ respectively. What the other timing parameters * are though, is not specified. Experience shows a zero RELAX * value will mess up a re-load of the shadow registers post OTP * burn. */ clk_rate = clk_get_rate(priv->clk); relax = DIV_ROUND_UP(clk_rate * TIMING_RELAX_NS, 1000000000) - 1; strobe_read = DIV_ROUND_UP(clk_rate * TIMING_STROBE_READ_NS, 1000000000); strobe_read += 2 * (relax + 1) - 1; strobe_prog = DIV_ROUND_CLOSEST(clk_rate * TIMING_STROBE_PROG_US, 1000000); strobe_prog += 2 * (relax + 1) - 1; timing = readl(priv->base + IMX_OCOTP_ADDR_TIMING) & 0x0FC00000; timing |= strobe_prog & 0x00000FFF; timing |= (relax << 12) & 0x0000F000; timing |= (strobe_read << 16) & 0x003F0000; writel(timing, priv->base + IMX_OCOTP_ADDR_TIMING); } static void imx_ocotp_set_imx7_timing(struct ocotp_priv *priv) { unsigned long clk_rate = 0; u64 fsource, strobe_prog; u32 timing = 0; /* i.MX 7Solo Applications Processor Reference Manual, Rev. 0.1 * 6.4.3.3 */ clk_rate = clk_get_rate(priv->clk); fsource = DIV_ROUND_UP_ULL((u64)clk_rate * DEF_FSOURCE, NSEC_PER_SEC) + 1; strobe_prog = DIV_ROUND_CLOSEST_ULL((u64)clk_rate * DEF_STROBE_PROG, NSEC_PER_SEC) + 1; timing = strobe_prog & 0x00000FFF; timing |= (fsource << 12) & 0x000FF000; writel(timing, priv->base + IMX_OCOTP_ADDR_TIMING); } static int imx_ocotp_write(void *context, unsigned int offset, void *val, size_t bytes) { struct ocotp_priv *priv = context; u32 *buf = val; int ret; u32 ctrl; u8 waddr; u8 word = 0; /* allow only writing one complete OTP word at a time */ if ((bytes != priv->config->word_size) || (offset % priv->config->word_size)) return -EINVAL; mutex_lock(&ocotp_mutex); ret = clk_prepare_enable(priv->clk); if (ret < 0) { mutex_unlock(&ocotp_mutex); dev_err(priv->dev, "failed to prepare/enable ocotp clk\n"); return ret; } /* Setup the write timing values */ priv->params->set_timing(priv); /* 47.3.1.3.2 * Check that HW_OCOTP_CTRL[BUSY] and HW_OCOTP_CTRL[ERROR] are clear. * Overlapped accesses are not supported by the controller. Any pending * write or reload must be completed before a write access can be * requested. */ ret = imx_ocotp_wait_for_busy(priv->base, 0); if (ret < 0) { dev_err(priv->dev, "timeout during timing setup\n"); goto write_end; } /* 47.3.1.3.3 * Write the requested address to HW_OCOTP_CTRL[ADDR] and program the * unlock code into HW_OCOTP_CTRL[WR_UNLOCK]. This must be programmed * for each write access. The lock code is documented in the register * description. Both the unlock code and address can be written in the * same operation. */ if (priv->params->bank_address_words != 0) { /* * In banked/i.MX7 mode the OTP register bank goes into waddr * see i.MX 7Solo Applications Processor Reference Manual, Rev. * 0.1 section 6.4.3.1 */ offset = offset / priv->config->word_size; waddr = offset / priv->params->bank_address_words; word = offset & (priv->params->bank_address_words - 1); } else { /* * Non-banked i.MX6 mode. * OTP write/read address specifies one of 128 word address * locations */ waddr = offset / 4; } ctrl = readl(priv->base + IMX_OCOTP_ADDR_CTRL); ctrl &= ~IMX_OCOTP_BM_CTRL_ADDR; ctrl |= waddr & IMX_OCOTP_BM_CTRL_ADDR; ctrl |= IMX_OCOTP_WR_UNLOCK; writel(ctrl, priv->base + IMX_OCOTP_ADDR_CTRL); /* 47.3.1.3.4 * Write the data to the HW_OCOTP_DATA register. This will automatically * set HW_OCOTP_CTRL[BUSY] and clear HW_OCOTP_CTRL[WR_UNLOCK]. To * protect programming same OTP bit twice, before program OCOTP will * automatically read fuse value in OTP and use read value to mask * program data. The controller will use masked program data to program * a 32-bit word in the OTP per the address in HW_OCOTP_CTRL[ADDR]. Bit * fields with 1's will result in that OTP bit being programmed. Bit * fields with 0's will be ignored. At the same time that the write is * accepted, the controller makes an internal copy of * HW_OCOTP_CTRL[ADDR] which cannot be updated until the next write * sequence is initiated. This copy guarantees that erroneous writes to * HW_OCOTP_CTRL[ADDR] will not affect an active write operation. It * should also be noted that during the programming HW_OCOTP_DATA will * shift right (with zero fill). This shifting is required to program * the OTP serially. During the write operation, HW_OCOTP_DATA cannot be * modified. * Note: on i.MX7 there are four data fields to write for banked write * with the fuse blowing operation only taking place after data0 * has been written. This is why data0 must always be the last * register written. */ if (priv->params->bank_address_words != 0) { /* Banked/i.MX7 mode */ switch (word) { case 0: writel(0, priv->base + IMX_OCOTP_ADDR_DATA1); writel(0, priv->base + IMX_OCOTP_ADDR_DATA2); writel(0, priv->base + IMX_OCOTP_ADDR_DATA3); writel(*buf, priv->base + IMX_OCOTP_ADDR_DATA0); break; case 1: writel(*buf, priv->base + IMX_OCOTP_ADDR_DATA1); writel(0, priv->base + IMX_OCOTP_ADDR_DATA2); writel(0, priv->base + IMX_OCOTP_ADDR_DATA3); writel(0, priv->base + IMX_OCOTP_ADDR_DATA0); break; case 2: writel(0, priv->base + IMX_OCOTP_ADDR_DATA1); writel(*buf, priv->base + IMX_OCOTP_ADDR_DATA2); writel(0, priv->base + IMX_OCOTP_ADDR_DATA3); writel(0, priv->base + IMX_OCOTP_ADDR_DATA0); break; case 3: writel(0, priv->base + IMX_OCOTP_ADDR_DATA1); writel(0, priv->base + IMX_OCOTP_ADDR_DATA2); writel(*buf, priv->base + IMX_OCOTP_ADDR_DATA3); writel(0, priv->base + IMX_OCOTP_ADDR_DATA0); break; } } else { /* Non-banked i.MX6 mode */ writel(*buf, priv->base + IMX_OCOTP_ADDR_DATA0); } /* 47.4.1.4.5 * Once complete, the controller will clear BUSY. A write request to a * protected or locked region will result in no OTP access and no * setting of HW_OCOTP_CTRL[BUSY]. In addition HW_OCOTP_CTRL[ERROR] will * be set. It must be cleared by software before any new write access * can be issued. */ ret = imx_ocotp_wait_for_busy(priv->base, 0); if (ret < 0) { if (ret == -EPERM) { dev_err(priv->dev, "failed write to locked region"); imx_ocotp_clr_err_if_set(priv->base); } else { dev_err(priv->dev, "timeout during data write\n"); } goto write_end; } /* 47.3.1.4 * Write Postamble: Due to internal electrical characteristics of the * OTP during writes, all OTP operations following a write must be * separated by 2 us after the clearing of HW_OCOTP_CTRL_BUSY following * the write. */ udelay(2); /* reload all shadow registers */ writel(IMX_OCOTP_BM_CTRL_REL_SHADOWS, priv->base + IMX_OCOTP_ADDR_CTRL_SET); ret = imx_ocotp_wait_for_busy(priv->base, IMX_OCOTP_BM_CTRL_REL_SHADOWS); if (ret < 0) { dev_err(priv->dev, "timeout during shadow register reload\n"); goto write_end; } write_end: clk_disable_unprepare(priv->clk); mutex_unlock(&ocotp_mutex); if (ret < 0) return ret; return bytes; } static struct nvmem_config imx_ocotp_nvmem_config = { .name = "imx-ocotp", .read_only = false, .word_size = 4, .stride = 4, .reg_read = imx_ocotp_read, .reg_write = imx_ocotp_write, }; static const struct ocotp_params imx6q_params = { .nregs = 128, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx6sl_params = { .nregs = 64, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx6sll_params = { .nregs = 128, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx6sx_params = { .nregs = 128, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx6ul_params = { .nregs = 128, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx6ull_params = { .nregs = 64, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx7d_params = { .nregs = 64, .bank_address_words = 4, .set_timing = imx_ocotp_set_imx7_timing, }; static const struct ocotp_params imx7ulp_params = { .nregs = 256, .bank_address_words = 0, }; static const struct ocotp_params imx8mq_params = { .nregs = 256, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx8mm_params = { .nregs = 256, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct ocotp_params imx8mn_params = { .nregs = 256, .bank_address_words = 0, .set_timing = imx_ocotp_set_imx6_timing, }; static const struct of_device_id imx_ocotp_dt_ids[] = { { .compatible = "fsl,imx6q-ocotp", .data = &imx6q_params }, { .compatible = "fsl,imx6sl-ocotp", .data = &imx6sl_params }, { .compatible = "fsl,imx6sx-ocotp", .data = &imx6sx_params }, { .compatible = "fsl,imx6ul-ocotp", .data = &imx6ul_params }, { .compatible = "fsl,imx6ull-ocotp", .data = &imx6ull_params }, { .compatible = "fsl,imx7d-ocotp", .data = &imx7d_params }, { .compatible = "fsl,imx6sll-ocotp", .data = &imx6sll_params }, { .compatible = "fsl,imx7ulp-ocotp", .data = &imx7ulp_params }, { .compatible = "fsl,imx8mq-ocotp", .data = &imx8mq_params }, { .compatible = "fsl,imx8mm-ocotp", .data = &imx8mm_params }, { .compatible = "fsl,imx8mn-ocotp", .data = &imx8mn_params }, { }, }; MODULE_DEVICE_TABLE(of, imx_ocotp_dt_ids); static int imx_ocotp_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct ocotp_priv *priv; struct nvmem_device *nvmem; priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->dev = dev; priv->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(priv->base)) return PTR_ERR(priv->base); priv->clk = devm_clk_get(dev, NULL); if (IS_ERR(priv->clk)) return PTR_ERR(priv->clk); priv->params = of_device_get_match_data(&pdev->dev); imx_ocotp_nvmem_config.size = 4 * priv->params->nregs; imx_ocotp_nvmem_config.dev = dev; imx_ocotp_nvmem_config.priv = priv; priv->config = &imx_ocotp_nvmem_config; nvmem = devm_nvmem_register(dev, &imx_ocotp_nvmem_config); return PTR_ERR_OR_ZERO(nvmem); } static struct platform_driver imx_ocotp_driver = { .probe = imx_ocotp_probe, .driver = { .name = "imx_ocotp", .of_match_table = imx_ocotp_dt_ids, }, }; module_platform_driver(imx_ocotp_driver); MODULE_AUTHOR("Philipp Zabel <[email protected]>"); MODULE_DESCRIPTION("i.MX6/i.MX7 OCOTP fuse box driver"); MODULE_LICENSE("GPL v2");
674102.c
#include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
653644.c
/* * Copyright (C) 2002 Nuno M. Rodrigues. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND NUNO M. RODRIGUES * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* $Id: bdb.c,v 1.2 2011/10/11 00:09:02 each Exp $ */ /* * BIND 9.1.x simple database driver * implementation, using Berkeley DB. */ #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <isc/file.h> #include <isc/log.h> #include <isc/lib.h> #include <isc/mem.h> #include <isc/msgs.h> #include <isc/msgcat.h> #include <isc/region.h> #include <isc/result.h> #include <isc/types.h> #include <isc/util.h> #include <dns/sdb.h> #include <dns/log.h> #include <dns/lib.h> #include <dns/ttl.h> #include <named/bdb.h> #include <named/globals.h> #include <named/config.h> #include <db.h> #define DRIVERNAME "bdb" static dns_sdbimplementation_t *bdb_imp; static isc_result_t bdb_create(const char *zone, int argc, char **argv, void *unused, void **dbdata) { int ret; UNUSED(zone); UNUSED(unused); if (argc < 1) return ISC_R_FAILURE; /* database path must be given */ if (db_create((DB **)dbdata, NULL, 0) != 0) { /* * XXX Should use dns_msgcat et al * but seems to be unavailable. */ isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_CRITICAL, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FATALERROR, "db_create"); return ISC_R_FAILURE; } if (isc_file_exists(*argv) != ISC_TRUE) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_CRITICAL, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FATALERROR, "isc_file_exists: %s", *argv); return ISC_R_FAILURE; } if ((ret = (*(DB **)dbdata)->open(*(DB **)dbdata, *argv, NULL, DB_HASH, DB_RDONLY, 0)) != 0) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_CRITICAL, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FATALERROR, "DB->open: %s", db_strerror(ret)); return ISC_R_FAILURE; } return ISC_R_SUCCESS; } static isc_result_t #ifdef DNS_CLIENTINFO_VERSION bdb_lookup(const char *zone, const char *name, void *dbdata, dns_sdblookup_t *l, dns_clientinfomethods_t *methods, dns_clientinfo_t *clientinfo,void *source_ip,dns_rdatatype_t type, void *zone_data) #else bdb_lookup(const char *zone, const char *name, void *dbdata, dns_sdblookup_t *l,,void *source_ip,dns_rdatatype_t type, void *zone_data) #endif /* DNS_CLIENTINFO_VERSION */ { int ret; char *type, *rdata; dns_ttl_t ttl; isc_consttextregion_t ttltext; DBC *c; DBT key, data; UNUSED(zone); #ifdef DNS_CLIENTINFO_VERSION UNUSED(methods); UNUSED(clientinfo); #endif /* DNS_CLIENTINFO_VERSION */ UNUSED(source_ip); UNUSED(type); UNUSED(zone_data); if ((ret = ((DB *)dbdata)->cursor((DB *)dbdata, NULL, &c, 0)) != 0) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "DB->cursor: %s", db_strerror(ret)); return ISC_R_FAILURE; } memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); (const char *)key.data = name; key.size = strlen(name); ret = c->c_get(c, &key, &data, DB_SET); while (ret == 0) { ((char *)key.data)[key.size] = 0; ((char *)data.data)[data.size] = 0; ttltext.base = strtok((char *)data.data, " "); ttltext.length = strlen(ttltext.base); dns_ttl_fromtext((isc_textregion_t *)&ttltext, &ttl); type = strtok(NULL, " "); rdata = type + strlen(type) + 1; if (dns_sdb_putrr(l, type, ttl, rdata) != ISC_R_SUCCESS) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "dns_sdb_putrr"); return ISC_R_FAILURE; } ret = c->c_get(c, &key, &data, DB_NEXT_DUP); } c->c_close(c); return ISC_R_SUCCESS; } static isc_result_t bdb_allnodes(const char *zone, void *dbdata, dns_sdballnodes_t *n) { int ret; char *type, *rdata; dns_ttl_t ttl; isc_consttextregion_t ttltext; DBC *c; DBT key, data; UNUSED(zone); UNUSED(source_ip); UNUSED(type); if ((ret = ((DB *)dbdata)->cursor((DB *)dbdata, NULL, &c, 0)) != 0) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "DB->cursor: %s", db_strerror(ret)); return ISC_R_FAILURE; } memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); while (c->c_get(c, &key, &data, DB_NEXT) == 0) { ((char *)key.data)[key.size] = 0; ((char *)data.data)[data.size] = 0; ttltext.base = strtok((char *)data.data, " "); ttltext.length = strlen(ttltext.base); dns_ttl_fromtext((isc_textregion_t *)&ttltext, &ttl); type = strtok(NULL, " "); rdata = type + strlen(type) + 1; if (dns_sdb_putnamedrr(n, key.data, type, ttl, rdata) != ISC_R_SUCCESS) { isc_log_iwrite(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_SDB, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "dns_sdb_putnamedrr"); return ISC_R_FAILURE; } } c->c_close(c); return ISC_R_SUCCESS; } static isc_result_t bdb_destroy(const char *zone, void *unused, void **dbdata, void *zone_data) { UNUSED(zone); UNUSED(unused); UNUSED(zone_data); (*(DB **)dbdata)->close(*(DB **)dbdata, 0); return ISC_R_SUCCESS; } isc_result_t bdb_init(void) { static dns_sdbmethods_t bdb_methods = { bdb_lookup, NULL, bdb_allnodes, bdb_create, bdb_destroy, NULL, /* lookup2 */ NULL /*zonedata for Intelligent DNS*/ }; return dns_sdb_register(DRIVERNAME, &bdb_methods, NULL, 0, ns_g_mctx, &bdb_imp); } void bdb_clear(void) { if (bdb_imp != NULL) dns_sdb_unregister(&bdb_imp); }
22917.c
#include "Configuration.h" // #define GYRO_SAMP_FRQ 125 #define GYRO_CUTOFF_FRQ 20 #define ACC_SAMP_FRQ 125 #define ACC_CUTOFF_FRQ 20 // U8 mpu_buffer[14] = {0}; U8 mpu_temperature[2] = {0}; // struct IMU_DATA_PARAMS acc_params; struct IMU_DATA_RAW acc_raw; struct LowPassFilter2p acc_filter_x; struct LowPassFilter2p acc_filter_y; struct LowPassFilter2p acc_filter_z; struct IMU_DATA_FILTERED acc_filtered; // // struct IMU_DATA_PARAMS gyro_params; struct IMU_DATA_RAW gyro_raw; struct LowPassFilter2p gyro_filter_x; struct LowPassFilter2p gyro_filter_y; struct LowPassFilter2p gyro_filter_z; struct IMU_DATA_FILTERED gyro_filtered; // U16 MpuFiFoPi = 0; U16 MpuFiFoPo = 0; struct IMU_DATA_RAW gyro_buffer[MPU_FIFO_LEN]; struct IMU_DATA_RAW acc_buffer[MPU_FIFO_LEN]; // U8 Is_RecordIMUData = true; // Initialize MPU6000 void MPU6000_Init(void) { U8 status; gyro_params.range_scale = 2000.0f / 180.0 * M_PI / 32768.0f; gyro_params.x_offset = 15.0f; gyro_params.y_offset = 7.0f; gyro_params.z_offset = -1.0f; gyro_params.x_scale = 1.0f; gyro_params.y_scale = 1.0f; gyro_params.z_scale = 1.0f; // -2156/2103 -2122/2052 -2344/2096 // -2099/2051 -2096/2036 -2168/2011 acc_params.range_scale = 16.0f * M_G / 32768.0f; //acc_params.range_scale = 1.0f * M_G; acc_params.x_offset = -24.0f; acc_params.y_offset = -30.0f; acc_params.z_offset = -29.0f; acc_params.x_scale = 1.0f; acc_params.y_scale = 1.0f; acc_params.z_scale = 1.0f; //acc_params.x_scale = 2.0f / (2051.0f + 2099.0f); //acc_params.y_scale = 2.0f / (2036.0f + 2096.0f); //acc_params.z_scale = 2.0f / (2011.0f + 2168.0f); LowPassFilter2p_Init(&gyro_filter_x, GYRO_SAMP_FRQ, GYRO_CUTOFF_FRQ); LowPassFilter2p_Init(&gyro_filter_y, GYRO_SAMP_FRQ, GYRO_CUTOFF_FRQ); LowPassFilter2p_Init(&gyro_filter_z, GYRO_SAMP_FRQ, GYRO_CUTOFF_FRQ); LowPassFilter2p_Init(&acc_filter_x, ACC_SAMP_FRQ, ACC_CUTOFF_FRQ); LowPassFilter2p_Init(&acc_filter_y, ACC_SAMP_FRQ, ACC_CUTOFF_FRQ); LowPassFilter2p_Init(&acc_filter_z, ACC_SAMP_FRQ, ACC_CUTOFF_FRQ); SPI1_HighSpeed(DISABLE); //Delayms(100); // 16bits gyroscope and acceleration MPU6000_WriteReg(MPU6000_REG_PWR_MGMT_1, 0x03); // PPL with gyroscope z clock Delayms(2000); MPU6000_WriteReg(MPU6000_REG_SIGNAL_PATH_RESET, 0x07); // reset all signal path Delayms(2000); //MPU6000_WriteReg(MPU6000_REG_SMPLRT_DIV, 15); // sample rate = output rate / (div + 1), 8k / (15+1) = 500Hz //MPU6000_WriteReg(MPU6000_REG_SMPLRT_DIV, 39); // sample rate = output rate / (div + 1), 8k / (39+1) = 200Hz MPU6000_WriteReg(MPU6000_REG_SMPLRT_DIV, 7); // sample rate = output rate / (div + 1), 1k / (7+1) = 125Hz //MPU6000_WriteReg(MPU6000_REG_SMPLRT_DIV, 4); // sample rate = output rate / (div + 1), 1k / (4+1) = 200Hz MPU6000_WriteReg(MPU6000_REG_CONFIG, BITS_DLPF_CFG_42HZ & BITS_DLPF_CFG_MASK); // DLPF 42HZ, gyroscope output rate 1khz MPU6000_WriteReg(MPU6000_REG_GYRO_CONFIG, 0x18); // +-2000 deg/sec, 16bits, -32768~32767 MPU6000_WriteReg(MPU6000_REG_ACCEL_CONFIG, 0x18); // +-16g, 16bits, -32768~32767 // MPU6000_WriteReg(MPU6000_REG_INT_PIN_CFG, 0xD0); // active low, open-drain, 50us pulse, clear by any read operation MPU6000_WriteReg(MPU6000_REG_INT_ENABLE, 0x01); // enable data ready interrupt //status = MPU6000_ReadReg(MPU6000_REG_INT_STATUS); status = MPU6000_ReadReg(MPU6000_REG_SMPLRT_DIV); SPI1_HighSpeed(ENABLE); //Delayms(100); #if defined (CONFIG_DEBUG) printf("\r\n Initializing MPU6000 ... Done div = %d", status); U1Printf(); #endif } // Read acceleration result void MPU6000_ReadResult(void) { U32 stamp = getTimeStamp(); S16 ax, ay, az, gx, gy, gz; float x, y, z; // ax, ay, az, T, gx, gy, gz MPU6000_ReadBuffer(MPU6000_REG_RESULT_FIRST, mpu_buffer, 14); ax = (mpu_buffer[0] << 8) + mpu_buffer[1]; ay = (mpu_buffer[2] << 8) + mpu_buffer[3]; az = (mpu_buffer[4] << 8) + mpu_buffer[5]; mpu_temperature[0] = mpu_buffer[6]; mpu_temperature[1] = mpu_buffer[7]; gx = (mpu_buffer[8] << 8) + mpu_buffer[9]; gy = (mpu_buffer[10] << 8) + mpu_buffer[11]; gz = (mpu_buffer[12] << 8) + mpu_buffer[13]; // gyroscope data // adjust coordinate gyro_raw.x = gy; gyro_raw.y = ((gx == -32768) ? 32767 : -gx); gyro_raw.z = gz; //gyro_raw.x = ((gy == -32768) ? 32767 : -gy); //gyro_raw.y = ((gx == -32768) ? 32767 : -gx); //gyro_raw.z = gz; gyro_raw.stamp = stamp; // read real value x = (gyro_raw.x - gyro_params.x_offset) * gyro_params.range_scale * gyro_params.x_scale; y = (gyro_raw.y - gyro_params.y_offset) * gyro_params.range_scale * gyro_params.y_scale; z = (gyro_raw.z - gyro_params.z_offset) * gyro_params.range_scale * gyro_params.z_scale; // // 2nd order low pass filter gyro_filtered.x = LowPassFilter2p_apply(&gyro_filter_x, x); gyro_filtered.y = LowPassFilter2p_apply(&gyro_filter_y, y); gyro_filtered.z = LowPassFilter2p_apply(&gyro_filter_z, z); gyro_filtered.stamp = stamp; // acceleration // adjust coordinate acc_raw.x = ay; acc_raw.y = ((ax == -32768) ? 32767 : -ax); acc_raw.z = az; //acc_raw.x = ay; //acc_raw.y = ax; //acc_raw.z = -az; acc_raw.stamp = stamp; // read real value x = (acc_raw.x - acc_params.x_offset) * acc_params.range_scale * acc_params.x_scale; y = (acc_raw.y - acc_params.y_offset) * acc_params.range_scale * acc_params.y_scale; z = (acc_raw.z - acc_params.z_offset) * acc_params.range_scale * acc_params.z_scale; // // 2nd order low pass filter acc_filtered.x = LowPassFilter2p_apply(&acc_filter_x, x); acc_filtered.y = LowPassFilter2p_apply(&acc_filter_y, y); acc_filtered.z = LowPassFilter2p_apply(&acc_filter_z, z); acc_filtered.stamp = stamp; if(Is_RecordIMUData) { InMpuFiFo(gyro_raw, acc_raw); } } // Write byte void MPU6000_WriteReg(U8 reg, U8 byte) { MPU_Selected(); // select chip Delayms(1); MPU_SPI_RW(MPU_WRITE_REG | reg); // send register address MPU_SPI_RW(byte); // send byte MPU_Deselected(); // deselect chip Delayms(1); } // Read byte U8 MPU6000_ReadReg(U8 reg) { U8 byte; MPU_Selected(); // select chip MPU_SPI_RW(MPU_READ_REG | reg); // send register address byte = MPU_SPI_RW(0xFF); // read byte MPU_Deselected(); // deselect chip return byte; } // Write buffer void MPU6000_WriteBuffer(U8 reg, U8*buffer, U8 num) { MPU_Selected(); // select chip Delayms(1); MPU_SPI_RW(MPU_WRITE_REG | reg); // send register address while(num > 0) { MPU_SPI_RW(*buffer); // send byte buffer++; num --; } MPU_Deselected(); // deselect chip Delayms(1); } // Read buffer void MPU6000_ReadBuffer(U8 reg, U8*buffer, U8 num) { MPU_Selected(); // select chip MPU_SPI_RW(MPU_READ_REG | reg); // send register address while(num > 0) { *buffer = MPU_SPI_RW(0xFF); // read byte buffer++; num--; } MPU_Deselected(); // deselect chip } void InMpuFiFo(struct IMU_DATA_RAW gin, struct IMU_DATA_RAW ain) { gyro_buffer[MpuFiFoPi].x = gin.x; gyro_buffer[MpuFiFoPi].y = gin.y; gyro_buffer[MpuFiFoPi].z = gin.z; gyro_buffer[MpuFiFoPi].stamp = gin.stamp; acc_buffer[MpuFiFoPi].x = ain.x; acc_buffer[MpuFiFoPi].y = ain.y; acc_buffer[MpuFiFoPi].z = ain.z; acc_buffer[MpuFiFoPi].stamp = ain.stamp; MpuFiFoPi = (MpuFiFoPi + 1) % MPU_FIFO_LEN; } U8 OutMpuFiFo(struct IMU_DATA_RAW *gout, struct IMU_DATA_RAW *aout) { if(MpuFiFoPo == MpuFiFoPi) return false; gout->x = gyro_buffer[MpuFiFoPo].x; gout->y = gyro_buffer[MpuFiFoPo].y; gout->z = gyro_buffer[MpuFiFoPo].z; gout->stamp = gyro_buffer[MpuFiFoPo].stamp; aout->x = acc_buffer[MpuFiFoPo].x; aout->y = acc_buffer[MpuFiFoPo].y; aout->z = acc_buffer[MpuFiFoPo].z; aout->stamp = acc_buffer[MpuFiFoPo].stamp; MpuFiFoPo = (MpuFiFoPo + 1) % MPU_FIFO_LEN; return true; } U16 GetMpuFiFoSize(void) { if(MpuFiFoPi < MpuFiFoPo) return (MpuFiFoPi + MPU_FIFO_LEN - MpuFiFoPo); else return (MpuFiFoPi - MpuFiFoPo); } void ClearMpuFiFo(void) { MpuFiFoPo = MpuFiFoPi; } U8 IsMpuFiFoEmpty(void) { return (MpuFiFoPo == MpuFiFoPi); }
555967.c
/* * Placeholder for the Recv path functions * * Copyright (c) 2020 Virtuozzo International GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met : * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and / or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of their contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "precomp.h" #include "viosock.h" #if defined(EVENT_TRACING) #include "Rx.tmh" #endif #define VIOSOCK_DMA_RX_PAGES 1 //contiguous buffer #define VIOSOCK_BYTES_TO_MERGE 128 //max bytes to merge with prev buffer #define VIOSOCK_CB_ENTRIES(n) ((n)+(n>>1)) //default chained buffer queue size //Chained Buffer entry typedef struct _VIOSOCK_RX_CB { union { SINGLE_LIST_ENTRY FreeListEntry; LIST_ENTRY ListEntry; //Request buffer list }; PVOID BufferVA; //common buffer of VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE bytes PHYSICAL_ADDRESS BufferPA; //common buffer PA ULONG DataLen; //Valid data len (pkt.header.len) WDFREQUEST Request; //Write request for loopback WDFMEMORY Memory; }VIOSOCK_RX_CB, *PVIOSOCK_RX_CB; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(VIOSOCK_RX_CB, GetRequestRxCb); typedef struct _VIOSOCK_RX_PKT { VIRTIO_VSOCK_HDR Header; PVIOSOCK_RX_CB Buffer; //Chained buffer union { BYTE IndirectDescs[SIZE_OF_SINGLE_INDIRECT_DESC * (1 + VIOSOCK_DMA_RX_PAGES)]; //Header + buffer SINGLE_LIST_ENTRY ListEntry; }; }VIOSOCK_RX_PKT, *PVIOSOCK_RX_PKT; typedef union _VIOSOCK_RX_CONTEXT { struct { LONGLONG Timeout; //100ns ULONG Counter; }; struct { LIST_ENTRY ListEntry; WDFREQUEST ThisRequest; }; }VIOSOCK_RX_CONTEXT, *PVIOSOCK_RX_CONTEXT; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(VIOSOCK_RX_CONTEXT, GetRequestRxContext); BOOLEAN VIOSockRxCbInit( IN PDEVICE_CONTEXT pContext ); VOID VIOSockRxCbCleanup( IN PDEVICE_CONTEXT pContext ); EVT_WDF_IO_QUEUE_IO_READ VIOSockRead; EVT_WDF_IO_QUEUE_IO_DEFAULT VIOSockReadSocketIoDefault; EVT_WDF_IO_QUEUE_IO_STOP VIOSockReadSocketIoStop; EVT_WDF_REQUEST_CANCEL VIOSockRxRequestCancelCb; EVT_WDF_TIMER VIOSockReadTimerFunc; #ifdef ALLOC_PRAGMA #pragma alloc_text (PAGE, VIOSockRxCbInit) #pragma alloc_text (PAGE, VIOSockRxCbCleanup) #pragma alloc_text (PAGE, VIOSockRxVqInit) #pragma alloc_text (PAGE, VIOSockReadQueueInit) #pragma alloc_text (PAGE, VIOSockReadSocketQueueInit) #endif ////////////////////////////////////////////////////////////////////////// #define VIOSockRxCbPush(c,b) PushEntryList(&(c)->RxCbBuffers, &(b)->FreeListEntry) __inline VOID VIOSockRxCbPushLocked( PDEVICE_CONTEXT pContext, PVIOSOCK_RX_CB pCb ) { WdfSpinLockAcquire(pContext->RxLock); VIOSockRxCbPush(pContext, pCb); WdfSpinLockRelease(pContext->RxLock); } __inline PVIOSOCK_RX_CB VIOSockRxCbPop( IN PDEVICE_CONTEXT pContext ) { PSINGLE_LIST_ENTRY pListEntry = PopEntryList(&pContext->RxCbBuffers); if (pListEntry) { return CONTAINING_RECORD(pListEntry, VIOSOCK_RX_CB, FreeListEntry); } return NULL; } __inline VOID VIOSockRxCbFree( IN PDEVICE_CONTEXT pContext, IN PVIOSOCK_RX_CB pCb ) { ASSERT(pCb && pCb->BufferVA); ASSERT(pCb->BufferPA.QuadPart && pCb->Request == WDF_NO_HANDLE); if (pCb->BufferPA.QuadPart) VirtIOWdfDeviceFreeDmaMemory(&pContext->VDevice.VIODevice, pCb->BufferVA); WdfObjectDelete(pCb->Memory); } static PVIOSOCK_RX_CB VIOSockRxCbAdd( IN PDEVICE_CONTEXT pContext ) { NTSTATUS status; PVIOSOCK_RX_CB pCb = NULL; WDFMEMORY Memory; status = WdfMemoryCreateFromLookaside(pContext->RxCbBufferMemoryList, &Memory); if (NT_SUCCESS(status)) { pCb = WdfMemoryGetBuffer(Memory, NULL); RtlZeroMemory(pCb, sizeof(*pCb)); pCb->Memory = Memory; pCb->BufferVA = VirtIOWdfDeviceAllocDmaMemory(&pContext->VDevice.VIODevice, VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE, VIOSOCK_DRIVER_MEMORY_TAG); if (!pCb->BufferVA) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfDeviceAllocDmaMemory(%u bytes for Rx buffer) failed\n", VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE); WdfObjectDelete(pCb->Memory); pCb = NULL; } else { pCb->BufferPA = VirtIOWdfDeviceGetPhysicalAddress(&pContext->VDevice.VIODevice, pCb->BufferVA); ASSERT(pCb->BufferPA.QuadPart); if (!pCb->BufferPA.QuadPart) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfDeviceGetPhysicalAddress failed\n"); VIOSockRxCbFree(pContext, pCb); pCb = NULL; } else { VIOSockRxCbPushLocked(pContext, pCb); } } } else { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "WdfMemoryCreateFromLookaside failed: 0x%x\n", status); } return pCb; } static PVIOSOCK_RX_CB VIOSockRxCbEntryForRequest( IN PDEVICE_CONTEXT pContext, IN WDFREQUEST Request, IN ULONG Length ) { NTSTATUS status; WDF_OBJECT_ATTRIBUTES attributes; PVIOSOCK_RX_CB pCb = NULL; ASSERT(Request != WDF_NO_HANDLE); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "--> %s\n", __FUNCTION__); WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE( &attributes, VIOSOCK_RX_CB ); status = WdfObjectAllocateContext( Request, &attributes, &pCb ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfObjectAllocateContext failed: 0x%x\n", status); return NULL; } pCb->Memory = WDF_NO_HANDLE; pCb->BufferPA.QuadPart = 0; InitializeListHead(&pCb->ListEntry); status = WdfRequestRetrieveInputBuffer(Request, 0, &pCb->BufferVA, NULL); if (NT_SUCCESS(status)) { pCb->Request = Request; pCb->DataLen = (ULONG)Length; } else { TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestRetrieveOutputBuffer failed: 0x%x\n", status); pCb = NULL; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "<-- %s\n", __FUNCTION__); return pCb; } //- static BOOLEAN VIOSockRxCbInit( IN PDEVICE_CONTEXT pContext ) { ULONG i; BOOLEAN bRes = TRUE; WDF_OBJECT_ATTRIBUTES lockAttributes, memAttributes; NTSTATUS status; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); PAGED_CODE(); pContext->RxCbBuffersNum = VIOSOCK_CB_ENTRIES(pContext->RxPktNum); if (pContext->RxCbBuffersNum < pContext->RxPktNum) pContext->RxCbBuffersNum = pContext->RxPktNum; WDF_OBJECT_ATTRIBUTES_INIT(&memAttributes); memAttributes.ParentObject = pContext->ThisDevice; status = WdfLookasideListCreate(&memAttributes, sizeof(VIOSOCK_RX_CB), NonPagedPoolNx, &memAttributes, VIOSOCK_DRIVER_MEMORY_TAG, &pContext->RxCbBufferMemoryList); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "WdfLookasideListCreate failed: 0x%x\n", status); return FALSE; } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "Initialize chained buffer with %u entries\n", pContext->RxCbBuffersNum); pContext->RxCbBuffers.Next = NULL; for (i = 0; i < pContext->RxCbBuffersNum; ++i) { if (!VIOSockRxCbAdd(pContext)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "VIOSockRxCbAdd failed, cleanup chained buffer\n"); bRes = FALSE; break; } } if (!bRes) VIOSockRxCbCleanup(pContext); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return bRes; } static VOID VIOSockRxCbCleanup( IN PDEVICE_CONTEXT pContext ) { PVIOSOCK_RX_CB pCb; PAGED_CODE(); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); //no need to lock while (pCb = VIOSockRxCbPop(pContext)) { VIOSockRxCbFree(pContext, pCb); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); } ////////////////////////////////////////////////////////////////////////// __inline VOID VIOSockRxPktCleanup( IN PDEVICE_CONTEXT pContext, IN PVIOSOCK_RX_PKT pPkt ) { ASSERT(pPkt); if (pPkt->Buffer) { VIOSockRxCbPush(pContext, pPkt->Buffer); pPkt->Buffer = NULL; } } C_ASSERT((VIOSOCK_DMA_RX_PAGES + 1) == 2); static BOOLEAN VIOSockRxPktInsert( IN PDEVICE_CONTEXT pContext, IN PVIOSOCK_RX_PKT pPkt ) { BOOLEAN bRes = TRUE; VIOSOCK_SG_DESC sg[VIOSOCK_DMA_RX_PAGES + 1]; PHYSICAL_ADDRESS pPKtPA; int ret; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); if (!pPkt->Buffer) { pPkt->Buffer = VIOSockRxCbPop(pContext); if (!pPkt->Buffer) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "VIOSockRxCbPop returns NULL\n"); return FALSE; } } ASSERT(pPkt->Buffer->Request == WDF_NO_HANDLE); pPKtPA.QuadPart = pContext->RxPktPA.QuadPart + (ULONGLONG)((PCHAR)pPkt - (PCHAR)pContext->RxPktVA); sg[0].length = sizeof(VIRTIO_VSOCK_HDR); sg[0].physAddr.QuadPart = pPKtPA.QuadPart + FIELD_OFFSET(VIOSOCK_RX_PKT, Header); sg[1].length = VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE; sg[1].physAddr.QuadPart = pPkt->Buffer->BufferPA.QuadPart; ret = virtqueue_add_buf(pContext->RxVq, sg, 0, 2, pPkt, &pPkt->IndirectDescs, pPKtPA.QuadPart + FIELD_OFFSET(VIOSOCK_RX_PKT, IndirectDescs)); ASSERT(ret >= 0); if (ret < 0) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Error adding buffer to Rx queue (ret = %d)\n", ret); VIOSockRxPktCleanup(pContext, pPkt); return FALSE; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "<-- %s\n", __FUNCTION__); return TRUE; } __inline VOID VIOSockRxPktListProcess( IN PDEVICE_CONTEXT pContext ) { PSINGLE_LIST_ENTRY pListEntry; while (pListEntry = PopEntryList(&pContext->RxPktList)) { PVIOSOCK_RX_PKT pPkt = CONTAINING_RECORD(pListEntry, VIOSOCK_RX_PKT, ListEntry); if (!VIOSockRxPktInsert(pContext, pPkt)) { PushEntryList(&pContext->RxPktList, &pPkt->ListEntry); break; } } } __inline VOID VIOSockRxPktInsertOrPostpone( IN PDEVICE_CONTEXT pContext, IN PVIOSOCK_RX_PKT pPkt ) { bool bNotify = false; WdfSpinLockAcquire(pContext->RxLock); if (!VIOSockRxPktInsert(pContext, pPkt)) { //postpone packet PushEntryList(&pContext->RxPktList, &pPkt->ListEntry); } else { VIOSockRxPktListProcess(pContext); bNotify = virtqueue_kick_prepare(pContext->RxVq); } WdfSpinLockRelease(pContext->RxLock); if (bNotify) virtqueue_notify(pContext->RxVq); } __inline BOOLEAN VIOSockRxPktInc( IN PSOCKET_CONTEXT pSocket, IN ULONG uPktLen ) { if (pSocket->RxBytes + uPktLen > pSocket->buf_alloc) return FALSE; pSocket->RxBytes += uPktLen; return TRUE; } __inline VOID VIOSockRxPktDec( IN PSOCKET_CONTEXT pSocket, IN ULONG uPktLen ) { pSocket->RxBytes -= uPktLen; pSocket->fwd_cnt += uPktLen; } VOID VIOSockRxVqCleanup( IN PDEVICE_CONTEXT pContext ) { PVIOSOCK_RX_PKT pPkt; PSINGLE_LIST_ENTRY pListEntry; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); ASSERT(pContext->RxVq && pContext->RxPktVA); //drain queue WdfSpinLockAcquire(pContext->RxLock); while (pPkt = (PVIOSOCK_RX_PKT)virtqueue_detach_unused_buf(pContext->RxVq)) { VIOSockRxPktCleanup(pContext, pPkt); } while (pListEntry = PopEntryList(&pContext->RxPktList)) { VIOSockRxPktCleanup(pContext, CONTAINING_RECORD(pListEntry, VIOSOCK_RX_PKT, ListEntry)); } WdfSpinLockRelease(pContext->RxLock); VIOSockRxCbCleanup(pContext); if (pContext->RxPktVA) { VirtIOWdfDeviceFreeDmaMemory(&pContext->VDevice.VIODevice, pContext->RxPktVA); pContext->RxPktVA = NULL; } pContext->RxVq = NULL; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "<-- %s\n", __FUNCTION__); } NTSTATUS VIOSockRxVqInit( IN PDEVICE_CONTEXT pContext ) { NTSTATUS status = STATUS_SUCCESS; USHORT uNumEntries; ULONG uRingSize, uHeapSize, uBufferSize; PAGED_CODE(); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); pContext->RxPktList.Next = NULL; status = virtio_query_queue_allocation(&pContext->VDevice.VIODevice, VIOSOCK_VQ_RX, &uNumEntries, &uRingSize, &uHeapSize); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "virtio_query_queue_allocation(VIOSOCK_VQ_RX) failed\n"); pContext->RxVq = NULL; return status; } pContext->RxPktNum = uNumEntries; uBufferSize = sizeof(VIOSOCK_RX_PKT) * uNumEntries; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "Allocating common buffer of %u bytes for %u Rx packets\n", uBufferSize, uNumEntries); pContext->RxPktVA = (PVIOSOCK_RX_PKT)VirtIOWdfDeviceAllocDmaMemory(&pContext->VDevice.VIODevice, uBufferSize, VIOSOCK_DRIVER_MEMORY_TAG); ASSERT(pContext->RxPktVA); if (!pContext->RxPktVA) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfDeviceAllocDmaMemory(%u bytes for RxPackets) failed\n", uBufferSize); status = STATUS_INSUFFICIENT_RESOURCES; } else if (VIOSockRxCbInit(pContext)) { ULONG i; PVIOSOCK_RX_PKT RxPktVA = (PVIOSOCK_RX_PKT)pContext->RxPktVA; pContext->RxPktPA = VirtIOWdfDeviceGetPhysicalAddress(&pContext->VDevice.VIODevice, pContext->RxPktVA); ASSERT(pContext->RxPktPA.QuadPart); //fill queue, no lock for (i = 0; i < uNumEntries; i++) { if (!VIOSockRxPktInsert(pContext, &RxPktVA[i])) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VIOSockRxPktInsert[%u] failed\n", i); status = STATUS_UNSUCCESSFUL; break; } } } else { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VIOSockRxCbInit failed\n"); status = STATUS_UNSUCCESSFUL; } if (!NT_SUCCESS(status)) { VIOSockRxVqCleanup(pContext); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "<-- %s\n", __FUNCTION__); return status; } static VOID VIOSockRxPktHandleConnecting( IN PSOCKET_CONTEXT pSocket, IN PVIOSOCK_RX_PKT pPkt, IN BOOLEAN bTxHasSpace ) { WDFREQUEST PendedRequest; NTSTATUS status; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "--> %s\n", __FUNCTION__); status = VIOSockPendedRequestGetLocked(pSocket, &PendedRequest); if (NT_SUCCESS(status)) { if (PendedRequest == WDF_NO_HANDLE && !VIOSockIsFlag(pSocket, SOCK_NON_BLOCK)) { status = STATUS_CANCELLED; } else { switch (pPkt->Header.op) { case VIRTIO_VSOCK_OP_RESPONSE: VIOSockStateSet(pSocket, VIOSOCK_STATE_CONNECTED); VIOSockEventSetBit(pSocket, FD_CONNECT_BIT, STATUS_SUCCESS); if (bTxHasSpace) VIOSockEventSetBit(pSocket, FD_WRITE_BIT, STATUS_SUCCESS); status = STATUS_SUCCESS; break; case VIRTIO_VSOCK_OP_INVALID: if (PendedRequest != WDF_NO_HANDLE) { status = VIOSockPendedRequestSetLocked(pSocket, PendedRequest); if (NT_SUCCESS(status)) PendedRequest = WDF_NO_HANDLE; } break; case VIRTIO_VSOCK_OP_RST: status = STATUS_CONNECTION_RESET; break; default: status = STATUS_CONNECTION_INVALID; } } } if (!NT_SUCCESS(status)) { VIOSockEventSetBit(pSocket, FD_CONNECT_BIT, status); VIOSockStateSet(pSocket, VIOSOCK_STATE_CLOSE); if (pPkt->Header.op != VIRTIO_VSOCK_OP_RST) VIOSockSendReset(pSocket, TRUE); } if (PendedRequest) { WdfTimerStop(pSocket->ConnectTimer, TRUE); WdfRequestComplete(PendedRequest, status); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "<-- %s\n", __FUNCTION__); } static BOOLEAN VIOSockRxPktEnqueueCb( IN PSOCKET_CONTEXT pSocket, IN PVIOSOCK_RX_PKT pPkt ) { PDEVICE_CONTEXT pContext = GetDeviceContextFromSocket(pSocket); PVIOSOCK_RX_CB pCurrentCb = NULL; ULONG BufferFree, PktLen; BOOLEAN bRes = FALSE; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); ASSERT(pPkt && pPkt->Buffer && pPkt->Header.len); PktLen = pPkt->Header.len; //Merge buffers WdfSpinLockAcquire(pSocket->RxLock); if (!IsListEmpty(&pSocket->RxCbList) && PktLen <= VIOSOCK_BYTES_TO_MERGE) { pCurrentCb = CONTAINING_RECORD(pSocket->RxCbList.Blink, VIOSOCK_RX_CB, ListEntry); BufferFree = VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE - pCurrentCb->DataLen; if (BufferFree >= PktLen) { if (VIOSockRxPktInc(pSocket, PktLen)) { memcpy((PCHAR)pCurrentCb->BufferVA + pCurrentCb->DataLen, pPkt->Buffer->BufferVA, PktLen); pCurrentCb->DataLen += PktLen; } else { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Rx buffer full, drop packet\n"); } //just leave buffer with pkt WdfSpinLockRelease(pSocket->RxLock); return FALSE; } } else { bRes = TRUE; //Scan read queue } //Enqueue buffer if (VIOSockRxPktInc(pSocket, PktLen)) { pPkt->Buffer->DataLen = PktLen; InsertTailList(&pSocket->RxCbList, &pPkt->Buffer->ListEntry); pSocket->RxBuffers++; pPkt->Buffer = NULL; //remove buffer from pkt } else { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Rx buffer full, drop packet\n"); bRes = FALSE; } WdfSpinLockRelease(pSocket->RxLock); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return bRes; } static VOID VIOSockRxRequestCancelCb( IN WDFREQUEST Request ) { PSOCKET_CONTEXT pSocket = GetSocketContextFromRequest(Request); PVIOSOCK_RX_CB pCb = GetRequestRxCb(Request); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); WdfSpinLockAcquire(pSocket->RxLock); RemoveEntryList(&pCb->ListEntry); WdfSpinLockRelease(pSocket->RxLock); WdfRequestComplete(Request, STATUS_CANCELLED); } //SRxLock- NTSTATUS VIOSockRxRequestEnqueueCb( IN PSOCKET_CONTEXT pSocket, IN WDFREQUEST Request, IN ULONG Length ) { PDEVICE_CONTEXT pContext = GetDeviceContextFromSocket(pSocket); PVIOSOCK_RX_CB pCurrentCb = NULL; ULONG BufferFree; NTSTATUS status; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); pCurrentCb = VIOSockRxCbEntryForRequest(pContext, Request, Length); if (!pCurrentCb) return STATUS_INSUFFICIENT_RESOURCES; WdfSpinLockAcquire(pSocket->RxLock); //Enqueue buffer if (VIOSockRxPktInc(pSocket, pCurrentCb->DataLen)) { status = WdfRequestMarkCancelableEx(Request, VIOSockRxRequestCancelCb); if (NT_SUCCESS(status)) { InsertTailList(&pSocket->RxCbList, &pCurrentCb->ListEntry); pSocket->RxBuffers++; status = STATUS_SUCCESS; } else { ASSERT(status == STATUS_CANCELLED); TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Loopback request canceled: 0x%x\n", status); } } else { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Rx buffer full, drop packet\n"); status = STATUS_BUFFER_TOO_SMALL; } WdfSpinLockRelease(pSocket->RxLock); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return status; } //SRxLock- static VOID VIOSockRxPktHandleConnected( IN PSOCKET_CONTEXT pSocket, IN PVIOSOCK_RX_PKT pPkt, IN BOOLEAN bTxHasSpace ) { NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "--> %s\n", __FUNCTION__); switch (pPkt->Header.op) { case VIRTIO_VSOCK_OP_RW: if (VIOSockRxPktEnqueueCb(pSocket, pPkt)) { VIOSockEventSetBit(pSocket, FD_READ_BIT, STATUS_SUCCESS); VIOSockReadDequeueCb(pSocket, WDF_NO_HANDLE); } break;//TODO: Remove break? case VIRTIO_VSOCK_OP_CREDIT_UPDATE: if (bTxHasSpace) { VIOSockEventSetBit(pSocket, FD_WRITE_BIT, STATUS_SUCCESS); } break; case VIRTIO_VSOCK_OP_SHUTDOWN: if (VIOSockShutdownFromPeer(pSocket, pPkt->Header.flags & VIRTIO_VSOCK_SHUTDOWN_MASK) && !VIOSockRxHasData(pSocket) && !VIOSockIsDone(pSocket)) { VIOSockSendReset(pSocket, FALSE); VIOSockDoClose(pSocket); } break; case VIRTIO_VSOCK_OP_RST: VIOSockDoClose(pSocket); VIOSockEventSetBit(pSocket, FD_CLOSE_BIT, STATUS_CONNECTION_RESET); break; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "<-- %s\n", __FUNCTION__); } static VOID VIOSockRxPktHandleDisconnecting( IN PSOCKET_CONTEXT pSocket, IN PVIOSOCK_RX_PKT pPkt ) { TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "--> %s\n", __FUNCTION__); if (pPkt->Header.op == VIRTIO_VSOCK_OP_RST) { VIOSockDoClose(pSocket); // if (pSocket->PeerShutdown & VIRTIO_VSOCK_SHUTDOWN_MASK != VIRTIO_VSOCK_SHUTDOWN_MASK) // { // VIOSockEventSetBit(pSocket, FD_CLOSE_BIT, STATUS_CONNECTION_RESET); // } } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "<-- %s\n", __FUNCTION__); } static VOID VIOSockRxPktHandleListen( IN PSOCKET_CONTEXT pSocket, IN PVIOSOCK_RX_PKT pPkt ) { PDEVICE_CONTEXT pContext = GetDeviceContextFromSocket(pSocket); NTSTATUS status; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "--> %s\n", __FUNCTION__); if (pPkt->Header.op == VIRTIO_VSOCK_OP_RST) { //remove pended accept VIOSockAcceptRemovePkt(pSocket, &pPkt->Header); } else if (pPkt->Header.op != VIRTIO_VSOCK_OP_REQUEST) { TraceEvents(TRACE_LEVEL_ERROR, DBG_SOCKET, "Invalid packet: %u\n", pPkt->Header.op); VIOSockSendResetNoSock(pContext, &pPkt->Header); return; } status = VIOSockAcceptEnqueuePkt(pSocket, &pPkt->Header); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_SOCKET, "VIOSockAcceptEnqueuePkt failed: 0x%x\n", status); VIOSockSendResetNoSock(pContext, &pPkt->Header); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "<-- %s\n", __FUNCTION__); } VOID VIOSockRxVqProcess( IN PDEVICE_CONTEXT pContext ) { PVIOSOCK_RX_PKT pPkt; UINT len; SINGLE_LIST_ENTRY CompletionList; PSINGLE_LIST_ENTRY pCurrentEntry; PSOCKET_CONTEXT pSocket = NULL; BOOLEAN bStop = FALSE; NTSTATUS status; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); CompletionList.Next = NULL; WdfSpinLockAcquire(pContext->RxLock); do { virtqueue_disable_cb(pContext->RxVq); while (TRUE) { if (!VIOSockTxMoreReplies(pContext)) { /* Stop rx until the device processes already * pending replies. Leave rx virtqueue * callbacks disabled. */ bStop = TRUE; break; } pPkt = (PVIOSOCK_RX_PKT)virtqueue_get_buf(pContext->RxVq, &len); if (!pPkt) break; /* Drop short/long packets */ if (len < sizeof(pPkt->Header) || len > sizeof(pPkt->Header) + pPkt->Header.len) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Short/Long packet\n"); VIOSockRxPktInsert(pContext, pPkt); continue; } ASSERT(pPkt->Header.len == len - sizeof(pPkt->Header)); //"complete" buffers later PushEntryList(&CompletionList, &pPkt->ListEntry); } } while (!virtqueue_enable_cb(pContext->RxVq) && !bStop); WdfSpinLockRelease(pContext->RxLock); //complete buffers while ((pCurrentEntry = PopEntryList(&CompletionList)) != NULL) { BOOLEAN bTxHasSpace; pPkt = CONTAINING_RECORD(pCurrentEntry, VIOSOCK_RX_PKT, ListEntry); //find socket pSocket = VIOSockConnectedFindByRxPkt(pContext, &pPkt->Header); if (!pSocket) { //no connected socket for incoming packet pSocket = VIOSockBoundFindByPort(pContext, pPkt->Header.dst_port); } if (pSocket && pSocket->type != pPkt->Header.type) { TraceEvents(TRACE_LEVEL_WARNING, DBG_SOCKET, "Invalid socket state or type\n"); pSocket = NULL; } if (!pSocket) { TraceEvents(TRACE_LEVEL_WARNING, DBG_SOCKET, "Socket for packet is not exists\n"); VIOSockSendResetNoSock(pContext, &pPkt->Header); VIOSockRxPktInsertOrPostpone(pContext, pPkt); continue; } //Update CID in case it has changed after a transport reset event //pContext->Config.guest_cid = (ULONG32)pPkt->Header.dst_cid; ASSERT(pContext->Config.guest_cid == (ULONG32)pPkt->Header.dst_cid); bTxHasSpace = !!VIOSockTxSpaceUpdate(pSocket, &pPkt->Header); switch (pSocket->State) { case VIOSOCK_STATE_CONNECTING: VIOSockRxPktHandleConnecting(pSocket, pPkt, bTxHasSpace); break; case VIOSOCK_STATE_CONNECTED: VIOSockRxPktHandleConnected(pSocket, pPkt, bTxHasSpace); break; case VIOSOCK_STATE_CLOSING: VIOSockRxPktHandleDisconnecting(pSocket, pPkt); break; case VIOSOCK_STATE_LISTEN: VIOSockRxPktHandleListen(pSocket, pPkt); break; default: TraceEvents(TRACE_LEVEL_ERROR, DBG_SOCKET, "Invalid socket state for Rx packet\n"); } //reinsert handled packet VIOSockRxPktInsertOrPostpone(pContext, pPkt); }; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "<-- %s\n", __FUNCTION__); } ////////////////////////////////////////////////////////////////////////// static VOID VIOSockRead( IN WDFQUEUE Queue, IN WDFREQUEST Request, IN size_t Length ) { PSOCKET_CONTEXT pSocket = GetSocketContextFromRequest(Request); NTSTATUS status; BOOLEAN bTimer = FALSE; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); //check Request if (VIOSockIsFlag(pSocket, SOCK_CONTROL)) { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Invalid read request\n"); WdfRequestComplete(Request, STATUS_INVALID_DEVICE_REQUEST); return; } //TODO: lock socket if (!VIOSockIsFlag(pSocket, SOCK_NON_BLOCK) && pSocket->RecvTimeout != LONG_MAX) { PVIOSOCK_RX_CONTEXT pRequest; WDF_OBJECT_ATTRIBUTES attributes; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE( &attributes, VIOSOCK_RX_CONTEXT ); status = WdfObjectAllocateContext( Request, &attributes, &pRequest ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfObjectAllocateContext failed: 0x%x\n", status); WdfRequestComplete(Request, status); return; } pRequest->Timeout = WDF_ABS_TIMEOUT_IN_MS(pSocket->RecvTimeout); pRequest->Counter = 0; VIOSockTimerStart(&pSocket->ReadTimer, pRequest->Timeout); bTimer = TRUE; } status = WdfRequestForwardToIoQueue(Request, pSocket->ReadQueue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestForwardToIoQueue failed: 0x%x\n", status); WdfRequestComplete(Request, status); if (bTimer) VIOSockTimerDeref(&pSocket->ReadTimer, TRUE); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); } NTSTATUS VIOSockReadWithFlags( IN WDFREQUEST Request ) { PSOCKET_CONTEXT pSocket = GetSocketContextFromRequest(Request); NTSTATUS status; PVIRTIO_VSOCK_READ_PARAMS pReadParams; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); //validate request status = WdfRequestRetrieveInputBuffer(Request, sizeof(*pReadParams), &pReadParams, NULL); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestRetrieveInputBuffer failed: 0x%x\n", status); } else if (pReadParams->Flags & ~(MSG_PEEK | MSG_WAITALL)) { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Unsupported flags: 0x%x\n", pReadParams->Flags & ~(MSG_PEEK | MSG_WAITALL)); status = STATUS_NOT_SUPPORTED; } else if ((pReadParams->Flags & (MSG_PEEK | MSG_WAITALL)) == (MSG_PEEK | MSG_WAITALL)) { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Incompatible flags: 0x%x\n", MSG_PEEK | MSG_WAITALL); status = STATUS_NOT_SUPPORTED; } else { PVOID pBuffer; status = WdfRequestRetrieveOutputBuffer(Request, 0, &pBuffer, NULL); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestRetrieveOutputBuffer failed: 0x%x\n", status); } else WdfRequestSetInformation(Request, pReadParams->Flags); } if (NT_SUCCESS(status)) { VIOSockEventClearBit(pSocket, FD_READ_BIT); status = WdfRequestForwardToIoQueue(Request, pSocket->ReadQueue); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestForwardToIoQueue failed: 0x%x\n", status); } else status = STATUS_PENDING; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return status; } NTSTATUS VIOSockReadQueueInit( IN WDFDEVICE hDevice ) { PDEVICE_CONTEXT pContext = GetDeviceContext(hDevice); WDF_IO_QUEUE_CONFIG queueConfig; NTSTATUS status; WDF_OBJECT_ATTRIBUTES attributes; PAGED_CODE(); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = pContext->ThisDevice; status = WdfSpinLockCreate( &attributes, &pContext->RxLock ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfSpinLockCreate failed: 0x%x\n", status); return FALSE; } WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchParallel ); queueConfig.EvtIoRead = VIOSockRead; queueConfig.AllowZeroLengthRequests = WdfFalse; status = WdfIoQueueCreate(hDevice, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &pContext->ReadQueue ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfIoQueueCreate failed (Read Queue): 0x%x\n", status); return status; } status = WdfDeviceConfigureRequestDispatching(hDevice, pContext->ReadQueue, WdfRequestTypeRead); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfDeviceConfigureRequestDispatching failed (Read Queue): 0x%x\n", status); return status; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return STATUS_SUCCESS; } static NTSTATUS VIOSockReadGetRequestParameters( IN WDFREQUEST Request, OUT PVOID *pBuffer, OUT ULONG *pLength, OUT ULONG *pFlags ) { NTSTATUS status; WDF_REQUEST_PARAMETERS parameters; size_t stLength; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); WDF_REQUEST_PARAMETERS_INIT(&parameters); WdfRequestGetParameters(Request, &parameters); if (parameters.Type == WdfRequestTypeDeviceControl) { *pFlags = (ULONG)WdfRequestGetInformation(Request); WdfRequestSetInformation(Request, 0); } else *pFlags = 0; status = WdfRequestRetrieveOutputBuffer(Request, 0, pBuffer, &stLength); if (!NT_SUCCESS(status)) { ASSERT(FALSE); TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestRetrieveOutputBuffer failed: 0x%x\n", status); } else { *pLength = (ULONG)stLength; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return status; } //SRxLock- VOID VIOSockReadDequeueCb( IN PSOCKET_CONTEXT pSocket, IN WDFREQUEST ReadRequest OPTIONAL ) { PDEVICE_CONTEXT pContext = GetDeviceContextFromSocket(pSocket); NTSTATUS status; ULONG ReadRequestFlags = 0; PCHAR ReadRequestPtr = NULL; ULONG ReadRequestFree, ReadRequestLength; PVIOSOCK_RX_CB pCurrentCb; LIST_ENTRY LoopbackList, *pCurrentItem; ULONG FreeSpace; BOOLEAN bSetBit, bStop = FALSE, bPend = FALSE; PVIOSOCK_RX_CONTEXT pRequest = NULL; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); WdfSpinLockAcquire(pSocket->RxLock); if (ReadRequest != WDF_NO_HANDLE) { pRequest = GetRequestRxContext(ReadRequest); if (pRequest && pRequest->Timeout) { VIOSockTimerDeref(&pSocket->ReadTimer, TRUE); pRequest->Timeout -= VIOSockTimerPassed(&pSocket->ReadTimer); } } if (VIOSockRxHasData(pSocket) || VIOSockIsFlag(pSocket, SOCK_NON_BLOCK) || VIOSockStateGet(pSocket) != VIOSOCK_STATE_CONNECTED) { if (ReadRequest != WDF_NO_HANDLE) { VIOSockEventClearBit(pSocket, FD_READ_BIT); status = VIOSockReadGetRequestParameters( ReadRequest, &ReadRequestPtr, &ReadRequestLength, &ReadRequestFlags); ReadRequestFree = ReadRequestLength; } else { status = VIOSockPendedRequestGet(pSocket, &ReadRequest); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Pended Read request canceled\n"); status = STATUS_SUCCESS; //do not complete canceled request ASSERT(ReadRequest == WDF_NO_HANDLE); } else if (ReadRequest != WDF_NO_HANDLE) { pRequest = GetRequestRxContext(ReadRequest); if (pRequest && pRequest->Timeout) { VIOSockTimerDeref(&pSocket->ReadTimer, TRUE); pRequest->Timeout -= VIOSockTimerPassed(&pSocket->ReadTimer); } ReadRequestPtr = pSocket->ReadRequestPtr; ReadRequestFree = pSocket->ReadRequestFree; ReadRequestLength = pSocket->ReadRequestLength; ReadRequestFlags = pSocket->ReadRequestFlags; } } if (ReadRequest == WDF_NO_HANDLE || !NT_SUCCESS(status)) { bStop = TRUE; } else if (!VIOSockRxHasData(pSocket)) { VIOSOCK_STATE State = VIOSockStateGet(pSocket); //complete request bStop = TRUE; if (State != VIOSOCK_STATE_CONNECTED) { //TODO: set appropriate status if (State == VIOSOCK_STATE_CONNECTING || State == VIOSOCK_STATE_CLOSING) status = STATUS_CONNECTION_DISCONNECTED; else if (State == VIOSOCK_STATE_LISTEN) status = STATUS_INVALID_PARAMETER; else status = STATUS_SUCCESS; //return zero bytes on closing/close } else if (VIOSockIsFlag(pSocket, SOCK_NON_BLOCK)) { status = STATUS_CANT_WAIT; } else { ASSERT(FALSE); bPend = TRUE; } } } else { bPend = TRUE; } if (bPend) { bStop = TRUE; ASSERT(ReadRequest != WDF_NO_HANDLE); if (ReadRequest != WDF_NO_HANDLE) { if (!pRequest || pRequest->Timeout > VIOSOCK_TIMER_TOLERANCE) { status = VIOSockReadGetRequestParameters( ReadRequest, &pSocket->ReadRequestPtr, &pSocket->ReadRequestLength, &pSocket->ReadRequestFlags); if (NT_SUCCESS(status)) { pSocket->ReadRequestFree = pSocket->ReadRequestLength; status = VIOSockPendedRequestSet(pSocket, ReadRequest); if (NT_SUCCESS(status)) { if(pRequest) VIOSockTimerStart(&pSocket->ReadTimer, pRequest->Timeout); ReadRequest = WDF_NO_HANDLE; } } } else if (pRequest) status = STATUS_TIMEOUT; } } if (ReadRequest == WDF_NO_HANDLE || bStop) { WdfSpinLockRelease(pSocket->RxLock); if (ReadRequest != WDF_NO_HANDLE) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "Complete request without CB dequeue: 0x%x\n", status); WdfRequestComplete(ReadRequest, status); } else { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "No read request available\n"); } return; } ASSERT(ReadRequestPtr); InitializeListHead(&LoopbackList); //process chained buffer for (pCurrentItem = pSocket->RxCbList.Flink; pCurrentItem != &pSocket->RxCbList; pCurrentItem = pCurrentItem->Flink) { //peek the first buffer pCurrentCb = CONTAINING_RECORD(pCurrentItem, VIOSOCK_RX_CB, ListEntry); if (pCurrentCb->Request != WDF_NO_HANDLE) //only loopback buffers have request assigned { status = WdfRequestUnmarkCancelable(pCurrentCb->Request); //STATUS_CANCELLED means cancellation is in progress, //cancel routine will remove from list and complete current request, //we should just skip it if (!NT_SUCCESS(status)) { ASSERT(status == STATUS_CANCELLED); TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Loopback request is canceling: 0x%x\n", status); pSocket->RxCbReadPtr = NULL; pSocket->RxCbReadLen = 0; continue; } } //set socket read data pointer if (!pSocket->RxCbReadPtr) { pSocket->RxCbReadPtr = pCurrentCb->BufferVA; pSocket->RxCbReadLen = pCurrentCb->DataLen; } //can we copy the whole CB? if (ReadRequestFree >= pSocket->RxCbReadLen) { memcpy(ReadRequestPtr, pSocket->RxCbReadPtr, pSocket->RxCbReadLen); //update request buffer data ptr ReadRequestPtr += pSocket->RxCbReadLen; ReadRequestFree -= pSocket->RxCbReadLen; if (!(ReadRequestFlags & MSG_PEEK)) { PLIST_ENTRY pPrevItem = pCurrentItem->Blink; VIOSockRxPktDec(pSocket, pCurrentCb->DataLen); RemoveEntryList(pCurrentItem); pCurrentItem = pPrevItem; if (pCurrentCb->Request != WDF_NO_HANDLE) InsertTailList(&LoopbackList, &pCurrentCb->ListEntry); //complete loopback requests later else VIOSockRxCbPushLocked(pContext, pCurrentCb); } pSocket->RxCbReadPtr = NULL; pSocket->RxCbReadLen = 0; } else //request buffer is not big enough { memcpy(ReadRequestPtr, pSocket->RxCbReadPtr, ReadRequestFree); ReadRequestFree = 0; if (!(ReadRequestFlags & MSG_PEEK)) { //update current CB data ptr pSocket->RxCbReadPtr += ReadRequestLength; pSocket->RxCbReadLen -= ReadRequestLength; } if (pCurrentCb->Request != WDF_NO_HANDLE) { //Postpone incomplete loopback request. status = WdfRequestMarkCancelableEx(pCurrentCb->Request, VIOSockRxRequestCancelCb); //WdfRequestMarkCancelableEx returns STATUS_CANCELLED if request has Canceled bit set //(was canceled after Unmark and before this call). In this case caller has to complete //request. //WARNING! SDV marks pCurrentCb->Request as INVALID despite of return status, but request still VALID //if status == STATUS_CANCELLED if (!NT_SUCCESS(status)) { ASSERT(status == STATUS_CANCELLED); TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Loopback request is canceled: 0x%x\n", status); RemoveEntryList(pCurrentItem); pSocket->RxCbReadPtr = NULL; pSocket->RxCbReadLen = 0; pCurrentCb->DataLen = 0; InsertTailList(&LoopbackList, &pCurrentCb->ListEntry); //complete canceled loopback request later } } break; } } if (!ReadRequestFree || ReadRequestFlags & MSG_PEEK) { TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "Should complete read request\n"); } else if (ReadRequestLength == ReadRequestFree || ReadRequestFlags & MSG_WAITALL) { if (!pRequest || pRequest->Timeout > VIOSOCK_TIMER_TOLERANCE) { //pend request ASSERT(!(ReadRequestFlags & MSG_PEEK)); pSocket->ReadRequestPtr = ReadRequestPtr; pSocket->ReadRequestFree = ReadRequestFree; pSocket->ReadRequestLength = ReadRequestLength; pSocket->ReadRequestFlags = ReadRequestFlags; status = VIOSockPendedRequestSet(pSocket, ReadRequest); if (!NT_SUCCESS(status)) { ASSERT(status == STATUS_CANCELLED); if (status == STATUS_CANCELLED) ReadRequest = WDF_NO_HANDLE; //already completed ReadRequestLength = ReadRequestFree = 0; } else { ReadRequest = WDF_NO_HANDLE; if(pRequest) VIOSockTimerStart(&pSocket->ReadTimer, pRequest->Timeout); } } else if (pRequest) { status = STATUS_TIMEOUT; ReadRequestLength = ReadRequestFree = 0; } } bSetBit = (ReadRequest != WDF_NO_HANDLE && VIOSockRxHasData(pSocket)); FreeSpace = pSocket->buf_alloc - (pSocket->fwd_cnt - pSocket->last_fwd_cnt); WdfSpinLockRelease(pSocket->RxLock); if (bSetBit) VIOSockEventSetBit(pSocket, FD_READ_BIT, STATUS_SUCCESS); if (FreeSpace < VIRTIO_VSOCK_MAX_PKT_BUF_SIZE) VIOSockSendCreditUpdate(pSocket); if (ReadRequest != WDF_NO_HANDLE) { ASSERT(pSocket->PendedRequest == WDF_NO_HANDLE); WdfRequestCompleteWithInformation(ReadRequest, status, ReadRequestLength - ReadRequestFree); } //complete loopback requests (succeed and canceled) while (!IsListEmpty(&LoopbackList)) { pCurrentCb = CONTAINING_RECORD(RemoveHeadList(&LoopbackList), VIOSOCK_RX_CB, ListEntry); //NOTE! SDV thinks we are completing INVALID request marked as cancelable, //but request is appeared in this list only if WdfRequestMarkCancelableEx failed WdfRequestCompleteWithInformation(pCurrentCb->Request, pCurrentCb->DataLen ? STATUS_SUCCESS : STATUS_CANCELLED, pCurrentCb->DataLen); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); } VOID VIOSockReadCleanupCb( IN PSOCKET_CONTEXT pSocket ) { PDEVICE_CONTEXT pContext = GetDeviceContextFromSocket(pSocket); PVIOSOCK_RX_CB pCurrentCb; LIST_ENTRY LoopbackList; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); InitializeListHead(&LoopbackList); WdfSpinLockAcquire(pSocket->RxLock); pSocket->RxCbReadLen = 0; pSocket->RxCbReadPtr = NULL; //process chained buffer while (!IsListEmpty(&pSocket->RxCbList)) { //peek the first buffer pCurrentCb = CONTAINING_RECORD(RemoveHeadList(&pSocket->RxCbList), VIOSOCK_RX_CB, ListEntry); if (pCurrentCb->Request) { NTSTATUS status = WdfRequestUnmarkCancelable(pCurrentCb->Request); if (!NT_SUCCESS(status)) { ASSERT(status == STATUS_CANCELLED); TraceEvents(TRACE_LEVEL_WARNING, DBG_READ, "Loopback request canceled\n"); } else InsertTailList(&LoopbackList, &pCurrentCb->ListEntry); //complete loopback requests later } else VIOSockRxCbPushLocked(pContext, pCurrentCb); } WdfSpinLockRelease(pSocket->RxLock); //complete loopback while (!IsListEmpty(&LoopbackList)) { pCurrentCb = CONTAINING_RECORD(RemoveHeadList(&LoopbackList), VIOSOCK_RX_CB, ListEntry); WdfRequestComplete(pCurrentCb->Request, STATUS_CANCELLED); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); } static VOID VIOSockReadSocketIoDefault( IN WDFQUEUE Queue, IN WDFREQUEST Request ) { PSOCKET_CONTEXT pSocket = GetSocketContextFromRequest(Request); VIOSockReadDequeueCb(pSocket, Request); } static VOID VIOSockReadSocketIoStop( IN WDFQUEUE Queue, IN WDFREQUEST Request, IN ULONG ActionFlags ) { TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); if (ActionFlags & WdfRequestStopActionSuspend) { WdfRequestStopAcknowledge(Request, FALSE); } else if (ActionFlags & WdfRequestStopActionPurge) { if (ActionFlags & WdfRequestStopRequestCancelable) { PSOCKET_CONTEXT pSocket = GetSocketContextFromRequest(Request); WdfSpinLockAcquire(pSocket->RxLock); if (pSocket->PendedRequest == Request) { pSocket->PendedRequest = WDF_NO_HANDLE; WdfObjectDereference(Request); } WdfSpinLockRelease(pSocket->RxLock); if (WdfRequestUnmarkCancelable(Request) != STATUS_CANCELLED) { WdfRequestComplete(Request, STATUS_CANCELLED); } } } } NTSTATUS VIOSockReadSocketQueueInit( IN PSOCKET_CONTEXT pSocket ) { WDFDEVICE hDevice = WdfFileObjectGetDevice(pSocket->ThisSocket); PDEVICE_CONTEXT pContext = GetDeviceContext(hDevice); WDF_OBJECT_ATTRIBUTES queueAttributes; WDF_IO_QUEUE_CONFIG queueConfig; NTSTATUS status; PAGED_CODE(); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchSequential ); queueConfig.EvtIoDefault = VIOSockReadSocketIoDefault; queueConfig.EvtIoStop = VIOSockReadSocketIoStop; queueConfig.AllowZeroLengthRequests = WdfFalse; WDF_OBJECT_ATTRIBUTES_INIT(&queueAttributes); queueAttributes.ParentObject = pSocket->ThisSocket; status = WdfIoQueueCreate(hDevice, &queueConfig, &queueAttributes, &pSocket->ReadQueue ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfIoQueueCreate failed (Socket Read Queue): 0x%x\n", status); return status; } VIOSockTimerCreate(&pSocket->ReadTimer, pSocket->ThisSocket, VIOSockReadTimerFunc); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "VIOSockTimerCreate failed (Socket Read Queue): 0x%x\n", status); return status; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return STATUS_SUCCESS; } ////////////////////////////////////////////////////////////////////////// VOID VIOSockReadTimerFunc( WDFTIMER Timer ) { static ULONG ulCounter; PSOCKET_CONTEXT pSocket = GetSocketContext(WdfTimerGetParentObject(Timer)); LONGLONG Timeout = LONGLONG_MAX; WDFREQUEST PrevTagRequest = WDF_NO_HANDLE, TagRequest = WDF_NO_HANDLE, Request; NTSTATUS status; LIST_ENTRY CompletionList; PVIOSOCK_RX_CONTEXT pRequest; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_SOCKET, "--> %s\n", __FUNCTION__); InitializeListHead(&CompletionList); WdfSpinLockAcquire(pSocket->RxLock); ++ulCounter; status = VIOSockPendedRequestGet(pSocket, &Request); if (NT_SUCCESS(status) && Request != WDF_NO_HANDLE) { pRequest = GetRequestRxContext(Request); if (pRequest) { if (pRequest->Timeout > pSocket->ReadTimer.Timeout + VIOSOCK_TIMER_TOLERANCE) { pRequest->Timeout -= pSocket->ReadTimer.Timeout; if (pRequest->Timeout < Timeout) Timeout = pRequest->Timeout; status = VIOSockPendedRequestSet(pSocket, Request); } else { status = STATUS_UNSUCCESSFUL; } if (!NT_SUCCESS(status)) { InsertTailList(&CompletionList, &pRequest->ListEntry); pRequest->ThisRequest = Request; VIOSockTimerDeref(&pSocket->ReadTimer, FALSE); } } } do { status = WdfIoQueueFindRequest(pSocket->ReadQueue, PrevTagRequest, WDF_NO_HANDLE, NULL, &TagRequest); if (PrevTagRequest != WDF_NO_HANDLE) { WdfObjectDereference(PrevTagRequest); } if (NT_SUCCESS(status)) { pRequest = GetRequestRxContext(TagRequest); if (pRequest && pRequest->Timeout && pRequest->Counter < ulCounter) { if (pRequest->Timeout <= pSocket->ReadTimer.Timeout + VIOSOCK_TIMER_TOLERANCE) { status = WdfIoQueueRetrieveFoundRequest(pSocket->ReadQueue, TagRequest, &Request); WdfObjectDereference(TagRequest); if (status == STATUS_NOT_FOUND) { TagRequest = PrevTagRequest = WDF_NO_HANDLE; status = STATUS_SUCCESS; } else if (!NT_SUCCESS(status)) { break; } else { InsertTailList(&CompletionList, &pRequest->ListEntry); pRequest->ThisRequest = Request; VIOSockTimerDeref(&pSocket->ReadTimer, FALSE); } } else { pRequest->Counter = ulCounter; pRequest->Timeout -= pSocket->ReadTimer.Timeout; if (pRequest->Timeout < Timeout) Timeout = pRequest->Timeout; PrevTagRequest = TagRequest; } } } else if (status == STATUS_NO_MORE_ENTRIES) { break; } else if (status == STATUS_NOT_FOUND) { TagRequest = PrevTagRequest = WDF_NO_HANDLE; status = STATUS_SUCCESS; } } while (NT_SUCCESS(status)); VIOSockTimerSet(&pSocket->ReadTimer, Timeout); WdfSpinLockRelease(pSocket->RxLock); while (!IsListEmpty(&CompletionList)) { pRequest = CONTAINING_RECORD(RemoveHeadList(&CompletionList), VIOSOCK_RX_CONTEXT, ListEntry); WdfRequestComplete(pRequest->ThisRequest, STATUS_TIMEOUT); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); }
966528.c
/** * security.c - Handling security/ACLs in NTFS. Originated from the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov * Copyright (c) 2005-2006 Szabolcs Szakacsits * Copyright (c) 2006 Yura Pakhuchiy * Copyright (c) 2007-2015 Jean-Pierre Andre * * This program/include file is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program/include file is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program (in the main directory of the NTFS-3G * distribution in the file COPYING); if not, write to the Free Software * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #include <unistd.h> #include <pwd.h> #include <grp.h> #include "compat.h" #include "param.h" #include "types.h" #include "layout.h" #include "attrib.h" #include "index.h" #include "dir.h" #include "bitmap.h" #include "security.h" #include "acls.h" #include "cache.h" #include "misc.h" #include "xattrs.h" /* * JPA NTFS constants or structs * should be moved to layout.h */ #define ALIGN_SDS_BLOCK 0x40000 /* Alignment for a $SDS block */ #define ALIGN_SDS_ENTRY 16 /* Alignment for a $SDS entry */ #define STUFFSZ 0x4000 /* unitary stuffing size for $SDS */ #define FIRST_SECURITY_ID 0x100 /* Lowest security id */ /* Mask for attributes which can be forced */ #define FILE_ATTR_SETTABLE ( FILE_ATTR_READONLY \ | FILE_ATTR_HIDDEN \ | FILE_ATTR_SYSTEM \ | FILE_ATTR_ARCHIVE \ | FILE_ATTR_TEMPORARY \ | FILE_ATTR_OFFLINE \ | FILE_ATTR_NOT_CONTENT_INDEXED ) struct SII { /* this is an image of an $SII index entry */ le16 offs; le16 size; le32 fill1; le16 indexsz; le16 indexksz; le16 flags; le16 fill2; le32 keysecurid; /* did not find official description for the following */ le32 hash; le32 securid; le32 dataoffsl; /* documented as badly aligned */ le32 dataoffsh; le32 datasize; } ; struct SDH { /* this is an image of an $SDH index entry */ le16 offs; le16 size; le32 fill1; le16 indexsz; le16 indexksz; le16 flags; le16 fill2; le32 keyhash; le32 keysecurid; /* did not find official description for the following */ le32 hash; le32 securid; le32 dataoffsl; le32 dataoffsh; le32 datasize; le32 fill3; } ; /* * A few useful constants */ static ntfschar sii_stream[] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'), const_cpu_to_le16('I'), const_cpu_to_le16('I'), const_cpu_to_le16(0) }; static ntfschar sdh_stream[] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'), const_cpu_to_le16('D'), const_cpu_to_le16('H'), const_cpu_to_le16(0) }; /* * null SID (S-1-0-0) */ extern const SID *nullsid; /* * The zero GUID. */ static const GUID __zero_guid = { const_cpu_to_le32(0), const_cpu_to_le16(0), const_cpu_to_le16(0), { 0, 0, 0, 0, 0, 0, 0, 0 } }; static const GUID *const zero_guid = &__zero_guid; /** * ntfs_guid_is_zero - check if a GUID is zero * @guid: [IN] guid to check * * Return TRUE if @guid is a valid pointer to a GUID and it is the zero GUID * and FALSE otherwise. */ BOOL ntfs_guid_is_zero(const GUID *guid) { return (memcmp(guid, zero_guid, sizeof(*zero_guid))); } /** * ntfs_guid_to_mbs - convert a GUID to a multi byte string * @guid: [IN] guid to convert * @guid_str: [OUT] string in which to return the GUID (optional) * * Convert the GUID pointed to by @guid to a multi byte string of the form * "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX". Therefore, @guid_str (if not NULL) * needs to be able to store at least 37 bytes. * * If @guid_str is not NULL it will contain the converted GUID on return. If * it is NULL a string will be allocated and this will be returned. The caller * is responsible for free()ing the string in that case. * * On success return the converted string and on failure return NULL with errno * set to the error code. */ char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) { char *_guid_str; int res; if (!guid) { errno = EINVAL; return NULL; } _guid_str = guid_str; if (!_guid_str) { _guid_str = (char*)ntfs_malloc(37); if (!_guid_str) return _guid_str; } res = snprintf(_guid_str, 37, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", (unsigned int)le32_to_cpu(guid->data1), le16_to_cpu(guid->data2), le16_to_cpu(guid->data3), guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3], guid->data4[4], guid->data4[5], guid->data4[6], guid->data4[7]); if (res == 36) return _guid_str; if (!guid_str) free(_guid_str); errno = EINVAL; return NULL; } /** * ntfs_sid_to_mbs_size - determine maximum size for the string of a SID * @sid: [IN] SID for which to determine the maximum string size * * Determine the maximum multi byte string size in bytes which is needed to * store the standard textual representation of the SID pointed to by @sid. * See ntfs_sid_to_mbs(), below. * * On success return the maximum number of bytes needed to store the multi byte * string and on failure return -1 with errno set to the error code. */ int ntfs_sid_to_mbs_size(const SID *sid) { int size, i; if (!ntfs_valid_sid(sid)) { errno = EINVAL; return -1; } /* Start with "S-". */ size = 2; /* * Add the SID_REVISION. Hopefully the compiler will optimize this * away as SID_REVISION is a constant. */ for (i = SID_REVISION; i > 0; i /= 10) size++; /* Add the "-". */ size++; /* * Add the identifier authority. If it needs to be in decimal, the * maximum is 2^32-1 = 4294967295 = 10 characters. If it needs to be * in hexadecimal, then maximum is 0x665544332211 = 14 characters. */ if (!sid->identifier_authority.high_part) size += 10; else size += 14; /* * Finally, add the sub authorities. For each we have a "-" followed * by a decimal which can be up to 2^32-1 = 4294967295 = 10 characters. */ size += (1 + 10) * sid->sub_authority_count; /* We need the zero byte at the end, too. */ size++; return size * sizeof(char); } /** * ntfs_sid_to_mbs - convert a SID to a multi byte string * @sid: [IN] SID to convert * @sid_str: [OUT] string in which to return the SID (optional) * @sid_str_size: [IN] size in bytes of @sid_str * * Convert the SID pointed to by @sid to its standard textual representation. * @sid_str (if not NULL) needs to be able to store at least * ntfs_sid_to_mbs_size() bytes. @sid_str_size is the size in bytes of * @sid_str if @sid_str is not NULL. * * The standard textual representation of the SID is of the form: * S-R-I-S-S... * Where: * - The first "S" is the literal character 'S' identifying the following * digits as a SID. * - R is the revision level of the SID expressed as a sequence of digits * in decimal. * - I is the 48-bit identifier_authority, expressed as digits in decimal, * if I < 2^32, or hexadecimal prefixed by "0x", if I >= 2^32. * - S... is one or more sub_authority values, expressed as digits in * decimal. * * If @sid_str is not NULL it will contain the converted SUID on return. If it * is NULL a string will be allocated and this will be returned. The caller is * responsible for free()ing the string in that case. * * On success return the converted string and on failure return NULL with errno * set to the error code. */ char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, size_t sid_str_size) { u64 u; le32 leauth; char *s; int i, j, cnt; /* * No need to check @sid if !@sid_str since ntfs_sid_to_mbs_size() will * check @sid, too. 8 is the minimum SID string size. */ if (sid_str && (sid_str_size < 8 || !ntfs_valid_sid(sid))) { errno = EINVAL; return NULL; } /* Allocate string if not provided. */ if (!sid_str) { cnt = ntfs_sid_to_mbs_size(sid); if (cnt < 0) return NULL; s = (char*)ntfs_malloc(cnt); if (!s) return s; sid_str = s; /* So we know we allocated it. */ sid_str_size = 0; } else { s = sid_str; cnt = sid_str_size; } /* Start with "S-R-". */ i = snprintf(s, cnt, "S-%hhu-", (unsigned char)sid->revision); if (i < 0 || i >= cnt) goto err_out; s += i; cnt -= i; /* Add the identifier authority. */ for (u = i = 0, j = 40; i < 6; i++, j -= 8) u += (u64)sid->identifier_authority.value[i] << j; if (!sid->identifier_authority.high_part) i = snprintf(s, cnt, "%lu", (unsigned long)u); else i = snprintf(s, cnt, "0x%llx", (unsigned long long)u); if (i < 0 || i >= cnt) goto err_out; s += i; cnt -= i; /* Finally, add the sub authorities. */ for (j = 0; j < sid->sub_authority_count; j++) { leauth = sid->sub_authority[j]; i = snprintf(s, cnt, "-%u", (unsigned int) le32_to_cpu(leauth)); if (i < 0 || i >= cnt) goto err_out; s += i; cnt -= i; } return sid_str; err_out: if (i >= cnt) i = EMSGSIZE; else i = errno; if (!sid_str_size) free(sid_str); errno = i; return NULL; } /** * ntfs_generate_guid - generatates a random current guid. * @guid: [OUT] pointer to a GUID struct to hold the generated guid. * * perhaps not a very good random number generator though... */ void ntfs_generate_guid(GUID *guid) { unsigned int i; u8 *p = (u8 *)guid; /* this is called at most once from mkntfs */ srandom(time((time_t*)NULL) ^ (getpid() << 16)); for (i = 0; i < sizeof(GUID); i++) { p[i] = (u8)(random() & 0xFF); if (i == 7) p[7] = (p[7] & 0x0F) | 0x40; if (i == 8) p[8] = (p[8] & 0x3F) | 0x80; } } /** * ntfs_security_hash - calculate the hash of a security descriptor * @sd: self-relative security descriptor whose hash to calculate * @length: size in bytes of the security descritor @sd * * Calculate the hash of the self-relative security descriptor @sd of length * @length bytes. * * This hash is used in the $Secure system file as the primary key for the $SDH * index and is also stored in the header of each security descriptor in the * $SDS data stream as well as in the index data of both the $SII and $SDH * indexes. In all three cases it forms part of the SDS_ENTRY_HEADER * structure. * * Return the calculated security hash in little endian. */ le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) { const le32 *pos = (const le32*)sd; const le32 *end = pos + (len >> 2); u32 hash = 0; while (pos < end) { hash = le32_to_cpup(pos) + ntfs_rol32(hash, 3); pos++; } return cpu_to_le32(hash); } /* * Get the first entry of current index block * cut and pasted form ntfs_ie_get_first() in index.c */ static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) { return (INDEX_ENTRY*)((u8*)ih + le32_to_cpu(ih->entries_offset)); } /* * Stuff a 256KB block into $SDS before writing descriptors * into the block. * * This prevents $SDS from being automatically declared as sparse * when the second copy of the first security descriptor is written * 256KB further ahead. * * Having $SDS declared as a sparse file is not wrong by itself * and chkdsk leaves it as a sparse file. It does however complain * and add a sparse flag (0x0200) into field file_attributes of * STANDARD_INFORMATION of $Secure. This probably means that a * sparse attribute (ATTR_IS_SPARSE) is only allowed in sparse * files (FILE_ATTR_SPARSE_FILE). * * Windows normally does not convert to sparse attribute or sparse * file. Stuffing is just a way to get to the same result. */ static int entersecurity_stuff(ntfs_volume *vol, off_t offs) { int res; int written; unsigned long total; char *stuff; res = 0; total = 0; stuff = (char*)ntfs_malloc(STUFFSZ); if (stuff) { memset(stuff, 0, STUFFSZ); do { written = ntfs_attr_data_write(vol->secure_ni, STREAM_SDS, 4, stuff, STUFFSZ, offs); if (written == STUFFSZ) { total += STUFFSZ; offs += STUFFSZ; } else { errno = ENOSPC; res = -1; } } while (!res && (total < ALIGN_SDS_BLOCK)); free(stuff); } else { errno = ENOMEM; res = -1; } return (res); } /* * Enter a new security descriptor into $Secure (data only) * it has to be written twice with an offset of 256KB * * Should only be called by entersecurityattr() to ensure consistency * * Returns zero if sucessful */ static int entersecurity_data(ntfs_volume *vol, const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, le32 hash, le32 keyid, off_t offs, int gap) { int res; int written1; int written2; char *fullattr; int fullsz; SECURITY_DESCRIPTOR_HEADER *phsds; res = -1; fullsz = attrsz + gap + sizeof(SECURITY_DESCRIPTOR_HEADER); fullattr = (char*)ntfs_malloc(fullsz); if (fullattr) { /* * Clear the gap from previous descriptor * this could be useful for appending the second * copy to the end of file. When creating a new * 256K block, the gap is cleared while writing * the first copy */ if (gap) memset(fullattr,0,gap); memcpy(&fullattr[gap + sizeof(SECURITY_DESCRIPTOR_HEADER)], attr,attrsz); phsds = (SECURITY_DESCRIPTOR_HEADER*)&fullattr[gap]; phsds->hash = hash; phsds->security_id = keyid; phsds->offset = cpu_to_le64(offs); phsds->length = cpu_to_le32(fullsz - gap); written1 = ntfs_attr_data_write(vol->secure_ni, STREAM_SDS, 4, fullattr, fullsz, offs - gap); written2 = ntfs_attr_data_write(vol->secure_ni, STREAM_SDS, 4, fullattr, fullsz, offs - gap + ALIGN_SDS_BLOCK); if ((written1 == fullsz) && (written2 == written1)) { /* * Make sure the data size for $SDS marks the end * of the last security attribute. Windows uses * this to determine where the next attribute will * be written, which causes issues if chkdsk had * previously deleted the last entries without * adjusting the size. */ res = ntfs_attr_shrink_size(vol->secure_ni,STREAM_SDS, 4, offs - gap + ALIGN_SDS_BLOCK + fullsz); } else errno = ENOSPC; free(fullattr); } else errno = ENOMEM; return (res); } /* * Enter a new security descriptor in $Secure (indexes only) * * Should only be called by entersecurityattr() to ensure consistency * * Returns zero if sucessful */ static int entersecurity_indexes(ntfs_volume *vol, s64 attrsz, le32 hash, le32 keyid, off_t offs) { union { struct { le32 dataoffsl; le32 dataoffsh; } parts; le64 all; } realign; int res; ntfs_index_context *xsii; ntfs_index_context *xsdh; struct SII newsii; struct SDH newsdh; res = -1; /* enter a new $SII record */ xsii = vol->secure_xsii; ntfs_index_ctx_reinit(xsii); newsii.offs = const_cpu_to_le16(20); newsii.size = const_cpu_to_le16(sizeof(struct SII) - 20); newsii.fill1 = const_cpu_to_le32(0); newsii.indexsz = const_cpu_to_le16(sizeof(struct SII)); newsii.indexksz = const_cpu_to_le16(sizeof(SII_INDEX_KEY)); newsii.flags = const_cpu_to_le16(0); newsii.fill2 = const_cpu_to_le16(0); newsii.keysecurid = keyid; newsii.hash = hash; newsii.securid = keyid; realign.all = cpu_to_le64(offs); newsii.dataoffsh = realign.parts.dataoffsh; newsii.dataoffsl = realign.parts.dataoffsl; newsii.datasize = cpu_to_le32(attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER)); if (!ntfs_ie_add(xsii,(INDEX_ENTRY*)&newsii)) { /* enter a new $SDH record */ xsdh = vol->secure_xsdh; ntfs_index_ctx_reinit(xsdh); newsdh.offs = const_cpu_to_le16(24); newsdh.size = const_cpu_to_le16( sizeof(SECURITY_DESCRIPTOR_HEADER)); newsdh.fill1 = const_cpu_to_le32(0); newsdh.indexsz = const_cpu_to_le16( sizeof(struct SDH)); newsdh.indexksz = const_cpu_to_le16( sizeof(SDH_INDEX_KEY)); newsdh.flags = const_cpu_to_le16(0); newsdh.fill2 = const_cpu_to_le16(0); newsdh.keyhash = hash; newsdh.keysecurid = keyid; newsdh.hash = hash; newsdh.securid = keyid; newsdh.dataoffsh = realign.parts.dataoffsh; newsdh.dataoffsl = realign.parts.dataoffsl; newsdh.datasize = cpu_to_le32(attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER)); /* special filler value, Windows generally */ /* fills with 0x00490049, sometimes with zero */ newsdh.fill3 = const_cpu_to_le32(0x00490049); if (!ntfs_ie_add(xsdh,(INDEX_ENTRY*)&newsdh)) res = 0; } return (res); } /* * Enter a new security descriptor in $Secure (data and indexes) * Returns id of entry, or zero if there is a problem. * (should not be called for NTFS version < 3.0) * * important : calls have to be serialized, however no locking is * needed while fuse is not multithreaded */ static le32 entersecurityattr(ntfs_volume *vol, const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, le32 hash) { union { struct { le32 dataoffsl; le32 dataoffsh; } parts; le64 all; } realign; le32 securid; le32 keyid; u32 newkey; off_t offs; int gap; int size; BOOL found; struct SII *psii; INDEX_ENTRY *entry; INDEX_ENTRY *next; ntfs_index_context *xsii; int retries; ntfs_attr *na; int olderrno; /* find the first available securid beyond the last key */ /* in $Secure:$SII. This also determines the first */ /* available location in $Secure:$SDS, as this stream */ /* is always appended to and the id's are allocated */ /* in sequence */ securid = const_cpu_to_le32(0); xsii = vol->secure_xsii; ntfs_index_ctx_reinit(xsii); offs = size = 0; keyid = const_cpu_to_le32(-1); olderrno = errno; found = !ntfs_index_lookup((char*)&keyid, sizeof(SII_INDEX_KEY), xsii); if (!found && (errno != ENOENT)) { ntfs_log_perror("Inconsistency in index $SII"); psii = (struct SII*)NULL; } else { /* restore errno to avoid misinterpretation */ errno = olderrno; entry = xsii->entry; psii = (struct SII*)xsii->entry; } if (psii) { /* * Get last entry in block, but must get first one * one first, as we should already be beyond the * last one. For some reason the search for the last * entry sometimes does not return the last block... * we assume this can only happen in root block */ if (xsii->is_in_root) entry = ntfs_ie_get_first ((INDEX_HEADER*)&xsii->ir->index); else entry = ntfs_ie_get_first ((INDEX_HEADER*)&xsii->ib->index); /* * All index blocks should be at least half full * so there always is a last entry but one, * except when creating the first entry in index root. * This was however found not to be true : chkdsk * sometimes deletes all the (unused) keys in the last * index block without rebalancing the tree. * When this happens, a new search is restarted from * the smallest key. */ keyid = const_cpu_to_le32(0); retries = 0; while (entry) { next = ntfs_index_next(entry,xsii); if (next) { psii = (struct SII*)next; /* save last key and */ /* available position */ keyid = psii->keysecurid; realign.parts.dataoffsh = psii->dataoffsh; realign.parts.dataoffsl = psii->dataoffsl; offs = le64_to_cpu(realign.all); size = le32_to_cpu(psii->datasize); } entry = next; if (!entry && !keyid && !retries) { /* search failed, retry from smallest key */ ntfs_index_ctx_reinit(xsii); found = !ntfs_index_lookup((char*)&keyid, sizeof(SII_INDEX_KEY), xsii); if (!found && (errno != ENOENT)) { ntfs_log_perror("Index $SII is broken"); psii = (struct SII*)NULL; } else { /* restore errno */ errno = olderrno; entry = xsii->entry; psii = (struct SII*)entry; } if (psii && !(psii->flags & INDEX_ENTRY_END)) { /* save first key and */ /* available position */ keyid = psii->keysecurid; realign.parts.dataoffsh = psii->dataoffsh; realign.parts.dataoffsl = psii->dataoffsl; offs = le64_to_cpu(realign.all); size = le32_to_cpu(psii->datasize); } retries++; } } } if (!keyid) { /* * could not find any entry, before creating the first * entry, make a double check by making sure size of $SII * is less than needed for one entry */ securid = const_cpu_to_le32(0); na = ntfs_attr_open(vol->secure_ni,AT_INDEX_ROOT,sii_stream,4); if (na) { if ((size_t)na->data_size < (sizeof(struct SII) + sizeof(INDEX_ENTRY_HEADER))) { ntfs_log_error("Creating the first security_id\n"); securid = const_cpu_to_le32(FIRST_SECURITY_ID); } ntfs_attr_close(na); } if (!securid) { ntfs_log_error("Error creating a security_id\n"); errno = EIO; } } else { newkey = le32_to_cpu(keyid) + 1; securid = cpu_to_le32(newkey); } /* * The security attr has to be written twice 256KB * apart. This implies that offsets like * 0x40000*odd_integer must be left available for * the second copy. So align to next block when * the last byte overflows on a wrong block. */ if (securid) { gap = (-size) & (ALIGN_SDS_ENTRY - 1); offs += gap + size; if ((offs + attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) & ALIGN_SDS_BLOCK) { offs = ((offs + attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) | (ALIGN_SDS_BLOCK - 1)) + 1; } if (!(offs & (ALIGN_SDS_BLOCK - 1))) entersecurity_stuff(vol, offs); /* * now write the security attr to storage : * first data, then SII, then SDH * If failure occurs while writing SDS, data will never * be accessed through indexes, and will be overwritten * by the next allocated descriptor * If failure occurs while writing SII, the id has not * recorded and will be reallocated later * If failure occurs while writing SDH, the space allocated * in SDS or SII will not be reused, an inconsistency * will persist with no significant consequence */ if (entersecurity_data(vol, attr, attrsz, hash, securid, offs, gap) || entersecurity_indexes(vol, attrsz, hash, securid, offs)) securid = const_cpu_to_le32(0); } /* inode now is dirty, synchronize it all */ ntfs_index_entry_mark_dirty(vol->secure_xsii); ntfs_index_ctx_reinit(vol->secure_xsii); ntfs_index_entry_mark_dirty(vol->secure_xsdh); ntfs_index_ctx_reinit(vol->secure_xsdh); NInoSetDirty(vol->secure_ni); if (ntfs_inode_sync(vol->secure_ni)) ntfs_log_perror("Could not sync $Secure\n"); return (securid); } /* * Find a matching security descriptor in $Secure, * if none, allocate a new id and write the descriptor to storage * Returns id of entry, or zero if there is a problem. * * important : calls have to be serialized, however no locking is * needed while fuse is not multithreaded */ static le32 setsecurityattr(ntfs_volume *vol, const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz) { struct SDH *psdh; /* this is an image of index (le) */ union { struct { le32 dataoffsl; le32 dataoffsh; } parts; le64 all; } realign; BOOL found; BOOL collision; size_t size; size_t rdsize; s64 offs; int res; ntfs_index_context *xsdh; char *oldattr; SDH_INDEX_KEY key; INDEX_ENTRY *entry; le32 securid; le32 hash; int olderrno; hash = ntfs_security_hash(attr,attrsz); oldattr = (char*)NULL; securid = const_cpu_to_le32(0); res = 0; xsdh = vol->secure_xsdh; if (vol->secure_ni && xsdh && !vol->secure_reentry++) { ntfs_index_ctx_reinit(xsdh); /* * find the nearest key as (hash,0) * (do not search for partial key : in case of collision, * it could return a key which is not the first one which * collides) */ key.hash = hash; key.security_id = const_cpu_to_le32(0); olderrno = errno; found = !ntfs_index_lookup((char*)&key, sizeof(SDH_INDEX_KEY), xsdh); if (!found && (errno != ENOENT)) ntfs_log_perror("Inconsistency in index $SDH"); else { /* restore errno to avoid misinterpretation */ errno = olderrno; entry = xsdh->entry; found = FALSE; /* * lookup() may return a node with no data, * if so get next */ if (entry->ie_flags & INDEX_ENTRY_END) entry = ntfs_index_next(entry,xsdh); do { collision = FALSE; psdh = (struct SDH*)entry; if (psdh) size = (size_t) le32_to_cpu(psdh->datasize) - sizeof(SECURITY_DESCRIPTOR_HEADER); else size = 0; /* if hash is not the same, the key is not present */ if (psdh && (size > 0) && (psdh->keyhash == hash)) { /* if hash is the same */ /* check the whole record */ realign.parts.dataoffsh = psdh->dataoffsh; realign.parts.dataoffsl = psdh->dataoffsl; offs = le64_to_cpu(realign.all) + sizeof(SECURITY_DESCRIPTOR_HEADER); oldattr = (char*)ntfs_malloc(size); if (oldattr) { rdsize = ntfs_attr_data_read( vol->secure_ni, STREAM_SDS, 4, oldattr, size, offs); found = (rdsize == size) && !memcmp(oldattr,attr,size); free(oldattr); /* if the records do not compare */ /* (hash collision), try next one */ if (!found) { entry = ntfs_index_next( entry,xsdh); collision = TRUE; } } else res = ENOMEM; } } while (collision && entry); if (found) securid = psdh->keysecurid; else { if (res) { errno = res; securid = const_cpu_to_le32(0); } else { /* * no matching key : * have to build a new one */ securid = entersecurityattr(vol, attr, attrsz, hash); } } } } if (--vol->secure_reentry) ntfs_log_perror("Reentry error, check no multithreading\n"); return (securid); } /* * Update the security descriptor of a file * Either as an attribute (complying with pre v3.x NTFS version) * or, when possible, as an entry in $Secure (for NTFS v3.x) * * returns 0 if success */ static int update_secur_descr(ntfs_volume *vol, char *newattr, ntfs_inode *ni) { int newattrsz; int written; int res; ntfs_attr *na; newattrsz = ntfs_attr_size(newattr); #if !FORCE_FORMAT_v1x if ((vol->major_ver < 3) || !vol->secure_ni) { #endif /* update for NTFS format v1.x */ /* update the old security attribute */ na = ntfs_attr_open(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); if (na) { /* resize attribute */ res = ntfs_attr_truncate(na, (s64) newattrsz); /* overwrite value */ if (!res) { written = (int)ntfs_attr_pwrite(na, (s64) 0, (s64) newattrsz, newattr); if (written != newattrsz) { ntfs_log_error("Failed to update " "a v1.x security descriptor\n"); errno = EIO; res = -1; } } ntfs_attr_close(na); /* if old security attribute was found, also */ /* truncate standard information attribute to v1.x */ /* this is needed when security data is wanted */ /* as v1.x though volume is formatted for v3.x */ na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0); if (na) { clear_nino_flag(ni, v3_Extensions); /* * Truncating the record does not sweep extensions * from copy in memory. Clear security_id to be safe */ ni->security_id = const_cpu_to_le32(0); res = ntfs_attr_truncate(na, (s64)48); ntfs_attr_close(na); clear_nino_flag(ni, v3_Extensions); } } else { /* * insert the new security attribute if there * were none */ res = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0, (u8*)newattr, (s64) newattrsz); } #if !FORCE_FORMAT_v1x } else { /* update for NTFS format v3.x */ le32 securid; securid = setsecurityattr(vol, (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, (s64)newattrsz); if (securid) { na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0); if (na) { res = 0; if (!test_nino_flag(ni, v3_Extensions)) { /* expand standard information attribute to v3.x */ res = ntfs_attr_truncate(na, (s64)sizeof(STANDARD_INFORMATION)); ni->owner_id = const_cpu_to_le32(0); ni->quota_charged = const_cpu_to_le64(0); ni->usn = const_cpu_to_le64(0); ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); } set_nino_flag(ni, v3_Extensions); ni->security_id = securid; ntfs_attr_close(na); } else { ntfs_log_error("Failed to update " "standard informations\n"); errno = EIO; res = -1; } } else res = -1; } #endif /* mark node as dirty */ NInoSetDirty(ni); return (res); } /* * Upgrade the security descriptor of a file * This is intended to allow graceful upgrades for files which * were created in previous versions, with a security attributes * and no security id. * * It will allocate a security id and replace the individual * security attribute by a reference to the global one * * Special files are not upgraded (currently / and files in * directories /$*) * * Though most code is similar to update_secur_desc() it has * been kept apart to facilitate the further processing of * special cases or even to remove it if found dangerous. * * returns 0 if success, * 1 if not upgradable. This is not an error. * -1 if there is a problem */ static int upgrade_secur_desc(ntfs_volume *vol, const char *attr, ntfs_inode *ni) { int attrsz; int res; le32 securid; ntfs_attr *na; /* * upgrade requires NTFS format v3.x * also refuse upgrading for special files * whose number is less than FILE_first_user */ if ((vol->major_ver >= 3) && (ni->mft_no >= FILE_first_user)) { attrsz = ntfs_attr_size(attr); securid = setsecurityattr(vol, (const SECURITY_DESCRIPTOR_RELATIVE*)attr, (s64)attrsz); if (securid) { na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0); if (na) { /* expand standard information attribute to v3.x */ res = ntfs_attr_truncate(na, (s64)sizeof(STANDARD_INFORMATION)); ni->owner_id = const_cpu_to_le32(0); ni->quota_charged = const_cpu_to_le64(0); ni->usn = const_cpu_to_le64(0); ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); set_nino_flag(ni, v3_Extensions); ni->security_id = securid; ntfs_attr_close(na); } else { ntfs_log_error("Failed to upgrade " "standard informations\n"); errno = EIO; res = -1; } } else res = -1; /* mark node as dirty */ NInoSetDirty(ni); } else res = 1; return (res); } /* * Optional simplified checking of group membership * * This only takes into account the groups defined in * /etc/group at initialization time. * It does not take into account the groups dynamically set by * setgroups() nor the changes in /etc/group since initialization * * This optional method could be useful if standard checking * leads to a performance concern. * * Should not be called for user root, however the group may be root * */ static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { BOOL ingroup; int grcnt; gid_t *groups; struct MAPPING *user; ingroup = FALSE; if (uid) { user = scx->mapping[MAPUSERS]; while (user && ((uid_t)user->xid != uid)) user = user->next; if (user) { groups = user->groups; grcnt = user->grcnt; while ((--grcnt >= 0) && (groups[grcnt] != gid)) { } ingroup = (grcnt >= 0); } } return (ingroup); } #if defined(__sun) && defined (__SVR4) /* * Check whether current thread owner is member of file group * Solaris/OpenIndiana version * Should not be called for user root, however the group may be root * * The group list is available in "/proc/$PID/cred" * */ static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { typedef struct prcred { uid_t pr_euid; /* effective user id */ uid_t pr_ruid; /* real user id */ uid_t pr_suid; /* saved user id (from exec) */ gid_t pr_egid; /* effective group id */ gid_t pr_rgid; /* real group id */ gid_t pr_sgid; /* saved group id (from exec) */ int pr_ngroups; /* number of supplementary groups */ gid_t pr_groups[1]; /* array of supplementary groups */ } prcred_t; enum { readset = 16 }; prcred_t basecreds; gid_t groups[readset]; char filename[64]; int fd; int k; int cnt; gid_t *p; BOOL ismember; int got; pid_t tid; if (scx->vol->secure_flags & (1 << SECURITY_STATICGRPS)) ismember = staticgroupmember(scx, uid, gid); else { ismember = FALSE; /* default return */ tid = scx->tid; sprintf(filename,"/proc/%u/cred",tid); fd = open(filename,O_RDONLY); if (fd >= 0) { got = read(fd, &basecreds, sizeof(prcred_t)); if (got == sizeof(prcred_t)) { if (basecreds.pr_egid == gid) ismember = TRUE; p = basecreds.pr_groups; cnt = 1; k = 0; while (!ismember && (k < basecreds.pr_ngroups) && (cnt > 0) && (*p != gid)) { k++; cnt--; p++; if (cnt <= 0) { got = read(fd, groups, readset*sizeof(gid_t)); cnt = got/sizeof(gid_t); p = groups; } } if ((cnt > 0) && (k < basecreds.pr_ngroups)) ismember = TRUE; } close(fd); } } return (ismember); } #else /* defined(__sun) && defined (__SVR4) */ /* * Check whether current thread owner is member of file group * Linux version * Should not be called for user root, however the group may be root * * As indicated by Miklos Szeredi : * * The group list is available in * * /proc/$PID/task/$TID/status * * and fuse supplies TID in get_fuse_context()->pid. The only problem is * finding out PID, for which I have no good solution, except to iterate * through all processes. This is rather slow, but may be speeded up * with caching and heuristics (for single threaded programs PID = TID). * * The following implementation gets the group list from * /proc/$TID/task/$TID/status which apparently exists and * contains the same data. */ static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { static char key[] = "\nGroups:"; char buf[BUFSZ+1]; char filename[64]; enum { INKEY, INSEP, INNUM, INEND } state; int fd; char c; int matched; BOOL ismember; int got; char *p; gid_t grp; pid_t tid; if (scx->vol->secure_flags & (1 << SECURITY_STATICGRPS)) ismember = staticgroupmember(scx, uid, gid); else { ismember = FALSE; /* default return */ tid = scx->tid; sprintf(filename,"/proc/%u/task/%u/status",tid,tid); fd = open(filename,O_RDONLY); if (fd >= 0) { got = read(fd, buf, BUFSZ); buf[got] = 0; state = INKEY; matched = 0; p = buf; grp = 0; /* * A simple automaton to process lines like * Groups: 14 500 513 */ do { c = *p++; if (!c) { /* refill buffer */ got = read(fd, buf, BUFSZ); buf[got] = 0; p = buf; c = *p++; /* 0 at end of file */ } switch (state) { case INKEY : if (key[matched] == c) { if (!key[++matched]) state = INSEP; } else if (key[0] == c) matched = 1; else matched = 0; break; case INSEP : if ((c >= '0') && (c <= '9')) { grp = c - '0'; state = INNUM; } else if ((c != ' ') && (c != '\t')) state = INEND; break; case INNUM : if ((c >= '0') && (c <= '9')) grp = grp*10 + c - '0'; else { ismember = (grp == gid); if ((c != ' ') && (c != '\t')) state = INEND; else state = INSEP; } default : break; } } while (!ismember && c && (state != INEND)); close(fd); if (!c) ntfs_log_error("No group record found in %s\n",filename); } else ntfs_log_error("Could not open %s\n",filename); } return (ismember); } #endif /* defined(__sun) && defined (__SVR4) */ #if POSIXACLS /* * Extract the basic permissions from a Posix ACL * * This is only to be used when Posix ACLs are compiled in, * but not enabled in the mount options. * * it replaces the permission mask by the group permissions. * If special groups are mapped, they are also considered as world. */ static int ntfs_basic_perms(const struct SECURITY_CONTEXT *scx, const struct POSIX_SECURITY *pxdesc) { int k; int perms; const struct POSIX_ACE *pace; const struct MAPPING* group; k = 0; perms = pxdesc->mode; for (k=0; k < pxdesc->acccnt; k++) { pace = &pxdesc->acl.ace[k]; if (pace->tag == POSIX_ACL_GROUP_OBJ) perms = (perms & 07707) | ((pace->perms & 7) << 3); else if (pace->tag == POSIX_ACL_GROUP) { group = scx->mapping[MAPGROUPS]; while (group && (group->xid != pace->id)) group = group->next; if (group && group->grcnt && (*(group->groups) == (gid_t)pace->id)) perms |= pace->perms & 7; } } return (perms); } #endif /* POSIXACLS */ /* * Cacheing is done two-way : * - from uid, gid and perm to securid (CACHED_SECURID) * - from a securid to uid, gid and perm (CACHED_PERMISSIONS) * * CACHED_SECURID data is kept in a most-recent-first list * which should not be too long to be efficient. Its optimal * size is depends on usage and is hard to determine. * * CACHED_PERMISSIONS data is kept in a two-level indexed array. It * is optimal at the expense of storage. Use of a most-recent-first * list would save memory and provide similar performances for * standard usage, but not for file servers with too many file * owners * * CACHED_PERMISSIONS_LEGACY is a special case for CACHED_PERMISSIONS * for legacy directories which were not allocated a security_id * it is organized in a most-recent-first list. * * In main caches, data is never invalidated, as the meaning of * a security_id only changes when user mapping is changed, which * current implies remounting. However returned entries may be * overwritten at next update, so data has to be copied elsewhere * before another cache update is made. * In legacy cache, data has to be invalidated when protection is * changed. * * Though the same data may be found in both list, they * must be kept separately : the interpretation of ACL * in both direction are approximations which could be non * reciprocal for some configuration of the user mapping data * * During the process of recompiling ntfs-3g from a tgz archive, * security processing added 7.6% to the cpu time used by ntfs-3g * and 30% if the cache is disabled. */ static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, u32 securindex) { struct PERMISSIONS_CACHE *cache; unsigned int index1; unsigned int i; cache = (struct PERMISSIONS_CACHE*)NULL; /* create the first permissions blocks */ index1 = securindex >> CACHE_PERMISSIONS_BITS; cache = (struct PERMISSIONS_CACHE*) ntfs_malloc(sizeof(struct PERMISSIONS_CACHE) + index1*sizeof(struct CACHED_PERMISSIONS*)); if (cache) { cache->head.last = index1; cache->head.p_reads = 0; cache->head.p_hits = 0; cache->head.p_writes = 0; *scx->pseccache = cache; for (i=0; i<=index1; i++) cache->cachetable[i] = (struct CACHED_PERMISSIONS*)NULL; } return (cache); } /* * Free memory used by caches * The only purpose is to facilitate the detection of memory leaks */ static void free_caches(struct SECURITY_CONTEXT *scx) { unsigned int index1; struct PERMISSIONS_CACHE *pseccache; pseccache = *scx->pseccache; if (pseccache) { for (index1=0; index1<=pseccache->head.last; index1++) if (pseccache->cachetable[index1]) { #if POSIXACLS struct CACHED_PERMISSIONS *cacheentry; unsigned int index2; for (index2=0; index2<(1<< CACHE_PERMISSIONS_BITS); index2++) { cacheentry = &pseccache->cachetable[index1][index2]; if (cacheentry->valid && cacheentry->pxdesc) free(cacheentry->pxdesc); } #endif free(pseccache->cachetable[index1]); } free(pseccache); } } static int compare(const struct CACHED_SECURID *cached, const struct CACHED_SECURID *item) { #if POSIXACLS size_t csize; size_t isize; /* only compare data and sizes */ csize = (cached->variable ? sizeof(struct POSIX_ACL) + (((struct POSIX_SECURITY*)cached->variable)->acccnt + ((struct POSIX_SECURITY*)cached->variable)->defcnt) *sizeof(struct POSIX_ACE) : 0); isize = (item->variable ? sizeof(struct POSIX_ACL) + (((struct POSIX_SECURITY*)item->variable)->acccnt + ((struct POSIX_SECURITY*)item->variable)->defcnt) *sizeof(struct POSIX_ACE) : 0); return ((cached->uid != item->uid) || (cached->gid != item->gid) || (cached->dmode != item->dmode) || (csize != isize) || (csize && isize && memcmp(&((struct POSIX_SECURITY*)cached->variable)->acl, &((struct POSIX_SECURITY*)item->variable)->acl, csize))); #else return ((cached->uid != item->uid) || (cached->gid != item->gid) || (cached->dmode != item->dmode)); #endif } static int leg_compare(const struct CACHED_PERMISSIONS_LEGACY *cached, const struct CACHED_PERMISSIONS_LEGACY *item) { return (cached->mft_no != item->mft_no); } /* * Resize permission cache table * do not call unless resizing is needed * * If allocation fails, the cache size is not updated * Lack of memory is not considered as an error, the cache is left * consistent and errno is not set. */ static void resize_cache(struct SECURITY_CONTEXT *scx, u32 securindex) { struct PERMISSIONS_CACHE *oldcache; struct PERMISSIONS_CACHE *newcache; int newcnt; int oldcnt; unsigned int index1; unsigned int i; oldcache = *scx->pseccache; index1 = securindex >> CACHE_PERMISSIONS_BITS; newcnt = index1 + 1; if (newcnt <= ((CACHE_PERMISSIONS_SIZE + (1 << CACHE_PERMISSIONS_BITS) - 1) >> CACHE_PERMISSIONS_BITS)) { /* expand cache beyond current end, do not use realloc() */ /* to avoid losing data when there is no more memory */ oldcnt = oldcache->head.last + 1; newcache = (struct PERMISSIONS_CACHE*) ntfs_malloc( sizeof(struct PERMISSIONS_CACHE) + (newcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); if (newcache) { memcpy(newcache,oldcache, sizeof(struct PERMISSIONS_CACHE) + (oldcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); free(oldcache); /* mark new entries as not valid */ for (i=newcache->head.last+1; i<=index1; i++) newcache->cachetable[i] = (struct CACHED_PERMISSIONS*)NULL; newcache->head.last = index1; *scx->pseccache = newcache; } } } /* * Enter uid, gid and mode into cache, if possible * * returns the updated or created cache entry, * or NULL if not possible (typically if there is no * security id associated) */ #if POSIXACLS static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, struct POSIX_SECURITY *pxdesc) #else static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode) #endif { struct CACHED_PERMISSIONS *cacheentry; struct CACHED_PERMISSIONS *cacheblock; struct PERMISSIONS_CACHE *pcache; u32 securindex; #if POSIXACLS int pxsize; struct POSIX_SECURITY *pxcached; #endif unsigned int index1; unsigned int index2; int i; /* cacheing is only possible if a security_id has been defined */ if (test_nino_flag(ni, v3_Extensions) && ni->security_id) { /* * Immediately test the most frequent situation * where the entry exists */ securindex = le32_to_cpu(ni->security_id); index1 = securindex >> CACHE_PERMISSIONS_BITS; index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); pcache = *scx->pseccache; if (pcache && (pcache->head.last >= index1) && pcache->cachetable[index1]) { cacheentry = &pcache->cachetable[index1][index2]; cacheentry->uid = uid; cacheentry->gid = gid; #if POSIXACLS if (cacheentry->valid && cacheentry->pxdesc) free(cacheentry->pxdesc); if (pxdesc) { pxsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); pxcached = (struct POSIX_SECURITY*)malloc(pxsize); if (pxcached) { memcpy(pxcached, pxdesc, pxsize); cacheentry->pxdesc = pxcached; } else { cacheentry->valid = 0; cacheentry = (struct CACHED_PERMISSIONS*)NULL; } cacheentry->mode = pxdesc->mode & 07777; } else cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; #else cacheentry->mode = mode & 07777; #endif cacheentry->inh_fileid = const_cpu_to_le32(0); cacheentry->inh_dirid = const_cpu_to_le32(0); cacheentry->valid = 1; pcache->head.p_writes++; } else { if (!pcache) { /* create the first cache block */ pcache = create_caches(scx, securindex); } else { if (index1 > pcache->head.last) { resize_cache(scx, securindex); pcache = *scx->pseccache; } } /* allocate block, if cache table was allocated */ if (pcache && (index1 <= pcache->head.last)) { cacheblock = (struct CACHED_PERMISSIONS*) malloc(sizeof(struct CACHED_PERMISSIONS) << CACHE_PERMISSIONS_BITS); pcache->cachetable[index1] = cacheblock; for (i=0; i<(1 << CACHE_PERMISSIONS_BITS); i++) cacheblock[i].valid = 0; cacheentry = &cacheblock[index2]; if (cacheentry) { cacheentry->uid = uid; cacheentry->gid = gid; #if POSIXACLS if (pxdesc) { pxsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); pxcached = (struct POSIX_SECURITY*)malloc(pxsize); if (pxcached) { memcpy(pxcached, pxdesc, pxsize); cacheentry->pxdesc = pxcached; } else { cacheentry->valid = 0; cacheentry = (struct CACHED_PERMISSIONS*)NULL; } cacheentry->mode = pxdesc->mode & 07777; } else cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; #else cacheentry->mode = mode & 07777; #endif cacheentry->inh_fileid = const_cpu_to_le32(0); cacheentry->inh_dirid = const_cpu_to_le32(0); cacheentry->valid = 1; pcache->head.p_writes++; } } else cacheentry = (struct CACHED_PERMISSIONS*)NULL; } } else { cacheentry = (struct CACHED_PERMISSIONS*)NULL; #if CACHE_LEGACY_SIZE if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { struct CACHED_PERMISSIONS_LEGACY wanted; struct CACHED_PERMISSIONS_LEGACY *legacy; wanted.perm.uid = uid; wanted.perm.gid = gid; #if POSIXACLS wanted.perm.mode = pxdesc->mode & 07777; wanted.perm.inh_fileid = const_cpu_to_le32(0); wanted.perm.inh_dirid = const_cpu_to_le32(0); wanted.mft_no = ni->mft_no; wanted.variable = (void*)pxdesc; wanted.varsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); #else wanted.perm.mode = mode & 07777; wanted.perm.inh_fileid = const_cpu_to_le32(0); wanted.perm.inh_dirid = const_cpu_to_le32(0); wanted.mft_no = ni->mft_no; wanted.variable = (void*)NULL; wanted.varsize = 0; #endif legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_enter_cache( scx->vol->legacy_cache, GENERIC(&wanted), (cache_compare)leg_compare); if (legacy) { cacheentry = &legacy->perm; #if POSIXACLS /* * give direct access to the cached pxdesc * in the permissions structure */ cacheentry->pxdesc = legacy->variable; #endif } } #endif } return (cacheentry); } /* * Fetch owner, group and permission of a file, if cached * * Beware : do not use the returned entry after a cache update : * the cache may be relocated making the returned entry meaningless * * returns the cache entry, or NULL if not available */ static struct CACHED_PERMISSIONS *fetch_cache(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) { struct CACHED_PERMISSIONS *cacheentry; struct PERMISSIONS_CACHE *pcache; u32 securindex; unsigned int index1; unsigned int index2; /* cacheing is only possible if a security_id has been defined */ cacheentry = (struct CACHED_PERMISSIONS*)NULL; if (test_nino_flag(ni, v3_Extensions) && (ni->security_id)) { securindex = le32_to_cpu(ni->security_id); index1 = securindex >> CACHE_PERMISSIONS_BITS; index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); pcache = *scx->pseccache; if (pcache && (pcache->head.last >= index1) && pcache->cachetable[index1]) { cacheentry = &pcache->cachetable[index1][index2]; /* reject if entry is not valid */ if (!cacheentry->valid) cacheentry = (struct CACHED_PERMISSIONS*)NULL; else pcache->head.p_hits++; if (pcache) pcache->head.p_reads++; } } #if CACHE_LEGACY_SIZE else { cacheentry = (struct CACHED_PERMISSIONS*)NULL; if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { struct CACHED_PERMISSIONS_LEGACY wanted; struct CACHED_PERMISSIONS_LEGACY *legacy; wanted.mft_no = ni->mft_no; wanted.variable = (void*)NULL; wanted.varsize = 0; legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_fetch_cache( scx->vol->legacy_cache, GENERIC(&wanted), (cache_compare)leg_compare); if (legacy) cacheentry = &legacy->perm; } } #endif #if POSIXACLS if (cacheentry && !cacheentry->pxdesc) { ntfs_log_error("No Posix descriptor in cache\n"); cacheentry = (struct CACHED_PERMISSIONS*)NULL; } #endif return (cacheentry); } /* * Retrieve a security attribute from $Secure */ static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) { struct SII *psii; union { struct { le32 dataoffsl; le32 dataoffsh; } parts; le64 all; } realign; int found; size_t size; size_t rdsize; s64 offs; ntfs_inode *ni; ntfs_index_context *xsii; char *securattr; securattr = (char*)NULL; ni = vol->secure_ni; xsii = vol->secure_xsii; if (ni && xsii) { ntfs_index_ctx_reinit(xsii); found = !ntfs_index_lookup((char*)&id, sizeof(SII_INDEX_KEY), xsii); if (found) { psii = (struct SII*)xsii->entry; size = (size_t) le32_to_cpu(psii->datasize) - sizeof(SECURITY_DESCRIPTOR_HEADER); /* work around bad alignment problem */ realign.parts.dataoffsh = psii->dataoffsh; realign.parts.dataoffsl = psii->dataoffsl; offs = le64_to_cpu(realign.all) + sizeof(SECURITY_DESCRIPTOR_HEADER); securattr = (char*)ntfs_malloc(size); if (securattr) { rdsize = ntfs_attr_data_read( ni, STREAM_SDS, 4, securattr, size, offs); if ((rdsize != size) || !ntfs_valid_descr(securattr, rdsize)) { /* error to be logged by caller */ free(securattr); securattr = (char*)NULL; } } } else if (errno != ENOENT) ntfs_log_perror("Inconsistency in index $SII"); } if (!securattr) { ntfs_log_error("Failed to retrieve a security descriptor\n"); errno = EIO; } return (securattr); } /* * Get the security descriptor associated to a file * * Either : * - read the security descriptor attribute (v1.x format) * - or find the descriptor in $Secure:$SDS (v3.x format) * * in both case, sanity checks are done on the attribute and * the descriptor can be assumed safe * * The returned descriptor is dynamically allocated and has to be freed */ static char *getsecurityattr(ntfs_volume *vol, ntfs_inode *ni) { SII_INDEX_KEY securid; char *securattr; s64 readallsz; /* * Warning : in some situations, after fixing by chkdsk, * v3_Extensions are marked present (long standard informations) * with a default security descriptor inserted in an * attribute */ if (test_nino_flag(ni, v3_Extensions) && vol->secure_ni && ni->security_id) { /* get v3.x descriptor in $Secure */ securid.security_id = ni->security_id; securattr = retrievesecurityattr(vol,securid); if (!securattr) ntfs_log_error("Bad security descriptor for 0x%lx\n", (long)le32_to_cpu(ni->security_id)); } else { /* get v1.x security attribute */ readallsz = 0; securattr = ntfs_attr_readall(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0, &readallsz); if (securattr && !ntfs_valid_descr(securattr, readallsz)) { ntfs_log_error("Bad security descriptor for inode %lld\n", (long long)ni->mft_no); free(securattr); securattr = (char*)NULL; } } if (!securattr) { /* * in some situations, there is no security * descriptor, and chkdsk does not detect or fix * anything. This could be a normal situation. * When this happens, simulate a descriptor with * minimum rights, so that a real descriptor can * be created by chown or chmod */ ntfs_log_error("No security descriptor found for inode %lld\n", (long long)ni->mft_no); securattr = ntfs_build_descr(0, 0, adminsid, adminsid); } return (securattr); } #if POSIXACLS /* * Determine which access types to a file are allowed * according to the relation of current process to the file * * When Posix ACLs are compiled in but not enabled in the mount * options POSIX_ACL_USER, POSIX_ACL_GROUP and POSIX_ACL_MASK * are ignored. */ static int access_check_posix(struct SECURITY_CONTEXT *scx, struct POSIX_SECURITY *pxdesc, mode_t request, uid_t uid, gid_t gid) { struct POSIX_ACE *pxace; int userperms; int groupperms; int mask; BOOL somegroup; BOOL needgroups; BOOL noacl; mode_t perms; int i; noacl = !(scx->vol->secure_flags & (1 << SECURITY_ACL)); if (noacl) perms = ntfs_basic_perms(scx, pxdesc); else perms = pxdesc->mode; /* owner and root access */ if (!scx->uid || (uid == scx->uid)) { if (!scx->uid) { /* root access if owner or other execution */ if (perms & 0101) perms |= 01777; else { /* root access if some group execution */ groupperms = 0; mask = 7; for (i=pxdesc->acccnt-1; i>=0 ; i--) { pxace = &pxdesc->acl.ace[i]; switch (pxace->tag) { case POSIX_ACL_USER_OBJ : case POSIX_ACL_GROUP_OBJ : groupperms |= pxace->perms; break; case POSIX_ACL_GROUP : if (!noacl) groupperms |= pxace->perms; break; case POSIX_ACL_MASK : if (!noacl) mask = pxace->perms & 7; break; default : break; } } perms = (groupperms & mask & 1) | 6; } } else perms &= 07700; } else { /* * analyze designated users, get mask * and identify whether we need to check * the group memberships. The groups are * not needed when all groups have the * same permissions as other for the * requested modes. */ userperms = -1; groupperms = -1; needgroups = FALSE; mask = 7; for (i=pxdesc->acccnt-1; i>=0 ; i--) { pxace = &pxdesc->acl.ace[i]; switch (pxace->tag) { case POSIX_ACL_USER : if (!noacl && ((uid_t)pxace->id == scx->uid)) userperms = pxace->perms; break; case POSIX_ACL_MASK : if (!noacl) mask = pxace->perms & 7; break; case POSIX_ACL_GROUP_OBJ : if (((pxace->perms & mask) ^ perms) & (request >> 6) & 7) needgroups = TRUE; break; case POSIX_ACL_GROUP : if (!noacl && (((pxace->perms & mask) ^ perms) & (request >> 6) & 7)) needgroups = TRUE; break; default : break; } } /* designated users */ if (userperms >= 0) perms = (perms & 07000) + (userperms & mask); else if (!needgroups) perms &= 07007; else { /* owning group */ if (!(~(perms >> 3) & request & mask) && ((gid == scx->gid) || groupmember(scx, scx->uid, gid))) perms &= 07070; else if (!noacl) { /* other groups */ groupperms = -1; somegroup = FALSE; for (i=pxdesc->acccnt-1; i>=0 ; i--) { pxace = &pxdesc->acl.ace[i]; if ((pxace->tag == POSIX_ACL_GROUP) && groupmember(scx, scx->uid, pxace->id)) { if (!(~pxace->perms & request & mask)) groupperms = pxace->perms; somegroup = TRUE; } } if (groupperms >= 0) perms = (perms & 07000) + (groupperms & mask); else if (somegroup) perms = 0; else perms &= 07007; } else perms &= 07007; } } return (perms); } /* * Get permissions to access a file * Takes into account the relation of user to file (owner, group, ...) * Do no use as mode of the file * Do no call if default_permissions is set * * returns -1 if there is a problem */ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, ntfs_inode * ni, mode_t request) { const SECURITY_DESCRIPTOR_RELATIVE *phead; const struct CACHED_PERMISSIONS *cached; char *securattr; const SID *usid; /* owner of file/directory */ const SID *gsid; /* group of file/directory */ uid_t uid; gid_t gid; int perm; BOOL isdir; struct POSIX_SECURITY *pxdesc; if (!scx->mapping[MAPUSERS]) perm = 07777; else { /* check whether available in cache */ cached = fetch_cache(scx,ni); if (cached) { uid = cached->uid; gid = cached->gid; perm = access_check_posix(scx,cached->pxdesc,request,uid,gid); } else { perm = 0; /* default to no permission */ isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); securattr = getsecurityattr(scx->vol, ni); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*) securattr; gsid = (const SID*)& securattr[le32_to_cpu(phead->group)]; gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL usid = ntfs_acl_owner(securattr); pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, usid, gsid, isdir); if (pxdesc) perm = pxdesc->mode & 07777; else perm = -1; uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else usid = (const SID*)& securattr[le32_to_cpu(phead->owner)]; pxdesc = ntfs_build_permissions_posix(scx,securattr, usid, gsid, isdir); if (pxdesc) perm = pxdesc->mode & 07777; else perm = -1; if (!perm && ntfs_same_sid(usid, adminsid)) { uid = find_tenant(scx, securattr); if (uid) perm = 0700; } else uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif /* * Create a security id if there were none * and upgrade option is selected */ if (!test_nino_flag(ni, v3_Extensions) && (perm >= 0) && (scx->vol->secure_flags & (1 << SECURITY_ADDSECURIDS))) { upgrade_secur_desc(scx->vol, securattr, ni); /* * fetch owner and group for cacheing * if there is a securid */ } if (test_nino_flag(ni, v3_Extensions) && (perm >= 0)) { enter_cache(scx, ni, uid, gid, pxdesc); } if (pxdesc) { perm = access_check_posix(scx,pxdesc,request,uid,gid); free(pxdesc); } free(securattr); } else { perm = -1; uid = gid = 0; } } } return (perm); } /* * Get a Posix ACL * * returns size or -errno if there is a problem * if size was too small, no copy is done and errno is not set, * the caller is expected to issue a new call */ int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, const char *name, char *value, size_t size) { const SECURITY_DESCRIPTOR_RELATIVE *phead; struct POSIX_SECURITY *pxdesc; const struct CACHED_PERMISSIONS *cached; char *securattr; const SID *usid; /* owner of file/directory */ const SID *gsid; /* group of file/directory */ uid_t uid; gid_t gid; BOOL isdir; size_t outsize; outsize = 0; /* default to error */ if (!scx->mapping[MAPUSERS]) errno = ENOTSUP; else { /* check whether available in cache */ cached = fetch_cache(scx,ni); if (cached) pxdesc = cached->pxdesc; else { securattr = getsecurityattr(scx->vol, ni); isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*) securattr; gsid = (const SID*)& securattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL usid = ntfs_acl_owner(securattr); #else usid = (const SID*)& securattr[le32_to_cpu(phead->owner)]; #endif pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, usid, gsid, isdir); /* * fetch owner and group for cacheing */ if (pxdesc) { /* * Create a security id if there were none * and upgrade option is selected */ if (!test_nino_flag(ni, v3_Extensions) && (scx->vol->secure_flags & (1 << SECURITY_ADDSECURIDS))) { upgrade_secur_desc(scx->vol, securattr, ni); } #if OWNERFROMACL uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else if (!(pxdesc->mode & 07777) && ntfs_same_sid(usid, adminsid)) { uid = find_tenant(scx, securattr); } else uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); if (pxdesc->tagsset & POSIX_ACL_EXTENSIONS) enter_cache(scx, ni, uid, gid, pxdesc); } free(securattr); } else pxdesc = (struct POSIX_SECURITY*)NULL; } if (pxdesc) { if (ntfs_valid_posix(pxdesc)) { if (!strcmp(name,"system.posix_acl_default")) { if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) outsize = sizeof(struct POSIX_ACL) + pxdesc->defcnt*sizeof(struct POSIX_ACE); else { /* * getting default ACL from plain file : * return EACCES if size > 0 as * indicated in the man, but return ok * if size == 0, so that ls does not * display an error */ if (size > 0) { outsize = 0; errno = EACCES; } else outsize = sizeof(struct POSIX_ACL); } if (outsize && (outsize <= size)) { memcpy(value,&pxdesc->acl,sizeof(struct POSIX_ACL)); memcpy(&value[sizeof(struct POSIX_ACL)], &pxdesc->acl.ace[pxdesc->firstdef], outsize-sizeof(struct POSIX_ACL)); } } else { outsize = sizeof(struct POSIX_ACL) + pxdesc->acccnt*sizeof(struct POSIX_ACE); if (outsize <= size) memcpy(value,&pxdesc->acl,outsize); } } else { outsize = 0; errno = EIO; ntfs_log_error("Invalid Posix ACL built\n"); } if (!cached) free(pxdesc); } else outsize = 0; } return (outsize ? (int)outsize : -errno); } #else /* POSIXACLS */ /* * Get permissions to access a file * Takes into account the relation of user to file (owner, group, ...) * Do no use as mode of the file * * returns -1 if there is a problem */ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, mode_t request) { const SECURITY_DESCRIPTOR_RELATIVE *phead; const struct CACHED_PERMISSIONS *cached; char *securattr; const SID *usid; /* owner of file/directory */ const SID *gsid; /* group of file/directory */ BOOL isdir; uid_t uid; gid_t gid; int perm; if (!scx->mapping[MAPUSERS] || (!scx->uid && !(request & S_IEXEC))) perm = 07777; else { /* check whether available in cache */ cached = fetch_cache(scx,ni); if (cached) { perm = cached->mode; uid = cached->uid; gid = cached->gid; } else { perm = 0; /* default to no permission */ isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); securattr = getsecurityattr(scx->vol, ni); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*) securattr; gsid = (const SID*)& securattr[le32_to_cpu(phead->group)]; gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL usid = ntfs_acl_owner(securattr); perm = ntfs_build_permissions(securattr, usid, gsid, isdir); uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else usid = (const SID*)& securattr[le32_to_cpu(phead->owner)]; perm = ntfs_build_permissions(securattr, usid, gsid, isdir); if (!perm && ntfs_same_sid(usid, adminsid)) { uid = find_tenant(scx, securattr); if (uid) perm = 0700; } else uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif /* * Create a security id if there were none * and upgrade option is selected */ if (!test_nino_flag(ni, v3_Extensions) && (perm >= 0) && (scx->vol->secure_flags & (1 << SECURITY_ADDSECURIDS))) { upgrade_secur_desc(scx->vol, securattr, ni); /* * fetch owner and group for cacheing * if there is a securid */ } if (test_nino_flag(ni, v3_Extensions) && (perm >= 0)) { enter_cache(scx, ni, uid, gid, perm); } free(securattr); } else { perm = -1; uid = gid = 0; } } if (perm >= 0) { if (!scx->uid) { /* root access and execution */ if (perm & 0111) perm |= 01777; else perm = 0; } else if (uid == scx->uid) perm &= 07700; else /* * avoid checking group membership * when the requested perms for group * are the same as perms for other */ if ((gid == scx->gid) || ((((perm >> 3) ^ perm) & (request >> 6) & 7) && groupmember(scx, scx->uid, gid))) perm &= 07070; else perm &= 07007; } } return (perm); } #endif /* POSIXACLS */ /* * Get an NTFS ACL * * Returns size or -errno if there is a problem * if size was too small, no copy is done and errno is not set, * the caller is expected to issue a new call */ int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, char *value, size_t size) { char *securattr; size_t outsize; outsize = 0; /* default to no data and no error */ securattr = getsecurityattr(scx->vol, ni); if (securattr) { outsize = ntfs_attr_size(securattr); if (outsize <= size) { memcpy(value,securattr,outsize); } free(securattr); } return (outsize ? (int)outsize : -errno); } /* * Get owner, group and permissions in an stat structure * returns permissions, or -1 if there is a problem */ int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode * ni, struct stat *stbuf) { const SECURITY_DESCRIPTOR_RELATIVE *phead; char *securattr; const SID *usid; /* owner of file/directory */ const SID *gsid; /* group of file/directory */ const struct CACHED_PERMISSIONS *cached; int perm; BOOL isdir; #if POSIXACLS struct POSIX_SECURITY *pxdesc; #endif if (!scx->mapping[MAPUSERS]) perm = 07777; else { /* check whether available in cache */ cached = fetch_cache(scx,ni); if (cached) { #if POSIXACLS if (!(scx->vol->secure_flags & (1 << SECURITY_ACL)) && cached->pxdesc) perm = ntfs_basic_perms(scx,cached->pxdesc); else #endif perm = cached->mode; stbuf->st_uid = cached->uid; stbuf->st_gid = cached->gid; stbuf->st_mode = (stbuf->st_mode & ~07777) + perm; } else { perm = -1; /* default to error */ isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); securattr = getsecurityattr(scx->vol, ni); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*) securattr; gsid = (const SID*)& securattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL usid = ntfs_acl_owner(securattr); #else usid = (const SID*)& securattr[le32_to_cpu(phead->owner)]; #endif #if POSIXACLS pxdesc = ntfs_build_permissions_posix( scx->mapping, securattr, usid, gsid, isdir); if (pxdesc) { if (!(scx->vol->secure_flags & (1 << SECURITY_ACL))) perm = ntfs_basic_perms(scx, pxdesc); else perm = pxdesc->mode & 07777; } else perm = -1; #else perm = ntfs_build_permissions(securattr, usid, gsid, isdir); #endif /* * fetch owner and group for cacheing */ if (perm >= 0) { /* * Create a security id if there were none * and upgrade option is selected */ if (!test_nino_flag(ni, v3_Extensions) && (scx->vol->secure_flags & (1 << SECURITY_ADDSECURIDS))) { upgrade_secur_desc(scx->vol, securattr, ni); } #if OWNERFROMACL stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else if (!perm && ntfs_same_sid(usid, adminsid)) { stbuf->st_uid = find_tenant(scx, securattr); if (stbuf->st_uid) perm = 0700; } else stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif stbuf->st_gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); stbuf->st_mode = (stbuf->st_mode & ~07777) + perm; #if POSIXACLS enter_cache(scx, ni, stbuf->st_uid, stbuf->st_gid, pxdesc); free(pxdesc); #else enter_cache(scx, ni, stbuf->st_uid, stbuf->st_gid, perm); #endif } free(securattr); } } } return (perm); } #if POSIXACLS /* * Get the base for a Posix inheritance and * build an inherited Posix descriptor */ static struct POSIX_SECURITY *inherit_posix(struct SECURITY_CONTEXT *scx, ntfs_inode *dir_ni, mode_t mode, BOOL isdir) { const struct CACHED_PERMISSIONS *cached; const SECURITY_DESCRIPTOR_RELATIVE *phead; struct POSIX_SECURITY *pxdesc; struct POSIX_SECURITY *pydesc; char *securattr; const SID *usid; const SID *gsid; uid_t uid; gid_t gid; pydesc = (struct POSIX_SECURITY*)NULL; /* check whether parent directory is available in cache */ cached = fetch_cache(scx,dir_ni); if (cached) { uid = cached->uid; gid = cached->gid; pxdesc = cached->pxdesc; if (pxdesc) { if (scx->vol->secure_flags & (1 << SECURITY_ACL)) pydesc = ntfs_build_inherited_posix(pxdesc, mode, scx->umask, isdir); else pydesc = ntfs_build_basic_posix(pxdesc, mode, scx->umask, isdir); } } else { securattr = getsecurityattr(scx->vol, dir_ni); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*) securattr; gsid = (const SID*)& securattr[le32_to_cpu(phead->group)]; gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL usid = ntfs_acl_owner(securattr); pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, usid, gsid, TRUE); uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else usid = (const SID*)& securattr[le32_to_cpu(phead->owner)]; pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, usid, gsid, TRUE); if (pxdesc && ntfs_same_sid(usid, adminsid)) { uid = find_tenant(scx, securattr); } else uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif if (pxdesc) { /* * Create a security id if there were none * and upgrade option is selected */ if (!test_nino_flag(dir_ni, v3_Extensions) && (scx->vol->secure_flags & (1 << SECURITY_ADDSECURIDS))) { upgrade_secur_desc(scx->vol, securattr, dir_ni); /* * fetch owner and group for cacheing * if there is a securid */ } if (test_nino_flag(dir_ni, v3_Extensions)) { enter_cache(scx, dir_ni, uid, gid, pxdesc); } if (scx->vol->secure_flags & (1 << SECURITY_ACL)) pydesc = ntfs_build_inherited_posix( pxdesc, mode, scx->umask, isdir); else pydesc = ntfs_build_basic_posix( pxdesc, mode, scx->umask, isdir); free(pxdesc); } free(securattr); } } return (pydesc); } /* * Allocate a security_id for a file being created * * Returns zero if not possible (NTFS v3.x required) */ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid, ntfs_inode *dir_ni, mode_t mode, BOOL isdir) { #if !FORCE_FORMAT_v1x const struct CACHED_SECURID *cached; struct CACHED_SECURID wanted; struct POSIX_SECURITY *pxdesc; char *newattr; int newattrsz; const SID *usid; const SID *gsid; BIGSID defusid; BIGSID defgsid; le32 securid; #endif securid = const_cpu_to_le32(0); #if !FORCE_FORMAT_v1x pxdesc = inherit_posix(scx, dir_ni, mode, isdir); if (pxdesc) { /* check whether target securid is known in cache */ wanted.uid = uid; wanted.gid = gid; wanted.dmode = pxdesc->mode & mode & 07777; if (isdir) wanted.dmode |= 0x10000; wanted.variable = (void*)pxdesc; wanted.varsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); /* quite simple, if we are lucky */ if (cached) securid = cached->securid; /* not in cache : make sure we can create ids */ if (!cached && (scx->vol->major_ver >= 3)) { usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); if (!usid || !gsid) { ntfs_log_error("File created by an unmapped user/group %d/%d\n", (int)uid, (int)gid); usid = gsid = adminsid; } newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, isdir, usid, gsid); if (newattr) { newattrsz = ntfs_attr_size(newattr); securid = setsecurityattr(scx->vol, (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, newattrsz); if (securid) { /* update cache, for subsequent use */ wanted.securid = securid; ntfs_enter_cache(scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); } free(newattr); } else { /* * could not build new security attribute * errno set by ntfs_build_descr() */ } } free(pxdesc); } #endif return (securid); } /* * Apply Posix inheritance to a newly created file * (for NTFS 1.x only : no securid) */ int ntfs_set_inherited_posix(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, ntfs_inode *dir_ni, mode_t mode) { struct POSIX_SECURITY *pxdesc; char *newattr; const SID *usid; const SID *gsid; BIGSID defusid; BIGSID defgsid; BOOL isdir; int res; res = -1; isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); pxdesc = inherit_posix(scx, dir_ni, mode, isdir); if (pxdesc) { usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); if (!usid || !gsid) { ntfs_log_error("File created by an unmapped user/group %d/%d\n", (int)uid, (int)gid); usid = gsid = adminsid; } newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, isdir, usid, gsid); if (newattr) { /* Adjust Windows read-only flag */ res = update_secur_descr(scx->vol, newattr, ni); if (!res && !isdir) { if (mode & S_IWUSR) ni->flags &= ~FILE_ATTR_READONLY; else ni->flags |= FILE_ATTR_READONLY; } #if CACHE_LEGACY_SIZE /* also invalidate legacy cache */ if (isdir && !ni->security_id) { struct CACHED_PERMISSIONS_LEGACY legacy; legacy.mft_no = ni->mft_no; legacy.variable = pxdesc; legacy.varsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); ntfs_invalidate_cache(scx->vol->legacy_cache, GENERIC(&legacy), (cache_compare)leg_compare,0); } #endif free(newattr); } else { /* * could not build new security attribute * errno set by ntfs_build_descr() */ } } return (res); } #else le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid, mode_t mode, BOOL isdir) { #if !FORCE_FORMAT_v1x const struct CACHED_SECURID *cached; struct CACHED_SECURID wanted; char *newattr; int newattrsz; const SID *usid; const SID *gsid; BIGSID defusid; BIGSID defgsid; le32 securid; #endif securid = const_cpu_to_le32(0); #if !FORCE_FORMAT_v1x /* check whether target securid is known in cache */ wanted.uid = uid; wanted.gid = gid; wanted.dmode = mode & 07777; if (isdir) wanted.dmode |= 0x10000; wanted.variable = (void*)NULL; wanted.varsize = 0; cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); /* quite simple, if we are lucky */ if (cached) securid = cached->securid; /* not in cache : make sure we can create ids */ if (!cached && (scx->vol->major_ver >= 3)) { usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); if (!usid || !gsid) { ntfs_log_error("File created by an unmapped user/group %d/%d\n", (int)uid, (int)gid); usid = gsid = adminsid; } newattr = ntfs_build_descr(mode, isdir, usid, gsid); if (newattr) { newattrsz = ntfs_attr_size(newattr); securid = setsecurityattr(scx->vol, (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, newattrsz); if (securid) { /* update cache, for subsequent use */ wanted.securid = securid; ntfs_enter_cache(scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); } free(newattr); } else { /* * could not build new security attribute * errno set by ntfs_build_descr() */ } } #endif return (securid); } #endif /* * Update ownership and mode of a file, reusing an existing * security descriptor when possible * * Returns zero if successful */ #if POSIXACLS int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode, struct POSIX_SECURITY *pxdesc) #else int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode) #endif { int res; const struct CACHED_SECURID *cached; struct CACHED_SECURID wanted; char *newattr; const SID *usid; const SID *gsid; BIGSID defusid; BIGSID defgsid; BOOL isdir; res = 0; /* check whether target securid is known in cache */ isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); wanted.uid = uid; wanted.gid = gid; wanted.dmode = mode & 07777; if (isdir) wanted.dmode |= 0x10000; #if POSIXACLS wanted.variable = (void*)pxdesc; if (pxdesc) wanted.varsize = sizeof(struct POSIX_SECURITY) + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); else wanted.varsize = 0; #else wanted.variable = (void*)NULL; wanted.varsize = 0; #endif if (test_nino_flag(ni, v3_Extensions)) { cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); /* quite simple, if we are lucky */ if (cached) { ni->security_id = cached->securid; NInoSetDirty(ni); /* adjust Windows read-only flag */ if (!isdir) { if (mode & S_IWUSR) ni->flags &= ~FILE_ATTR_READONLY; else ni->flags |= FILE_ATTR_READONLY; NInoFileNameSetDirty(ni); } } } else cached = (struct CACHED_SECURID*)NULL; if (!cached) { /* * Do not use usid and gsid from former attributes, * but recompute them to get repeatable results * which can be kept in cache. */ usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); if (!usid || !gsid) { ntfs_log_error("File made owned by an unmapped user/group %d/%d\n", uid, gid); usid = gsid = adminsid; } #if POSIXACLS if (pxdesc) newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, isdir, usid, gsid); else newattr = ntfs_build_descr(mode, isdir, usid, gsid); #else newattr = ntfs_build_descr(mode, isdir, usid, gsid); #endif if (newattr) { res = update_secur_descr(scx->vol, newattr, ni); if (!res) { /* adjust Windows read-only flag */ if (!isdir) { if (mode & S_IWUSR) ni->flags &= ~FILE_ATTR_READONLY; else ni->flags |= FILE_ATTR_READONLY; NInoFileNameSetDirty(ni); } /* update cache, for subsequent use */ if (test_nino_flag(ni, v3_Extensions)) { wanted.securid = ni->security_id; ntfs_enter_cache(scx->vol->securid_cache, GENERIC(&wanted), (cache_compare)compare); } #if CACHE_LEGACY_SIZE /* also invalidate legacy cache */ if (isdir && !ni->security_id) { struct CACHED_PERMISSIONS_LEGACY legacy; legacy.mft_no = ni->mft_no; #if POSIXACLS legacy.variable = wanted.variable; legacy.varsize = wanted.varsize; #else legacy.variable = (void*)NULL; legacy.varsize = 0; #endif ntfs_invalidate_cache(scx->vol->legacy_cache, GENERIC(&legacy), (cache_compare)leg_compare,0); } #endif } free(newattr); } else { /* * could not build new security attribute * errno set by ntfs_build_descr() */ res = -1; } } return (res); } /* * Check whether user has ownership rights on a file * * Returns TRUE if allowed * if not, errno tells why */ BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) { const struct CACHED_PERMISSIONS *cached; char *oldattr; const SID *usid; uid_t processuid; uid_t uid; BOOL gotowner; int allowed; processuid = scx->uid; /* TODO : use CAP_FOWNER process capability */ /* * Always allow for root * Also always allow if no mapping has been defined */ if (!scx->mapping[MAPUSERS] || !processuid) allowed = TRUE; else { gotowner = FALSE; /* default */ /* get the owner, either from cache or from old attribute */ cached = fetch_cache(scx, ni); if (cached) { uid = cached->uid; gotowner = TRUE; } else { oldattr = getsecurityattr(scx->vol, ni); if (oldattr) { #if OWNERFROMACL usid = ntfs_acl_owner(oldattr); #else const SECURITY_DESCRIPTOR_RELATIVE *phead; phead = (const SECURITY_DESCRIPTOR_RELATIVE*) oldattr; usid = (const SID*)&oldattr [le32_to_cpu(phead->owner)]; #endif uid = ntfs_find_user(scx->mapping[MAPUSERS], usid); gotowner = TRUE; free(oldattr); } } allowed = FALSE; if (gotowner) { /* TODO : use CAP_FOWNER process capability */ if (!processuid || (processuid == uid)) allowed = TRUE; else errno = EPERM; } } return (allowed); } #if POSIXACLS /* * Set a new access or default Posix ACL to a file * (or remove ACL if no input data) * Validity of input data is checked after merging * * Returns 0, or -1 if there is a problem which errno describes */ int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, const char *name, const char *value, size_t size, int flags) { const SECURITY_DESCRIPTOR_RELATIVE *phead; const struct CACHED_PERMISSIONS *cached; char *oldattr; uid_t processuid; const SID *usid; const SID *gsid; uid_t uid; uid_t gid; int res; BOOL isdir; BOOL deflt; BOOL exist; int count; struct POSIX_SECURITY *oldpxdesc; struct POSIX_SECURITY *newpxdesc; /* get the current pxsec, either from cache or from old attribute */ res = -1; deflt = !strcmp(name,"system.posix_acl_default"); if (size) count = (size - sizeof(struct POSIX_ACL)) / sizeof(struct POSIX_ACE); else count = 0; isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); newpxdesc = (struct POSIX_SECURITY*)NULL; if ((!value || (((const struct POSIX_ACL*)value)->version == POSIX_VERSION)) && (!deflt || isdir || (!size && !value))) { cached = fetch_cache(scx, ni); if (cached) { uid = cached->uid; gid = cached->gid; oldpxdesc = cached->pxdesc; if (oldpxdesc) { newpxdesc = ntfs_replace_acl(oldpxdesc, (const struct POSIX_ACL*)value,count,deflt); } } else { oldattr = getsecurityattr(scx->vol, ni); if (oldattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; #if OWNERFROMACL usid = ntfs_acl_owner(oldattr); #else usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; #endif gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); oldpxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, usid, gsid, isdir); if (oldpxdesc) { if (deflt) exist = oldpxdesc->defcnt > 0; else exist = oldpxdesc->acccnt > 3; if ((exist && (flags & XATTR_CREATE)) || (!exist && (flags & XATTR_REPLACE))) { errno = (exist ? EEXIST : ENODATA); } else { newpxdesc = ntfs_replace_acl(oldpxdesc, (const struct POSIX_ACL*)value,count,deflt); } free(oldpxdesc); } free(oldattr); } } } else errno = EINVAL; if (newpxdesc) { processuid = scx->uid; /* TODO : use CAP_FOWNER process capability */ if (!processuid || (uid == processuid)) { /* * clear setgid if file group does * not match process group */ if (processuid && (gid != scx->gid) && !groupmember(scx, scx->uid, gid)) { newpxdesc->mode &= ~S_ISGID; } res = ntfs_set_owner_mode(scx, ni, uid, gid, newpxdesc->mode, newpxdesc); } else errno = EPERM; free(newpxdesc); } return (res ? -1 : 0); } /* * Remove a default Posix ACL from a file * * Returns 0, or -1 if there is a problem which errno describes */ int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, const char *name) { return (ntfs_set_posix_acl(scx, ni, name, (const char*)NULL, 0, 0)); } #endif /* * Set a new NTFS ACL to a file * * Returns 0, or -1 if there is a problem */ int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, const char *value, size_t size, int flags) { char *attr; int res; res = -1; if ((size > 0) && !(flags & XATTR_CREATE) && ntfs_valid_descr(value,size) && (ntfs_attr_size(value) == size)) { /* need copying in order to write */ attr = (char*)ntfs_malloc(size); if (attr) { memcpy(attr,value,size); res = update_secur_descr(scx->vol, attr, ni); /* * No need to invalidate standard caches : * the relation between a securid and * the associated protection is unchanged, * only the relation between a file and * its securid and protection is changed. */ #if CACHE_LEGACY_SIZE /* * we must however invalidate the legacy * cache, which is based on inode numbers. * For safety, invalidate even if updating * failed. */ if ((ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) && !ni->security_id) { struct CACHED_PERMISSIONS_LEGACY legacy; legacy.mft_no = ni->mft_no; legacy.variable = (char*)NULL; legacy.varsize = 0; ntfs_invalidate_cache(scx->vol->legacy_cache, GENERIC(&legacy), (cache_compare)leg_compare,0); } #endif free(attr); } else errno = ENOMEM; } else errno = EINVAL; return (res ? -1 : 0); } /* * Set new permissions to a file * Checks user mapping has been defined before request for setting * * rejected if request is not originated by owner or root * * returns 0 on success * -1 on failure, with errno = EIO */ int ntfs_set_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, mode_t mode) { const SECURITY_DESCRIPTOR_RELATIVE *phead; const struct CACHED_PERMISSIONS *cached; char *oldattr; const SID *usid; const SID *gsid; uid_t processuid; uid_t uid; uid_t gid; int res; #if POSIXACLS BOOL isdir; int pxsize; const struct POSIX_SECURITY *oldpxdesc; struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; #endif /* get the current owner, either from cache or from old attribute */ res = 0; cached = fetch_cache(scx, ni); if (cached) { uid = cached->uid; gid = cached->gid; #if POSIXACLS oldpxdesc = cached->pxdesc; if (oldpxdesc) { /* must copy before merging */ pxsize = sizeof(struct POSIX_SECURITY) + (oldpxdesc->acccnt + oldpxdesc->defcnt)*sizeof(struct POSIX_ACE); newpxdesc = (struct POSIX_SECURITY*)malloc(pxsize); if (newpxdesc) { memcpy(newpxdesc, oldpxdesc, pxsize); if (ntfs_merge_mode_posix(newpxdesc, mode)) res = -1; } else res = -1; } else newpxdesc = (struct POSIX_SECURITY*)NULL; #endif } else { oldattr = getsecurityattr(scx->vol, ni); if (oldattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; #if OWNERFROMACL usid = ntfs_acl_owner(oldattr); #else usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; #endif gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if POSIXACLS isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); newpxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, usid, gsid, isdir); if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) res = -1; #endif free(oldattr); } else res = -1; } if (!res) { processuid = scx->uid; /* TODO : use CAP_FOWNER process capability */ if (!processuid || (uid == processuid)) { /* * clear setgid if file group does * not match process group */ if (processuid && (gid != scx->gid) && !groupmember(scx, scx->uid, gid)) mode &= ~S_ISGID; #if POSIXACLS if (newpxdesc) { newpxdesc->mode = mode; res = ntfs_set_owner_mode(scx, ni, uid, gid, mode, newpxdesc); } else res = ntfs_set_owner_mode(scx, ni, uid, gid, mode, newpxdesc); #else res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); #endif } else { errno = EPERM; res = -1; /* neither owner nor root */ } } else { /* * Should not happen : a default descriptor is generated * by getsecurityattr() when there are none */ ntfs_log_error("File has no security descriptor\n"); res = -1; errno = EIO; } #if POSIXACLS if (newpxdesc) free(newpxdesc); #endif return (res ? -1 : 0); } /* * Create a default security descriptor for files whose descriptor * cannot be inherited */ int ntfs_sd_add_everyone(ntfs_inode *ni) { /* JPA SECURITY_DESCRIPTOR_ATTR *sd; */ SECURITY_DESCRIPTOR_RELATIVE *sd; ACL *acl; ACCESS_ALLOWED_ACE *ace; SID *sid; int ret, sd_len; /* Create SECURITY_DESCRIPTOR attribute (everyone has full access). */ /* * Calculate security descriptor length. We have 2 sub-authorities in * owner and group SIDs, but structure SID contain only one, so add * 4 bytes to every SID. */ sd_len = sizeof(SECURITY_DESCRIPTOR_ATTR) + 2 * (sizeof(SID) + 4) + sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE); sd = (SECURITY_DESCRIPTOR_RELATIVE*)ntfs_calloc(sd_len); if (!sd) return -1; sd->revision = SECURITY_DESCRIPTOR_REVISION; sd->control = SE_DACL_PRESENT | SE_SELF_RELATIVE; sid = (SID*)((u8*)sd + sizeof(SECURITY_DESCRIPTOR_ATTR)); sid->revision = SID_REVISION; sid->sub_authority_count = 2; sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); sid->identifier_authority.value[5] = 5; sd->owner = cpu_to_le32((u8*)sid - (u8*)sd); sid = (SID*)((u8*)sid + sizeof(SID) + 4); sid->revision = SID_REVISION; sid->sub_authority_count = 2; sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); sid->identifier_authority.value[5] = 5; sd->group = cpu_to_le32((u8*)sid - (u8*)sd); acl = (ACL*)((u8*)sid + sizeof(SID) + 4); acl->revision = ACL_REVISION; acl->size = const_cpu_to_le16(sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)); acl->ace_count = const_cpu_to_le16(1); sd->dacl = cpu_to_le32((u8*)acl - (u8*)sd); ace = (ACCESS_ALLOWED_ACE*)((u8*)acl + sizeof(ACL)); ace->type = ACCESS_ALLOWED_ACE_TYPE; ace->flags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; ace->size = const_cpu_to_le16(sizeof(ACCESS_ALLOWED_ACE)); ace->mask = const_cpu_to_le32(0x1f01ff); /* FIXME */ ace->sid.revision = SID_REVISION; ace->sid.sub_authority_count = 1; ace->sid.sub_authority[0] = const_cpu_to_le32(0); ace->sid.identifier_authority.value[5] = 1; ret = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0, (u8*)sd, sd_len); if (ret) ntfs_log_perror("Failed to add initial SECURITY_DESCRIPTOR"); free(sd); return ret; } /* * Check whether user can access a file in a specific way * * Returns 1 if access is allowed, including user is root or no * user mapping defined * 2 if sticky and accesstype is S_IWRITE + S_IEXEC + S_ISVTX * 0 and sets errno if there is a problem or if access * is not allowed * * This is used for Posix ACL and checking creation of DOS file names */ int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, int accesstype) /* access type required (S_Ixxx values) */ { int perm; int res; int allow; struct stat stbuf; /* * Always allow for root unless execution is requested. * (was checked by fuse until kernel 2.6.29) * Also always allow if no mapping has been defined */ if (!scx->mapping[MAPUSERS] || (!scx->uid && (!(accesstype & S_IEXEC) || (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)))) allow = 1; else { perm = ntfs_get_perm(scx, ni, accesstype); if (perm >= 0) { res = EACCES; switch (accesstype) { case S_IEXEC: allow = (perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0; break; case S_IWRITE: allow = (perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0; break; case S_IWRITE + S_IEXEC: allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); break; case S_IREAD: allow = (perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0; break; case S_IREAD + S_IEXEC: allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); break; case S_IREAD + S_IWRITE: allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) && ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0); break; case S_IWRITE + S_IEXEC + S_ISVTX: if (perm & S_ISVTX) { if ((ntfs_get_owner_mode(scx,ni,&stbuf) >= 0) && (stbuf.st_uid == scx->uid)) allow = 1; else allow = 2; } else allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); break; case S_IREAD + S_IWRITE + S_IEXEC: allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) && ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); break; default : res = EINVAL; allow = 0; break; } if (!allow) errno = res; } else allow = 0; } return (allow); } /* * Check whether user can create a file (or directory) * * Returns TRUE if access is allowed, * Also returns the gid and dsetgid applicable to the created file */ int ntfs_allowed_create(struct SECURITY_CONTEXT *scx, ntfs_inode *dir_ni, gid_t *pgid, mode_t *pdsetgid) { int perm; int res; int allow; struct stat stbuf; /* * Always allow for root. * Also always allow if no mapping has been defined */ if (!scx->mapping[MAPUSERS]) perm = 0777; else perm = ntfs_get_perm(scx, dir_ni, S_IWRITE + S_IEXEC); if (!scx->mapping[MAPUSERS] || !scx->uid) { allow = 1; } else { perm = ntfs_get_perm(scx, dir_ni, S_IWRITE + S_IEXEC); if (perm >= 0) { res = EACCES; allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); if (!allow) errno = res; } else allow = 0; } *pgid = scx->gid; *pdsetgid = 0; /* return directory group if S_ISGID is set */ if (allow && (perm & S_ISGID)) { if (ntfs_get_owner_mode(scx, dir_ni, &stbuf) >= 0) { *pdsetgid = stbuf.st_mode & S_ISGID; if (perm & S_ISGID) *pgid = stbuf.st_gid; } } return (allow); } #if 0 /* not needed any more */ /* * Check whether user can access the parent directory * of a file in a specific way * * Returns true if access is allowed, including user is root and * no user mapping defined * * Sets errno if there is a problem or if not allowed * * This is used for Posix ACL and checking creation of DOS file names */ BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, const char *path, int accesstype) { int allow; char *dirpath; char *name; ntfs_inode *ni; ntfs_inode *dir_ni; struct stat stbuf; allow = 0; dirpath = strdup(path); if (dirpath) { /* the root of file system is seen as a parent of itself */ /* is that correct ? */ name = strrchr(dirpath, '/'); *name = 0; dir_ni = ntfs_pathname_to_inode(scx->vol, NULL, dirpath); if (dir_ni) { allow = ntfs_allowed_access(scx, dir_ni, accesstype); ntfs_inode_close(dir_ni); /* * for an not-owned sticky directory, have to * check whether file itself is owned */ if ((accesstype == (S_IWRITE + S_IEXEC + S_ISVTX)) && (allow == 2)) { ni = ntfs_pathname_to_inode(scx->vol, NULL, path); allow = FALSE; if (ni) { allow = (ntfs_get_owner_mode(scx,ni,&stbuf) >= 0) && (stbuf.st_uid == scx->uid); ntfs_inode_close(ni); } } } free(dirpath); } return (allow); /* errno is set if not allowed */ } #endif /* * Define a new owner/group to a file * * returns zero if successful */ int ntfs_set_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid) { const SECURITY_DESCRIPTOR_RELATIVE *phead; const struct CACHED_PERMISSIONS *cached; char *oldattr; const SID *usid; const SID *gsid; uid_t fileuid; uid_t filegid; mode_t mode; int perm; BOOL isdir; int res; #if POSIXACLS struct POSIX_SECURITY *pxdesc; BOOL pxdescbuilt = FALSE; #endif res = 0; /* get the current owner and mode from cache or security attributes */ oldattr = (char*)NULL; cached = fetch_cache(scx,ni); if (cached) { fileuid = cached->uid; filegid = cached->gid; mode = cached->mode; #if POSIXACLS pxdesc = cached->pxdesc; if (!pxdesc) res = -1; #endif } else { fileuid = 0; filegid = 0; mode = 0; oldattr = getsecurityattr(scx->vol, ni); if (oldattr) { isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); phead = (const SECURITY_DESCRIPTOR_RELATIVE*) oldattr; gsid = (const SID*) &oldattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL usid = ntfs_acl_owner(oldattr); #else usid = (const SID*) &oldattr[le32_to_cpu(phead->owner)]; #endif #if POSIXACLS pxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, usid, gsid, isdir); if (pxdesc) { pxdescbuilt = TRUE; fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); mode = perm = pxdesc->mode; } else res = -1; #else mode = perm = ntfs_build_permissions(oldattr, usid, gsid, isdir); if (perm >= 0) { fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); } else res = -1; #endif free(oldattr); } else res = -1; } if (!res) { /* check requested by root */ /* or chgrp requested by owner to an owned group */ if (!scx->uid || ((((int)uid < 0) || (uid == fileuid)) && ((gid == scx->gid) || groupmember(scx, scx->uid, gid)) && (fileuid == scx->uid))) { /* replace by the new usid and gsid */ /* or reuse old gid and sid for cacheing */ if ((int)uid < 0) uid = fileuid; if ((int)gid < 0) gid = filegid; #if !defined(__sun) || !defined (__SVR4) /* clear setuid and setgid if owner has changed */ /* unless request originated by root */ if (uid && (fileuid != uid)) mode &= 01777; #endif #if POSIXACLS res = ntfs_set_owner_mode(scx, ni, uid, gid, mode, pxdesc); #else res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); #endif } else { res = -1; /* neither owner nor root */ errno = EPERM; } #if POSIXACLS if (pxdescbuilt) free(pxdesc); #endif } else { /* * Should not happen : a default descriptor is generated * by getsecurityattr() when there are none */ ntfs_log_error("File has no security descriptor\n"); res = -1; errno = EIO; } return (res ? -1 : 0); } /* * Define new owner/group and mode to a file * * returns zero if successful */ int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, const mode_t mode) { const struct CACHED_PERMISSIONS *cached; char *oldattr; uid_t fileuid; uid_t filegid; int res; #if POSIXACLS const SECURITY_DESCRIPTOR_RELATIVE *phead; const SID *usid; const SID *gsid; BOOL isdir; const struct POSIX_SECURITY *oldpxdesc; struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; int pxsize; #endif res = 0; /* get the current owner and mode from cache or security attributes */ oldattr = (char*)NULL; cached = fetch_cache(scx,ni); if (cached) { fileuid = cached->uid; filegid = cached->gid; #if POSIXACLS oldpxdesc = cached->pxdesc; if (oldpxdesc) { /* must copy before merging */ pxsize = sizeof(struct POSIX_SECURITY) + (oldpxdesc->acccnt + oldpxdesc->defcnt)*sizeof(struct POSIX_ACE); newpxdesc = (struct POSIX_SECURITY*)malloc(pxsize); if (newpxdesc) { memcpy(newpxdesc, oldpxdesc, pxsize); if (ntfs_merge_mode_posix(newpxdesc, mode)) res = -1; } else res = -1; } #endif } else { fileuid = 0; filegid = 0; oldattr = getsecurityattr(scx->vol, ni); if (oldattr) { #if POSIXACLS isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); phead = (const SECURITY_DESCRIPTOR_RELATIVE*) oldattr; gsid = (const SID*) &oldattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL usid = ntfs_acl_owner(oldattr); #else usid = (const SID*) &oldattr[le32_to_cpu(phead->owner)]; #endif newpxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, usid, gsid, isdir); if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) res = -1; else { fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); } #endif free(oldattr); } else res = -1; } if (!res) { /* check requested by root */ /* or chgrp requested by owner to an owned group */ if (!scx->uid || ((((int)uid < 0) || (uid == fileuid)) && ((gid == scx->gid) || groupmember(scx, scx->uid, gid)) && (fileuid == scx->uid))) { /* replace by the new usid and gsid */ /* or reuse old gid and sid for cacheing */ if ((int)uid < 0) uid = fileuid; if ((int)gid < 0) gid = filegid; #if POSIXACLS res = ntfs_set_owner_mode(scx, ni, uid, gid, mode, newpxdesc); #else res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); #endif } else { res = -1; /* neither owner nor root */ errno = EPERM; } } else { /* * Should not happen : a default descriptor is generated * by getsecurityattr() when there are none */ ntfs_log_error("File has no security descriptor\n"); res = -1; errno = EIO; } #if POSIXACLS free(newpxdesc); #endif return (res ? -1 : 0); } /* * Build a security id for a descriptor inherited from * parent directory the Windows way */ static le32 build_inherited_id(struct SECURITY_CONTEXT *scx, const char *parentattr, BOOL fordir) { const SECURITY_DESCRIPTOR_RELATIVE *pphead; const ACL *ppacl; const SID *usid; const SID *gsid; BIGSID defusid; BIGSID defgsid; int offpacl; int offgroup; SECURITY_DESCRIPTOR_RELATIVE *pnhead; ACL *pnacl; int parentattrsz; char *newattr; int newattrsz; int aclsz; int usidsz; int gsidsz; int pos; le32 securid; parentattrsz = ntfs_attr_size(parentattr); pphead = (const SECURITY_DESCRIPTOR_RELATIVE*)parentattr; if (scx->mapping[MAPUSERS]) { usid = ntfs_find_usid(scx->mapping[MAPUSERS], scx->uid, (SID*)&defusid); gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS], scx->gid, (SID*)&defgsid); #if OWNERFROMACL /* Get approximation of parent owner when cannot map */ if (!gsid) gsid = adminsid; if (!usid) { usid = ntfs_acl_owner(parentattr); if (!ntfs_is_user_sid(gsid)) gsid = usid; } #else /* Define owner as root when cannot map */ if (!usid) usid = adminsid; if (!gsid) gsid = adminsid; #endif } else { /* * If there is no user mapping and this is not a root * user, we have to get owner and group from somewhere, * and the parent directory has to contribute. * Windows never has to do that, because it can always * rely on a user mapping */ if (!scx->uid) usid = adminsid; else { #if OWNERFROMACL usid = ntfs_acl_owner(parentattr); #else int offowner; offowner = le32_to_cpu(pphead->owner); usid = (const SID*)&parentattr[offowner]; #endif } if (!scx->gid) gsid = adminsid; else { offgroup = le32_to_cpu(pphead->group); gsid = (const SID*)&parentattr[offgroup]; } } /* * new attribute is smaller than parent's * except for differences in SIDs which appear in * owner, group and possible grants and denials in * generic creator-owner and creator-group ACEs. * For directories, an ACE may be duplicated for * access and inheritance, so we double the count. */ usidsz = ntfs_sid_size(usid); gsidsz = ntfs_sid_size(gsid); newattrsz = parentattrsz + 3*usidsz + 3*gsidsz; if (fordir) newattrsz *= 2; newattr = (char*)ntfs_malloc(newattrsz); if (newattr) { pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)newattr; pnhead->revision = SECURITY_DESCRIPTOR_REVISION; pnhead->alignment = 0; pnhead->control = (pphead->control & (SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED)) | SE_SELF_RELATIVE; pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); /* * locate and inherit DACL * do not test SE_DACL_PRESENT (wrong for "DR Watson") */ pnhead->dacl = const_cpu_to_le32(0); if (pphead->dacl) { offpacl = le32_to_cpu(pphead->dacl); ppacl = (const ACL*)&parentattr[offpacl]; pnacl = (ACL*)&newattr[pos]; aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir, pphead->control & SE_DACL_AUTO_INHERITED); if (aclsz) { pnhead->dacl = cpu_to_le32(pos); pos += aclsz; pnhead->control |= SE_DACL_PRESENT; } } /* * locate and inherit SACL */ pnhead->sacl = const_cpu_to_le32(0); if (pphead->sacl) { offpacl = le32_to_cpu(pphead->sacl); ppacl = (const ACL*)&parentattr[offpacl]; pnacl = (ACL*)&newattr[pos]; aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir, pphead->control & SE_SACL_AUTO_INHERITED); if (aclsz) { pnhead->sacl = cpu_to_le32(pos); pos += aclsz; pnhead->control |= SE_SACL_PRESENT; } } /* * inherit or redefine owner */ memcpy(&newattr[pos],usid,usidsz); pnhead->owner = cpu_to_le32(pos); pos += usidsz; /* * inherit or redefine group */ memcpy(&newattr[pos],gsid,gsidsz); pnhead->group = cpu_to_le32(pos); pos += gsidsz; securid = setsecurityattr(scx->vol, (SECURITY_DESCRIPTOR_RELATIVE*)newattr, pos); free(newattr); } else securid = const_cpu_to_le32(0); return (securid); } /* * Get an inherited security id * * For Windows compatibility, the normal initial permission setting * may be inherited from the parent directory instead of being * defined by the creation arguments. * * The following creates an inherited id for that purpose. * * Note : the owner and group of parent directory are also * inherited (which is not the case on Windows) if no user mapping * is defined. * * Returns the inherited id, or zero if not possible (eg on NTFS 1.x) */ le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, ntfs_inode *dir_ni, BOOL fordir) { struct CACHED_PERMISSIONS *cached; char *parentattr; le32 securid; securid = const_cpu_to_le32(0); cached = (struct CACHED_PERMISSIONS*)NULL; /* * Try to get inherited id from cache, possible when * the current process owns the parent directory */ if (test_nino_flag(dir_ni, v3_Extensions) && dir_ni->security_id) { cached = fetch_cache(scx, dir_ni); if (cached && (cached->uid == scx->uid) && (cached->gid == scx->gid)) securid = (fordir ? cached->inh_dirid : cached->inh_fileid); } /* * Not cached or not available in cache, compute it all * Note : if parent directory has no id, it is not cacheable */ if (!securid) { parentattr = getsecurityattr(scx->vol, dir_ni); if (parentattr) { securid = build_inherited_id(scx, parentattr, fordir); free(parentattr); /* * Store the result into cache for further use * if the current process owns the parent directory */ if (securid) { cached = fetch_cache(scx, dir_ni); if (cached && (cached->uid == scx->uid) && (cached->gid == scx->gid)) { if (fordir) cached->inh_dirid = securid; else cached->inh_fileid = securid; } } } } return (securid); } /* * Link a group to a member of group * * Returns 0 if OK, -1 (and errno set) if error */ static int link_single_group(struct MAPPING *usermapping, struct passwd *user, gid_t gid) { struct group *group; char **grmem; int grcnt; gid_t *groups; int res; res = 0; group = getgrgid(gid); if (group && group->gr_mem) { grcnt = usermapping->grcnt; groups = usermapping->groups; grmem = group->gr_mem; while (*grmem && strcmp(user->pw_name, *grmem)) grmem++; if (*grmem) { if (!grcnt) groups = (gid_t*)malloc(sizeof(gid_t)); else groups = (gid_t*)realloc(groups, (grcnt+1)*sizeof(gid_t)); if (groups) groups[grcnt++] = gid; else { res = -1; errno = ENOMEM; } } usermapping->grcnt = grcnt; usermapping->groups = groups; } return (res); } /* * Statically link group to users * This is based on groups defined in /etc/group and does not take * the groups dynamically set by setgroups() nor any changes in * /etc/group into account * * Only mapped groups and root group are linked to mapped users * * Returns 0 if OK, -1 (and errno set) if error * */ static int link_group_members(struct SECURITY_CONTEXT *scx) { struct MAPPING *usermapping; struct MAPPING *groupmapping; struct passwd *user; int res; res = 0; for (usermapping=scx->mapping[MAPUSERS]; usermapping && !res; usermapping=usermapping->next) { usermapping->grcnt = 0; usermapping->groups = (gid_t*)NULL; user = getpwuid(usermapping->xid); if (user && user->pw_name) { for (groupmapping=scx->mapping[MAPGROUPS]; groupmapping && !res; groupmapping=groupmapping->next) { if (link_single_group(usermapping, user, groupmapping->xid)) res = -1; } if (!res && link_single_group(usermapping, user, (gid_t)0)) res = -1; } } return (res); } /* * Apply default single user mapping * returns zero if successful */ static int ntfs_do_default_mapping(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid, const SID *usid) { struct MAPPING *usermapping; struct MAPPING *groupmapping; SID *sid; int sidsz; int res; res = -1; sidsz = ntfs_sid_size(usid); sid = (SID*)ntfs_malloc(sidsz); if (sid) { memcpy(sid,usid,sidsz); usermapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); if (usermapping) { groupmapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); if (groupmapping) { usermapping->sid = sid; usermapping->xid = uid; usermapping->next = (struct MAPPING*)NULL; groupmapping->sid = sid; groupmapping->xid = gid; groupmapping->next = (struct MAPPING*)NULL; scx->mapping[MAPUSERS] = usermapping; scx->mapping[MAPGROUPS] = groupmapping; res = 0; } } } return (res); } /* * Make sure there are no ambiguous mapping * Ambiguous mapping may lead to undesired configurations and * we had rather be safe until the consequences are understood */ #if 0 /* not activated for now */ static BOOL check_mapping(const struct MAPPING *usermapping, const struct MAPPING *groupmapping) { const struct MAPPING *mapping1; const struct MAPPING *mapping2; BOOL ambiguous; ambiguous = FALSE; for (mapping1=usermapping; mapping1; mapping1=mapping1->next) for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { if (mapping1->xid != mapping2->xid) ambiguous = TRUE; } else { if (mapping1->xid == mapping2->xid) ambiguous = TRUE; } for (mapping1=groupmapping; mapping1; mapping1=mapping1->next) for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { if (mapping1->xid != mapping2->xid) ambiguous = TRUE; } else { if (mapping1->xid == mapping2->xid) ambiguous = TRUE; } return (ambiguous); } #endif #if 0 /* not used any more */ /* * Try and apply default single user mapping * returns zero if successful */ static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) { const SECURITY_DESCRIPTOR_RELATIVE *phead; ntfs_inode *ni; char *securattr; const SID *usid; int res; res = -1; ni = ntfs_pathname_to_inode(scx->vol, NULL, "/."); if (ni) { securattr = getsecurityattr(scx->vol, ni); if (securattr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; usid = (SID*)&securattr[le32_to_cpu(phead->owner)]; if (ntfs_is_user_sid(usid)) res = ntfs_do_default_mapping(scx, scx->uid, scx->gid, usid); free(securattr); } ntfs_inode_close(ni); } return (res); } #endif /* * Basic read from a user mapping file on another volume */ static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribute__((unused))) { return (read(*(int*)fileid, buf, size)); } /* * Read from a user mapping file on current NTFS partition */ static int localread(void *fileid, char *buf, size_t size, off_t offs) { return (ntfs_attr_data_read((ntfs_inode*)fileid, AT_UNNAMED, 0, buf, size, offs)); } /* * Build the user mapping * - according to a mapping file if defined (or default present), * - or try default single user mapping if possible * * The mapping is specific to a mounted device * No locking done, mounting assumed non multithreaded * * returns zero if mapping is successful * (failure should not be interpreted as an error) */ int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path, BOOL allowdef) { struct MAPLIST *item; struct MAPLIST *firstitem; struct MAPPING *usermapping; struct MAPPING *groupmapping; ntfs_inode *ni; int fd; static struct { u8 revision; u8 levels; be16 highbase; be32 lowbase; le32 level1; le32 level2; le32 level3; le32 level4; le32 level5; } defmap = { 1, 5, const_cpu_to_be16(0), const_cpu_to_be32(5), const_cpu_to_le32(21), const_cpu_to_le32(DEFSECAUTH1), const_cpu_to_le32(DEFSECAUTH2), const_cpu_to_le32(DEFSECAUTH3), const_cpu_to_le32(DEFSECBASE) } ; /* be sure not to map anything until done */ scx->mapping[MAPUSERS] = (struct MAPPING*)NULL; scx->mapping[MAPGROUPS] = (struct MAPPING*)NULL; if (!usermap_path) usermap_path = MAPPINGFILE; if (usermap_path[0] == '/') { fd = open(usermap_path,O_RDONLY); if (fd > 0) { firstitem = ntfs_read_mapping(basicread, (void*)&fd); close(fd); } else firstitem = (struct MAPLIST*)NULL; } else { ni = ntfs_pathname_to_inode(scx->vol, NULL, usermap_path); if (ni) { firstitem = ntfs_read_mapping(localread, ni); ntfs_inode_close(ni); } else firstitem = (struct MAPLIST*)NULL; } if (firstitem) { usermapping = ntfs_do_user_mapping(firstitem); groupmapping = ntfs_do_group_mapping(firstitem); if (usermapping && groupmapping) { scx->mapping[MAPUSERS] = usermapping; scx->mapping[MAPGROUPS] = groupmapping; } else ntfs_log_error("There were no valid user or no valid group\n"); /* now we can free the memory copy of input text */ /* and rely on internal representation */ while (firstitem) { item = firstitem->next; free(firstitem); firstitem = item; } } else { /* no mapping file, try a default mapping */ if (allowdef) { if (!ntfs_do_default_mapping(scx, 0, 0, (const SID*)&defmap)) ntfs_log_info("Using default user mapping\n"); } } return (!scx->mapping[MAPUSERS] || link_group_members(scx)); } /* * Get the ntfs attribute into an extended attribute * The attribute is returned according to cpu endianness */ int ntfs_get_ntfs_attrib(ntfs_inode *ni, char *value, size_t size) { u32 attrib; size_t outsize; outsize = 0; /* default to no data and no error */ if (ni) { attrib = le32_to_cpu(ni->flags); if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); else attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); if (!attrib) attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); outsize = sizeof(FILE_ATTR_FLAGS); if (size >= outsize) { if (value) memcpy(value,&attrib,outsize); else errno = EINVAL; } } return (outsize ? (int)outsize : -errno); } /* * Return the ntfs attribute into an extended attribute * The attribute is expected according to cpu endianness * * Returns 0, or -1 if there is a problem */ int ntfs_set_ntfs_attrib(ntfs_inode *ni, const char *value, size_t size, int flags) { u32 attrib; le32 settable; ATTR_FLAGS dirflags; int res; res = -1; if (ni && value && (size >= sizeof(FILE_ATTR_FLAGS))) { if (!(flags & XATTR_CREATE)) { /* copy to avoid alignment problems */ memcpy(&attrib,value,sizeof(FILE_ATTR_FLAGS)); settable = FILE_ATTR_SETTABLE; res = 0; if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { /* * Accept changing compression for a directory * and set index root accordingly */ settable |= FILE_ATTR_COMPRESSED; if ((ni->flags ^ cpu_to_le32(attrib)) & FILE_ATTR_COMPRESSED) { if (ni->flags & FILE_ATTR_COMPRESSED) dirflags = const_cpu_to_le16(0); else dirflags = ATTR_IS_COMPRESSED; res = ntfs_attr_set_flags(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4, dirflags, ATTR_COMPRESSION_MASK); } } if (!res) { ni->flags = (ni->flags & ~settable) | (cpu_to_le32(attrib) & settable); NInoFileNameSetDirty(ni); NInoSetDirty(ni); } } else errno = EEXIST; } else errno = EINVAL; return (res ? -1 : 0); } /* * Open the volume's security descriptor index ($Secure) * * returns 0 if it succeeds * -1 with errno set if it fails and the volume is NTFS v3.0+ */ int ntfs_open_secure(ntfs_volume *vol) { ntfs_inode *ni; ntfs_index_context *sii; ntfs_index_context *sdh; if (vol->secure_ni) /* Already open? */ return 0; ni = ntfs_pathname_to_inode(vol, NULL, "$Secure"); if (!ni) goto err; if (ni->mft_no != FILE_Secure) { ntfs_log_error("$Secure does not have expected inode number!"); errno = EINVAL; goto err_close_ni; } /* Allocate the needed index contexts. */ sii = ntfs_index_ctx_get(ni, sii_stream, 4); if (!sii) goto err_close_ni; sdh = ntfs_index_ctx_get(ni, sdh_stream, 4); if (!sdh) goto err_close_sii; vol->secure_xsdh = sdh; vol->secure_xsii = sii; vol->secure_ni = ni; return 0; err_close_sii: ntfs_index_ctx_put(sii); err_close_ni: ntfs_inode_close(ni); err: /* Failing on NTFS pre-v3.0 is expected. */ if (vol->major_ver < 3) return 0; ntfs_log_perror("Failed to open $Secure"); return -1; } /* * Close the volume's security descriptor index ($Secure) * * returns 0 if it succeeds * -1 with errno set if it fails */ int ntfs_close_secure(ntfs_volume *vol) { int res = 0; if (vol->secure_ni) { ntfs_index_ctx_put(vol->secure_xsdh); ntfs_index_ctx_put(vol->secure_xsii); res = ntfs_inode_close(vol->secure_ni); vol->secure_ni = NULL; } return res; } /* * Destroy a security context * Allocated memory is freed to facilitate the detection of memory leaks */ void ntfs_destroy_security_context(struct SECURITY_CONTEXT *scx) { ntfs_free_mapping(scx->mapping); free_caches(scx); } /* * API for direct access to security descriptors * based on Win32 API */ /* * Selective feeding of a security descriptor into user buffer * * Returns TRUE if successful */ static BOOL feedsecurityattr(const char *attr, u32 selection, char *buf, u32 buflen, u32 *psize) { const SECURITY_DESCRIPTOR_RELATIVE *phead; SECURITY_DESCRIPTOR_RELATIVE *pnhead; const ACL *pdacl; const ACL *psacl; const SID *pusid; const SID *pgsid; unsigned int offdacl; unsigned int offsacl; unsigned int offowner; unsigned int offgroup; unsigned int daclsz; unsigned int saclsz; unsigned int usidsz; unsigned int gsidsz; unsigned int size; /* size of requested attributes */ BOOL ok; unsigned int pos; unsigned int avail; le16 control; avail = 0; control = SE_SELF_RELATIVE; phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; size = sizeof(SECURITY_DESCRIPTOR_RELATIVE); /* locate DACL if requested and available */ if (phead->dacl && (selection & DACL_SECURITY_INFORMATION)) { offdacl = le32_to_cpu(phead->dacl); pdacl = (const ACL*)&attr[offdacl]; daclsz = le16_to_cpu(pdacl->size); size += daclsz; avail |= DACL_SECURITY_INFORMATION; } else offdacl = daclsz = 0; /* locate owner if requested and available */ offowner = le32_to_cpu(phead->owner); if (offowner && (selection & OWNER_SECURITY_INFORMATION)) { /* find end of USID */ pusid = (const SID*)&attr[offowner]; usidsz = ntfs_sid_size(pusid); size += usidsz; avail |= OWNER_SECURITY_INFORMATION; } else offowner = usidsz = 0; /* locate group if requested and available */ offgroup = le32_to_cpu(phead->group); if (offgroup && (selection & GROUP_SECURITY_INFORMATION)) { /* find end of GSID */ pgsid = (const SID*)&attr[offgroup]; gsidsz = ntfs_sid_size(pgsid); size += gsidsz; avail |= GROUP_SECURITY_INFORMATION; } else offgroup = gsidsz = 0; /* locate SACL if requested and available */ if (phead->sacl && (selection & SACL_SECURITY_INFORMATION)) { /* find end of SACL */ offsacl = le32_to_cpu(phead->sacl); psacl = (const ACL*)&attr[offsacl]; saclsz = le16_to_cpu(psacl->size); size += saclsz; avail |= SACL_SECURITY_INFORMATION; } else offsacl = saclsz = 0; /* * Check having enough size in destination buffer * (required size is returned nevertheless so that * the request can be reissued with adequate size) */ if (size > buflen) { *psize = size; errno = EINVAL; ok = FALSE; } else { if (selection & OWNER_SECURITY_INFORMATION) control |= phead->control & SE_OWNER_DEFAULTED; if (selection & GROUP_SECURITY_INFORMATION) control |= phead->control & SE_GROUP_DEFAULTED; if (selection & DACL_SECURITY_INFORMATION) control |= phead->control & (SE_DACL_PRESENT | SE_DACL_DEFAULTED | SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED); if (selection & SACL_SECURITY_INFORMATION) control |= phead->control & (SE_SACL_PRESENT | SE_SACL_DEFAULTED | SE_SACL_AUTO_INHERITED | SE_SACL_PROTECTED); /* * copy header and feed new flags, even if no detailed data */ memcpy(buf,attr,sizeof(SECURITY_DESCRIPTOR_RELATIVE)); pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)buf; pnhead->control = control; pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); /* copy DACL if requested and available */ if (selection & avail & DACL_SECURITY_INFORMATION) { pnhead->dacl = cpu_to_le32(pos); memcpy(&buf[pos],&attr[offdacl],daclsz); pos += daclsz; } else pnhead->dacl = const_cpu_to_le32(0); /* copy SACL if requested and available */ if (selection & avail & SACL_SECURITY_INFORMATION) { pnhead->sacl = cpu_to_le32(pos); memcpy(&buf[pos],&attr[offsacl],saclsz); pos += saclsz; } else pnhead->sacl = const_cpu_to_le32(0); /* copy owner if requested and available */ if (selection & avail & OWNER_SECURITY_INFORMATION) { pnhead->owner = cpu_to_le32(pos); memcpy(&buf[pos],&attr[offowner],usidsz); pos += usidsz; } else pnhead->owner = const_cpu_to_le32(0); /* copy group if requested and available */ if (selection & avail & GROUP_SECURITY_INFORMATION) { pnhead->group = cpu_to_le32(pos); memcpy(&buf[pos],&attr[offgroup],gsidsz); pos += gsidsz; } else pnhead->group = const_cpu_to_le32(0); if (pos != size) ntfs_log_error("Error in security descriptor size\n"); *psize = size; ok = TRUE; } return (ok); } /* * Merge a new security descriptor into the old one * and assign to designated file * * Returns TRUE if successful */ static BOOL mergesecurityattr(ntfs_volume *vol, const char *oldattr, const char *newattr, u32 selection, ntfs_inode *ni) { const SECURITY_DESCRIPTOR_RELATIVE *oldhead; const SECURITY_DESCRIPTOR_RELATIVE *newhead; SECURITY_DESCRIPTOR_RELATIVE *targhead; const ACL *pdacl; const ACL *psacl; const SID *powner; const SID *pgroup; int offdacl; int offsacl; int offowner; int offgroup; unsigned int size; le16 control; char *target; int pos; int oldattrsz; int newattrsz; BOOL ok; ok = FALSE; /* default return */ oldhead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; newhead = (const SECURITY_DESCRIPTOR_RELATIVE*)newattr; oldattrsz = ntfs_attr_size(oldattr); newattrsz = ntfs_attr_size(newattr); target = (char*)ntfs_malloc(oldattrsz + newattrsz); if (target) { targhead = (SECURITY_DESCRIPTOR_RELATIVE*)target; pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); control = SE_SELF_RELATIVE; /* * copy new DACL if selected * or keep old DACL if any */ if ((selection & DACL_SECURITY_INFORMATION) ? newhead->dacl : oldhead->dacl) { if (selection & DACL_SECURITY_INFORMATION) { offdacl = le32_to_cpu(newhead->dacl); pdacl = (const ACL*)&newattr[offdacl]; } else { offdacl = le32_to_cpu(oldhead->dacl); pdacl = (const ACL*)&oldattr[offdacl]; } size = le16_to_cpu(pdacl->size); memcpy(&target[pos], pdacl, size); targhead->dacl = cpu_to_le32(pos); pos += size; } else targhead->dacl = const_cpu_to_le32(0); if (selection & DACL_SECURITY_INFORMATION) { control |= newhead->control & (SE_DACL_PRESENT | SE_DACL_DEFAULTED | SE_DACL_PROTECTED); if (newhead->control & SE_DACL_AUTO_INHERIT_REQ) control |= SE_DACL_AUTO_INHERITED; } else control |= oldhead->control & (SE_DACL_PRESENT | SE_DACL_DEFAULTED | SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED); /* * copy new SACL if selected * or keep old SACL if any */ if ((selection & SACL_SECURITY_INFORMATION) ? newhead->sacl : oldhead->sacl) { if (selection & SACL_SECURITY_INFORMATION) { offsacl = le32_to_cpu(newhead->sacl); psacl = (const ACL*)&newattr[offsacl]; } else { offsacl = le32_to_cpu(oldhead->sacl); psacl = (const ACL*)&oldattr[offsacl]; } size = le16_to_cpu(psacl->size); memcpy(&target[pos], psacl, size); targhead->sacl = cpu_to_le32(pos); pos += size; } else targhead->sacl = const_cpu_to_le32(0); if (selection & SACL_SECURITY_INFORMATION) { control |= newhead->control & (SE_SACL_PRESENT | SE_SACL_DEFAULTED | SE_SACL_PROTECTED); if (newhead->control & SE_SACL_AUTO_INHERIT_REQ) control |= SE_SACL_AUTO_INHERITED; } else control |= oldhead->control & (SE_SACL_PRESENT | SE_SACL_DEFAULTED | SE_SACL_AUTO_INHERITED | SE_SACL_PROTECTED); /* * copy new OWNER if selected * or keep old OWNER if any */ if ((selection & OWNER_SECURITY_INFORMATION) ? newhead->owner : oldhead->owner) { if (selection & OWNER_SECURITY_INFORMATION) { offowner = le32_to_cpu(newhead->owner); powner = (const SID*)&newattr[offowner]; } else { offowner = le32_to_cpu(oldhead->owner); powner = (const SID*)&oldattr[offowner]; } size = ntfs_sid_size(powner); memcpy(&target[pos], powner, size); targhead->owner = cpu_to_le32(pos); pos += size; } else targhead->owner = const_cpu_to_le32(0); if (selection & OWNER_SECURITY_INFORMATION) control |= newhead->control & SE_OWNER_DEFAULTED; else control |= oldhead->control & SE_OWNER_DEFAULTED; /* * copy new GROUP if selected * or keep old GROUP if any */ if ((selection & GROUP_SECURITY_INFORMATION) ? newhead->group : oldhead->group) { if (selection & GROUP_SECURITY_INFORMATION) { offgroup = le32_to_cpu(newhead->group); pgroup = (const SID*)&newattr[offgroup]; control |= newhead->control & SE_GROUP_DEFAULTED; } else { offgroup = le32_to_cpu(oldhead->group); pgroup = (const SID*)&oldattr[offgroup]; control |= oldhead->control & SE_GROUP_DEFAULTED; } size = ntfs_sid_size(pgroup); memcpy(&target[pos], pgroup, size); targhead->group = cpu_to_le32(pos); pos += size; } else targhead->group = const_cpu_to_le32(0); if (selection & GROUP_SECURITY_INFORMATION) control |= newhead->control & SE_GROUP_DEFAULTED; else control |= oldhead->control & SE_GROUP_DEFAULTED; targhead->revision = SECURITY_DESCRIPTOR_REVISION; targhead->alignment = 0; targhead->control = control; ok = !update_secur_descr(vol, target, ni); free(target); } return (ok); } /* * Return the security descriptor of a file * This is intended to be similar to GetFileSecurity() from Win32 * in order to facilitate the development of portable tools * * returns zero if unsuccessful (following Win32 conventions) * -1 if no securid * the securid if any * * The Win32 API is : * * BOOL WINAPI GetFileSecurity( * __in LPCTSTR lpFileName, * __in SECURITY_INFORMATION RequestedInformation, * __out_opt PSECURITY_DESCRIPTOR pSecurityDescriptor, * __in DWORD nLength, * __out LPDWORD lpnLengthNeeded * ); * */ int ntfs_get_file_security(struct SECURITY_API *scapi, const char *path, u32 selection, char *buf, u32 buflen, u32 *psize) { ntfs_inode *ni; char *attr; int res; res = 0; /* default return */ if (scapi && (scapi->magic == MAGIC_API)) { ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); if (ni) { attr = getsecurityattr(scapi->security.vol, ni); if (attr) { if (feedsecurityattr(attr,selection, buf,buflen,psize)) { if (test_nino_flag(ni, v3_Extensions) && ni->security_id) res = le32_to_cpu( ni->security_id); else res = -1; } free(attr); } ntfs_inode_close(ni); } else errno = ENOENT; if (!res) *psize = 0; } else errno = EINVAL; /* do not clear *psize */ return (res); } /* * Set the security descriptor of a file or directory * This is intended to be similar to SetFileSecurity() from Win32 * in order to facilitate the development of portable tools * * returns zero if unsuccessful (following Win32 conventions) * -1 if no securid * the securid if any * * The Win32 API is : * * BOOL WINAPI SetFileSecurity( * __in LPCTSTR lpFileName, * __in SECURITY_INFORMATION SecurityInformation, * __in PSECURITY_DESCRIPTOR pSecurityDescriptor * ); */ int ntfs_set_file_security(struct SECURITY_API *scapi, const char *path, u32 selection, const char *attr) { const SECURITY_DESCRIPTOR_RELATIVE *phead; ntfs_inode *ni; int attrsz; BOOL missing; char *oldattr; int res; res = 0; /* default return */ if (scapi && (scapi->magic == MAGIC_API) && attr) { phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; attrsz = ntfs_attr_size(attr); /* if selected, owner and group must be present or defaulted */ missing = ((selection & OWNER_SECURITY_INFORMATION) && !phead->owner && !(phead->control & SE_OWNER_DEFAULTED)) || ((selection & GROUP_SECURITY_INFORMATION) && !phead->group && !(phead->control & SE_GROUP_DEFAULTED)); if (!missing && (phead->control & SE_SELF_RELATIVE) && ntfs_valid_descr(attr, attrsz)) { ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); if (ni) { oldattr = getsecurityattr(scapi->security.vol, ni); if (oldattr) { if (mergesecurityattr( scapi->security.vol, oldattr, attr, selection, ni)) { if (test_nino_flag(ni, v3_Extensions)) res = le32_to_cpu( ni->security_id); else res = -1; } free(oldattr); } ntfs_inode_close(ni); } } else errno = EINVAL; } else errno = EINVAL; return (res); } /* * Return the attributes of a file * This is intended to be similar to GetFileAttributes() from Win32 * in order to facilitate the development of portable tools * * returns -1 if unsuccessful (Win32 : INVALID_FILE_ATTRIBUTES) * * The Win32 API is : * * DWORD WINAPI GetFileAttributes( * __in LPCTSTR lpFileName * ); */ int ntfs_get_file_attributes(struct SECURITY_API *scapi, const char *path) { ntfs_inode *ni; s32 attrib; attrib = -1; /* default return */ if (scapi && (scapi->magic == MAGIC_API) && path) { ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); if (ni) { attrib = le32_to_cpu(ni->flags); if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); else attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); if (!attrib) attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); ntfs_inode_close(ni); } else errno = ENOENT; } else errno = EINVAL; /* do not clear *psize */ return (attrib); } /* * Set attributes to a file or directory * This is intended to be similar to SetFileAttributes() from Win32 * in order to facilitate the development of portable tools * * Only a few flags can be set (same list as Win32) * * returns zero if unsuccessful (following Win32 conventions) * nonzero if successful * * The Win32 API is : * * BOOL WINAPI SetFileAttributes( * __in LPCTSTR lpFileName, * __in DWORD dwFileAttributes * ); */ BOOL ntfs_set_file_attributes(struct SECURITY_API *scapi, const char *path, s32 attrib) { ntfs_inode *ni; le32 settable; ATTR_FLAGS dirflags; int res; res = 0; /* default return */ if (scapi && (scapi->magic == MAGIC_API) && path) { ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); if (ni) { settable = FILE_ATTR_SETTABLE; if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { /* * Accept changing compression for a directory * and set index root accordingly */ settable |= FILE_ATTR_COMPRESSED; if ((ni->flags ^ cpu_to_le32(attrib)) & FILE_ATTR_COMPRESSED) { if (ni->flags & FILE_ATTR_COMPRESSED) dirflags = const_cpu_to_le16(0); else dirflags = ATTR_IS_COMPRESSED; res = ntfs_attr_set_flags(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4, dirflags, ATTR_COMPRESSION_MASK); } } if (!res) { ni->flags = (ni->flags & ~settable) | (cpu_to_le32(attrib) & settable); NInoSetDirty(ni); NInoFileNameSetDirty(ni); } if (!ntfs_inode_close(ni)) res = -1; } else errno = ENOENT; } return (res); } BOOL ntfs_read_directory(struct SECURITY_API *scapi, const char *path, ntfs_filldir_t callback, void *context) { ntfs_inode *ni; BOOL ok; s64 pos; ok = FALSE; /* default return */ if (scapi && (scapi->magic == MAGIC_API) && callback) { ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); if (ni) { if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { pos = 0; ntfs_readdir(ni,&pos,context,callback); ok = !ntfs_inode_close(ni); } else { ntfs_inode_close(ni); errno = ENOTDIR; } } else errno = ENOENT; } else errno = EINVAL; /* do not clear *psize */ return (ok); } /* * read $SDS (for auditing security data) * * Returns the number or read bytes, or -1 if there is an error */ int ntfs_read_sds(struct SECURITY_API *scapi, char *buf, u32 size, u32 offset) { int got; got = -1; /* default return */ if (scapi && (scapi->magic == MAGIC_API)) { if (scapi->security.vol->secure_ni) got = ntfs_attr_data_read(scapi->security.vol->secure_ni, STREAM_SDS, 4, buf, size, offset); else errno = EOPNOTSUPP; } else errno = EINVAL; return (got); } /* * read $SII (for auditing security data) * * Returns next entry, or NULL if there is an error */ INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, INDEX_ENTRY *entry) { SII_INDEX_KEY key; INDEX_ENTRY *ret; BOOL found; ntfs_index_context *xsii; ret = (INDEX_ENTRY*)NULL; /* default return */ if (scapi && (scapi->magic == MAGIC_API)) { xsii = scapi->security.vol->secure_xsii; if (xsii) { if (!entry) { key.security_id = const_cpu_to_le32(0); found = !ntfs_index_lookup((char*)&key, sizeof(SII_INDEX_KEY), xsii); /* not supposed to find */ if (!found && (errno == ENOENT)) ret = xsii->entry; } else ret = ntfs_index_next(entry,xsii); if (!ret) errno = ENODATA; } else errno = EOPNOTSUPP; } else errno = EINVAL; return (ret); } /* * read $SDH (for auditing security data) * * Returns next entry, or NULL if there is an error */ INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, INDEX_ENTRY *entry) { SDH_INDEX_KEY key; INDEX_ENTRY *ret; BOOL found; ntfs_index_context *xsdh; ret = (INDEX_ENTRY*)NULL; /* default return */ if (scapi && (scapi->magic == MAGIC_API)) { xsdh = scapi->security.vol->secure_xsdh; if (xsdh) { if (!entry) { key.hash = const_cpu_to_le32(0); key.security_id = const_cpu_to_le32(0); found = !ntfs_index_lookup((char*)&key, sizeof(SDH_INDEX_KEY), xsdh); /* not supposed to find */ if (!found && (errno == ENOENT)) ret = xsdh->entry; } else ret = ntfs_index_next(entry,xsdh); if (!ret) errno = ENODATA; } else errno = ENOTSUP; } else errno = EINVAL; return (ret); } /* * Get the mapped user SID * A buffer of 40 bytes has to be supplied * * returns the size of the SID, or zero and errno set if not found */ int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) { const SID *usid; BIGSID defusid; int size; size = 0; if (scapi && (scapi->magic == MAGIC_API)) { usid = ntfs_find_usid(scapi->security.mapping[MAPUSERS], uid, (SID*)&defusid); if (usid) { size = ntfs_sid_size(usid); memcpy(buf,usid,size); } else errno = ENODATA; } else errno = EINVAL; return (size); } /* * Get the mapped group SID * A buffer of 40 bytes has to be supplied * * returns the size of the SID, or zero and errno set if not found */ int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) { const SID *gsid; BIGSID defgsid; int size; size = 0; if (scapi && (scapi->magic == MAGIC_API)) { gsid = ntfs_find_gsid(scapi->security.mapping[MAPGROUPS], gid, (SID*)&defgsid); if (gsid) { size = ntfs_sid_size(gsid); memcpy(buf,gsid,size); } else errno = ENODATA; } else errno = EINVAL; return (size); } /* * Get the user mapped to a SID * * returns the uid, or -1 if not found */ int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) { int uid; uid = -1; if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(usid)) { if (ntfs_same_sid(usid,adminsid)) uid = 0; else { uid = ntfs_find_user(scapi->security.mapping[MAPUSERS], usid); if (!uid) { uid = -1; errno = ENODATA; } } } else errno = EINVAL; return (uid); } /* * Get the group mapped to a SID * * returns the uid, or -1 if not found */ int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) { int gid; gid = -1; if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(gsid)) { if (ntfs_same_sid(gsid,adminsid)) gid = 0; else { gid = ntfs_find_group(scapi->security.mapping[MAPGROUPS], gsid); if (!gid) { gid = -1; errno = ENODATA; } } } else errno = EINVAL; return (gid); } /* * Initializations before calling ntfs_get_file_security() * ntfs_set_file_security() and ntfs_read_directory() * * Only allowed for root * * Returns an (obscured) struct SECURITY_API* needed for further calls * NULL if not root (EPERM) or device is mounted (EBUSY) */ struct SECURITY_API *ntfs_initialize_file_security(const char *device, unsigned long flags) { ntfs_volume *vol; unsigned long mntflag; int mnt; struct SECURITY_API *scapi; struct SECURITY_CONTEXT *scx; scapi = (struct SECURITY_API*)NULL; mnt = ntfs_check_if_mounted(device, &mntflag); if (!mnt && !(mntflag & NTFS_MF_MOUNTED) && !getuid()) { vol = ntfs_mount(device, flags); if (vol) { scapi = (struct SECURITY_API*) ntfs_malloc(sizeof(struct SECURITY_API)); if (!ntfs_volume_get_free_space(vol) && scapi) { scapi->magic = MAGIC_API; scapi->seccache = (struct PERMISSIONS_CACHE*)NULL; scx = &scapi->security; scx->vol = vol; scx->uid = getuid(); scx->gid = getgid(); scx->pseccache = &scapi->seccache; scx->vol->secure_flags = 0; /* accept no mapping and no $Secure */ ntfs_build_mapping(scx,(const char*)NULL,TRUE); } else { if (scapi) free(scapi); else errno = ENOMEM; mnt = ntfs_umount(vol,FALSE); scapi = (struct SECURITY_API*)NULL; } } } else if (getuid()) errno = EPERM; else errno = EBUSY; return (scapi); } /* * Leaving after ntfs_initialize_file_security() * * Returns FALSE if FAILED */ BOOL ntfs_leave_file_security(struct SECURITY_API *scapi) { int ok; ntfs_volume *vol; ok = FALSE; if (scapi && (scapi->magic == MAGIC_API) && scapi->security.vol) { vol = scapi->security.vol; ntfs_destroy_security_context(&scapi->security); free(scapi); if (!ntfs_umount(vol, 0)) ok = TRUE; } return (ok); }
694444.c
/* Intel(R) Gigabit Ethernet Linux driver * Copyright(c) 2007-2014 Intel Corporation. * RTnet port 2009 Vladimir Zapolskiy <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see <http://www.gnu.org/licenses/>. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Contact Information: * e1000-devel Mailing List <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 */ #include <linux/if_ether.h> #include <linux/delay.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include "e1000_mac.h" #include "igb.h" static s32 igb_set_default_fc(struct e1000_hw *hw); static s32 igb_set_fc_watermarks(struct e1000_hw *hw); /** * igb_get_bus_info_pcie - Get PCIe bus information * @hw: pointer to the HW structure * * Determines and stores the system bus information for a particular * network interface. The following bus information is determined and stored: * bus speed, bus width, type (PCIe), and PCIe function. **/ s32 igb_get_bus_info_pcie(struct e1000_hw *hw) { struct e1000_bus_info *bus = &hw->bus; s32 ret_val; u32 reg; u16 pcie_link_status; bus->type = e1000_bus_type_pci_express; ret_val = igb_read_pcie_cap_reg(hw, PCI_EXP_LNKSTA, &pcie_link_status); if (ret_val) { bus->width = e1000_bus_width_unknown; bus->speed = e1000_bus_speed_unknown; } else { switch (pcie_link_status & PCI_EXP_LNKSTA_CLS) { case PCI_EXP_LNKSTA_CLS_2_5GB: bus->speed = e1000_bus_speed_2500; break; case PCI_EXP_LNKSTA_CLS_5_0GB: bus->speed = e1000_bus_speed_5000; break; default: bus->speed = e1000_bus_speed_unknown; break; } bus->width = (enum e1000_bus_width)((pcie_link_status & PCI_EXP_LNKSTA_NLW) >> PCI_EXP_LNKSTA_NLW_SHIFT); } reg = rd32(E1000_STATUS); bus->func = (reg & E1000_STATUS_FUNC_MASK) >> E1000_STATUS_FUNC_SHIFT; return 0; } /** * igb_clear_vfta - Clear VLAN filter table * @hw: pointer to the HW structure * * Clears the register array which contains the VLAN filter table by * setting all the values to 0. **/ void igb_clear_vfta(struct e1000_hw *hw) { u32 offset; for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) { array_wr32(E1000_VFTA, offset, 0); wrfl(); } } /** * igb_write_vfta - Write value to VLAN filter table * @hw: pointer to the HW structure * @offset: register offset in VLAN filter table * @value: register value written to VLAN filter table * * Writes value at the given offset in the register array which stores * the VLAN filter table. **/ static void igb_write_vfta(struct e1000_hw *hw, u32 offset, u32 value) { array_wr32(E1000_VFTA, offset, value); wrfl(); } /* Due to a hw errata, if the host tries to configure the VFTA register * while performing queries from the BMC or DMA, then the VFTA in some * cases won't be written. */ /** * igb_clear_vfta_i350 - Clear VLAN filter table * @hw: pointer to the HW structure * * Clears the register array which contains the VLAN filter table by * setting all the values to 0. **/ void igb_clear_vfta_i350(struct e1000_hw *hw) { u32 offset; int i; for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) { for (i = 0; i < 10; i++) array_wr32(E1000_VFTA, offset, 0); wrfl(); } } /** * igb_write_vfta_i350 - Write value to VLAN filter table * @hw: pointer to the HW structure * @offset: register offset in VLAN filter table * @value: register value written to VLAN filter table * * Writes value at the given offset in the register array which stores * the VLAN filter table. **/ static void igb_write_vfta_i350(struct e1000_hw *hw, u32 offset, u32 value) { int i; for (i = 0; i < 10; i++) array_wr32(E1000_VFTA, offset, value); wrfl(); } /** * igb_init_rx_addrs - Initialize receive address's * @hw: pointer to the HW structure * @rar_count: receive address registers * * Setups the receive address registers by setting the base receive address * register to the devices MAC address and clearing all the other receive * address registers to 0. **/ void igb_init_rx_addrs(struct e1000_hw *hw, u16 rar_count) { u32 i; u8 mac_addr[ETH_ALEN] = {0}; /* Setup the receive address */ hw_dbg("Programming MAC Address into RAR[0]\n"); hw->mac.ops.rar_set(hw, hw->mac.addr, 0); /* Zero out the other (rar_entry_count - 1) receive addresses */ hw_dbg("Clearing RAR[1-%u]\n", rar_count-1); for (i = 1; i < rar_count; i++) hw->mac.ops.rar_set(hw, mac_addr, i); } /** * igb_vfta_set - enable or disable vlan in VLAN filter table * @hw: pointer to the HW structure * @vid: VLAN id to add or remove * @add: if true add filter, if false remove * * Sets or clears a bit in the VLAN filter table array based on VLAN id * and if we are adding or removing the filter **/ s32 igb_vfta_set(struct e1000_hw *hw, u32 vid, bool add) { u32 index = (vid >> E1000_VFTA_ENTRY_SHIFT) & E1000_VFTA_ENTRY_MASK; u32 mask = 1 << (vid & E1000_VFTA_ENTRY_BIT_SHIFT_MASK); u32 vfta; struct igb_adapter *adapter = hw->back; s32 ret_val = 0; vfta = adapter->shadow_vfta[index]; /* bit was set/cleared before we started */ if ((!!(vfta & mask)) == add) { ret_val = -E1000_ERR_CONFIG; } else { if (add) vfta |= mask; else vfta &= ~mask; } if ((hw->mac.type == e1000_i350) || (hw->mac.type == e1000_i354)) igb_write_vfta_i350(hw, index, vfta); else igb_write_vfta(hw, index, vfta); adapter->shadow_vfta[index] = vfta; return ret_val; } /** * igb_check_alt_mac_addr - Check for alternate MAC addr * @hw: pointer to the HW structure * * Checks the nvm for an alternate MAC address. An alternate MAC address * can be setup by pre-boot software and must be treated like a permanent * address and must override the actual permanent MAC address. If an * alternate MAC address is found it is saved in the hw struct and * programmed into RAR0 and the function returns success, otherwise the * function returns an error. **/ s32 igb_check_alt_mac_addr(struct e1000_hw *hw) { u32 i; s32 ret_val = 0; u16 offset, nvm_alt_mac_addr_offset, nvm_data; u8 alt_mac_addr[ETH_ALEN]; /* Alternate MAC address is handled by the option ROM for 82580 * and newer. SW support not required. */ if (hw->mac.type >= e1000_82580) goto out; ret_val = hw->nvm.ops.read(hw, NVM_ALT_MAC_ADDR_PTR, 1, &nvm_alt_mac_addr_offset); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if ((nvm_alt_mac_addr_offset == 0xFFFF) || (nvm_alt_mac_addr_offset == 0x0000)) /* There is no Alternate MAC Address */ goto out; if (hw->bus.func == E1000_FUNC_1) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN1; if (hw->bus.func == E1000_FUNC_2) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN2; if (hw->bus.func == E1000_FUNC_3) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN3; for (i = 0; i < ETH_ALEN; i += 2) { offset = nvm_alt_mac_addr_offset + (i >> 1); ret_val = hw->nvm.ops.read(hw, offset, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } alt_mac_addr[i] = (u8)(nvm_data & 0xFF); alt_mac_addr[i + 1] = (u8)(nvm_data >> 8); } /* if multicast bit is set, the alternate address will not be used */ if (is_multicast_ether_addr(alt_mac_addr)) { hw_dbg("Ignoring Alternate Mac Address with MC bit set\n"); goto out; } /* We have a valid alternate MAC address, and we want to treat it the * same as the normal permanent MAC address stored by the HW into the * RAR. Do this by mapping this address into RAR0. */ hw->mac.ops.rar_set(hw, alt_mac_addr, 0); out: return ret_val; } /** * igb_rar_set - Set receive address register * @hw: pointer to the HW structure * @addr: pointer to the receive address * @index: receive address array register * * Sets the receive address array register at index to the address passed * in by addr. **/ void igb_rar_set(struct e1000_hw *hw, u8 *addr, u32 index) { u32 rar_low, rar_high; /* HW expects these in little endian so we reverse the byte order * from network order (big endian) to little endian */ rar_low = ((u32) addr[0] | ((u32) addr[1] << 8) | ((u32) addr[2] << 16) | ((u32) addr[3] << 24)); rar_high = ((u32) addr[4] | ((u32) addr[5] << 8)); /* If MAC address zero, no need to set the AV bit */ if (rar_low || rar_high) rar_high |= E1000_RAH_AV; /* Some bridges will combine consecutive 32-bit writes into * a single burst write, which will malfunction on some parts. * The flushes avoid this. */ wr32(E1000_RAL(index), rar_low); wrfl(); wr32(E1000_RAH(index), rar_high); wrfl(); } /** * igb_mta_set - Set multicast filter table address * @hw: pointer to the HW structure * @hash_value: determines the MTA register and bit to set * * The multicast table address is a register array of 32-bit registers. * The hash_value is used to determine what register the bit is in, the * current value is read, the new bit is OR'd in and the new value is * written back into the register. **/ void igb_mta_set(struct e1000_hw *hw, u32 hash_value) { u32 hash_bit, hash_reg, mta; /* The MTA is a register array of 32-bit registers. It is * treated like an array of (32*mta_reg_count) bits. We want to * set bit BitArray[hash_value]. So we figure out what register * the bit is in, read it, OR in the new bit, then write * back the new value. The (hw->mac.mta_reg_count - 1) serves as a * mask to bits 31:5 of the hash value which gives us the * register we're modifying. The hash bit within that register * is determined by the lower 5 bits of the hash value. */ hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; mta = array_rd32(E1000_MTA, hash_reg); mta |= (1 << hash_bit); array_wr32(E1000_MTA, hash_reg, mta); wrfl(); } /** * igb_hash_mc_addr - Generate a multicast hash value * @hw: pointer to the HW structure * @mc_addr: pointer to a multicast address * * Generates a multicast address hash value which is used to determine * the multicast filter table array address and new table value. See * igb_mta_set() **/ static u32 igb_hash_mc_addr(struct e1000_hw *hw, u8 *mc_addr) { u32 hash_value, hash_mask; u8 bit_shift = 0; /* Register count multiplied by bits per register */ hash_mask = (hw->mac.mta_reg_count * 32) - 1; /* For a mc_filter_type of 0, bit_shift is the number of left-shifts * where 0xFF would still fall within the hash mask. */ while (hash_mask >> bit_shift != 0xFF) bit_shift++; /* The portion of the address that is used for the hash table * is determined by the mc_filter_type setting. * The algorithm is such that there is a total of 8 bits of shifting. * The bit_shift for a mc_filter_type of 0 represents the number of * left-shifts where the MSB of mc_addr[5] would still fall within * the hash_mask. Case 0 does this exactly. Since there are a total * of 8 bits of shifting, then mc_addr[4] will shift right the * remaining number of bits. Thus 8 - bit_shift. The rest of the * cases are a variation of this algorithm...essentially raising the * number of bits to shift mc_addr[5] left, while still keeping the * 8-bit shifting total. * * For example, given the following Destination MAC Address and an * mta register count of 128 (thus a 4096-bit vector and 0xFFF mask), * we can see that the bit_shift for case 0 is 4. These are the hash * values resulting from each mc_filter_type... * [0] [1] [2] [3] [4] [5] * 01 AA 00 12 34 56 * LSB MSB * * case 0: hash_value = ((0x34 >> 4) | (0x56 << 4)) & 0xFFF = 0x563 * case 1: hash_value = ((0x34 >> 3) | (0x56 << 5)) & 0xFFF = 0xAC6 * case 2: hash_value = ((0x34 >> 2) | (0x56 << 6)) & 0xFFF = 0x163 * case 3: hash_value = ((0x34 >> 0) | (0x56 << 8)) & 0xFFF = 0x634 */ switch (hw->mac.mc_filter_type) { default: case 0: break; case 1: bit_shift += 1; break; case 2: bit_shift += 2; break; case 3: bit_shift += 4; break; } hash_value = hash_mask & (((mc_addr[4] >> (8 - bit_shift)) | (((u16) mc_addr[5]) << bit_shift))); return hash_value; } /** * igb_update_mc_addr_list - Update Multicast addresses * @hw: pointer to the HW structure * @mc_addr_list: array of multicast addresses to program * @mc_addr_count: number of multicast addresses to program * * Updates entire Multicast Table Array. * The caller must have a packed mc_addr_list of multicast addresses. **/ void igb_update_mc_addr_list(struct e1000_hw *hw, u8 *mc_addr_list, u32 mc_addr_count) { u32 hash_value, hash_bit, hash_reg; int i; /* clear mta_shadow */ memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow)); /* update mta_shadow from mc_addr_list */ for (i = 0; (u32) i < mc_addr_count; i++) { hash_value = igb_hash_mc_addr(hw, mc_addr_list); hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; hw->mac.mta_shadow[hash_reg] |= (1 << hash_bit); mc_addr_list += (ETH_ALEN); } /* replace the entire MTA table */ for (i = hw->mac.mta_reg_count - 1; i >= 0; i--) array_wr32(E1000_MTA, i, hw->mac.mta_shadow[i]); wrfl(); } /** * igb_clear_hw_cntrs_base - Clear base hardware counters * @hw: pointer to the HW structure * * Clears the base hardware counters by reading the counter registers. **/ void igb_clear_hw_cntrs_base(struct e1000_hw *hw) { rd32(E1000_CRCERRS); rd32(E1000_SYMERRS); rd32(E1000_MPC); rd32(E1000_SCC); rd32(E1000_ECOL); rd32(E1000_MCC); rd32(E1000_LATECOL); rd32(E1000_COLC); rd32(E1000_DC); rd32(E1000_SEC); rd32(E1000_RLEC); rd32(E1000_XONRXC); rd32(E1000_XONTXC); rd32(E1000_XOFFRXC); rd32(E1000_XOFFTXC); rd32(E1000_FCRUC); rd32(E1000_GPRC); rd32(E1000_BPRC); rd32(E1000_MPRC); rd32(E1000_GPTC); rd32(E1000_GORCL); rd32(E1000_GORCH); rd32(E1000_GOTCL); rd32(E1000_GOTCH); rd32(E1000_RNBC); rd32(E1000_RUC); rd32(E1000_RFC); rd32(E1000_ROC); rd32(E1000_RJC); rd32(E1000_TORL); rd32(E1000_TORH); rd32(E1000_TOTL); rd32(E1000_TOTH); rd32(E1000_TPR); rd32(E1000_TPT); rd32(E1000_MPTC); rd32(E1000_BPTC); } /** * igb_check_for_copper_link - Check for link (Copper) * @hw: pointer to the HW structure * * Checks to see of the link status of the hardware has changed. If a * change in link status has been detected, then we read the PHY registers * to get the current speed/duplex if link exists. **/ s32 igb_check_for_copper_link(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; bool link; /* We only want to go out to the PHY registers to see if Auto-Neg * has completed and/or if our link status has changed. The * get_link_status flag is set upon receiving a Link Status * Change or Rx Sequence Error interrupt. */ if (!mac->get_link_status) { ret_val = 0; goto out; } /* First we want to see if the MII Status Register reports * link. If so, then we want to get the current speed/duplex * of the PHY. */ ret_val = igb_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) goto out; /* No link detected */ mac->get_link_status = false; /* Check if there was DownShift, must be checked * immediately after link-up */ igb_check_downshift(hw); /* If we are forcing speed/duplex, then we simply return since * we have already determined whether we have link or not. */ if (!mac->autoneg) { ret_val = -E1000_ERR_CONFIG; goto out; } /* Auto-Neg is enabled. Auto Speed Detection takes care * of MAC speed/duplex configuration. So we only need to * configure Collision Distance in the MAC. */ igb_config_collision_dist(hw); /* Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control * settings because we may have had to re-autoneg with a * different link partner. */ ret_val = igb_config_fc_after_link_up(hw); if (ret_val) hw_dbg("Error configuring flow control\n"); out: return ret_val; } /** * igb_setup_link - Setup flow control and link settings * @hw: pointer to the HW structure * * Determines which flow control settings to use, then configures flow * control. Calls the appropriate media-specific link configuration * function. Assuming the adapter has a valid link partner, a valid link * should be established. Assumes the hardware has previously been reset * and the transmitter and receiver are not enabled. **/ s32 igb_setup_link(struct e1000_hw *hw) { s32 ret_val = 0; /* In the case of the phy reset being blocked, we already have a link. * We do not need to set it up again. */ if (igb_check_reset_block(hw)) goto out; /* If requested flow control is set to default, set flow control * based on the EEPROM flow control settings. */ if (hw->fc.requested_mode == e1000_fc_default) { ret_val = igb_set_default_fc(hw); if (ret_val) goto out; } /* We want to save off the original Flow Control configuration just * in case we get disconnected and then reconnected into a different * hub or switch with different Flow Control capabilities. */ hw->fc.current_mode = hw->fc.requested_mode; hw_dbg("After fix-ups FlowControl is now = %x\n", hw->fc.current_mode); /* Call the necessary media_type subroutine to configure the link. */ ret_val = hw->mac.ops.setup_physical_interface(hw); if (ret_val) goto out; /* Initialize the flow control address, type, and PAUSE timer * registers to their default values. This is done even if flow * control is disabled, because it does not hurt anything to * initialize these registers. */ hw_dbg("Initializing the Flow Control address, type and timer regs\n"); wr32(E1000_FCT, FLOW_CONTROL_TYPE); wr32(E1000_FCAH, FLOW_CONTROL_ADDRESS_HIGH); wr32(E1000_FCAL, FLOW_CONTROL_ADDRESS_LOW); wr32(E1000_FCTTV, hw->fc.pause_time); ret_val = igb_set_fc_watermarks(hw); out: return ret_val; } /** * igb_config_collision_dist - Configure collision distance * @hw: pointer to the HW structure * * Configures the collision distance to the default value and is used * during link setup. Currently no func pointer exists and all * implementations are handled in the generic version of this function. **/ void igb_config_collision_dist(struct e1000_hw *hw) { u32 tctl; tctl = rd32(E1000_TCTL); tctl &= ~E1000_TCTL_COLD; tctl |= E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT; wr32(E1000_TCTL, tctl); wrfl(); } /** * igb_set_fc_watermarks - Set flow control high/low watermarks * @hw: pointer to the HW structure * * Sets the flow control high/low threshold (watermark) registers. If * flow control XON frame transmission is enabled, then set XON frame * tansmission as well. **/ static s32 igb_set_fc_watermarks(struct e1000_hw *hw) { s32 ret_val = 0; u32 fcrtl = 0, fcrth = 0; /* Set the flow control receive threshold registers. Normally, * these registers will be set to a default threshold that may be * adjusted later by the driver's runtime code. However, if the * ability to transmit pause frames is not enabled, then these * registers will be set to 0. */ if (hw->fc.current_mode & e1000_fc_tx_pause) { /* We need to set up the Receive Threshold high and low water * marks as well as (optionally) enabling the transmission of * XON frames. */ fcrtl = hw->fc.low_water; if (hw->fc.send_xon) fcrtl |= E1000_FCRTL_XONE; fcrth = hw->fc.high_water; } wr32(E1000_FCRTL, fcrtl); wr32(E1000_FCRTH, fcrth); return ret_val; } /** * igb_set_default_fc - Set flow control default values * @hw: pointer to the HW structure * * Read the EEPROM for the default values for flow control and store the * values. **/ static s32 igb_set_default_fc(struct e1000_hw *hw) { s32 ret_val = 0; u16 lan_offset; u16 nvm_data; /* Read and store word 0x0F of the EEPROM. This word contains bits * that determine the hardware's default PAUSE (flow control) mode, * a bit that determines whether the HW defaults to enabling or * disabling auto-negotiation, and the direction of the * SW defined pins. If there is no SW over-ride of the flow * control setting, then the variable hw->fc will * be initialized based on a value in the EEPROM. */ if (hw->mac.type == e1000_i350) { lan_offset = NVM_82580_LAN_FUNC_OFFSET(hw->bus.func); ret_val = hw->nvm.ops.read(hw, NVM_INIT_CONTROL2_REG + lan_offset, 1, &nvm_data); } else { ret_val = hw->nvm.ops.read(hw, NVM_INIT_CONTROL2_REG, 1, &nvm_data); } if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == 0) hw->fc.requested_mode = e1000_fc_none; else if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == NVM_WORD0F_ASM_DIR) hw->fc.requested_mode = e1000_fc_tx_pause; else hw->fc.requested_mode = e1000_fc_full; out: return ret_val; } /** * igb_force_mac_fc - Force the MAC's flow control settings * @hw: pointer to the HW structure * * Force the MAC's flow control settings. Sets the TFCE and RFCE bits in the * device control register to reflect the adapter settings. TFCE and RFCE * need to be explicitly set by software when a copper PHY is used because * autonegotiation is managed by the PHY rather than the MAC. Software must * also configure these bits when link is forced on a fiber connection. **/ s32 igb_force_mac_fc(struct e1000_hw *hw) { u32 ctrl; s32 ret_val = 0; ctrl = rd32(E1000_CTRL); /* Because we didn't get link via the internal auto-negotiation * mechanism (we either forced link or we got link via PHY * auto-neg), we have to manually enable/disable transmit an * receive flow control. * * The "Case" statement below enables/disable flow control * according to the "hw->fc.current_mode" parameter. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause * frames but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * frames but we do not receive pause frames). * 3: Both Rx and TX flow control (symmetric) is enabled. * other: No other values should be possible at this point. */ hw_dbg("hw->fc.current_mode = %u\n", hw->fc.current_mode); switch (hw->fc.current_mode) { case e1000_fc_none: ctrl &= (~(E1000_CTRL_TFCE | E1000_CTRL_RFCE)); break; case e1000_fc_rx_pause: ctrl &= (~E1000_CTRL_TFCE); ctrl |= E1000_CTRL_RFCE; break; case e1000_fc_tx_pause: ctrl &= (~E1000_CTRL_RFCE); ctrl |= E1000_CTRL_TFCE; break; case e1000_fc_full: ctrl |= (E1000_CTRL_TFCE | E1000_CTRL_RFCE); break; default: hw_dbg("Flow control param set incorrectly\n"); ret_val = -E1000_ERR_CONFIG; goto out; } wr32(E1000_CTRL, ctrl); out: return ret_val; } /** * igb_config_fc_after_link_up - Configures flow control after link * @hw: pointer to the HW structure * * Checks the status of auto-negotiation after link up to ensure that the * speed and duplex were not forced. If the link needed to be forced, then * flow control needs to be forced also. If auto-negotiation is enabled * and did not fail, then we configure flow control based on our link * partner. **/ s32 igb_config_fc_after_link_up(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val = 0; u32 pcs_status_reg, pcs_adv_reg, pcs_lp_ability_reg, pcs_ctrl_reg; u16 mii_status_reg, mii_nway_adv_reg, mii_nway_lp_ability_reg; u16 speed, duplex; /* Check for the case where we have fiber media and auto-neg failed * so we had to force link. In this case, we need to force the * configuration of the MAC to match the "fc" parameter. */ if (mac->autoneg_failed) { if (hw->phy.media_type == e1000_media_type_internal_serdes) ret_val = igb_force_mac_fc(hw); } else { if (hw->phy.media_type == e1000_media_type_copper) ret_val = igb_force_mac_fc(hw); } if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } /* Check for the case where we have copper media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->phy.media_type == e1000_media_type_copper) && mac->autoneg) { /* Read the MII Status Register and check to see if AutoNeg * has completed. We read this twice because this reg has * some "sticky" (latched) bits. */ ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; if (!(mii_status_reg & MII_SR_AUTONEG_COMPLETE)) { hw_dbg("Copper PHY and Auto Neg has not completed.\n"); goto out; } /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (Address 4) and the Auto_Negotiation Base * Page Ability Register (Address 5) to determine how * flow control was negotiated. */ ret_val = hw->phy.ops.read_reg(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg); if (ret_val) goto out; /* Two bits in the Auto Negotiation Advertisement Register * (Address 4) and two bits in the Auto Negotiation Base * Page Ability Register (Address 5) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | e1000_fc_none * 0 | 1 | 0 | DC | e1000_fc_none * 0 | 1 | 1 | 0 | e1000_fc_none * 0 | 1 | 1 | 1 | e1000_fc_tx_pause * 1 | 0 | 0 | DC | e1000_fc_none * 1 | DC | 1 | DC | e1000_fc_full * 1 | 1 | 0 | 0 | e1000_fc_none * 1 | 1 | 0 | 1 | e1000_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | E1000_fc_full * */ if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) { /* Now we need to check if the user selected RX ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise RX * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == e1000_fc_full) { hw->fc.current_mode = e1000_fc_full; hw_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | e1000_fc_tx_pause */ else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_tx_pause; hw_dbg("Flow Control = TX PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | e1000_fc_rx_pause */ else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && !(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Per the IEEE spec, at this point flow control should be * disabled. However, we want to consider that we could * be connected to a legacy switch that doesn't advertise * desired flow control, but can be forced on the link * partner. So if we advertised no flow control, that is * what we will resolve to. If we advertised some kind of * receive capability (Rx Pause Only or Full Flow Control) * and the link partner advertised none, we will configure * ourselves to enable Rx Flow Control only. We can do * this safely for two reasons: If the link partner really * didn't want flow control enabled, and we enable Rx, no * harm done since we won't be receiving any PAUSE frames * anyway. If the intent on the link partner was to have * flow control enabled, then by us enabling RX only, we * can at least receive pause frames and process them. * This is a good idea because in most cases, since we are * predominantly a server NIC, more times than not we will * be asked to delay transmission of packets than asking * our link partner to pause transmission of frames. */ else if ((hw->fc.requested_mode == e1000_fc_none) || (hw->fc.requested_mode == e1000_fc_tx_pause) || (hw->fc.strict_ieee)) { hw->fc.current_mode = e1000_fc_none; hw_dbg("Flow Control = NONE.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Now we need to do one last check... If we auto- * negotiated to HALF DUPLEX, flow control should not be * enabled per IEEE 802.3 spec. */ ret_val = hw->mac.ops.get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { hw_dbg("Error getting link speed and duplex\n"); goto out; } if (duplex == HALF_DUPLEX) hw->fc.current_mode = e1000_fc_none; /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ ret_val = igb_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } } /* Check for the case where we have SerDes media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->phy.media_type == e1000_media_type_internal_serdes) && mac->autoneg) { /* Read the PCS_LSTS and check to see if AutoNeg * has completed. */ pcs_status_reg = rd32(E1000_PCS_LSTAT); if (!(pcs_status_reg & E1000_PCS_LSTS_AN_COMPLETE)) { hw_dbg("PCS Auto Neg has not completed.\n"); return ret_val; } /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (PCS_ANADV) and the Auto_Negotiation Base * Page Ability Register (PCS_LPAB) to determine how * flow control was negotiated. */ pcs_adv_reg = rd32(E1000_PCS_ANADV); pcs_lp_ability_reg = rd32(E1000_PCS_LPAB); /* Two bits in the Auto Negotiation Advertisement Register * (PCS_ANADV) and two bits in the Auto Negotiation Base * Page Ability Register (PCS_LPAB) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | e1000_fc_none * 0 | 1 | 0 | DC | e1000_fc_none * 0 | 1 | 1 | 0 | e1000_fc_none * 0 | 1 | 1 | 1 | e1000_fc_tx_pause * 1 | 0 | 0 | DC | e1000_fc_none * 1 | DC | 1 | DC | e1000_fc_full * 1 | 1 | 0 | 0 | e1000_fc_none * 1 | 1 | 0 | 1 | e1000_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | e1000_fc_full * */ if ((pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_PAUSE)) { /* Now we need to check if the user selected Rx ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise Rx * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == e1000_fc_full) { hw->fc.current_mode = e1000_fc_full; hw_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = Rx PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | e1000_fc_tx_pause */ else if (!(pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_adv_reg & E1000_TXCW_ASM_DIR) && (pcs_lp_ability_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_ASM_DIR)) { hw->fc.current_mode = e1000_fc_tx_pause; hw_dbg("Flow Control = Tx PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | e1000_fc_rx_pause */ else if ((pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_adv_reg & E1000_TXCW_ASM_DIR) && !(pcs_lp_ability_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_ASM_DIR)) { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = Rx PAUSE frames only.\n"); } else { /* Per the IEEE spec, at this point flow control * should be disabled. */ hw->fc.current_mode = e1000_fc_none; hw_dbg("Flow Control = NONE.\n"); } /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ pcs_ctrl_reg = rd32(E1000_PCS_LCTL); pcs_ctrl_reg |= E1000_PCS_LCTL_FORCE_FCTRL; wr32(E1000_PCS_LCTL, pcs_ctrl_reg); ret_val = igb_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); return ret_val; } } out: return ret_val; } /** * igb_get_speed_and_duplex_copper - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Read the status register for the current speed/duplex and store the current * speed and duplex for copper connections. **/ s32 igb_get_speed_and_duplex_copper(struct e1000_hw *hw, u16 *speed, u16 *duplex) { u32 status; status = rd32(E1000_STATUS); if (status & E1000_STATUS_SPEED_1000) { *speed = SPEED_1000; hw_dbg("1000 Mbs, "); } else if (status & E1000_STATUS_SPEED_100) { *speed = SPEED_100; hw_dbg("100 Mbs, "); } else { *speed = SPEED_10; hw_dbg("10 Mbs, "); } if (status & E1000_STATUS_FD) { *duplex = FULL_DUPLEX; hw_dbg("Full Duplex\n"); } else { *duplex = HALF_DUPLEX; hw_dbg("Half Duplex\n"); } return 0; } /** * igb_get_hw_semaphore - Acquire hardware semaphore * @hw: pointer to the HW structure * * Acquire the HW semaphore to access the PHY or NVM **/ s32 igb_get_hw_semaphore(struct e1000_hw *hw) { u32 swsm; s32 ret_val = 0; s32 timeout = hw->nvm.word_size + 1; s32 i = 0; /* Get the SW semaphore */ while (i < timeout) { swsm = rd32(E1000_SWSM); if (!(swsm & E1000_SWSM_SMBI)) break; udelay(50); i++; } if (i == timeout) { hw_dbg("Driver can't access device - SMBI bit is set.\n"); ret_val = -E1000_ERR_NVM; goto out; } /* Get the FW semaphore. */ for (i = 0; i < timeout; i++) { swsm = rd32(E1000_SWSM); wr32(E1000_SWSM, swsm | E1000_SWSM_SWESMBI); /* Semaphore acquired if bit latched */ if (rd32(E1000_SWSM) & E1000_SWSM_SWESMBI) break; udelay(50); } if (i == timeout) { /* Release semaphores */ igb_put_hw_semaphore(hw); hw_dbg("Driver can't access the NVM\n"); ret_val = -E1000_ERR_NVM; goto out; } out: return ret_val; } /** * igb_put_hw_semaphore - Release hardware semaphore * @hw: pointer to the HW structure * * Release hardware semaphore used to access the PHY or NVM **/ void igb_put_hw_semaphore(struct e1000_hw *hw) { u32 swsm; swsm = rd32(E1000_SWSM); swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI); wr32(E1000_SWSM, swsm); } /** * igb_get_auto_rd_done - Check for auto read completion * @hw: pointer to the HW structure * * Check EEPROM for Auto Read done bit. **/ s32 igb_get_auto_rd_done(struct e1000_hw *hw) { s32 i = 0; s32 ret_val = 0; while (i < AUTO_READ_DONE_TIMEOUT) { if (rd32(E1000_EECD) & E1000_EECD_AUTO_RD) break; usleep_range(1000, 2000); i++; } if (i == AUTO_READ_DONE_TIMEOUT) { hw_dbg("Auto read by HW from NVM has not completed.\n"); ret_val = -E1000_ERR_RESET; goto out; } out: return ret_val; } /** * igb_valid_led_default - Verify a valid default LED config * @hw: pointer to the HW structure * @data: pointer to the NVM (EEPROM) * * Read the EEPROM for the current default LED configuration. If the * LED configuration is not valid, set to a valid LED configuration. **/ static s32 igb_valid_led_default(struct e1000_hw *hw, u16 *data) { s32 ret_val; ret_val = hw->nvm.ops.read(hw, NVM_ID_LED_SETTINGS, 1, data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if (*data == ID_LED_RESERVED_0000 || *data == ID_LED_RESERVED_FFFF) { switch (hw->phy.media_type) { case e1000_media_type_internal_serdes: *data = ID_LED_DEFAULT_82575_SERDES; break; case e1000_media_type_copper: default: *data = ID_LED_DEFAULT; break; } } out: return ret_val; } /** * igb_id_led_init - * @hw: pointer to the HW structure * **/ s32 igb_id_led_init(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; const u32 ledctl_mask = 0x000000FF; const u32 ledctl_on = E1000_LEDCTL_MODE_LED_ON; const u32 ledctl_off = E1000_LEDCTL_MODE_LED_OFF; u16 data, i, temp; const u16 led_mask = 0x0F; /* i210 and i211 devices have different LED mechanism */ if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) ret_val = igb_valid_led_default_i210(hw, &data); else ret_val = igb_valid_led_default(hw, &data); if (ret_val) goto out; mac->ledctl_default = rd32(E1000_LEDCTL); mac->ledctl_mode1 = mac->ledctl_default; mac->ledctl_mode2 = mac->ledctl_default; for (i = 0; i < 4; i++) { temp = (data >> (i << 2)) & led_mask; switch (temp) { case ID_LED_ON1_DEF2: case ID_LED_ON1_ON2: case ID_LED_ON1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_on << (i << 3); break; case ID_LED_OFF1_DEF2: case ID_LED_OFF1_ON2: case ID_LED_OFF1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } switch (temp) { case ID_LED_DEF1_ON2: case ID_LED_ON1_ON2: case ID_LED_OFF1_ON2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_on << (i << 3); break; case ID_LED_DEF1_OFF2: case ID_LED_ON1_OFF2: case ID_LED_OFF1_OFF2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } } out: return ret_val; } /** * igb_cleanup_led - Set LED config to default operation * @hw: pointer to the HW structure * * Remove the current LED configuration and set the LED configuration * to the default value, saved from the EEPROM. **/ s32 igb_cleanup_led(struct e1000_hw *hw) { wr32(E1000_LEDCTL, hw->mac.ledctl_default); return 0; } /** * igb_blink_led - Blink LED * @hw: pointer to the HW structure * * Blink the led's which are set to be on. **/ s32 igb_blink_led(struct e1000_hw *hw) { u32 ledctl_blink = 0; u32 i; if (hw->phy.media_type == e1000_media_type_fiber) { /* always blink LED0 for PCI-E fiber */ ledctl_blink = E1000_LEDCTL_LED0_BLINK | (E1000_LEDCTL_MODE_LED_ON << E1000_LEDCTL_LED0_MODE_SHIFT); } else { /* Set the blink bit for each LED that's "on" (0x0E) * (or "off" if inverted) in ledctl_mode2. The blink * logic in hardware only works when mode is set to "on" * so it must be changed accordingly when the mode is * "off" and inverted. */ ledctl_blink = hw->mac.ledctl_mode2; for (i = 0; i < 32; i += 8) { u32 mode = (hw->mac.ledctl_mode2 >> i) & E1000_LEDCTL_LED0_MODE_MASK; u32 led_default = hw->mac.ledctl_default >> i; if ((!(led_default & E1000_LEDCTL_LED0_IVRT) && (mode == E1000_LEDCTL_MODE_LED_ON)) || ((led_default & E1000_LEDCTL_LED0_IVRT) && (mode == E1000_LEDCTL_MODE_LED_OFF))) { ledctl_blink &= ~(E1000_LEDCTL_LED0_MODE_MASK << i); ledctl_blink |= (E1000_LEDCTL_LED0_BLINK | E1000_LEDCTL_MODE_LED_ON) << i; } } } wr32(E1000_LEDCTL, ledctl_blink); return 0; } /** * igb_led_off - Turn LED off * @hw: pointer to the HW structure * * Turn LED off. **/ s32 igb_led_off(struct e1000_hw *hw) { switch (hw->phy.media_type) { case e1000_media_type_copper: wr32(E1000_LEDCTL, hw->mac.ledctl_mode1); break; default: break; } return 0; } /** * igb_disable_pcie_master - Disables PCI-express master access * @hw: pointer to the HW structure * * Returns 0 (0) if successful, else returns -10 * (-E1000_ERR_MASTER_REQUESTS_PENDING) if master disable bit has not caused * the master requests to be disabled. * * Disables PCI-Express master access and verifies there are no pending * requests. **/ s32 igb_disable_pcie_master(struct e1000_hw *hw) { u32 ctrl; s32 timeout = MASTER_DISABLE_TIMEOUT; s32 ret_val = 0; if (hw->bus.type != e1000_bus_type_pci_express) goto out; ctrl = rd32(E1000_CTRL); ctrl |= E1000_CTRL_GIO_MASTER_DISABLE; wr32(E1000_CTRL, ctrl); while (timeout) { if (!(rd32(E1000_STATUS) & E1000_STATUS_GIO_MASTER_ENABLE)) break; udelay(100); timeout--; } if (!timeout) { hw_dbg("Master requests are pending.\n"); ret_val = -E1000_ERR_MASTER_REQUESTS_PENDING; goto out; } out: return ret_val; } /** * igb_validate_mdi_setting - Verify MDI/MDIx settings * @hw: pointer to the HW structure * * Verify that when not using auto-negotitation that MDI/MDIx is correctly * set, which is forced to MDI mode only. **/ s32 igb_validate_mdi_setting(struct e1000_hw *hw) { s32 ret_val = 0; /* All MDI settings are supported on 82580 and newer. */ if (hw->mac.type >= e1000_82580) goto out; if (!hw->mac.autoneg && (hw->phy.mdix == 0 || hw->phy.mdix == 3)) { hw_dbg("Invalid MDI setting detected\n"); hw->phy.mdix = 1; ret_val = -E1000_ERR_CONFIG; goto out; } out: return ret_val; } /** * igb_write_8bit_ctrl_reg - Write a 8bit CTRL register * @hw: pointer to the HW structure * @reg: 32bit register offset such as E1000_SCTL * @offset: register offset to write to * @data: data to write at register offset * * Writes an address/data control type register. There are several of these * and they all have the format address << 8 | data and bit 31 is polled for * completion. **/ s32 igb_write_8bit_ctrl_reg(struct e1000_hw *hw, u32 reg, u32 offset, u8 data) { u32 i, regvalue = 0; s32 ret_val = 0; /* Set up the address and data */ regvalue = ((u32)data) | (offset << E1000_GEN_CTL_ADDRESS_SHIFT); wr32(reg, regvalue); /* Poll the ready bit to see if the MDI read completed */ for (i = 0; i < E1000_GEN_POLL_TIMEOUT; i++) { udelay(5); regvalue = rd32(reg); if (regvalue & E1000_GEN_CTL_READY) break; } if (!(regvalue & E1000_GEN_CTL_READY)) { hw_dbg("Reg %08x did not indicate ready\n", reg); ret_val = -E1000_ERR_PHY; goto out; } out: return ret_val; } /** * igb_enable_mng_pass_thru - Enable processing of ARP's * @hw: pointer to the HW structure * * Verifies the hardware needs to leave interface enabled so that frames can * be directed to and from the management interface. **/ bool igb_enable_mng_pass_thru(struct e1000_hw *hw) { u32 manc; u32 fwsm, factps; bool ret_val = false; if (!hw->mac.asf_firmware_present) goto out; manc = rd32(E1000_MANC); if (!(manc & E1000_MANC_RCV_TCO_EN)) goto out; if (hw->mac.arc_subsystem_valid) { fwsm = rd32(E1000_FWSM); factps = rd32(E1000_FACTPS); if (!(factps & E1000_FACTPS_MNGCG) && ((fwsm & E1000_FWSM_MODE_MASK) == (e1000_mng_mode_pt << E1000_FWSM_MODE_SHIFT))) { ret_val = true; goto out; } } else { if ((manc & E1000_MANC_SMBUS_EN) && !(manc & E1000_MANC_ASF_EN)) { ret_val = true; goto out; } } out: return ret_val; }
377784.c
int printTeste() { printf("Hello World"); printf("\n New line"); printf("\"Aspas\""); //Formatadores //Numero printf("%d", 800); printf("%c", "a"); printf("My favorite food is %s and costs %f", "pizza", 50.0); return 0; }
411945.c
//Arif Burak Demiray //This code compiled with GNU99 #include "dynamic_array.h" #include <stdio.h> #include <stdlib.h> //calculates size of a char array int size(char *values) { int size = 0; //size char last; //current char value while (1) { last = values[size]; //take current char if (last != '\0') //if char not equal empty size++; //increase else //otherwise means char array finished break; } return size; //return size } //copies a given char array to char list void copy(char list[], char *ptr, int len) { //int sizeList = size(ptr); //calculates size of char array for (int i = 0; i < len; i++) { list[i] = ptr[i]; //and copy it } } //destructor for array struct void delete (Array *array) { free(array->values); //free char values array->values = NULL; //make pointer null } //changes arrays values to element values if successful returns 1 else 0 void set(Array *array, Array *element) { array->size = element->size; //update size char *temp = malloc(array->size); //take space for new values delete (array); //delete old values copy(temp, element->values, array->size); //and copy element to buffer array->values = temp; //than make values buffer } //initially create an array struct Array initalize() { Array dynamic; //array char *values = malloc(5); //initially 5 dynamic.values = values; //make values values dynamic.size = 5; //make size 5 return dynamic; //and return it } //this function creates a dynamic array from given char array Array array(char *array) { Array dynamic; //array struct int sizeArray = size(array); //calculate size of the char array /* if(sizeArray > 0 & array[sizeArray-1]=='\n') //if there is newline at the end array[sizeArray-1]='\0'; //eliminate it */ dynamic.values = array; //make values array dynamic.size = sizeArray; //update size return dynamic; //return it } //this function lowers char arrays void toLowerCase(Array *input) { int max = input->size; //calculate size for (int i = 0; i < max; i++) { if (input->values[i] >= 65 && input->values[i] <= 90) { //if values in range of A,B....Y,Z input->values[i] = input->values[i] + 32; //make it a,b..y,z } //because there is 32 difference from A to a,B to b,..Y to y,Z to z } } //this function splits a sentence into 2 by given delimeter int split(char *sentence, char *delimeter) { int max = size(sentence); //calculate size int delSize = size(delimeter); int wordSize = -1; //found delimeter location for (int i = 0; i < max; i++) { if (sentence[i] == delimeter[0]) { //if delimeter location wordSize = i; for (int j = 0; j < delSize; j++) { if (sentence[i] == delimeter[j]) { } else return -1; } break; //break } } return wordSize; } //converts a char to integer, returns number if successful //otherwise returns -1 int to_int(char *input) { int len = size(input); //calculate size int isOkey = 0; //if it is okey to convert for (int i = 0; i < len; i++) { if (input[i] >= 48 & input[i] <= 57) { //if char values in range 0 to 9 isOkey++; //increase isOkey } if (input[i] == '\n') //if there is newline at the end isOkey++; //increase isOkey } if (isOkey == len) { //if isOkey equal to char len return atoi(input); //convert to integer } return -1; //otherwise return -1 } //this function deletes all elements of an array by its len void free_array(Array *array, int len) { for (int i = 0; i < len; i++)//delete all elements { delete (&array[i]); } array = NULL; }
110290.c
/* * drivers/net/ethernet/netx-eth.c * * Copyright (c) 2005 Sascha Hauer <[email protected]>, Pengutronix * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/platform_device.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/mii.h> #include <asm/io.h> #include <mach/hardware.h> #include <mach/netx-regs.h> #include <mach/pfifo.h> #include <mach/xc.h> #include <linux/platform_data/eth-netx.h> /* XC Fifo Offsets */ #define EMPTY_PTR_FIFO(xcno) (0 + ((xcno) << 3)) /* Index of the empty pointer FIFO */ #define IND_FIFO_PORT_HI(xcno) (1 + ((xcno) << 3)) /* Index of the FIFO where received */ /* Data packages are indicated by XC */ #define IND_FIFO_PORT_LO(xcno) (2 + ((xcno) << 3)) /* Index of the FIFO where received */ /* Data packages are indicated by XC */ #define REQ_FIFO_PORT_HI(xcno) (3 + ((xcno) << 3)) /* Index of the FIFO where Data packages */ /* have to be indicated by ARM which */ /* shall be sent */ #define REQ_FIFO_PORT_LO(xcno) (4 + ((xcno) << 3)) /* Index of the FIFO where Data packages */ /* have to be indicated by ARM which shall */ /* be sent */ #define CON_FIFO_PORT_HI(xcno) (5 + ((xcno) << 3)) /* Index of the FIFO where sent Data packages */ /* are confirmed */ #define CON_FIFO_PORT_LO(xcno) (6 + ((xcno) << 3)) /* Index of the FIFO where sent Data */ /* packages are confirmed */ #define PFIFO_MASK(xcno) (0x7f << (xcno*8)) #define FIFO_PTR_FRAMELEN_SHIFT 0 #define FIFO_PTR_FRAMELEN_MASK (0x7ff << 0) #define FIFO_PTR_FRAMELEN(len) (((len) << 0) & FIFO_PTR_FRAMELEN_MASK) #define FIFO_PTR_TIMETRIG (1<<11) #define FIFO_PTR_MULTI_REQ #define FIFO_PTR_ORIGIN (1<<14) #define FIFO_PTR_VLAN (1<<15) #define FIFO_PTR_FRAMENO_SHIFT 16 #define FIFO_PTR_FRAMENO_MASK (0x3f << 16) #define FIFO_PTR_FRAMENO(no) (((no) << 16) & FIFO_PTR_FRAMENO_MASK) #define FIFO_PTR_SEGMENT_SHIFT 22 #define FIFO_PTR_SEGMENT_MASK (0xf << 22) #define FIFO_PTR_SEGMENT(seg) (((seg) & 0xf) << 22) #define FIFO_PTR_ERROR_SHIFT 28 #define FIFO_PTR_ERROR_MASK (0xf << 28) #define ISR_LINK_STATUS_CHANGE (1<<4) #define ISR_IND_LO (1<<3) #define ISR_CON_LO (1<<2) #define ISR_IND_HI (1<<1) #define ISR_CON_HI (1<<0) #define ETH_MAC_LOCAL_CONFIG 0x1560 #define ETH_MAC_4321 0x1564 #define ETH_MAC_65 0x1568 #define MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT 16 #define MAC_TRAFFIC_CLASS_ARRANGEMENT_MASK (0xf<<MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT) #define MAC_TRAFFIC_CLASS_ARRANGEMENT(x) (((x)<<MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT) & MAC_TRAFFIC_CLASS_ARRANGEMENT_MASK) #define LOCAL_CONFIG_LINK_STATUS_IRQ_EN (1<<24) #define LOCAL_CONFIG_CON_LO_IRQ_EN (1<<23) #define LOCAL_CONFIG_CON_HI_IRQ_EN (1<<22) #define LOCAL_CONFIG_IND_LO_IRQ_EN (1<<21) #define LOCAL_CONFIG_IND_HI_IRQ_EN (1<<20) #define CARDNAME "netx-eth" /* LSB must be zero */ #define INTERNAL_PHY_ADR 0x1c struct netx_eth_priv { void __iomem *sram_base, *xpec_base, *xmac_base; int id; struct mii_if_info mii; u32 msg_enable; struct xc *xc; spinlock_t lock; }; static void netx_eth_set_multicast_list(struct net_device *ndev) { /* implement me */ } static int netx_eth_hard_start_xmit(struct sk_buff *skb, struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned char *buf = skb->data; unsigned int len = skb->len; spin_lock_irq(&priv->lock); memcpy_toio(priv->sram_base + 1560, (void *)buf, len); if (len < 60) { memset_io(priv->sram_base + 1560 + len, 0, 60 - len); len = 60; } pfifo_push(REQ_FIFO_PORT_LO(priv->id), FIFO_PTR_SEGMENT(priv->id) | FIFO_PTR_FRAMENO(1) | FIFO_PTR_FRAMELEN(len)); ndev->stats.tx_packets++; ndev->stats.tx_bytes += skb->len; netif_stop_queue(ndev); spin_unlock_irq(&priv->lock); dev_kfree_skb(skb); return NETDEV_TX_OK; } static void netx_eth_receive(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned int val, frameno, seg, len; unsigned char *data; struct sk_buff *skb; val = pfifo_pop(IND_FIFO_PORT_LO(priv->id)); frameno = (val & FIFO_PTR_FRAMENO_MASK) >> FIFO_PTR_FRAMENO_SHIFT; seg = (val & FIFO_PTR_SEGMENT_MASK) >> FIFO_PTR_SEGMENT_SHIFT; len = (val & FIFO_PTR_FRAMELEN_MASK) >> FIFO_PTR_FRAMELEN_SHIFT; skb = netdev_alloc_skb(ndev, len); if (unlikely(skb == NULL)) { ndev->stats.rx_dropped++; return; } data = skb_put(skb, len); memcpy_fromio(data, priv->sram_base + frameno * 1560, len); pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_SEGMENT(seg) | FIFO_PTR_FRAMENO(frameno)); skb->protocol = eth_type_trans(skb, ndev); netif_rx(skb); ndev->stats.rx_packets++; ndev->stats.rx_bytes += len; } static irqreturn_t netx_eth_interrupt(int irq, void *dev_id) { struct net_device *ndev = dev_id; struct netx_eth_priv *priv = netdev_priv(ndev); int status; unsigned long flags; spin_lock_irqsave(&priv->lock, flags); status = readl(NETX_PFIFO_XPEC_ISR(priv->id)); while (status) { int fill_level; writel(status, NETX_PFIFO_XPEC_ISR(priv->id)); if ((status & ISR_CON_HI) || (status & ISR_IND_HI)) printk("%s: unexpected status: 0x%08x\n", __func__, status); fill_level = readl(NETX_PFIFO_FILL_LEVEL(IND_FIFO_PORT_LO(priv->id))); while (fill_level--) netx_eth_receive(ndev); if (status & ISR_CON_LO) netif_wake_queue(ndev); if (status & ISR_LINK_STATUS_CHANGE) mii_check_media(&priv->mii, netif_msg_link(priv), 1); status = readl(NETX_PFIFO_XPEC_ISR(priv->id)); } spin_unlock_irqrestore(&priv->lock, flags); return IRQ_HANDLED; } static int netx_eth_open(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); if (request_irq (ndev->irq, netx_eth_interrupt, IRQF_SHARED, ndev->name, ndev)) return -EAGAIN; writel(ndev->dev_addr[0] | ndev->dev_addr[1]<<8 | ndev->dev_addr[2]<<16 | ndev->dev_addr[3]<<24, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_4321); writel(ndev->dev_addr[4] | ndev->dev_addr[5]<<8, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_65); writel(LOCAL_CONFIG_LINK_STATUS_IRQ_EN | LOCAL_CONFIG_CON_LO_IRQ_EN | LOCAL_CONFIG_CON_HI_IRQ_EN | LOCAL_CONFIG_IND_LO_IRQ_EN | LOCAL_CONFIG_IND_HI_IRQ_EN, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_LOCAL_CONFIG); mii_check_media(&priv->mii, netif_msg_link(priv), 1); netif_start_queue(ndev); return 0; } static int netx_eth_close(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); netif_stop_queue(ndev); writel(0, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_LOCAL_CONFIG); free_irq(ndev->irq, ndev); return 0; } static void netx_eth_timeout(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); int i; printk(KERN_ERR "%s: transmit timed out, resetting\n", ndev->name); spin_lock_irq(&priv->lock); xc_reset(priv->xc); xc_start(priv->xc); for (i=2; i<=18; i++) pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_FRAMENO(i) | FIFO_PTR_SEGMENT(priv->id)); spin_unlock_irq(&priv->lock); netif_wake_queue(ndev); } static int netx_eth_phy_read(struct net_device *ndev, int phy_id, int reg) { unsigned int val; val = MIIMU_SNRDY | MIIMU_PREAMBLE | MIIMU_PHYADDR(phy_id) | MIIMU_REGADDR(reg) | MIIMU_PHY_NRES; writel(val, NETX_MIIMU); while (readl(NETX_MIIMU) & MIIMU_SNRDY); return readl(NETX_MIIMU) >> 16; } static void netx_eth_phy_write(struct net_device *ndev, int phy_id, int reg, int value) { unsigned int val; val = MIIMU_SNRDY | MIIMU_PREAMBLE | MIIMU_PHYADDR(phy_id) | MIIMU_REGADDR(reg) | MIIMU_PHY_NRES | MIIMU_OPMODE_WRITE | MIIMU_DATA(value); writel(val, NETX_MIIMU); while (readl(NETX_MIIMU) & MIIMU_SNRDY); } static const struct net_device_ops netx_eth_netdev_ops = { .ndo_open = netx_eth_open, .ndo_stop = netx_eth_close, .ndo_start_xmit = netx_eth_hard_start_xmit, .ndo_tx_timeout = netx_eth_timeout, .ndo_set_rx_mode = netx_eth_set_multicast_list, .ndo_change_mtu = eth_change_mtu, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = eth_mac_addr, }; static int netx_eth_enable(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned int mac4321, mac65; int running, i; ether_setup(ndev); ndev->netdev_ops = &netx_eth_netdev_ops; ndev->watchdog_timeo = msecs_to_jiffies(5000); priv->msg_enable = NETIF_MSG_LINK; priv->mii.phy_id_mask = 0x1f; priv->mii.reg_num_mask = 0x1f; priv->mii.force_media = 0; priv->mii.full_duplex = 0; priv->mii.dev = ndev; priv->mii.mdio_read = netx_eth_phy_read; priv->mii.mdio_write = netx_eth_phy_write; priv->mii.phy_id = INTERNAL_PHY_ADR + priv->id; running = xc_running(priv->xc); xc_stop(priv->xc); /* if the xc engine is already running, assume the bootloader has * loaded the firmware for us */ if (running) { /* get Node Address from hardware */ mac4321 = readl(priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_4321); mac65 = readl(priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_65); ndev->dev_addr[0] = mac4321 & 0xff; ndev->dev_addr[1] = (mac4321 >> 8) & 0xff; ndev->dev_addr[2] = (mac4321 >> 16) & 0xff; ndev->dev_addr[3] = (mac4321 >> 24) & 0xff; ndev->dev_addr[4] = mac65 & 0xff; ndev->dev_addr[5] = (mac65 >> 8) & 0xff; } else { if (xc_request_firmware(priv->xc)) { printk(CARDNAME ": requesting firmware failed\n"); return -ENODEV; } } xc_reset(priv->xc); xc_start(priv->xc); if (!is_valid_ether_addr(ndev->dev_addr)) printk("%s: Invalid ethernet MAC address. Please " "set using ifconfig\n", ndev->name); for (i=2; i<=18; i++) pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_FRAMENO(i) | FIFO_PTR_SEGMENT(priv->id)); return register_netdev(ndev); } static int netx_eth_drv_probe(struct platform_device *pdev) { struct netx_eth_priv *priv; struct net_device *ndev; struct netxeth_platform_data *pdata; int ret; ndev = alloc_etherdev(sizeof (struct netx_eth_priv)); if (!ndev) { ret = -ENOMEM; goto exit; } SET_NETDEV_DEV(ndev, &pdev->dev); platform_set_drvdata(pdev, ndev); priv = netdev_priv(ndev); pdata = dev_get_platdata(&pdev->dev); priv->xc = request_xc(pdata->xcno, &pdev->dev); if (!priv->xc) { dev_err(&pdev->dev, "unable to request xc engine\n"); ret = -ENODEV; goto exit_free_netdev; } ndev->irq = priv->xc->irq; priv->id = pdev->id; priv->xpec_base = priv->xc->xpec_base; priv->xmac_base = priv->xc->xmac_base; priv->sram_base = priv->xc->sram_base; spin_lock_init(&priv->lock); ret = pfifo_request(PFIFO_MASK(priv->id)); if (ret) { printk("unable to request PFIFO\n"); goto exit_free_xc; } ret = netx_eth_enable(ndev); if (ret) goto exit_free_pfifo; return 0; exit_free_pfifo: pfifo_free(PFIFO_MASK(priv->id)); exit_free_xc: free_xc(priv->xc); exit_free_netdev: free_netdev(ndev); exit: return ret; } static int netx_eth_drv_remove(struct platform_device *pdev) { struct net_device *ndev = platform_get_drvdata(pdev); struct netx_eth_priv *priv = netdev_priv(ndev); unregister_netdev(ndev); xc_stop(priv->xc); free_xc(priv->xc); free_netdev(ndev); pfifo_free(PFIFO_MASK(priv->id)); return 0; } static int netx_eth_drv_suspend(struct platform_device *pdev, pm_message_t state) { dev_err(&pdev->dev, "suspend not implemented\n"); return 0; } static int netx_eth_drv_resume(struct platform_device *pdev) { dev_err(&pdev->dev, "resume not implemented\n"); return 0; } static struct platform_driver netx_eth_driver = { .probe = netx_eth_drv_probe, .remove = netx_eth_drv_remove, .suspend = netx_eth_drv_suspend, .resume = netx_eth_drv_resume, .driver = { .name = CARDNAME, .owner = THIS_MODULE, }, }; static int __init netx_eth_init(void) { unsigned int phy_control, val; printk("NetX Ethernet driver\n"); phy_control = PHY_CONTROL_PHY_ADDRESS(INTERNAL_PHY_ADR>>1) | PHY_CONTROL_PHY1_MODE(PHY_MODE_ALL) | PHY_CONTROL_PHY1_AUTOMDIX | PHY_CONTROL_PHY1_EN | PHY_CONTROL_PHY0_MODE(PHY_MODE_ALL) | PHY_CONTROL_PHY0_AUTOMDIX | PHY_CONTROL_PHY0_EN | PHY_CONTROL_CLK_XLATIN; val = readl(NETX_SYSTEM_IOC_ACCESS_KEY); writel(val, NETX_SYSTEM_IOC_ACCESS_KEY); writel(phy_control | PHY_CONTROL_RESET, NETX_SYSTEM_PHY_CONTROL); udelay(100); val = readl(NETX_SYSTEM_IOC_ACCESS_KEY); writel(val, NETX_SYSTEM_IOC_ACCESS_KEY); writel(phy_control, NETX_SYSTEM_PHY_CONTROL); return platform_driver_register(&netx_eth_driver); } static void __exit netx_eth_cleanup(void) { platform_driver_unregister(&netx_eth_driver); } module_init(netx_eth_init); module_exit(netx_eth_cleanup); MODULE_AUTHOR("Sascha Hauer, Pengutronix"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" CARDNAME); MODULE_FIRMWARE("xc0.bin"); MODULE_FIRMWARE("xc1.bin"); MODULE_FIRMWARE("xc2.bin");
499641.c
/* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2015-2020 Micron Technology, Inc. All rights reserved. */ #include <stdio.h> #include <string.h> #include <hse/hse.h> /* * This is a simple example application that performs basic key-value operations * on a KVS. * * This program * 1. puts few keys into a KVS * 2. verifies that hse_kvs_get() can find them. * 3. delete one of the keys * 4. verify that the deleted key cannot be found. */ int usage(char *prog) { printf("usage: %s <kvdb> <kvs>\n", prog); return 1; } int main(int argc, char **argv) { char *mpool_name, *kvs_name; struct hse_kvdb *kvdb; struct hse_kvs * kvs; size_t vlen; char vbuf[32]; bool found; hse_err_t rc; if (argc != 3) return usage(argv[0]); mpool_name = argv[1]; kvs_name = argv[2]; rc = hse_kvdb_init(); if (rc) { printf("failed to initialize kvdb"); exit(1); } rc = hse_kvdb_open(mpool_name, NULL, &kvdb); if (rc) { printf("Cannot open kvdb: %s\n", strerror(rc)); exit(1); } rc = hse_kvdb_kvs_open(kvdb, kvs_name, NULL, &kvs); if (rc) exit(1); /* Error handling is elided for clarity */ /* 1. Put a few keys and verify that hse_kvs_get() can find them */ rc = hse_kvs_put(kvs, NULL, "k1", 2, "val1", 4); rc = hse_kvs_put(kvs, NULL, "k2", 2, "val2", 4); rc = hse_kvs_put(kvs, NULL, "k3", 2, "val3", 4); rc = hse_kvs_put(kvs, NULL, "k4", 2, NULL, 0); hse_kvs_get(kvs, NULL, "k1", 2, &found, vbuf, sizeof(vbuf), &vlen); printf("k1 found = %s\n", found ? "true" : "false"); hse_kvs_get(kvs, NULL, "k2", 2, &found, vbuf, sizeof(vbuf), &vlen); printf("k2 found = %s\n", found ? "true" : "false"); hse_kvs_get(kvs, NULL, "k3", 2, &found, vbuf, sizeof(vbuf), &vlen); printf("k3 found = %s\n", found ? "true" : "false"); hse_kvs_get(kvs, NULL, "k4", 2, &found, vbuf, sizeof(vbuf), &vlen); printf("k4 found = %s, length was %lu bytes\n", found ? "true" : "false", vlen); /* 2. Delete a key and ensure that it cannot be found by hse_kvs_get() */ rc = hse_kvs_delete(kvs, NULL, "k1", 2); printf("k1 deleted\n"); rc = hse_kvs_get(kvs, NULL, "k1", 2, &found, vbuf, sizeof(vbuf), &vlen); printf("k1 found = %s\n", found ? "true" : "false"); hse_kvdb_close(kvdb); hse_kvdb_fini(); return 0; }
339908.c
#include <lv2/lv2.h> #include <lv2/modules.h> #include <lv2/thread.h> #ifdef DEBUG #include <lv2/debug.h> #endif int prx_get_module_name_by_address(process_t process, void *addr, char *name) { sys_prx_module_info_t modinfo; sys_prx_id_t id = prx_get_module_id_by_address(process, addr); if (id < 0) return id; memset(&modinfo, 0, sizeof(modinfo)); int ret = prx_get_module_info(process, id, &modinfo, NULL, NULL); if (ret < 0) return ret; strncpy(name, modinfo.name, 30); return 0; } int prx_start_module_with_thread(sys_prx_id_t id, process_t process, uint64_t flags, uint64_t arg) { int ret; uint64_t meminfo[5]; uint32_t toc[2]; thread_t thread; uint64_t exit_code; meminfo[0] = sizeof(meminfo); meminfo[1] = 1; ret = prx_start_module(id, process, flags, meminfo); if (ret != 0) { //printf("prx_start_module returned: %llx\n", ret); return ret; } ret = copy_from_process(process, (void *)meminfo[2], toc, sizeof(toc)); if (ret != 0) { //printf("copy_from_process returned: %llx\n", ret); return ret; } ret = ppu_user_thread_create(process, &thread, toc, arg, 0, 0x1000, PPU_THREAD_CREATE_JOINABLE, ""); if (ret != 0) { //printf("ppu_user_thread_create returned: %llx\n", ret); return ret; } ppu_thread_join(thread, &exit_code); meminfo[1] = 2; meminfo[3] = 0; return prx_start_module(id, process, flags, meminfo); } int prx_stop_module_with_thread(sys_prx_id_t id, process_t process, uint64_t flags, uint64_t arg) { int ret; uint64_t meminfo[5]; uint32_t toc[2]; thread_t thread; uint64_t exit_code; meminfo[0] = sizeof(meminfo); meminfo[1] = 1; ret = prx_stop_module(id, process, flags, meminfo); if (ret != 0) return ret; ret = copy_from_process(process, (void *)meminfo[2], toc, sizeof(toc)); if (ret != 0) return ret; ret = ppu_user_thread_create(process, &thread, toc, arg, 0, 0x1000, PPU_THREAD_CREATE_JOINABLE, ""); if (ret != 0) return ret; return ppu_thread_join(thread, &exit_code); }
518930.c
#include <stdio.h> #include <string.h> #include <stdint.h> #include <bl_timer.h> #include <blog.h> #include <bloop.h> #include <utils_debug.h> int bloop_init(struct loop_ctx *loop) { int i; memset(loop, 0, sizeof(struct loop_ctx)); for (i = 0; i < sizeof(loop->list)/sizeof(loop->list[0]); i++) { utils_list_init(&(loop->list[i])); } INIT_UTILS_DLIST_HEAD(&(loop->timer_dlist)); INIT_UTILS_DLIST_HEAD(&(loop->timer_dued)); printf("=== %d task inited\r\n", i); return 0; } int bloop_handler_register(struct loop_ctx *loop, const struct loop_evt_handler *handler, int priority) { int i; if (priority < 0 || priority >= LOOP_TASK_MAX) { /* out of range */ return -1; } if (NULL == loop->handlers[priority]) { i = priority; } else { for (i = priority; i < LOOP_TASK_MAX; i++) { if (NULL == loop->handlers[priority]) { break; } } if (LOOP_TASK_MAX == i) { /*No valid task SLOT*/ return -1; } } loop->handlers[i] = handler; return 0; } int bloop_handler_unregister(struct loop_ctx *loop, const struct loop_evt_handler *handler, int priority) { if (priority < 0 || priority >= LOOP_TASK_MAX) { /* out of range */ return -1; } if (NULL == loop->handlers[priority]) { /* empty */ return -2; } if (handler != loop->handlers[priority]) { /* something mustbe wrong */ return -3; } loop->handlers[priority] = NULL; return 0; } void bloop_timer_init(struct loop_timer *timer, int use_auto_free) { memset(timer, 0, sizeof(struct loop_timer)); utils_dlist_init(&timer->dlist_item); timer->flags = use_auto_free ? LOOP_TIMER_FLAG_AUTO_FREE : LOOP_TIMER_FLAG_NONE; } void bloop_timer_configure(struct loop_timer *timer, unsigned int delay_ms, void(*cb)(struct loop_ctx *loop, struct loop_timer *timer, void *arg), void *arg, int idx_task, uint32_t evt_type_map) { timer->time_added = xTaskGetTickCount(); timer->time_target = timer->time_added + delay_ms; timer->cb = cb; timer->arg = arg; timer->idx_task = idx_task; timer->evt_type_map = evt_type_map; } void bloop_timer_repeat_enable(struct loop_timer *timer) { timer->flags |= LOOP_TIMER_FLAG_AUTO_REPEAT; } void bloop_timer_repeat_reconfigure(struct loop_timer *timer) { int delay_ms; delay_ms = (int)timer->time_target - (int)timer->time_added; timer->time_added = xTaskGetTickCount(); timer->time_target = timer->time_added + delay_ms; } void bloop_timer_register(struct loop_ctx *loop, struct loop_timer *timer) { int found = 0; struct loop_timer *node = NULL, *node_pre = NULL; if (utils_dlist_empty(&loop->timer_dlist)) { utils_dlist_add(&timer->dlist_item, &loop->timer_dlist); } else { utils_dlist_for_each_entry(&loop->timer_dlist, node, struct loop_timer, dlist_item) { if ((int)timer->time_target - (int)node->time_target <= 0) { /* ascend list on time_target*/ if (NULL == node_pre) { /* Still add to the head*/ utils_dlist_add(&timer->dlist_item, &loop->timer_dlist); } else { utils_dlist_add(&timer->dlist_item, &node_pre->dlist_item); } found = 1; break; } else { node_pre = node; } } if (0 == found) { /*add to the tail*/ utils_dlist_add(&timer->dlist_item, &node_pre->dlist_item); } } } /* timer maybe free after this function*/ static inline void _timer_is_up_handle(struct loop_ctx *loop, struct loop_timer *timer) { bloop_evt_set_sync(loop, timer->idx_task, timer->evt_type_map); if (timer->cb) { timer->cb(loop, timer, timer->arg); } utils_dlist_del(&timer->dlist_item); utils_dlist_add(&timer->dlist_item, &loop->timer_dued); } static inline void _timer_dued_clean(struct loop_ctx *loop) { utils_dlist_t *tmp; struct loop_timer *timer; utils_dlist_for_each_entry_safe(&loop->timer_dued, tmp, timer, struct loop_timer, dlist_item) { utils_dlist_del(&timer->dlist_item); if (LOOP_TIMER_IS_AUTO_FREE(timer)) { blog_debug("Free now\r\n"); vPortFree(timer); } else if (LOOP_TIMER_IS_AUTO_REPEAT(timer)) { blog_debug("Repeat timer\r\n"); bloop_timer_repeat_reconfigure(timer); bloop_timer_register(loop, timer); } } } static int _bloop_wait(struct loop_ctx *loop) { struct loop_timer *timer = NULL; utils_dlist_t *tmp; int time2wait; unsigned int time_now; copy_evt: /* Copy latest evt from ASYNC evt */ taskENTER_CRITICAL(); loop->bitmap_evt_sync |= loop->bitmap_evt_async; loop->bitmap_evt_async = 0; taskEXIT_CRITICAL(); if (0 == loop->bitmap_evt_sync) { if (utils_dlist_empty(&loop->timer_dlist)) { /* timer list is empty*/ ulTaskNotifyTake(pdTRUE, portMAX_DELAY); } else { /* timer list is NOT empty, so wait with timeout*/ timer = utils_dlist_first_entry(&loop->timer_dlist, struct loop_timer, dlist_item); time2wait = (int)timer->time_target - (int)xTaskGetTickCount(); if (time2wait > 0) { ulTaskNotifyTake(pdTRUE, time2wait); } else { /*time is up, so quit now*/ goto handle_timer; } } goto copy_evt; } handle_timer: if (!utils_dlist_empty(&loop->timer_dlist)) { time_now = xTaskGetTickCount(); //must use time_now to skeep the snapshot of tiemstamp utils_dlist_for_each_entry_safe(&loop->timer_dlist, tmp, timer, struct loop_timer, dlist_item) { if ((int)time_now - (int)timer->time_target >= 0) { /*this timer is up*/ _timer_is_up_handle(loop, timer); } else { /* Break now, since timer list is ascend*/ break; } } _timer_dued_clean(loop); } return 0; } static inline int _evt_highest(struct loop_ctx *loop) { return 31 - __builtin_clz(loop->bitmap_evt_sync); } static inline int _msg_highest(struct loop_ctx *loop) { return 31 - __builtin_clz(loop->bitmap_msg); } static inline void _evt_handle(struct loop_ctx *loop, int highest_evt) { const struct loop_evt_handler *handler; struct loop_evt_handler_statistic *statistic; int time_start; handler = loop->handlers[highest_evt]; BL_ASSERT_ERROR(handler); /* Update all the possible EVT Map for this handler*/ taskENTER_CRITICAL(); loop->evt_type_map_sync[highest_evt] |= loop->evt_type_map_async[highest_evt]; loop->evt_type_map_async[highest_evt] = 0; taskEXIT_CRITICAL(); time_start = bl_timer_now_us(); handler->evt(loop, handler, &(loop->bitmap_evt_sync), &(loop->evt_type_map_sync[highest_evt])); //FIXME not Count in to the task switch during evt handler statistic = &loop->statistic[highest_evt]; statistic->time_consumed = (int)bl_timer_now_us() - (int)time_start; statistic->time_accumulated += statistic->time_consumed; if (statistic->time_max < statistic->time_consumed) { /* TODO: 使用中值统计更合理?*/ statistic->time_max = statistic->time_consumed; } statistic->count_triggered++; bloop_evt_unset_sync(loop, highest_evt); } static inline void _msg_handle(struct loop_ctx *loop, int highest_msg) { #if 0 const struct loop_evt_handler *handler; #endif struct loop_msg *msg; //TODO use containerof msg = (struct loop_msg*)utils_list_pop_front(&loop->list[highest_msg]); BL_ASSERT_ERROR(msg); #if 0 handler = loop->handlers[msg->u.header.priority]; #endif #if 0 uint8_t priority; uint8_t id_dst; uint8_t id_msg; uint8_t id_src; } header; } u; BL_ASSERT_ERROR(handler); #endif } static void _bloop_handle_set(struct loop_ctx *loop) { loop->looper = xTaskGetCurrentTaskHandle(); } void bloop_wait_startup(struct loop_ctx *loop) { while (NULL == loop->looper) { vTaskDelay(1); } } int bloop_run(struct loop_ctx *loop) { int highest_evt, highest_msg; /*setup current task handle of looper */ _bloop_handle_set(loop); while (0 == _bloop_wait(loop)) { /*check highest EVT or MSG*/ highest_evt = _evt_highest(loop); highest_msg = _msg_highest(loop); if (highest_evt >= highest_msg && highest_evt >= 0) { /*highest_evt may have evt to handle*/ _evt_handle(loop, highest_evt); } else if (highest_msg >= 0) { /*highest_msg may have msg to handle*/ _msg_handle(loop, highest_msg); } } return 0; } void bloop_evt_set_async(struct loop_ctx *loop, unsigned int evt, uint32_t evt_map) { BL_ASSERT_ERROR(evt < LOOP_TASK_MAX); taskENTER_CRITICAL(); loop->bitmap_evt_async |= (1 << evt); loop->evt_type_map_async[evt] |= evt_map; taskEXIT_CRITICAL(); /*wait up looper in case*/ xTaskNotifyGive(loop->looper); } void bloop_evt_set_async_fromISR(struct loop_ctx *loop, unsigned int evt, uint32_t evt_map) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; BL_ASSERT_ERROR(evt < LOOP_TASK_MAX); loop->bitmap_evt_async |= (1 << evt); loop->evt_type_map_async[evt] |= evt_map; /*wait up looper in case*/ vTaskNotifyGiveFromISR(loop->looper, &xHigherPriorityTaskWoken); if (pdTRUE == xHigherPriorityTaskWoken) { portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } } void bloop_evt_set_sync(struct loop_ctx *loop, unsigned int evt, uint32_t evt_map) { BL_ASSERT_ERROR(evt < LOOP_TASK_MAX); loop->bitmap_evt_sync |= (1 << evt); loop->evt_type_map_async[evt] |= evt_map; } void bloop_evt_unset_sync(struct loop_ctx *loop, unsigned int evt) { BL_ASSERT_ERROR(evt < LOOP_TASK_MAX); loop->bitmap_evt_sync &= (~(1 << evt)); } static void _dump_task_handler(const struct loop_evt_handler *handler, struct loop_evt_handler_statistic *statistic, uint32_t bitmap_async, uint32_t bitmap_sync) { printf(" evt handler %p,", handler->evt); printf(" msg handler %p,", handler->handle); printf(" trigged cnt %u,", statistic->count_triggered); printf(" bitmap async %lx sync %lx,", bitmap_async, bitmap_sync); printf(" time consumed %dus acc %dms, max %uus\r\n", statistic->time_consumed, statistic->time_accumulated/1000, statistic->time_max ); } static void _dump_timer_dlist(utils_dlist_t *dlist) { struct loop_timer *node; unsigned int time_now; int count = 0; time_now = xTaskGetTickCount(); puts("--->>> timer list:\r\n"); utils_dlist_for_each_entry(dlist, node, struct loop_timer, dlist_item) { printf(" timer[%02d]: %u(diff %d)ms, \t\t task idx %02d, evt map %08lx, ptr %p\r\n", count, node->time_target, (int)time_now - (int)node->time_target, node->idx_task, node->evt_type_map, node->cb ); count++; } } int bloop_status_dump(struct loop_ctx *loop) { int i; puts("====== bloop dump ======\r\n"); printf(" bitmap_evt %lx\r\n", loop->bitmap_evt_sync); printf(" bitmap_msg %lx\r\n", loop->bitmap_msg); _dump_timer_dlist(&loop->timer_dlist); printf(" %d task:\r\n", sizeof(loop->list)/sizeof(loop->list[0])); for (i = sizeof(loop->list)/sizeof(loop->list[0]) - 1; i >= 0; i--) { printf(" task[%02d] : %s\r\n", i, loop->handlers[i] ? loop->handlers[i]->name : "empty" ); if (loop->handlers[i]) { _dump_task_handler( loop->handlers[i], &(loop->statistic[i]), loop->evt_type_map_async[i], loop->evt_type_map_sync[i] ); } } return 0; }
590634.c
/* ----------------------------------------------------------------------------- * Copyright (c) 2013-2014 ARM Limited. All rights reserved. * * $Date: 2. January 2014 * $Revision: V2.00 * * Project: MCI Driver API * -------------------------------------------------------------------------- */ /** \defgroup mci_interface_gr MCI Interface \brief Driver API for Memory Card Interface using SD/MMC interface (%Driver_MCI.h) \details The <b>Memory Card Interface</b> (MCI) implements the hardware abstraction layer for Secure Digital (SD) and Multi Media Card (MMC) memory that is typically used as file storage. For embedded systems, SD/MMC devices are available as memory cards in several forms (SD, miniSD, microSD, MMC, MMCmicro) or as non-removable devic es that are directly soldered to the PCB (eMMC). \b References: - Wikipedia offers more information about the <a href="http://en.wikipedia.org/wiki/SD_card" target="_blank"><b>Secure Digital</b> memory</a>. - Wikipedia offers more information about the <a href="http://en.wikipedia.org/wiki/MultiMediaCard" target="_blank"><b>MultiMediaCard</b></a>. - The SD Association provides detailed documentation under <a href="http://www.sdcard.org">www.sdcard.org</a>. - The MultiMediaCard Association (merged with JEDEC) provides detailed documentation under <a href="http://www.jedec.org">www.jedec.org</a>. **Block Diagram** The MCI driver allows you to exchange data of the SD/MMC memory via SD/MMC interface. The following modes are supported by SD/MMC memory cards: - SPI bus mode: Serial Peripheral Interface Bus supported by most microcontrollers. - 1-bit SD/MMC Bus mode: proprietary data transfer protocol supported by SD/MMC interfaces. - 4-bit SD/MMC Bus mode: high-speed version of the SD/MMC interface using 4 data I/O pins. - 8-bit SD/MMC Bus mode: high-speed version of the SD/MMC interface using 8 data I/O pins. \image html SPI_BusMode.png "SD memory connected via SPI interface" <p>&nbsp;</p> \image html SD_1BitBusMode.png "SD memory connected via 1-bit SD Bus Mode" <p>&nbsp;</p> \image html SD_4BitBusMode.png "SD memory connected via 4-bit SD Bus Mode" **MCI API** The following header files define the Application Programming Interface (API) for the MCI interface: - \b %Driver_MCI.h : Driver API for Memory Card Interface using SD/MMC interface The driver implementation is a typical part of the Device Family Pack (DFP) that supports the peripherals of the microcontroller family. \note For parameters, the value marked with (default) is the setting after the driver initialization. **Driver Functions** The driver functions are published in the access struct as explained in \ref DriverFunctions - \ref ARM_DRIVER_MCI : access struct for MCI driver functions @{ */ /* A typical setup sequence for the driver is shown below: <b>Example Code:</b> \todo example */ /************* Structures ******************************************************************************************************/ /** \struct ARM_DRIVER_MCI \details The functions of the MCI are accessed by function pointers exposed by this structure. Refer to \ref DriverFunctions for overview information. Each instance of an MCI provides such an access structure. The instance is identified by a postfix number in the symbol name of the access structure, for example: - \b Driver_MCI0 is the name of the access struct of the first instance (no. 0). - \b Driver_MCI1 is the name of the access struct of the second instance (no. 1). A configuration setting in the middleware allows connecting the middleware to a specific driver instance <b>Driver_MCI<i>n</i></b>. The default is \token{0}, which connects a middleware to the first instance of a driver. *******************************************************************************************************************/ /** \struct ARM_MCI_CAPABILITIES \details A MCI driver can be implemented with different capabilities. The data fields of this struct encode the capabilities implemented by this driver. <b>Returned by:</b> - \ref ARM_MCI_GetCapabilities *******************************************************************************************************************/ /** \defgroup mci_event_gr MCI Events \brief The MCI driver generates call back events that are notified via the function \ref ARM_MCI_SignalEvent. \details This section provides the event values for the \ref ARM_MCI_SignalEvent callback function. The following call back notification events are generated: @{ \def ARM_MCI_EVENT_CARD_INSERTED \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_CARD_REMOVED \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_COMMAND_COMPLETE \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_COMMAND_TIMEOUT \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_COMMAND_ERROR \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_TRANSFER_COMPLETE \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_TRANSFER_TIMEOUT \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_TRANSFER_ERROR \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_SDIO_INTERRUPT \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_CCS \sa \ref ARM_MCI_SignalEvent \def ARM_MCI_EVENT_CCS_TIMEOUT \sa \ref ARM_MCI_SignalEvent @} *******************************************************************************************************************/ //open mci_contorl_gr /** @{ */ /** \defgroup mci_control_gr MCI Control Codes \ingroup mci_interface_gr \brief Configure and control the MCI using the \ref ARM_MCI_Control. \details @{ Many parameters of the MCI driver are configured using the \ref ARM_MCI_Control function. The various MCI control codes define: - \ref mci_mode_ctrls configures and controls the MCI interface - \ref mci_bus_speed_ctrls specifies the bus speed mode - \ref mci_bus_data_width_ctrls specifies the data bus width - \ref mci_cmd_line_ctrls specifies the CMD line mode - \ref mci_driver_strength_ctrls specifies the driver strength Refer to the function \ref ARM_MCI_Control for further details. @} *******************************************************************************************************************/ /** \defgroup mci_mode_ctrls MCI Controls \ingroup mci_control_gr \brief Configure and control the MCI interface. \details The following codes are used as values for the parameter \em control of the function \ref ARM_MCI_Control to setup the MCI interface. @{ \def ARM_MCI_BUS_SPEED \def ARM_MCI_BUS_SPEED_MODE \def ARM_MCI_BUS_CMD_MODE \def ARM_MCI_BUS_DATA_WIDTH \def ARM_MCI_DRIVER_STRENGTH \def ARM_MCI_CONTROL_RESET \def ARM_MCI_CONTROL_CLOCK_IDLE \def ARM_MCI_UHS_TUNING_OPERATION \def ARM_MCI_UHS_TUNING_RESULT \def ARM_MCI_DATA_TIMEOUT \def ARM_MCI_CSS_TIMEOUT \def ARM_MCI_MONITOR_SDIO_INTERRUPT \def ARM_MCI_CONTROL_READ_WAIT \def ARM_MCI_SUSPEND_TRANSFER \def ARM_MCI_RESUME_TRANSFER @} *******************************************************************************************************************/ /** \defgroup mci_bus_speed_ctrls MCI Bus Speed Mode \ingroup mci_control_gr \brief Specify the bus speed mode. \details @{ The function \ref ARM_MCI_Control with \em control = \ref ARM_MCI_BUS_SPEED configures the bus speed of the MCI to the requested bits/s specified with \em arg. The function \ref ARM_MCI_Control with \em control = \ref ARM_MCI_BUS_SPEED_MODE configures the bus speed mode of the MCI as specified with \em arg listed bellow. The function \ref ARM_MCI_GetCapabilities lists the supported bus speed modes. Initially, all SD cards use a 3.3 volt electrical interface. Some SD cards can switch to 1.8 volt operation. For example, the use of ultra-high-speed (UHS) SD cards requires 1.8 volt operation and a 4-bit bus data width. The data field \em uhs_signaling of the structure ARM_MCI_CAPABILITIES encodes whether the driver supports 1.8 volt UHS signaling. \sa - \ref mci_driver_strength_ctrls The following codes are defined: \def ARM_MCI_BUS_DEFAULT_SPEED \def ARM_MCI_BUS_HIGH_SPEED \def ARM_MCI_BUS_UHS_SDR12 \def ARM_MCI_BUS_UHS_SDR25 \def ARM_MCI_BUS_UHS_SDR50 \def ARM_MCI_BUS_UHS_SDR104 \def ARM_MCI_BUS_UHS_DDR50 @} *******************************************************************************************************************/ /** \defgroup mci_bus_data_width_ctrls MCI Bus Data Width \ingroup mci_control_gr \brief Specify the data bus width. \details @{ The function \ref ARM_MCI_Control with \em control = \ref ARM_MCI_BUS_DATA_WIDTH specifies with \em arg the number of data I/O pins on the SD/MMC interface. For high-speed memory cards, a 4-bit bus data width should be used (or 8-bit for eMMC). The data fields \em data_width_4 and \em data_width_8 of the structure ARM_MCI_CAPABILITIES encode whether the driver supports a specific bus data with. The following codes are defined: \def ARM_MCI_BUS_DATA_WIDTH_1 \def ARM_MCI_BUS_DATA_WIDTH_4 \def ARM_MCI_BUS_DATA_WIDTH_8 \def ARM_MCI_BUS_DATA_WIDTH_4_DDR \def ARM_MCI_BUS_DATA_WIDTH_8_DDR @} *******************************************************************************************************************/ /** \defgroup mci_cmd_line_ctrls MCI CMD Line Mode \ingroup mci_control_gr \brief Specify the CMD line mode (Push-Pull or Open Drain). \details @{ Set the CMD line type with the function \ref ARM_MCI_Control. The CMD line mode is push-pull (default) or open drain (needed for older MMC). \def ARM_MCI_BUS_CMD_PUSH_PULL \def ARM_MCI_BUS_CMD_OPEN_DRAIN @} *******************************************************************************************************************/ /** \defgroup mci_driver_strength_ctrls MCI Driver Strength \ingroup mci_control_gr \brief Specify the driver strength. \details @{ The function \ref ARM_MCI_Control with \em control = \ref ARM_MCI_DRIVER_STRENGTH specifies with \em arg the driver type of the SD interface. \sa - \ref mci_bus_speed_ctrls The following codes are defined: \def ARM_MCI_DRIVER_TYPE_A \def ARM_MCI_DRIVER_TYPE_B \def ARM_MCI_DRIVER_TYPE_C \def ARM_MCI_DRIVER_TYPE_D @} *******************************************************************************************************************/ /** @} */ // close group mci_control_gr /** \defgroup mci_send_command_flags_ctrls MCI Send Command Flags \ingroup mci_interface_gr \brief Specify various options for sending commands to the card and the expected response. \details \b ARM_MCI_xxx flags are sent with the function \ref ARM_MCI_SendCommand as the parameter \em flag. It controls the behavior of the command sent to the card and provides information about the expected response from the card. The following codes are defined: @{ \def ARM_MCI_RESPONSE_NONE \def ARM_MCI_RESPONSE_SHORT \def ARM_MCI_RESPONSE_SHORT_BUSY \def ARM_MCI_RESPONSE_LONG \def ARM_MCI_RESPONSE_INDEX \def ARM_MCI_RESPONSE_CRC \def ARM_MCI_WAIT_BUSY \def ARM_MCI_TRANSFER_DATA \def ARM_MCI_CARD_INITIALIZE \def ARM_MCI_INTERRUPT_COMMAND \def ARM_MCI_INTERRUPT_RESPONSE \def ARM_MCI_BOOT_OPERATION \def ARM_MCI_BOOT_ALTERNATIVE \def ARM_MCI_BOOT_ACK \def ARM_MCI_CCSD \def ARM_MCI_CCS @} *******************************************************************************************************************/ /** \defgroup mci_transfer_ctrls MCI Transfer Controls \ingroup mci_interface_gr \brief Specify data transfer mode. \details Data transfer codes specifies the transfer direction and type and are used with the function \ref ARM_MCI_SetupTransfer as the parameter \em mode. The following codes are defined: @{ \def ARM_MCI_TRANSFER_READ \def ARM_MCI_TRANSFER_WRITE \def ARM_MCI_TRANSFER_BLOCK \def ARM_MCI_TRANSFER_STREAM @} *******************************************************************************************************************/ /** \defgroup mci_card_power_ctrls MCI Card Power Controls \ingroup mci_interface_gr \brief Specify Memory Card Power supply voltage \details Specifies the power supply volatge for a memory card. Used with the function \ref ARM_MCI_CardPower as the parameter \em voltage. The following codes are defined: @{ \def ARM_MCI_POWER_VDD_OFF \def ARM_MCI_POWER_VDD_3V3 \def ARM_MCI_POWER_VDD_1V8 \def ARM_MCI_POWER_VCCQ_OFF \def ARM_MCI_POWER_VCCQ_3V3 \def ARM_MCI_POWER_VCCQ_1V8 \def ARM_MCI_POWER_VCCQ_1V2 @} *******************************************************************************************************************/ /** \struct ARM_MCI_STATUS \details Structure with information about the status of the MCI. <b>Returned by:</b> - \ref ARM_MCI_GetStatus *******************************************************************************************************************/ /** \typedef ARM_MCI_SignalEvent_t \details Provides the typedef for the callback function \ref ARM_MCI_SignalEvent. <b>Parameter for:</b> - \ref ARM_MCI_Initialize *******************************************************************************************************************/ // // Functions // ARM_DRIVER_VERSION ARM_MCI_GetVersion (void) { return { 0, 0 }; } /** \fn ARM_DRIVER_VERSION ARM_MCI_GetVersion (void) \details The function \b ARM_MCI_GetVersion returns version information of the driver implementation in \ref ARM_DRIVER_VERSION - API version is the version of the CMSIS-Driver specification used to implement this driver. - Driver version is source code version of the actual driver implementation. Example: \code extern ARM_DRIVER_MCI Driver_MCI0; ARM_DRIVER_MCI *drv_info; void setup_mci (void) { ARM_DRIVER_VERSION version; drv_info = &Driver_MCI0; version = drv_info->GetVersion (); if (version.api < 0x10A) { // requires at minimum API version 1.10 or higher // error handling return; } } \endcode *******************************************************************************************************************/ ARM_MCI_CAPABILITIES ARM_MCI_GetCapabilities (void) { return { 0 }; } /** \fn ARM_MCI_CAPABILITIES ARM_MCI_GetCapabilities (void) \details The function \b ARM_MCI_GetCapabilities returns information about capabilities in this driver implementation. The data fields of the structure \ref ARM_MCI_CAPABILITIES encode various capabilities, for example supported bus modes ... Example: \code extern ARM_DRIVER_MCI Driver_MCI0; ARM_DRIVER_MCI *drv_info; void read_capabilities (void) { ARM_MCI_CAPABILITIES drv_capabilities; drv_info = &Driver_MCI0; drv_capabilities = drv_info->GetCapabilities (); // interrogate capabilities } \endcode *******************************************************************************************************************/ int32_t ARM_MCI_Initialize (ARM_MCI_SignalEvent_t cb_event) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_Initialize (ARM_MCI_SignalEvent_t cb_event) \details The function \b ARM_MCI_Initialize initializes the MCI interface. It is called when the middleware component starts operation. The function performs the following operations: - Initializes the resources needed for the MCI interface. - Registers the \ref ARM_MCI_SignalEvent callback function. The parameter \em cb_event is a pointer to the \ref ARM_MCI_SignalEvent callback function; use a NULL pointer when no callback signals are required. \b Example: - see \ref mci_interface_gr - Driver Functions *******************************************************************************************************************/ int32_t ARM_MCI_Uninitialize (void) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_Uninitialize (void) \details The function \b ARM_MCI_Uninitialize de-initializes the resources of I2C interface. It is called when the middleware component stops operation and releases the software resources used by the interface. *******************************************************************************************************************/ int32_t ARM_MCI_PowerControl (ARM_POWER_STATE state) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_PowerControl (ARM_POWER_STATE state) \details The function \b ARM_MCI_PowerControl operates the power modes of the MCI interface. The parameter \em state can have the following values: - \ref ARM_POWER_FULL : set-up peripheral for data transfers, enable interrupts (NVIC) and optionally DMA. Can be called multiple times. If the peripheral is already in this mode, then the function performs no operation and returns with \ref ARM_DRIVER_OK. - \ref ARM_POWER_LOW : may use power saving. Returns \ref ARM_DRIVER_ERROR_UNSUPPORTED when not implemented. - \ref ARM_POWER_OFF : terminates any pending data transfers, disables peripheral, disables related interrupts and DMA. Refer to \ref CallSequence for more information. *******************************************************************************************************************/ int32_t ARM_MCI_CardPower (uint32_t voltage) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_CardPower (uint32_t voltage) \details The function \b ARM_MCI_CardPower operates the memory card power supply voltage. The parameter \em voltage sets the voltage. Not every voltage might be supported by the driver implementation. The structure \ref ARM_MCI_CAPABILITIES encodes the supported voltage. Retrieve the information with the function \ref ARM_MCI_GetCapabilities and verify the data fields. The following values: Parameter \em voltage | Description | supported when ARM_MCI_CAPABILITIES :-------------------------------------|:------------------------------|----------------------------------------- \ref ARM_MCI_POWER_VDD_OFF | VDD (VCC) turned off | <i>allways supported</i> \ref ARM_MCI_POWER_VDD_3V3 | VDD (VCC) = \token{3.3V} | data field \em vdd = \token{1} \ref ARM_MCI_POWER_VDD_1V8 | VDD (VCC) = \token{1.8V} | data field \em vdd_1v8 = \token{1} \ref ARM_MCI_POWER_VCCQ_OFF | eMMC VCCQ turned off | <i>allways supported</i> \ref ARM_MCI_POWER_VCCQ_3V3 | eMMC VCCQ = \token{3.3V} | data field \em vccq = \token{1} \ref ARM_MCI_POWER_VCCQ_1V8 | eMMC VCCQ = \token{1.8V} | data field \em vccq_1v8 = \token{1} \ref ARM_MCI_POWER_VCCQ_1V2 | eMMC VCCQ = \token{1.2V} | data field \em vccq_1v2 = \token{1} *******************************************************************************************************************/ int32_t ARM_MCI_ReadCD (void) { return 0; } /** \fn int32_t ARM_MCI_ReadCD (void) \details The function \b ARM_MCI_ReadCD reads the status of the Card Detect (CD) pin. *******************************************************************************************************************/ int32_t ARM_MCI_ReadWP (void) { return 0; } /** \fn int32_t ARM_MCI_ReadWP (void) \details The function \b ARM_MCI_ReadWP reads the status of the Write Protect (WP) pin. *******************************************************************************************************************/ int32_t ARM_MCI_SendCommand (uint32_t cmd, uint32_t arg, uint32_t flags, uint32_t *response) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_SendCommand (uint32_t cmd, uint32_t arg, uint32_t flags, uint32_t *response) \details The function \b ARM_MCI_SendCommand - sends commands to the memory card - retrieve the response from the card - optionally, start the data transfer. The parameter \em cmd is the command sent to the card. \n The parameter \em arg contains arguments for the command \em cmd. \n The parameter \em flags controls the behavior of the operation and takes predefined values listed in the table below. \n The parameter \em response is a pointer to receive data. The parameter \em flags can have the following values: Parameter \em flags | Description :-------------------------------------|:------------ \ref ARM_MCI_RESPONSE_NONE | No response expected (default) \ref ARM_MCI_RESPONSE_SHORT | Short response (\token{48}-bit) expected \ref ARM_MCI_RESPONSE_SHORT_BUSY | Short response with busy signal (\token{48}-bit) expected \ref ARM_MCI_RESPONSE_LONG | Long response (\token{136}-bit) expected \ref ARM_MCI_RESPONSE_INDEX | Check command index in response \ref ARM_MCI_RESPONSE_CRC | Check CRC in response \ref ARM_MCI_WAIT_BUSY | Wait until busy before sending the command \ref ARM_MCI_TRANSFER_DATA | Activate Data transfer \ref ARM_MCI_CARD_INITIALIZE | Execute Memory Card initialization sequence \ref ARM_MCI_INTERRUPT_COMMAND | Send Interrupt command (CMD40 - MMC only) \ref ARM_MCI_INTERRUPT_RESPONSE | Send Interrupt response (CMD40 - MMC only) \ref ARM_MCI_BOOT_OPERATION | Execute Boot operation (MMC only) \ref ARM_MCI_BOOT_ALTERNATIVE | Execute Alternative Boot operation (MMC only) \ref ARM_MCI_BOOT_ACK | Expect Boot Acknowledge (MMC only) \ref ARM_MCI_CCSD | Send Command Completion Signal Disable (CCSD) for CE-ATA device \ref ARM_MCI_CCS | Expect Command Completion Signal (CCS) for CE-ATA device Calling the function <b>ARM_MCI_SendCommand</b> only starts the operation. The function is non-blocking and returns as soon as the driver has started the operation. It is not allowed to call this function again until the operation is in progress. After the command is sent the response is retrieved if specified with <b>ARM_MCI_RESPONSE_xxx</b> flags. When the command completes successfully (requested response is received without errors) the \ref ARM_MCI_EVENT_COMMAND_COMPLETE event is generated. In case that response is requested but not received the \ref ARM_MCI_EVENT_COMMAND_TIMEOUT event is generated instead. In case of invalid response (or CRC error) the \ref ARM_MCI_EVENT_COMMAND_ERROR event is generated instead. Progress of command operation can be monitored by calling the \ref ARM_MCI_GetStatus and checking the \em command_active flag. After the command operation the data transfer operation is started if specified with <b>ARM_MCI_TRANSFER_DATA</b> flag. The data transfer needs to be configured before that by calling the \ref ARM_MCI_SetupTransfer. When the data transfer completes successfully the \ref ARM_MCI_EVENT_TRANSFER_COMPLETE event is generated. In case that data transfer is not completed in-time (specified by \ref ARM_MCI_DATA_TIMEOUT) the \ref ARM_MCI_EVENT_TRANSFER_TIMEOUT event is generated instead. In case of CRC errors the \ref ARM_MCI_EVENT_TRANSFER_ERROR event is generated instead. Progress of data transfer operation can be monitored by calling the \ref ARM_MCI_GetStatus and checking the \em transfer_active flag. <b>See also:</b> - \ref ARM_MCI_SignalEvent *******************************************************************************************************************/ int32_t ARM_MCI_SetupTransfer (uint8_t *data, uint32_t block_count, uint32_t block_size, uint32_t mode) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_SetupTransfer (uint8_t *data, uint32_t block_count, uint32_t block_size, uint32_t mode) \details The function \b ARM_MCI_SetupTransfer prepares the data transfer operation that is initiated by calling the function \ref ARM_MCI_SendCommand with the parameter \em flags = \ref ARM_MCI_TRANSFER_DATA. The parameter \em data is a pointer to the data to transfer. \n The parameter \em block_count is the number of blocks to transfer. \n The parameter \em block_size is the size of a block. \n The parameter \em mode sets the transfer mode and can have the values liste in the table below: Transfer Directions | Description :-------------------------------------|:------------ \ref ARM_MCI_TRANSFER_READ | Read data from MCI \ref ARM_MCI_TRANSFER_WRITE | Write data to MCI \ref ARM_MCI_TRANSFER_BLOCK (default) | Block Data transfer \ref ARM_MCI_TRANSFER_STREAM | Stream Data transfer (MMC only) *******************************************************************************************************************/ int32_t ARM_MCI_AbortTransfer (void) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_AbortTransfer (void) \details The function \b ARM_MCI_AbortTransfer aborts the active data transfer operation initiated with \ref ARM_MCI_SendCommand. *******************************************************************************************************************/ int32_t ARM_MCI_Control (uint32_t control, uint32_t arg) { return ARM_DRIVER_OK; } /** \fn int32_t ARM_MCI_Control (uint32_t control, uint32_t arg) \details Th function \b ARM_MCI_Control controls the MCI interface and executes various operations. The parameter \em control specifies the operation. Values for \em control cannot be ORed, but must be called separately in the code. \n The parameter \em arg provides, depending on the operation, additional information or sets values. \note For parameters, the values marked with (default) are the setting after the driver initialization. The table lists values for the parameter \em control. Parameter \em control | Operation :-------------------------------------|:------------ \ref ARM_MCI_BUS_SPEED | Set the Bus Speed. The parameter \em arg specifies the speed in bits/s; The function returns the bus speed configured in bits/s. \ref ARM_MCI_BUS_SPEED_MODE | Set the Bus Speed Mode. Predefined values for \em arg are listed in the table <b>Bus Speed Mode</b>. \ref ARM_MCI_BUS_CMD_MODE | Set the CMD Line Mode. Predefined values for \em arg are listed in the table <b>Bus CMD Line Mode</b>. \ref ARM_MCI_BUS_DATA_WIDTH | Set data bus width. Predefined values for \em arg are encoded in <b>Bus Data Width</b>. \ref ARM_MCI_DRIVER_STRENGTH | Set driver strength. Predefined values for \em arg are listed in the table <b>Driver Type</b> \ref ARM_MCI_CONTROL_RESET | Control optional RST_n Pin (eMMC). The parameter \em arg can have the values \token{[0:inactive(default); 1:active]} \ref ARM_MCI_CONTROL_CLOCK_IDLE | Control clock generation on CLK Pin when idle. The parameter \em arg can have the values \token{[0:disabled; 1:enabled]} \ref ARM_MCI_UHS_TUNING_OPERATION | Sampling clock Tuning operation (SD UHS-I). The parameter \em arg can have the values \token{[0:reset; 1:execute]} \ref ARM_MCI_UHS_TUNING_RESULT | Sampling clock Tuning result (SD UHS-I). Returns \token{[0:done; 1:in progress; -1:error]} \ref ARM_MCI_DATA_TIMEOUT | Set Data timeout; The parameter \em arg sets the timeout in bus cycles. \ref ARM_MCI_CSS_TIMEOUT | Set Command Completion Signal (CCS) timeout. The parameter \em arg sets timeout in bus cycles. \ref ARM_MCI_MONITOR_SDIO_INTERRUPT | Monitor SD I/O interrupt. The parameter \em arg can have the values \token{[0:disabled(default); 1:enabled]}. Monitoring is automatically disabled when an interrupt is recognized. \ref ARM_MCI_CONTROL_READ_WAIT | Control Read/Wait states for SD I/O. The parameter \em arg can have the values \token{[0:disabled(default); 1:enabled]}. \ref ARM_MCI_SUSPEND_TRANSFER | Suspend Data transfer (SD I/O). Returns the number of remaining bytes to transfer. \ref ARM_MCI_RESUME_TRANSFER | Resume Data transfer (SD I/O). <b>Bus Speed Mode</b> The function \ref ARM_MCI_GetCapabilities lists the supported bus speed modes. Initially, all SD cards use a 3.3 volt electrical interface. Some SD cards can switch to 1.8 volt operation. For example, the use of ultra-high-speed (UHS) SD cards requires 1.8 volt operation and a 4-bit bus data width. The bit field ARM_MCI_CAPABILITIES.uhs_signaling encodes whether the driver supports 1.8 volt UHS signaling. The \em control operation \b ARM_MCI_BUS_SPEED_MODE sets the bus speed mode using the parameter \em arg. Parameter \em arg | Bus Speed Mode :-------------------------------------------------------------|:------------------------------------------ \ref ARM_MCI_BUS_DEFAULT_SPEED (default) | Set the bus speed for SD/MMC cards: Default Speed mode up to \token{[25;26]MHz} \ref ARM_MCI_BUS_HIGH_SPEED | Set the bus speed for SD/MMC: High Speed mode up to \token{[50;52]MHz} \ref ARM_MCI_BUS_UHS_SDR12 | Set the bus speed for SD: SDR12 (Single Data Rate) up to \token{25MHz, 12.5MB/s: UHS-I (Ultra High Speed) 1.8V signalling} \ref ARM_MCI_BUS_UHS_SDR25 | Set the bus speed for SD: SDR25 (Single Data Rate) up to \token{50MHz, 25 MB/s: UHS-I (Ultra High Speed) 1.8V signalling} \ref ARM_MCI_BUS_UHS_SDR50 | Set the bus speed for SD: SDR50 (Single Data Rate) up to \token{100MHz, 50 MB/s: UHS-I (Ultra High Speed) 1.8V signalling} \ref ARM_MCI_BUS_UHS_SDR104 | Set the bus speed for SD: SDR104 (Single Data Rate) up to \token{208MHz, 104 MB/s: UHS-I (Ultra High Speed) 1.8V signalling} \ref ARM_MCI_BUS_UHS_DDR50 | Set the bus speed for SD: DDR50 (Dual Data Rate) up to \token{50MHz, 50 MB/s: UHS-I (Ultra High Speed) 1.8V signalling} <b>Bus CMD Line Mode</b> The \em control operation \b ARM_MCI_BUS_CMD_MODE sets the bus command line mode using the parameter \em arg. Parameter \em arg | Bus CMD Line Mode :-------------------------------------------------------------|:------------------------------------------ \ref ARM_MCI_BUS_CMD_PUSH_PULL (default) | Set the Push-Pull CMD line \ref ARM_MCI_BUS_CMD_OPEN_DRAIN | Set the Open Drain CMD line (MMC only) <b>Bus Data Width</b> Specifies the bus data width (the number of data I/O pins on the SD/MMC interface). For high speed memory cards, a 4-bit bus data width should be used (or 8-bit for eMMC). The bit fields ARM_MCI_CAPABILITIES.data_width_4 and ARM_MCI_CAPABILITIES.data_width_8 encode whether the driver supports a specific bus data with. The \em control operation \b ARM_MCI_BUS_DATA_WIDTH sets the bus data width using the parameter \em arg. Parameter \em arg | Bus Data Width :-------------------------------------------------------------|:------------------------------------------ \ref ARM_MCI_BUS_DATA_WIDTH_1 (default) | Set the Bus data width to \token{1 bit} \ref ARM_MCI_BUS_DATA_WIDTH_4 | Set the Bus data width to \token{4 bits} \ref ARM_MCI_BUS_DATA_WIDTH_8 | Set the Bus data width to \token{8 bits} \ref ARM_MCI_BUS_DATA_WIDTH_4_DDR | Set the Bus data width to \token{4 bits}, DDR (Dual Data Rate) - MMC only \ref ARM_MCI_BUS_DATA_WIDTH_8_DDR | Set the Bus data width to \token{8 bits}, DDR (Dual Data Rate) - MMC only <b>Driver Type</b> Specifies the interface driver type. The \em control operation \b ARM_MCI_DRIVER_STRENGTH sets the interface driver type using the parameter \em arg. Parameter \em arg | Driver Type :-------------------------------------------------------------|:------------------------------------------ \ref ARM_MCI_DRIVER_TYPE_A | Set the interface to SD UHS-I Driver Type A \ref ARM_MCI_DRIVER_TYPE_B (default) | Set the interface to SD UHS-I Driver Type B \ref ARM_MCI_DRIVER_TYPE_C | Set the interface to SD UHS-I Driver Type C \ref ARM_MCI_DRIVER_TYPE_D | Set the interface to SD UHS-I Driver Type D \b Examples: \code // Set Bus Speed to 25MHz MCIdrv->Control(ARM_MCI_BUS_SPEED, 25000000); // Set High Speed mode MCIdrv->Control(ARM_MCI_BUS_SPEED_MODE, ARM_MCI_BUS_HIGH_SPEED); // Configure CMD line as Open Drain (MMC only) MCIdrv->Control(ARM_MCI_BUS_CMD_MODE, ARM_MCI_BUS_CMD_OPEN_DRAIN); // Set Bus Data Width = 4bits MCIdrv->Control(ARM_MCI_BUS_DATA_WIDTH, ARM_MCI_BUS_DATA_WIDTH_4); // Set SD UHS-I Driver Type B MCIdrv->Control(ARM_MCI_DRIVER_STRENGTH, ARM_MCI_DRIVER_TYPE_B); // RTS_n Pin is not active by default // Assert RTS_n Pin (eMMC) MCIdrv->Control(ARM_MCI_CONTROL_RESET, 1); // De-assert RTS_n Pin (eMMC) MCIdrv->Control(ARM_MCI_CONTROL_RESET, 0); // Clock generation on CLK when Idle: hardware specific default behavior // Enable Clock generation on CLK when Idle MCIdrv->Control(ARM_MCI_CONTROL_CLOCK_IDLE, 1); // Disable Clock generation on CLK when Idle MCIdrv->Control(ARM_MCI_CONTROL_CLOCK_IDLE, 0); // UHS Tuning MCIdrv->Control(ARM_MCI_UHS_TUNING_OPERATION, 1); // start tuning do { status = MCIdrv->Control(ARM_MCI_UHS_TUNING_RESULT, 0/*argument not used*/); if (status == -1) { break; /* tuning failed */ } } while (status == 1); // Set Data Timeout to 12500000 bus cycles (0.5s @25MHz Bus Speed) // Default value is hardware specific (typically 2^32-1) MCIdrv->Control(ARM_MCI_DATA_TIMEOUT, 12500000); // Set CSS Timeout to 1000000 bus cycles // Default value is hardware specific MCIdrv->Control(ARM_MCI_CSS_TIMEOUT, 1000000); // SD I/O Interrupt Monitoring is disabled by default // Enable SD I/O Interrupt Monitoring MCIdrv->Control(ARM_MCI_MONITOR_SDIO_INTERRUPT, 1); // Disable SD I/O Interrupt Monitoring MCIdrv->Control(ARM_MCI_MONITOR_SDIO_INTERRUPT, 0); // Read/Wait for SD I/O is disabled by default // Enable Read/Wait for SD I/O MCIdrv->Control(ARM_MCI_CONTROL_READ_WAIT, 1); // Disable Read/Wait for SD I/O MCIdrv->Control(ARM_MCI_CONTROL_READ_WAIT, 0); // Suspend Data transfer (SD I/O) MCIdrv->Control(ARM_MCI_SUSPEND_TRANSFER, 0/*argument not used*/); // Resume Data transfer (SD I/O) MCIdrv->Control(ARM_MCI_RESUME_TRANSFER, 0/*argument not used*/); \endcode *******************************************************************************************************************/ ARM_MCI_STATUS ARM_MCI_GetStatus (void) { return ARM_DRIVER_OK; } /** \fn ARM_MCI_STATUS ARM_MCI_GetStatus (void) \details The function \b ARM_MCI_GetStatus returns the current MCI interface status. *******************************************************************************************************************/ void ARM_MCI_SignalEvent (uint32_t event) { // function body } /** \fn void ARM_MCI_SignalEvent (uint32_t event) \details The function \b ARM_MCI_SignalEvent is a callback function registered by the function \ref ARM_MCI_Initialize. The parameter \em event indicates one or more events that occurred during driver operation. Each event is encoded in a separate bit and therefore it is possible to signal multiple events within the same call. Not every event is necessarily generated by the driver. This depends on the implemented capabilities stored in the data fields of the structure \ref ARM_NAND_CAPABILITIES, which can be retrieved with the function \ref ARM_NAND_GetCapabilities. The following events can be generated: Parameter \em event |Bit | Description | supported when \ref ARM_NAND_CAPABILITIES :------------------------------------------|---:|:----------------------------------------------------------------------|:--------------------------------------------- \ref ARM_MCI_EVENT_CARD_INSERTED | 0 | Occurs after Memory Card inserted | <i>always supported</i> \ref ARM_MCI_EVENT_CARD_REMOVED | 1 | Occurs after Memory Card removal | <i>always supported</i> \ref ARM_MCI_EVENT_COMMAND_COMPLETE | 2 | Occurs after command completed successfully | <i>always supported</i> \ref ARM_MCI_EVENT_COMMAND_TIMEOUT | 3 | Occurs after command timeout | <i>always supported</i> \ref ARM_MCI_EVENT_COMMAND_ERROR | 4 | Occurs after command response error (CRC error or invalid response) | <i>always supported</i> \ref ARM_MCI_EVENT_TRANSFER_COMPLETE | 5 | Occurs after data transfer completed successfully | <i>always supported</i> \ref ARM_MCI_EVENT_TRANSFER_TIMEOUT | 6 | Occurs after data transfer timeout | <i>always supported</i> \ref ARM_MCI_EVENT_TRANSFER_ERROR | 7 | Occurs after data transfer error (CRC failed) | <i>always supported</i> \ref ARM_MCI_EVENT_SDIO_INTERRUPT | 8 | Indicates SD I/O Interrupt | data field \em sdio_interrupt = \token{1} \ref ARM_MCI_EVENT_CCS | 9 | Indicates a Command Completion Signal (CCS) | data field \em ccs = \token{1} \ref ARM_MCI_EVENT_CCS_TIMEOUT |10 | Indicates a Command Completion Signal (CCS) Timeout | data field \em css_timeout = \token{1} <b>See also:</b> - \ref ARM_MCI_SendCommand *******************************************************************************************************************/ /** @} */ // End MCI Interface
696917.c
#include "stdio.h" #include "phli.h" char* fnAttributeValue(char*,char*); int main(int argc, char* argv[]) { char *result_dir="/data/phli/results/fnAttributeValue/"; char* arg_0=phli_create_char_array("arg_0"); char* arg_1=phli_create_char_array("arg_1"); char* result; result=fnAttributeValue(arg_0,arg_1); }
639155.c
/* * Carsten Langgaard, [email protected] * Copyright (C) 1999,2000 MIPS Technologies, Inc. All rights reserved. * * This program is free software; you can distribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. * * Routines for generic manipulation of the interrupts found on the * Lasat boards. */ #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <asm/bootinfo.h> #include <asm/irq.h> #include <asm/lasat/lasatint.h> #include <asm/gdb-stub.h> static volatile int *lasat_int_status = NULL; static volatile int *lasat_int_mask = NULL; static volatile int lasat_int_mask_shift; extern asmlinkage void lasatIRQ(void); void disable_lasat_irq(unsigned int irq_nr) { unsigned long flags; local_irq_save(flags); *lasat_int_mask &= ~(1 << irq_nr) << lasat_int_mask_shift; local_irq_restore(flags); } void enable_lasat_irq(unsigned int irq_nr) { unsigned long flags; local_irq_save(flags); *lasat_int_mask |= (1 << irq_nr) << lasat_int_mask_shift; local_irq_restore(flags); } static unsigned int startup_lasat_irq(unsigned int irq) { enable_lasat_irq(irq); return 0; /* never anything pending */ } #define shutdown_lasat_irq disable_lasat_irq #define mask_and_ack_lasat_irq disable_lasat_irq static void end_lasat_irq(unsigned int irq) { if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS))) enable_lasat_irq(irq); } static struct hw_interrupt_type lasat_irq_type = { .typename = "Lasat", .startup = startup_lasat_irq, .shutdown = shutdown_lasat_irq, .enable = enable_lasat_irq, .disable = disable_lasat_irq, .ack = mask_and_ack_lasat_irq, .end = end_lasat_irq, }; static inline int ls1bit32(unsigned int x) { int b = 31, s; s = 16; if (x << 16 == 0) s = 0; b -= s; x <<= s; s = 8; if (x << 8 == 0) s = 0; b -= s; x <<= s; s = 4; if (x << 4 == 0) s = 0; b -= s; x <<= s; s = 2; if (x << 2 == 0) s = 0; b -= s; x <<= s; s = 1; if (x << 1 == 0) s = 0; b -= s; return b; } static unsigned long (* get_int_status)(void); static unsigned long get_int_status_100(void) { return *lasat_int_status & *lasat_int_mask; } static unsigned long get_int_status_200(void) { unsigned long int_status; int_status = *lasat_int_status; int_status &= (int_status >> LASATINT_MASK_SHIFT_200) & 0xffff; return int_status; } void lasat_hw0_irqdispatch(struct pt_regs *regs) { unsigned long int_status; int irq; int_status = get_int_status(); /* if int_status == 0, then the interrupt has already been cleared */ if (int_status) { irq = ls1bit32(int_status); do_IRQ(irq, regs); } } void __init arch_init_irq(void) { int i; switch (mips_machtype) { case MACH_LASAT_100: lasat_int_status = (void *)LASAT_INT_STATUS_REG_100; lasat_int_mask = (void *)LASAT_INT_MASK_REG_100; lasat_int_mask_shift = LASATINT_MASK_SHIFT_100; get_int_status = get_int_status_100; *lasat_int_mask = 0; break; case MACH_LASAT_200: lasat_int_status = (void *)LASAT_INT_STATUS_REG_200; lasat_int_mask = (void *)LASAT_INT_MASK_REG_200; lasat_int_mask_shift = LASATINT_MASK_SHIFT_200; get_int_status = get_int_status_200; *lasat_int_mask &= 0xffff; break; default: panic("arch_init_irq: mips_machtype incorrect"); } /* Now safe to set the exception vector. */ set_except_vector(0, lasatIRQ); for (i = 0; i <= LASATINT_END; i++) { irq_desc[i].status = IRQ_DISABLED; irq_desc[i].action = 0; irq_desc[i].depth = 1; irq_desc[i].handler = &lasat_irq_type; } }
111118.c
/* * $Id: commands.c,v 1.12 2008-07-27 03:18:38 haley Exp $ */ /************************************************************************ * * * Copyright (C) 2000 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * * The use of this Software is governed by a License Agreement. * * * ************************************************************************/ /* * commands.c * * Author John Clyne * * Date Thu Sep 13 12:48:22 MDT 1990 * * This module is resonpsible for providing generating a syntatically * correct ictrans command and sending it to the appropriate translator. */ #include <stdio.h> #include <sys/types.h> #include <signal.h> #include <string.h> #include "display.h" #include "commands.h" #include "talkto.h" /* * Command * [exported] * * Format a command string and send it to the translator. The $format * arg contains one or more newline-separated translator commands and * possibly a single %s format specifier. * * * * on entry * id : communication channel * *format : a printf-style formating string containing the * actual command string to be sent to the translator. * If $format contains a '%s' the string referenced by * $command_data will be substitued for '%s'. * * * *command_data : data to send with the command */ void Command(id, format, command_data) int id; char *format; char *command_data; /* possibly NULL */ { char buf[1024]; /* formatted command string(s) */ char cmd_buf[1024]; /* a single translator command string */ char *s; sprintf(buf, format, command_data); /* * break the string of possibly multiple translator commands into * multiple strings of single commands */ s = strtok(buf, "\n"); if (s) { sprintf(cmd_buf, "%s\n", s); (void) TalkTo(id, cmd_buf, ASYNC); } for (s=strtok(NULL, "\n"); s; s=strtok(NULL, "\n")) { sprintf(cmd_buf, "%s\n", s); (void) TalkTo(id, cmd_buf, ASYNC); } }
479307.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M AAA GGGG IIIII CCCC K K % % MM MM A A G I C K K % % M M M AAAAA G GGG I C KKK % % M M A A G G I C K K % % M M A A GGGG IIIII CCCC K K % % % % PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y % % P P R R O O P P E R R T Y Y % % PPPP RRRR O O PPPP EEE RRRR T Y % % P R R O O P E R R T Y % % P R R OOO P EEEEE R R T Y % % % % % % Set or Get MagickWand Properties, Options, or Profiles % % % % Software Design % % John Cristy % % August 2003 % % % % % % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "wand/studio.h" #include "wand/MagickWand.h" #include "wand/magick-wand-private.h" #include "wand/wand.h" #include "magick/string-private.h" /* Define declarations. */ #define ThrowWandException(severity,tag,context) \ { \ (void) ThrowMagickException(wand->exception,GetMagickModule(),severity, \ tag,"`%s'",context); \ return(MagickFalse); \ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k D e l e t e I m a g e A r t i f a c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickDeleteImageArtifact() deletes a wand artifact. % % The format of the MagickDeleteImageArtifact method is: % % MagickBooleanType MagickDeleteImageArtifact(MagickWand *wand, % const char *artifact) % % A description of each parameter follows: % % o image: the image. % % o artifact: the image artifact. % */ WandExport MagickBooleanType MagickDeleteImageArtifact(MagickWand *wand, const char *artifact) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return(MagickFalse); } return(DeleteImageArtifact(wand->images,artifact)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k D e l e t e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickDeleteImageProperty() deletes a wand property. % % The format of the MagickDeleteImageProperty method is: % % MagickBooleanType MagickDeleteImageProperty(MagickWand *wand, % const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ WandExport MagickBooleanType MagickDeleteImageProperty(MagickWand *wand, const char *property) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return(MagickFalse); } return(DeleteImageProperty(wand->images,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k D e l e t e O p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickDeleteOption() deletes a wand option. % % The format of the MagickDeleteOption method is: % % MagickBooleanType MagickDeleteOption(MagickWand *wand, % const char *option) % % A description of each parameter follows: % % o image: the image. % % o option: the image option. % */ WandExport MagickBooleanType MagickDeleteOption(MagickWand *wand, const char *option) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(DeleteImageOption(wand->image_info,option)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t A n t i a l i a s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetAntialias() returns the antialias property associated with the % wand. % % The format of the MagickGetAntialias method is: % % MagickBooleanType MagickGetAntialias(const MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickBooleanType MagickGetAntialias(const MagickWand *wand) { assert(wand != (const MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->antialias); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetBackgroundColor() returns the wand background color. % % The format of the MagickGetBackgroundColor method is: % % PixelWand *MagickGetBackgroundColor(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport PixelWand *MagickGetBackgroundColor(MagickWand *wand) { PixelWand *background_color; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); background_color=NewPixelWand(); PixelSetQuantumColor(background_color,&wand->image_info->background_color); return(background_color); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetColorspace() gets the wand colorspace type. % % The format of the MagickGetColorspace method is: % % ColorspaceType MagickGetColorspace(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport ColorspaceType MagickGetColorspace(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t C o m p r e s s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetCompression() gets the wand compression type. % % The format of the MagickGetCompression method is: % % CompressionType MagickGetCompression(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport CompressionType MagickGetCompression(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->compression); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t C o m p r e s s i o n Q u a l i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetCompressionQuality() gets the wand compression quality. % % The format of the MagickGetCompressionQuality method is: % % size_t MagickGetCompressionQuality(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport size_t MagickGetCompressionQuality(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->quality); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t C o p y r i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetCopyright() returns the ImageMagick API copyright as a string % constant. % % The format of the MagickGetCopyright method is: % % const char *MagickGetCopyright(void) % */ WandExport const char *MagickGetCopyright(void) { return(GetMagickCopyright()); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetFilename() returns the filename associated with an image sequence. % % The format of the MagickGetFilename method is: % % const char *MagickGetFilename(const MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport char *MagickGetFilename(const MagickWand *wand) { assert(wand != (const MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(AcquireString(wand->image_info->filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t F o n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetFont() returns the font associated with the MagickWand. % % The format of the MagickGetFont method is: % % char *MagickGetFont(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport char *MagickGetFont(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->image_info->font == (char *) NULL) return((char *) NULL); return(AcquireString(wand->image_info->font)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetFormat() returns the format of the magick wand. % % The format of the MagickGetFormat method is: % % const char MagickGetFormat(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport char *MagickGetFormat(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(AcquireString(wand->image_info->magick)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t G r a v i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetGravity() gets the wand gravity. % % The format of the MagickGetGravity method is: % % GravityType MagickGetGravity(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport GravityType MagickGetGravity(MagickWand *wand) { const char *option; GravityType type; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); option=GetImageOption(wand->image_info,"gravity"); if (option == (const char *) NULL) return(UndefinedGravity); type=(GravityType) ParseCommandOption(MagickGravityOptions,MagickFalse,option); return(type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t H o m e U R L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetHomeURL() returns the ImageMagick home URL. % % The format of the MagickGetHomeURL method is: % % char *MagickGetHomeURL(void) % */ WandExport char *MagickGetHomeURL(void) { return(GetMagickHomeURL()); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e A r t i f a c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageArtifact() returns a value associated with the specified % artifact. Use MagickRelinquishMemory() to free the value when you are % finished with it. % % The format of the MagickGetImageArtifact method is: % % char *MagickGetImageArtifact(MagickWand *wand,const char *artifact) % % A description of each parameter follows: % % o wand: the magick wand. % % o artifact: the artifact. % */ WandExport char *MagickGetImageArtifact(MagickWand *wand,const char *artifact) { const char *value; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char *) NULL); } value=GetImageArtifact(wand->images,artifact); if (value == (const char *) NULL) return((char *) NULL); return(ConstantString(value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageArtifacts() returns all the artifact names that match the % specified pattern associated with a wand. Use MagickGetImageProperty() to % return the value of a particular artifact. Use MagickRelinquishMemory() to % free the value when you are finished with it. % % The format of the MagickGetImageArtifacts method is: % % char *MagickGetImageArtifacts(MagickWand *wand, % const char *pattern,size_t *number_artifacts) % % A description of each parameter follows: % % o wand: the magick wand. % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_artifacts: the number artifacts associated with this wand. % */ WandExport char **MagickGetImageArtifacts(MagickWand *wand, const char *pattern,size_t *number_artifacts) { char **artifacts; const char *artifact; register ssize_t i; size_t length; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char **) NULL); } (void) GetImageProperty(wand->images,"exif:*"); length=1024; artifacts=(char **) AcquireQuantumMemory(length,sizeof(*artifacts)); if (artifacts == (char **) NULL) return((char **) NULL); ResetImagePropertyIterator(wand->images); artifact=GetNextImageProperty(wand->images); for (i=0; artifact != (const char *) NULL; ) { if ((*artifact != '[') && (GlobExpression(artifact,pattern,MagickFalse) != MagickFalse)) { if ((i+1) >= (ssize_t) length) { length<<=1; artifacts=(char **) ResizeQuantumMemory(artifacts,length, sizeof(*artifacts)); if (artifacts == (char **) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", wand->name); return((char **) NULL); } } artifacts[i]=ConstantString(artifact); i++; } artifact=GetNextImageProperty(wand->images); } artifacts[i]=(char *) NULL; *number_artifacts=(size_t) i; return(artifacts); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageProfile() returns the named image profile. % % The format of the MagickGetImageProfile method is: % % unsigned char *MagickGetImageProfile(MagickWand *wand,const char *name, % size_t *length) % % A description of each parameter follows: % % o wand: the magick wand. % % o name: Name of profile to return: ICC, IPTC, or generic profile. % % o length: the length of the profile. % */ WandExport unsigned char *MagickGetImageProfile(MagickWand *wand, const char *name,size_t *length) { const StringInfo *profile; unsigned char *datum; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((unsigned char *) NULL); } *length=0; if (wand->images->profiles == (SplayTreeInfo *) NULL) return((unsigned char *) NULL); profile=GetImageProfile(wand->images,name); if (profile == (StringInfo *) NULL) return((unsigned char *) NULL); datum=(unsigned char *) AcquireQuantumMemory(GetStringInfoLength(profile), sizeof(*datum)); if (datum == (unsigned char *) NULL) return((unsigned char *) NULL); (void) CopyMagickMemory(datum,GetStringInfoDatum(profile), GetStringInfoLength(profile)); *length=(size_t) GetStringInfoLength(profile); return(datum); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageProfiles() returns all the profile names that match the % specified pattern associated with a wand. Use MagickGetImageProfile() to % return the value of a particular property. Use MagickRelinquishMemory() to % free the value when you are finished with it. % % The format of the MagickGetImageProfiles method is: % % char *MagickGetImageProfiles(MagickWand *wand,const char *pattern, % size_t *number_profiles) % % A description of each parameter follows: % % o wand: the magick wand. % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_profiles: the number profiles associated with this wand. % */ WandExport char **MagickGetImageProfiles(MagickWand *wand,const char *pattern, size_t *number_profiles) { char **profiles; const char *property; register ssize_t i; size_t length; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char **) NULL); } (void) GetImageProfile(wand->images,"exif:*"); length=1024; profiles=(char **) AcquireQuantumMemory(length,sizeof(*profiles)); if (profiles == (char **) NULL) return((char **) NULL); ResetImageProfileIterator(wand->images); property=GetNextImageProfile(wand->images); for (i=0; property != (const char *) NULL; ) { if ((*property != '[') && (GlobExpression(property,pattern,MagickFalse) != MagickFalse)) { if ((i+1) >= (ssize_t) length) { length<<=1; profiles=(char **) ResizeQuantumMemory(profiles,length, sizeof(*profiles)); if (profiles == (char **) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", wand->name); return((char **) NULL); } } profiles[i]=ConstantString(property); i++; } property=GetNextImageProfile(wand->images); } profiles[i]=(char *) NULL; *number_profiles=(size_t) i; return(profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageProperty() returns a value associated with the specified % property. Use MagickRelinquishMemory() to free the value when you are % finished with it. % % The format of the MagickGetImageProperty method is: % % char *MagickGetImageProperty(MagickWand *wand,const char *property) % % A description of each parameter follows: % % o wand: the magick wand. % % o property: the property. % */ WandExport char *MagickGetImageProperty(MagickWand *wand,const char *property) { const char *value; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char *) NULL); } value=GetImageProperty(wand->images,property); if (value == (const char *) NULL) return((char *) NULL); return(ConstantString(value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageProperties() returns all the property names that match the % specified pattern associated with a wand. Use MagickGetImageProperty() to % return the value of a particular property. Use MagickRelinquishMemory() to % free the value when you are finished with it. % % The format of the MagickGetImageProperties method is: % % char *MagickGetImageProperties(MagickWand *wand, % const char *pattern,size_t *number_properties) % % A description of each parameter follows: % % o wand: the magick wand. % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_properties: the number properties associated with this wand. % */ WandExport char **MagickGetImageProperties(MagickWand *wand, const char *pattern,size_t *number_properties) { char **properties; const char *property; register ssize_t i; size_t length; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char **) NULL); } (void) GetImageProperty(wand->images,"exif:*"); length=1024; properties=(char **) AcquireQuantumMemory(length,sizeof(*properties)); if (properties == (char **) NULL) return((char **) NULL); ResetImagePropertyIterator(wand->images); property=GetNextImageProperty(wand->images); for (i=0; property != (const char *) NULL; ) { if ((*property != '[') && (GlobExpression(property,pattern,MagickFalse) != MagickFalse)) { if ((i+1) >= (ssize_t) length) { length<<=1; properties=(char **) ResizeQuantumMemory(properties,length, sizeof(*properties)); if (properties == (char **) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", wand->name); return((char **) NULL); } } properties[i]=ConstantString(property); i++; } property=GetNextImageProperty(wand->images); } properties[i]=(char *) NULL; *number_properties=(size_t) i; return(properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I n t e r l a c e S c h e m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetInterlaceScheme() gets the wand interlace scheme. % % The format of the MagickGetInterlaceScheme method is: % % InterlaceType MagickGetInterlaceScheme(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport InterlaceType MagickGetInterlaceScheme(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->interlace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I n t e r p o l a t e M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetInterpolateMethod() gets the wand compression. % % The format of the MagickGetInterpolateMethod method is: % % InterpolatePixelMethod MagickGetInterpolateMethod(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport InterpolatePixelMethod MagickGetInterpolateMethod(MagickWand *wand) { const char *option; InterpolatePixelMethod method; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); option=GetImageOption(wand->image_info,"interpolate"); if (option == (const char *) NULL) return(UndefinedInterpolatePixel); method=(InterpolatePixelMethod) ParseCommandOption(MagickInterpolateOptions, MagickFalse,option); return(method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t O p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetOption() returns a value associated with a wand and the specified % key. Use MagickRelinquishMemory() to free the value when you are finished % with it. % % The format of the MagickGetOption method is: % % char *MagickGetOption(MagickWand *wand,const char *key) % % A description of each parameter follows: % % o wand: the magick wand. % % o key: the key. % */ WandExport char *MagickGetOption(MagickWand *wand,const char *key) { const char *option; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); option=GetImageOption(wand->image_info,key); return(ConstantString(option)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetOptions() returns all the option names that match the specified % pattern associated with a wand. Use MagickGetOption() to return the value % of a particular option. Use MagickRelinquishMemory() to free the value % when you are finished with it. % % The format of the MagickGetOptions method is: % % char *MagickGetOptions(MagickWand *wand,const char *pattern,, % size_t *number_options) % % A description of each parameter follows: % % o wand: the magick wand. % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_options: the number options associated with this wand. % */ WandExport char **MagickGetOptions(MagickWand *wand,const char *pattern, size_t *number_options) { char **options; const char *option; register ssize_t i; size_t length; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((char **) NULL); } length=1024; options=(char **) AcquireQuantumMemory(length,sizeof(*options)); if (options == (char **) NULL) return((char **) NULL); ResetImageOptionIterator(wand->image_info); option=GetNextImageOption(wand->image_info); for (i=0; option != (const char *) NULL; ) { if ((*option != '[') && (GlobExpression(option,pattern,MagickFalse) != MagickFalse)) { if ((i+1) >= (ssize_t) length) { length<<=1; options=(char **) ResizeQuantumMemory(options,length, sizeof(*options)); if (options == (char **) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", wand->name); return((char **) NULL); } } options[i]=ConstantString(option); i++; } option=GetNextImageOption(wand->image_info); } options[i]=(char *) NULL; *number_options=(size_t) i; return(options); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t O r i e n t a t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetOrientation() gets the wand orientation type. % % The format of the MagickGetOrientation method is: % % OrientationType MagickGetOrientation(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport OrientationType MagickGetOrientation(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->orientation); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t P a c k a g e N a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetPackageName() returns the ImageMagick package name as a string % constant. % % The format of the MagickGetPackageName method is: % % const char *MagickGetPackageName(void) % % */ WandExport const char *MagickGetPackageName(void) { return(GetMagickPackageName()); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetPage() returns the page geometry associated with the magick wand. % % The format of the MagickGetPage method is: % % MagickBooleanType MagickGetPage(const MagickWand *wand, % size_t *width,size_t *height,ssize_t *x,ssize_t *y) % % A description of each parameter follows: % % o wand: the magick wand. % % o width: the page width. % % o height: page height. % % o x: the page x-offset. % % o y: the page y-offset. % */ WandExport MagickBooleanType MagickGetPage(const MagickWand *wand, size_t *width,size_t *height,ssize_t *x,ssize_t *y) { RectangleInfo geometry; assert(wand != (const MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); (void) ParseAbsoluteGeometry(wand->image_info->page,&geometry); *width=geometry.width; *height=geometry.height; *x=geometry.x; *y=geometry.y; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t P o i n t s i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetPointsize() returns the font pointsize associated with the % MagickWand. % % The format of the MagickGetPointsize method is: % % double MagickGetPointsize(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport double MagickGetPointsize(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->pointsize); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetQuantumDepth() returns the ImageMagick quantum depth as a string % constant. % % The format of the MagickGetQuantumDepth method is: % % const char *MagickGetQuantumDepth(size_t *depth) % % A description of each parameter follows: % % o depth: the quantum depth is returned as a number. % */ WandExport const char *MagickGetQuantumDepth(size_t *depth) { return(GetMagickQuantumDepth(depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t Q u a n t u m R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetQuantumRange() returns the ImageMagick quantum range as a string % constant. % % The format of the MagickGetQuantumRange method is: % % const char *MagickGetQuantumRange(size_t *range) % % A description of each parameter follows: % % o range: the quantum range is returned as a number. % */ WandExport const char *MagickGetQuantumRange(size_t *range) { return(GetMagickQuantumRange(range)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t R e l e a s e D a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetReleaseDate() returns the ImageMagick release date as a string % constant. % % The format of the MagickGetReleaseDate method is: % % const char *MagickGetReleaseDate(void) % */ WandExport const char *MagickGetReleaseDate(void) { return(GetMagickReleaseDate()); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t R e s o l u t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetResolution() gets the image X and Y resolution. % % The format of the MagickGetResolution method is: % % MagickBooleanType MagickGetResolution(const MagickWand *wand,double *x, % double *y) % % A description of each parameter follows: % % o wand: the magick wand. % % o x: the x-resolution. % % o y: the y-resolution. % */ WandExport MagickBooleanType MagickGetResolution(const MagickWand *wand, double *x,double *y) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); *x=72.0; *y=72.0; if (wand->image_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(wand->image_info->density,&geometry_info); *x=geometry_info.rho; *y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) *y=(*x); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t R e s o u r c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetResource() returns the specified resource in megabytes. % % The format of the MagickGetResource method is: % % MagickSizeType MagickGetResource(const ResourceType type) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickSizeType MagickGetResource(const ResourceType type) { return(GetMagickResource(type)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t R e s o u r c e L i m i t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetResourceLimit() returns the specified resource limit in megabytes. % % The format of the MagickGetResourceLimit method is: % % MagickSizeType MagickGetResourceLimit(const ResourceType type) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickSizeType MagickGetResourceLimit(const ResourceType type) { return(GetMagickResourceLimit(type)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t S a m p l i n g F a c t o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetSamplingFactors() gets the horizontal and vertical sampling factor. % % The format of the MagickGetSamplingFactors method is: % % double *MagickGetSamplingFactor(MagickWand *wand, % size_t *number_factors) % % A description of each parameter follows: % % o wand: the magick wand. % % o number_factors: the number of factors in the returned array. % */ WandExport double *MagickGetSamplingFactors(MagickWand *wand, size_t *number_factors) { double *sampling_factors; register const char *p; register ssize_t i; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); *number_factors=0; sampling_factors=(double *) NULL; if (wand->image_info->sampling_factor == (char *) NULL) return(sampling_factors); i=0; for (p=wand->image_info->sampling_factor; p != (char *) NULL; p=strchr(p,',')) { while (((int) *p != 0) && ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))) p++; i++; } sampling_factors=(double *) AcquireQuantumMemory((size_t) i, sizeof(*sampling_factors)); if (sampling_factors == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", wand->image_info->filename); i=0; for (p=wand->image_info->sampling_factor; p != (char *) NULL; p=strchr(p,',')) { while (((int) *p != 0) && ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))) p++; sampling_factors[i]=StringToDouble(p,(char **) NULL); i++; } *number_factors=(size_t) i; return(sampling_factors); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetSize() returns the size associated with the magick wand. % % The format of the MagickGetSize method is: % % MagickBooleanType MagickGetSize(const MagickWand *wand, % size_t *columns,size_t *rows) % % A description of each parameter follows: % % o wand: the magick wand. % % o columns: the width in pixels. % % o height: the height in pixels. % */ WandExport MagickBooleanType MagickGetSize(const MagickWand *wand, size_t *columns,size_t *rows) { RectangleInfo geometry; assert(wand != (const MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); (void) ParseAbsoluteGeometry(wand->image_info->size,&geometry); *columns=geometry.width; *rows=geometry.height; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t S i z e O f f s e t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetSizeOffset() returns the size offset associated with the magick % wand. % % The format of the MagickGetSizeOffset method is: % % MagickBooleanType MagickGetSizeOffset(const MagickWand *wand, % ssize_t *offset) % % A description of each parameter follows: % % o wand: the magick wand. % % o offset: the image offset. % */ WandExport MagickBooleanType MagickGetSizeOffset(const MagickWand *wand, ssize_t *offset) { RectangleInfo geometry; assert(wand != (const MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); (void) ParseAbsoluteGeometry(wand->image_info->size,&geometry); *offset=geometry.x; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetType() returns the wand type. % % The format of the MagickGetType method is: % % ImageType MagickGetType(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport ImageType MagickGetType(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(wand->image_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t V e r s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetVersion() returns the ImageMagick API version as a string constant % and as a number. % % The format of the MagickGetVersion method is: % % const char *MagickGetVersion(size_t *version) % % A description of each parameter follows: % % o version: the ImageMagick version is returned as a number. % */ WandExport const char *MagickGetVersion(size_t *version) { return(GetMagickVersion(version)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickProfileImage() adds or removes a ICC, IPTC, or generic profile % from an image. If the profile is NULL, it is removed from the image % otherwise added. Use a name of '*' and a profile of NULL to remove all % profiles from the image. % % The format of the MagickProfileImage method is: % % MagickBooleanType MagickProfileImage(MagickWand *wand,const char *name, % const void *profile,const size_t length) % % A description of each parameter follows: % % o wand: the magick wand. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o profile: the profile. % % o length: the length of the profile. % */ WandExport MagickBooleanType MagickProfileImage(MagickWand *wand, const char *name,const void *profile,const size_t length) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=ProfileImage(wand->images,name,profile,length,MagickTrue); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickRemoveImageProfile() removes the named image profile and returns it. % % The format of the MagickRemoveImageProfile method is: % % unsigned char *MagickRemoveImageProfile(MagickWand *wand, % const char *name,size_t *length) % % A description of each parameter follows: % % o wand: the magick wand. % % o name: Name of profile to return: ICC, IPTC, or generic profile. % % o length: the length of the profile. % */ WandExport unsigned char *MagickRemoveImageProfile(MagickWand *wand, const char *name,size_t *length) { StringInfo *profile; unsigned char *datum; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) { (void) ThrowMagickException(wand->exception,GetMagickModule(),WandError, "ContainsNoImages","`%s'",wand->name); return((unsigned char *) NULL); } *length=0; profile=RemoveImageProfile(wand->images,name); if (profile == (StringInfo *) NULL) return((unsigned char *) NULL); datum=(unsigned char *) AcquireQuantumMemory(GetStringInfoLength(profile), sizeof(*datum)); if (datum == (unsigned char *) NULL) return((unsigned char *) NULL); (void) CopyMagickMemory(datum,GetStringInfoDatum(profile), GetStringInfoLength(profile)); *length=GetStringInfoLength(profile); profile=DestroyStringInfo(profile); return(datum); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t A n t i a l i a s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetAntialias() sets the antialias propery of the wand. % % The format of the MagickSetAntialias method is: % % MagickBooleanType MagickSetAntialias(MagickWand *wand, % const MagickBooleanType antialias) % % A description of each parameter follows: % % o wand: the magick wand. % % o antialias: the antialias property. % */ WandExport MagickBooleanType MagickSetAntialias(MagickWand *wand, const MagickBooleanType antialias) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->antialias=antialias; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetBackgroundColor() sets the wand background color. % % The format of the MagickSetBackgroundColor method is: % % MagickBooleanType MagickSetBackgroundColor(MagickWand *wand, % const PixelWand *background) % % A description of each parameter follows: % % o wand: the magick wand. % % o background: the background pixel wand. % */ WandExport MagickBooleanType MagickSetBackgroundColor(MagickWand *wand, const PixelWand *background) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); PixelGetQuantumColor(background,&wand->image_info->background_color); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetColorspace() sets the wand colorspace type. % % The format of the MagickSetColorspace method is: % % MagickBooleanType MagickSetColorspace(MagickWand *wand, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o wand: the magick wand. % % o colorspace: the wand colorspace. % */ WandExport MagickBooleanType MagickSetColorspace(MagickWand *wand, const ColorspaceType colorspace) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->colorspace=colorspace; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t C o m p r e s s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetCompression() sets the wand compression type. % % The format of the MagickSetCompression method is: % % MagickBooleanType MagickSetCompression(MagickWand *wand, % const CompressionType compression) % % A description of each parameter follows: % % o wand: the magick wand. % % o compression: the wand compression. % */ WandExport MagickBooleanType MagickSetCompression(MagickWand *wand, const CompressionType compression) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->compression=compression; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t C o m p r e s s i o n Q u a l i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetCompressionQuality() sets the wand compression quality. % % The format of the MagickSetCompressionQuality method is: % % MagickBooleanType MagickSetCompressionQuality(MagickWand *wand, % const size_t quality) % % A description of each parameter follows: % % o wand: the magick wand. % % o quality: the wand compression quality. % */ WandExport MagickBooleanType MagickSetCompressionQuality(MagickWand *wand, const size_t quality) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->quality=quality; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetDepth() sets the wand pixel depth. % % The format of the MagickSetDepth method is: % % MagickBooleanType MagickSetDepth(MagickWand *wand, % const size_t depth) % % A description of each parameter follows: % % o wand: the magick wand. % % o depth: the wand pixel depth. % */ WandExport MagickBooleanType MagickSetDepth(MagickWand *wand, const size_t depth) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->depth=depth; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t E x t r a c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetExtract() sets the extract geometry before you read or write an % image file. Use it for inline cropping (e.g. 200x200+0+0) or resizing % (e.g.200x200). % % The format of the MagickSetExtract method is: % % MagickBooleanType MagickSetExtract(MagickWand *wand, % const char *geometry) % % A description of each parameter follows: % % o wand: the magick wand. % % o geometry: the extract geometry. % */ WandExport MagickBooleanType MagickSetExtract(MagickWand *wand, const char *geometry) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (geometry != (const char *) NULL) (void) CopyMagickString(wand->image_info->extract,geometry,MaxTextExtent); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetFilename() sets the filename before you read or write an image file. % % The format of the MagickSetFilename method is: % % MagickBooleanType MagickSetFilename(MagickWand *wand, % const char *filename) % % A description of each parameter follows: % % o wand: the magick wand. % % o filename: the image filename. % */ WandExport MagickBooleanType MagickSetFilename(MagickWand *wand, const char *filename) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (filename != (const char *) NULL) (void) CopyMagickString(wand->image_info->filename,filename,MaxTextExtent); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t F o n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetFont() sets the font associated with the MagickWand. % % The format of the MagickSetFont method is: % % MagickBooleanType MagickSetFont(MagickWand *wand, const char *font) % % A description of each parameter follows: % % o wand: the magick wand. % % o font: the font % */ WandExport MagickBooleanType MagickSetFont(MagickWand *wand,const char *font) { if ((font == (const char *) NULL) || (*font == '\0')) return(MagickFalse); assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) CloneString(&wand->image_info->font,font); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetFormat() sets the format of the magick wand. % % The format of the MagickSetFormat method is: % % MagickBooleanType MagickSetFormat(MagickWand *wand,const char *format) % % A description of each parameter follows: % % o wand: the magick wand. % % o format: the image format. % */ WandExport MagickBooleanType MagickSetFormat(MagickWand *wand, const char *format) { const MagickInfo *magick_info; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if ((format == (char *) NULL) || (*format == '\0')) { *wand->image_info->magick='\0'; return(MagickTrue); } magick_info=GetMagickInfo(format,wand->exception); if (magick_info == (const MagickInfo *) NULL) return(MagickFalse); ClearMagickException(wand->exception); (void) CopyMagickString(wand->image_info->magick,format,MaxTextExtent); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t G r a v i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetGravity() sets the gravity type. % % The format of the MagickSetGravity type is: % % MagickBooleanType MagickSetGravity(MagickWand *wand, % const GravityType type) % % A description of each parameter follows: % % o wand: the magick wand. % % o type: the gravity type. % */ WandExport MagickBooleanType MagickSetGravity(MagickWand *wand, const GravityType type) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); status=SetImageOption(wand->image_info,"gravity",CommandOptionToMnemonic( MagickGravityOptions,(ssize_t) type)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I m a g e A r t i f r c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageArtifact() associates a artifact with an image. % % The format of the MagickSetImageArtifact method is: % % MagickBooleanType MagickSetImageArtifact(MagickWand *wand, % const char *artifact,const char *value) % % A description of each parameter follows: % % o wand: the magick wand. % % o artifact: the artifact. % % o value: the value. % */ WandExport MagickBooleanType MagickSetImageArtifact(MagickWand *wand, const char *artifact,const char *value) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=SetImageArtifact(wand->images,artifact,value); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageProfile() adds a named profile to the magick wand. If a % profile with the same name already exists, it is replaced. This method % differs from the MagickProfileImage() method in that it does not apply any % CMS color profiles. % % The format of the MagickSetImageProfile method is: % % MagickBooleanType MagickSetImageProfile(MagickWand *wand, % const char *name,const void *profile,const size_t length) % % A description of each parameter follows: % % o wand: the magick wand. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o profile: the profile. % % o length: the length of the profile. % */ WandExport MagickBooleanType MagickSetImageProfile(MagickWand *wand, const char *name,const void *profile,const size_t length) { MagickBooleanType status; StringInfo *profile_info; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); profile_info=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile_info,(unsigned char *) profile); status=SetImageProfile(wand->images,name,profile_info); profile_info=DestroyStringInfo(profile_info); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageProperty() associates a property with an image. % % The format of the MagickSetImageProperty method is: % % MagickBooleanType MagickSetImageProperty(MagickWand *wand, % const char *property,const char *value) % % A description of each parameter follows: % % o wand: the magick wand. % % o property: the property. % % o value: the value. % */ WandExport MagickBooleanType MagickSetImageProperty(MagickWand *wand, const char *property,const char *value) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=SetImageProperty(wand->images,property,value); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I n t e r l a c e S c h e m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetInterlaceScheme() sets the image compression. % % The format of the MagickSetInterlaceScheme method is: % % MagickBooleanType MagickSetInterlaceScheme(MagickWand *wand, % const InterlaceType interlace_scheme) % % A description of each parameter follows: % % o wand: the magick wand. % % o interlace_scheme: the image interlace scheme: NoInterlace, LineInterlace, % PlaneInterlace, PartitionInterlace. % */ WandExport MagickBooleanType MagickSetInterlaceScheme(MagickWand *wand, const InterlaceType interlace_scheme) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->interlace=interlace_scheme; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I n t e r p o l a t e M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetInterpolateMethod() sets the interpolate pixel method. % % The format of the MagickSetInterpolateMethod method is: % % MagickBooleanType MagickSetInterpolateMethod(MagickWand *wand, % const InterpolateMethodPixel method) % % A description of each parameter follows: % % o wand: the magick wand. % % o method: the interpolate pixel method. % */ WandExport MagickBooleanType MagickSetInterpolateMethod(MagickWand *wand, const InterpolatePixelMethod method) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); status=SetImageOption(wand->image_info,"interpolate", CommandOptionToMnemonic(MagickInterpolateOptions,(ssize_t) method)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t O p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetOption() associates one or options with the wand (.e.g % MagickSetOption(wand,"jpeg:perserve","yes")). % % The format of the MagickSetOption method is: % % MagickBooleanType MagickSetOption(MagickWand *wand,const char *key, % const char *value) % % A description of each parameter follows: % % o wand: the magick wand. % % o key: The key. % % o value: The value. % */ WandExport MagickBooleanType MagickSetOption(MagickWand *wand,const char *key, const char *value) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); return(SetImageOption(wand->image_info,key,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t O r i e n t a t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetOrientation() sets the wand orientation type. % % The format of the MagickSetOrientation method is: % % MagickBooleanType MagickSetOrientation(MagickWand *wand, % const OrientationType orientation) % % A description of each parameter follows: % % o wand: the magick wand. % % o orientation: the wand orientation. % */ WandExport MagickBooleanType MagickSetOrientation(MagickWand *wand, const OrientationType orientation) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->orientation=orientation; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetPage() sets the page geometry of the magick wand. % % The format of the MagickSetPage method is: % % MagickBooleanType MagickSetPage(MagickWand *wand, % const size_t width,const size_t height,const ssize_t x, % const ssize_t y) % % A description of each parameter follows: % % o wand: the magick wand. % % o width: the page width. % % o height: the page height. % % o x: the page x-offset. % % o y: the page y-offset. % */ WandExport MagickBooleanType MagickSetPage(MagickWand *wand, const size_t width,const size_t height,const ssize_t x, const ssize_t y) { char geometry[MaxTextExtent]; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g%+.20g%+.20g", (double) width,(double) height,(double) x,(double) y); (void) CloneString(&wand->image_info->page,geometry); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t P a s s p h r a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetPassphrase() sets the passphrase. % % The format of the MagickSetPassphrase method is: % % MagickBooleanType MagickSetPassphrase(MagickWand *wand, % const char *passphrase) % % A description of each parameter follows: % % o wand: the magick wand. % % o passphrase: the passphrase. % */ WandExport MagickBooleanType MagickSetPassphrase(MagickWand *wand, const char *passphrase) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) CloneString(&wand->image_info->authenticate,passphrase); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t P o i n t s i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetPointsize() sets the font pointsize associated with the MagickWand. % % The format of the MagickSetPointsize method is: % % MagickBooleanType MagickSetPointsize(MagickWand *wand, % const double pointsize) % % A description of each parameter follows: % % o wand: the magick wand. % % o pointsize: the size of the font % */ WandExport MagickBooleanType MagickSetPointsize(MagickWand *wand, const double pointsize) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->pointsize=pointsize; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t P r o g r e s s M o n i t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetProgressMonitor() sets the wand progress monitor to the specified % method and returns the previous progress monitor if any. The progress % monitor method looks like this: % % MagickBooleanType MagickProgressMonitor(const char *text, % const MagickOffsetType offset,const MagickSizeType span, % void *client_data) % % If the progress monitor returns MagickFalse, the current operation is % interrupted. % % The format of the MagickSetProgressMonitor method is: % % MagickProgressMonitor MagickSetProgressMonitor(MagickWand *wand % const MagickProgressMonitor progress_monitor,void *client_data) % % A description of each parameter follows: % % o wand: the magick wand. % % o progress_monitor: Specifies a pointer to a method to monitor progress % of an image operation. % % o client_data: Specifies a pointer to any client data. % */ WandExport MagickProgressMonitor MagickSetProgressMonitor(MagickWand *wand, const MagickProgressMonitor progress_monitor,void *client_data) { MagickProgressMonitor previous_monitor; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); previous_monitor=SetImageInfoProgressMonitor(wand->image_info, progress_monitor,client_data); return(previous_monitor); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t R e s o u r c e L i m i t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetResourceLimit() sets the limit for a particular resource in % megabytes. % % The format of the MagickSetResourceLimit method is: % % MagickBooleanType MagickSetResourceLimit(const ResourceType type, % const MagickSizeType limit) % % A description of each parameter follows: % % o type: the type of resource: AreaResource, MemoryResource, MapResource, % DiskResource, FileResource. % % o The maximum limit for the resource. % */ WandExport MagickBooleanType MagickSetResourceLimit(const ResourceType type, const MagickSizeType limit) { return(SetMagickResourceLimit(type,limit)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t R e s o l u t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetResolution() sets the image resolution. % % The format of the MagickSetResolution method is: % % MagickBooleanType MagickSetResolution(MagickWand *wand, % const double x_resolution,const double y_resolution) % % A description of each parameter follows: % % o wand: the magick wand. % % o x_resolution: the image x resolution. % % o y_resolution: the image y resolution. % */ WandExport MagickBooleanType MagickSetResolution(MagickWand *wand, const double x_resolution,const double y_resolution) { char density[MaxTextExtent]; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",x_resolution, y_resolution); (void) CloneString(&wand->image_info->density,density); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t S a m p l i n g F a c t o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetSamplingFactors() sets the image sampling factors. % % The format of the MagickSetSamplingFactors method is: % % MagickBooleanType MagickSetSamplingFactors(MagickWand *wand, % const size_t number_factors,const double *sampling_factors) % % A description of each parameter follows: % % o wand: the magick wand. % % o number_factoes: the number of factors. % % o sampling_factors: An array of doubles representing the sampling factor % for each color component (in RGB order). % */ WandExport MagickBooleanType MagickSetSamplingFactors(MagickWand *wand, const size_t number_factors,const double *sampling_factors) { char sampling_factor[MaxTextExtent]; register ssize_t i; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->image_info->sampling_factor != (char *) NULL) wand->image_info->sampling_factor=(char *) RelinquishMagickMemory(wand->image_info->sampling_factor); if (number_factors == 0) return(MagickTrue); for (i=0; i < (ssize_t) (number_factors-1); i++) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%g,", sampling_factors[i]); (void) ConcatenateString(&wand->image_info->sampling_factor, sampling_factor); } (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%g", sampling_factors[i]); (void) ConcatenateString(&wand->image_info->sampling_factor,sampling_factor); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetSize() sets the size of the magick wand. Set it before you % read a raw image format such as RGB, GRAY, or CMYK. % % The format of the MagickSetSize method is: % % MagickBooleanType MagickSetSize(MagickWand *wand, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o wand: the magick wand. % % o columns: the width in pixels. % % o rows: the rows in pixels. % */ WandExport MagickBooleanType MagickSetSize(MagickWand *wand, const size_t columns,const size_t rows) { char geometry[MaxTextExtent]; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",(double) columns,(double) rows); (void) CloneString(&wand->image_info->size,geometry); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t S i z e O f f s e t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetSizeOffset() sets the size and offset of the magick wand. Set it % before you read a raw image format such as RGB, GRAY, or CMYK. % % The format of the MagickSetSizeOffset method is: % % MagickBooleanType MagickSetSizeOffset(MagickWand *wand, % const size_t columns,const size_t rows, % const ssize_t offset) % % A description of each parameter follows: % % o wand: the magick wand. % % o columns: the image width in pixels. % % o rows: the image rows in pixels. % % o offset: the image offset. % */ WandExport MagickBooleanType MagickSetSizeOffset(MagickWand *wand, const size_t columns,const size_t rows,const ssize_t offset) { char geometry[MaxTextExtent]; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g%+.20g", (double) columns,(double) rows,(double) offset); (void) CloneString(&wand->image_info->size,geometry); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetType() sets the image type attribute. % % The format of the MagickSetType method is: % % MagickBooleanType MagickSetType(MagickWand *wand, % const ImageType image_type) % % A description of each parameter follows: % % o wand: the magick wand. % % o image_type: the image type: UndefinedType, BilevelType, GrayscaleType, % GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, % TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, % or OptimizeType. % */ WandExport MagickBooleanType MagickSetType(MagickWand *wand, const ImageType image_type) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); wand->image_info->type=image_type; return(MagickTrue); }
20444.c
/** ****************************************************************************** * @file example.c * @author Jalon * @date 2016.07.01 * @brief 该代码只是调用通讯接口范例,并非直接可运行的程序 * @attention Copyright (C) 2016 Inmotion ****************************************************************************** */ #include "navipack_api.h" #define NAVI_MAX(a, b) (a>b?a:b) #define NAVI_MAX_BLOCK (u32)(NAVI_MAX(NAVI_MAX( sizeof(NaviPack_CtrlType), sizeof(NaviPack_StatusType)), sizeof(NaviPack_ConfigType))) #define NAVIPACK_COMM_SIZE (NAVI_MAX_BLOCK + sizeof(NaviPack_HeadType) + 1) NavipackComm_Type Comm; u8 RecvBuf[NAVIPACK_COMM_SIZE]; u8 SendBuf[NAVIPACK_COMM_SIZE*2+6]; void SendStatus(void) { NaviPack_HeadType head = { NAVIPACK_SLAVE_ID, FUNC_ID_READ_STATUS, 0, sizeof(NaviPack_StatusType), }; // 调用发送函数前必须将新的值填入对应的寄存器变量中 Comm.status.lineVelocity = v; Comm.status.angularVelocity = w; if(NaviPack_TxProcessor(&Comm, head)) { // 成功发送了指定的寄存器内容 } } void Recv(void) { // 用户自己的接收程序,从通讯接口接收数据 u8 data = RecvData(); // 逐个 byte 的调用该接口,读取新收到的数据方法见 RxProcessor() 函数 if(NaviPack_RxProcessor(&comm, data)) { //成功接收并处理了一个寄存器操作 } } int main(void) { // 初始化 Comm.rxBuffer = RecvBuf; Comm.rxSize = sizeof(RecvBuf); Comm.txBuffer = SendBuf; Comm.txSize = sizeof(SendBuf); NaviPack_Init(); while(1) { // 接收处理根据用户的程序架构来决定调用位置,比如在接收中断里调用 Recv(); // 推荐 10 ms 调用一次,持续向上位机发送状态寄存器的数据 SendStatus(); Sleep(10); } }
557434.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * arch/powerpc/sysdev/qe_lib/qe_io.c * * QE Parallel I/O ports configuration routines * * Copyright 2006 Freescale Semiconductor, Inc. All rights reserved. * * Author: Li Yang <[email protected]> * Based on code from Shlomi Gridish <[email protected]> */ #include <linux/stddef.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/module.h> #include <linux/ioport.h> #include <asm/io.h> #include <soc/fsl/qe/qe.h> #undef DEBUG static struct qe_pio_regs __iomem *par_io; static int num_par_io_ports = 0; int par_io_init(struct device_node *np) { struct resource res; int ret; u32 num_ports; /* Map Parallel I/O ports registers */ ret = of_address_to_resource(np, 0, &res); if (ret) return ret; par_io = ioremap(res.start, resource_size(&res)); if (!of_property_read_u32(np, "num-ports", &num_ports)) num_par_io_ports = num_ports; return 0; } void __par_io_config_pin(struct qe_pio_regs __iomem *par_io, u8 pin, int dir, int open_drain, int assignment, int has_irq) { u32 pin_mask1bit; u32 pin_mask2bits; u32 new_mask2bits; u32 tmp_val; /* calculate pin location for single and 2 bits information */ pin_mask1bit = (u32) (1 << (QE_PIO_PINS - (pin + 1))); /* Set open drain, if required */ tmp_val = qe_ioread32be(&par_io->cpodr); if (open_drain) qe_iowrite32be(pin_mask1bit | tmp_val, &par_io->cpodr); else qe_iowrite32be(~pin_mask1bit & tmp_val, &par_io->cpodr); /* define direction */ tmp_val = (pin > (QE_PIO_PINS / 2) - 1) ? qe_ioread32be(&par_io->cpdir2) : qe_ioread32be(&par_io->cpdir1); /* get all bits mask for 2 bit per port */ pin_mask2bits = (u32) (0x3 << (QE_PIO_PINS - (pin % (QE_PIO_PINS / 2) + 1) * 2)); /* Get the final mask we need for the right definition */ new_mask2bits = (u32) (dir << (QE_PIO_PINS - (pin % (QE_PIO_PINS / 2) + 1) * 2)); /* clear and set 2 bits mask */ if (pin > (QE_PIO_PINS / 2) - 1) { qe_iowrite32be(~pin_mask2bits & tmp_val, &par_io->cpdir2); tmp_val &= ~pin_mask2bits; qe_iowrite32be(new_mask2bits | tmp_val, &par_io->cpdir2); } else { qe_iowrite32be(~pin_mask2bits & tmp_val, &par_io->cpdir1); tmp_val &= ~pin_mask2bits; qe_iowrite32be(new_mask2bits | tmp_val, &par_io->cpdir1); } /* define pin assignment */ tmp_val = (pin > (QE_PIO_PINS / 2) - 1) ? qe_ioread32be(&par_io->cppar2) : qe_ioread32be(&par_io->cppar1); new_mask2bits = (u32) (assignment << (QE_PIO_PINS - (pin % (QE_PIO_PINS / 2) + 1) * 2)); /* clear and set 2 bits mask */ if (pin > (QE_PIO_PINS / 2) - 1) { qe_iowrite32be(~pin_mask2bits & tmp_val, &par_io->cppar2); tmp_val &= ~pin_mask2bits; qe_iowrite32be(new_mask2bits | tmp_val, &par_io->cppar2); } else { qe_iowrite32be(~pin_mask2bits & tmp_val, &par_io->cppar1); tmp_val &= ~pin_mask2bits; qe_iowrite32be(new_mask2bits | tmp_val, &par_io->cppar1); } } EXPORT_SYMBOL(__par_io_config_pin); int par_io_config_pin(u8 port, u8 pin, int dir, int open_drain, int assignment, int has_irq) { if (!par_io || port >= num_par_io_ports) return -EINVAL; __par_io_config_pin(&par_io[port], pin, dir, open_drain, assignment, has_irq); return 0; } EXPORT_SYMBOL(par_io_config_pin); int par_io_data_set(u8 port, u8 pin, u8 val) { u32 pin_mask, tmp_val; if (port >= num_par_io_ports) return -EINVAL; if (pin >= QE_PIO_PINS) return -EINVAL; /* calculate pin location */ pin_mask = (u32) (1 << (QE_PIO_PINS - 1 - pin)); tmp_val = qe_ioread32be(&par_io[port].cpdata); if (val == 0) /* clear */ qe_iowrite32be(~pin_mask & tmp_val, &par_io[port].cpdata); else /* set */ qe_iowrite32be(pin_mask | tmp_val, &par_io[port].cpdata); return 0; } EXPORT_SYMBOL(par_io_data_set); int par_io_of_config(struct device_node *np) { struct device_node *pio; int pio_map_len; const __be32 *pio_map; if (par_io == NULL) { printk(KERN_ERR "par_io not initialized\n"); return -1; } pio = of_parse_phandle(np, "pio-handle", 0); if (pio == NULL) { printk(KERN_ERR "pio-handle not available\n"); return -1; } pio_map = of_get_property(pio, "pio-map", &pio_map_len); if (pio_map == NULL) { printk(KERN_ERR "pio-map is not set!\n"); return -1; } pio_map_len /= sizeof(unsigned int); if ((pio_map_len % 6) != 0) { printk(KERN_ERR "pio-map format wrong!\n"); return -1; } while (pio_map_len > 0) { u8 port = be32_to_cpu(pio_map[0]); u8 pin = be32_to_cpu(pio_map[1]); int dir = be32_to_cpu(pio_map[2]); int open_drain = be32_to_cpu(pio_map[3]); int assignment = be32_to_cpu(pio_map[4]); int has_irq = be32_to_cpu(pio_map[5]); par_io_config_pin(port, pin, dir, open_drain, assignment, has_irq); pio_map += 6; pio_map_len -= 6; } of_node_put(pio); return 0; } EXPORT_SYMBOL(par_io_of_config);
570372.c
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Stig Venaas <[email protected]> | | Wez Furlong <[email protected]> | | Sascha Kettler <[email protected]> | | Pierre-Alain Joye <[email protected]> | | Marc Delling <[email protected]> (PKCS12 functions) | | Jakub Zelenka <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_openssl.h" #include "zend_exceptions.h" /* PHP Includes */ #include "ext/standard/file.h" #include "ext/standard/info.h" #include "ext/standard/php_fopen_wrappers.h" #include "ext/standard/md5.h" #include "ext/standard/base64.h" #ifdef PHP_WIN32 # include "win32/winutil.h" #endif /* OpenSSL includes */ #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/conf.h> #include <openssl/rand.h> #include <openssl/ssl.h> #include <openssl/pkcs12.h> /* Common */ #include <time.h> #if (defined(PHP_WIN32) && defined(_MSC_VER) && _MSC_VER >= 1900) #define timezone _timezone /* timezone is called _timezone in LibC */ #endif #define MIN_KEY_LENGTH 384 #define OPENSSL_ALGO_SHA1 1 #define OPENSSL_ALGO_MD5 2 #define OPENSSL_ALGO_MD4 3 #ifdef HAVE_OPENSSL_MD2_H #define OPENSSL_ALGO_MD2 4 #endif #if PHP_OPENSSL_API_VERSION < 0x10100 #define OPENSSL_ALGO_DSS1 5 #endif #define OPENSSL_ALGO_SHA224 6 #define OPENSSL_ALGO_SHA256 7 #define OPENSSL_ALGO_SHA384 8 #define OPENSSL_ALGO_SHA512 9 #define OPENSSL_ALGO_RMD160 10 #define DEBUG_SMIME 0 #if !defined(OPENSSL_NO_EC) && defined(EVP_PKEY_EC) #define HAVE_EVP_PKEY_EC 1 #endif ZEND_DECLARE_MODULE_GLOBALS(openssl) /* FIXME: Use the openssl constants instead of * enum. It is now impossible to match real values * against php constants. Also sorry to break the * enum principles here, BC... */ enum php_openssl_key_type { OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_DEFAULT = OPENSSL_KEYTYPE_RSA, #ifdef HAVE_EVP_PKEY_EC OPENSSL_KEYTYPE_EC = OPENSSL_KEYTYPE_DH +1 #endif }; enum php_openssl_cipher_type { PHP_OPENSSL_CIPHER_RC2_40, PHP_OPENSSL_CIPHER_RC2_128, PHP_OPENSSL_CIPHER_RC2_64, PHP_OPENSSL_CIPHER_DES, PHP_OPENSSL_CIPHER_3DES, PHP_OPENSSL_CIPHER_AES_128_CBC, PHP_OPENSSL_CIPHER_AES_192_CBC, PHP_OPENSSL_CIPHER_AES_256_CBC, PHP_OPENSSL_CIPHER_DEFAULT = PHP_OPENSSL_CIPHER_RC2_40 }; PHP_FUNCTION(openssl_get_md_methods); PHP_FUNCTION(openssl_get_cipher_methods); #ifdef HAVE_EVP_PKEY_EC PHP_FUNCTION(openssl_get_curve_names); #endif PHP_FUNCTION(openssl_digest); PHP_FUNCTION(openssl_encrypt); PHP_FUNCTION(openssl_decrypt); PHP_FUNCTION(openssl_cipher_iv_length); PHP_FUNCTION(openssl_dh_compute_key); PHP_FUNCTION(openssl_pkey_derive); PHP_FUNCTION(openssl_random_pseudo_bytes); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_export_to_file, 0, 0, 2) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(0, outfilename) ZEND_ARG_INFO(0, notext) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_export, 0, 0, 2) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(1, out) ZEND_ARG_INFO(0, notext) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_fingerprint, 0, 0, 1) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_check_private_key, 0) ZEND_ARG_INFO(0, cert) ZEND_ARG_INFO(0, key) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_verify, 0) ZEND_ARG_INFO(0, cert) ZEND_ARG_INFO(0, key) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_parse, 0, 0, 1) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(0, shortname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_checkpurpose, 0, 0, 2) ZEND_ARG_INFO(0, x509cert) ZEND_ARG_INFO(0, purpose) ZEND_ARG_INFO(0, cainfo) /* array */ ZEND_ARG_INFO(0, untrustedfile) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_read, 0) ZEND_ARG_INFO(0, cert) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_free, 0) ZEND_ARG_INFO(0, x509) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs12_export_to_file, 0, 0, 4) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, priv_key) ZEND_ARG_INFO(0, pass) ZEND_ARG_INFO(0, args) /* array */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs12_export, 0, 0, 4) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(1, out) ZEND_ARG_INFO(0, priv_key) ZEND_ARG_INFO(0, pass) ZEND_ARG_INFO(0, args) /* array */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkcs12_read, 0) ZEND_ARG_INFO(0, PKCS12) ZEND_ARG_INFO(1, certs) /* array */ ZEND_ARG_INFO(0, pass) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_export_to_file, 0, 0, 2) ZEND_ARG_INFO(0, csr) ZEND_ARG_INFO(0, outfilename) ZEND_ARG_INFO(0, notext) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_export, 0, 0, 2) ZEND_ARG_INFO(0, csr) ZEND_ARG_INFO(1, out) ZEND_ARG_INFO(0, notext) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_sign, 0, 0, 4) ZEND_ARG_INFO(0, csr) ZEND_ARG_INFO(0, x509) ZEND_ARG_INFO(0, priv_key) ZEND_ARG_INFO(0, days) ZEND_ARG_INFO(0, config_args) /* array */ ZEND_ARG_INFO(0, serial) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_new, 0, 0, 2) ZEND_ARG_INFO(0, dn) /* array */ ZEND_ARG_INFO(1, privkey) ZEND_ARG_INFO(0, configargs) ZEND_ARG_INFO(0, extraattribs) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_get_subject, 0, 0, 1) ZEND_ARG_INFO(0, csr) ZEND_ARG_INFO(0, use_shortnames) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_get_public_key, 0, 0, 1) ZEND_ARG_INFO(0, csr) ZEND_ARG_INFO(0, use_shortnames) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_new, 0, 0, 0) ZEND_ARG_INFO(0, configargs) /* array */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_export_to_file, 0, 0, 2) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, outfilename) ZEND_ARG_INFO(0, passphrase) ZEND_ARG_INFO(0, config_args) /* array */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_export, 0, 0, 2) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(1, out) ZEND_ARG_INFO(0, passphrase) ZEND_ARG_INFO(0, config_args) /* array */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_get_public, 0) ZEND_ARG_INFO(0, cert) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_free, 0) ZEND_ARG_INFO(0, key) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_get_private, 0, 0, 1) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, passphrase) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_get_details, 0) ZEND_ARG_INFO(0, key) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pbkdf2, 0, 0, 4) ZEND_ARG_INFO(0, password) ZEND_ARG_INFO(0, salt) ZEND_ARG_INFO(0, key_length) ZEND_ARG_INFO(0, iterations) ZEND_ARG_INFO(0, digest_algorithm) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_verify, 0, 0, 2) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, signerscerts) ZEND_ARG_INFO(0, cainfo) /* array */ ZEND_ARG_INFO(0, extracerts) ZEND_ARG_INFO(0, content) ZEND_ARG_INFO(0, pk7) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_encrypt, 0, 0, 4) ZEND_ARG_INFO(0, infile) ZEND_ARG_INFO(0, outfile) ZEND_ARG_INFO(0, recipcerts) ZEND_ARG_INFO(0, headers) /* array */ ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, cipher) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_sign, 0, 0, 5) ZEND_ARG_INFO(0, infile) ZEND_ARG_INFO(0, outfile) ZEND_ARG_INFO(0, signcert) ZEND_ARG_INFO(0, signkey) ZEND_ARG_INFO(0, headers) /* array */ ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, extracertsfilename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_decrypt, 0, 0, 3) ZEND_ARG_INFO(0, infilename) ZEND_ARG_INFO(0, outfilename) ZEND_ARG_INFO(0, recipcert) ZEND_ARG_INFO(0, recipkey) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_read, 0, 0, 2) ZEND_ARG_INFO(0, infilename) ZEND_ARG_INFO(1, certs) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_private_encrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, crypted) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, padding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_private_decrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, crypted) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, padding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_public_encrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, crypted) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, padding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_public_decrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, crypted) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, padding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_error_string, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_sign, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, signature) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_verify, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, signature) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_seal, 0, 0, 4) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, sealdata) ZEND_ARG_INFO(1, ekeys) /* array */ ZEND_ARG_INFO(0, pubkeys) /* array */ ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(1, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_open, 0, 0, 4) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(1, opendata) ZEND_ARG_INFO(0, ekey) ZEND_ARG_INFO(0, privkey) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_get_md_methods, 0, 0, 0) ZEND_ARG_INFO(0, aliases) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_get_cipher_methods, 0, 0, 0) ZEND_ARG_INFO(0, aliases) ZEND_END_ARG_INFO() #ifdef HAVE_EVP_PKEY_EC ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_get_curve_names, 0, 0, 0) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_digest, 0, 0, 2) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_encrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, password) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, iv) ZEND_ARG_INFO(1, tag) ZEND_ARG_INFO(0, aad) ZEND_ARG_INFO(0, tag_length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_decrypt, 0, 0, 3) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, password) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, iv) ZEND_ARG_INFO(0, tag) ZEND_ARG_INFO(0, aad) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_cipher_iv_length, 0) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_dh_compute_key, 0) ZEND_ARG_INFO(0, pub_key) ZEND_ARG_INFO(0, dh_key) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_derive, 0, 0, 2) ZEND_ARG_INFO(0, peer_pub_key) ZEND_ARG_INFO(0, priv_key) ZEND_ARG_INFO(0, keylen) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_random_pseudo_bytes, 0, 0, 1) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(1, result_is_strong) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_spki_new, 0, 0, 2) ZEND_ARG_INFO(0, privkey) ZEND_ARG_INFO(0, challenge) ZEND_ARG_INFO(0, algo) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_spki_verify, 0) ZEND_ARG_INFO(0, spki) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_spki_export, 0) ZEND_ARG_INFO(0, spki) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_spki_export_challenge, 0) ZEND_ARG_INFO(0, spki) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_openssl_get_cert_locations, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ openssl_functions[] */ static const zend_function_entry openssl_functions[] = { PHP_FE(openssl_get_cert_locations, arginfo_openssl_get_cert_locations) /* spki functions */ PHP_FE(openssl_spki_new, arginfo_openssl_spki_new) PHP_FE(openssl_spki_verify, arginfo_openssl_spki_verify) PHP_FE(openssl_spki_export, arginfo_openssl_spki_export) PHP_FE(openssl_spki_export_challenge, arginfo_openssl_spki_export_challenge) /* public/private key functions */ PHP_FE(openssl_pkey_free, arginfo_openssl_pkey_free) PHP_FE(openssl_pkey_new, arginfo_openssl_pkey_new) PHP_FE(openssl_pkey_export, arginfo_openssl_pkey_export) PHP_FE(openssl_pkey_export_to_file, arginfo_openssl_pkey_export_to_file) PHP_FE(openssl_pkey_get_private, arginfo_openssl_pkey_get_private) PHP_FE(openssl_pkey_get_public, arginfo_openssl_pkey_get_public) PHP_FE(openssl_pkey_get_details, arginfo_openssl_pkey_get_details) PHP_FALIAS(openssl_free_key, openssl_pkey_free, arginfo_openssl_pkey_free) PHP_FALIAS(openssl_get_privatekey, openssl_pkey_get_private, arginfo_openssl_pkey_get_private) PHP_FALIAS(openssl_get_publickey, openssl_pkey_get_public, arginfo_openssl_pkey_get_public) /* x.509 cert funcs */ PHP_FE(openssl_x509_read, arginfo_openssl_x509_read) PHP_FE(openssl_x509_free, arginfo_openssl_x509_free) PHP_FE(openssl_x509_parse, arginfo_openssl_x509_parse) PHP_FE(openssl_x509_checkpurpose, arginfo_openssl_x509_checkpurpose) PHP_FE(openssl_x509_check_private_key, arginfo_openssl_x509_check_private_key) PHP_FE(openssl_x509_verify, arginfo_openssl_x509_verify) PHP_FE(openssl_x509_export, arginfo_openssl_x509_export) PHP_FE(openssl_x509_fingerprint, arginfo_openssl_x509_fingerprint) PHP_FE(openssl_x509_export_to_file, arginfo_openssl_x509_export_to_file) /* PKCS12 funcs */ PHP_FE(openssl_pkcs12_export, arginfo_openssl_pkcs12_export) PHP_FE(openssl_pkcs12_export_to_file, arginfo_openssl_pkcs12_export_to_file) PHP_FE(openssl_pkcs12_read, arginfo_openssl_pkcs12_read) /* CSR funcs */ PHP_FE(openssl_csr_new, arginfo_openssl_csr_new) PHP_FE(openssl_csr_export, arginfo_openssl_csr_export) PHP_FE(openssl_csr_export_to_file, arginfo_openssl_csr_export_to_file) PHP_FE(openssl_csr_sign, arginfo_openssl_csr_sign) PHP_FE(openssl_csr_get_subject, arginfo_openssl_csr_get_subject) PHP_FE(openssl_csr_get_public_key, arginfo_openssl_csr_get_public_key) PHP_FE(openssl_digest, arginfo_openssl_digest) PHP_FE(openssl_encrypt, arginfo_openssl_encrypt) PHP_FE(openssl_decrypt, arginfo_openssl_decrypt) PHP_FE(openssl_cipher_iv_length, arginfo_openssl_cipher_iv_length) PHP_FE(openssl_sign, arginfo_openssl_sign) PHP_FE(openssl_verify, arginfo_openssl_verify) PHP_FE(openssl_seal, arginfo_openssl_seal) PHP_FE(openssl_open, arginfo_openssl_open) PHP_FE(openssl_pbkdf2, arginfo_openssl_pbkdf2) /* for S/MIME handling */ PHP_FE(openssl_pkcs7_verify, arginfo_openssl_pkcs7_verify) PHP_FE(openssl_pkcs7_decrypt, arginfo_openssl_pkcs7_decrypt) PHP_FE(openssl_pkcs7_sign, arginfo_openssl_pkcs7_sign) PHP_FE(openssl_pkcs7_encrypt, arginfo_openssl_pkcs7_encrypt) PHP_FE(openssl_pkcs7_read, arginfo_openssl_pkcs7_read) PHP_FE(openssl_private_encrypt, arginfo_openssl_private_encrypt) PHP_FE(openssl_private_decrypt, arginfo_openssl_private_decrypt) PHP_FE(openssl_public_encrypt, arginfo_openssl_public_encrypt) PHP_FE(openssl_public_decrypt, arginfo_openssl_public_decrypt) PHP_FE(openssl_get_md_methods, arginfo_openssl_get_md_methods) PHP_FE(openssl_get_cipher_methods, arginfo_openssl_get_cipher_methods) #ifdef HAVE_EVP_PKEY_EC PHP_FE(openssl_get_curve_names, arginfo_openssl_get_curve_names) #endif PHP_FE(openssl_dh_compute_key, arginfo_openssl_dh_compute_key) PHP_FE(openssl_pkey_derive, arginfo_openssl_pkey_derive) PHP_FE(openssl_random_pseudo_bytes, arginfo_openssl_random_pseudo_bytes) PHP_FE(openssl_error_string, arginfo_openssl_error_string) PHP_FE_END }; /* }}} */ /* {{{ openssl_module_entry */ zend_module_entry openssl_module_entry = { STANDARD_MODULE_HEADER, "openssl", openssl_functions, PHP_MINIT(openssl), PHP_MSHUTDOWN(openssl), NULL, NULL, PHP_MINFO(openssl), PHP_OPENSSL_VERSION, PHP_MODULE_GLOBALS(openssl), PHP_GINIT(openssl), PHP_GSHUTDOWN(openssl), NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #ifdef COMPILE_DL_OPENSSL ZEND_GET_MODULE(openssl) #endif /* {{{ OpenSSL compatibility functions and macros */ #if PHP_OPENSSL_API_VERSION < 0x10100 #define EVP_PKEY_get0_RSA(_pkey) _pkey->pkey.rsa #define EVP_PKEY_get0_DH(_pkey) _pkey->pkey.dh #define EVP_PKEY_get0_DSA(_pkey) _pkey->pkey.dsa #define EVP_PKEY_get0_EC_KEY(_pkey) _pkey->pkey.ec static int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) { r->n = n; r->e = e; r->d = d; return 1; } static int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q) { r->p = p; r->q = q; return 1; } static int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) { r->dmp1 = dmp1; r->dmq1 = dmq1; r->iqmp = iqmp; return 1; } static void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d) { *n = r->n; *e = r->e; *d = r->d; } static void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q) { *p = r->p; *q = r->q; } static void RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1, const BIGNUM **iqmp) { *dmp1 = r->dmp1; *dmq1 = r->dmq1; *iqmp = r->iqmp; } static void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { *p = dh->p; *q = dh->q; *g = dh->g; } static int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { dh->p = p; dh->q = q; dh->g = g; return 1; } static void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key) { *pub_key = dh->pub_key; *priv_key = dh->priv_key; } static int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key) { dh->pub_key = pub_key; dh->priv_key = priv_key; return 1; } static void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { *p = d->p; *q = d->q; *g = d->g; } int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g) { d->p = p; d->q = q; d->g = g; return 1; } static void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key) { *pub_key = d->pub_key; *priv_key = d->priv_key; } int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key) { d->pub_key = pub_key; d->priv_key = priv_key; return 1; } static const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) { return M_ASN1_STRING_data(asn1); } #if PHP_OPENSSL_API_VERSION < 0x10002 static int X509_get_signature_nid(const X509 *x) { return OBJ_obj2nid(x->sig_alg->algorithm); } #endif #define OpenSSL_version SSLeay_version #define OPENSSL_VERSION SSLEAY_VERSION #define X509_getm_notBefore X509_get_notBefore #define X509_getm_notAfter X509_get_notAfter #define EVP_CIPHER_CTX_reset EVP_CIPHER_CTX_cleanup #endif /* }}} */ /* number conversion flags checks */ #define PHP_OPENSSL_CHECK_NUMBER_CONVERSION(_cond, _name) \ do { \ if (_cond) { \ php_error_docref(NULL, E_WARNING, #_name" is too long"); \ RETURN_FALSE; \ } \ } while(0) /* number conversion flags checks */ #define PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(_cond, _name) \ do { \ if (_cond) { \ php_error_docref(NULL, E_WARNING, #_name" is too long"); \ return NULL; \ } \ } while(0) /* check if size_t can be safely casted to int */ #define PHP_OPENSSL_CHECK_SIZE_T_TO_INT(_var, _name) \ PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_SIZE_T_INT_OVFL(_var), _name) /* check if size_t can be safely casted to int */ #define PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(_var, _name) \ PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(ZEND_SIZE_T_INT_OVFL(_var), _name) /* check if size_t can be safely casted to unsigned int */ #define PHP_OPENSSL_CHECK_SIZE_T_TO_UINT(_var, _name) \ PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_SIZE_T_UINT_OVFL(_var), _name) /* check if long can be safely casted to int */ #define PHP_OPENSSL_CHECK_LONG_TO_INT(_var, _name) \ PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_LONG_EXCEEDS_INT(_var), _name) /* check if long can be safely casted to int */ #define PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(_var, _name) \ PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(ZEND_LONG_EXCEEDS_INT(_var), _name) /* {{{ php_openssl_store_errors */ void php_openssl_store_errors() { struct php_openssl_errors *errors; int error_code = ERR_get_error(); if (!error_code) { return; } if (!OPENSSL_G(errors)) { OPENSSL_G(errors) = pecalloc(1, sizeof(struct php_openssl_errors), 1); } errors = OPENSSL_G(errors); do { errors->top = (errors->top + 1) % ERR_NUM_ERRORS; if (errors->top == errors->bottom) { errors->bottom = (errors->bottom + 1) % ERR_NUM_ERRORS; } errors->buffer[errors->top] = error_code; } while ((error_code = ERR_get_error())); } /* }}} */ static int le_key; static int le_x509; static int le_csr; static int ssl_stream_data_index; int php_openssl_get_x509_list_id(void) /* {{{ */ { return le_x509; } /* }}} */ /* {{{ resource destructors */ static void php_openssl_pkey_free(zend_resource *rsrc) { EVP_PKEY *pkey = (EVP_PKEY *)rsrc->ptr; assert(pkey != NULL); EVP_PKEY_free(pkey); } static void php_openssl_x509_free(zend_resource *rsrc) { X509 *x509 = (X509 *)rsrc->ptr; X509_free(x509); } static void php_openssl_csr_free(zend_resource *rsrc) { X509_REQ * csr = (X509_REQ*)rsrc->ptr; X509_REQ_free(csr); } /* }}} */ /* {{{ openssl open_basedir check */ inline static int php_openssl_open_base_dir_chk(char *filename) { if (php_check_open_basedir(filename)) { return -1; } return 0; } /* }}} */ php_stream* php_openssl_get_stream_from_ssl_handle(const SSL *ssl) { return (php_stream*)SSL_get_ex_data(ssl, ssl_stream_data_index); } int php_openssl_get_ssl_stream_data_index() { return ssl_stream_data_index; } /* openssl -> PHP "bridging" */ /* true global; readonly after module startup */ static char default_ssl_conf_filename[MAXPATHLEN]; struct php_x509_request { /* {{{ */ LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */ LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */ const EVP_MD * md_alg; const EVP_MD * digest; char * section_name, * config_filename, * digest_name, * extensions_section, * request_extensions_section; int priv_key_bits; int priv_key_type; int priv_key_encrypt; #ifdef HAVE_EVP_PKEY_EC int curve_name; #endif EVP_PKEY * priv_key; const EVP_CIPHER * priv_key_encrypt_cipher; }; /* }}} */ static X509 * php_openssl_x509_from_zval(zval * val, int makeresource, zend_resource **resourceval); static EVP_PKEY * php_openssl_evp_from_zval( zval * val, int public_key, char *passphrase, size_t passphrase_len, int makeresource, zend_resource **resourceval); static int php_openssl_is_private_key(EVP_PKEY* pkey); static X509_STORE * php_openssl_setup_verify(zval * calist); static STACK_OF(X509) * php_openssl_load_all_certs_from_file(char *certfile); static X509_REQ * php_openssl_csr_from_zval(zval * val, int makeresource, zend_resource ** resourceval); static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req); static void php_openssl_add_assoc_name_entry(zval * val, char * key, X509_NAME * name, int shortname) /* {{{ */ { zval *data; zval subitem, tmp; int i; char *sname; int nid; X509_NAME_ENTRY * ne; ASN1_STRING * str = NULL; ASN1_OBJECT * obj; if (key != NULL) { array_init(&subitem); } else { ZVAL_COPY_VALUE(&subitem, val); } for (i = 0; i < X509_NAME_entry_count(name); i++) { const unsigned char *to_add = NULL; int to_add_len = 0; unsigned char *to_add_buf = NULL; ne = X509_NAME_get_entry(name, i); obj = X509_NAME_ENTRY_get_object(ne); nid = OBJ_obj2nid(obj); if (shortname) { sname = (char *) OBJ_nid2sn(nid); } else { sname = (char *) OBJ_nid2ln(nid); } str = X509_NAME_ENTRY_get_data(ne); if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) { /* ASN1_STRING_to_UTF8(3): The converted data is copied into a newly allocated buffer */ to_add_len = ASN1_STRING_to_UTF8(&to_add_buf, str); to_add = to_add_buf; } else { /* ASN1_STRING_get0_data(3): Since this is an internal pointer it should not be freed or modified in any way */ to_add = ASN1_STRING_get0_data(str); to_add_len = ASN1_STRING_length(str); } if (to_add_len != -1) { if ((data = zend_hash_str_find(Z_ARRVAL(subitem), sname, strlen(sname))) != NULL) { if (Z_TYPE_P(data) == IS_ARRAY) { add_next_index_stringl(data, (const char *)to_add, to_add_len); } else if (Z_TYPE_P(data) == IS_STRING) { array_init(&tmp); add_next_index_str(&tmp, zend_string_copy(Z_STR_P(data))); add_next_index_stringl(&tmp, (const char *)to_add, to_add_len); zend_hash_str_update(Z_ARRVAL(subitem), sname, strlen(sname), &tmp); } } else { /* it might be better to expand it and pass zval from ZVAL_STRING * to zend_symtable_str_update so we do not silently drop const * but we need a test to cover this part first */ add_assoc_stringl(&subitem, sname, (char *)to_add, to_add_len); } } else { php_openssl_store_errors(); } if (to_add_buf != NULL) { OPENSSL_free(to_add_buf); } } if (key != NULL) { zend_hash_str_update(Z_ARRVAL_P(val), key, strlen(key), &subitem); } } /* }}} */ static void php_openssl_add_assoc_asn1_string(zval * val, char * key, ASN1_STRING * str) /* {{{ */ { add_assoc_stringl(val, key, (char *)str->data, str->length); } /* }}} */ static time_t php_openssl_asn1_time_to_time_t(ASN1_UTCTIME * timestr) /* {{{ */ { /* This is how the time string is formatted: snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ time_t ret; struct tm thetime; char * strbuf; char * thestr; long gmadjust = 0; size_t timestr_len; if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) { php_error_docref(NULL, E_WARNING, "illegal ASN1 data type for timestamp"); return (time_t)-1; } timestr_len = (size_t)ASN1_STRING_length(timestr); if (timestr_len != strlen((const char *)ASN1_STRING_get0_data(timestr))) { php_error_docref(NULL, E_WARNING, "illegal length in timestamp"); return (time_t)-1; } if (timestr_len < 13 && timestr_len != 11) { php_error_docref(NULL, E_WARNING, "unable to parse time string %s correctly", timestr->data); return (time_t)-1; } if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { php_error_docref(NULL, E_WARNING, "unable to parse time string %s correctly", timestr->data); return (time_t)-1; } strbuf = estrdup((const char *)ASN1_STRING_get0_data(timestr)); memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ thestr = strbuf + timestr_len - 3; if (timestr_len == 11) { thetime.tm_sec = 0; } else { thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; } thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) { thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) { thestr -= 4; thetime.tm_year = atoi(thestr) - 1900; } thetime.tm_isdst = -1; ret = mktime(&thetime); #if HAVE_STRUCT_TM_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #else /* ** If correcting for daylight savings time, we set the adjustment to ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and ** set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); #endif ret += gmadjust; efree(strbuf); return ret; } /* }}} */ static inline int php_openssl_config_check_syntax(const char * section_label, const char * config_filename, const char * section, LHASH_OF(CONF_VALUE) * config) /* {{{ */ { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_conf_lhash(&ctx, config); if (!X509V3_EXT_add_conf(config, &ctx, (char *)section, NULL)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Error loading %s section %s of %s", section_label, section, config_filename); return FAILURE; } return SUCCESS; } /* }}} */ static int php_openssl_add_oid_section(struct php_x509_request * req) /* {{{ */ { char * str; STACK_OF(CONF_VALUE) * sktmp; CONF_VALUE * cnf; int i; str = CONF_get_string(req->req_config, NULL, "oid_section"); if (str == NULL) { php_openssl_store_errors(); return SUCCESS; } sktmp = CONF_get_section(req->req_config, str); if (sktmp == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "problem loading oid section %s", str); return FAILURE; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef && OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "problem creating object %s=%s", cnf->name, cnf->value); return FAILURE; } } return SUCCESS; } /* }}} */ #define PHP_SSL_REQ_INIT(req) memset(req, 0, sizeof(*req)) #define PHP_SSL_REQ_DISPOSE(req) php_openssl_dispose_config(req) #define PHP_SSL_REQ_PARSE(req, zval) php_openssl_parse_config(req, zval) #define PHP_SSL_CONFIG_SYNTAX_CHECK(var) if (req->var && php_openssl_config_check_syntax(#var, \ req->config_filename, req->var, req->req_config) == FAILURE) return FAILURE #define SET_OPTIONAL_STRING_ARG(key, varname, defval) \ do { \ if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), key, sizeof(key)-1)) != NULL && Z_TYPE_P(item) == IS_STRING) { \ varname = Z_STRVAL_P(item); \ } else { \ varname = defval; \ if (varname == NULL) { \ php_openssl_store_errors(); \ } \ } \ } while(0) #define SET_OPTIONAL_LONG_ARG(key, varname, defval) \ if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), key, sizeof(key)-1)) != NULL && Z_TYPE_P(item) == IS_LONG) \ varname = (int)Z_LVAL_P(item); \ else \ varname = defval static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(zend_long algo); /* {{{ strip line endings from spkac */ static int php_openssl_spki_cleanup(const char *src, char *dest) { int removed = 0; while (*src) { if (*src != '\n' && *src != '\r') { *dest++ = *src; } else { ++removed; } ++src; } *dest = 0; return removed; } /* }}} */ static int php_openssl_parse_config(struct php_x509_request * req, zval * optional_args) /* {{{ */ { char * str; zval * item; SET_OPTIONAL_STRING_ARG("config", req->config_filename, default_ssl_conf_filename); SET_OPTIONAL_STRING_ARG("config_section_name", req->section_name, "req"); req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL); if (req->global_config == NULL) { php_openssl_store_errors(); } req->req_config = CONF_load(NULL, req->config_filename, NULL); if (req->req_config == NULL) { php_openssl_store_errors(); return FAILURE; } /* read in the oids */ str = CONF_get_string(req->req_config, NULL, "oid_file"); if (str == NULL) { php_openssl_store_errors(); } else if (!php_openssl_open_base_dir_chk(str)) { BIO *oid_bio = BIO_new_file(str, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); if (oid_bio) { OBJ_create_objects(oid_bio); BIO_free(oid_bio); php_openssl_store_errors(); } } if (php_openssl_add_oid_section(req) == FAILURE) { return FAILURE; } SET_OPTIONAL_STRING_ARG("digest_alg", req->digest_name, CONF_get_string(req->req_config, req->section_name, "default_md")); SET_OPTIONAL_STRING_ARG("x509_extensions", req->extensions_section, CONF_get_string(req->req_config, req->section_name, "x509_extensions")); SET_OPTIONAL_STRING_ARG("req_extensions", req->request_extensions_section, CONF_get_string(req->req_config, req->section_name, "req_extensions")); SET_OPTIONAL_LONG_ARG("private_key_bits", req->priv_key_bits, CONF_get_number(req->req_config, req->section_name, "default_bits")); SET_OPTIONAL_LONG_ARG("private_key_type", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT); if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "encrypt_key", sizeof("encrypt_key")-1)) != NULL) { req->priv_key_encrypt = Z_TYPE_P(item) == IS_TRUE ? 1 : 0; } else { str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key"); if (str == NULL) { str = CONF_get_string(req->req_config, req->section_name, "encrypt_key"); /* it is sure that there are some errrors as str was NULL for encrypt_rsa_key */ php_openssl_store_errors(); } if (str != NULL && strcmp(str, "no") == 0) { req->priv_key_encrypt = 0; } else { req->priv_key_encrypt = 1; } } if (req->priv_key_encrypt && optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "encrypt_key_cipher", sizeof("encrypt_key_cipher")-1)) != NULL && Z_TYPE_P(item) == IS_LONG ) { zend_long cipher_algo = Z_LVAL_P(item); const EVP_CIPHER* cipher = php_openssl_get_evp_cipher_from_algo(cipher_algo); if (cipher == NULL) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm for private key."); return FAILURE; } else { req->priv_key_encrypt_cipher = cipher; } } else { req->priv_key_encrypt_cipher = NULL; } /* digest alg */ if (req->digest_name == NULL) { req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md"); } if (req->digest_name != NULL) { req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); } else { php_openssl_store_errors(); } if (req->md_alg == NULL) { req->md_alg = req->digest = EVP_sha1(); php_openssl_store_errors(); } PHP_SSL_CONFIG_SYNTAX_CHECK(extensions_section); #ifdef HAVE_EVP_PKEY_EC /* set the ec group curve name */ req->curve_name = NID_undef; if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "curve_name", sizeof("curve_name")-1)) != NULL && Z_TYPE_P(item) == IS_STRING) { req->curve_name = OBJ_sn2nid(Z_STRVAL_P(item)); if (req->curve_name == NID_undef) { php_error_docref(NULL, E_WARNING, "Unknown elliptic curve (short) name %s", Z_STRVAL_P(item)); return FAILURE; } } #endif /* set the string mask */ str = CONF_get_string(req->req_config, req->section_name, "string_mask"); if (str == NULL) { php_openssl_store_errors(); } else if (!ASN1_STRING_set_default_mask_asc(str)) { php_error_docref(NULL, E_WARNING, "Invalid global string mask setting %s", str); return FAILURE; } PHP_SSL_CONFIG_SYNTAX_CHECK(request_extensions_section); return SUCCESS; } /* }}} */ static void php_openssl_dispose_config(struct php_x509_request * req) /* {{{ */ { if (req->priv_key) { EVP_PKEY_free(req->priv_key); req->priv_key = NULL; } if (req->global_config) { CONF_free(req->global_config); req->global_config = NULL; } if (req->req_config) { CONF_free(req->req_config); req->req_config = NULL; } } /* }}} */ #if defined(PHP_WIN32) || PHP_OPENSSL_API_VERSION >= 0x10100 #define PHP_OPENSSL_RAND_ADD_TIME() ((void) 0) #else #define PHP_OPENSSL_RAND_ADD_TIME() php_openssl_rand_add_timeval() static inline void php_openssl_rand_add_timeval() /* {{{ */ { struct timeval tv; gettimeofday(&tv, NULL); RAND_add(&tv, sizeof(tv), 0.0); } /* }}} */ #endif static int php_openssl_load_rand_file(const char * file, int *egdsocket, int *seeded) /* {{{ */ { char buffer[MAXPATHLEN]; *egdsocket = 0; *seeded = 0; if (file == NULL) { file = RAND_file_name(buffer, sizeof(buffer)); #ifdef HAVE_RAND_EGD } else if (RAND_egd(file) > 0) { /* if the given filename is an EGD socket, don't * write anything back to it */ *egdsocket = 1; return SUCCESS; #endif } if (file == NULL || !RAND_load_file(file, -1)) { if (RAND_status() == 0) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "unable to load random state; not enough random data!"); return FAILURE; } return FAILURE; } *seeded = 1; return SUCCESS; } /* }}} */ static int php_openssl_write_rand_file(const char * file, int egdsocket, int seeded) /* {{{ */ { char buffer[MAXPATHLEN]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return FAILURE; } if (file == NULL) { file = RAND_file_name(buffer, sizeof(buffer)); } PHP_OPENSSL_RAND_ADD_TIME(); if (file == NULL || !RAND_write_file(file)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "unable to write random state"); return FAILURE; } return SUCCESS; } /* }}} */ static EVP_MD * php_openssl_get_evp_md_from_algo(zend_long algo) { /* {{{ */ EVP_MD *mdtype; switch (algo) { case OPENSSL_ALGO_SHA1: mdtype = (EVP_MD *) EVP_sha1(); break; case OPENSSL_ALGO_MD5: mdtype = (EVP_MD *) EVP_md5(); break; case OPENSSL_ALGO_MD4: mdtype = (EVP_MD *) EVP_md4(); break; #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: mdtype = (EVP_MD *) EVP_md2(); break; #endif #if PHP_OPENSSL_API_VERSION < 0x10100 case OPENSSL_ALGO_DSS1: mdtype = (EVP_MD *) EVP_dss1(); break; #endif case OPENSSL_ALGO_SHA224: mdtype = (EVP_MD *) EVP_sha224(); break; case OPENSSL_ALGO_SHA256: mdtype = (EVP_MD *) EVP_sha256(); break; case OPENSSL_ALGO_SHA384: mdtype = (EVP_MD *) EVP_sha384(); break; case OPENSSL_ALGO_SHA512: mdtype = (EVP_MD *) EVP_sha512(); break; case OPENSSL_ALGO_RMD160: mdtype = (EVP_MD *) EVP_ripemd160(); break; default: return NULL; break; } return mdtype; } /* }}} */ static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(zend_long algo) { /* {{{ */ switch (algo) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: return EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: return EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: return EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: return EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: return EVP_des_ede3_cbc(); break; #endif #ifndef OPENSSL_NO_AES case PHP_OPENSSL_CIPHER_AES_128_CBC: return EVP_aes_128_cbc(); break; case PHP_OPENSSL_CIPHER_AES_192_CBC: return EVP_aes_192_cbc(); break; case PHP_OPENSSL_CIPHER_AES_256_CBC: return EVP_aes_256_cbc(); break; #endif default: return NULL; break; } } /* }}} */ /* {{{ INI Settings */ PHP_INI_BEGIN() PHP_INI_ENTRY("openssl.cafile", NULL, PHP_INI_PERDIR, NULL) PHP_INI_ENTRY("openssl.capath", NULL, PHP_INI_PERDIR, NULL) PHP_INI_END() /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(openssl) { char * config_filename; le_key = zend_register_list_destructors_ex(php_openssl_pkey_free, NULL, "OpenSSL key", module_number); le_x509 = zend_register_list_destructors_ex(php_openssl_x509_free, NULL, "OpenSSL X.509", module_number); le_csr = zend_register_list_destructors_ex(php_openssl_csr_free, NULL, "OpenSSL X.509 CSR", module_number); #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER) OPENSSL_config(NULL); SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); OpenSSL_add_all_algorithms(); #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && OPENSSL_VERSION_NUMBER < 0x100020000 EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_256_ccm()); #endif SSL_load_error_strings(); #else OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL); #endif /* register a resource id number with OpenSSL so that we can map SSL -> stream structures in * OpenSSL callbacks */ ssl_stream_data_index = SSL_get_ex_new_index(0, "PHP stream index", NULL, NULL, NULL); REGISTER_STRING_CONSTANT("OPENSSL_VERSION_TEXT", OPENSSL_VERSION_TEXT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_VERSION_NUMBER", OPENSSL_VERSION_NUMBER, CONST_CS|CONST_PERSISTENT); /* purposes for cert purpose checking */ REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_CLIENT", X509_PURPOSE_SSL_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_SERVER", X509_PURPOSE_SSL_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("X509_PURPOSE_NS_SSL_SERVER", X509_PURPOSE_NS_SSL_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_SIGN", X509_PURPOSE_SMIME_SIGN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_ENCRYPT", X509_PURPOSE_SMIME_ENCRYPT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("X509_PURPOSE_CRL_SIGN", X509_PURPOSE_CRL_SIGN, CONST_CS|CONST_PERSISTENT); #ifdef X509_PURPOSE_ANY REGISTER_LONG_CONSTANT("X509_PURPOSE_ANY", X509_PURPOSE_ANY, CONST_CS|CONST_PERSISTENT); #endif /* signature algorithm constants */ REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA1", OPENSSL_ALGO_SHA1, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD5", OPENSSL_ALGO_MD5, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD4", OPENSSL_ALGO_MD4, CONST_CS|CONST_PERSISTENT); #ifdef HAVE_OPENSSL_MD2_H REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD2", OPENSSL_ALGO_MD2, CONST_CS|CONST_PERSISTENT); #endif #if PHP_OPENSSL_API_VERSION < 0x10100 REGISTER_LONG_CONSTANT("OPENSSL_ALGO_DSS1", OPENSSL_ALGO_DSS1, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA224", OPENSSL_ALGO_SHA224, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA256", OPENSSL_ALGO_SHA256, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA384", OPENSSL_ALGO_SHA384, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA512", OPENSSL_ALGO_SHA512, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ALGO_RMD160", OPENSSL_ALGO_RMD160, CONST_CS|CONST_PERSISTENT); /* flags for S/MIME */ REGISTER_LONG_CONSTANT("PKCS7_DETACHED", PKCS7_DETACHED, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_TEXT", PKCS7_TEXT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOINTERN", PKCS7_NOINTERN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOVERIFY", PKCS7_NOVERIFY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOCHAIN", PKCS7_NOCHAIN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOCERTS", PKCS7_NOCERTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOATTR", PKCS7_NOATTR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_BINARY", PKCS7_BINARY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PKCS7_NOSIGS", PKCS7_NOSIGS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_PADDING", RSA_PKCS1_PADDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_SSLV23_PADDING", RSA_SSLV23_PADDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_NO_PADDING", RSA_NO_PADDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_OAEP_PADDING", RSA_PKCS1_OAEP_PADDING, CONST_CS|CONST_PERSISTENT); /* Informational stream wrapper constants */ REGISTER_STRING_CONSTANT("OPENSSL_DEFAULT_STREAM_CIPHERS", OPENSSL_DEFAULT_STREAM_CIPHERS, CONST_CS|CONST_PERSISTENT); /* Ciphers */ #ifndef OPENSSL_NO_RC2 REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_40", PHP_OPENSSL_CIPHER_RC2_40, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_128", PHP_OPENSSL_CIPHER_RC2_128, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_64", PHP_OPENSSL_CIPHER_RC2_64, CONST_CS|CONST_PERSISTENT); #endif #ifndef OPENSSL_NO_DES REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_DES", PHP_OPENSSL_CIPHER_DES, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_3DES", PHP_OPENSSL_CIPHER_3DES, CONST_CS|CONST_PERSISTENT); #endif #ifndef OPENSSL_NO_AES REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_128_CBC", PHP_OPENSSL_CIPHER_AES_128_CBC, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_192_CBC", PHP_OPENSSL_CIPHER_AES_192_CBC, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_256_CBC", PHP_OPENSSL_CIPHER_AES_256_CBC, CONST_CS|CONST_PERSISTENT); #endif /* Values for key types */ REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_RSA", OPENSSL_KEYTYPE_RSA, CONST_CS|CONST_PERSISTENT); #ifndef NO_DSA REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DSA", OPENSSL_KEYTYPE_DSA, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DH", OPENSSL_KEYTYPE_DH, CONST_CS|CONST_PERSISTENT); #ifdef HAVE_EVP_PKEY_EC REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_EC", OPENSSL_KEYTYPE_EC, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("OPENSSL_RAW_DATA", OPENSSL_RAW_DATA, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_ZERO_PADDING", OPENSSL_ZERO_PADDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("OPENSSL_DONT_ZERO_PAD_KEY", OPENSSL_DONT_ZERO_PAD_KEY, CONST_CS|CONST_PERSISTENT); #ifndef OPENSSL_NO_TLSEXT /* SNI support included */ REGISTER_LONG_CONSTANT("OPENSSL_TLSEXT_SERVER_NAME", 1, CONST_CS|CONST_PERSISTENT); #endif /* Determine default SSL configuration file */ config_filename = getenv("OPENSSL_CONF"); if (config_filename == NULL) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == NULL) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { strlcpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename)); } php_stream_xport_register("ssl", php_openssl_ssl_socket_factory); #ifndef OPENSSL_NO_SSL3 php_stream_xport_register("sslv3", php_openssl_ssl_socket_factory); #endif php_stream_xport_register("tls", php_openssl_ssl_socket_factory); php_stream_xport_register("tlsv1.0", php_openssl_ssl_socket_factory); php_stream_xport_register("tlsv1.1", php_openssl_ssl_socket_factory); php_stream_xport_register("tlsv1.2", php_openssl_ssl_socket_factory); #if OPENSSL_VERSION_NUMBER >= 0x10101000 php_stream_xport_register("tlsv1.3", php_openssl_ssl_socket_factory); #endif /* override the default tcp socket provider */ php_stream_xport_register("tcp", php_openssl_ssl_socket_factory); php_register_url_stream_wrapper("https", &php_stream_http_wrapper); php_register_url_stream_wrapper("ftps", &php_stream_ftp_wrapper); REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ PHP_GINIT_FUNCTION(openssl) { #if defined(COMPILE_DL_OPENSSL) && defined(ZTS) ZEND_TSRMLS_CACHE_UPDATE(); #endif openssl_globals->errors = NULL; } /* }}} */ /* {{{ PHP_GSHUTDOWN_FUNCTION */ PHP_GSHUTDOWN_FUNCTION(openssl) { if (openssl_globals->errors) { pefree(openssl_globals->errors, 1); } } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(openssl) { php_info_print_table_start(); php_info_print_table_row(2, "OpenSSL support", "enabled"); php_info_print_table_row(2, "OpenSSL Library Version", OpenSSL_version(OPENSSL_VERSION)); php_info_print_table_row(2, "OpenSSL Header Version", OPENSSL_VERSION_TEXT); php_info_print_table_row(2, "Openssl default config", default_ssl_conf_filename); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(openssl) { #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER) EVP_cleanup(); /* prevent accessing locking callback from unloaded extension */ CRYPTO_set_locking_callback(NULL); /* free allocated error strings */ ERR_free_strings(); CONF_modules_free(); #endif php_unregister_url_stream_wrapper("https"); php_unregister_url_stream_wrapper("ftps"); php_stream_xport_unregister("ssl"); #ifndef OPENSSL_NO_SSL3 php_stream_xport_unregister("sslv3"); #endif php_stream_xport_unregister("tls"); php_stream_xport_unregister("tlsv1.0"); php_stream_xport_unregister("tlsv1.1"); php_stream_xport_unregister("tlsv1.2"); #if OPENSSL_VERSION_NUMBER >= 0x10101000 php_stream_xport_unregister("tlsv1.3"); #endif /* reinstate the default tcp handler */ php_stream_xport_register("tcp", php_stream_generic_socket_factory); UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ x509 cert functions */ /* {{{ proto array openssl_get_cert_locations(void) Retrieve an array mapping available certificate locations */ PHP_FUNCTION(openssl_get_cert_locations) { array_init(return_value); add_assoc_string(return_value, "default_cert_file", (char *) X509_get_default_cert_file()); add_assoc_string(return_value, "default_cert_file_env", (char *) X509_get_default_cert_file_env()); add_assoc_string(return_value, "default_cert_dir", (char *) X509_get_default_cert_dir()); add_assoc_string(return_value, "default_cert_dir_env", (char *) X509_get_default_cert_dir_env()); add_assoc_string(return_value, "default_private_dir", (char *) X509_get_default_private_dir()); add_assoc_string(return_value, "default_default_cert_area", (char *) X509_get_default_cert_area()); add_assoc_string(return_value, "ini_cafile", zend_ini_string("openssl.cafile", sizeof("openssl.cafile")-1, 0)); add_assoc_string(return_value, "ini_capath", zend_ini_string("openssl.capath", sizeof("openssl.capath")-1, 0)); } /* }}} */ /* {{{ php_openssl_x509_from_zval Given a zval, coerce it into an X509 object. The zval can be: . X509 resource created using openssl_read_x509() . if it starts with file:// then it will be interpreted as the path to that cert . it will be interpreted as the cert data If you supply makeresource, the result will be registered as an x509 resource and it's value returned in makeresource. */ static X509 * php_openssl_x509_from_zval(zval * val, int makeresource, zend_resource **resourceval) { X509 *cert = NULL; BIO *in; if (resourceval) { *resourceval = NULL; } if (Z_TYPE_P(val) == IS_RESOURCE) { /* is it an x509 resource ? */ void * what; zend_resource *res = Z_RES_P(val); what = zend_fetch_resource(res, "OpenSSL X.509", le_x509); if (!what) { return NULL; } if (resourceval) { *resourceval = res; if (makeresource) { Z_ADDREF_P(val); } } return (X509*)what; } if (!(Z_TYPE_P(val) == IS_STRING || Z_TYPE_P(val) == IS_OBJECT)) { return NULL; } /* force it to be a string and check if it refers to a file */ if (!try_convert_to_string(val)) { return NULL; } if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) { if (php_openssl_open_base_dir_chk(Z_STRVAL_P(val) + (sizeof("file://") - 1))) { return NULL; } in = BIO_new_file(Z_STRVAL_P(val) + (sizeof("file://") - 1), PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); if (in == NULL) { php_openssl_store_errors(); return NULL; } cert = PEM_read_bio_X509(in, NULL, NULL, NULL); } else { in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val)); if (in == NULL) { php_openssl_store_errors(); return NULL; } #ifdef TYPEDEF_D2I_OF cert = (X509 *) PEM_ASN1_read_bio((d2i_of_void *)d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL); #else cert = (X509 *) PEM_ASN1_read_bio((char *(*)())d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL); #endif } if (!BIO_free(in)) { php_openssl_store_errors(); } if (cert == NULL) { php_openssl_store_errors(); return NULL; } if (makeresource && resourceval) { *resourceval = zend_register_resource(cert, le_x509); } return cert; } /* }}} */ /* {{{ proto bool openssl_x509_export_to_file(mixed x509, string outfilename [, bool notext = true]) Exports a CERT to file or a var */ PHP_FUNCTION(openssl_x509_export_to_file) { X509 * cert; zval * zcert; zend_bool notext = 1; BIO * bio_out; char * filename; size_t filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zp|b", &zcert, &filename, &filename_len, &notext) == FAILURE) { return; } RETVAL_FALSE; cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 1"); return; } if (php_openssl_open_base_dir_chk(filename)) { return; } bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (bio_out) { if (!notext && !X509_print(bio_out, cert)) { php_openssl_store_errors(); } if (!PEM_write_bio_X509(bio_out, cert)) { php_openssl_store_errors(); } RETVAL_TRUE; } else { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening file %s", filename); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } if (!BIO_free(bio_out)) { php_openssl_store_errors(); } } /* }}} */ /* {{{ proto string openssl_spki_new(mixed zpkey, string challenge [, mixed method]) Creates new private key (or uses existing) and creates a new spki cert outputting results to var */ PHP_FUNCTION(openssl_spki_new) { size_t challenge_len; char * challenge = NULL, * spkstr = NULL; zend_string * s = NULL; zend_resource *keyresource = NULL; const char *spkac = "SPKAC="; zend_long algo = OPENSSL_ALGO_MD5; zval *method = NULL; zval * zpkey = NULL; EVP_PKEY * pkey = NULL; NETSCAPE_SPKI *spki=NULL; const EVP_MD *mdtype; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|z", &zpkey, &challenge, &challenge_len, &method) == FAILURE) { return; } RETVAL_FALSE; PHP_OPENSSL_CHECK_SIZE_T_TO_INT(challenge_len, challenge); pkey = php_openssl_evp_from_zval(zpkey, 0, challenge, challenge_len, 1, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "Unable to use supplied private key"); goto cleanup; } if (method != NULL) { if (Z_TYPE_P(method) == IS_LONG) { algo = Z_LVAL_P(method); } else { php_error_docref(NULL, E_WARNING, "Algorithm must be of supported type"); goto cleanup; } } mdtype = php_openssl_get_evp_md_from_algo(algo); if (!mdtype) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm"); goto cleanup; } if ((spki = NETSCAPE_SPKI_new()) == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to create new SPKAC"); goto cleanup; } if (challenge) { if (!ASN1_STRING_set(spki->spkac->challenge, challenge, (int)challenge_len)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to set challenge data"); goto cleanup; } } if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to embed public key"); goto cleanup; } if (!NETSCAPE_SPKI_sign(spki, pkey, mdtype)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to sign with specified algorithm"); goto cleanup; } spkstr = NETSCAPE_SPKI_b64_encode(spki); if (!spkstr){ php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to encode SPKAC"); goto cleanup; } s = zend_string_alloc(strlen(spkac) + strlen(spkstr), 0); sprintf(ZSTR_VAL(s), "%s%s", spkac, spkstr); ZSTR_LEN(s) = strlen(ZSTR_VAL(s)); OPENSSL_free(spkstr); RETVAL_STR(s); goto cleanup; cleanup: if (spki != NULL) { NETSCAPE_SPKI_free(spki); } if (keyresource == NULL && pkey != NULL) { EVP_PKEY_free(pkey); } if (s && ZSTR_LEN(s) <= 0) { RETVAL_FALSE; } if (keyresource == NULL && s != NULL) { zend_string_release_ex(s, 0); } } /* }}} */ /* {{{ proto bool openssl_spki_verify(string spki) Verifies spki returns boolean */ PHP_FUNCTION(openssl_spki_verify) { size_t spkstr_len; int i = 0, spkstr_cleaned_len = 0; char *spkstr, * spkstr_cleaned = NULL; EVP_PKEY *pkey = NULL; NETSCAPE_SPKI *spki = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) { return; } RETVAL_FALSE; spkstr_cleaned = emalloc(spkstr_len + 1); spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned)); if (spkstr_cleaned_len == 0) { php_error_docref(NULL, E_WARNING, "Invalid SPKAC"); goto cleanup; } spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len); if (spki == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to decode supplied SPKAC"); goto cleanup; } pkey = X509_PUBKEY_get(spki->spkac->pubkey); if (pkey == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to acquire signed public key"); goto cleanup; } i = NETSCAPE_SPKI_verify(spki, pkey); goto cleanup; cleanup: if (spki != NULL) { NETSCAPE_SPKI_free(spki); } if (pkey != NULL) { EVP_PKEY_free(pkey); } if (spkstr_cleaned != NULL) { efree(spkstr_cleaned); } if (i > 0) { RETVAL_TRUE; } else { php_openssl_store_errors(); } } /* }}} */ /* {{{ proto string openssl_spki_export(string spki) Exports public key from existing spki to var */ PHP_FUNCTION(openssl_spki_export) { size_t spkstr_len; char *spkstr, * spkstr_cleaned = NULL, * s = NULL; int spkstr_cleaned_len; EVP_PKEY *pkey = NULL; NETSCAPE_SPKI *spki = NULL; BIO *out = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) { return; } RETVAL_FALSE; spkstr_cleaned = emalloc(spkstr_len + 1); spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned)); if (spkstr_cleaned_len == 0) { php_error_docref(NULL, E_WARNING, "Invalid SPKAC"); goto cleanup; } spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len); if (spki == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to decode supplied SPKAC"); goto cleanup; } pkey = X509_PUBKEY_get(spki->spkac->pubkey); if (pkey == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to acquire signed public key"); goto cleanup; } out = BIO_new(BIO_s_mem()); if (out && PEM_write_bio_PUBKEY(out, pkey)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(out, &bio_buf); RETVAL_STRINGL((char *)bio_buf->data, bio_buf->length); } else { php_openssl_store_errors(); } goto cleanup; cleanup: if (spki != NULL) { NETSCAPE_SPKI_free(spki); } if (out != NULL) { BIO_free_all(out); } if (pkey != NULL) { EVP_PKEY_free(pkey); } if (spkstr_cleaned != NULL) { efree(spkstr_cleaned); } if (s != NULL) { efree(s); } } /* }}} */ /* {{{ proto string openssl_spki_export_challenge(string spki) Exports spkac challenge from existing spki to var */ PHP_FUNCTION(openssl_spki_export_challenge) { size_t spkstr_len; char *spkstr, * spkstr_cleaned = NULL; int spkstr_cleaned_len; NETSCAPE_SPKI *spki = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) { return; } RETVAL_FALSE; spkstr_cleaned = emalloc(spkstr_len + 1); spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned)); if (spkstr_cleaned_len == 0) { php_error_docref(NULL, E_WARNING, "Invalid SPKAC"); goto cleanup; } spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len); if (spki == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Unable to decode SPKAC"); goto cleanup; } RETVAL_STRING((const char *)ASN1_STRING_get0_data(spki->spkac->challenge)); goto cleanup; cleanup: if (spkstr_cleaned != NULL) { efree(spkstr_cleaned); } if (spki) { NETSCAPE_SPKI_free(spki); } } /* }}} */ /* {{{ proto bool openssl_x509_export(mixed x509, string &out [, bool notext = true]) Exports a CERT to file or a var */ PHP_FUNCTION(openssl_x509_export) { X509 * cert; zval * zcert, *zout; zend_bool notext = 1; BIO * bio_out; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|b", &zcert, &zout, &notext) == FAILURE) { return; } RETVAL_FALSE; cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 1"); return; } bio_out = BIO_new(BIO_s_mem()); if (!bio_out) { php_openssl_store_errors(); goto cleanup; } if (!notext && !X509_print(bio_out, cert)) { php_openssl_store_errors(); } if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length); RETVAL_TRUE; } else { php_openssl_store_errors(); } BIO_free(bio_out); cleanup: if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* }}} */ zend_string* php_openssl_x509_fingerprint(X509 *peer, const char *method, zend_bool raw) { unsigned char md[EVP_MAX_MD_SIZE]; const EVP_MD *mdtype; unsigned int n; zend_string *ret; if (!(mdtype = EVP_get_digestbyname(method))) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm"); return NULL; } else if (!X509_digest(peer, mdtype, md, &n)) { php_openssl_store_errors(); php_error_docref(NULL, E_ERROR, "Could not generate signature"); return NULL; } if (raw) { ret = zend_string_init((char*)md, n, 0); } else { ret = zend_string_alloc(n * 2, 0); make_digest_ex(ZSTR_VAL(ret), md, n); ZSTR_VAL(ret)[n * 2] = '\0'; } return ret; } PHP_FUNCTION(openssl_x509_fingerprint) { X509 *cert; zval *zcert; zend_bool raw_output = 0; char *method = "sha1"; size_t method_len; zend_string *fingerprint; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|sb", &zcert, &method, &method_len, &raw_output) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 1"); RETURN_FALSE; } fingerprint = php_openssl_x509_fingerprint(cert, method, raw_output); if (fingerprint) { RETVAL_STR(fingerprint); } else { RETVAL_FALSE; } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* {{{ proto bool openssl_x509_check_private_key(mixed cert, mixed key) Checks if a private key corresponds to a CERT */ PHP_FUNCTION(openssl_x509_check_private_key) { zval * zcert, *zkey; X509 * cert = NULL; EVP_PKEY * key = NULL; zend_resource *keyresource = NULL; RETVAL_FALSE; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zcert, &zkey) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { RETURN_FALSE; } key = php_openssl_evp_from_zval(zkey, 0, "", 0, 1, &keyresource); if (key) { RETVAL_BOOL(X509_check_private_key(cert, key)); } if (keyresource == NULL && key) { EVP_PKEY_free(key); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* }}} */ /* {{{ proto int openssl_x509_verify(mixed cert, mixed key) Verifies the signature of certificate cert using public key key */ PHP_FUNCTION(openssl_x509_verify) { zval * zcert, *zkey; X509 * cert = NULL; EVP_PKEY * key = NULL; zend_resource *keyresource = NULL; int err = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zcert, &zkey) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { RETURN_LONG(err); } key = php_openssl_evp_from_zval(zkey, 1, NULL, 0, 0, &keyresource); if (key == NULL) { X509_free(cert); RETURN_LONG(err); } err = X509_verify(cert, key); if (err < 0) { php_openssl_store_errors(); } if (keyresource == NULL && key) { EVP_PKEY_free(key); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } RETURN_LONG(err); } /* }}} */ /* Special handling of subjectAltName, see CVE-2013-4073 * Christian Heimes */ static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension) { GENERAL_NAMES *names; const X509V3_EXT_METHOD *method = NULL; ASN1_OCTET_STRING *extension_data; long i, length, num; const unsigned char *p; method = X509V3_EXT_get(extension); if (method == NULL) { return -1; } extension_data = X509_EXTENSION_get_data(extension); p = extension_data->data; length = extension_data->length; if (method->it) { names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, &p, length, ASN1_ITEM_ptr(method->it))); } else { names = (GENERAL_NAMES*) (method->d2i(NULL, &p, length)); } if (names == NULL) { php_openssl_store_errors(); return -1; } num = sk_GENERAL_NAME_num(names); for (i = 0; i < num; i++) { GENERAL_NAME *name; ASN1_STRING *as; name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: BIO_puts(bio, "email:"); as = name->d.rfc822Name; BIO_write(bio, ASN1_STRING_get0_data(as), ASN1_STRING_length(as)); break; case GEN_DNS: BIO_puts(bio, "DNS:"); as = name->d.dNSName; BIO_write(bio, ASN1_STRING_get0_data(as), ASN1_STRING_length(as)); break; case GEN_URI: BIO_puts(bio, "URI:"); as = name->d.uniformResourceIdentifier; BIO_write(bio, ASN1_STRING_get0_data(as), ASN1_STRING_length(as)); break; default: /* use builtin print for GEN_OTHERNAME, GEN_X400, * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID */ GENERAL_NAME_print(bio, name); } /* trailing ', ' except for last element */ if (i < (num - 1)) { BIO_puts(bio, ", "); } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); return 0; } /* {{{ proto array openssl_x509_parse(mixed x509 [, bool shortnames=true]) Returns an array of the fields/values of the CERT */ PHP_FUNCTION(openssl_x509_parse) { zval * zcert; X509 * cert = NULL; int i, sig_nid; zend_bool useshortnames = 1; char * tmpstr; zval subitem; X509_EXTENSION *extension; X509_NAME *subject_name; char *cert_name; char *extname; BIO *bio_out; BUF_MEM *bio_buf; ASN1_INTEGER *asn1_serial; BIGNUM *bn_serial; char *str_serial; char *hex_serial; char buf[256]; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcert, &useshortnames) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { RETURN_FALSE; } array_init(return_value); subject_name = X509_get_subject_name(cert); cert_name = X509_NAME_oneline(subject_name, NULL, 0); add_assoc_string(return_value, "name", cert_name); OPENSSL_free(cert_name); php_openssl_add_assoc_name_entry(return_value, "subject", subject_name, useshortnames); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); add_assoc_string(return_value, "hash", buf); } php_openssl_add_assoc_name_entry(return_value, "issuer", X509_get_issuer_name(cert), useshortnames); add_assoc_long(return_value, "version", X509_get_version(cert)); asn1_serial = X509_get_serialNumber(cert); bn_serial = ASN1_INTEGER_to_BN(asn1_serial, NULL); /* Can return NULL on error or memory allocation failure */ if (!bn_serial) { php_openssl_store_errors(); RETURN_FALSE; } hex_serial = BN_bn2hex(bn_serial); BN_free(bn_serial); /* Can return NULL on error or memory allocation failure */ if (!hex_serial) { php_openssl_store_errors(); RETURN_FALSE; } str_serial = i2s_ASN1_INTEGER(NULL, asn1_serial); add_assoc_string(return_value, "serialNumber", str_serial); OPENSSL_free(str_serial); /* Return the hex representation of the serial number, as defined by OpenSSL */ add_assoc_string(return_value, "serialNumberHex", hex_serial); OPENSSL_free(hex_serial); php_openssl_add_assoc_asn1_string(return_value, "validFrom", X509_getm_notBefore(cert)); php_openssl_add_assoc_asn1_string(return_value, "validTo", X509_getm_notAfter(cert)); add_assoc_long(return_value, "validFrom_time_t", php_openssl_asn1_time_to_time_t(X509_getm_notBefore(cert))); add_assoc_long(return_value, "validTo_time_t", php_openssl_asn1_time_to_time_t(X509_getm_notAfter(cert))); tmpstr = (char *)X509_alias_get0(cert, NULL); if (tmpstr) { add_assoc_string(return_value, "alias", tmpstr); } sig_nid = X509_get_signature_nid(cert); add_assoc_string(return_value, "signatureTypeSN", (char*)OBJ_nid2sn(sig_nid)); add_assoc_string(return_value, "signatureTypeLN", (char*)OBJ_nid2ln(sig_nid)); add_assoc_long(return_value, "signatureTypeNID", sig_nid); array_init(&subitem); /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ for (i = 0; i < X509_PURPOSE_get_count(); i++) { int id, purpset; char * pname; X509_PURPOSE * purp; zval subsub; array_init(&subsub); purp = X509_PURPOSE_get0(i); id = X509_PURPOSE_get_id(purp); purpset = X509_check_purpose(cert, id, 0); add_index_bool(&subsub, 0, purpset); purpset = X509_check_purpose(cert, id, 1); add_index_bool(&subsub, 1, purpset); pname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); add_index_string(&subsub, 2, pname); /* NOTE: if purpset > 1 then it's a warning - we should mention it ? */ add_index_zval(&subitem, id, &subsub); } add_assoc_zval(return_value, "purposes", &subitem); array_init(&subitem); for (i = 0; i < X509_get_ext_count(cert); i++) { int nid; extension = X509_get_ext(cert, i); nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); if (nid != NID_undef) { extname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } bio_out = BIO_new(BIO_s_mem()); if (bio_out == NULL) { php_openssl_store_errors(); RETURN_FALSE; } if (nid == NID_subject_alt_name) { if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) { BIO_get_mem_ptr(bio_out, &bio_buf); add_assoc_stringl(&subitem, extname, bio_buf->data, bio_buf->length); } else { zend_array_destroy(Z_ARR_P(return_value)); BIO_free(bio_out); if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } RETURN_FALSE; } } else if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BIO_get_mem_ptr(bio_out, &bio_buf); add_assoc_stringl(&subitem, extname, bio_buf->data, bio_buf->length); } else { php_openssl_add_assoc_asn1_string(&subitem, extname, X509_EXTENSION_get_data(extension)); } BIO_free(bio_out); } add_assoc_zval(return_value, "extensions", &subitem); if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* }}} */ /* {{{ php_openssl_load_all_certs_from_file */ static STACK_OF(X509) *php_openssl_load_all_certs_from_file(char *certfile) { STACK_OF(X509_INFO) *sk=NULL; STACK_OF(X509) *stack=NULL, *ret=NULL; BIO *in=NULL; X509_INFO *xi; if(!(stack = sk_X509_new_null())) { php_openssl_store_errors(); php_error_docref(NULL, E_ERROR, "memory allocation failure"); goto end; } if (php_openssl_open_base_dir_chk(certfile)) { sk_X509_free(stack); goto end; } if (!(in=BIO_new_file(certfile, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)))) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening the file, %s", certfile); sk_X509_free(stack); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ if (!(sk=PEM_X509_INFO_read_bio(in, NULL, NULL, NULL))) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error reading the file, %s", certfile); sk_X509_free(stack); goto end; } /* scan over it and pull out the certs */ while (sk_X509_INFO_num(sk)) { xi=sk_X509_INFO_shift(sk); if (xi->x509 != NULL) { sk_X509_push(stack,xi->x509); xi->x509=NULL; } X509_INFO_free(xi); } if (!sk_X509_num(stack)) { php_error_docref(NULL, E_WARNING, "no certificates in file, %s", certfile); sk_X509_free(stack); goto end; } ret = stack; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; } /* }}} */ /* {{{ check_cert */ static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose) { int ret=0; X509_STORE_CTX *csc; csc = X509_STORE_CTX_new(); if (csc == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_ERROR, "memory allocation failure"); return 0; } if (!X509_STORE_CTX_init(csc, ctx, x, untrustedchain)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "cert store initialization failed"); return 0; } if (purpose >= 0 && !X509_STORE_CTX_set_purpose(csc, purpose)) { php_openssl_store_errors(); } ret = X509_verify_cert(csc); if (ret < 0) { php_openssl_store_errors(); } X509_STORE_CTX_free(csc); return ret; } /* }}} */ /* {{{ proto int openssl_x509_checkpurpose(mixed x509cert, int purpose, array cainfo [, string untrustedfile]) Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs */ PHP_FUNCTION(openssl_x509_checkpurpose) { zval * zcert, * zcainfo = NULL; X509_STORE * cainfo = NULL; X509 * cert = NULL; STACK_OF(X509) * untrustedchain = NULL; zend_long purpose; char * untrusted = NULL; size_t untrusted_len = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zl|a!s", &zcert, &purpose, &zcainfo, &untrusted, &untrusted_len) == FAILURE) { return; } RETVAL_LONG(-1); if (untrusted) { untrustedchain = php_openssl_load_all_certs_from_file(untrusted); if (untrustedchain == NULL) { goto clean_exit; } } cainfo = php_openssl_setup_verify(zcainfo); if (cainfo == NULL) { goto clean_exit; } cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { goto clean_exit; } ret = check_cert(cainfo, cert, untrustedchain, (int)purpose); if (ret != 0 && ret != 1) { RETVAL_LONG(ret); } else { RETVAL_BOOL(ret); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } clean_exit: if (cainfo) { X509_STORE_free(cainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } } /* }}} */ /* {{{ php_openssl_setup_verify * calist is an array containing file and directory names. create a * certificate store and add those certs to it for use in verification. */ static X509_STORE *php_openssl_setup_verify(zval *calist) { X509_STORE *store; X509_LOOKUP * dir_lookup, * file_lookup; int ndirs = 0, nfiles = 0; zval * item; zend_stat_t sb; store = X509_STORE_new(); if (store == NULL) { php_openssl_store_errors(); return NULL; } if (calist && (Z_TYPE_P(calist) == IS_ARRAY)) { ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(calist), item) { zend_string *str = zval_try_get_string(item); if (UNEXPECTED(!str)) { return NULL; } if (VCWD_STAT(ZSTR_VAL(str), &sb) == -1) { php_error_docref(NULL, E_WARNING, "unable to stat %s", ZSTR_VAL(str)); zend_string_release(str); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, ZSTR_VAL(str), X509_FILETYPE_PEM)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error loading file %s", ZSTR_VAL(str)); } else { nfiles++; } file_lookup = NULL; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, ZSTR_VAL(str), X509_FILETYPE_PEM)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error loading directory %s", ZSTR_VAL(str)); } else { ndirs++; } dir_lookup = NULL; } zend_string_release(str); } ZEND_HASH_FOREACH_END(); } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, NULL, X509_FILETYPE_DEFAULT)) { php_openssl_store_errors(); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, NULL, X509_FILETYPE_DEFAULT)) { php_openssl_store_errors(); } } return store; } /* }}} */ /* {{{ proto resource openssl_x509_read(mixed cert) Reads X.509 certificates */ PHP_FUNCTION(openssl_x509_read) { zval *cert; X509 *x509; zend_resource *res; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &cert) == FAILURE) { return; } x509 = php_openssl_x509_from_zval(cert, 1, &res); ZVAL_RES(return_value, res); if (x509 == NULL) { php_error_docref(NULL, E_WARNING, "supplied parameter cannot be coerced into an X509 certificate!"); RETURN_FALSE; } } /* }}} */ /* {{{ proto void openssl_x509_free(resource x509) Frees X.509 certificates */ PHP_FUNCTION(openssl_x509_free) { zval *x509; X509 *cert; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &x509) == FAILURE) { return; } if ((cert = (X509 *)zend_fetch_resource(Z_RES_P(x509), "OpenSSL X.509", le_x509)) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(x509)); } /* }}} */ /* }}} */ /* Pop all X509 from Stack and free them, free the stack afterwards */ static void php_sk_X509_free(STACK_OF(X509) * sk) /* {{{ */ { for (;;) { X509* x = sk_X509_pop(sk); if (!x) break; X509_free(x); } sk_X509_free(sk); } /* }}} */ static STACK_OF(X509) * php_array_to_X509_sk(zval * zcerts) /* {{{ */ { zval * zcertval; STACK_OF(X509) * sk = NULL; X509 * cert; zend_resource *certresource; sk = sk_X509_new_null(); /* get certs */ if (Z_TYPE_P(zcerts) == IS_ARRAY) { ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(zcerts), zcertval) { cert = php_openssl_x509_from_zval(zcertval, 0, &certresource); if (cert == NULL) { goto clean_exit; } if (certresource != NULL) { cert = X509_dup(cert); if (cert == NULL) { php_openssl_store_errors(); goto clean_exit; } } sk_X509_push(sk, cert); } ZEND_HASH_FOREACH_END(); } else { /* a single certificate */ cert = php_openssl_x509_from_zval(zcerts, 0, &certresource); if (cert == NULL) { goto clean_exit; } if (certresource != NULL) { cert = X509_dup(cert); if (cert == NULL) { php_openssl_store_errors(); goto clean_exit; } } sk_X509_push(sk, cert); } clean_exit: return sk; } /* }}} */ /* {{{ proto bool openssl_pkcs12_export_to_file(mixed x509, string filename, mixed priv_key, string pass[, array args]) Creates and exports a PKCS to file */ PHP_FUNCTION(openssl_pkcs12_export_to_file) { X509 * cert = NULL; BIO * bio_out = NULL; PKCS12 * p12 = NULL; char * filename; char * friendly_name = NULL; size_t filename_len; char * pass; size_t pass_len; zval *zcert = NULL, *zpkey = NULL, *args = NULL; EVP_PKEY *priv_key = NULL; zend_resource *keyresource; zval * item; STACK_OF(X509) *ca = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zpzs|a", &zcert, &filename, &filename_len, &zpkey, &pass, &pass_len, &args) == FAILURE) return; RETVAL_FALSE; cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 1"); return; } priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource); if (priv_key == NULL) { php_error_docref(NULL, E_WARNING, "cannot get private key from parameter 3"); goto cleanup; } if (!X509_check_private_key(cert, priv_key)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "private key does not correspond to cert"); goto cleanup; } if (php_openssl_open_base_dir_chk(filename)) { goto cleanup; } /* parse extra config from args array, promote this to an extra function */ if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name")-1)) != NULL && Z_TYPE_P(item) == IS_STRING ) { friendly_name = Z_STRVAL_P(item); } /* certpbe (default RC2-40) keypbe (default 3DES) friendly_caname */ if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts")-1)) != NULL) { ca = php_array_to_X509_sk(item); } /* end parse extra config */ /*PKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype);*/ p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0); if (p12 != NULL) { bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (bio_out != NULL) { i2d_PKCS12_bio(bio_out, p12); BIO_free(bio_out); RETVAL_TRUE; } else { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening file %s", filename); } PKCS12_free(p12); } else { php_openssl_store_errors(); } php_sk_X509_free(ca); cleanup: if (keyresource == NULL && priv_key) { EVP_PKEY_free(priv_key); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* }}} */ /* {{{ proto bool openssl_pkcs12_export(mixed x509, string &out, mixed priv_key, string pass[, array args]) Creates and exports a PKCS12 to a var */ PHP_FUNCTION(openssl_pkcs12_export) { X509 * cert = NULL; BIO * bio_out; PKCS12 * p12 = NULL; zval * zcert = NULL, *zout = NULL, *zpkey, *args = NULL; EVP_PKEY *priv_key = NULL; zend_resource *keyresource; char * pass; size_t pass_len; char * friendly_name = NULL; zval * item; STACK_OF(X509) *ca = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zzzs|a", &zcert, &zout, &zpkey, &pass, &pass_len, &args) == FAILURE) return; RETVAL_FALSE; cert = php_openssl_x509_from_zval(zcert, 0, NULL); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 1"); return; } priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource); if (priv_key == NULL) { php_error_docref(NULL, E_WARNING, "cannot get private key from parameter 3"); goto cleanup; } if (!X509_check_private_key(cert, priv_key)) { php_error_docref(NULL, E_WARNING, "private key does not correspond to cert"); goto cleanup; } /* parse extra config from args array, promote this to an extra function */ if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name")-1)) != NULL && Z_TYPE_P(item) == IS_STRING ) { friendly_name = Z_STRVAL_P(item); } if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts")-1)) != NULL) { ca = php_array_to_X509_sk(item); } /* end parse extra config */ p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0); if (p12 != NULL) { bio_out = BIO_new(BIO_s_mem()); if (i2d_PKCS12_bio(bio_out, p12)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length); RETVAL_TRUE; } else { php_openssl_store_errors(); } BIO_free(bio_out); PKCS12_free(p12); } else { php_openssl_store_errors(); } php_sk_X509_free(ca); cleanup: if (keyresource == NULL && priv_key) { EVP_PKEY_free(priv_key); } if (Z_TYPE_P(zcert) != IS_RESOURCE) { X509_free(cert); } } /* }}} */ /* {{{ proto bool openssl_pkcs12_read(string PKCS12, array &certs, string pass) Parses a PKCS12 to an array */ PHP_FUNCTION(openssl_pkcs12_read) { zval *zout = NULL, zextracerts, zcert, zpkey; char *pass, *zp12; size_t pass_len, zp12_len; PKCS12 * p12 = NULL; EVP_PKEY * pkey = NULL; X509 * cert = NULL; STACK_OF(X509) * ca = NULL; BIO * bio_in = NULL; int i; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szs", &zp12, &zp12_len, &zout, &pass, &pass_len) == FAILURE) return; RETVAL_FALSE; PHP_OPENSSL_CHECK_SIZE_T_TO_INT(zp12_len, pkcs12); bio_in = BIO_new(BIO_s_mem()); if (0 >= BIO_write(bio_in, zp12, (int)zp12_len)) { php_openssl_store_errors(); goto cleanup; } if (d2i_PKCS12_bio(bio_in, &p12) && PKCS12_parse(p12, pass, &pkey, &cert, &ca)) { BIO * bio_out; int cert_num; zout = zend_try_array_init(zout); if (!zout) { goto cleanup; } if (cert) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length); add_assoc_zval(zout, "cert", &zcert); } else { php_openssl_store_errors(); } BIO_free(bio_out); } if (pkey) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_PrivateKey(bio_out, pkey, NULL, NULL, 0, 0, NULL)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZVAL_STRINGL(&zpkey, bio_buf->data, bio_buf->length); add_assoc_zval(zout, "pkey", &zpkey); } else { php_openssl_store_errors(); } BIO_free(bio_out); } cert_num = sk_X509_num(ca); if (ca && cert_num) { array_init(&zextracerts); for (i = 0; i < cert_num; i++) { zval zextracert; X509* aCA = sk_X509_pop(ca); if (!aCA) break; bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, aCA)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZVAL_STRINGL(&zextracert, bio_buf->data, bio_buf->length); add_index_zval(&zextracerts, i, &zextracert); } X509_free(aCA); BIO_free(bio_out); } sk_X509_free(ca); add_assoc_zval(zout, "extracerts", &zextracerts); } RETVAL_TRUE; } else { php_openssl_store_errors(); } cleanup: if (bio_in) { BIO_free(bio_in); } if (pkey) { EVP_PKEY_free(pkey); } if (cert) { X509_free(cert); } if (p12) { PKCS12_free(p12); } } /* }}} */ /* {{{ x509 CSR functions */ /* {{{ php_openssl_make_REQ */ static int php_openssl_make_REQ(struct php_x509_request * req, X509_REQ * csr, zval * dn, zval * attribs) { STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL; char * str, *dn_sect, *attr_sect; dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name"); if (dn_sect == NULL) { php_openssl_store_errors(); return FAILURE; } dn_sk = CONF_get_section(req->req_config, dn_sect); if (dn_sk == NULL) { php_openssl_store_errors(); return FAILURE; } attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes"); if (attr_sect == NULL) { php_openssl_store_errors(); attr_sk = NULL; } else { attr_sk = CONF_get_section(req->req_config, attr_sect); if (attr_sk == NULL) { php_openssl_store_errors(); return FAILURE; } } /* setup the version number: version 1 */ if (X509_REQ_set_version(csr, 0L)) { int i, nid; char * type; CONF_VALUE * v; X509_NAME * subj; zval * item; zend_string * strindex = NULL; subj = X509_REQ_get_subject_name(csr); /* apply values from the dn hash */ ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(dn), strindex, item) { if (strindex) { int nid = OBJ_txt2nid(ZSTR_VAL(strindex)); if (nid != NID_undef) { zend_string *str_item = zval_try_get_string(item); if (UNEXPECTED(!str_item)) { return FAILURE; } if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8, (unsigned char*)ZSTR_VAL(str_item), -1, -1, 0)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "dn: add_entry_by_NID %d -> %s (failed; check error" " queue and value of string_mask OpenSSL option " "if illegal characters are reported)", nid, ZSTR_VAL(str_item)); zend_string_release(str_item); return FAILURE; } zend_string_release(str_item); } else { php_error_docref(NULL, E_WARNING, "dn: %s is not a recognized name", ZSTR_VAL(strindex)); } } } ZEND_HASH_FOREACH_END(); /* Finally apply defaults from config file */ for(i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { size_t len; char buffer[200 + 1]; /*200 + \0 !*/ v = sk_CONF_VALUE_value(dn_sk, i); type = v->name; len = strlen(type); if (len < sizeof("_default")) { continue; } len -= sizeof("_default") - 1; if (strcmp("_default", type + len) != 0) { continue; } if (len > 200) { len = 200; } memcpy(buffer, type, len); buffer[len] = '\0'; type = buffer; /* Skip past any leading X. X: X, etc to allow for multiple * instances */ for (str = type; *str; str++) { if (*str == ':' || *str == ',' || *str == '.') { str++; if (*str) { type = str; } break; } } /* if it is already set, skip this */ nid = OBJ_txt2nid(type); if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) { continue; } if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_UTF8, (unsigned char*)v->value, -1, -1, 0)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "add_entry_by_txt %s -> %s (failed)", type, v->value); return FAILURE; } if (!X509_NAME_entry_count(subj)) { php_error_docref(NULL, E_WARNING, "no objects specified in config file"); return FAILURE; } } if (attribs) { ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(attribs), strindex, item) { int nid; if (NULL == strindex) { php_error_docref(NULL, E_WARNING, "dn: numeric fild names are not supported"); continue; } nid = OBJ_txt2nid(ZSTR_VAL(strindex)); if (nid != NID_undef) { zend_string *str_item = zval_try_get_string(item); if (UNEXPECTED(!str_item)) { return FAILURE; } if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8, (unsigned char*)ZSTR_VAL(str_item), -1, -1, 0)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "attribs: add_entry_by_NID %d -> %s (failed)", nid, ZSTR_VAL(str_item)); zend_string_release(str_item); return FAILURE; } zend_string_release(str_item); } else { php_error_docref(NULL, E_WARNING, "dn: %s is not a recognized name", ZSTR_VAL(strindex)); } } ZEND_HASH_FOREACH_END(); for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { v = sk_CONF_VALUE_value(attr_sk, i); /* if it is already set, skip this */ nid = OBJ_txt2nid(v->name); if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) { continue; } if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_UTF8, (unsigned char*)v->value, -1)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "add1_attr_by_txt %s -> %s (failed; check error queue " "and value of string_mask OpenSSL option if illegal " "characters are reported)", v->name, v->value); return FAILURE; } } } } else { php_openssl_store_errors(); } if (!X509_REQ_set_pubkey(csr, req->priv_key)) { php_openssl_store_errors(); } return SUCCESS; } /* }}} */ /* {{{ php_openssl_csr_from_zval */ static X509_REQ * php_openssl_csr_from_zval(zval * val, int makeresource, zend_resource **resourceval) { X509_REQ * csr = NULL; char * filename = NULL; BIO * in; if (resourceval) { *resourceval = NULL; } if (Z_TYPE_P(val) == IS_RESOURCE) { void * what; zend_resource *res = Z_RES_P(val); what = zend_fetch_resource(res, "OpenSSL X.509 CSR", le_csr); if (what) { if (resourceval) { *resourceval = res; if (makeresource) { Z_ADDREF_P(val); } } return (X509_REQ*)what; } return NULL; } else if (Z_TYPE_P(val) != IS_STRING) { return NULL; } if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) { filename = Z_STRVAL_P(val) + (sizeof("file://") - 1); } if (filename) { if (php_openssl_open_base_dir_chk(filename)) { return NULL; } in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); } else { in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val)); } if (in == NULL) { php_openssl_store_errors(); return NULL; } csr = PEM_read_bio_X509_REQ(in, NULL,NULL,NULL); if (csr == NULL) { php_openssl_store_errors(); } BIO_free(in); return csr; } /* }}} */ /* {{{ proto bool openssl_csr_export_to_file(resource csr, string outfilename [, bool notext=true]) Exports a CSR to file */ PHP_FUNCTION(openssl_csr_export_to_file) { X509_REQ * csr; zval * zcsr = NULL; zend_bool notext = 1; char * filename = NULL; size_t filename_len; BIO * bio_out; zend_resource *csr_resource; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rp|b", &zcsr, &filename, &filename_len, &notext) == FAILURE) { return; } RETVAL_FALSE; csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource); if (csr == NULL) { php_error_docref(NULL, E_WARNING, "cannot get CSR from parameter 1"); return; } if (php_openssl_open_base_dir_chk(filename)) { return; } bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (bio_out != NULL) { if (!notext && !X509_REQ_print(bio_out, csr)) { php_openssl_store_errors(); } if (!PEM_write_bio_X509_REQ(bio_out, csr)) { php_error_docref(NULL, E_WARNING, "error writing PEM to file %s", filename); php_openssl_store_errors(); } else { RETVAL_TRUE; } BIO_free(bio_out); } else { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening file %s", filename); } if (csr_resource == NULL && csr != NULL) { X509_REQ_free(csr); } } /* }}} */ /* {{{ proto bool openssl_csr_export(resource csr, string &out [, bool notext=true]) Exports a CSR to file or a var */ PHP_FUNCTION(openssl_csr_export) { X509_REQ * csr; zval * zcsr = NULL, *zout=NULL; zend_bool notext = 1; BIO * bio_out; zend_resource *csr_resource; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz|b", &zcsr, &zout, &notext) == FAILURE) { return; } RETVAL_FALSE; csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource); if (csr == NULL) { php_error_docref(NULL, E_WARNING, "cannot get CSR from parameter 1"); return; } /* export to a var */ bio_out = BIO_new(BIO_s_mem()); if (!notext && !X509_REQ_print(bio_out, csr)) { php_openssl_store_errors(); } if (PEM_write_bio_X509_REQ(bio_out, csr)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length); RETVAL_TRUE; } else { php_openssl_store_errors(); } if (csr_resource == NULL && csr) { X509_REQ_free(csr); } BIO_free(bio_out); } /* }}} */ /* {{{ proto resource openssl_csr_sign(mixed csr, mixed x509, mixed priv_key, int days [, array config_args [, int serial]]) Signs a cert with another CERT */ PHP_FUNCTION(openssl_csr_sign) { zval * zcert = NULL, *zcsr, *zpkey, *args = NULL; zend_long num_days; zend_long serial = Z_L(0); X509 * cert = NULL, *new_cert = NULL; X509_REQ * csr; EVP_PKEY * key = NULL, *priv_key = NULL; zend_resource *csr_resource, *certresource = NULL, *keyresource = NULL; int i; struct php_x509_request req; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz!zl|a!l", &zcsr, &zcert, &zpkey, &num_days, &args, &serial) == FAILURE) return; RETVAL_FALSE; PHP_SSL_REQ_INIT(&req); csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource); if (csr == NULL) { php_error_docref(NULL, E_WARNING, "cannot get CSR from parameter 1"); return; } if (zcert) { cert = php_openssl_x509_from_zval(zcert, 0, &certresource); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "cannot get cert from parameter 2"); goto cleanup; } } priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource); if (priv_key == NULL) { php_error_docref(NULL, E_WARNING, "cannot get private key from parameter 3"); goto cleanup; } if (cert && !X509_check_private_key(cert, priv_key)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "private key does not correspond to signing cert"); goto cleanup; } if (PHP_SSL_REQ_PARSE(&req, args) == FAILURE) { goto cleanup; } /* Check that the request matches the signature */ key = X509_REQ_get_pubkey(csr); if (key == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error unpacking public key"); goto cleanup; } i = X509_REQ_verify(csr, key); if (i < 0) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Signature verification problems"); goto cleanup; } else if (i == 0) { php_error_docref(NULL, E_WARNING, "Signature did not match the certificate request"); goto cleanup; } /* Now we can get on with it */ new_cert = X509_new(); if (new_cert == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "No memory"); goto cleanup; } /* Version 3 cert */ if (!X509_set_version(new_cert, 2)) { goto cleanup; } ASN1_INTEGER_set(X509_get_serialNumber(new_cert), (long)serial); X509_set_subject_name(new_cert, X509_REQ_get_subject_name(csr)); if (cert == NULL) { cert = new_cert; } if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) { php_openssl_store_errors(); goto cleanup; } X509_gmtime_adj(X509_getm_notBefore(new_cert), 0); X509_gmtime_adj(X509_getm_notAfter(new_cert), 60*60*24*(long)num_days); i = X509_set_pubkey(new_cert, key); if (!i) { php_openssl_store_errors(); goto cleanup; } if (req.extensions_section) { X509V3_CTX ctx; X509V3_set_ctx(&ctx, cert, new_cert, csr, NULL, 0); X509V3_set_conf_lhash(&ctx, req.req_config); if (!X509V3_EXT_add_conf(req.req_config, &ctx, req.extensions_section, new_cert)) { php_openssl_store_errors(); goto cleanup; } } /* Now sign it */ if (!X509_sign(new_cert, priv_key, req.digest)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "failed to sign it"); goto cleanup; } /* Succeeded; lets return the cert */ ZVAL_RES(return_value, zend_register_resource(new_cert, le_x509)); new_cert = NULL; cleanup: if (cert == new_cert) { cert = NULL; } PHP_SSL_REQ_DISPOSE(&req); if (keyresource == NULL && priv_key) { EVP_PKEY_free(priv_key); } if (key) { EVP_PKEY_free(key); } if (csr_resource == NULL && csr) { X509_REQ_free(csr); } if (zcert && certresource == NULL && cert) { X509_free(cert); } if (new_cert) { X509_free(new_cert); } } /* }}} */ /* {{{ proto bool openssl_csr_new(array dn, resource &privkey [, array configargs [, array extraattribs]]) Generates a privkey and CSR */ PHP_FUNCTION(openssl_csr_new) { struct php_x509_request req; zval * args = NULL, * dn, *attribs = NULL; zval * out_pkey; X509_REQ * csr = NULL; int we_made_the_key = 1; zend_resource *key_resource; if (zend_parse_parameters(ZEND_NUM_ARGS(), "az|a!a!", &dn, &out_pkey, &args, &attribs) == FAILURE) { return; } RETVAL_FALSE; PHP_SSL_REQ_INIT(&req); if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) { zval *out_pkey_val = out_pkey; ZVAL_DEREF(out_pkey_val); /* Generate or use a private key */ if (Z_TYPE_P(out_pkey_val) != IS_NULL) { req.priv_key = php_openssl_evp_from_zval(out_pkey_val, 0, NULL, 0, 0, &key_resource); if (req.priv_key != NULL) { we_made_the_key = 0; } } if (req.priv_key == NULL) { php_openssl_generate_private_key(&req); } if (req.priv_key == NULL) { php_error_docref(NULL, E_WARNING, "Unable to generate a private key"); } else { csr = X509_REQ_new(); if (csr) { if (php_openssl_make_REQ(&req, csr, dn, attribs) == SUCCESS) { X509V3_CTX ext_ctx; X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, 0); X509V3_set_conf_lhash(&ext_ctx, req.req_config); /* Add extensions */ if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config, &ext_ctx, req.request_extensions_section, csr)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Error loading extension section %s", req.request_extensions_section); } else { RETVAL_TRUE; if (X509_REQ_sign(csr, req.priv_key, req.digest)) { ZVAL_RES(return_value, zend_register_resource(csr, le_csr)); csr = NULL; } else { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Error signing request"); } if (we_made_the_key) { /* and a resource for the private key */ ZEND_TRY_ASSIGN_REF_RES(out_pkey, zend_register_resource(req.priv_key, le_key)); req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */ } else if (key_resource != NULL) { req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */ } } } else { if (!we_made_the_key) { /* if we have not made the key we are not supposed to zap it by calling dispose! */ req.priv_key = NULL; } } } else { php_openssl_store_errors(); } } } if (csr) { X509_REQ_free(csr); } PHP_SSL_REQ_DISPOSE(&req); } /* }}} */ /* {{{ proto mixed openssl_csr_get_subject(mixed csr) Returns the subject of a CERT or FALSE on error */ PHP_FUNCTION(openssl_csr_get_subject) { zval * zcsr; zend_bool use_shortnames = 1; zend_resource *csr_resource; X509_NAME * subject; X509_REQ * csr; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcsr, &use_shortnames) == FAILURE) { return; } csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource); if (csr == NULL) { RETURN_FALSE; } subject = X509_REQ_get_subject_name(csr); array_init(return_value); php_openssl_add_assoc_name_entry(return_value, NULL, subject, use_shortnames); if (!csr_resource) { X509_REQ_free(csr); } } /* }}} */ /* {{{ proto mixed openssl_csr_get_public_key(mixed csr) Returns the subject of a CERT or FALSE on error */ PHP_FUNCTION(openssl_csr_get_public_key) { zval * zcsr; zend_bool use_shortnames = 1; zend_resource *csr_resource; X509_REQ *orig_csr, *csr; EVP_PKEY *tpubkey; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcsr, &use_shortnames) == FAILURE) { return; } orig_csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource); if (orig_csr == NULL) { RETURN_FALSE; } #if PHP_OPENSSL_API_VERSION >= 0x10100 /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR, * the pub key is not changed after assigning. It means if we pass * a private key, it will be returned including the private part. * If we duplicate it, then we get just the public part which is * the same behavior as for OpenSSL 1.0 */ csr = X509_REQ_dup(orig_csr); #else csr = orig_csr; #endif /* Retrieve the public key from the CSR */ tpubkey = X509_REQ_get_pubkey(csr); if (csr != orig_csr) { /* We need to free the duplicated CSR */ X509_REQ_free(csr); } if (!csr_resource) { /* We also need to free the original CSR if it was freshly created */ X509_REQ_free(orig_csr); } if (tpubkey == NULL) { php_openssl_store_errors(); RETURN_FALSE; } RETURN_RES(zend_register_resource(tpubkey, le_key)); } /* }}} */ /* }}} */ /* {{{ EVP Public/Private key functions */ struct php_openssl_pem_password { char *key; int len; }; /* {{{ php_openssl_pem_password_cb */ static int php_openssl_pem_password_cb(char *buf, int size, int rwflag, void *userdata) { struct php_openssl_pem_password *password = userdata; if (password == NULL || password->key == NULL) { return -1; } size = (password->len > size) ? size : password->len; memcpy(buf, password->key, size); return size; } /* }}} */ /* {{{ php_openssl_evp_from_zval Given a zval, coerce it into a EVP_PKEY object. It can be: 1. private key resource from openssl_get_privatekey() 2. X509 resource -> public key will be extracted from it 3. if it starts with file:// interpreted as path to key file 4. interpreted as the data from the cert/key file and interpreted in same way as openssl_get_privatekey() 5. an array(0 => [items 2..4], 1 => passphrase) 6. if val is a string (possibly starting with file:///) and it is not an X509 certificate, then interpret as public key NOTE: If you are requesting a private key but have not specified a passphrase, you should use an empty string rather than NULL for the passphrase - NULL causes a passphrase prompt to be emitted in the Apache error log! */ static EVP_PKEY * php_openssl_evp_from_zval( zval * val, int public_key, char *passphrase, size_t passphrase_len, int makeresource, zend_resource **resourceval) { EVP_PKEY * key = NULL; X509 * cert = NULL; int free_cert = 0; zend_resource *cert_res = NULL; char * filename = NULL; zval tmp; ZVAL_NULL(&tmp); #define TMP_CLEAN \ if (Z_TYPE(tmp) == IS_STRING) {\ zval_ptr_dtor_str(&tmp); \ } \ return NULL; if (resourceval) { *resourceval = NULL; } if (Z_TYPE_P(val) == IS_ARRAY) { zval * zphrase; /* get passphrase */ if ((zphrase = zend_hash_index_find(Z_ARRVAL_P(val), 1)) == NULL) { php_error_docref(NULL, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)"); return NULL; } if (Z_TYPE_P(zphrase) == IS_STRING) { passphrase = Z_STRVAL_P(zphrase); passphrase_len = Z_STRLEN_P(zphrase); } else { ZVAL_COPY(&tmp, zphrase); if (!try_convert_to_string(&tmp)) { return NULL; } passphrase = Z_STRVAL(tmp); passphrase_len = Z_STRLEN(tmp); } /* now set val to be the key param and continue */ if ((val = zend_hash_index_find(Z_ARRVAL_P(val), 0)) == NULL) { php_error_docref(NULL, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)"); TMP_CLEAN; } } if (Z_TYPE_P(val) == IS_RESOURCE) { void * what; zend_resource * res = Z_RES_P(val); what = zend_fetch_resource2(res, "OpenSSL X.509/key", le_x509, le_key); if (!what) { TMP_CLEAN; } if (resourceval) { *resourceval = res; Z_ADDREF_P(val); } if (res->type == le_x509) { /* extract key from cert, depending on public_key param */ cert = (X509*)what; free_cert = 0; } else if (res->type == le_key) { int is_priv; is_priv = php_openssl_is_private_key((EVP_PKEY*)what); /* check whether it is actually a private key if requested */ if (!public_key && !is_priv) { php_error_docref(NULL, E_WARNING, "supplied key param is a public key"); TMP_CLEAN; } if (public_key && is_priv) { php_error_docref(NULL, E_WARNING, "Don't know how to get public key from this private key"); TMP_CLEAN; } else { if (Z_TYPE(tmp) == IS_STRING) { zval_ptr_dtor_str(&tmp); } /* got the key - return it */ return (EVP_PKEY*)what; } } else { /* other types could be used here - eg: file pointers and read in the data from them */ TMP_CLEAN; } } else { /* force it to be a string and check if it refers to a file */ /* passing non string values leaks, object uses toString, it returns NULL * See bug38255.phpt */ if (!(Z_TYPE_P(val) == IS_STRING || Z_TYPE_P(val) == IS_OBJECT)) { TMP_CLEAN; } if (!try_convert_to_string(val)) { TMP_CLEAN; } if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) { filename = Z_STRVAL_P(val) + (sizeof("file://") - 1); if (php_openssl_open_base_dir_chk(filename)) { TMP_CLEAN; } } /* it's an X509 file/cert of some kind, and we need to extract the data from that */ if (public_key) { cert = php_openssl_x509_from_zval(val, 0, &cert_res); free_cert = (cert_res == NULL); /* actual extraction done later */ if (!cert) { /* not a X509 certificate, try to retrieve public key */ BIO* in; if (filename) { in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); } else { in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val)); } if (in == NULL) { php_openssl_store_errors(); TMP_CLEAN; } key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); BIO_free(in); } } else { /* we want the private key */ BIO *in; if (filename) { in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); } else { in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val)); } if (in == NULL) { TMP_CLEAN; } if (passphrase == NULL) { key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL); } else { struct php_openssl_pem_password password; password.key = passphrase; password.len = passphrase_len; key = PEM_read_bio_PrivateKey(in, NULL, php_openssl_pem_password_cb, &password); } BIO_free(in); } } if (key == NULL) { php_openssl_store_errors(); if (public_key && cert) { /* extract public key from X509 cert */ key = (EVP_PKEY *) X509_get_pubkey(cert); if (key == NULL) { php_openssl_store_errors(); } } } if (free_cert && cert) { X509_free(cert); } if (key && makeresource && resourceval) { *resourceval = zend_register_resource(key, le_key); } if (Z_TYPE(tmp) == IS_STRING) { zval_ptr_dtor_str(&tmp); } return key; } /* }}} */ /* {{{ php_openssl_generate_private_key */ static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req) { char * randfile = NULL; int egdsocket, seeded; EVP_PKEY * return_val = NULL; if (req->priv_key_bits < MIN_KEY_LENGTH) { php_error_docref(NULL, E_WARNING, "private key length is too short; it needs to be at least %d bits, not %d", MIN_KEY_LENGTH, req->priv_key_bits); return NULL; } randfile = CONF_get_string(req->req_config, req->section_name, "RANDFILE"); if (randfile == NULL) { php_openssl_store_errors(); } php_openssl_load_rand_file(randfile, &egdsocket, &seeded); if ((req->priv_key = EVP_PKEY_new()) != NULL) { switch(req->priv_key_type) { case OPENSSL_KEYTYPE_RSA: { RSA* rsaparam; #if OPENSSL_VERSION_NUMBER < 0x10002000L /* OpenSSL 1.0.2 deprecates RSA_generate_key */ PHP_OPENSSL_RAND_ADD_TIME(); rsaparam = (RSA*)RSA_generate_key(req->priv_key_bits, RSA_F4, NULL, NULL); #else { BIGNUM *bne = (BIGNUM *)BN_new(); if (BN_set_word(bne, RSA_F4) != 1) { BN_free(bne); php_error_docref(NULL, E_WARNING, "failed setting exponent"); return NULL; } rsaparam = RSA_new(); PHP_OPENSSL_RAND_ADD_TIME(); if (rsaparam == NULL || !RSA_generate_key_ex(rsaparam, req->priv_key_bits, bne, NULL)) { php_openssl_store_errors(); } BN_free(bne); } #endif if (rsaparam && EVP_PKEY_assign_RSA(req->priv_key, rsaparam)) { return_val = req->priv_key; } else { php_openssl_store_errors(); } } break; #if !defined(NO_DSA) case OPENSSL_KEYTYPE_DSA: PHP_OPENSSL_RAND_ADD_TIME(); { DSA *dsaparam = DSA_new(); if (dsaparam && DSA_generate_parameters_ex(dsaparam, req->priv_key_bits, NULL, 0, NULL, NULL, NULL)) { DSA_set_method(dsaparam, DSA_get_default_method()); if (DSA_generate_key(dsaparam)) { if (EVP_PKEY_assign_DSA(req->priv_key, dsaparam)) { return_val = req->priv_key; } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); DSA_free(dsaparam); } } else { php_openssl_store_errors(); } } break; #endif #if !defined(NO_DH) case OPENSSL_KEYTYPE_DH: PHP_OPENSSL_RAND_ADD_TIME(); { int codes = 0; DH *dhparam = DH_new(); if (dhparam && DH_generate_parameters_ex(dhparam, req->priv_key_bits, 2, NULL)) { DH_set_method(dhparam, DH_get_default_method()); if (DH_check(dhparam, &codes) && codes == 0 && DH_generate_key(dhparam)) { if (EVP_PKEY_assign_DH(req->priv_key, dhparam)) { return_val = req->priv_key; } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); DH_free(dhparam); } } else { php_openssl_store_errors(); } } break; #endif #ifdef HAVE_EVP_PKEY_EC case OPENSSL_KEYTYPE_EC: { EC_KEY *eckey; if (req->curve_name == NID_undef) { php_error_docref(NULL, E_WARNING, "Missing configuration value: 'curve_name' not set"); return NULL; } eckey = EC_KEY_new_by_curve_name(req->curve_name); if (eckey) { EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_generate_key(eckey) && EVP_PKEY_assign_EC_KEY(req->priv_key, eckey)) { return_val = req->priv_key; } else { EC_KEY_free(eckey); } } } break; #endif default: php_error_docref(NULL, E_WARNING, "Unsupported private key type"); } } else { php_openssl_store_errors(); } php_openssl_write_rand_file(randfile, egdsocket, seeded); if (return_val == NULL) { EVP_PKEY_free(req->priv_key); req->priv_key = NULL; return NULL; } return return_val; } /* }}} */ /* {{{ php_openssl_is_private_key Check whether the supplied key is a private key by checking if the secret prime factors are set */ static int php_openssl_is_private_key(EVP_PKEY* pkey) { assert(pkey != NULL); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { RSA *rsa = EVP_PKEY_get0_RSA(pkey); if (rsa != NULL) { const BIGNUM *p, *q; RSA_get0_factors(rsa, &p, &q); if (p == NULL || q == NULL) { return 0; } } } break; case EVP_PKEY_DSA: case EVP_PKEY_DSA1: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { DSA *dsa = EVP_PKEY_get0_DSA(pkey); if (dsa != NULL) { const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); if (p == NULL || q == NULL) { return 0; } DSA_get0_key(dsa, &pub_key, &priv_key); if (priv_key == NULL) { return 0; } } } break; case EVP_PKEY_DH: { DH *dh = EVP_PKEY_get0_DH(pkey); if (dh != NULL) { const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); if (p == NULL) { return 0; } DH_get0_key(dh, &pub_key, &priv_key); if (priv_key == NULL) { return 0; } } } break; #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); if (ec != NULL && NULL == EC_KEY_get0_private_key(ec)) { return 0; } } break; #endif default: php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!"); break; } return 1; } /* }}} */ #define OPENSSL_GET_BN(_array, _bn, _name) do { \ if (_bn != NULL) { \ int len = BN_num_bytes(_bn); \ zend_string *str = zend_string_alloc(len, 0); \ BN_bn2bin(_bn, (unsigned char*)ZSTR_VAL(str)); \ ZSTR_VAL(str)[len] = 0; \ add_assoc_str(&_array, #_name, str); \ } \ } while (0); #define OPENSSL_PKEY_GET_BN(_type, _name) OPENSSL_GET_BN(_type, _name, _name) #define OPENSSL_PKEY_SET_BN(_data, _name) do { \ zval *bn; \ if ((bn = zend_hash_str_find(Z_ARRVAL_P(_data), #_name, sizeof(#_name)-1)) != NULL && \ Z_TYPE_P(bn) == IS_STRING) { \ _name = BN_bin2bn( \ (unsigned char*)Z_STRVAL_P(bn), \ (int)Z_STRLEN_P(bn), NULL); \ } else { \ _name = NULL; \ } \ } while (0); /* {{{ php_openssl_pkey_init_rsa */ static zend_bool php_openssl_pkey_init_and_assign_rsa(EVP_PKEY *pkey, RSA *rsa, zval *data) { BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; OPENSSL_PKEY_SET_BN(data, n); OPENSSL_PKEY_SET_BN(data, e); OPENSSL_PKEY_SET_BN(data, d); if (!n || !d || !RSA_set0_key(rsa, n, e, d)) { return 0; } OPENSSL_PKEY_SET_BN(data, p); OPENSSL_PKEY_SET_BN(data, q); if ((p || q) && !RSA_set0_factors(rsa, p, q)) { return 0; } OPENSSL_PKEY_SET_BN(data, dmp1); OPENSSL_PKEY_SET_BN(data, dmq1); OPENSSL_PKEY_SET_BN(data, iqmp); if ((dmp1 || dmq1 || iqmp) && !RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp)) { return 0; } if (!EVP_PKEY_assign_RSA(pkey, rsa)) { php_openssl_store_errors(); return 0; } return 1; } /* {{{ php_openssl_pkey_init_dsa */ static zend_bool php_openssl_pkey_init_dsa(DSA *dsa, zval *data) { BIGNUM *p, *q, *g, *priv_key, *pub_key; const BIGNUM *priv_key_const, *pub_key_const; OPENSSL_PKEY_SET_BN(data, p); OPENSSL_PKEY_SET_BN(data, q); OPENSSL_PKEY_SET_BN(data, g); if (!p || !q || !g || !DSA_set0_pqg(dsa, p, q, g)) { return 0; } OPENSSL_PKEY_SET_BN(data, pub_key); OPENSSL_PKEY_SET_BN(data, priv_key); if (pub_key) { return DSA_set0_key(dsa, pub_key, priv_key); } /* generate key */ PHP_OPENSSL_RAND_ADD_TIME(); if (!DSA_generate_key(dsa)) { php_openssl_store_errors(); return 0; } /* if BN_mod_exp return -1, then DSA_generate_key succeed for failed key * so we need to double check that public key is created */ DSA_get0_key(dsa, &pub_key_const, &priv_key_const); if (!pub_key_const || BN_is_zero(pub_key_const)) { return 0; } /* all good */ return 1; } /* }}} */ /* {{{ php_openssl_dh_pub_from_priv */ static BIGNUM *php_openssl_dh_pub_from_priv(BIGNUM *priv_key, BIGNUM *g, BIGNUM *p) { BIGNUM *pub_key, *priv_key_const_time; BN_CTX *ctx; pub_key = BN_new(); if (pub_key == NULL) { php_openssl_store_errors(); return NULL; } priv_key_const_time = BN_new(); if (priv_key_const_time == NULL) { BN_free(pub_key); php_openssl_store_errors(); return NULL; } ctx = BN_CTX_new(); if (ctx == NULL) { BN_free(pub_key); BN_free(priv_key_const_time); php_openssl_store_errors(); return NULL; } BN_with_flags(priv_key_const_time, priv_key, BN_FLG_CONSTTIME); if (!BN_mod_exp_mont(pub_key, g, priv_key_const_time, p, ctx, NULL)) { BN_free(pub_key); php_openssl_store_errors(); pub_key = NULL; } BN_free(priv_key_const_time); BN_CTX_free(ctx); return pub_key; } /* }}} */ /* {{{ php_openssl_pkey_init_dh */ static zend_bool php_openssl_pkey_init_dh(DH *dh, zval *data) { BIGNUM *p, *q, *g, *priv_key, *pub_key; OPENSSL_PKEY_SET_BN(data, p); OPENSSL_PKEY_SET_BN(data, q); OPENSSL_PKEY_SET_BN(data, g); if (!p || !g || !DH_set0_pqg(dh, p, q, g)) { return 0; } OPENSSL_PKEY_SET_BN(data, priv_key); OPENSSL_PKEY_SET_BN(data, pub_key); if (pub_key) { return DH_set0_key(dh, pub_key, priv_key); } if (priv_key) { pub_key = php_openssl_dh_pub_from_priv(priv_key, g, p); if (pub_key == NULL) { return 0; } return DH_set0_key(dh, pub_key, priv_key); } /* generate key */ PHP_OPENSSL_RAND_ADD_TIME(); if (!DH_generate_key(dh)) { php_openssl_store_errors(); return 0; } /* all good */ return 1; } /* }}} */ /* {{{ proto resource openssl_pkey_new([array configargs]) Generates a new private key */ PHP_FUNCTION(openssl_pkey_new) { struct php_x509_request req; zval * args = NULL; zval *data; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &args) == FAILURE) { return; } RETVAL_FALSE; if (args && Z_TYPE_P(args) == IS_ARRAY) { EVP_PKEY *pkey; if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa")-1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { RSA *rsa = RSA_new(); if (rsa) { if (php_openssl_pkey_init_and_assign_rsa(pkey, rsa, data)) { RETURN_RES(zend_register_resource(pkey, le_key)); } RSA_free(rsa); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { DSA *dsa = DSA_new(); if (dsa) { if (php_openssl_pkey_init_dsa(dsa, data)) { if (EVP_PKEY_assign_DSA(pkey, dsa)) { RETURN_RES(zend_register_resource(pkey, le_key)); } else { php_openssl_store_errors(); } } DSA_free(dsa); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dh", sizeof("dh") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { DH *dh = DH_new(); if (dh) { if (php_openssl_pkey_init_dh(dh, data)) { if (EVP_PKEY_assign_DH(pkey, dh)) { ZVAL_COPY_VALUE(return_value, zend_list_insert(pkey, le_key)); return; } else { php_openssl_store_errors(); } } DH_free(dh); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; #ifdef HAVE_EVP_PKEY_EC } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "ec", sizeof("ec") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { EC_KEY *eckey = NULL; EC_GROUP *group = NULL; EC_POINT *pnt = NULL; BIGNUM *d = NULL; pkey = EVP_PKEY_new(); if (pkey) { eckey = EC_KEY_new(); if (eckey) { EC_GROUP *group = NULL; zval *bn; zval *x; zval *y; if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "curve_name", sizeof("curve_name") - 1)) != NULL && Z_TYPE_P(bn) == IS_STRING) { int nid = OBJ_sn2nid(Z_STRVAL_P(bn)); if (nid != NID_undef) { group = EC_GROUP_new_by_curve_name(nid); if (!group) { php_openssl_store_errors(); goto clean_exit; } EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED); if (!EC_KEY_set_group(eckey, group)) { php_openssl_store_errors(); goto clean_exit; } } } if (group == NULL) { php_error_docref(NULL, E_WARNING, "Unknown curve_name"); goto clean_exit; } // The public key 'pnt' can be calculated from 'd' or is defined by 'x' and 'y' if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "d", sizeof("d") - 1)) != NULL && Z_TYPE_P(bn) == IS_STRING) { d = BN_bin2bn((unsigned char*) Z_STRVAL_P(bn), Z_STRLEN_P(bn), NULL); if (!EC_KEY_set_private_key(eckey, d)) { php_openssl_store_errors(); goto clean_exit; } // Calculate the public key by multiplying the Point Q with the public key // P = d * Q pnt = EC_POINT_new(group); if (!pnt || !EC_POINT_mul(group, pnt, d, NULL, NULL, NULL)) { php_openssl_store_errors(); goto clean_exit; } BN_free(d); } else if ((x = zend_hash_str_find(Z_ARRVAL_P(data), "x", sizeof("x") - 1)) != NULL && Z_TYPE_P(x) == IS_STRING && (y = zend_hash_str_find(Z_ARRVAL_P(data), "y", sizeof("y") - 1)) != NULL && Z_TYPE_P(y) == IS_STRING) { pnt = EC_POINT_new(group); if (pnt == NULL) { php_openssl_store_errors(); goto clean_exit; } if (!EC_POINT_set_affine_coordinates_GFp( group, pnt, BN_bin2bn((unsigned char*) Z_STRVAL_P(x), Z_STRLEN_P(x), NULL), BN_bin2bn((unsigned char*) Z_STRVAL_P(y), Z_STRLEN_P(y), NULL), NULL)) { php_openssl_store_errors(); goto clean_exit; } } if (pnt != NULL) { if (!EC_KEY_set_public_key(eckey, pnt)) { php_openssl_store_errors(); goto clean_exit; } EC_POINT_free(pnt); pnt = NULL; } if (!EC_KEY_check_key(eckey)) { PHP_OPENSSL_RAND_ADD_TIME(); EC_KEY_generate_key(eckey); php_openssl_store_errors(); } if (EC_KEY_check_key(eckey) && EVP_PKEY_assign_EC_KEY(pkey, eckey)) { EC_GROUP_free(group); RETURN_RES(zend_register_resource(pkey, le_key)); } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); } clean_exit: if (d != NULL) { BN_free(d); } if (pnt != NULL) { EC_POINT_free(pnt); } if (group != NULL) { EC_GROUP_free(group); } if (eckey != NULL) { EC_KEY_free(eckey); } if (pkey != NULL) { EVP_PKEY_free(pkey); } RETURN_FALSE; #endif } } PHP_SSL_REQ_INIT(&req); if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) { if (php_openssl_generate_private_key(&req)) { /* pass back a key resource */ RETVAL_RES(zend_register_resource(req.priv_key, le_key)); /* make sure the cleanup code doesn't zap it! */ req.priv_key = NULL; } } PHP_SSL_REQ_DISPOSE(&req); } /* }}} */ /* {{{ proto bool openssl_pkey_export_to_file(mixed key, string outfilename [, string passphrase, array config_args) Gets an exportable representation of a key into a file */ PHP_FUNCTION(openssl_pkey_export_to_file) { struct php_x509_request req; zval * zpkey, * args = NULL; char * passphrase = NULL; size_t passphrase_len = 0; char * filename = NULL; size_t filename_len = 0; zend_resource *key_resource = NULL; int pem_write = 0; EVP_PKEY * key; BIO * bio_out = NULL; const EVP_CIPHER * cipher; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zp|s!a!", &zpkey, &filename, &filename_len, &passphrase, &passphrase_len, &args) == FAILURE) { return; } RETVAL_FALSE; PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase); key = php_openssl_evp_from_zval(zpkey, 0, passphrase, passphrase_len, 0, &key_resource); if (key == NULL) { php_error_docref(NULL, E_WARNING, "cannot get key from parameter 1"); RETURN_FALSE; } if (php_openssl_open_base_dir_chk(filename)) { RETURN_FALSE; } PHP_SSL_REQ_INIT(&req); if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) { bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (bio_out == NULL) { php_openssl_store_errors(); goto clean_exit; } if (passphrase && req.priv_key_encrypt) { if (req.priv_key_encrypt_cipher) { cipher = req.priv_key_encrypt_cipher; } else { cipher = (EVP_CIPHER *) EVP_des_ede3_cbc(); } } else { cipher = NULL; } switch (EVP_PKEY_base_id(key)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: pem_write = PEM_write_bio_ECPrivateKey( bio_out, EVP_PKEY_get0_EC_KEY(key), cipher, (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL); break; #endif default: pem_write = PEM_write_bio_PrivateKey( bio_out, key, cipher, (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL); break; } if (pem_write) { /* Success! * If returning the output as a string, do so now */ RETVAL_TRUE; } else { php_openssl_store_errors(); } } clean_exit: PHP_SSL_REQ_DISPOSE(&req); if (key_resource == NULL && key) { EVP_PKEY_free(key); } if (bio_out) { BIO_free(bio_out); } } /* }}} */ /* {{{ proto bool openssl_pkey_export(mixed key, &mixed out [, string passphrase [, array config_args]]) Gets an exportable representation of a key into a string or file */ PHP_FUNCTION(openssl_pkey_export) { struct php_x509_request req; zval * zpkey, * args = NULL, *out; char * passphrase = NULL; size_t passphrase_len = 0; int pem_write = 0; zend_resource *key_resource = NULL; EVP_PKEY * key; BIO * bio_out = NULL; const EVP_CIPHER * cipher; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|s!a!", &zpkey, &out, &passphrase, &passphrase_len, &args) == FAILURE) { return; } RETVAL_FALSE; PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase); key = php_openssl_evp_from_zval(zpkey, 0, passphrase, passphrase_len, 0, &key_resource); if (key == NULL) { php_error_docref(NULL, E_WARNING, "cannot get key from parameter 1"); RETURN_FALSE; } PHP_SSL_REQ_INIT(&req); if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) { bio_out = BIO_new(BIO_s_mem()); if (passphrase && req.priv_key_encrypt) { if (req.priv_key_encrypt_cipher) { cipher = req.priv_key_encrypt_cipher; } else { cipher = (EVP_CIPHER *) EVP_des_ede3_cbc(); } } else { cipher = NULL; } switch (EVP_PKEY_base_id(key)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: pem_write = PEM_write_bio_ECPrivateKey( bio_out, EVP_PKEY_get0_EC_KEY(key), cipher, (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL); break; #endif default: pem_write = PEM_write_bio_PrivateKey( bio_out, key, cipher, (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL); break; } if (pem_write) { /* Success! * If returning the output as a string, do so now */ char * bio_mem_ptr; long bio_mem_len; RETVAL_TRUE; bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr); ZEND_TRY_ASSIGN_REF_STRINGL(out, bio_mem_ptr, bio_mem_len); } else { php_openssl_store_errors(); } } PHP_SSL_REQ_DISPOSE(&req); if (key_resource == NULL && key) { EVP_PKEY_free(key); } if (bio_out) { BIO_free(bio_out); } } /* }}} */ /* {{{ proto int openssl_pkey_get_public(mixed cert) Gets public key from X.509 certificate */ PHP_FUNCTION(openssl_pkey_get_public) { zval *cert; EVP_PKEY *pkey; zend_resource *res; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &cert) == FAILURE) { return; } pkey = php_openssl_evp_from_zval(cert, 1, NULL, 0, 1, &res); if (pkey == NULL) { RETURN_FALSE; } ZVAL_RES(return_value, res); Z_ADDREF_P(return_value); } /* }}} */ /* {{{ proto void openssl_pkey_free(int key) Frees a key */ PHP_FUNCTION(openssl_pkey_free) { zval *key; EVP_PKEY *pkey; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &key) == FAILURE) { return; } if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(key)); } /* }}} */ /* {{{ proto int openssl_pkey_get_private(string key [, string passphrase]) Gets private keys */ PHP_FUNCTION(openssl_pkey_get_private) { zval *cert; EVP_PKEY *pkey; char * passphrase = ""; size_t passphrase_len = sizeof("")-1; zend_resource *res; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|s", &cert, &passphrase, &passphrase_len) == FAILURE) { return; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase); pkey = php_openssl_evp_from_zval(cert, 0, passphrase, passphrase_len, 1, &res); if (pkey == NULL) { RETURN_FALSE; } ZVAL_RES(return_value, res); Z_ADDREF_P(return_value); } /* }}} */ /* {{{ proto resource openssl_pkey_get_details(resource key) returns an array with the key details (bits, pkey, type)*/ PHP_FUNCTION(openssl_pkey_get_details) { zval *key; EVP_PKEY *pkey; BIO *out; unsigned int pbio_len; char *pbio; zend_long ktype; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &key) == FAILURE) { return; } if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) { RETURN_FALSE; } out = BIO_new(BIO_s_mem()); if (!PEM_write_bio_PUBKEY(out, pkey)) { BIO_free(out); php_openssl_store_errors(); RETURN_FALSE; } pbio_len = BIO_get_mem_data(out, &pbio); array_init(return_value); add_assoc_long(return_value, "bits", EVP_PKEY_bits(pkey)); add_assoc_stringl(return_value, "key", pbio, pbio_len); /*TODO: Use the real values once the openssl constants are used * See the enum at the top of this file */ switch (EVP_PKEY_base_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { RSA *rsa = EVP_PKEY_get0_RSA(pkey); ktype = OPENSSL_KEYTYPE_RSA; if (rsa != NULL) { zval z_rsa; const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); array_init(&z_rsa); OPENSSL_PKEY_GET_BN(z_rsa, n); OPENSSL_PKEY_GET_BN(z_rsa, e); OPENSSL_PKEY_GET_BN(z_rsa, d); OPENSSL_PKEY_GET_BN(z_rsa, p); OPENSSL_PKEY_GET_BN(z_rsa, q); OPENSSL_PKEY_GET_BN(z_rsa, dmp1); OPENSSL_PKEY_GET_BN(z_rsa, dmq1); OPENSSL_PKEY_GET_BN(z_rsa, iqmp); add_assoc_zval(return_value, "rsa", &z_rsa); } } break; case EVP_PKEY_DSA: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { DSA *dsa = EVP_PKEY_get0_DSA(pkey); ktype = OPENSSL_KEYTYPE_DSA; if (dsa != NULL) { zval z_dsa; const BIGNUM *p, *q, *g, *priv_key, *pub_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, &priv_key); array_init(&z_dsa); OPENSSL_PKEY_GET_BN(z_dsa, p); OPENSSL_PKEY_GET_BN(z_dsa, q); OPENSSL_PKEY_GET_BN(z_dsa, g); OPENSSL_PKEY_GET_BN(z_dsa, priv_key); OPENSSL_PKEY_GET_BN(z_dsa, pub_key); add_assoc_zval(return_value, "dsa", &z_dsa); } } break; case EVP_PKEY_DH: { DH *dh = EVP_PKEY_get0_DH(pkey); ktype = OPENSSL_KEYTYPE_DH; if (dh != NULL) { zval z_dh; const BIGNUM *p, *q, *g, *priv_key, *pub_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, &priv_key); array_init(&z_dh); OPENSSL_PKEY_GET_BN(z_dh, p); OPENSSL_PKEY_GET_BN(z_dh, g); OPENSSL_PKEY_GET_BN(z_dh, priv_key); OPENSSL_PKEY_GET_BN(z_dh, pub_key); add_assoc_zval(return_value, "dh", &z_dh); } } break; #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: ktype = OPENSSL_KEYTYPE_EC; if (EVP_PKEY_get0_EC_KEY(pkey) != NULL) { zval ec; const EC_GROUP *ec_group; const EC_POINT *pub; int nid; char *crv_sn; ASN1_OBJECT *obj; // openssl recommends a buffer length of 80 char oir_buf[80]; const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); BIGNUM *x = BN_new(); BIGNUM *y = BN_new(); const BIGNUM *d; ec_group = EC_KEY_get0_group(ec_key); // Curve nid (numerical identifier) used for ASN1 mapping nid = EC_GROUP_get_curve_name(ec_group); if (nid == NID_undef) { break; } array_init(&ec); // Short object name crv_sn = (char*) OBJ_nid2sn(nid); if (crv_sn != NULL) { add_assoc_string(&ec, "curve_name", crv_sn); } obj = OBJ_nid2obj(nid); if (obj != NULL) { int oir_len = OBJ_obj2txt(oir_buf, sizeof(oir_buf), obj, 1); add_assoc_stringl(&ec, "curve_oid", (char*) oir_buf, oir_len); ASN1_OBJECT_free(obj); } pub = EC_KEY_get0_public_key(ec_key); if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, NULL)) { OPENSSL_GET_BN(ec, x, x); OPENSSL_GET_BN(ec, y, y); } else { php_openssl_store_errors(); } if ((d = EC_KEY_get0_private_key(EVP_PKEY_get0_EC_KEY(pkey))) != NULL) { OPENSSL_GET_BN(ec, d, d); } add_assoc_zval(return_value, "ec", &ec); BN_free(x); BN_free(y); } break; #endif default: ktype = -1; break; } add_assoc_long(return_value, "type", ktype); BIO_free(out); } /* }}} */ /* {{{ proto string openssl_dh_compute_key(string pub_key, resource dh_key) Computes shared secret for public value of remote DH key and local DH key */ PHP_FUNCTION(openssl_dh_compute_key) { zval *key; char *pub_str; size_t pub_len; DH *dh; EVP_PKEY *pkey; BIGNUM *pub; zend_string *data; int len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sr", &pub_str, &pub_len, &key) == FAILURE) { return; } if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) { RETURN_FALSE; } if (EVP_PKEY_base_id(pkey) != EVP_PKEY_DH) { RETURN_FALSE; } dh = EVP_PKEY_get0_DH(pkey); if (dh == NULL) { RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(pub_len, pub_key); pub = BN_bin2bn((unsigned char*)pub_str, (int)pub_len, NULL); data = zend_string_alloc(DH_size(dh), 0); len = DH_compute_key((unsigned char*)ZSTR_VAL(data), pub, dh); if (len >= 0) { ZSTR_LEN(data) = len; ZSTR_VAL(data)[len] = 0; RETVAL_NEW_STR(data); } else { php_openssl_store_errors(); zend_string_release_ex(data, 0); RETVAL_FALSE; } BN_free(pub); } /* }}} */ /* {{{ proto string openssl_pkey_derive(peer_pub_key, priv_key, int keylen=NULL) Computes shared secret for public value of remote and local DH or ECDH key */ PHP_FUNCTION(openssl_pkey_derive) { zval *priv_key; zval *peer_pub_key; EVP_PKEY *pkey; EVP_PKEY *peer_key; size_t key_size; zend_long key_len = 0; zend_string *result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|l", &peer_pub_key, &priv_key, &key_len) == FAILURE) { RETURN_FALSE; } if (key_len < 0) { php_error_docref(NULL, E_WARNING, "keylen < 0, assuming NULL"); } key_size = key_len; if ((pkey = php_openssl_evp_from_zval(priv_key, 0, "", 0, 0, NULL)) == NULL || (peer_key = php_openssl_evp_from_zval(peer_pub_key, 1, NULL, 0, 0, NULL)) == NULL) { RETURN_FALSE; } EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey, NULL); if (!ctx) { RETURN_FALSE; } if (EVP_PKEY_derive_init(ctx) > 0 && EVP_PKEY_derive_set_peer(ctx, peer_key) > 0 && (key_size > 0 || EVP_PKEY_derive(ctx, NULL, &key_size) > 0) && (result = zend_string_alloc(key_size, 0)) != NULL) { if (EVP_PKEY_derive(ctx, (unsigned char*)ZSTR_VAL(result), &key_size) > 0) { ZSTR_LEN(result) = key_size; ZSTR_VAL(result)[key_size] = 0; RETVAL_NEW_STR(result); } else { php_openssl_store_errors(); zend_string_release_ex(result, 0); RETVAL_FALSE; } } else { RETVAL_FALSE; } EVP_PKEY_CTX_free(ctx); } /* }}} */ /* {{{ proto string openssl_pbkdf2(string password, string salt, int key_length, int iterations [, string digest_method = "sha1"]) Generates a PKCS5 v2 PBKDF2 string, defaults to sha1 */ PHP_FUNCTION(openssl_pbkdf2) { zend_long key_length = 0, iterations = 0; char *password; size_t password_len; char *salt; size_t salt_len; char *method; size_t method_len = 0; zend_string *out_buffer; const EVP_MD *digest; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssll|s", &password, &password_len, &salt, &salt_len, &key_length, &iterations, &method, &method_len) == FAILURE) { return; } if (key_length <= 0) { RETURN_FALSE; } if (method_len) { digest = EVP_get_digestbyname(method); } else { digest = EVP_sha1(); } if (!digest) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm"); RETURN_FALSE; } PHP_OPENSSL_CHECK_LONG_TO_INT(key_length, key); PHP_OPENSSL_CHECK_LONG_TO_INT(iterations, iterations); PHP_OPENSSL_CHECK_SIZE_T_TO_INT(password_len, password); PHP_OPENSSL_CHECK_SIZE_T_TO_INT(salt_len, salt); out_buffer = zend_string_alloc(key_length, 0); if (PKCS5_PBKDF2_HMAC(password, (int)password_len, (unsigned char *)salt, (int)salt_len, (int)iterations, digest, (int)key_length, (unsigned char*)ZSTR_VAL(out_buffer)) == 1) { ZSTR_VAL(out_buffer)[key_length] = 0; RETURN_NEW_STR(out_buffer); } else { php_openssl_store_errors(); zend_string_release_ex(out_buffer, 0); RETURN_FALSE; } } /* }}} */ /* {{{ PKCS7 S/MIME functions */ /* {{{ proto bool openssl_pkcs7_verify(string filename, int flags [, string signerscerts [, array cainfo [, string extracerts [, string content [, string pk7]]]]]) Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers */ PHP_FUNCTION(openssl_pkcs7_verify) { X509_STORE * store = NULL; zval * cainfo = NULL; STACK_OF(X509) *signers= NULL; STACK_OF(X509) *others = NULL; PKCS7 * p7 = NULL; BIO * in = NULL, * datain = NULL, * dataout = NULL, * p7bout = NULL; zend_long flags = 0; char * filename; size_t filename_len; char * extracerts = NULL; size_t extracerts_len = 0; char * signersfilename = NULL; size_t signersfilename_len = 0; char * datafilename = NULL; size_t datafilename_len = 0; char * p7bfilename = NULL; size_t p7bfilename_len = 0; RETVAL_LONG(-1); if (zend_parse_parameters(ZEND_NUM_ARGS(), "pl|pappp", &filename, &filename_len, &flags, &signersfilename, &signersfilename_len, &cainfo, &extracerts, &extracerts_len, &datafilename, &datafilename_len, &p7bfilename, &p7bfilename_len) == FAILURE) { return; } if (extracerts) { others = php_openssl_load_all_certs_from_file(extracerts); if (others == NULL) { goto clean_exit; } } flags = flags & ~PKCS7_DETACHED; store = php_openssl_setup_verify(cainfo); if (!store) { goto clean_exit; } if (php_openssl_open_base_dir_chk(filename)) { goto clean_exit; } in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(flags)); if (in == NULL) { php_openssl_store_errors(); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == NULL) { #if DEBUG_SMIME zend_printf("SMIME_read_PKCS7 failed\n"); #endif php_openssl_store_errors(); goto clean_exit; } if (datafilename) { if (php_openssl_open_base_dir_chk(datafilename)) { goto clean_exit; } dataout = BIO_new_file(datafilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (dataout == NULL) { php_openssl_store_errors(); goto clean_exit; } } if (p7bfilename) { if (php_openssl_open_base_dir_chk(p7bfilename)) { goto clean_exit; } p7bout = BIO_new_file(p7bfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (p7bout == NULL) { php_openssl_store_errors(); goto clean_exit; } } #if DEBUG_SMIME zend_printf("Calling PKCS7 verify\n"); #endif if (PKCS7_verify(p7, others, store, datain, dataout, (int)flags)) { RETVAL_TRUE; if (signersfilename) { BIO *certout; if (php_openssl_open_base_dir_chk(signersfilename)) { goto clean_exit; } certout = BIO_new_file(signersfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (certout) { int i; signers = PKCS7_get0_signers(p7, NULL, (int)flags); if (signers != NULL) { for (i = 0; i < sk_X509_num(signers); i++) { if (!PEM_write_bio_X509(certout, sk_X509_value(signers, i))) { php_openssl_store_errors(); RETVAL_LONG(-1); php_error_docref(NULL, E_WARNING, "failed to write signer %d", i); } } sk_X509_free(signers); } else { RETVAL_LONG(-1); php_openssl_store_errors(); } BIO_free(certout); } else { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "signature OK, but cannot open %s for writing", signersfilename); RETVAL_LONG(-1); } if (p7bout) { PEM_write_bio_PKCS7(p7bout, p7); } } } else { php_openssl_store_errors(); RETVAL_FALSE; } clean_exit: if (p7bout) { BIO_free(p7bout); } X509_STORE_free(store); BIO_free(datain); BIO_free(in); BIO_free(dataout); PKCS7_free(p7); sk_X509_pop_free(others, X509_free); } /* }}} */ /* {{{ proto bool openssl_pkcs7_encrypt(string infile, string outfile, mixed recipcerts, array headers [, int flags [, int cipher]]) Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile */ PHP_FUNCTION(openssl_pkcs7_encrypt) { zval * zrecipcerts, * zheaders = NULL; STACK_OF(X509) * recipcerts = NULL; BIO * infile = NULL, * outfile = NULL; zend_long flags = 0; PKCS7 * p7 = NULL; zval * zcertval; X509 * cert; const EVP_CIPHER *cipher = NULL; zend_long cipherid = PHP_OPENSSL_CIPHER_DEFAULT; zend_string * strindex; char * infilename = NULL; size_t infilename_len; char * outfilename = NULL; size_t outfilename_len; RETVAL_FALSE; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppza!|ll", &infilename, &infilename_len, &outfilename, &outfilename_len, &zrecipcerts, &zheaders, &flags, &cipherid) == FAILURE) return; if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) { return; } infile = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(flags)); if (infile == NULL) { php_openssl_store_errors(); goto clean_exit; } outfile = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(flags)); if (outfile == NULL) { php_openssl_store_errors(); goto clean_exit; } recipcerts = sk_X509_new_null(); /* get certs */ if (Z_TYPE_P(zrecipcerts) == IS_ARRAY) { ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(zrecipcerts), zcertval) { zend_resource *certresource; cert = php_openssl_x509_from_zval(zcertval, 0, &certresource); if (cert == NULL) { goto clean_exit; } if (certresource != NULL) { /* we shouldn't free this particular cert, as it is a resource. make a copy and push that on the stack instead */ cert = X509_dup(cert); if (cert == NULL) { php_openssl_store_errors(); goto clean_exit; } } sk_X509_push(recipcerts, cert); } ZEND_HASH_FOREACH_END(); } else { /* a single certificate */ zend_resource *certresource; cert = php_openssl_x509_from_zval(zrecipcerts, 0, &certresource); if (cert == NULL) { goto clean_exit; } if (certresource != NULL) { /* we shouldn't free this particular cert, as it is a resource. make a copy and push that on the stack instead */ cert = X509_dup(cert); if (cert == NULL) { php_openssl_store_errors(); goto clean_exit; } } sk_X509_push(recipcerts, cert); } /* sanity check the cipher */ cipher = php_openssl_get_evp_cipher_from_algo(cipherid); if (cipher == NULL) { /* shouldn't happen */ php_error_docref(NULL, E_WARNING, "Failed to get cipher"); goto clean_exit; } p7 = PKCS7_encrypt(recipcerts, infile, (EVP_CIPHER*)cipher, (int)flags); if (p7 == NULL) { php_openssl_store_errors(); goto clean_exit; } /* tack on extra headers */ if (zheaders) { ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(zheaders), strindex, zcertval) { zend_string *str = zval_try_get_string(zcertval); if (UNEXPECTED(!str)) { goto clean_exit; } if (strindex) { BIO_printf(outfile, "%s: %s\n", ZSTR_VAL(strindex), ZSTR_VAL(str)); } else { BIO_printf(outfile, "%s\n", ZSTR_VAL(str)); } zend_string_release(str); } ZEND_HASH_FOREACH_END(); } (void)BIO_reset(infile); /* write the encrypted data */ if (!SMIME_write_PKCS7(outfile, p7, infile, (int)flags)) { php_openssl_store_errors(); goto clean_exit; } RETVAL_TRUE; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (recipcerts) { sk_X509_pop_free(recipcerts, X509_free); } } /* }}} */ /* {{{ proto bool openssl_pkcs7_read(string P7B, array &certs) Exports the PKCS7 file to an array of PEM certificates */ PHP_FUNCTION(openssl_pkcs7_read) { zval * zout = NULL, zcert; char *p7b; size_t p7b_len; STACK_OF(X509) *certs = NULL; STACK_OF(X509_CRL) *crls = NULL; BIO * bio_in = NULL, * bio_out = NULL; PKCS7 * p7 = NULL; int i; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &p7b, &p7b_len, &zout) == FAILURE) { return; } RETVAL_FALSE; PHP_OPENSSL_CHECK_SIZE_T_TO_INT(p7b_len, p7b); bio_in = BIO_new(BIO_s_mem()); if (bio_in == NULL) { goto clean_exit; } if (0 >= BIO_write(bio_in, p7b, (int)p7b_len)) { php_openssl_store_errors(); goto clean_exit; } p7 = PEM_read_bio_PKCS7(bio_in, NULL, NULL, NULL); if (p7 == NULL) { php_openssl_store_errors(); goto clean_exit; } switch (OBJ_obj2nid(p7->type)) { case NID_pkcs7_signed: if (p7->d.sign != NULL) { certs = p7->d.sign->cert; crls = p7->d.sign->crl; } break; case NID_pkcs7_signedAndEnveloped: if (p7->d.signed_and_enveloped != NULL) { certs = p7->d.signed_and_enveloped->cert; crls = p7->d.signed_and_enveloped->crl; } break; default: break; } zout = zend_try_array_init(zout); if (!zout) { goto clean_exit; } if (certs != NULL) { for (i = 0; i < sk_X509_num(certs); i++) { X509* ca = sk_X509_value(certs, i); bio_out = BIO_new(BIO_s_mem()); if (bio_out && PEM_write_bio_X509(bio_out, ca)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length); add_index_zval(zout, i, &zcert); BIO_free(bio_out); } } } if (crls != NULL) { for (i = 0; i < sk_X509_CRL_num(crls); i++) { X509_CRL* crl = sk_X509_CRL_value(crls, i); bio_out = BIO_new(BIO_s_mem()); if (bio_out && PEM_write_bio_X509_CRL(bio_out, crl)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length); add_index_zval(zout, i, &zcert); BIO_free(bio_out); } } } RETVAL_TRUE; clean_exit: if (bio_in != NULL) { BIO_free(bio_in); } if (p7 != NULL) { PKCS7_free(p7); } } /* }}} */ /* {{{ proto bool openssl_pkcs7_sign(string infile, string outfile, mixed signcert, mixed signkey, array headers [, int flags [, string extracertsfilename]]) Signs the MIME message in the file named infile with signcert/signkey and output the result to file name outfile. headers lists plain text headers to exclude from the signed portion of the message, and should include to, from and subject as a minimum */ PHP_FUNCTION(openssl_pkcs7_sign) { zval * zcert, * zprivkey, * zheaders; zval * hval; X509 * cert = NULL; EVP_PKEY * privkey = NULL; zend_long flags = PKCS7_DETACHED; PKCS7 * p7 = NULL; BIO * infile = NULL, * outfile = NULL; STACK_OF(X509) *others = NULL; zend_resource *certresource = NULL, *keyresource = NULL; zend_string * strindex; char * infilename; size_t infilename_len; char * outfilename; size_t outfilename_len; char * extracertsfilename = NULL; size_t extracertsfilename_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppzza!|lp!", &infilename, &infilename_len, &outfilename, &outfilename_len, &zcert, &zprivkey, &zheaders, &flags, &extracertsfilename, &extracertsfilename_len) == FAILURE) { return; } RETVAL_FALSE; if (extracertsfilename) { others = php_openssl_load_all_certs_from_file(extracertsfilename); if (others == NULL) { goto clean_exit; } } privkey = php_openssl_evp_from_zval(zprivkey, 0, "", 0, 0, &keyresource); if (privkey == NULL) { php_error_docref(NULL, E_WARNING, "error getting private key"); goto clean_exit; } cert = php_openssl_x509_from_zval(zcert, 0, &certresource); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "error getting cert"); goto clean_exit; } if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) { goto clean_exit; } infile = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(flags)); if (infile == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening input file %s!", infilename); goto clean_exit; } outfile = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (outfile == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error opening output file %s!", outfilename); goto clean_exit; } p7 = PKCS7_sign(cert, privkey, others, infile, (int)flags); if (p7 == NULL) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "error creating PKCS7 structure!"); goto clean_exit; } (void)BIO_reset(infile); /* tack on extra headers */ if (zheaders) { int ret; ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(zheaders), strindex, hval) { zend_string *str = zval_try_get_string(hval); if (UNEXPECTED(!str)) { goto clean_exit; } if (strindex) { ret = BIO_printf(outfile, "%s: %s\n", ZSTR_VAL(strindex), ZSTR_VAL(str)); } else { ret = BIO_printf(outfile, "%s\n", ZSTR_VAL(str)); } zend_string_release(str); if (ret < 0) { php_openssl_store_errors(); } } ZEND_HASH_FOREACH_END(); } /* write the signed data */ if (!SMIME_write_PKCS7(outfile, p7, infile, (int)flags)) { php_openssl_store_errors(); goto clean_exit; } RETVAL_TRUE; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (others) { sk_X509_pop_free(others, X509_free); } if (privkey && keyresource == NULL) { EVP_PKEY_free(privkey); } if (cert && certresource == NULL) { X509_free(cert); } } /* }}} */ /* {{{ proto bool openssl_pkcs7_decrypt(string infilename, string outfilename, mixed recipcert [, mixed recipkey]) Decrypts the S/MIME message in the file name infilename and output the results to the file name outfilename. recipcert is a CERT for one of the recipients. recipkey specifies the private key matching recipcert, if recipcert does not include the key */ PHP_FUNCTION(openssl_pkcs7_decrypt) { zval * recipcert, * recipkey = NULL; X509 * cert = NULL; EVP_PKEY * key = NULL; zend_resource *certresval, *keyresval; BIO * in = NULL, * out = NULL, * datain = NULL; PKCS7 * p7 = NULL; char * infilename; size_t infilename_len; char * outfilename; size_t outfilename_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppz|z", &infilename, &infilename_len, &outfilename, &outfilename_len, &recipcert, &recipkey) == FAILURE) { return; } RETVAL_FALSE; cert = php_openssl_x509_from_zval(recipcert, 0, &certresval); if (cert == NULL) { php_error_docref(NULL, E_WARNING, "unable to coerce parameter 3 to x509 cert"); goto clean_exit; } key = php_openssl_evp_from_zval(recipkey ? recipkey : recipcert, 0, "", 0, 0, &keyresval); if (key == NULL) { php_error_docref(NULL, E_WARNING, "unable to get private key"); goto clean_exit; } if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) { goto clean_exit; } in = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)); if (in == NULL) { php_openssl_store_errors(); goto clean_exit; } out = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY)); if (out == NULL) { php_openssl_store_errors(); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == NULL) { php_openssl_store_errors(); goto clean_exit; } if (PKCS7_decrypt(p7, key, cert, out, PKCS7_DETACHED)) { RETVAL_TRUE; } else { php_openssl_store_errors(); } clean_exit: PKCS7_free(p7); BIO_free(datain); BIO_free(in); BIO_free(out); if (cert && certresval == NULL) { X509_free(cert); } if (key && keyresval == NULL) { EVP_PKEY_free(key); } } /* }}} */ /* }}} */ /* {{{ proto bool openssl_private_encrypt(string data, string &crypted, mixed key [, int padding]) Encrypts data with private key */ PHP_FUNCTION(openssl_private_encrypt) { zval *key, *crypted; EVP_PKEY *pkey; int cryptedlen; zend_string *cryptedbuf = NULL; int successful = 0; zend_resource *keyresource = NULL; char * data; size_t data_len; zend_long padding = RSA_PKCS1_PADDING; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) { return; } RETVAL_FALSE; pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "key param is not a valid private key"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); cryptedlen = EVP_PKEY_size(pkey); cryptedbuf = zend_string_alloc(cryptedlen, 0); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_private_encrypt((int)data_len, (unsigned char *)data, (unsigned char *)ZSTR_VAL(cryptedbuf), EVP_PKEY_get0_RSA(pkey), (int)padding) == cryptedlen); break; default: php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!"); } if (successful) { ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf); cryptedbuf = NULL; RETVAL_TRUE; } else { php_openssl_store_errors(); } if (cryptedbuf) { zend_string_release_ex(cryptedbuf, 0); } if (keyresource == NULL) { EVP_PKEY_free(pkey); } } /* }}} */ /* {{{ proto bool openssl_private_decrypt(string data, string &decrypted, mixed key [, int padding]) Decrypts data with private key */ PHP_FUNCTION(openssl_private_decrypt) { zval *key, *crypted; EVP_PKEY *pkey; int cryptedlen; zend_string *cryptedbuf = NULL; unsigned char *crypttemp; int successful = 0; zend_long padding = RSA_PKCS1_PADDING; zend_resource *keyresource = NULL; char * data; size_t data_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) { return; } RETVAL_FALSE; pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "key parameter is not a valid private key"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); cryptedlen = EVP_PKEY_size(pkey); crypttemp = emalloc(cryptedlen + 1); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_private_decrypt((int)data_len, (unsigned char *)data, crypttemp, EVP_PKEY_get0_RSA(pkey), (int)padding); if (cryptedlen != -1) { cryptedbuf = zend_string_alloc(cryptedlen, 0); memcpy(ZSTR_VAL(cryptedbuf), crypttemp, cryptedlen); successful = 1; } break; default: php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!"); } efree(crypttemp); if (successful) { ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf); cryptedbuf = NULL; RETVAL_TRUE; } else { php_openssl_store_errors(); } if (keyresource == NULL) { EVP_PKEY_free(pkey); } if (cryptedbuf) { zend_string_release_ex(cryptedbuf, 0); } } /* }}} */ /* {{{ proto bool openssl_public_encrypt(string data, string &crypted, mixed key [, int padding]) Encrypts data with public key */ PHP_FUNCTION(openssl_public_encrypt) { zval *key, *crypted; EVP_PKEY *pkey; int cryptedlen; zend_string *cryptedbuf; int successful = 0; zend_resource *keyresource = NULL; zend_long padding = RSA_PKCS1_PADDING; char * data; size_t data_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) return; RETVAL_FALSE; pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "key parameter is not a valid public key"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); cryptedlen = EVP_PKEY_size(pkey); cryptedbuf = zend_string_alloc(cryptedlen, 0); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_public_encrypt((int)data_len, (unsigned char *)data, (unsigned char *)ZSTR_VAL(cryptedbuf), EVP_PKEY_get0_RSA(pkey), (int)padding) == cryptedlen); break; default: php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!"); } if (successful) { ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf); cryptedbuf = NULL; RETVAL_TRUE; } else { php_openssl_store_errors(); } if (keyresource == NULL) { EVP_PKEY_free(pkey); } if (cryptedbuf) { zend_string_release_ex(cryptedbuf, 0); } } /* }}} */ /* {{{ proto bool openssl_public_decrypt(string data, string &crypted, resource key [, int padding]) Decrypts data with public key */ PHP_FUNCTION(openssl_public_decrypt) { zval *key, *crypted; EVP_PKEY *pkey; int cryptedlen; zend_string *cryptedbuf = NULL; unsigned char *crypttemp; int successful = 0; zend_resource *keyresource = NULL; zend_long padding = RSA_PKCS1_PADDING; char * data; size_t data_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) { return; } RETVAL_FALSE; pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "key parameter is not a valid public key"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); cryptedlen = EVP_PKEY_size(pkey); crypttemp = emalloc(cryptedlen + 1); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_public_decrypt((int)data_len, (unsigned char *)data, crypttemp, EVP_PKEY_get0_RSA(pkey), (int)padding); if (cryptedlen != -1) { cryptedbuf = zend_string_alloc(cryptedlen, 0); memcpy(ZSTR_VAL(cryptedbuf), crypttemp, cryptedlen); successful = 1; } break; default: php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!"); } efree(crypttemp); if (successful) { ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf); cryptedbuf = NULL; RETVAL_TRUE; } else { php_openssl_store_errors(); } if (cryptedbuf) { zend_string_release_ex(cryptedbuf, 0); } if (keyresource == NULL) { EVP_PKEY_free(pkey); } } /* }}} */ /* {{{ proto mixed openssl_error_string(void) Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages */ PHP_FUNCTION(openssl_error_string) { char buf[256]; unsigned long val; if (zend_parse_parameters_none() == FAILURE) { return; } php_openssl_store_errors(); if (OPENSSL_G(errors) == NULL || OPENSSL_G(errors)->top == OPENSSL_G(errors)->bottom) { RETURN_FALSE; } OPENSSL_G(errors)->bottom = (OPENSSL_G(errors)->bottom + 1) % ERR_NUM_ERRORS; val = OPENSSL_G(errors)->buffer[OPENSSL_G(errors)->bottom]; if (val) { ERR_error_string_n(val, buf, 256); RETURN_STRING(buf); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool openssl_sign(string data, &string signature, mixed key[, mixed method]) Signs data */ PHP_FUNCTION(openssl_sign) { zval *key, *signature; EVP_PKEY *pkey; unsigned int siglen; zend_string *sigbuf; zend_resource *keyresource = NULL; char * data; size_t data_len; EVP_MD_CTX *md_ctx; zval *method = NULL; zend_long signature_algo = OPENSSL_ALGO_SHA1; const EVP_MD *mdtype; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|z", &data, &data_len, &signature, &key, &method) == FAILURE) { return; } pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "supplied key param cannot be coerced into a private key"); RETURN_FALSE; } if (method == NULL || Z_TYPE_P(method) == IS_LONG) { if (method != NULL) { signature_algo = Z_LVAL_P(method); } mdtype = php_openssl_get_evp_md_from_algo(signature_algo); } else if (Z_TYPE_P(method) == IS_STRING) { mdtype = EVP_get_digestbyname(Z_STRVAL_P(method)); } else { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } if (!mdtype) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } siglen = EVP_PKEY_size(pkey); sigbuf = zend_string_alloc(siglen, 0); md_ctx = EVP_MD_CTX_create(); if (md_ctx != NULL && EVP_SignInit(md_ctx, mdtype) && EVP_SignUpdate(md_ctx, data, data_len) && EVP_SignFinal(md_ctx, (unsigned char*)ZSTR_VAL(sigbuf), &siglen, pkey)) { ZSTR_VAL(sigbuf)[siglen] = '\0'; ZSTR_LEN(sigbuf) = siglen; ZEND_TRY_ASSIGN_REF_NEW_STR(signature, sigbuf); RETVAL_TRUE; } else { php_openssl_store_errors(); efree(sigbuf); RETVAL_FALSE; } EVP_MD_CTX_destroy(md_ctx); if (keyresource == NULL) { EVP_PKEY_free(pkey); } } /* }}} */ /* {{{ proto int openssl_verify(string data, string signature, mixed key[, mixed method]) Verifys data */ PHP_FUNCTION(openssl_verify) { zval *key; EVP_PKEY *pkey; int err = 0; EVP_MD_CTX *md_ctx; const EVP_MD *mdtype; zend_resource *keyresource = NULL; char * data; size_t data_len; char * signature; size_t signature_len; zval *method = NULL; zend_long signature_algo = OPENSSL_ALGO_SHA1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssz|z", &data, &data_len, &signature, &signature_len, &key, &method) == FAILURE) { return; } PHP_OPENSSL_CHECK_SIZE_T_TO_UINT(signature_len, signature); if (method == NULL || Z_TYPE_P(method) == IS_LONG) { if (method != NULL) { signature_algo = Z_LVAL_P(method); } mdtype = php_openssl_get_evp_md_from_algo(signature_algo); } else if (Z_TYPE_P(method) == IS_STRING) { mdtype = EVP_get_digestbyname(Z_STRVAL_P(method)); } else { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } if (!mdtype) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "supplied key param cannot be coerced into a public key"); RETURN_FALSE; } md_ctx = EVP_MD_CTX_create(); if (md_ctx == NULL || !EVP_VerifyInit (md_ctx, mdtype) || !EVP_VerifyUpdate (md_ctx, data, data_len) || (err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature, (unsigned int)signature_len, pkey)) < 0) { php_openssl_store_errors(); } EVP_MD_CTX_destroy(md_ctx); if (keyresource == NULL) { EVP_PKEY_free(pkey); } RETURN_LONG(err); } /* }}} */ /* {{{ proto int openssl_seal(string data, &string sealdata, &array ekeys, array pubkeys [, string method [, &string iv]])) Seals data */ PHP_FUNCTION(openssl_seal) { zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL; HashTable *pubkeysht; EVP_PKEY **pkeys; zend_resource ** key_resources; /* so we know what to cleanup */ int i, len1, len2, *eksl, nkeys, iv_len; unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks; char * data; size_t data_len; char *method =NULL; size_t method_len = 0; const EVP_CIPHER *cipher; EVP_CIPHER_CTX *ctx; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szza|sz", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) { return; } pubkeysht = Z_ARRVAL_P(pubkeys); nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0; if (!nkeys) { php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); if (method) { cipher = EVP_get_cipherbyname(method); if (!cipher) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } } else { cipher = EVP_rc4(); } iv_len = EVP_CIPHER_iv_length(cipher); if (!iv && iv_len > 0) { php_error_docref(NULL, E_WARNING, "Cipher algorithm requires an IV to be supplied as a sixth parameter"); RETURN_FALSE; } pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0); eksl = safe_emalloc(nkeys, sizeof(*eksl), 0); eks = safe_emalloc(nkeys, sizeof(*eks), 0); memset(eks, 0, sizeof(*eks) * nkeys); key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0); memset(key_resources, 0, sizeof(zend_resource*) * nkeys); memset(pkeys, 0, sizeof(*pkeys) * nkeys); /* get the public keys we are using to seal this data */ i = 0; ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) { pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]); if (pkeys[i] == NULL) { php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1); RETVAL_FALSE; goto clean_exit; } eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1); i++; } ZEND_HASH_FOREACH_END(); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) { EVP_CIPHER_CTX_free(ctx); php_openssl_store_errors(); RETVAL_FALSE; goto clean_exit; } /* allocate one byte extra to make room for \0 */ buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx)); EVP_CIPHER_CTX_reset(ctx); if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) || !EVP_SealFinal(ctx, buf + len1, &len2)) { efree(buf); EVP_CIPHER_CTX_free(ctx); php_openssl_store_errors(); RETVAL_FALSE; goto clean_exit; } if (len1 + len2 > 0) { ZEND_TRY_ASSIGN_REF_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0)); efree(buf); ekeys = zend_try_array_init(ekeys); if (!ekeys) { EVP_CIPHER_CTX_free(ctx); goto clean_exit; } for (i=0; i<nkeys; i++) { eks[i][eksl[i]] = '\0'; add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]); efree(eks[i]); eks[i] = NULL; } if (iv) { iv_buf[iv_len] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0)); } } else { efree(buf); } RETVAL_LONG(len1 + len2); EVP_CIPHER_CTX_free(ctx); clean_exit: for (i=0; i<nkeys; i++) { if (key_resources[i] == NULL && pkeys[i] != NULL) { EVP_PKEY_free(pkeys[i]); } if (eks[i]) { efree(eks[i]); } } efree(eks); efree(eksl); efree(pkeys); efree(key_resources); } /* }}} */ /* {{{ proto bool openssl_open(string data, &string opendata, string ekey, mixed privkey [, string method [, string iv]]) Opens data */ PHP_FUNCTION(openssl_open) { zval *privkey, *opendata; EVP_PKEY *pkey; int len1, len2, cipher_iv_len; unsigned char *buf, *iv_buf; zend_resource *keyresource = NULL; EVP_CIPHER_CTX *ctx; char * data; size_t data_len; char * ekey; size_t ekey_len; char *method = NULL, *iv = NULL; size_t method_len = 0, iv_len = 0; const EVP_CIPHER *cipher; if (zend_parse_parameters(ZEND_NUM_ARGS(), "szsz|ss", &data, &data_len, &opendata, &ekey, &ekey_len, &privkey, &method, &method_len, &iv, &iv_len) == FAILURE) { return; } pkey = php_openssl_evp_from_zval(privkey, 0, "", 0, 0, &keyresource); if (pkey == NULL) { php_error_docref(NULL, E_WARNING, "unable to coerce parameter 4 into a private key"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(ekey_len, ekey); PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); if (method) { cipher = EVP_get_cipherbyname(method); if (!cipher) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } } else { cipher = EVP_rc4(); } cipher_iv_len = EVP_CIPHER_iv_length(cipher); if (cipher_iv_len > 0) { if (!iv) { php_error_docref(NULL, E_WARNING, "Cipher algorithm requires an IV to be supplied as a sixth parameter"); RETURN_FALSE; } if ((size_t)cipher_iv_len != iv_len) { php_error_docref(NULL, E_WARNING, "IV length is invalid"); RETURN_FALSE; } iv_buf = (unsigned char *)iv; } else { iv_buf = NULL; } buf = emalloc(data_len + 1); ctx = EVP_CIPHER_CTX_new(); if (ctx != NULL && EVP_OpenInit(ctx, cipher, (unsigned char *)ekey, (int)ekey_len, iv_buf, pkey) && EVP_OpenUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) && EVP_OpenFinal(ctx, buf + len1, &len2) && (len1 + len2 > 0)) { buf[len1 + len2] = '\0'; ZEND_TRY_ASSIGN_REF_NEW_STR(opendata, zend_string_init((char*)buf, len1 + len2, 0)); RETVAL_TRUE; } else { php_openssl_store_errors(); RETVAL_FALSE; } efree(buf); if (keyresource == NULL) { EVP_PKEY_free(pkey); } EVP_CIPHER_CTX_free(ctx); } /* }}} */ static void php_openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) /* {{{ */ { add_next_index_string((zval*)arg, (char*)name->name); } /* }}} */ static void php_openssl_add_method(const OBJ_NAME *name, void *arg) /* {{{ */ { if (name->alias == 0) { add_next_index_string((zval*)arg, (char*)name->name); } } /* }}} */ /* {{{ proto array openssl_get_md_methods([bool aliases = false]) Return array of available digest methods */ PHP_FUNCTION(openssl_get_md_methods) { zend_bool aliases = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &aliases) == FAILURE) { return; } array_init(return_value); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, aliases ? php_openssl_add_method_or_alias: php_openssl_add_method, return_value); } /* }}} */ /* {{{ proto array openssl_get_cipher_methods([bool aliases = false]) Return array of available cipher methods */ PHP_FUNCTION(openssl_get_cipher_methods) { zend_bool aliases = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &aliases) == FAILURE) { return; } array_init(return_value); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? php_openssl_add_method_or_alias: php_openssl_add_method, return_value); } /* }}} */ /* {{{ proto array openssl_get_curve_names() Return array of available elliptic curves */ #ifdef HAVE_EVP_PKEY_EC PHP_FUNCTION(openssl_get_curve_names) { EC_builtin_curve *curves = NULL; const char *sname; size_t i; size_t len = EC_get_builtin_curves(NULL, 0); curves = emalloc(sizeof(EC_builtin_curve) * len); if (!EC_get_builtin_curves(curves, len)) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < len; i++) { sname = OBJ_nid2sn(curves[i].nid); if (sname != NULL) { add_next_index_string(return_value, sname); } } efree(curves); } #endif /* }}} */ /* {{{ proto string openssl_digest(string data, string method [, bool raw_output=false]) Computes digest hash value for given data using given method, returns raw or binhex encoded string */ PHP_FUNCTION(openssl_digest) { zend_bool raw_output = 0; char *data, *method; size_t data_len, method_len; const EVP_MD *mdtype; EVP_MD_CTX *md_ctx; unsigned int siglen; zend_string *sigbuf; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|b", &data, &data_len, &method, &method_len, &raw_output) == FAILURE) { return; } mdtype = EVP_get_digestbyname(method); if (!mdtype) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm"); RETURN_FALSE; } siglen = EVP_MD_size(mdtype); sigbuf = zend_string_alloc(siglen, 0); md_ctx = EVP_MD_CTX_create(); if (EVP_DigestInit(md_ctx, mdtype) && EVP_DigestUpdate(md_ctx, (unsigned char *)data, data_len) && EVP_DigestFinal (md_ctx, (unsigned char *)ZSTR_VAL(sigbuf), &siglen)) { if (raw_output) { ZSTR_VAL(sigbuf)[siglen] = '\0'; ZSTR_LEN(sigbuf) = siglen; RETVAL_STR(sigbuf); } else { int digest_str_len = siglen * 2; zend_string *digest_str = zend_string_alloc(digest_str_len, 0); make_digest_ex(ZSTR_VAL(digest_str), (unsigned char*)ZSTR_VAL(sigbuf), siglen); ZSTR_VAL(digest_str)[digest_str_len] = '\0'; zend_string_release_ex(sigbuf, 0); RETVAL_NEW_STR(digest_str); } } else { php_openssl_store_errors(); zend_string_release_ex(sigbuf, 0); RETVAL_FALSE; } EVP_MD_CTX_destroy(md_ctx); } /* }}} */ /* Cipher mode info */ struct php_openssl_cipher_mode { zend_bool is_aead; zend_bool is_single_run_aead; int aead_get_tag_flag; int aead_set_tag_flag; int aead_ivlen_flag; }; static void php_openssl_load_cipher_mode(struct php_openssl_cipher_mode *mode, const EVP_CIPHER *cipher_type) /* {{{ */ { switch (EVP_CIPHER_mode(cipher_type)) { #ifdef EVP_CIPH_GCM_MODE case EVP_CIPH_GCM_MODE: mode->is_aead = 1; mode->is_single_run_aead = 0; mode->aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG; mode->aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG; mode->aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN; break; #endif #ifdef EVP_CIPH_CCM_MODE case EVP_CIPH_CCM_MODE: mode->is_aead = 1; mode->is_single_run_aead = 1; mode->aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG; mode->aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG; mode->aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN; break; #endif default: memset(mode, 0, sizeof(struct php_openssl_cipher_mode)); } } /* }}} */ static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len, zend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */ { char *iv_new; /* Best case scenario, user behaved */ if (*piv_len == iv_required_len) { return SUCCESS; } if (mode->is_aead) { if (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) { php_error_docref(NULL, E_WARNING, "Setting of IV length for AEAD mode failed"); return FAILURE; } return SUCCESS; } iv_new = ecalloc(1, iv_required_len + 1); if (*piv_len == 0) { /* BC behavior */ *piv_len = iv_required_len; *piv = iv_new; *free_iv = 1; return SUCCESS; } if (*piv_len < iv_required_len) { php_error_docref(NULL, E_WARNING, "IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\0", *piv_len, iv_required_len); memcpy(iv_new, *piv, *piv_len); *piv_len = iv_required_len; *piv = iv_new; *free_iv = 1; return SUCCESS; } php_error_docref(NULL, E_WARNING, "IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating", *piv_len, iv_required_len); memcpy(iv_new, *piv, iv_required_len); *piv_len = iv_required_len; *piv = iv_new; *free_iv = 1; return SUCCESS; } /* }}} */ static int php_openssl_cipher_init(const EVP_CIPHER *cipher_type, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode, char **ppassword, size_t *ppassword_len, zend_bool *free_password, char **piv, size_t *piv_len, zend_bool *free_iv, char *tag, int tag_len, zend_long options, int enc) /* {{{ */ { unsigned char *key; int key_len, password_len; size_t max_iv_len; *free_password = 0; max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (enc && *piv_len == 0 && max_iv_len > 0 && !mode->is_aead) { php_error_docref(NULL, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended"); } if (!EVP_CipherInit_ex(cipher_ctx, cipher_type, NULL, NULL, NULL, enc)) { php_openssl_store_errors(); return FAILURE; } if (php_openssl_validate_iv(piv, piv_len, max_iv_len, free_iv, cipher_ctx, mode) == FAILURE) { return FAILURE; } if (mode->is_single_run_aead && enc) { if (!EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_set_tag_flag, tag_len, NULL)) { php_error_docref(NULL, E_WARNING, "Setting tag length for AEAD cipher failed"); return FAILURE; } } else if (!enc && tag && tag_len > 0) { if (!mode->is_aead) { php_error_docref(NULL, E_WARNING, "The tag cannot be used because the cipher method does not support AEAD"); } else if (!EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_set_tag_flag, tag_len, (unsigned char *) tag)) { php_error_docref(NULL, E_WARNING, "Setting tag for AEAD cipher decryption failed"); return FAILURE; } } /* check and set key */ password_len = (int) *ppassword_len; key_len = EVP_CIPHER_key_length(cipher_type); if (key_len > password_len) { if ((OPENSSL_DONT_ZERO_PAD_KEY & options) && !EVP_CIPHER_CTX_set_key_length(cipher_ctx, password_len)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Key length cannot be set for the cipher method"); return FAILURE; } key = emalloc(key_len); memset(key, 0, key_len); memcpy(key, *ppassword, password_len); *ppassword = (char *) key; *ppassword_len = key_len; *free_password = 1; } else { if (password_len > key_len && !EVP_CIPHER_CTX_set_key_length(cipher_ctx, password_len)) { php_openssl_store_errors(); } key = (unsigned char*)*ppassword; } if (!EVP_CipherInit_ex(cipher_ctx, NULL, NULL, key, (unsigned char *)*piv, enc)) { php_openssl_store_errors(); return FAILURE; } if (options & OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } return SUCCESS; } /* }}} */ static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode, zend_string **poutbuf, int *poutlen, char *data, size_t data_len, char *aad, size_t aad_len, int enc) /* {{{ */ { int i = 0; if (mode->is_single_run_aead && !EVP_CipherUpdate(cipher_ctx, NULL, &i, NULL, (int)data_len)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Setting of data length failed"); return FAILURE; } if (mode->is_aead && !EVP_CipherUpdate(cipher_ctx, NULL, &i, (unsigned char *)aad, (int)aad_len)) { php_openssl_store_errors(); php_error_docref(NULL, E_WARNING, "Setting of additional application data failed"); return FAILURE; } *poutbuf = zend_string_alloc((int)data_len + EVP_CIPHER_block_size(cipher_type), 0); if (!EVP_CipherUpdate(cipher_ctx, (unsigned char*)ZSTR_VAL(*poutbuf), &i, (unsigned char *)data, (int)data_len)) { /* we don't show warning when we fail but if we ever do, then it should look like this: if (mode->is_single_run_aead && !enc) { php_error_docref(NULL, E_WARNING, "Tag verifycation failed"); } else { php_error_docref(NULL, E_WARNING, enc ? "Encryption failed" : "Decryption failed"); } */ php_openssl_store_errors(); zend_string_release_ex(*poutbuf, 0); return FAILURE; } *poutlen = i; return SUCCESS; } /* }}} */ PHP_OPENSSL_API zend_string* php_openssl_encrypt(char *data, size_t data_len, char *method, size_t method_len, char *password, size_t password_len, zend_long options, char *iv, size_t iv_len, zval *tag, zend_long tag_len, char *aad, size_t aad_len) { const EVP_CIPHER *cipher_type; EVP_CIPHER_CTX *cipher_ctx; struct php_openssl_cipher_mode mode; int i = 0, outlen; zend_bool free_iv = 0, free_password = 0; zend_string *outbuf = NULL; PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(data_len, data); PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(password_len, password); PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(aad_len, aad); PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(tag_len, tag_len); cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm"); return NULL; } cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { php_error_docref(NULL, E_WARNING, "Failed to create cipher context"); return NULL; } php_openssl_load_cipher_mode(&mode, cipher_type); if (php_openssl_cipher_init(cipher_type, cipher_ctx, &mode, &password, &password_len, &free_password, &iv, &iv_len, &free_iv, NULL, tag_len, options, 1) == FAILURE || php_openssl_cipher_update(cipher_type, cipher_ctx, &mode, &outbuf, &outlen, data, data_len, aad, aad_len, 1) == FAILURE) { outbuf = NULL; } else if (EVP_EncryptFinal(cipher_ctx, (unsigned char *)ZSTR_VAL(outbuf) + outlen, &i)) { outlen += i; if (options & OPENSSL_RAW_DATA) { ZSTR_VAL(outbuf)[outlen] = '\0'; ZSTR_LEN(outbuf) = outlen; } else { zend_string *base64_str; base64_str = php_base64_encode((unsigned char*)ZSTR_VAL(outbuf), outlen); zend_string_release_ex(outbuf, 0); outbuf = base64_str; } if (mode.is_aead && tag) { zend_string *tag_str = zend_string_alloc(tag_len, 0); if (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode.aead_get_tag_flag, tag_len, ZSTR_VAL(tag_str)) == 1) { ZSTR_VAL(tag_str)[tag_len] = '\0'; ZSTR_LEN(tag_str) = tag_len; ZEND_TRY_ASSIGN_REF_NEW_STR(tag, tag_str); } else { php_error_docref(NULL, E_WARNING, "Retrieving verification tag failed"); zend_string_release_ex(tag_str, 0); zend_string_release_ex(outbuf, 0); outbuf = NULL; } } else if (tag) { ZEND_TRY_ASSIGN_REF_NULL(tag); php_error_docref(NULL, E_WARNING, "The authenticated tag cannot be provided for cipher that doesn not support AEAD"); } else if (mode.is_aead) { php_error_docref(NULL, E_WARNING, "A tag should be provided when using AEAD mode"); zend_string_release_ex(outbuf, 0); outbuf = NULL; } } else { php_openssl_store_errors(); zend_string_release_ex(outbuf, 0); outbuf = NULL; } if (free_password) { efree(password); } if (free_iv) { efree(iv); } EVP_CIPHER_CTX_reset(cipher_ctx); EVP_CIPHER_CTX_free(cipher_ctx); return outbuf; } /* {{{ proto string openssl_encrypt(string data, string method, string password [, int options=0 [, string $iv=''[, string &$tag = ''[, string $aad = ''[, int $tag_length = 16]]]]]) Encrypts given data with given method and key, returns raw or base64 encoded string */ PHP_FUNCTION(openssl_encrypt) { zend_long options = 0, tag_len = 16; char *data, *method, *password, *iv = "", *aad = ""; size_t data_len, method_len, password_len, iv_len = 0, aad_len = 0; zend_string *ret; zval *tag = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|lszsl", &data, &data_len, &method, &method_len, &password, &password_len, &options, &iv, &iv_len, &tag, &aad, &aad_len, &tag_len) == FAILURE) { return; } if ((ret = php_openssl_encrypt(data, data_len, method, method_len, password, password_len, options, iv, iv_len, tag, tag_len, aad, aad_len))) { RETVAL_STR(ret); } else { RETVAL_FALSE; } } /* }}} */ PHP_OPENSSL_API zend_string* php_openssl_decrypt(char *data, size_t data_len, char *method, size_t method_len, char *password, size_t password_len, zend_long options, char *iv, size_t iv_len, char *tag, zend_long tag_len, char *aad, size_t aad_len) { const EVP_CIPHER *cipher_type; EVP_CIPHER_CTX *cipher_ctx; struct php_openssl_cipher_mode mode; int i = 0, outlen; zend_string *base64_str = NULL; zend_bool free_iv = 0, free_password = 0; zend_string *outbuf = NULL; PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(data_len, data); PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(password_len, password); PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(aad_len, aad); PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(tag_len, tag); cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm"); return NULL; } cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { php_error_docref(NULL, E_WARNING, "Failed to create cipher context"); return NULL; } php_openssl_load_cipher_mode(&mode, cipher_type); if (!(options & OPENSSL_RAW_DATA)) { base64_str = php_base64_decode((unsigned char*)data, data_len); if (!base64_str) { php_error_docref(NULL, E_WARNING, "Failed to base64 decode the input"); EVP_CIPHER_CTX_free(cipher_ctx); return NULL; } data_len = ZSTR_LEN(base64_str); data = ZSTR_VAL(base64_str); } if (php_openssl_cipher_init(cipher_type, cipher_ctx, &mode, &password, &password_len, &free_password, &iv, &iv_len, &free_iv, tag, tag_len, options, 0) == FAILURE || php_openssl_cipher_update(cipher_type, cipher_ctx, &mode, &outbuf, &outlen, data, data_len, aad, aad_len, 0) == FAILURE) { outbuf = NULL; } else if (mode.is_single_run_aead || EVP_DecryptFinal(cipher_ctx, (unsigned char *)ZSTR_VAL(outbuf) + outlen, &i)) { outlen += i; ZSTR_VAL(outbuf)[outlen] = '\0'; ZSTR_LEN(outbuf) = outlen; } else { php_openssl_store_errors(); zend_string_release_ex(outbuf, 0); outbuf = NULL; } if (free_password) { efree(password); } if (free_iv) { efree(iv); } if (base64_str) { zend_string_release_ex(base64_str, 0); } EVP_CIPHER_CTX_reset(cipher_ctx); EVP_CIPHER_CTX_free(cipher_ctx); return outbuf; } /* {{{ proto string openssl_decrypt(string data, string method, string password [, int options=0 [, string $iv = ''[, string $tag = ''[, string $aad = '']]]]) Takes raw or base64 encoded string and decrypts it using given method and key */ PHP_FUNCTION(openssl_decrypt) { zend_long options = 0; char *data, *method, *password, *iv = "", *tag = NULL, *aad = ""; size_t data_len, method_len, password_len, iv_len = 0, tag_len = 0, aad_len = 0; zend_string *ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|lsss", &data, &data_len, &method, &method_len, &password, &password_len, &options, &iv, &iv_len, &tag, &tag_len, &aad, &aad_len) == FAILURE) { return; } if (!method_len) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm"); RETURN_FALSE; } if ((ret = php_openssl_decrypt(data, data_len, method, method_len, password, password_len, options, iv, iv_len, tag, tag_len, aad, aad_len))) { RETVAL_STR(ret); } else { RETVAL_FALSE; } } /* }}} */ PHP_OPENSSL_API zend_long php_openssl_cipher_iv_length(char *method) { const EVP_CIPHER *cipher_type; cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm"); return -1; } return EVP_CIPHER_iv_length(cipher_type); } /* {{{ proto int openssl_cipher_iv_length(string $method) */ PHP_FUNCTION(openssl_cipher_iv_length) { char *method; size_t method_len; zend_long ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &method, &method_len) == FAILURE) { return; } if (!method_len) { php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm"); RETURN_FALSE; } if ((ret = php_openssl_cipher_iv_length(method)) == -1) { RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ PHP_OPENSSL_API zend_string* php_openssl_random_pseudo_bytes(zend_long buffer_length) { zend_string *buffer = NULL; if (buffer_length <= 0 #ifndef PHP_WIN32 || ZEND_LONG_INT_OVFL(buffer_length) #endif ) { zend_throw_exception(zend_ce_error, "Length must be greater than 0", 0); return NULL; } buffer = zend_string_alloc(buffer_length, 0); #ifdef PHP_WIN32 /* random/urandom equivalent on Windows */ if (php_win32_get_random_bytes((unsigned char*)(buffer)->val, (size_t) buffer_length) == FAILURE){ zend_string_release_ex(buffer, 0); zend_throw_exception(zend_ce_exception, "Error reading from source device", 0); return NULL; } #else PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(buffer_length, length); PHP_OPENSSL_RAND_ADD_TIME(); /* FIXME loop if requested size > INT_MAX */ if (RAND_bytes((unsigned char*)ZSTR_VAL(buffer), (int)buffer_length) <= 0) { zend_string_release_ex(buffer, 0); zend_throw_exception(zend_ce_exception, "Error reading from source device", 0); return NULL; } else { php_openssl_store_errors(); } #endif return buffer; } /* {{{ proto string openssl_random_pseudo_bytes(int length [, &bool returned_strong_result]) Returns a string of the length specified filled with random pseudo bytes */ PHP_FUNCTION(openssl_random_pseudo_bytes) { zend_string *buffer = NULL; zend_long buffer_length; zval *zstrong_result_returned = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) { return; } if (zstrong_result_returned) { ZEND_TRY_ASSIGN_REF_FALSE(zstrong_result_returned); } if ((buffer = php_openssl_random_pseudo_bytes(buffer_length))) { ZSTR_VAL(buffer)[buffer_length] = 0; RETVAL_NEW_STR(buffer); } if (zstrong_result_returned) { ZEND_TRY_ASSIGN_REF_TRUE(zstrong_result_returned); } } /* }}} */
730120.c
/* Test C11 static assertions. Invalid assertions. */ /* { dg-do compile } */ /* { dg-options "-std=c11 -pedantic-errors" } */ _Static_assert (__INT_MAX__ * 2, "overflow"); /* { dg-warning "integer overflow in expression" } */ /* { dg-error "overflow in constant expression" "error" { target *-*-* } .-1 } */ _Static_assert ((void *)(__SIZE_TYPE__)16, "non-integer"); /* { dg-error "not an integer" } */ _Static_assert (1.0, "non-integer"); /* { dg-error "not an integer" } */ _Static_assert ((int)(1.0 + 1.0), "non-constant-expression"); /* { dg-error "not an integer constant expression" } */ int i; _Static_assert (i, "non-constant"); /* { dg-error "not constant" } */ void f (void) { int j = 0; for (_Static_assert (sizeof (struct s { int k; }), ""); j < 10; j++) /* { dg-error "loop initial declaration" } */ ; } _Static_assert (1, 1); /* { dg-error "expected" } */ _Static_assert (1, ("")); /* { dg-error "expected" } */
717666.c
/* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2020-04-16 bigmagic first version */ #include <rthw.h> #include <rtthread.h> #include "board.h" #include "drv_uart.h" #include "cp15.h" #include "mmu.h" #include "mbox.h" struct mem_desc platform_mem_desc[] = { {0x0, 0x6400000, 0x0, NORMAL_MEM}, {0x8000000, 0x8800000, 0x8000000, DEVICE_MEM}, //mbox msg {0x0E000000, 0x0EE00000, 0x0E000000, DEVICE_MEM}, //framebuffer {0x0F400000, 0x0FA00000, 0x0F400000, DEVICE_MEM}, //dsi_touch {0xFD500000, 0xFDA00000, 0xFD500000, DEVICE_MEM}, //gmac {0xFE000000, 0xFF000000, 0xFE000000, DEVICE_MEM}, //peripheral {0xFF800000, 0xFFA00000, 0xFF800000, DEVICE_MEM} //gic }; const rt_uint32_t platform_mem_desc_size = sizeof(platform_mem_desc)/sizeof(platform_mem_desc[0]); void rt_hw_timer_isr(int vector, void *parameter) { ARM_TIMER_IRQCLR = 0; rt_tick_increase(); } void rt_hw_timer_init(void) { rt_uint32_t apb_clock = 0; rt_uint32_t timer_clock = 1000000; /* timer_clock = apb_clock/(pre_divider + 1) */ apb_clock = bcm271x_mbox_clock_get_rate(CORE_CLK_ID); ARM_TIMER_PREDIV = (apb_clock/timer_clock - 1); ARM_TIMER_RELOAD = 0; ARM_TIMER_LOAD = 0; ARM_TIMER_IRQCLR = 0; ARM_TIMER_CTRL = 0; ARM_TIMER_RELOAD = 1000000/RT_TICK_PER_SECOND; ARM_TIMER_LOAD = 1000000/RT_TICK_PER_SECOND; /* 23-bit counter, enable interrupt, enable timer */ ARM_TIMER_CTRL = (1 << 1) | (1 << 5) | (1 << 7); rt_hw_interrupt_install(ARM_TIMER_IRQ, rt_hw_timer_isr, RT_NULL, "tick"); rt_hw_interrupt_umask(ARM_TIMER_IRQ); } void idle_wfi(void) { asm volatile ("wfi"); } /** * Initialize the Hardware related stuffs. Called from rtthread_startup() * after interrupt disabled. */ void rt_hw_board_init(void) { /* initialize hardware interrupt */ rt_hw_interrupt_init(); /* initialize uart */ rt_hw_uart_init(); // driver/drv_uart.c #ifdef RT_USING_CONSOLE /* set console device */ rt_console_set_device(RT_CONSOLE_DEVICE_NAME); #endif /* RT_USING_CONSOLE */ #ifdef RT_USING_HEAP /* initialize memory system */ rt_kprintf("heap: 0x%08x - 0x%08x\n", RT_HW_HEAP_BEGIN, RT_HW_HEAP_END); rt_system_heap_init(RT_HW_HEAP_BEGIN, RT_HW_HEAP_END); #endif /* initialize timer for os tick */ rt_hw_timer_init(); rt_thread_idle_sethook(idle_wfi); #ifdef RT_USING_COMPONENTS_INIT rt_components_board_init(); #endif }
823682.c
/* Copyright 2020 Josh Hinnebusch * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include QMK_KEYBOARD_H // Defines names for use in layer keycodes and the keymap enum layer_names { _BASE, _FN, _FN2, _FN3 }; const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { /* k000, k001, k002, k003, k004, k005, k006, k007, k008, k009, k010, k011, k012, k113, k013, k014, \ k100, k101, k102, k103, k104, k105, k106, k107, k108, k109, k110, k111, k112, k213, k114, \ k200, k201, k202, k203, k204, k205, k206, k207, k208, k209, k210, k211, k212, k313, \ k300, k301, k302, k303, k304, k305, k306, k307, k308, k309, k310, k311, k312, k314, \ k400, k401, k402, k407, k409, k410, k411, k412, k413, k414 \ */ [_BASE] = LAYOUT_all( KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_BSPC, KC_PGUP, KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_PGDN, KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_NUHS, KC_ENT, KC_LSFT, KC_NUBS, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_UP, KC_LCTL, KC_LGUI, KC_LALT, KC_SPC, KC_RALT, MO(1), KC_RCTL, KC_LEFT, KC_DOWN, KC_RGHT), [_FN] = LAYOUT_all( KC_TRNS, RGB_TOG, RGB_MOD, BL_TOGG, BL_DEC, BL_INC, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, RESET, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS), [_FN2] = LAYOUT_all( KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS), [_FN3] = LAYOUT_all( KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS,KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS) };
440685.c
/* * Copyright (C) 2011 Martin Willi * Copyright (C) 2011 revosec AG * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include "certexpire_cron.h" #include <time.h> #include <utils/debug.h> #include <processing/jobs/callback_job.h> typedef struct private_certexpire_cron_t private_certexpire_cron_t; /** * Private data of an certexpire_cron_t object. */ struct private_certexpire_cron_t { /** * Public certexpire_cron_t interface. */ certexpire_cron_t public; /** * time when to run export job */ struct { bool m[60]; bool h[24]; bool d[32]; bool my[13]; bool dw[8]; } cron; /** * Callback function to execute */ certexpire_cron_job_t job; /** * Data to pass to callback */ void *data; }; /** * Check if we should execute the export job */ static job_requeue_t check_cron(private_certexpire_cron_t *this) { struct tm tm; time_t t; t = time(NULL); localtime_r(&t, &tm); /* recheck every minute at second 0 */ lib->scheduler->schedule_job(lib->scheduler, (job_t*)callback_job_create_with_prio((callback_job_cb_t)check_cron, this, NULL, NULL, JOB_PRIO_CRITICAL), 60 - tm.tm_sec); /* skip this minute if we had a large negative time shift */ if (tm.tm_sec <= 30) { if (this->cron.m[tm.tm_min] && this->cron.h[tm.tm_hour] && this->cron.d[tm.tm_mday] && this->cron.my[tm.tm_mon + 1] && (this->cron.dw[tm.tm_wday] || (this->cron.dw[7] && tm.tm_wday == 0))) { this->job(this->data); } } return JOB_REQUEUE_NONE; } /** * Parse a cron range component into boolean fields */ static void parse_ranges(bool *fields, char *label, int mi, int ma, char *range) { enumerator_t *enumerator; int from, to, i; if (streq(range, "*")) { for (i = mi; i <= ma; i++) { fields[i] = TRUE; } } else { enumerator = enumerator_create_token(range, ",", ""); while (enumerator->enumerate(enumerator, &range)) { switch (sscanf(range, "%d-%d", &from, &to)) { case 1: /* single value */ if (from >= mi && from <= ma) { fields[from] = TRUE; } else { DBG1(DBG_CFG, "ignoring cron %s %d, out of range", label, from); } break; case 2: /* range */ if (from < mi) { DBG1(DBG_CFG, "cron %s out of range, shortening start " "from %d to %d", label, from, mi); from = mi; } if (to > ma) { DBG1(DBG_CFG, "cron %s out of range, shortening end " "from %d to %d", label, to, ma); to = ma; } for (i = from; i <= to; i++) { fields[i] = TRUE; } break; default: break; } } enumerator->destroy(enumerator); } DBG3(DBG_CFG, "cron job with enabled %ss:", label); for (i = mi; i <= ma; i++) { if (fields[i]) { DBG3(DBG_CFG, " %d", i); } } } /** * Start cron processing, if configured */ static void start_cron(private_certexpire_cron_t *this, char *cron) { enumerator_t *enumerator; int i = 0; enumerator = enumerator_create_token(cron, " ", " "); for (i = 0; i < 5; i++) { if (!enumerator->enumerate(enumerator, &cron)) { DBG1(DBG_CFG, "cron misses a field, using '*'"); cron = "*"; } switch (i) { case 0: parse_ranges(this->cron.m, "minute", 0, 59, cron); break; case 1: parse_ranges(this->cron.h, "hour", 0, 23, cron); break; case 2: parse_ranges(this->cron.d, "day", 1, 31, cron); break; case 3: parse_ranges(this->cron.my, "month", 1, 12, cron); break; case 4: parse_ranges(this->cron.dw, "weekday", 0, 7, cron); break; default: break; } } if (enumerator->enumerate(enumerator, &cron)) { DBG1(DBG_CFG, "ignoring extra fields in cron"); } enumerator->destroy(enumerator); check_cron(this); } METHOD(certexpire_cron_t, destroy, void, private_certexpire_cron_t *this) { free(this); } /** * See header */ certexpire_cron_t *certexpire_cron_create(char *cron, certexpire_cron_job_t job, void *data) { private_certexpire_cron_t *this; INIT(this, .public = { .destroy = _destroy, }, .job = job, .data = data, ); start_cron(this, cron); return &this->public; }
934433.c
#define _DEFAULT_SOURCE #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <time.h> #ifdef WINDOWS #include <Windows.h> #else // Linux or MacOS #include <termios.h> #endif #include <dirent.h> #include <string.h> #include <gtk/gtk.h> #include "serial.h" #include "error.h" #include "data.h" #include "form.h" #include "threads.h" #include "data.h" #include "error.h" #include "util.h" #include "packet.h" void send_data_packet(struct Data *data, int is_gui, const char *key, const char *value) { if (key == NULL) { timestamp_error(data, is_gui, 0, "key to send was NULL."); return; } if (value == NULL) { timestamp_error(data, is_gui, 0, "value to send was NULL."); return; } int len; if ((len = strlen(key)) > PACKET_KEY_LEN) { timestamp_error(data, is_gui, 0, "Key too large to send (must be < %d chars, is %lu chars)", PACKET_KEY_LEN, len); return; } if ((len = strlen(value)) > ARDUINO_MESG_LEN/2) { timestamp_error(data, is_gui, 0, "Value too large to send (must be < %d chars, is %lu chars)", PACKET_VALUE_LEN, len); return; } char mesg[ARDUINO_MESG_LEN] = {0}; snprintf(mesg, ARDUINO_MESG_LEN, "%s=%s", key, value); timestamp(NULL, is_gui, "sending k/v pair: %s", mesg); write(data->serial_fd, mesg, ARDUINO_MESG_LEN); switch (wait_for(data, is_gui, "OK", 10, &data->connect_worker_status, THREAD_CANCELLED)) { case -1: timestamp_error(NULL, is_gui, 0, "Cancelled by user."); return; case -2: timestamp_error(NULL, is_gui, 0, "Arduino didn't understand message"); // TODO: deal with this properly exit(1); } timestamp(data, is_gui, "Sent data { %s = %s } successfully.", key, value); } int wait_for(struct Data *data, int is_gui, const char *trigger, int timeout_s, int *flagaddr, int stopval) { int delay_us = 10 * 1000; int timeout_n = (1000 * 1000 * timeout_s) / delay_us; if (trigger == NULL) { timestamp(NULL, 0, "NULL TRIGGER"); } if (flagaddr == NULL) { timestamp(NULL, 0, "NULL FLAGADDR"); } for (int time = 0; time < timeout_n; time++) { char buffer[512] = {0}; read_serial_line(data, buffer, 512, 10); if (strcmp(buffer, trigger) == 0) return 0; //ptble_usleep(delay_us); if ((*flagaddr) == stopval) return -1; timestamp(NULL, is_gui, "waiting for \"%s\" (%ds / %ds)", trigger, (int)( ((float)time+1) * ((float)delay_us) / ((float)timeout_n) ), timeout_s); } return -2; } #ifdef WINDOWS // https://www.xanthium.in/Serial-port-Programming-using-win32-api int open_serial(const char *serial_port_path, struct Data *data) { HANDLE serial_handle = CreateFile(serial_port_path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (serial_handle == INVALID_HANDLE_VALUE) return -1; DCB serial_params = { 0 }; serial_params.DCBlength = sizeof(serial_params); GetCommState(serial_handle, &serial_params); // 9600 8N1 serial_params.BaudRate = CBR_9600; serial_params.ByteSize = 8; serial_params.parity = NOPARITY; serial_params.StopBits = ONESTOPBIT; if (!SetCommState(serial_handle, &serial_params)) { CloseHandle(serial_handle); return -2; } // timeout settings COMMTIMEOUTS serial_timeouts = { 0 }; serial_timeouts.ReadIntervalTimeout = 50; serial_timeouts.ReadTotalTimeoutConstant = 50; serial_timeouts.ReadTotalTimeoutMultiplier = 10; serial_timeouts.WriteTotalTimeoutConstant = 50; serial_timeouts.WriteTotalTimeoutMultiplier = 10; if (!SetCommTimeouts(serial_handle, &serial_timeouts)) { CloseHandle(serial_handle); return -3; } data->serial_handle = serial_handle; return 0; } #else // NOT WINDOWS: MACOS OR LINUX int open_serial(const char *serial_port_path, struct Data *data) { int fd; fd = open(serial_port_path, O_RDWR | O_NOCTTY); if (fd < 0) return -1; // prepare serial for input from arduino // https://chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/ // man 3 termios struct termios toptions; tcgetattr(fd, &toptions); // 9600 BAUD cfsetispeed(&toptions, B9600); cfsetospeed(&toptions, B9600); // control options toptions.c_cflag &= ~PARENB; // no parity toptions.c_cflag &= ~CSTOPB; // no second stop bit toptions.c_cflag &= ~CSIZE; // unset character size toptions.c_cflag |= CS8; // set char size to 8 toptions.c_cflag &= ~CRTSCTS; // hardware flow control toptions.c_cflag |= CREAD; // enable receiver toptions.c_cflag |= CLOCAL; // ignore modem control lines // input options toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // ?? options toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // output options toptions.c_oflag &= ~OPOST; // minimum bytes to read, timeout // this combination represents "blocking read" //toptions.c_cc[VMIN] = 1; //toptions.c_cc[VTIME] = 0; // polling read: int read(fd) is non-blocking toptions.c_cc[VMIN] = 0; toptions.c_cc[VTIME] = 2; if (tcsetattr(fd, TCSANOW, &toptions)) { close(fd); return -2; } // give the arduino a little bit of time to catch up usleep(100*1000); //flush stream tcflush(fd, TCIFLUSH); data->serial_fd = fd; return 0; } int is_serial_open(struct Data *data) { #ifdef WINDOWS // TODO #else return data->serial_fd > 0; #endif } int close_serial(struct Data *data) { #ifdef WINDOWS int rv = !CloseHandle(data->serial_handle); #else int rv = close(data->serial_fd); if (!rv) data->serial_fd = -1; #endif return rv; } int read_serial_until( struct Data *data, char* buf, int buf_max, char until, int timeout) { #ifdef WINDOWS // wait for arduino to start sending data SetCommMask(serial_handle, EV_RXCHAR); DWORD event_dat; if (!WaitCommEvent(serial_handle, &event_data, NULL)) return -1; #endif char ch[1] = {0}; int rx_bytes_count = 0, n = 0; do { #ifdef WINDOWS // todo non blocking (cancelable) ReadFile(serial_handle, ch, sizeof(char), &rx_bytes_count, NULL); #else // read until we get something, or connection times out while ((n = read(data->serial_fd, ch, 1)) < 1) { if (n < 0 || timeout == 0) return -1; //ptble_usleep(10); timeout --; } #endif if (ch[0] == until) return 0; else buf[rx_bytes_count] = ch[0]; rx_bytes_count++; } while(rx_bytes_count > 0 && rx_bytes_count < buf_max); buf[buf_max-1] = 0; // reached end of buffer return -2; } int read_serial_line( struct Data *data, char *buf, int buf_max, int timeout) { return read_serial_until(data, buf, buf_max, '\n', timeout); } int write_serial(struct Data *data, char *mesg, int mesglen) { int written = 0; #ifdef WINDOWS int resp = !WriteFile(data->serial_handle, mesg, mesglen, &written); if (!resp) return -1; #else written = write(data->serial_fd, mesg, mesglen); if (written < 0) return -1; #endif if (written != mesglen) return -2; return 0; } #endif
627391.c
/**************************************************************************/ /* */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* */ /* This software is licensed under the Microsoft Software License */ /* Terms for Microsoft Azure RTOS. Full text of the license can be */ /* found in the LICENSE file at https://aka.ms/AzureRTOS_EULA */ /* and in the root directory of this software. */ /* */ /**************************************************************************/ /**************************************************************************/ /**************************************************************************/ /** */ /** USBX Component */ /** */ /** Host Simulator Controller Driver */ /** */ /**************************************************************************/ /**************************************************************************/ #define UX_SOURCE_CODE /* Include necessary system files. */ #include "ux_api.h" #include "ux_hcd_sim_host.h" /**************************************************************************/ /* */ /* FUNCTION RELEASE */ /* */ /* _ux_hcd_sim_host_asynch_schedule PORTABLE C */ /* 6.1 */ /* AUTHOR */ /* */ /* Chaoqiong Xiao, Microsoft Corporation */ /* */ /* DESCRIPTION */ /* */ /* This function schedules new transfers from the control/bulk lists. */ /* */ /* INPUT */ /* */ /* hcd_sim_host Pointer to host controller */ /* */ /* OUTPUT */ /* */ /* None */ /* */ /* CALLS */ /* */ /* _ux_hcd_sim_host_transaction_schedule Schedule simulator transaction*/ /* */ /* CALLED BY */ /* */ /* Host Simulator Controller Driver */ /* */ /* RELEASE HISTORY */ /* */ /* DATE NAME DESCRIPTION */ /* */ /* 05-19-2020 Chaoqiong Xiao Initial Version 6.0 */ /* 09-30-2020 Chaoqiong Xiao Modified comment(s), */ /* resulting in version 6.1 */ /* */ /**************************************************************************/ VOID _ux_hcd_sim_host_asynch_schedule(UX_HCD_SIM_HOST *hcd_sim_host) { UX_HCD_SIM_HOST_ED *ed; UX_HCD_SIM_HOST_ED *first_ed; UINT status; /* Get the pointer to the current ED in the asynchronous list. */ ed = hcd_sim_host -> ux_hcd_sim_host_asynch_current_ed; /* Check if there is any ED candidate in the asynch list. */ if (ed == UX_NULL) { /* Check if there is any ED in the asynch list. If none, nothing to do. */ if (hcd_sim_host -> ux_hcd_sim_host_asynch_head_ed == UX_NULL) return; else ed = hcd_sim_host -> ux_hcd_sim_host_asynch_head_ed; } /* Remember this ED. */ first_ed = ed; /* In simulation, we are not tied to bandwidth limitation. */ do { /* Check if this ED has a tail and head TD different. */ if (ed -> ux_sim_host_ed_tail_td != ed -> ux_sim_host_ed_head_td) { /* Schedule this transaction with the device simulator. */ status = _ux_hcd_sim_host_transaction_schedule(hcd_sim_host, ed); /* If the TD has been added to the list, we can memorize this ED has being served and make the next ED as the one to be first scanned at the next SOF. */ if (status == UX_SUCCESS) { if (ed -> ux_sim_host_ed_next_ed == UX_NULL) hcd_sim_host -> ux_hcd_sim_host_asynch_current_ed = hcd_sim_host -> ux_hcd_sim_host_asynch_head_ed; else hcd_sim_host -> ux_hcd_sim_host_asynch_current_ed = ed -> ux_sim_host_ed_next_ed; } } /* Point to the next ED in the list. Check if at end of list. */ if (ed -> ux_sim_host_ed_next_ed == UX_NULL) ed = hcd_sim_host -> ux_hcd_sim_host_asynch_head_ed; else ed = ed -> ux_sim_host_ed_next_ed; } while ((ed) && (ed != first_ed)); }
389006.c
/********************************************************************** * Copyright (c) 2013, 2014, 2015 Pieter Wuille, Gregory Maxwell * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "secp256k1.c" #include "include/secp256k1.h" #include "testrand_impl.h" #ifdef ENABLE_OPENSSL_TESTS #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/ecdsa.h" #include "openssl/obj_mac.h" #endif #include "contrib/lax_der_parsing.c" #include "contrib/lax_der_privatekey_parsing.c" #if !defined(VG_CHECK) # if defined(VALGRIND) # include <valgrind/memcheck.h> # define VG_UNDEF(x,y) VALGRIND_MAKE_MEM_UNDEFINED((x),(y)) # define VG_CHECK(x,y) VALGRIND_CHECK_MEM_IS_DEFINED((x),(y)) # else # define VG_UNDEF(x,y) # define VG_CHECK(x,y) # endif #endif static int count = 64; static secp256k1_context *ctx = NULL; static void counting_illegal_callback_fn(const char* str, void* data) { /* Dummy callback function that just counts. */ int32_t *p; (void)str; p = data; (*p)++; } static void uncounting_illegal_callback_fn(const char* str, void* data) { /* Dummy callback function that just counts (backwards). */ int32_t *p; (void)str; p = data; (*p)--; } void random_field_element_test(secp256k1_fe *fe) { do { unsigned char b32[32]; secp256k1_rand256_test(b32); if (secp256k1_fe_set_b32(fe, b32)) { break; } } while(1); } void random_field_element_magnitude(secp256k1_fe *fe) { secp256k1_fe zero; int n = secp256k1_rand_int(9); secp256k1_fe_normalize(fe); if (n == 0) { return; } secp256k1_fe_clear(&zero); secp256k1_fe_negate(&zero, &zero, 0); secp256k1_fe_mul_int(&zero, n - 1); secp256k1_fe_add(fe, &zero); VERIFY_CHECK(fe->magnitude == n); } void random_group_element_test(secp256k1_ge *ge) { secp256k1_fe fe; do { random_field_element_test(&fe); if (secp256k1_ge_set_xo_var(ge, &fe, secp256k1_rand_bits(1))) { secp256k1_fe_normalize(&ge->y); break; } } while(1); } void random_group_element_jacobian_test(secp256k1_gej *gej, const secp256k1_ge *ge) { secp256k1_fe z2, z3; do { random_field_element_test(&gej->z); if (!secp256k1_fe_is_zero(&gej->z)) { break; } } while(1); secp256k1_fe_sqr(&z2, &gej->z); secp256k1_fe_mul(&z3, &z2, &gej->z); secp256k1_fe_mul(&gej->x, &ge->x, &z2); secp256k1_fe_mul(&gej->y, &ge->y, &z3); gej->infinity = ge->infinity; } void random_scalar_order_test(secp256k1_scalar *num) { do { unsigned char b32[32]; int overflow = 0; secp256k1_rand256_test(b32); secp256k1_scalar_set_b32(num, b32, &overflow); if (overflow || secp256k1_scalar_is_zero(num)) { continue; } break; } while(1); } void random_scalar_order(secp256k1_scalar *num) { do { unsigned char b32[32]; int overflow = 0; secp256k1_rand256(b32); secp256k1_scalar_set_b32(num, b32, &overflow); if (overflow || secp256k1_scalar_is_zero(num)) { continue; } break; } while(1); } void run_context_tests(void) { secp256k1_pubkey pubkey; secp256k1_pubkey zero_pubkey; secp256k1_ecdsa_signature sig; unsigned char ctmp[32]; int32_t ecount; int32_t ecount2; secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); secp256k1_gej pubj; secp256k1_ge pub; secp256k1_scalar msg, key, nonce; secp256k1_scalar sigr, sigs; memset(&zero_pubkey, 0, sizeof(zero_pubkey)); ecount = 0; ecount2 = 10; secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount2); secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, NULL); CHECK(vrfy->error_callback.fn != sign->error_callback.fn); /*** clone and destroy all of them to make sure cloning was complete ***/ { secp256k1_context *ctx_tmp; ctx_tmp = none; none = secp256k1_context_clone(none); secp256k1_context_destroy(ctx_tmp); ctx_tmp = sign; sign = secp256k1_context_clone(sign); secp256k1_context_destroy(ctx_tmp); ctx_tmp = vrfy; vrfy = secp256k1_context_clone(vrfy); secp256k1_context_destroy(ctx_tmp); ctx_tmp = both; both = secp256k1_context_clone(both); secp256k1_context_destroy(ctx_tmp); } /* Verify that the error callback makes it across the clone. */ CHECK(vrfy->error_callback.fn != sign->error_callback.fn); /* And that it resets back to default. */ secp256k1_context_set_error_callback(sign, NULL, NULL); CHECK(vrfy->error_callback.fn == sign->error_callback.fn); /*** attempt to use them ***/ random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_ecmult_gen(&both->ecmult_gen_ctx, &pubj, &key); secp256k1_ge_set_gej(&pub, &pubj); /* Verify context-type checking illegal-argument errors. */ memset(ctmp, 1, 32); CHECK(secp256k1_ec_pubkey_create(vrfy, &pubkey, ctmp) == 0); CHECK(ecount == 1); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(sign, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ecdsa_sign(vrfy, &sig, ctmp, ctmp, NULL, NULL) == 0); CHECK(ecount == 2); VG_UNDEF(&sig, sizeof(sig)); CHECK(secp256k1_ecdsa_sign(sign, &sig, ctmp, ctmp, NULL, NULL) == 1); VG_CHECK(&sig, sizeof(sig)); CHECK(ecount2 == 10); CHECK(secp256k1_ecdsa_verify(sign, &sig, ctmp, &pubkey) == 0); CHECK(ecount2 == 11); CHECK(secp256k1_ecdsa_verify(vrfy, &sig, ctmp, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_tweak_add(sign, &pubkey, ctmp) == 0); CHECK(ecount2 == 12); CHECK(secp256k1_ec_pubkey_tweak_add(vrfy, &pubkey, ctmp) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_tweak_mul(sign, &pubkey, ctmp) == 0); CHECK(ecount2 == 13); CHECK(secp256k1_ec_pubkey_negate(vrfy, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_negate(sign, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_negate(sign, NULL) == 0); CHECK(ecount2 == 14); CHECK(secp256k1_ec_pubkey_negate(vrfy, &zero_pubkey) == 0); CHECK(ecount == 3); CHECK(secp256k1_ec_pubkey_tweak_mul(vrfy, &pubkey, ctmp) == 1); CHECK(ecount == 3); CHECK(secp256k1_context_randomize(vrfy, ctmp) == 0); CHECK(ecount == 4); CHECK(secp256k1_context_randomize(sign, NULL) == 1); CHECK(ecount2 == 14); secp256k1_context_set_illegal_callback(vrfy, NULL, NULL); secp256k1_context_set_illegal_callback(sign, NULL, NULL); /* This shouldn't leak memory, due to already-set tests. */ secp256k1_ecmult_gen_context_build(&sign->ecmult_gen_ctx, NULL); secp256k1_ecmult_context_build(&vrfy->ecmult_ctx, NULL); /* obtain a working nonce */ do { random_scalar_order_test(&nonce); } while(!secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); /* try signing */ CHECK(secp256k1_ecdsa_sig_sign(&sign->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); CHECK(secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); /* try verifying */ CHECK(secp256k1_ecdsa_sig_verify(&vrfy->ecmult_ctx, &sigr, &sigs, &pub, &msg)); CHECK(secp256k1_ecdsa_sig_verify(&both->ecmult_ctx, &sigr, &sigs, &pub, &msg)); /* cleanup */ secp256k1_context_destroy(none); secp256k1_context_destroy(sign); secp256k1_context_destroy(vrfy); secp256k1_context_destroy(both); /* Defined as no-op. */ secp256k1_context_destroy(NULL); } /***** HASH TESTS *****/ void run_sha256_tests(void) { static const char *inputs[8] = { "", "abc", "message digest", "secure hash algorithm", "SHA256 is considered to be safe", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "For this sample, this 63-byte string will be used as input data", "This is exactly 64 bytes long, not counting the terminating byte" }; static const unsigned char outputs[8][32] = { {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}, {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}, {0xf7, 0x84, 0x6f, 0x55, 0xcf, 0x23, 0xe1, 0x4e, 0xeb, 0xea, 0xb5, 0xb4, 0xe1, 0x55, 0x0c, 0xad, 0x5b, 0x50, 0x9e, 0x33, 0x48, 0xfb, 0xc4, 0xef, 0xa3, 0xa1, 0x41, 0x3d, 0x39, 0x3c, 0xb6, 0x50}, {0xf3, 0x0c, 0xeb, 0x2b, 0xb2, 0x82, 0x9e, 0x79, 0xe4, 0xca, 0x97, 0x53, 0xd3, 0x5a, 0x8e, 0xcc, 0x00, 0x26, 0x2d, 0x16, 0x4c, 0xc0, 0x77, 0x08, 0x02, 0x95, 0x38, 0x1c, 0xbd, 0x64, 0x3f, 0x0d}, {0x68, 0x19, 0xd9, 0x15, 0xc7, 0x3f, 0x4d, 0x1e, 0x77, 0xe4, 0xe1, 0xb5, 0x2d, 0x1f, 0xa0, 0xf9, 0xcf, 0x9b, 0xea, 0xea, 0xd3, 0x93, 0x9f, 0x15, 0x87, 0x4b, 0xd9, 0x88, 0xe2, 0xa2, 0x36, 0x30}, {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}, {0xf0, 0x8a, 0x78, 0xcb, 0xba, 0xee, 0x08, 0x2b, 0x05, 0x2a, 0xe0, 0x70, 0x8f, 0x32, 0xfa, 0x1e, 0x50, 0xc5, 0xc4, 0x21, 0xaa, 0x77, 0x2b, 0xa5, 0xdb, 0xb4, 0x06, 0xa2, 0xea, 0x6b, 0xe3, 0x42}, {0xab, 0x64, 0xef, 0xf7, 0xe8, 0x8e, 0x2e, 0x46, 0x16, 0x5e, 0x29, 0xf2, 0xbc, 0xe4, 0x18, 0x26, 0xbd, 0x4c, 0x7b, 0x35, 0x52, 0xf6, 0xb3, 0x82, 0xa9, 0xe7, 0xd3, 0xaf, 0x47, 0xc2, 0x45, 0xf8} }; int i; for (i = 0; i < 8; i++) { unsigned char out[32]; secp256k1_sha256_t hasher; secp256k1_sha256_initialize(&hasher); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); secp256k1_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); if (strlen(inputs[i]) > 0) { int split = secp256k1_rand_int(strlen(inputs[i])); secp256k1_sha256_initialize(&hasher); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); secp256k1_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); } } } void run_hmac_sha256_tests(void) { static const char *keys[6] = { "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", "\x4a\x65\x66\x65", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" }; static const char *inputs[6] = { "\x48\x69\x20\x54\x68\x65\x72\x65", "\x77\x68\x61\x74\x20\x64\x6f\x20\x79\x61\x20\x77\x61\x6e\x74\x20\x66\x6f\x72\x20\x6e\x6f\x74\x68\x69\x6e\x67\x3f", "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", "\x54\x65\x73\x74\x20\x55\x73\x69\x6e\x67\x20\x4c\x61\x72\x67\x65\x72\x20\x54\x68\x61\x6e\x20\x42\x6c\x6f\x63\x6b\x2d\x53\x69\x7a\x65\x20\x4b\x65\x79\x20\x2d\x20\x48\x61\x73\x68\x20\x4b\x65\x79\x20\x46\x69\x72\x73\x74", "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x20\x75\x73\x69\x6e\x67\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x6b\x65\x79\x20\x61\x6e\x64\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x64\x61\x74\x61\x2e\x20\x54\x68\x65\x20\x6b\x65\x79\x20\x6e\x65\x65\x64\x73\x20\x74\x6f\x20\x62\x65\x20\x68\x61\x73\x68\x65\x64\x20\x62\x65\x66\x6f\x72\x65\x20\x62\x65\x69\x6e\x67\x20\x75\x73\x65\x64\x20\x62\x79\x20\x74\x68\x65\x20\x48\x4d\x41\x43\x20\x61\x6c\x67\x6f\x72\x69\x74\x68\x6d\x2e" }; static const unsigned char outputs[6][32] = { {0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7}, {0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43}, {0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe}, {0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b}, {0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54}, {0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2} }; int i; for (i = 0; i < 6; i++) { secp256k1_hmac_sha256_t hasher; unsigned char out[32]; secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); secp256k1_hmac_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); if (strlen(inputs[i]) > 0) { int split = secp256k1_rand_int(strlen(inputs[i])); secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); secp256k1_hmac_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); } } } void run_rfc6979_hmac_sha256_tests(void) { static const unsigned char key1[65] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x4b, 0xf5, 0x12, 0x2f, 0x34, 0x45, 0x54, 0xc5, 0x3b, 0xde, 0x2e, 0xbb, 0x8c, 0xd2, 0xb7, 0xe3, 0xd1, 0x60, 0x0a, 0xd6, 0x31, 0xc3, 0x85, 0xa5, 0xd7, 0xcc, 0xe2, 0x3c, 0x77, 0x85, 0x45, 0x9a, 0}; static const unsigned char out1[3][32] = { {0x4f, 0xe2, 0x95, 0x25, 0xb2, 0x08, 0x68, 0x09, 0x15, 0x9a, 0xcd, 0xf0, 0x50, 0x6e, 0xfb, 0x86, 0xb0, 0xec, 0x93, 0x2c, 0x7b, 0xa4, 0x42, 0x56, 0xab, 0x32, 0x1e, 0x42, 0x1e, 0x67, 0xe9, 0xfb}, {0x2b, 0xf0, 0xff, 0xf1, 0xd3, 0xc3, 0x78, 0xa2, 0x2d, 0xc5, 0xde, 0x1d, 0x85, 0x65, 0x22, 0x32, 0x5c, 0x65, 0xb5, 0x04, 0x49, 0x1a, 0x0c, 0xbd, 0x01, 0xcb, 0x8f, 0x3a, 0xa6, 0x7f, 0xfd, 0x4a}, {0xf5, 0x28, 0xb4, 0x10, 0xcb, 0x54, 0x1f, 0x77, 0x00, 0x0d, 0x7a, 0xfb, 0x6c, 0x5b, 0x53, 0xc5, 0xc4, 0x71, 0xea, 0xb4, 0x3e, 0x46, 0x6d, 0x9a, 0xc5, 0x19, 0x0c, 0x39, 0xc8, 0x2f, 0xd8, 0x2e} }; static const unsigned char key2[64] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}; static const unsigned char out2[3][32] = { {0x9c, 0x23, 0x6c, 0x16, 0x5b, 0x82, 0xae, 0x0c, 0xd5, 0x90, 0x65, 0x9e, 0x10, 0x0b, 0x6b, 0xab, 0x30, 0x36, 0xe7, 0xba, 0x8b, 0x06, 0x74, 0x9b, 0xaf, 0x69, 0x81, 0xe1, 0x6f, 0x1a, 0x2b, 0x95}, {0xdf, 0x47, 0x10, 0x61, 0x62, 0x5b, 0xc0, 0xea, 0x14, 0xb6, 0x82, 0xfe, 0xee, 0x2c, 0x9c, 0x02, 0xf2, 0x35, 0xda, 0x04, 0x20, 0x4c, 0x1d, 0x62, 0xa1, 0x53, 0x6c, 0x6e, 0x17, 0xae, 0xd7, 0xa9}, {0x75, 0x97, 0x88, 0x7c, 0xbd, 0x76, 0x32, 0x1f, 0x32, 0xe3, 0x04, 0x40, 0x67, 0x9a, 0x22, 0xcf, 0x7f, 0x8d, 0x9d, 0x2e, 0xac, 0x39, 0x0e, 0x58, 0x1f, 0xea, 0x09, 0x1c, 0xe2, 0x02, 0xba, 0x94} }; secp256k1_rfc6979_hmac_sha256_t rng; unsigned char out[32]; int i; secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 64); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out1[i], 32) == 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 65); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out1[i], 32) != 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); secp256k1_rfc6979_hmac_sha256_initialize(&rng, key2, 64); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out2[i], 32) == 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); } /***** RANDOM TESTS *****/ void test_rand_bits(int rand32, int bits) { /* (1-1/2^B)^rounds[B] < 1/10^9, so rounds is the number of iterations to * get a false negative chance below once in a billion */ static const unsigned int rounds[7] = {1, 30, 73, 156, 322, 653, 1316}; /* We try multiplying the results with various odd numbers, which shouldn't * influence the uniform distribution modulo a power of 2. */ static const uint32_t mults[6] = {1, 3, 21, 289, 0x9999, 0x80402011}; /* We only select up to 6 bits from the output to analyse */ unsigned int usebits = bits > 6 ? 6 : bits; unsigned int maxshift = bits - usebits; /* For each of the maxshift+1 usebits-bit sequences inside a bits-bit number, track all observed outcomes, one per bit in a uint64_t. */ uint64_t x[6][27] = {{0}}; unsigned int i, shift, m; /* Multiply the output of all rand calls with the odd number m, which should not change the uniformity of its distribution. */ for (i = 0; i < rounds[usebits]; i++) { uint32_t r = (rand32 ? secp256k1_rand32() : secp256k1_rand_bits(bits)); CHECK((((uint64_t)r) >> bits) == 0); for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) { uint32_t rm = r * mults[m]; for (shift = 0; shift <= maxshift; shift++) { x[m][shift] |= (((uint64_t)1) << ((rm >> shift) & ((1 << usebits) - 1))); } } } for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) { for (shift = 0; shift <= maxshift; shift++) { /* Test that the lower usebits bits of x[shift] are 1 */ CHECK(((~x[m][shift]) << (64 - (1 << usebits))) == 0); } } } /* Subrange must be a whole divisor of range, and at most 64 */ void test_rand_int(uint32_t range, uint32_t subrange) { /* (1-1/subrange)^rounds < 1/10^9 */ int rounds = (subrange * 2073) / 100; int i; uint64_t x = 0; CHECK((range % subrange) == 0); for (i = 0; i < rounds; i++) { uint32_t r = secp256k1_rand_int(range); CHECK(r < range); r = r % subrange; x |= (((uint64_t)1) << r); } /* Test that the lower subrange bits of x are 1. */ CHECK(((~x) << (64 - subrange)) == 0); } void run_rand_bits(void) { size_t b; test_rand_bits(1, 32); for (b = 1; b <= 32; b++) { test_rand_bits(0, b); } } void run_rand_int(void) { static const uint32_t ms[] = {1, 3, 17, 1000, 13771, 999999, 33554432}; static const uint32_t ss[] = {1, 3, 6, 9, 13, 31, 64}; unsigned int m, s; for (m = 0; m < sizeof(ms) / sizeof(ms[0]); m++) { for (s = 0; s < sizeof(ss) / sizeof(ss[0]); s++) { test_rand_int(ms[m] * ss[s], ss[s]); } } } /***** NUM TESTS *****/ #ifndef USE_NUM_NONE void random_num_negate(secp256k1_num *num) { if (secp256k1_rand_bits(1)) { secp256k1_num_negate(num); } } void random_num_order_test(secp256k1_num *num) { secp256k1_scalar sc; random_scalar_order_test(&sc); secp256k1_scalar_get_num(num, &sc); } void random_num_order(secp256k1_num *num) { secp256k1_scalar sc; random_scalar_order(&sc); secp256k1_scalar_get_num(num, &sc); } void test_num_negate(void) { secp256k1_num n1; secp256k1_num n2; random_num_order_test(&n1); /* n1 = R */ random_num_negate(&n1); secp256k1_num_copy(&n2, &n1); /* n2 = R */ secp256k1_num_sub(&n1, &n2, &n1); /* n1 = n2-n1 = 0 */ CHECK(secp256k1_num_is_zero(&n1)); secp256k1_num_copy(&n1, &n2); /* n1 = R */ secp256k1_num_negate(&n1); /* n1 = -R */ CHECK(!secp256k1_num_is_zero(&n1)); secp256k1_num_add(&n1, &n2, &n1); /* n1 = n2+n1 = 0 */ CHECK(secp256k1_num_is_zero(&n1)); secp256k1_num_copy(&n1, &n2); /* n1 = R */ secp256k1_num_negate(&n1); /* n1 = -R */ CHECK(secp256k1_num_is_neg(&n1) != secp256k1_num_is_neg(&n2)); secp256k1_num_negate(&n1); /* n1 = R */ CHECK(secp256k1_num_eq(&n1, &n2)); } void test_num_add_sub(void) { int i; secp256k1_scalar s; secp256k1_num n1; secp256k1_num n2; secp256k1_num n1p2, n2p1, n1m2, n2m1; random_num_order_test(&n1); /* n1 = R1 */ if (secp256k1_rand_bits(1)) { random_num_negate(&n1); } random_num_order_test(&n2); /* n2 = R2 */ if (secp256k1_rand_bits(1)) { random_num_negate(&n2); } secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = R1 + R2 */ secp256k1_num_add(&n2p1, &n2, &n1); /* n2p1 = R2 + R1 */ secp256k1_num_sub(&n1m2, &n1, &n2); /* n1m2 = R1 - R2 */ secp256k1_num_sub(&n2m1, &n2, &n1); /* n2m1 = R2 - R1 */ CHECK(secp256k1_num_eq(&n1p2, &n2p1)); CHECK(!secp256k1_num_eq(&n1p2, &n1m2)); secp256k1_num_negate(&n2m1); /* n2m1 = -R2 + R1 */ CHECK(secp256k1_num_eq(&n2m1, &n1m2)); CHECK(!secp256k1_num_eq(&n2m1, &n1)); secp256k1_num_add(&n2m1, &n2m1, &n2); /* n2m1 = -R2 + R1 + R2 = R1 */ CHECK(secp256k1_num_eq(&n2m1, &n1)); CHECK(!secp256k1_num_eq(&n2p1, &n1)); secp256k1_num_sub(&n2p1, &n2p1, &n2); /* n2p1 = R2 + R1 - R2 = R1 */ CHECK(secp256k1_num_eq(&n2p1, &n1)); /* check is_one */ secp256k1_scalar_set_int(&s, 1); secp256k1_scalar_get_num(&n1, &s); CHECK(secp256k1_num_is_one(&n1)); /* check that 2^n + 1 is never 1 */ secp256k1_scalar_get_num(&n2, &s); for (i = 0; i < 250; ++i) { secp256k1_num_add(&n1, &n1, &n1); /* n1 *= 2 */ secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = n1 + 1 */ CHECK(!secp256k1_num_is_one(&n1p2)); } } void test_num_mod(void) { int i; secp256k1_scalar s; secp256k1_num order, n; /* check that 0 mod anything is 0 */ random_scalar_order_test(&s); secp256k1_scalar_get_num(&order, &s); secp256k1_scalar_set_int(&s, 0); secp256k1_scalar_get_num(&n, &s); secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); /* check that anything mod 1 is 0 */ secp256k1_scalar_set_int(&s, 1); secp256k1_scalar_get_num(&order, &s); secp256k1_scalar_get_num(&n, &s); secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); /* check that increasing the number past 2^256 does not break this */ random_scalar_order_test(&s); secp256k1_scalar_get_num(&n, &s); /* multiply by 2^8, which'll test this case with high probability */ for (i = 0; i < 8; ++i) { secp256k1_num_add(&n, &n, &n); } secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); } void test_num_jacobi(void) { secp256k1_scalar sqr; secp256k1_scalar small; secp256k1_scalar five; /* five is not a quadratic residue */ secp256k1_num order, n; int i; /* squares mod 5 are 1, 4 */ const int jacobi5[10] = { 0, 1, -1, -1, 1, 0, 1, -1, -1, 1 }; /* check some small values with 5 as the order */ secp256k1_scalar_set_int(&five, 5); secp256k1_scalar_get_num(&order, &five); for (i = 0; i < 10; ++i) { secp256k1_scalar_set_int(&small, i); secp256k1_scalar_get_num(&n, &small); CHECK(secp256k1_num_jacobi(&n, &order) == jacobi5[i]); } /** test large values with 5 as group order */ secp256k1_scalar_get_num(&order, &five); /* we first need a scalar which is not a multiple of 5 */ do { secp256k1_num fiven; random_scalar_order_test(&sqr); secp256k1_scalar_get_num(&fiven, &five); secp256k1_scalar_get_num(&n, &sqr); secp256k1_num_mod(&n, &fiven); } while (secp256k1_num_is_zero(&n)); /* next force it to be a residue. 2 is a nonresidue mod 5 so we can * just multiply by two, i.e. add the number to itself */ if (secp256k1_num_jacobi(&n, &order) == -1) { secp256k1_num_add(&n, &n, &n); } /* test residue */ CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* test nonresidue */ secp256k1_num_add(&n, &n, &n); CHECK(secp256k1_num_jacobi(&n, &order) == -1); /** test with secp group order as order */ secp256k1_scalar_order_get_num(&order); random_scalar_order_test(&sqr); secp256k1_scalar_sqr(&sqr, &sqr); /* test residue */ secp256k1_scalar_get_num(&n, &sqr); CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* test nonresidue */ secp256k1_scalar_mul(&sqr, &sqr, &five); secp256k1_scalar_get_num(&n, &sqr); CHECK(secp256k1_num_jacobi(&n, &order) == -1); /* test multiple of the order*/ CHECK(secp256k1_num_jacobi(&order, &order) == 0); /* check one less than the order */ secp256k1_scalar_set_int(&small, 1); secp256k1_scalar_get_num(&n, &small); secp256k1_num_sub(&n, &order, &n); CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* sage confirms this is 1 */ } void run_num_smalltests(void) { int i; for (i = 0; i < 100*count; i++) { test_num_negate(); test_num_add_sub(); test_num_mod(); test_num_jacobi(); } } #endif /***** SCALAR TESTS *****/ void scalar_test(void) { secp256k1_scalar s; secp256k1_scalar s1; secp256k1_scalar s2; #ifndef USE_NUM_NONE secp256k1_num snum, s1num, s2num; secp256k1_num order, half_order; #endif unsigned char c[32]; /* Set 's' to a random scalar, with value 'snum'. */ random_scalar_order_test(&s); /* Set 's1' to a random scalar, with value 's1num'. */ random_scalar_order_test(&s1); /* Set 's2' to a random scalar, with value 'snum2', and byte array representation 'c'. */ random_scalar_order_test(&s2); secp256k1_scalar_get_b32(c, &s2); #ifndef USE_NUM_NONE secp256k1_scalar_get_num(&snum, &s); secp256k1_scalar_get_num(&s1num, &s1); secp256k1_scalar_get_num(&s2num, &s2); secp256k1_scalar_order_get_num(&order); half_order = order; secp256k1_num_shift(&half_order, 1); #endif { int i; /* Test that fetching groups of 4 bits from a scalar and recursing n(i)=16*n(i-1)+p(i) reconstructs it. */ secp256k1_scalar n; secp256k1_scalar_set_int(&n, 0); for (i = 0; i < 256; i += 4) { secp256k1_scalar t; int j; secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits(&s, 256 - 4 - i, 4)); for (j = 0; j < 4; j++) { secp256k1_scalar_add(&n, &n, &n); } secp256k1_scalar_add(&n, &n, &t); } CHECK(secp256k1_scalar_eq(&n, &s)); } { /* Test that fetching groups of randomly-sized bits from a scalar and recursing n(i)=b*n(i-1)+p(i) reconstructs it. */ secp256k1_scalar n; int i = 0; secp256k1_scalar_set_int(&n, 0); while (i < 256) { secp256k1_scalar t; int j; int now = secp256k1_rand_int(15) + 1; if (now + i > 256) { now = 256 - i; } secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits_var(&s, 256 - now - i, now)); for (j = 0; j < now; j++) { secp256k1_scalar_add(&n, &n, &n); } secp256k1_scalar_add(&n, &n, &t); i += now; } CHECK(secp256k1_scalar_eq(&n, &s)); } #ifndef USE_NUM_NONE { /* Test that adding the scalars together is equal to adding their numbers together modulo the order. */ secp256k1_num rnum; secp256k1_num r2num; secp256k1_scalar r; secp256k1_num_add(&rnum, &snum, &s2num); secp256k1_num_mod(&rnum, &order); secp256k1_scalar_add(&r, &s, &s2); secp256k1_scalar_get_num(&r2num, &r); CHECK(secp256k1_num_eq(&rnum, &r2num)); } { /* Test that multiplying the scalars is equal to multiplying their numbers modulo the order. */ secp256k1_scalar r; secp256k1_num r2num; secp256k1_num rnum; secp256k1_num_mul(&rnum, &snum, &s2num); secp256k1_num_mod(&rnum, &order); secp256k1_scalar_mul(&r, &s, &s2); secp256k1_scalar_get_num(&r2num, &r); CHECK(secp256k1_num_eq(&rnum, &r2num)); /* The result can only be zero if at least one of the factors was zero. */ CHECK(secp256k1_scalar_is_zero(&r) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_zero(&s2))); /* The results can only be equal to one of the factors if that factor was zero, or the other factor was one. */ CHECK(secp256k1_num_eq(&rnum, &snum) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_one(&s2))); CHECK(secp256k1_num_eq(&rnum, &s2num) == (secp256k1_scalar_is_zero(&s2) || secp256k1_scalar_is_one(&s))); } { secp256k1_scalar neg; secp256k1_num negnum; secp256k1_num negnum2; /* Check that comparison with zero matches comparison with zero on the number. */ CHECK(secp256k1_num_is_zero(&snum) == secp256k1_scalar_is_zero(&s)); /* Check that comparison with the half order is equal to testing for high scalar. */ CHECK(secp256k1_scalar_is_high(&s) == (secp256k1_num_cmp(&snum, &half_order) > 0)); secp256k1_scalar_negate(&neg, &s); secp256k1_num_sub(&negnum, &order, &snum); secp256k1_num_mod(&negnum, &order); /* Check that comparison with the half order is equal to testing for high scalar after negation. */ CHECK(secp256k1_scalar_is_high(&neg) == (secp256k1_num_cmp(&negnum, &half_order) > 0)); /* Negating should change the high property, unless the value was already zero. */ CHECK((secp256k1_scalar_is_high(&s) == secp256k1_scalar_is_high(&neg)) == secp256k1_scalar_is_zero(&s)); secp256k1_scalar_get_num(&negnum2, &neg); /* Negating a scalar should be equal to (order - n) mod order on the number. */ CHECK(secp256k1_num_eq(&negnum, &negnum2)); secp256k1_scalar_add(&neg, &neg, &s); /* Adding a number to its negation should result in zero. */ CHECK(secp256k1_scalar_is_zero(&neg)); secp256k1_scalar_negate(&neg, &neg); /* Negating zero should still result in zero. */ CHECK(secp256k1_scalar_is_zero(&neg)); } { /* Test secp256k1_scalar_mul_shift_var. */ secp256k1_scalar r; secp256k1_num one; secp256k1_num rnum; secp256k1_num rnum2; unsigned char cone[1] = {0x01}; unsigned int shift = 256 + secp256k1_rand_int(257); secp256k1_scalar_mul_shift_var(&r, &s1, &s2, shift); secp256k1_num_mul(&rnum, &s1num, &s2num); secp256k1_num_shift(&rnum, shift - 1); secp256k1_num_set_bin(&one, cone, 1); secp256k1_num_add(&rnum, &rnum, &one); secp256k1_num_shift(&rnum, 1); secp256k1_scalar_get_num(&rnum2, &r); CHECK(secp256k1_num_eq(&rnum, &rnum2)); } { /* test secp256k1_scalar_shr_int */ secp256k1_scalar r; int i; random_scalar_order_test(&r); for (i = 0; i < 100; ++i) { int low; int shift = 1 + secp256k1_rand_int(15); int expected = r.d[0] % (1 << shift); low = secp256k1_scalar_shr_int(&r, shift); CHECK(expected == low); } } #endif { /* Test that scalar inverses are equal to the inverse of their number modulo the order. */ if (!secp256k1_scalar_is_zero(&s)) { secp256k1_scalar inv; #ifndef USE_NUM_NONE secp256k1_num invnum; secp256k1_num invnum2; #endif secp256k1_scalar_inverse(&inv, &s); #ifndef USE_NUM_NONE secp256k1_num_mod_inverse(&invnum, &snum, &order); secp256k1_scalar_get_num(&invnum2, &inv); CHECK(secp256k1_num_eq(&invnum, &invnum2)); #endif secp256k1_scalar_mul(&inv, &inv, &s); /* Multiplying a scalar with its inverse must result in one. */ CHECK(secp256k1_scalar_is_one(&inv)); secp256k1_scalar_inverse(&inv, &inv); /* Inverting one must result in one. */ CHECK(secp256k1_scalar_is_one(&inv)); #ifndef USE_NUM_NONE secp256k1_scalar_get_num(&invnum, &inv); CHECK(secp256k1_num_is_one(&invnum)); #endif } } { /* Test commutativity of add. */ secp256k1_scalar r1, r2; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_add(&r2, &s2, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { secp256k1_scalar r1, r2; secp256k1_scalar b; int i; /* Test add_bit. */ int bit = secp256k1_rand_bits(8); secp256k1_scalar_set_int(&b, 1); CHECK(secp256k1_scalar_is_one(&b)); for (i = 0; i < bit; i++) { secp256k1_scalar_add(&b, &b, &b); } r1 = s1; r2 = s1; if (!secp256k1_scalar_add(&r1, &r1, &b)) { /* No overflow happened. */ secp256k1_scalar_cadd_bit(&r2, bit, 1); CHECK(secp256k1_scalar_eq(&r1, &r2)); /* cadd is a noop when flag is zero */ secp256k1_scalar_cadd_bit(&r2, bit, 0); CHECK(secp256k1_scalar_eq(&r1, &r2)); } } { /* Test commutativity of mul. */ secp256k1_scalar r1, r2; secp256k1_scalar_mul(&r1, &s1, &s2); secp256k1_scalar_mul(&r2, &s2, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test associativity of add. */ secp256k1_scalar r1, r2; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_add(&r1, &r1, &s); secp256k1_scalar_add(&r2, &s2, &s); secp256k1_scalar_add(&r2, &s1, &r2); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test associativity of mul. */ secp256k1_scalar r1, r2; secp256k1_scalar_mul(&r1, &s1, &s2); secp256k1_scalar_mul(&r1, &r1, &s); secp256k1_scalar_mul(&r2, &s2, &s); secp256k1_scalar_mul(&r2, &s1, &r2); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test distributitivity of mul over add. */ secp256k1_scalar r1, r2, t; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_mul(&r1, &r1, &s); secp256k1_scalar_mul(&r2, &s1, &s); secp256k1_scalar_mul(&t, &s2, &s); secp256k1_scalar_add(&r2, &r2, &t); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test square. */ secp256k1_scalar r1, r2; secp256k1_scalar_sqr(&r1, &s1); secp256k1_scalar_mul(&r2, &s1, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test multiplicative identity. */ secp256k1_scalar r1, v1; secp256k1_scalar_set_int(&v1,1); secp256k1_scalar_mul(&r1, &s1, &v1); CHECK(secp256k1_scalar_eq(&r1, &s1)); } { /* Test additive identity. */ secp256k1_scalar r1, v0; secp256k1_scalar_set_int(&v0,0); secp256k1_scalar_add(&r1, &s1, &v0); CHECK(secp256k1_scalar_eq(&r1, &s1)); } { /* Test zero product property. */ secp256k1_scalar r1, v0; secp256k1_scalar_set_int(&v0,0); secp256k1_scalar_mul(&r1, &s1, &v0); CHECK(secp256k1_scalar_eq(&r1, &v0)); } } void run_scalar_tests(void) { int i; for (i = 0; i < 128 * count; i++) { scalar_test(); } { /* (-1)+1 should be zero. */ secp256k1_scalar s, o; secp256k1_scalar_set_int(&s, 1); CHECK(secp256k1_scalar_is_one(&s)); secp256k1_scalar_negate(&o, &s); secp256k1_scalar_add(&o, &o, &s); CHECK(secp256k1_scalar_is_zero(&o)); secp256k1_scalar_negate(&o, &o); CHECK(secp256k1_scalar_is_zero(&o)); } #ifndef USE_NUM_NONE { /* A scalar with value of the curve order should be 0. */ secp256k1_num order; secp256k1_scalar zero; unsigned char bin[32]; int overflow = 0; secp256k1_scalar_order_get_num(&order); secp256k1_num_get_bin(bin, 32, &order); secp256k1_scalar_set_b32(&zero, bin, &overflow); CHECK(overflow == 1); CHECK(secp256k1_scalar_is_zero(&zero)); } #endif { /* Does check_overflow check catch all ones? */ static const secp256k1_scalar overflowed = SECP256K1_SCALAR_CONST( 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL ); CHECK(secp256k1_scalar_check_overflow(&overflowed)); } { /* Static test vectors. * These were reduced from ~10^12 random vectors based on comparison-decision * and edge-case coverage on 32-bit and 64-bit implementations. * The responses were generated with Sage 5.9. */ secp256k1_scalar x; secp256k1_scalar y; secp256k1_scalar z; secp256k1_scalar zz; secp256k1_scalar one; secp256k1_scalar r1; secp256k1_scalar r2; #if defined(USE_SCALAR_INV_NUM) secp256k1_scalar zzv; #endif int overflow; unsigned char chal[33][2][32] = { {{0xff, 0xff, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0xc0, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff}}, {{0xef, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x80, 0xff}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0x00}, {0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1e, 0xf8, 0xff, 0xff, 0xff, 0xfd, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x03, 0x00, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xf3, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x80, 0xff, 0xff, 0x3f, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xfc, 0x9f, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x0f, 0xfc, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0xf8, 0xff, 0x0f, 0xc0, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xf0}, {0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0x00, 0xf8, 0xff, 0x03, 0xff, 0xff, 0xff, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xc0, 0xff, 0x0f, 0xfc, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x3f, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0x8f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00, 0x00, 0x80, 0xff, 0x7f}, {0xff, 0xcf, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xbf, 0xff, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x01, 0xfc, 0xff, 0x01, 0x00, 0xfe, 0xff}, {0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x01, 0x00, 0xf0, 0xff, 0xff, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3f, 0xf0, 0xff, 0xff, 0x3f, 0x00, 0x00, 0xf8, 0x07, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x7e, 0x00, 0x00}}, {{0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xfe, 0x07, 0x00}, {0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60}}, {{0xff, 0x01, 0x00, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x80, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0x1f, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00}}, {{0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xcf, 0xff, 0x1f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00}, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0x7f, 0x00, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x80, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x7f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0xfe}}, {{0xff, 0xff, 0xff, 0x3f, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x03, 0xfe, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xc0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff}}, {{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7e, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x07, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0x01, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0xc0, 0xf1, 0x7f, 0x00}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00}, {0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x80, 0x1f, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x01, 0xff, 0xff}}, {{0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x03, 0xe0, 0x01, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xf0, 0x07, 0x00, 0x3c, 0x80, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xe0, 0xff, 0x00, 0x00, 0x00}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x80, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x7f, 0xfe, 0xff, 0x1f, 0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0xfe, 0xff}}, {{0xff, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x83, 0xff, 0xff, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xf0}, {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xf8, 0x07, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff}}, {{0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb, 0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03}, {0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb, 0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03}} }; unsigned char res[33][2][32] = { {{0x0c, 0x3b, 0x0a, 0xca, 0x8d, 0x1a, 0x2f, 0xb9, 0x8a, 0x7b, 0x53, 0x5a, 0x1f, 0xc5, 0x22, 0xa1, 0x07, 0x2a, 0x48, 0xea, 0x02, 0xeb, 0xb3, 0xd6, 0x20, 0x1e, 0x86, 0xd0, 0x95, 0xf6, 0x92, 0x35}, {0xdc, 0x90, 0x7a, 0x07, 0x2e, 0x1e, 0x44, 0x6d, 0xf8, 0x15, 0x24, 0x5b, 0x5a, 0x96, 0x37, 0x9c, 0x37, 0x7b, 0x0d, 0xac, 0x1b, 0x65, 0x58, 0x49, 0x43, 0xb7, 0x31, 0xbb, 0xa7, 0xf4, 0x97, 0x15}}, {{0xf1, 0xf7, 0x3a, 0x50, 0xe6, 0x10, 0xba, 0x22, 0x43, 0x4d, 0x1f, 0x1f, 0x7c, 0x27, 0xca, 0x9c, 0xb8, 0xb6, 0xa0, 0xfc, 0xd8, 0xc0, 0x05, 0x2f, 0xf7, 0x08, 0xe1, 0x76, 0xdd, 0xd0, 0x80, 0xc8}, {0xe3, 0x80, 0x80, 0xb8, 0xdb, 0xe3, 0xa9, 0x77, 0x00, 0xb0, 0xf5, 0x2e, 0x27, 0xe2, 0x68, 0xc4, 0x88, 0xe8, 0x04, 0xc1, 0x12, 0xbf, 0x78, 0x59, 0xe6, 0xa9, 0x7c, 0xe1, 0x81, 0xdd, 0xb9, 0xd5}}, {{0x96, 0xe2, 0xee, 0x01, 0xa6, 0x80, 0x31, 0xef, 0x5c, 0xd0, 0x19, 0xb4, 0x7d, 0x5f, 0x79, 0xab, 0xa1, 0x97, 0xd3, 0x7e, 0x33, 0xbb, 0x86, 0x55, 0x60, 0x20, 0x10, 0x0d, 0x94, 0x2d, 0x11, 0x7c}, {0xcc, 0xab, 0xe0, 0xe8, 0x98, 0x65, 0x12, 0x96, 0x38, 0x5a, 0x1a, 0xf2, 0x85, 0x23, 0x59, 0x5f, 0xf9, 0xf3, 0xc2, 0x81, 0x70, 0x92, 0x65, 0x12, 0x9c, 0x65, 0x1e, 0x96, 0x00, 0xef, 0xe7, 0x63}}, {{0xac, 0x1e, 0x62, 0xc2, 0x59, 0xfc, 0x4e, 0x5c, 0x83, 0xb0, 0xd0, 0x6f, 0xce, 0x19, 0xf6, 0xbf, 0xa4, 0xb0, 0xe0, 0x53, 0x66, 0x1f, 0xbf, 0xc9, 0x33, 0x47, 0x37, 0xa9, 0x3d, 0x5d, 0xb0, 0x48}, {0x86, 0xb9, 0x2a, 0x7f, 0x8e, 0xa8, 0x60, 0x42, 0x26, 0x6d, 0x6e, 0x1c, 0xa2, 0xec, 0xe0, 0xe5, 0x3e, 0x0a, 0x33, 0xbb, 0x61, 0x4c, 0x9f, 0x3c, 0xd1, 0xdf, 0x49, 0x33, 0xcd, 0x72, 0x78, 0x18}}, {{0xf7, 0xd3, 0xcd, 0x49, 0x5c, 0x13, 0x22, 0xfb, 0x2e, 0xb2, 0x2f, 0x27, 0xf5, 0x8a, 0x5d, 0x74, 0xc1, 0x58, 0xc5, 0xc2, 0x2d, 0x9f, 0x52, 0xc6, 0x63, 0x9f, 0xba, 0x05, 0x76, 0x45, 0x7a, 0x63}, {0x8a, 0xfa, 0x55, 0x4d, 0xdd, 0xa3, 0xb2, 0xc3, 0x44, 0xfd, 0xec, 0x72, 0xde, 0xef, 0xc0, 0x99, 0xf5, 0x9f, 0xe2, 0x52, 0xb4, 0x05, 0x32, 0x58, 0x57, 0xc1, 0x8f, 0xea, 0xc3, 0x24, 0x5b, 0x94}}, {{0x05, 0x83, 0xee, 0xdd, 0x64, 0xf0, 0x14, 0x3b, 0xa0, 0x14, 0x4a, 0x3a, 0x41, 0x82, 0x7c, 0xa7, 0x2c, 0xaa, 0xb1, 0x76, 0xbb, 0x59, 0x64, 0x5f, 0x52, 0xad, 0x25, 0x29, 0x9d, 0x8f, 0x0b, 0xb0}, {0x7e, 0xe3, 0x7c, 0xca, 0xcd, 0x4f, 0xb0, 0x6d, 0x7a, 0xb2, 0x3e, 0xa0, 0x08, 0xb9, 0xa8, 0x2d, 0xc2, 0xf4, 0x99, 0x66, 0xcc, 0xac, 0xd8, 0xb9, 0x72, 0x2a, 0x4a, 0x3e, 0x0f, 0x7b, 0xbf, 0xf4}}, {{0x8c, 0x9c, 0x78, 0x2b, 0x39, 0x61, 0x7e, 0xf7, 0x65, 0x37, 0x66, 0x09, 0x38, 0xb9, 0x6f, 0x70, 0x78, 0x87, 0xff, 0xcf, 0x93, 0xca, 0x85, 0x06, 0x44, 0x84, 0xa7, 0xfe, 0xd3, 0xa4, 0xe3, 0x7e}, {0xa2, 0x56, 0x49, 0x23, 0x54, 0xa5, 0x50, 0xe9, 0x5f, 0xf0, 0x4d, 0xe7, 0xdc, 0x38, 0x32, 0x79, 0x4f, 0x1c, 0xb7, 0xe4, 0xbb, 0xf8, 0xbb, 0x2e, 0x40, 0x41, 0x4b, 0xcc, 0xe3, 0x1e, 0x16, 0x36}}, {{0x0c, 0x1e, 0xd7, 0x09, 0x25, 0x40, 0x97, 0xcb, 0x5c, 0x46, 0xa8, 0xda, 0xef, 0x25, 0xd5, 0xe5, 0x92, 0x4d, 0xcf, 0xa3, 0xc4, 0x5d, 0x35, 0x4a, 0xe4, 0x61, 0x92, 0xf3, 0xbf, 0x0e, 0xcd, 0xbe}, {0xe4, 0xaf, 0x0a, 0xb3, 0x30, 0x8b, 0x9b, 0x48, 0x49, 0x43, 0xc7, 0x64, 0x60, 0x4a, 0x2b, 0x9e, 0x95, 0x5f, 0x56, 0xe8, 0x35, 0xdc, 0xeb, 0xdc, 0xc7, 0xc4, 0xfe, 0x30, 0x40, 0xc7, 0xbf, 0xa4}}, {{0xd4, 0xa0, 0xf5, 0x81, 0x49, 0x6b, 0xb6, 0x8b, 0x0a, 0x69, 0xf9, 0xfe, 0xa8, 0x32, 0xe5, 0xe0, 0xa5, 0xcd, 0x02, 0x53, 0xf9, 0x2c, 0xe3, 0x53, 0x83, 0x36, 0xc6, 0x02, 0xb5, 0xeb, 0x64, 0xb8}, {0x1d, 0x42, 0xb9, 0xf9, 0xe9, 0xe3, 0x93, 0x2c, 0x4c, 0xee, 0x6c, 0x5a, 0x47, 0x9e, 0x62, 0x01, 0x6b, 0x04, 0xfe, 0xa4, 0x30, 0x2b, 0x0d, 0x4f, 0x71, 0x10, 0xd3, 0x55, 0xca, 0xf3, 0x5e, 0x80}}, {{0x77, 0x05, 0xf6, 0x0c, 0x15, 0x9b, 0x45, 0xe7, 0xb9, 0x11, 0xb8, 0xf5, 0xd6, 0xda, 0x73, 0x0c, 0xda, 0x92, 0xea, 0xd0, 0x9d, 0xd0, 0x18, 0x92, 0xce, 0x9a, 0xaa, 0xee, 0x0f, 0xef, 0xde, 0x30}, {0xf1, 0xf1, 0xd6, 0x9b, 0x51, 0xd7, 0x77, 0x62, 0x52, 0x10, 0xb8, 0x7a, 0x84, 0x9d, 0x15, 0x4e, 0x07, 0xdc, 0x1e, 0x75, 0x0d, 0x0c, 0x3b, 0xdb, 0x74, 0x58, 0x62, 0x02, 0x90, 0x54, 0x8b, 0x43}}, {{0xa6, 0xfe, 0x0b, 0x87, 0x80, 0x43, 0x67, 0x25, 0x57, 0x5d, 0xec, 0x40, 0x50, 0x08, 0xd5, 0x5d, 0x43, 0xd7, 0xe0, 0xaa, 0xe0, 0x13, 0xb6, 0xb0, 0xc0, 0xd4, 0xe5, 0x0d, 0x45, 0x83, 0xd6, 0x13}, {0x40, 0x45, 0x0a, 0x92, 0x31, 0xea, 0x8c, 0x60, 0x8c, 0x1f, 0xd8, 0x76, 0x45, 0xb9, 0x29, 0x00, 0x26, 0x32, 0xd8, 0xa6, 0x96, 0x88, 0xe2, 0xc4, 0x8b, 0xdb, 0x7f, 0x17, 0x87, 0xcc, 0xc8, 0xf2}}, {{0xc2, 0x56, 0xe2, 0xb6, 0x1a, 0x81, 0xe7, 0x31, 0x63, 0x2e, 0xbb, 0x0d, 0x2f, 0x81, 0x67, 0xd4, 0x22, 0xe2, 0x38, 0x02, 0x25, 0x97, 0xc7, 0x88, 0x6e, 0xdf, 0xbe, 0x2a, 0xa5, 0x73, 0x63, 0xaa}, {0x50, 0x45, 0xe2, 0xc3, 0xbd, 0x89, 0xfc, 0x57, 0xbd, 0x3c, 0xa3, 0x98, 0x7e, 0x7f, 0x36, 0x38, 0x92, 0x39, 0x1f, 0x0f, 0x81, 0x1a, 0x06, 0x51, 0x1f, 0x8d, 0x6a, 0xff, 0x47, 0x16, 0x06, 0x9c}}, {{0x33, 0x95, 0xa2, 0x6f, 0x27, 0x5f, 0x9c, 0x9c, 0x64, 0x45, 0xcb, 0xd1, 0x3c, 0xee, 0x5e, 0x5f, 0x48, 0xa6, 0xaf, 0xe3, 0x79, 0xcf, 0xb1, 0xe2, 0xbf, 0x55, 0x0e, 0xa2, 0x3b, 0x62, 0xf0, 0xe4}, {0x14, 0xe8, 0x06, 0xe3, 0xbe, 0x7e, 0x67, 0x01, 0xc5, 0x21, 0x67, 0xd8, 0x54, 0xb5, 0x7f, 0xa4, 0xf9, 0x75, 0x70, 0x1c, 0xfd, 0x79, 0xdb, 0x86, 0xad, 0x37, 0x85, 0x83, 0x56, 0x4e, 0xf0, 0xbf}}, {{0xbc, 0xa6, 0xe0, 0x56, 0x4e, 0xef, 0xfa, 0xf5, 0x1d, 0x5d, 0x3f, 0x2a, 0x5b, 0x19, 0xab, 0x51, 0xc5, 0x8b, 0xdd, 0x98, 0x28, 0x35, 0x2f, 0xc3, 0x81, 0x4f, 0x5c, 0xe5, 0x70, 0xb9, 0xeb, 0x62}, {0xc4, 0x6d, 0x26, 0xb0, 0x17, 0x6b, 0xfe, 0x6c, 0x12, 0xf8, 0xe7, 0xc1, 0xf5, 0x2f, 0xfa, 0x91, 0x13, 0x27, 0xbd, 0x73, 0xcc, 0x33, 0x31, 0x1c, 0x39, 0xe3, 0x27, 0x6a, 0x95, 0xcf, 0xc5, 0xfb}}, {{0x30, 0xb2, 0x99, 0x84, 0xf0, 0x18, 0x2a, 0x6e, 0x1e, 0x27, 0xed, 0xa2, 0x29, 0x99, 0x41, 0x56, 0xe8, 0xd4, 0x0d, 0xef, 0x99, 0x9c, 0xf3, 0x58, 0x29, 0x55, 0x1a, 0xc0, 0x68, 0xd6, 0x74, 0xa4}, {0x07, 0x9c, 0xe7, 0xec, 0xf5, 0x36, 0x73, 0x41, 0xa3, 0x1c, 0xe5, 0x93, 0x97, 0x6a, 0xfd, 0xf7, 0x53, 0x18, 0xab, 0xaf, 0xeb, 0x85, 0xbd, 0x92, 0x90, 0xab, 0x3c, 0xbf, 0x30, 0x82, 0xad, 0xf6}}, {{0xc6, 0x87, 0x8a, 0x2a, 0xea, 0xc0, 0xa9, 0xec, 0x6d, 0xd3, 0xdc, 0x32, 0x23, 0xce, 0x62, 0x19, 0xa4, 0x7e, 0xa8, 0xdd, 0x1c, 0x33, 0xae, 0xd3, 0x4f, 0x62, 0x9f, 0x52, 0xe7, 0x65, 0x46, 0xf4}, {0x97, 0x51, 0x27, 0x67, 0x2d, 0xa2, 0x82, 0x87, 0x98, 0xd3, 0xb6, 0x14, 0x7f, 0x51, 0xd3, 0x9a, 0x0b, 0xd0, 0x76, 0x81, 0xb2, 0x4f, 0x58, 0x92, 0xa4, 0x86, 0xa1, 0xa7, 0x09, 0x1d, 0xef, 0x9b}}, {{0xb3, 0x0f, 0x2b, 0x69, 0x0d, 0x06, 0x90, 0x64, 0xbd, 0x43, 0x4c, 0x10, 0xe8, 0x98, 0x1c, 0xa3, 0xe1, 0x68, 0xe9, 0x79, 0x6c, 0x29, 0x51, 0x3f, 0x41, 0xdc, 0xdf, 0x1f, 0xf3, 0x60, 0xbe, 0x33}, {0xa1, 0x5f, 0xf7, 0x1d, 0xb4, 0x3e, 0x9b, 0x3c, 0xe7, 0xbd, 0xb6, 0x06, 0xd5, 0x60, 0x06, 0x6d, 0x50, 0xd2, 0xf4, 0x1a, 0x31, 0x08, 0xf2, 0xea, 0x8e, 0xef, 0x5f, 0x7d, 0xb6, 0xd0, 0xc0, 0x27}}, {{0x62, 0x9a, 0xd9, 0xbb, 0x38, 0x36, 0xce, 0xf7, 0x5d, 0x2f, 0x13, 0xec, 0xc8, 0x2d, 0x02, 0x8a, 0x2e, 0x72, 0xf0, 0xe5, 0x15, 0x9d, 0x72, 0xae, 0xfc, 0xb3, 0x4f, 0x02, 0xea, 0xe1, 0x09, 0xfe}, {0x00, 0x00, 0x00, 0x00, 0xfa, 0x0a, 0x3d, 0xbc, 0xad, 0x16, 0x0c, 0xb6, 0xe7, 0x7c, 0x8b, 0x39, 0x9a, 0x43, 0xbb, 0xe3, 0xc2, 0x55, 0x15, 0x14, 0x75, 0xac, 0x90, 0x9b, 0x7f, 0x9a, 0x92, 0x00}}, {{0x8b, 0xac, 0x70, 0x86, 0x29, 0x8f, 0x00, 0x23, 0x7b, 0x45, 0x30, 0xaa, 0xb8, 0x4c, 0xc7, 0x8d, 0x4e, 0x47, 0x85, 0xc6, 0x19, 0xe3, 0x96, 0xc2, 0x9a, 0xa0, 0x12, 0xed, 0x6f, 0xd7, 0x76, 0x16}, {0x45, 0xaf, 0x7e, 0x33, 0xc7, 0x7f, 0x10, 0x6c, 0x7c, 0x9f, 0x29, 0xc1, 0xa8, 0x7e, 0x15, 0x84, 0xe7, 0x7d, 0xc0, 0x6d, 0xab, 0x71, 0x5d, 0xd0, 0x6b, 0x9f, 0x97, 0xab, 0xcb, 0x51, 0x0c, 0x9f}}, {{0x9e, 0xc3, 0x92, 0xb4, 0x04, 0x9f, 0xc8, 0xbb, 0xdd, 0x9e, 0xc6, 0x05, 0xfd, 0x65, 0xec, 0x94, 0x7f, 0x2c, 0x16, 0xc4, 0x40, 0xac, 0x63, 0x7b, 0x7d, 0xb8, 0x0c, 0xe4, 0x5b, 0xe3, 0xa7, 0x0e}, {0x43, 0xf4, 0x44, 0xe8, 0xcc, 0xc8, 0xd4, 0x54, 0x33, 0x37, 0x50, 0xf2, 0x87, 0x42, 0x2e, 0x00, 0x49, 0x60, 0x62, 0x02, 0xfd, 0x1a, 0x7c, 0xdb, 0x29, 0x6c, 0x6d, 0x54, 0x53, 0x08, 0xd1, 0xc8}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}, {0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}}, {{0x28, 0x56, 0xac, 0x0e, 0x4f, 0x98, 0x09, 0xf0, 0x49, 0xfa, 0x7f, 0x84, 0xac, 0x7e, 0x50, 0x5b, 0x17, 0x43, 0x14, 0x89, 0x9c, 0x53, 0xa8, 0x94, 0x30, 0xf2, 0x11, 0x4d, 0x92, 0x14, 0x27, 0xe8}, {0x39, 0x7a, 0x84, 0x56, 0x79, 0x9d, 0xec, 0x26, 0x2c, 0x53, 0xc1, 0x94, 0xc9, 0x8d, 0x9e, 0x9d, 0x32, 0x1f, 0xdd, 0x84, 0x04, 0xe8, 0xe2, 0x0a, 0x6b, 0xbe, 0xbb, 0x42, 0x40, 0x67, 0x30, 0x6c}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x73, 0x2f, 0xc9, 0xbe, 0xbd}, {0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0x1c, 0xc4, 0xf7, 0xda, 0x0f, 0x65, 0xca, 0x39, 0x70, 0x52, 0x92, 0x8e, 0xc3, 0xc8, 0x15, 0xea, 0x7f, 0x10, 0x9e, 0x77, 0x4b, 0x6e, 0x2d, 0xdf, 0xe8, 0x30, 0x9d, 0xda, 0xe8, 0x9a, 0x65, 0xae}, {0x02, 0xb0, 0x16, 0xb1, 0x1d, 0xc8, 0x57, 0x7b, 0xa2, 0x3a, 0xa2, 0xa3, 0x38, 0x5c, 0x8f, 0xeb, 0x66, 0x37, 0x91, 0xa8, 0x5f, 0xef, 0x04, 0xf6, 0x59, 0x75, 0xe1, 0xee, 0x92, 0xf6, 0x0e, 0x30}}, {{0x8d, 0x76, 0x14, 0xa4, 0x14, 0x06, 0x9f, 0x9a, 0xdf, 0x4a, 0x85, 0xa7, 0x6b, 0xbf, 0x29, 0x6f, 0xbc, 0x34, 0x87, 0x5d, 0xeb, 0xbb, 0x2e, 0xa9, 0xc9, 0x1f, 0x58, 0xd6, 0x9a, 0x82, 0xa0, 0x56}, {0xd4, 0xb9, 0xdb, 0x88, 0x1d, 0x04, 0xe9, 0x93, 0x8d, 0x3f, 0x20, 0xd5, 0x86, 0xa8, 0x83, 0x07, 0xdb, 0x09, 0xd8, 0x22, 0x1f, 0x7f, 0xf1, 0x71, 0xc8, 0xe7, 0x5d, 0x47, 0xaf, 0x8b, 0x72, 0xe9}}, {{0x83, 0xb9, 0x39, 0xb2, 0xa4, 0xdf, 0x46, 0x87, 0xc2, 0xb8, 0xf1, 0xe6, 0x4c, 0xd1, 0xe2, 0xa9, 0xe4, 0x70, 0x30, 0x34, 0xbc, 0x52, 0x7c, 0x55, 0xa6, 0xec, 0x80, 0xa4, 0xe5, 0xd2, 0xdc, 0x73}, {0x08, 0xf1, 0x03, 0xcf, 0x16, 0x73, 0xe8, 0x7d, 0xb6, 0x7e, 0x9b, 0xc0, 0xb4, 0xc2, 0xa5, 0x86, 0x02, 0x77, 0xd5, 0x27, 0x86, 0xa5, 0x15, 0xfb, 0xae, 0x9b, 0x8c, 0xa9, 0xf9, 0xf8, 0xa8, 0x4a}}, {{0x8b, 0x00, 0x49, 0xdb, 0xfa, 0xf0, 0x1b, 0xa2, 0xed, 0x8a, 0x9a, 0x7a, 0x36, 0x78, 0x4a, 0xc7, 0xf7, 0xad, 0x39, 0xd0, 0x6c, 0x65, 0x7a, 0x41, 0xce, 0xd6, 0xd6, 0x4c, 0x20, 0x21, 0x6b, 0xc7}, {0xc6, 0xca, 0x78, 0x1d, 0x32, 0x6c, 0x6c, 0x06, 0x91, 0xf2, 0x1a, 0xe8, 0x43, 0x16, 0xea, 0x04, 0x3c, 0x1f, 0x07, 0x85, 0xf7, 0x09, 0x22, 0x08, 0xba, 0x13, 0xfd, 0x78, 0x1e, 0x3f, 0x6f, 0x62}}, {{0x25, 0x9b, 0x7c, 0xb0, 0xac, 0x72, 0x6f, 0xb2, 0xe3, 0x53, 0x84, 0x7a, 0x1a, 0x9a, 0x98, 0x9b, 0x44, 0xd3, 0x59, 0xd0, 0x8e, 0x57, 0x41, 0x40, 0x78, 0xa7, 0x30, 0x2f, 0x4c, 0x9c, 0xb9, 0x68}, {0xb7, 0x75, 0x03, 0x63, 0x61, 0xc2, 0x48, 0x6e, 0x12, 0x3d, 0xbf, 0x4b, 0x27, 0xdf, 0xb1, 0x7a, 0xff, 0x4e, 0x31, 0x07, 0x83, 0xf4, 0x62, 0x5b, 0x19, 0xa5, 0xac, 0xa0, 0x32, 0x58, 0x0d, 0xa7}}, {{0x43, 0x4f, 0x10, 0xa4, 0xca, 0xdb, 0x38, 0x67, 0xfa, 0xae, 0x96, 0xb5, 0x6d, 0x97, 0xff, 0x1f, 0xb6, 0x83, 0x43, 0xd3, 0xa0, 0x2d, 0x70, 0x7a, 0x64, 0x05, 0x4c, 0xa7, 0xc1, 0xa5, 0x21, 0x51}, {0xe4, 0xf1, 0x23, 0x84, 0xe1, 0xb5, 0x9d, 0xf2, 0xb8, 0x73, 0x8b, 0x45, 0x2b, 0x35, 0x46, 0x38, 0x10, 0x2b, 0x50, 0xf8, 0x8b, 0x35, 0xcd, 0x34, 0xc8, 0x0e, 0xf6, 0xdb, 0x09, 0x35, 0xf0, 0xda}}, {{0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34, 0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13, 0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46, 0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5}, {0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34, 0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13, 0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46, 0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5}} }; secp256k1_scalar_set_int(&one, 1); for (i = 0; i < 33; i++) { secp256k1_scalar_set_b32(&x, chal[i][0], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&y, chal[i][1], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&r1, res[i][0], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&r2, res[i][1], &overflow); CHECK(!overflow); secp256k1_scalar_mul(&z, &x, &y); CHECK(!secp256k1_scalar_check_overflow(&z)); CHECK(secp256k1_scalar_eq(&r1, &z)); if (!secp256k1_scalar_is_zero(&y)) { secp256k1_scalar_inverse(&zz, &y); CHECK(!secp256k1_scalar_check_overflow(&zz)); #if defined(USE_SCALAR_INV_NUM) secp256k1_scalar_inverse_var(&zzv, &y); CHECK(secp256k1_scalar_eq(&zzv, &zz)); #endif secp256k1_scalar_mul(&z, &z, &zz); CHECK(!secp256k1_scalar_check_overflow(&z)); CHECK(secp256k1_scalar_eq(&x, &z)); secp256k1_scalar_mul(&zz, &zz, &y); CHECK(!secp256k1_scalar_check_overflow(&zz)); CHECK(secp256k1_scalar_eq(&one, &zz)); } secp256k1_scalar_mul(&z, &x, &x); CHECK(!secp256k1_scalar_check_overflow(&z)); secp256k1_scalar_sqr(&zz, &x); CHECK(!secp256k1_scalar_check_overflow(&zz)); CHECK(secp256k1_scalar_eq(&zz, &z)); CHECK(secp256k1_scalar_eq(&r2, &zz)); } } } /***** FIELD TESTS *****/ void random_fe(secp256k1_fe *x) { unsigned char bin[32]; do { secp256k1_rand256(bin); if (secp256k1_fe_set_b32(x, bin)) { return; } } while(1); } void random_fe_test(secp256k1_fe *x) { unsigned char bin[32]; do { secp256k1_rand256_test(bin); if (secp256k1_fe_set_b32(x, bin)) { return; } } while(1); } void random_fe_non_zero(secp256k1_fe *nz) { int tries = 10; while (--tries >= 0) { random_fe(nz); secp256k1_fe_normalize(nz); if (!secp256k1_fe_is_zero(nz)) { break; } } /* Infinitesimal probability of spurious failure here */ CHECK(tries >= 0); } void random_fe_non_square(secp256k1_fe *ns) { secp256k1_fe r; random_fe_non_zero(ns); if (secp256k1_fe_sqrt(&r, ns)) { secp256k1_fe_negate(ns, ns, 1); } } int check_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b) { secp256k1_fe an = *a; secp256k1_fe bn = *b; secp256k1_fe_normalize_weak(&an); secp256k1_fe_normalize_var(&bn); return secp256k1_fe_equal_var(&an, &bn); } int check_fe_inverse(const secp256k1_fe *a, const secp256k1_fe *ai) { secp256k1_fe x; secp256k1_fe one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_fe_mul(&x, a, ai); return check_fe_equal(&x, &one); } void run_field_convert(void) { static const unsigned char b32[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x40 }; static const secp256k1_fe_storage fes = SECP256K1_FE_STORAGE_CONST( 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL ); static const secp256k1_fe fe = SECP256K1_FE_CONST( 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL ); secp256k1_fe fe2; unsigned char b322[32]; secp256k1_fe_storage fes2; /* Check conversions to fe. */ CHECK(secp256k1_fe_set_b32(&fe2, b32)); CHECK(secp256k1_fe_equal_var(&fe, &fe2)); secp256k1_fe_from_storage(&fe2, &fes); CHECK(secp256k1_fe_equal_var(&fe, &fe2)); /* Check conversion from fe. */ secp256k1_fe_get_b32(b322, &fe); CHECK(memcmp(b322, b32, 32) == 0); secp256k1_fe_to_storage(&fes2, &fe); CHECK(memcmp(&fes2, &fes, sizeof(fes)) == 0); } int fe_memcmp(const secp256k1_fe *a, const secp256k1_fe *b) { secp256k1_fe t = *b; #ifdef VERIFY t.magnitude = a->magnitude; t.normalized = a->normalized; #endif return memcmp(a, &t, sizeof(secp256k1_fe)); } void run_field_misc(void) { secp256k1_fe x; secp256k1_fe y; secp256k1_fe z; secp256k1_fe q; secp256k1_fe fe5 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 5); int i, j; for (i = 0; i < 5*count; i++) { secp256k1_fe_storage xs, ys, zs; random_fe(&x); random_fe_non_zero(&y); /* Test the fe equality and comparison operations. */ CHECK(secp256k1_fe_cmp_var(&x, &x) == 0); CHECK(secp256k1_fe_equal_var(&x, &x)); z = x; secp256k1_fe_add(&z,&y); /* Test fe conditional move; z is not normalized here. */ q = x; secp256k1_fe_cmov(&x, &z, 0); VERIFY_CHECK(!x.normalized && x.magnitude == z.magnitude); secp256k1_fe_cmov(&x, &x, 1); CHECK(fe_memcmp(&x, &z) != 0); CHECK(fe_memcmp(&x, &q) == 0); secp256k1_fe_cmov(&q, &z, 1); VERIFY_CHECK(!q.normalized && q.magnitude == z.magnitude); CHECK(fe_memcmp(&q, &z) == 0); secp256k1_fe_normalize_var(&x); secp256k1_fe_normalize_var(&z); CHECK(!secp256k1_fe_equal_var(&x, &z)); secp256k1_fe_normalize_var(&q); secp256k1_fe_cmov(&q, &z, (i&1)); VERIFY_CHECK(q.normalized && q.magnitude == 1); for (j = 0; j < 6; j++) { secp256k1_fe_negate(&z, &z, j+1); secp256k1_fe_normalize_var(&q); secp256k1_fe_cmov(&q, &z, (j&1)); VERIFY_CHECK(!q.normalized && q.magnitude == (j+2)); } secp256k1_fe_normalize_var(&z); /* Test storage conversion and conditional moves. */ secp256k1_fe_to_storage(&xs, &x); secp256k1_fe_to_storage(&ys, &y); secp256k1_fe_to_storage(&zs, &z); secp256k1_fe_storage_cmov(&zs, &xs, 0); secp256k1_fe_storage_cmov(&zs, &zs, 1); CHECK(memcmp(&xs, &zs, sizeof(xs)) != 0); secp256k1_fe_storage_cmov(&ys, &xs, 1); CHECK(memcmp(&xs, &ys, sizeof(xs)) == 0); secp256k1_fe_from_storage(&x, &xs); secp256k1_fe_from_storage(&y, &ys); secp256k1_fe_from_storage(&z, &zs); /* Test that mul_int, mul, and add agree. */ secp256k1_fe_add(&y, &x); secp256k1_fe_add(&y, &x); z = x; secp256k1_fe_mul_int(&z, 3); CHECK(check_fe_equal(&y, &z)); secp256k1_fe_add(&y, &x); secp256k1_fe_add(&z, &x); CHECK(check_fe_equal(&z, &y)); z = x; secp256k1_fe_mul_int(&z, 5); secp256k1_fe_mul(&q, &x, &fe5); CHECK(check_fe_equal(&z, &q)); secp256k1_fe_negate(&x, &x, 1); secp256k1_fe_add(&z, &x); secp256k1_fe_add(&q, &x); CHECK(check_fe_equal(&y, &z)); CHECK(check_fe_equal(&q, &y)); } } void run_field_inv(void) { secp256k1_fe x, xi, xii; int i; for (i = 0; i < 10*count; i++) { random_fe_non_zero(&x); secp256k1_fe_inv(&xi, &x); CHECK(check_fe_inverse(&x, &xi)); secp256k1_fe_inv(&xii, &xi); CHECK(check_fe_equal(&x, &xii)); } } void run_field_inv_var(void) { secp256k1_fe x, xi, xii; int i; for (i = 0; i < 10*count; i++) { random_fe_non_zero(&x); secp256k1_fe_inv_var(&xi, &x); CHECK(check_fe_inverse(&x, &xi)); secp256k1_fe_inv_var(&xii, &xi); CHECK(check_fe_equal(&x, &xii)); } } void run_field_inv_all_var(void) { secp256k1_fe x[16], xi[16], xii[16]; int i; /* Check it's safe to call for 0 elements */ secp256k1_fe_inv_all_var(xi, x, 0); for (i = 0; i < count; i++) { size_t j; size_t len = secp256k1_rand_int(15) + 1; for (j = 0; j < len; j++) { random_fe_non_zero(&x[j]); } secp256k1_fe_inv_all_var(xi, x, len); for (j = 0; j < len; j++) { CHECK(check_fe_inverse(&x[j], &xi[j])); } secp256k1_fe_inv_all_var(xii, xi, len); for (j = 0; j < len; j++) { CHECK(check_fe_equal(&x[j], &xii[j])); } } } void run_sqr(void) { secp256k1_fe x, s; { int i; secp256k1_fe_set_int(&x, 1); secp256k1_fe_negate(&x, &x, 1); for (i = 1; i <= 512; ++i) { secp256k1_fe_mul_int(&x, 2); secp256k1_fe_normalize(&x); secp256k1_fe_sqr(&s, &x); } } } void test_sqrt(const secp256k1_fe *a, const secp256k1_fe *k) { secp256k1_fe r1, r2; int v = secp256k1_fe_sqrt(&r1, a); CHECK((v == 0) == (k == NULL)); if (k != NULL) { /* Check that the returned root is +/- the given known answer */ secp256k1_fe_negate(&r2, &r1, 1); secp256k1_fe_add(&r1, k); secp256k1_fe_add(&r2, k); secp256k1_fe_normalize(&r1); secp256k1_fe_normalize(&r2); CHECK(secp256k1_fe_is_zero(&r1) || secp256k1_fe_is_zero(&r2)); } } void run_sqrt(void) { secp256k1_fe ns, x, s, t; int i; /* Check sqrt(0) is 0 */ secp256k1_fe_set_int(&x, 0); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); /* Check sqrt of small squares (and their negatives) */ for (i = 1; i <= 100; i++) { secp256k1_fe_set_int(&x, i); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); secp256k1_fe_negate(&t, &s, 1); test_sqrt(&t, NULL); } /* Consistency checks for large random values */ for (i = 0; i < 10; i++) { int j; random_fe_non_square(&ns); for (j = 0; j < count; j++) { random_fe(&x); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); secp256k1_fe_negate(&t, &s, 1); test_sqrt(&t, NULL); secp256k1_fe_mul(&t, &s, &ns); test_sqrt(&t, NULL); } } } /***** GROUP TESTS *****/ void ge_equals_ge(const secp256k1_ge *a, const secp256k1_ge *b) { CHECK(a->infinity == b->infinity); if (a->infinity) { return; } CHECK(secp256k1_fe_equal_var(&a->x, &b->x)); CHECK(secp256k1_fe_equal_var(&a->y, &b->y)); } /* This compares jacobian points including their Z, not just their geometric meaning. */ int gej_xyz_equals_gej(const secp256k1_gej *a, const secp256k1_gej *b) { secp256k1_gej a2; secp256k1_gej b2; int ret = 1; ret &= a->infinity == b->infinity; if (ret && !a->infinity) { a2 = *a; b2 = *b; secp256k1_fe_normalize(&a2.x); secp256k1_fe_normalize(&a2.y); secp256k1_fe_normalize(&a2.z); secp256k1_fe_normalize(&b2.x); secp256k1_fe_normalize(&b2.y); secp256k1_fe_normalize(&b2.z); ret &= secp256k1_fe_cmp_var(&a2.x, &b2.x) == 0; ret &= secp256k1_fe_cmp_var(&a2.y, &b2.y) == 0; ret &= secp256k1_fe_cmp_var(&a2.z, &b2.z) == 0; } return ret; } void ge_equals_gej(const secp256k1_ge *a, const secp256k1_gej *b) { secp256k1_fe z2s; secp256k1_fe u1, u2, s1, s2; CHECK(a->infinity == b->infinity); if (a->infinity) { return; } /* Check a.x * b.z^2 == b.x && a.y * b.z^3 == b.y, to avoid inverses. */ secp256k1_fe_sqr(&z2s, &b->z); secp256k1_fe_mul(&u1, &a->x, &z2s); u2 = b->x; secp256k1_fe_normalize_weak(&u2); secp256k1_fe_mul(&s1, &a->y, &z2s); secp256k1_fe_mul(&s1, &s1, &b->z); s2 = b->y; secp256k1_fe_normalize_weak(&s2); CHECK(secp256k1_fe_equal_var(&u1, &u2)); CHECK(secp256k1_fe_equal_var(&s1, &s2)); } void test_ge(void) { int i, i1; #ifdef USE_ENDOMORPHISM int runs = 6; #else int runs = 4; #endif /* Points: (infinity, p1, p1, -p1, -p1, p2, p2, -p2, -p2, p3, p3, -p3, -p3, p4, p4, -p4, -p4). * The second in each pair of identical points uses a random Z coordinate in the Jacobian form. * All magnitudes are randomized. * All 17*17 combinations of points are added to each other, using all applicable methods. * * When the endomorphism code is compiled in, p5 = lambda*p1 and p6 = lambda^2*p1 are added as well. */ secp256k1_ge *ge = (secp256k1_ge *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_ge) * (1 + 4 * runs)); secp256k1_gej *gej = (secp256k1_gej *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_gej) * (1 + 4 * runs)); secp256k1_fe *zinv = (secp256k1_fe *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs)); secp256k1_fe zf; secp256k1_fe zfi2, zfi3; secp256k1_gej_set_infinity(&gej[0]); secp256k1_ge_clear(&ge[0]); secp256k1_ge_set_gej_var(&ge[0], &gej[0]); for (i = 0; i < runs; i++) { int j; secp256k1_ge g; random_group_element_test(&g); #ifdef USE_ENDOMORPHISM if (i >= runs - 2) { secp256k1_ge_mul_lambda(&g, &ge[1]); } if (i >= runs - 1) { secp256k1_ge_mul_lambda(&g, &g); } #endif ge[1 + 4 * i] = g; ge[2 + 4 * i] = g; secp256k1_ge_neg(&ge[3 + 4 * i], &g); secp256k1_ge_neg(&ge[4 + 4 * i], &g); secp256k1_gej_set_ge(&gej[1 + 4 * i], &ge[1 + 4 * i]); random_group_element_jacobian_test(&gej[2 + 4 * i], &ge[2 + 4 * i]); secp256k1_gej_set_ge(&gej[3 + 4 * i], &ge[3 + 4 * i]); random_group_element_jacobian_test(&gej[4 + 4 * i], &ge[4 + 4 * i]); for (j = 0; j < 4; j++) { random_field_element_magnitude(&ge[1 + j + 4 * i].x); random_field_element_magnitude(&ge[1 + j + 4 * i].y); random_field_element_magnitude(&gej[1 + j + 4 * i].x); random_field_element_magnitude(&gej[1 + j + 4 * i].y); random_field_element_magnitude(&gej[1 + j + 4 * i].z); } } /* Compute z inverses. */ { secp256k1_fe *zs = checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs)); for (i = 0; i < 4 * runs + 1; i++) { if (i == 0) { /* The point at infinity does not have a meaningful z inverse. Any should do. */ do { random_field_element_test(&zs[i]); } while(secp256k1_fe_is_zero(&zs[i])); } else { zs[i] = gej[i].z; } } secp256k1_fe_inv_all_var(zinv, zs, 4 * runs + 1); free(zs); } /* Generate random zf, and zfi2 = 1/zf^2, zfi3 = 1/zf^3 */ do { random_field_element_test(&zf); } while(secp256k1_fe_is_zero(&zf)); random_field_element_magnitude(&zf); secp256k1_fe_inv_var(&zfi3, &zf); secp256k1_fe_sqr(&zfi2, &zfi3); secp256k1_fe_mul(&zfi3, &zfi3, &zfi2); for (i1 = 0; i1 < 1 + 4 * runs; i1++) { int i2; for (i2 = 0; i2 < 1 + 4 * runs; i2++) { /* Compute reference result using gej + gej (var). */ secp256k1_gej refj, resj; secp256k1_ge ref; secp256k1_fe zr; secp256k1_gej_add_var(&refj, &gej[i1], &gej[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr); /* Check Z ratio. */ if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&refj)) { secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zrz, &refj.z)); } secp256k1_ge_set_gej_var(&ref, &refj); /* Test gej + ge with Z ratio result (var). */ secp256k1_gej_add_ge_var(&resj, &gej[i1], &ge[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr); ge_equals_gej(&ref, &resj); if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&resj)) { secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zrz, &resj.z)); } /* Test gej + ge (var, with additional Z factor). */ { secp256k1_ge ge2_zfi = ge[i2]; /* the second term with x and y rescaled for z = 1/zf */ secp256k1_fe_mul(&ge2_zfi.x, &ge2_zfi.x, &zfi2); secp256k1_fe_mul(&ge2_zfi.y, &ge2_zfi.y, &zfi3); random_field_element_magnitude(&ge2_zfi.x); random_field_element_magnitude(&ge2_zfi.y); secp256k1_gej_add_zinv_var(&resj, &gej[i1], &ge2_zfi, &zf); ge_equals_gej(&ref, &resj); } /* Test gej + ge (const). */ if (i2 != 0) { /* secp256k1_gej_add_ge does not support its second argument being infinity. */ secp256k1_gej_add_ge(&resj, &gej[i1], &ge[i2]); ge_equals_gej(&ref, &resj); } /* Test doubling (var). */ if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 == ((i2 + 3)%4)/2)) { secp256k1_fe zr2; /* Normal doubling with Z ratio result. */ secp256k1_gej_double_var(&resj, &gej[i1], &zr2); ge_equals_gej(&ref, &resj); /* Check Z ratio. */ secp256k1_fe_mul(&zr2, &zr2, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zr2, &resj.z)); /* Normal doubling. */ secp256k1_gej_double_var(&resj, &gej[i2], NULL); ge_equals_gej(&ref, &resj); } /* Test adding opposites. */ if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 != ((i2 + 3)%4)/2)) { CHECK(secp256k1_ge_is_infinity(&ref)); } /* Test adding infinity. */ if (i1 == 0) { CHECK(secp256k1_ge_is_infinity(&ge[i1])); CHECK(secp256k1_gej_is_infinity(&gej[i1])); ge_equals_gej(&ref, &gej[i2]); } if (i2 == 0) { CHECK(secp256k1_ge_is_infinity(&ge[i2])); CHECK(secp256k1_gej_is_infinity(&gej[i2])); ge_equals_gej(&ref, &gej[i1]); } } } /* Test adding all points together in random order equals infinity. */ { secp256k1_gej sum = SECP256K1_GEJ_CONST_INFINITY; secp256k1_gej *gej_shuffled = (secp256k1_gej *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_gej)); for (i = 0; i < 4 * runs + 1; i++) { gej_shuffled[i] = gej[i]; } for (i = 0; i < 4 * runs + 1; i++) { int swap = i + secp256k1_rand_int(4 * runs + 1 - i); if (swap != i) { secp256k1_gej t = gej_shuffled[i]; gej_shuffled[i] = gej_shuffled[swap]; gej_shuffled[swap] = t; } } for (i = 0; i < 4 * runs + 1; i++) { secp256k1_gej_add_var(&sum, &sum, &gej_shuffled[i], NULL); } CHECK(secp256k1_gej_is_infinity(&sum)); free(gej_shuffled); } /* Test batch gej -> ge conversion with and without known z ratios. */ { secp256k1_fe *zr = (secp256k1_fe *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_fe)); secp256k1_ge *ge_set_table = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge)); secp256k1_ge *ge_set_all = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge)); for (i = 0; i < 4 * runs + 1; i++) { /* Compute gej[i + 1].z / gez[i].z (with gej[n].z taken to be 1). */ if (i < 4 * runs) { secp256k1_fe_mul(&zr[i + 1], &zinv[i], &gej[i + 1].z); } } secp256k1_ge_set_table_gej_var(ge_set_table, gej, zr, 4 * runs + 1); secp256k1_ge_set_all_gej_var(ge_set_all, gej, 4 * runs + 1, &ctx->error_callback); for (i = 0; i < 4 * runs + 1; i++) { secp256k1_fe s; random_fe_non_zero(&s); secp256k1_gej_rescale(&gej[i], &s); ge_equals_gej(&ge_set_table[i], &gej[i]); ge_equals_gej(&ge_set_all[i], &gej[i]); } free(ge_set_table); free(ge_set_all); free(zr); } free(ge); free(gej); free(zinv); } void test_add_neg_y_diff_x(void) { /* The point of this test is to check that we can add two points * whose y-coordinates are negatives of each other but whose x * coordinates differ. If the x-coordinates were the same, these * points would be negatives of each other and their sum is * infinity. This is cool because it "covers up" any degeneracy * in the addition algorithm that would cause the xy coordinates * of the sum to be wrong (since infinity has no xy coordinates). * HOWEVER, if the x-coordinates are different, infinity is the * wrong answer, and such degeneracies are exposed. This is the * root of https://github.com/bull-core/secp256k1/issues/257 * which this test is a regression test for. * * These points were generated in sage as * # secp256k1 params * F = FiniteField (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F) * C = EllipticCurve ([F (0), F (7)]) * G = C.lift_x(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798) * N = FiniteField(G.order()) * * # endomorphism values (lambda is 1^{1/3} in N, beta is 1^{1/3} in F) * x = polygen(N) * lam = (1 - x^3).roots()[1][0] * * # random "bad pair" * P = C.random_element() * Q = -int(lam) * P * print " P: %x %x" % P.xy() * print " Q: %x %x" % Q.xy() * print "P + Q: %x %x" % (P + Q).xy() */ secp256k1_gej aj = SECP256K1_GEJ_CONST( 0x8d24cd95, 0x0a355af1, 0x3c543505, 0x44238d30, 0x0643d79f, 0x05a59614, 0x2f8ec030, 0xd58977cb, 0x001e337a, 0x38093dcd, 0x6c0f386d, 0x0b1293a8, 0x4d72c879, 0xd7681924, 0x44e6d2f3, 0x9190117d ); secp256k1_gej bj = SECP256K1_GEJ_CONST( 0xc7b74206, 0x1f788cd9, 0xabd0937d, 0x164a0d86, 0x95f6ff75, 0xf19a4ce9, 0xd013bd7b, 0xbf92d2a7, 0xffe1cc85, 0xc7f6c232, 0x93f0c792, 0xf4ed6c57, 0xb28d3786, 0x2897e6db, 0xbb192d0b, 0x6e6feab2 ); secp256k1_gej sumj = SECP256K1_GEJ_CONST( 0x671a63c0, 0x3efdad4c, 0x389a7798, 0x24356027, 0xb3d69010, 0x278625c3, 0x5c86d390, 0x184a8f7a, 0x5f6409c2, 0x2ce01f2b, 0x511fd375, 0x25071d08, 0xda651801, 0x70e95caf, 0x8f0d893c, 0xbed8fbbe ); secp256k1_ge b; secp256k1_gej resj; secp256k1_ge res; secp256k1_ge_set_gej(&b, &bj); secp256k1_gej_add_var(&resj, &aj, &bj, NULL); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); secp256k1_gej_add_ge(&resj, &aj, &b); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); secp256k1_gej_add_ge_var(&resj, &aj, &b, NULL); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); } void run_ge(void) { int i; for (i = 0; i < count * 32; i++) { test_ge(); } test_add_neg_y_diff_x(); } void test_ec_combine(void) { secp256k1_scalar sum = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_pubkey data[6]; const secp256k1_pubkey* d[6]; secp256k1_pubkey sd; secp256k1_pubkey sd2; secp256k1_gej Qj; secp256k1_ge Q; int i; for (i = 1; i <= 6; i++) { secp256k1_scalar s; random_scalar_order_test(&s); secp256k1_scalar_add(&sum, &sum, &s); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &s); secp256k1_ge_set_gej(&Q, &Qj); secp256k1_pubkey_save(&data[i - 1], &Q); d[i - 1] = &data[i - 1]; secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &sum); secp256k1_ge_set_gej(&Q, &Qj); secp256k1_pubkey_save(&sd, &Q); CHECK(secp256k1_ec_pubkey_combine(ctx, &sd2, d, i) == 1); CHECK(memcmp(&sd, &sd2, sizeof(sd)) == 0); } } void run_ec_combine(void) { int i; for (i = 0; i < count * 8; i++) { test_ec_combine(); } } void test_group_decompress(const secp256k1_fe* x) { /* The input itself, normalized. */ secp256k1_fe fex = *x; secp256k1_fe fez; /* Results of set_xquad_var, set_xo_var(..., 0), set_xo_var(..., 1). */ secp256k1_ge ge_quad, ge_even, ge_odd; secp256k1_gej gej_quad; /* Return values of the above calls. */ int res_quad, res_even, res_odd; secp256k1_fe_normalize_var(&fex); res_quad = secp256k1_ge_set_xquad(&ge_quad, &fex); res_even = secp256k1_ge_set_xo_var(&ge_even, &fex, 0); res_odd = secp256k1_ge_set_xo_var(&ge_odd, &fex, 1); CHECK(res_quad == res_even); CHECK(res_quad == res_odd); if (res_quad) { secp256k1_fe_normalize_var(&ge_quad.x); secp256k1_fe_normalize_var(&ge_odd.x); secp256k1_fe_normalize_var(&ge_even.x); secp256k1_fe_normalize_var(&ge_quad.y); secp256k1_fe_normalize_var(&ge_odd.y); secp256k1_fe_normalize_var(&ge_even.y); /* No infinity allowed. */ CHECK(!ge_quad.infinity); CHECK(!ge_even.infinity); CHECK(!ge_odd.infinity); /* Check that the x coordinates check out. */ CHECK(secp256k1_fe_equal_var(&ge_quad.x, x)); CHECK(secp256k1_fe_equal_var(&ge_even.x, x)); CHECK(secp256k1_fe_equal_var(&ge_odd.x, x)); /* Check that the Y coordinate result in ge_quad is a square. */ CHECK(secp256k1_fe_is_quad_var(&ge_quad.y)); /* Check odd/even Y in ge_odd, ge_even. */ CHECK(secp256k1_fe_is_odd(&ge_odd.y)); CHECK(!secp256k1_fe_is_odd(&ge_even.y)); /* Check secp256k1_gej_has_quad_y_var. */ secp256k1_gej_set_ge(&gej_quad, &ge_quad); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); do { random_fe_test(&fez); } while (secp256k1_fe_is_zero(&fez)); secp256k1_gej_rescale(&gej_quad, &fez); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); secp256k1_gej_neg(&gej_quad, &gej_quad); CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad)); do { random_fe_test(&fez); } while (secp256k1_fe_is_zero(&fez)); secp256k1_gej_rescale(&gej_quad, &fez); CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad)); secp256k1_gej_neg(&gej_quad, &gej_quad); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); } } void run_group_decompress(void) { int i; for (i = 0; i < count * 4; i++) { secp256k1_fe fe; random_fe_test(&fe); test_group_decompress(&fe); } } /***** ECMULT TESTS *****/ void run_ecmult_chain(void) { /* random starting point A (on the curve) */ secp256k1_gej a = SECP256K1_GEJ_CONST( 0x8b30bbe9, 0xae2a9906, 0x96b22f67, 0x0709dff3, 0x727fd8bc, 0x04d3362c, 0x6c7bf458, 0xe2846004, 0xa357ae91, 0x5c4a6528, 0x1309edf2, 0x0504740f, 0x0eb33439, 0x90216b4f, 0x81063cb6, 0x5f2f7e0f ); /* two random initial factors xn and gn */ secp256k1_scalar xn = SECP256K1_SCALAR_CONST( 0x84cc5452, 0xf7fde1ed, 0xb4d38a8c, 0xe9b1b84c, 0xcef31f14, 0x6e569be9, 0x705d357a, 0x42985407 ); secp256k1_scalar gn = SECP256K1_SCALAR_CONST( 0xa1e58d22, 0x553dcd42, 0xb2398062, 0x5d4c57a9, 0x6e9323d4, 0x2b3152e5, 0xca2c3990, 0xedc7c9de ); /* two small multipliers to be applied to xn and gn in every iteration: */ static const secp256k1_scalar xf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x1337); static const secp256k1_scalar gf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x7113); /* accumulators with the resulting coefficients to A and G */ secp256k1_scalar ae = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_scalar ge = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); /* actual points */ secp256k1_gej x; secp256k1_gej x2; int i; /* the point being computed */ x = a; for (i = 0; i < 200*count; i++) { /* in each iteration, compute X = xn*X + gn*G; */ secp256k1_ecmult(&ctx->ecmult_ctx, &x, &x, &xn, &gn); /* also compute ae and ge: the actual accumulated factors for A and G */ /* if X was (ae*A+ge*G), xn*X + gn*G results in (xn*ae*A + (xn*ge+gn)*G) */ secp256k1_scalar_mul(&ae, &ae, &xn); secp256k1_scalar_mul(&ge, &ge, &xn); secp256k1_scalar_add(&ge, &ge, &gn); /* modify xn and gn */ secp256k1_scalar_mul(&xn, &xn, &xf); secp256k1_scalar_mul(&gn, &gn, &gf); /* verify */ if (i == 19999) { /* expected result after 19999 iterations */ secp256k1_gej rp = SECP256K1_GEJ_CONST( 0xD6E96687, 0xF9B10D09, 0x2A6F3543, 0x9D86CEBE, 0xA4535D0D, 0x409F5358, 0x6440BD74, 0xB933E830, 0xB95CBCA2, 0xC77DA786, 0x539BE8FD, 0x53354D2D, 0x3B4F566A, 0xE6580454, 0x07ED6015, 0xEE1B2A88 ); secp256k1_gej_neg(&rp, &rp); secp256k1_gej_add_var(&rp, &rp, &x, NULL); CHECK(secp256k1_gej_is_infinity(&rp)); } } /* redo the computation, but directly with the resulting ae and ge coefficients: */ secp256k1_ecmult(&ctx->ecmult_ctx, &x2, &a, &ae, &ge); secp256k1_gej_neg(&x2, &x2); secp256k1_gej_add_var(&x2, &x2, &x, NULL); CHECK(secp256k1_gej_is_infinity(&x2)); } void test_point_times_order(const secp256k1_gej *point) { /* X * (point + G) + (order-X) * (pointer + G) = 0 */ secp256k1_scalar x; secp256k1_scalar nx; secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_gej res1, res2; secp256k1_ge res3; unsigned char pub[65]; size_t psize = 65; random_scalar_order_test(&x); secp256k1_scalar_negate(&nx, &x); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &x, &x); /* calc res1 = x * point + x * G; */ secp256k1_ecmult(&ctx->ecmult_ctx, &res2, point, &nx, &nx); /* calc res2 = (order - x) * point + (order - x) * G; */ secp256k1_gej_add_var(&res1, &res1, &res2, NULL); CHECK(secp256k1_gej_is_infinity(&res1)); CHECK(secp256k1_gej_is_valid_var(&res1) == 0); secp256k1_ge_set_gej(&res3, &res1); CHECK(secp256k1_ge_is_infinity(&res3)); CHECK(secp256k1_ge_is_valid_var(&res3) == 0); CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 0) == 0); psize = 65; CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 1) == 0); /* check zero/one edge cases */ secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &zero); secp256k1_ge_set_gej(&res3, &res1); CHECK(secp256k1_ge_is_infinity(&res3)); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &one, &zero); secp256k1_ge_set_gej(&res3, &res1); ge_equals_gej(&res3, point); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &one); secp256k1_ge_set_gej(&res3, &res1); ge_equals_ge(&res3, &secp256k1_ge_const_g); } void run_point_times_order(void) { int i; secp256k1_fe x = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 2); static const secp256k1_fe xr = SECP256K1_FE_CONST( 0x7603CB59, 0xB0EF6C63, 0xFE608479, 0x2A0C378C, 0xDB3233A8, 0x0F8A9A09, 0xA877DEAD, 0x31B38C45 ); for (i = 0; i < 500; i++) { secp256k1_ge p; if (secp256k1_ge_set_xo_var(&p, &x, 1)) { secp256k1_gej j; CHECK(secp256k1_ge_is_valid_var(&p)); secp256k1_gej_set_ge(&j, &p); CHECK(secp256k1_gej_is_valid_var(&j)); test_point_times_order(&j); } secp256k1_fe_sqr(&x, &x); } secp256k1_fe_normalize_var(&x); CHECK(secp256k1_fe_equal_var(&x, &xr)); } void ecmult_const_random_mult(void) { /* random starting point A (on the curve) */ secp256k1_ge a = SECP256K1_GE_CONST( 0x6d986544, 0x57ff52b8, 0xcf1b8126, 0x5b802a5b, 0xa97f9263, 0xb1e88044, 0x93351325, 0x91bc450a, 0x535c59f7, 0x325e5d2b, 0xc391fbe8, 0x3c12787c, 0x337e4a98, 0xe82a9011, 0x0123ba37, 0xdd769c7d ); /* random initial factor xn */ secp256k1_scalar xn = SECP256K1_SCALAR_CONST( 0x649d4f77, 0xc4242df7, 0x7f2079c9, 0x14530327, 0xa31b876a, 0xd2d8ce2a, 0x2236d5c6, 0xd7b2029b ); /* expected xn * A (from sage) */ secp256k1_ge expected_b = SECP256K1_GE_CONST( 0x23773684, 0x4d209dc7, 0x098a786f, 0x20d06fcd, 0x070a38bf, 0xc11ac651, 0x03004319, 0x1e2a8786, 0xed8c3b8e, 0xc06dd57b, 0xd06ea66e, 0x45492b0f, 0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956 ); secp256k1_gej b; secp256k1_ecmult_const(&b, &a, &xn); CHECK(secp256k1_ge_is_valid_var(&a)); ge_equals_gej(&expected_b, &b); } void ecmult_const_commutativity(void) { secp256k1_scalar a; secp256k1_scalar b; secp256k1_gej res1; secp256k1_gej res2; secp256k1_ge mid1; secp256k1_ge mid2; random_scalar_order_test(&a); random_scalar_order_test(&b); secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a); secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); secp256k1_ecmult_const(&res1, &mid1, &b); secp256k1_ecmult_const(&res2, &mid2, &a); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); ge_equals_ge(&mid1, &mid2); } void ecmult_const_mult_zero_one(void) { secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_scalar negone; secp256k1_gej res1; secp256k1_ge res2; secp256k1_ge point; secp256k1_scalar_negate(&negone, &one); random_group_element_test(&point); secp256k1_ecmult_const(&res1, &point, &zero); secp256k1_ge_set_gej(&res2, &res1); CHECK(secp256k1_ge_is_infinity(&res2)); secp256k1_ecmult_const(&res1, &point, &one); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); secp256k1_ecmult_const(&res1, &point, &negone); secp256k1_gej_neg(&res1, &res1); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); } void ecmult_const_chain_multiply(void) { /* Check known result (randomly generated test problem from sage) */ const secp256k1_scalar scalar = SECP256K1_SCALAR_CONST( 0x4968d524, 0x2abf9b7a, 0x466abbcf, 0x34b11b6d, 0xcd83d307, 0x827bed62, 0x05fad0ce, 0x18fae63b ); const secp256k1_gej expected_point = SECP256K1_GEJ_CONST( 0x5494c15d, 0x32099706, 0xc2395f94, 0x348745fd, 0x757ce30e, 0x4e8c90fb, 0xa2bad184, 0xf883c69f, 0x5d195d20, 0xe191bf7f, 0x1be3e55f, 0x56a80196, 0x6071ad01, 0xf1462f66, 0xc997fa94, 0xdb858435 ); secp256k1_gej point; secp256k1_ge res; int i; secp256k1_gej_set_ge(&point, &secp256k1_ge_const_g); for (i = 0; i < 100; ++i) { secp256k1_ge tmp; secp256k1_ge_set_gej(&tmp, &point); secp256k1_ecmult_const(&point, &tmp, &scalar); } secp256k1_ge_set_gej(&res, &point); ge_equals_gej(&res, &expected_point); } void run_ecmult_const_tests(void) { ecmult_const_mult_zero_one(); ecmult_const_random_mult(); ecmult_const_commutativity(); ecmult_const_chain_multiply(); } void test_wnaf(const secp256k1_scalar *number, int w) { secp256k1_scalar x, two, t; int wnaf[256]; int zeroes = -1; int i; int bits; secp256k1_scalar_set_int(&x, 0); secp256k1_scalar_set_int(&two, 2); bits = secp256k1_ecmult_wnaf(wnaf, 256, number, w); CHECK(bits <= 256); for (i = bits-1; i >= 0; i--) { int v = wnaf[i]; secp256k1_scalar_mul(&x, &x, &two); if (v) { CHECK(zeroes == -1 || zeroes >= w-1); /* check that distance between non-zero elements is at least w-1 */ zeroes=0; CHECK((v & 1) == 1); /* check non-zero elements are odd */ CHECK(v <= (1 << (w-1)) - 1); /* check range below */ CHECK(v >= -(1 << (w-1)) - 1); /* check range above */ } else { CHECK(zeroes != -1); /* check that no unnecessary zero padding exists */ zeroes++; } if (v >= 0) { secp256k1_scalar_set_int(&t, v); } else { secp256k1_scalar_set_int(&t, -v); secp256k1_scalar_negate(&t, &t); } secp256k1_scalar_add(&x, &x, &t); } CHECK(secp256k1_scalar_eq(&x, number)); /* check that wnaf represents number */ } void test_constant_wnaf_negate(const secp256k1_scalar *number) { secp256k1_scalar neg1 = *number; secp256k1_scalar neg2 = *number; int sign1 = 1; int sign2 = 1; if (!secp256k1_scalar_get_bits(&neg1, 0, 1)) { secp256k1_scalar_negate(&neg1, &neg1); sign1 = -1; } sign2 = secp256k1_scalar_cond_negate(&neg2, secp256k1_scalar_is_even(&neg2)); CHECK(sign1 == sign2); CHECK(secp256k1_scalar_eq(&neg1, &neg2)); } void test_constant_wnaf(const secp256k1_scalar *number, int w) { secp256k1_scalar x, shift; int wnaf[256] = {0}; int i; int skew; secp256k1_scalar num = *number; secp256k1_scalar_set_int(&x, 0); secp256k1_scalar_set_int(&shift, 1 << w); /* With USE_ENDOMORPHISM on we only consider 128-bit numbers */ #ifdef USE_ENDOMORPHISM for (i = 0; i < 16; ++i) { secp256k1_scalar_shr_int(&num, 8); } #endif skew = secp256k1_wnaf_const(wnaf, num, w); for (i = WNAF_SIZE(w); i >= 0; --i) { secp256k1_scalar t; int v = wnaf[i]; CHECK(v != 0); /* check nonzero */ CHECK(v & 1); /* check parity */ CHECK(v > -(1 << w)); /* check range above */ CHECK(v < (1 << w)); /* check range below */ secp256k1_scalar_mul(&x, &x, &shift); if (v >= 0) { secp256k1_scalar_set_int(&t, v); } else { secp256k1_scalar_set_int(&t, -v); secp256k1_scalar_negate(&t, &t); } secp256k1_scalar_add(&x, &x, &t); } /* Skew num because when encoding numbers as odd we use an offset */ secp256k1_scalar_cadd_bit(&num, skew == 2, 1); CHECK(secp256k1_scalar_eq(&x, &num)); } void run_wnaf(void) { int i; secp256k1_scalar n = {{0}}; /* Sanity check: 1 and 2 are the smallest odd and even numbers and should * have easier-to-diagnose failure modes */ n.d[0] = 1; test_constant_wnaf(&n, 4); n.d[0] = 2; test_constant_wnaf(&n, 4); /* Random tests */ for (i = 0; i < count; i++) { random_scalar_order(&n); test_wnaf(&n, 4+(i%10)); test_constant_wnaf_negate(&n); test_constant_wnaf(&n, 4 + (i % 10)); } secp256k1_scalar_set_int(&n, 0); CHECK(secp256k1_scalar_cond_negate(&n, 1) == -1); CHECK(secp256k1_scalar_is_zero(&n)); CHECK(secp256k1_scalar_cond_negate(&n, 0) == 1); CHECK(secp256k1_scalar_is_zero(&n)); } void test_ecmult_constants(void) { /* Test ecmult_gen() for [0..36) and [order-36..0). */ secp256k1_scalar x; secp256k1_gej r; secp256k1_ge ng; int i; int j; secp256k1_ge_neg(&ng, &secp256k1_ge_const_g); for (i = 0; i < 36; i++ ) { secp256k1_scalar_set_int(&x, i); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x); for (j = 0; j < i; j++) { if (j == i - 1) { ge_equals_gej(&secp256k1_ge_const_g, &r); } secp256k1_gej_add_ge(&r, &r, &ng); } CHECK(secp256k1_gej_is_infinity(&r)); } for (i = 1; i <= 36; i++ ) { secp256k1_scalar_set_int(&x, i); secp256k1_scalar_negate(&x, &x); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x); for (j = 0; j < i; j++) { if (j == i - 1) { ge_equals_gej(&ng, &r); } secp256k1_gej_add_ge(&r, &r, &secp256k1_ge_const_g); } CHECK(secp256k1_gej_is_infinity(&r)); } } void run_ecmult_constants(void) { test_ecmult_constants(); } void test_ecmult_gen_blind(void) { /* Test ecmult_gen() blinding and confirm that the blinding changes, the affine points match, and the z's don't match. */ secp256k1_scalar key; secp256k1_scalar b; unsigned char seed32[32]; secp256k1_gej pgej; secp256k1_gej pgej2; secp256k1_gej i; secp256k1_ge pge; random_scalar_order_test(&key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej, &key); secp256k1_rand256(seed32); b = ctx->ecmult_gen_ctx.blind; i = ctx->ecmult_gen_ctx.initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32); CHECK(!secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind)); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej2, &key); CHECK(!gej_xyz_equals_gej(&pgej, &pgej2)); CHECK(!gej_xyz_equals_gej(&i, &ctx->ecmult_gen_ctx.initial)); secp256k1_ge_set_gej(&pge, &pgej); ge_equals_gej(&pge, &pgej2); } void test_ecmult_gen_blind_reset(void) { /* Test ecmult_gen() blinding reset and confirm that the blinding is consistent. */ secp256k1_scalar b; secp256k1_gej initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0); b = ctx->ecmult_gen_ctx.blind; initial = ctx->ecmult_gen_ctx.initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0); CHECK(secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind)); CHECK(gej_xyz_equals_gej(&initial, &ctx->ecmult_gen_ctx.initial)); } void run_ecmult_gen_blind(void) { int i; test_ecmult_gen_blind_reset(); for (i = 0; i < 10; i++) { test_ecmult_gen_blind(); } } #ifdef USE_ENDOMORPHISM /***** ENDOMORPHISH TESTS *****/ void test_scalar_split(void) { secp256k1_scalar full; secp256k1_scalar s1, slam; const unsigned char zero[32] = {0}; unsigned char tmp[32]; random_scalar_order_test(&full); secp256k1_scalar_split_lambda(&s1, &slam, &full); /* check that both are <= 128 bits in size */ if (secp256k1_scalar_is_high(&s1)) { secp256k1_scalar_negate(&s1, &s1); } if (secp256k1_scalar_is_high(&slam)) { secp256k1_scalar_negate(&slam, &slam); } secp256k1_scalar_get_b32(tmp, &s1); CHECK(memcmp(zero, tmp, 16) == 0); secp256k1_scalar_get_b32(tmp, &slam); CHECK(memcmp(zero, tmp, 16) == 0); } void run_endomorphism_tests(void) { test_scalar_split(); } #endif void ec_pubkey_parse_pointtest(const unsigned char *input, int xvalid, int yvalid) { unsigned char pubkeyc[65]; secp256k1_pubkey pubkey; secp256k1_ge ge; size_t pubkeyclen; int32_t ecount; ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); for (pubkeyclen = 3; pubkeyclen <= 65; pubkeyclen++) { /* Smaller sizes are tested exhaustively elsewhere. */ int32_t i; memcpy(&pubkeyc[1], input, 64); VG_UNDEF(&pubkeyc[pubkeyclen], 65 - pubkeyclen); for (i = 0; i < 256; i++) { /* Try all type bytes. */ int xpass; int ypass; int ysign; pubkeyc[0] = i; /* What sign does this point have? */ ysign = (input[63] & 1) + 2; /* For the current type (i) do we expect parsing to work? Handled all of compressed/uncompressed/hybrid. */ xpass = xvalid && (pubkeyclen == 33) && ((i & 254) == 2); /* Do we expect a parse and re-serialize as uncompressed to give a matching y? */ ypass = xvalid && yvalid && ((i & 4) == ((pubkeyclen == 65) << 2)) && ((i == 4) || ((i & 251) == ysign)) && ((pubkeyclen == 33) || (pubkeyclen == 65)); if (xpass || ypass) { /* These cases must parse. */ unsigned char pubkeyo[65]; size_t outl; memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); ecount = 0; CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); outl = 65; VG_UNDEF(pubkeyo, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_COMPRESSED) == 1); VG_CHECK(pubkeyo, outl); CHECK(outl == 33); CHECK(memcmp(&pubkeyo[1], &pubkeyc[1], 32) == 0); CHECK((pubkeyclen != 33) || (pubkeyo[0] == pubkeyc[0])); if (ypass) { /* This test isn't always done because we decode with alternative signs, so the y won't match. */ CHECK(pubkeyo[0] == ysign); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); secp256k1_pubkey_save(&pubkey, &ge); VG_CHECK(&pubkey, sizeof(pubkey)); outl = 65; VG_UNDEF(pubkeyo, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1); VG_CHECK(pubkeyo, outl); CHECK(outl == 65); CHECK(pubkeyo[0] == 4); CHECK(memcmp(&pubkeyo[1], input, 64) == 0); } CHECK(ecount == 0); } else { /* These cases must fail to parse. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } } } secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } void run_ec_pubkey_parse_test(void) { #define SECP256K1_EC_PARSE_TEST_NVALID (12) const unsigned char valid[SECP256K1_EC_PARSE_TEST_NVALID][64] = { { /* Point with leading and trailing zeros in x and y serialization. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0xef, 0xa1, 0x7b, 0x77, 0x61, 0xe1, 0xe4, 0x27, 0x06, 0x98, 0x9f, 0xb4, 0x83, 0xb8, 0xd2, 0xd4, 0x9b, 0xf7, 0x8f, 0xae, 0x98, 0x03, 0xf0, 0x99, 0xb8, 0x34, 0xed, 0xeb, 0x00 }, { /* Point with x equal to a 3rd root of unity.*/ 0x7a, 0xe9, 0x6a, 0x2b, 0x65, 0x7c, 0x07, 0x10, 0x6e, 0x64, 0x47, 0x9e, 0xac, 0x34, 0x34, 0xe9, 0x9c, 0xf0, 0x49, 0x75, 0x12, 0xf5, 0x89, 0x95, 0xc1, 0x39, 0x6c, 0x28, 0x71, 0x95, 0x01, 0xee, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Point with largest x. (1/2) */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c, 0x0e, 0x99, 0x4b, 0x14, 0xea, 0x72, 0xf8, 0xc3, 0xeb, 0x95, 0xc7, 0x1e, 0xf6, 0x92, 0x57, 0x5e, 0x77, 0x50, 0x58, 0x33, 0x2d, 0x7e, 0x52, 0xd0, 0x99, 0x5c, 0xf8, 0x03, 0x88, 0x71, 0xb6, 0x7d, }, { /* Point with largest x. (2/2) */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c, 0xf1, 0x66, 0xb4, 0xeb, 0x15, 0x8d, 0x07, 0x3c, 0x14, 0x6a, 0x38, 0xe1, 0x09, 0x6d, 0xa8, 0xa1, 0x88, 0xaf, 0xa7, 0xcc, 0xd2, 0x81, 0xad, 0x2f, 0x66, 0xa3, 0x07, 0xfb, 0x77, 0x8e, 0x45, 0xb2, }, { /* Point with smallest x. (1/2) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Point with smallest x. (2/2) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb, 0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41, }, { /* Point with largest y. (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with largest y. (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with largest y. (3/3) */ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with smallest y. (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Point with smallest y. (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Point with smallest y. (3/3) */ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } }; #define SECP256K1_EC_PARSE_TEST_NXVALID (4) const unsigned char onlyxvalid[SECP256K1_EC_PARSE_TEST_NXVALID][64] = { { /* Valid if y overflow ignored (y = 1 mod p). (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* Valid if y overflow ignored (y = 1 mod p). (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* Valid if y overflow ignored (y = 1 mod p). (3/3)*/ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* x on curve, y is from y^2 = x^3 + 8. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 } }; #define SECP256K1_EC_PARSE_TEST_NINVALID (7) const unsigned char invalid[SECP256K1_EC_PARSE_TEST_NINVALID][64] = { { /* x is third root of -8, y is -1 * (x^3+7); also on the curve for y^2 = x^3 + 9. */ 0x0a, 0x2d, 0x2b, 0xa9, 0x35, 0x07, 0xf1, 0xdf, 0x23, 0x37, 0x70, 0xc2, 0xa7, 0x97, 0x96, 0x2c, 0xc6, 0x1f, 0x6d, 0x15, 0xda, 0x14, 0xec, 0xd4, 0x7d, 0x8d, 0x27, 0xae, 0x1c, 0xd5, 0xf8, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Valid if x overflow ignored (x = 1 mod p). */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Valid if x overflow ignored (x = 1 mod p). */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, 0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb, 0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41, }, { /* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, 0xf4, 0x84, 0x14, 0x5c, 0xb0, 0x14, 0x9b, 0x82, 0x5d, 0xff, 0x41, 0x2f, 0xa0, 0x52, 0xa8, 0x3f, 0xcb, 0x72, 0xdb, 0x61, 0xd5, 0x6f, 0x37, 0x70, 0xce, 0x06, 0x6b, 0x73, 0x49, 0xa2, 0xaa, 0x28, }, { /* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, 0x0b, 0x7b, 0xeb, 0xa3, 0x4f, 0xeb, 0x64, 0x7d, 0xa2, 0x00, 0xbe, 0xd0, 0x5f, 0xad, 0x57, 0xc0, 0x34, 0x8d, 0x24, 0x9e, 0x2a, 0x90, 0xc8, 0x8f, 0x31, 0xf9, 0x94, 0x8b, 0xb6, 0x5d, 0x52, 0x07, }, { /* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x53, 0x7e, 0xef, 0xdf, 0xc1, 0x60, 0x6a, 0x07, 0x27, 0xcd, 0x69, 0xb4, 0xa7, 0x33, 0x3d, 0x38, 0xed, 0x44, 0xe3, 0x93, 0x2a, 0x71, 0x79, 0xee, 0xcb, 0x4b, 0x6f, 0xba, 0x93, 0x60, 0xdc, }, { /* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0xac, 0x81, 0x10, 0x20, 0x3e, 0x9f, 0x95, 0xf8, 0xd8, 0x32, 0x96, 0x4b, 0x58, 0xcc, 0xc2, 0xc7, 0x12, 0xbb, 0x1c, 0x6c, 0xd5, 0x8e, 0x86, 0x11, 0x34, 0xb4, 0x8f, 0x45, 0x6c, 0x9b, 0x53 } }; const unsigned char pubkeyc[66] = { /* Serialization of G. */ 0x04, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98, 0x48, 0x3A, 0xDA, 0x77, 0x26, 0xA3, 0xC4, 0x65, 0x5D, 0xA4, 0xFB, 0xFC, 0x0E, 0x11, 0x08, 0xA8, 0xFD, 0x17, 0xB4, 0x48, 0xA6, 0x85, 0x54, 0x19, 0x9C, 0x47, 0xD0, 0x8F, 0xFB, 0x10, 0xD4, 0xB8, 0x00 }; unsigned char sout[65]; unsigned char shortkey[2]; secp256k1_ge ge; secp256k1_pubkey pubkey; size_t len; int32_t i; int32_t ecount; int32_t ecount2; ecount = 0; /* Nothing should be reading this far into pubkeyc. */ VG_UNDEF(&pubkeyc[65], 1); secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); /* Zero length claimed, fail, zeroize, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(shortkey, 2); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 0) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* Length one claimed, fail, zeroize, no illegal arg error. */ for (i = 0; i < 256 ; i++) { memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; shortkey[0] = i; VG_UNDEF(&shortkey[1], 1); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 1) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } /* Length two claimed, fail, zeroize, no illegal arg error. */ for (i = 0; i < 65536 ; i++) { memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; shortkey[0] = i & 255; shortkey[1] = i >> 8; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 2) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); /* 33 bytes claimed on otherwise valid input starting with 0x04, fail, zeroize output, no illegal arg error. */ CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 33) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* NULL pubkey, illegal arg error. Pubkey isn't rewritten before this step, since it's NULL into the parser. */ CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, pubkeyc, 65) == 0); CHECK(ecount == 2); /* NULL input string. Illegal arg and zeroize output. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, NULL, 65) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 1); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 2); /* 64 bytes claimed on input starting with 0x04, fail, zeroize output, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 64) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* 66 bytes claimed, fail, zeroize output, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 66) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* Valid parse. */ memset(&pubkey, 0, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 65) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); VG_UNDEF(&ge, sizeof(ge)); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1); VG_CHECK(&ge.x, sizeof(ge.x)); VG_CHECK(&ge.y, sizeof(ge.y)); VG_CHECK(&ge.infinity, sizeof(ge.infinity)); ge_equals_ge(&secp256k1_ge_const_g, &ge); CHECK(ecount == 0); /* secp256k1_ec_pubkey_serialize illegal args. */ ecount = 0; len = 65; CHECK(secp256k1_ec_pubkey_serialize(ctx, NULL, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0); CHECK(ecount == 1); CHECK(len == 0); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, NULL, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0); CHECK(ecount == 2); len = 65; VG_UNDEF(sout, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, NULL, SECP256K1_EC_UNCOMPRESSED) == 0); VG_CHECK(sout, 65); CHECK(ecount == 3); CHECK(len == 0); len = 65; CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, ~0) == 0); CHECK(ecount == 4); CHECK(len == 0); len = 65; VG_UNDEF(sout, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1); VG_CHECK(sout, 65); CHECK(ecount == 4); CHECK(len == 65); /* Multiple illegal args. Should still set arg error only once. */ ecount = 0; ecount2 = 11; CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0); CHECK(ecount == 1); /* Does the illegal arg callback actually change the behavior? */ secp256k1_context_set_illegal_callback(ctx, uncounting_illegal_callback_fn, &ecount2); CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0); CHECK(ecount == 1); CHECK(ecount2 == 10); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); /* Try a bunch of prefabbed points with all possible encodings. */ for (i = 0; i < SECP256K1_EC_PARSE_TEST_NVALID; i++) { ec_pubkey_parse_pointtest(valid[i], 1, 1); } for (i = 0; i < SECP256K1_EC_PARSE_TEST_NXVALID; i++) { ec_pubkey_parse_pointtest(onlyxvalid[i], 1, 0); } for (i = 0; i < SECP256K1_EC_PARSE_TEST_NINVALID; i++) { ec_pubkey_parse_pointtest(invalid[i], 0, 0); } } void run_eckey_edge_case_test(void) { const unsigned char orderc[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 }; const unsigned char zeros[sizeof(secp256k1_pubkey)] = {0x00}; unsigned char ctmp[33]; unsigned char ctmp2[33]; secp256k1_pubkey pubkey; secp256k1_pubkey pubkey2; secp256k1_pubkey pubkey_one; secp256k1_pubkey pubkey_negone; const secp256k1_pubkey *pubkeys[3]; size_t len; int32_t ecount; /* Group order is too large, reject. */ CHECK(secp256k1_ec_seckey_verify(ctx, orderc) == 0); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, orderc) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* Maximum value is too large, reject. */ memset(ctmp, 255, 32); CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* Zero is too small, reject. */ memset(ctmp, 0, 32); CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* One must be accepted. */ ctmp[31] = 0x01; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); pubkey_one = pubkey; /* Group order + 1 is too large, reject. */ memcpy(ctmp, orderc, 32); ctmp[31] = 0x42; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* -1 must be accepted. */ ctmp[31] = 0x40; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); pubkey_negone = pubkey; /* Tweak of zero leaves the value changed. */ memset(ctmp2, 0, 32); CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, ctmp2) == 1); CHECK(memcmp(orderc, ctmp, 31) == 0 && ctmp[31] == 0x40); memcpy(&pubkey2, &pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Multiply tweak of zero zeroizes the output. */ CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, ctmp2) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, ctmp2) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Overflowing key tweak zeroizes. */ memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, orderc) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, orderc) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, orderc) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, orderc) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Private key tweaks results in a key of zero. */ ctmp2[31] = 1; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 0); CHECK(memcmp(zeros, ctmp2, 32) == 0); ctmp2[31] = 1; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Tweak computation wraps and results in a key of 1. */ ctmp2[31] = 2; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 1); CHECK(memcmp(ctmp2, zeros, 31) == 0 && ctmp2[31] == 1); ctmp2[31] = 2; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); ctmp2[31] = 1; CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Tweak mul * 2 = 1+1. */ CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); ctmp2[31] = 2; CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Test argument errors. */ ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); CHECK(ecount == 0); /* Zeroize pubkey on parse error. */ memset(&pubkey, 0, 32); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0); CHECK(ecount == 1); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); memset(&pubkey2, 0, 32); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 0); CHECK(ecount == 2); CHECK(memcmp(&pubkey2, zeros, sizeof(pubkey2)) == 0); /* Plain argument errors. */ ecount = 0; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); CHECK(ecount == 0); CHECK(secp256k1_ec_seckey_verify(ctx, NULL) == 0); CHECK(ecount == 1); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 4; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 4; CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); CHECK(secp256k1_ec_privkey_tweak_add(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 1; CHECK(secp256k1_ec_privkey_tweak_mul(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, NULL) == 0); CHECK(ecount == 2); ecount = 0; CHECK(secp256k1_ec_pubkey_create(ctx, NULL, ctmp) == 0); CHECK(ecount == 1); memset(&pubkey, 1, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* secp256k1_ec_pubkey_combine tests. */ ecount = 0; pubkeys[0] = &pubkey_one; VG_UNDEF(&pubkeys[0], sizeof(secp256k1_pubkey *)); VG_UNDEF(&pubkeys[1], sizeof(secp256k1_pubkey *)); VG_UNDEF(&pubkeys[2], sizeof(secp256k1_pubkey *)); memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 0) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_combine(ctx, NULL, pubkeys, 1) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 2); memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, NULL, 1) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 3); pubkeys[0] = &pubkey_negone; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 1) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); len = 33; CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1); CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_negone, SECP256K1_EC_COMPRESSED) == 1); CHECK(memcmp(ctmp, ctmp2, 33) == 0); /* Result is infinity. */ pubkeys[0] = &pubkey_one; pubkeys[1] = &pubkey_negone; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 3); /* Passes through infinity but comes out one. */ pubkeys[2] = &pubkey_one; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 3) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); len = 33; CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1); CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_one, SECP256K1_EC_COMPRESSED) == 1); CHECK(memcmp(ctmp, ctmp2, 33) == 0); /* Adds to two. */ pubkeys[1] = &pubkey_one; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } void random_sign(secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *key, const secp256k1_scalar *msg, int *recid) { secp256k1_scalar nonce; do { random_scalar_order_test(&nonce); } while(!secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, sigr, sigs, key, msg, &nonce, recid)); } void test_ecdsa_sign_verify(void) { secp256k1_gej pubj; secp256k1_ge pub; secp256k1_scalar one; secp256k1_scalar msg, key; secp256k1_scalar sigr, sigs; int recid; int getrec; random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pubj, &key); secp256k1_ge_set_gej(&pub, &pubj); getrec = secp256k1_rand_bits(1); random_sign(&sigr, &sigs, &key, &msg, getrec?&recid:NULL); if (getrec) { CHECK(recid >= 0 && recid < 4); } CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg)); secp256k1_scalar_set_int(&one, 1); secp256k1_scalar_add(&msg, &msg, &one); CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg)); } void run_ecdsa_sign_verify(void) { int i; for (i = 0; i < 10*count; i++) { test_ecdsa_sign_verify(); } } /** Dummy nonce generation function that just uses a precomputed nonce, and fails if it is not accepted. Use only for testing. */ static int precomputed_nonce_function(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { (void)msg32; (void)key32; (void)algo16; memcpy(nonce32, data, 32); return (counter == 0); } static int nonce_function_test_fail(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { /* Dummy nonce generator that has a fatal error on the first counter value. */ if (counter == 0) { return 0; } return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 1); } static int nonce_function_test_retry(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { /* Dummy nonce generator that produces unacceptable nonces for the first several counter values. */ if (counter < 3) { memset(nonce32, counter==0 ? 0 : 255, 32); if (counter == 2) { nonce32[31]--; } return 1; } if (counter < 5) { static const unsigned char order[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 }; memcpy(nonce32, order, 32); if (counter == 4) { nonce32[31]++; } return 1; } /* Retry rate of 6979 is negligible esp. as we only call this in deterministic tests. */ /* If someone does fine a case where it retries for secp256k1, we'd like to know. */ if (counter > 5) { return 0; } return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 5); } int is_empty_signature(const secp256k1_ecdsa_signature *sig) { static const unsigned char res[sizeof(secp256k1_ecdsa_signature)] = {0}; return memcmp(sig, res, sizeof(secp256k1_ecdsa_signature)) == 0; } void test_ecdsa_end_to_end(void) { unsigned char extra[32] = {0x00}; unsigned char privkey[32]; unsigned char message[32]; unsigned char privkey2[32]; secp256k1_ecdsa_signature signature[6]; secp256k1_scalar r, s; unsigned char sig[74]; size_t siglen = 74; unsigned char pubkeyc[65]; size_t pubkeyclen = 65; secp256k1_pubkey pubkey; secp256k1_pubkey pubkey_tmp; unsigned char seckey[300]; size_t seckeylen = 300; /* Generate a random key and message. */ { secp256k1_scalar msg, key; random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_scalar_get_b32(privkey, &key); secp256k1_scalar_get_b32(message, &msg); } /* Construct and verify corresponding public key. */ CHECK(secp256k1_ec_seckey_verify(ctx, privkey) == 1); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, privkey) == 1); /* Verify exporting and importing public key. */ CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyc, &pubkeyclen, &pubkey, secp256k1_rand_bits(1) == 1 ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED)); memset(&pubkey, 0, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1); /* Verify negation changes the key and changes it back */ memcpy(&pubkey_tmp, &pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1); CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) != 0); CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1); CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) == 0); /* Verify private key import and export. */ CHECK(ec_privkey_export_der(ctx, seckey, &seckeylen, privkey, secp256k1_rand_bits(1) == 1)); CHECK(ec_privkey_import_der(ctx, privkey2, seckey, seckeylen) == 1); CHECK(memcmp(privkey, privkey2, 32) == 0); /* Optionally tweak the keys using addition. */ if (secp256k1_rand_int(3) == 0) { int ret1; int ret2; unsigned char rnd[32]; secp256k1_pubkey pubkey2; secp256k1_rand256_test(rnd); ret1 = secp256k1_ec_privkey_tweak_add(ctx, privkey, rnd); ret2 = secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, rnd); CHECK(ret1 == ret2); if (ret1 == 0) { return; } CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); } /* Optionally tweak the keys using multiplication. */ if (secp256k1_rand_int(3) == 0) { int ret1; int ret2; unsigned char rnd[32]; secp256k1_pubkey pubkey2; secp256k1_rand256_test(rnd); ret1 = secp256k1_ec_privkey_tweak_mul(ctx, privkey, rnd); ret2 = secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, rnd); CHECK(ret1 == ret2); if (ret1 == 0) { return; } CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); } /* Sign. */ CHECK(secp256k1_ecdsa_sign(ctx, &signature[0], message, privkey, NULL, NULL) == 1); CHECK(secp256k1_ecdsa_sign(ctx, &signature[4], message, privkey, NULL, NULL) == 1); CHECK(secp256k1_ecdsa_sign(ctx, &signature[1], message, privkey, NULL, extra) == 1); extra[31] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &signature[2], message, privkey, NULL, extra) == 1); extra[31] = 0; extra[0] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &signature[3], message, privkey, NULL, extra) == 1); CHECK(memcmp(&signature[0], &signature[4], sizeof(signature[0])) == 0); CHECK(memcmp(&signature[0], &signature[1], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[0], &signature[2], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[0], &signature[3], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[1], &signature[2], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[1], &signature[3], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[2], &signature[3], sizeof(signature[0])) != 0); /* Verify. */ CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[1], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[2], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[3], message, &pubkey) == 1); /* Test lower-S form, malleate, verify and fail, test again, malleate again */ CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[0])); secp256k1_ecdsa_signature_load(ctx, &r, &s, &signature[0]); secp256k1_scalar_negate(&s, &s); secp256k1_ecdsa_signature_save(&signature[5], &r, &s); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 0); CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5])); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5])); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1); secp256k1_scalar_negate(&s, &s); secp256k1_ecdsa_signature_save(&signature[5], &r, &s); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1); CHECK(memcmp(&signature[5], &signature[0], 64) == 0); /* Serialize/parse DER and verify again */ CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1); memset(&signature[0], 0, sizeof(signature[0])); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1); /* Serialize/destroy/parse DER and verify again. */ siglen = 74; CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1); sig[secp256k1_rand_int(siglen)] += 1 + secp256k1_rand_int(255); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 0 || secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 0); } void test_random_pubkeys(void) { secp256k1_ge elem; secp256k1_ge elem2; unsigned char in[65]; /* Generate some randomly sized pubkeys. */ size_t len = secp256k1_rand_bits(2) == 0 ? 65 : 33; if (secp256k1_rand_bits(2) == 0) { len = secp256k1_rand_bits(6); } if (len == 65) { in[0] = secp256k1_rand_bits(1) ? 4 : (secp256k1_rand_bits(1) ? 6 : 7); } else { in[0] = secp256k1_rand_bits(1) ? 2 : 3; } if (secp256k1_rand_bits(3) == 0) { in[0] = secp256k1_rand_bits(8); } if (len > 1) { secp256k1_rand256(&in[1]); } if (len > 33) { secp256k1_rand256(&in[33]); } if (secp256k1_eckey_pubkey_parse(&elem, in, len)) { unsigned char out[65]; unsigned char firstb; int res; size_t size = len; firstb = in[0]; /* If the pubkey can be parsed, it should round-trip... */ CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, len == 33)); CHECK(size == len); CHECK(memcmp(&in[1], &out[1], len-1) == 0); /* ... except for the type of hybrid inputs. */ if ((in[0] != 6) && (in[0] != 7)) { CHECK(in[0] == out[0]); } size = 65; CHECK(secp256k1_eckey_pubkey_serialize(&elem, in, &size, 0)); CHECK(size == 65); CHECK(secp256k1_eckey_pubkey_parse(&elem2, in, size)); ge_equals_ge(&elem,&elem2); /* Check that the X9.62 hybrid type is checked. */ in[0] = secp256k1_rand_bits(1) ? 6 : 7; res = secp256k1_eckey_pubkey_parse(&elem2, in, size); if (firstb == 2 || firstb == 3) { if (in[0] == firstb + 4) { CHECK(res); } else { CHECK(!res); } } if (res) { ge_equals_ge(&elem,&elem2); CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, 0)); CHECK(memcmp(&in[1], &out[1], 64) == 0); } } } void run_random_pubkeys(void) { int i; for (i = 0; i < 10*count; i++) { test_random_pubkeys(); } } void run_ecdsa_end_to_end(void) { int i; for (i = 0; i < 64*count; i++) { test_ecdsa_end_to_end(); } } int test_ecdsa_der_parse(const unsigned char *sig, size_t siglen, int certainly_der, int certainly_not_der) { static const unsigned char zeroes[32] = {0}; #ifdef ENABLE_OPENSSL_TESTS static const unsigned char max_scalar[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40 }; #endif int ret = 0; secp256k1_ecdsa_signature sig_der; unsigned char roundtrip_der[2048]; unsigned char compact_der[64]; size_t len_der = 2048; int parsed_der = 0, valid_der = 0, roundtrips_der = 0; secp256k1_ecdsa_signature sig_der_lax; unsigned char roundtrip_der_lax[2048]; unsigned char compact_der_lax[64]; size_t len_der_lax = 2048; int parsed_der_lax = 0, valid_der_lax = 0, roundtrips_der_lax = 0; #ifdef ENABLE_OPENSSL_TESTS ECDSA_SIG *sig_openssl; const unsigned char *sigptr; unsigned char roundtrip_openssl[2048]; int len_openssl = 2048; int parsed_openssl, valid_openssl = 0, roundtrips_openssl = 0; #endif parsed_der = secp256k1_ecdsa_signature_parse_der(ctx, &sig_der, sig, siglen); if (parsed_der) { ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der, &sig_der)) << 0; valid_der = (memcmp(compact_der, zeroes, 32) != 0) && (memcmp(compact_der + 32, zeroes, 32) != 0); } if (valid_der) { ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der, &len_der, &sig_der)) << 1; roundtrips_der = (len_der == siglen) && memcmp(roundtrip_der, sig, siglen) == 0; } parsed_der_lax = ecdsa_signature_parse_der_lax(ctx, &sig_der_lax, sig, siglen); if (parsed_der_lax) { ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der_lax, &sig_der_lax)) << 10; valid_der_lax = (memcmp(compact_der_lax, zeroes, 32) != 0) && (memcmp(compact_der_lax + 32, zeroes, 32) != 0); } if (valid_der_lax) { ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der_lax, &len_der_lax, &sig_der_lax)) << 11; roundtrips_der_lax = (len_der_lax == siglen) && memcmp(roundtrip_der_lax, sig, siglen) == 0; } if (certainly_der) { ret |= (!parsed_der) << 2; } if (certainly_not_der) { ret |= (parsed_der) << 17; } if (valid_der) { ret |= (!roundtrips_der) << 3; } if (valid_der) { ret |= (!roundtrips_der_lax) << 12; ret |= (len_der != len_der_lax) << 13; ret |= (memcmp(roundtrip_der_lax, roundtrip_der, len_der) != 0) << 14; } ret |= (roundtrips_der != roundtrips_der_lax) << 15; if (parsed_der) { ret |= (!parsed_der_lax) << 16; } #ifdef ENABLE_OPENSSL_TESTS sig_openssl = ECDSA_SIG_new(); sigptr = sig; parsed_openssl = (d2i_ECDSA_SIG(&sig_openssl, &sigptr, siglen) != NULL); if (parsed_openssl) { valid_openssl = !BN_is_negative(sig_openssl->r) && !BN_is_negative(sig_openssl->s) && BN_num_bits(sig_openssl->r) > 0 && BN_num_bits(sig_openssl->r) <= 256 && BN_num_bits(sig_openssl->s) > 0 && BN_num_bits(sig_openssl->s) <= 256; if (valid_openssl) { unsigned char tmp[32] = {0}; BN_bn2bin(sig_openssl->r, tmp + 32 - BN_num_bytes(sig_openssl->r)); valid_openssl = memcmp(tmp, max_scalar, 32) < 0; } if (valid_openssl) { unsigned char tmp[32] = {0}; BN_bn2bin(sig_openssl->s, tmp + 32 - BN_num_bytes(sig_openssl->s)); valid_openssl = memcmp(tmp, max_scalar, 32) < 0; } } len_openssl = i2d_ECDSA_SIG(sig_openssl, NULL); if (len_openssl <= 2048) { unsigned char *ptr = roundtrip_openssl; CHECK(i2d_ECDSA_SIG(sig_openssl, &ptr) == len_openssl); roundtrips_openssl = valid_openssl && ((size_t)len_openssl == siglen) && (memcmp(roundtrip_openssl, sig, siglen) == 0); } else { len_openssl = 0; } ECDSA_SIG_free(sig_openssl); ret |= (parsed_der && !parsed_openssl) << 4; ret |= (valid_der && !valid_openssl) << 5; ret |= (roundtrips_openssl && !parsed_der) << 6; ret |= (roundtrips_der != roundtrips_openssl) << 7; if (roundtrips_openssl) { ret |= (len_der != (size_t)len_openssl) << 8; ret |= (memcmp(roundtrip_der, roundtrip_openssl, len_der) != 0) << 9; } #endif return ret; } static void assign_big_endian(unsigned char *ptr, size_t ptrlen, uint32_t val) { size_t i; for (i = 0; i < ptrlen; i++) { int shift = ptrlen - 1 - i; if (shift >= 4) { ptr[i] = 0; } else { ptr[i] = (val >> shift) & 0xFF; } } } static void damage_array(unsigned char *sig, size_t *len) { int pos; int action = secp256k1_rand_bits(3); if (action < 1 && *len > 3) { /* Delete a byte. */ pos = secp256k1_rand_int(*len); memmove(sig + pos, sig + pos + 1, *len - pos - 1); (*len)--; return; } else if (action < 2 && *len < 2048) { /* Insert a byte. */ pos = secp256k1_rand_int(1 + *len); memmove(sig + pos + 1, sig + pos, *len - pos); sig[pos] = secp256k1_rand_bits(8); (*len)++; return; } else if (action < 4) { /* Modify a byte. */ sig[secp256k1_rand_int(*len)] += 1 + secp256k1_rand_int(255); return; } else { /* action < 8 */ /* Modify a bit. */ sig[secp256k1_rand_int(*len)] ^= 1 << secp256k1_rand_bits(3); return; } } static void random_ber_signature(unsigned char *sig, size_t *len, int* certainly_der, int* certainly_not_der) { int der; int nlow[2], nlen[2], nlenlen[2], nhbit[2], nhbyte[2], nzlen[2]; size_t tlen, elen, glen; int indet; int n; *len = 0; der = secp256k1_rand_bits(2) == 0; *certainly_der = der; *certainly_not_der = 0; indet = der ? 0 : secp256k1_rand_int(10) == 0; for (n = 0; n < 2; n++) { /* We generate two classes of numbers: nlow==1 "low" ones (up to 32 bytes), nlow==0 "high" ones (32 bytes with 129 top bits set, or larger than 32 bytes) */ nlow[n] = der ? 1 : (secp256k1_rand_bits(3) != 0); /* The length of the number in bytes (the first byte of which will always be nonzero) */ nlen[n] = nlow[n] ? secp256k1_rand_int(33) : 32 + secp256k1_rand_int(200) * secp256k1_rand_int(8) / 8; CHECK(nlen[n] <= 232); /* The top bit of the number. */ nhbit[n] = (nlow[n] == 0 && nlen[n] == 32) ? 1 : (nlen[n] == 0 ? 0 : secp256k1_rand_bits(1)); /* The top byte of the number (after the potential hardcoded 16 0xFF characters for "high" 32 bytes numbers) */ nhbyte[n] = nlen[n] == 0 ? 0 : (nhbit[n] ? 128 + secp256k1_rand_bits(7) : 1 + secp256k1_rand_int(127)); /* The number of zero bytes in front of the number (which is 0 or 1 in case of DER, otherwise we extend up to 300 bytes) */ nzlen[n] = der ? ((nlen[n] == 0 || nhbit[n]) ? 1 : 0) : (nlow[n] ? secp256k1_rand_int(3) : secp256k1_rand_int(300 - nlen[n]) * secp256k1_rand_int(8) / 8); if (nzlen[n] > ((nlen[n] == 0 || nhbit[n]) ? 1 : 0)) { *certainly_not_der = 1; } CHECK(nlen[n] + nzlen[n] <= 300); /* The length of the length descriptor for the number. 0 means short encoding, anything else is long encoding. */ nlenlen[n] = nlen[n] + nzlen[n] < 128 ? 0 : (nlen[n] + nzlen[n] < 256 ? 1 : 2); if (!der) { /* nlenlen[n] max 127 bytes */ int add = secp256k1_rand_int(127 - nlenlen[n]) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256; nlenlen[n] += add; if (add != 0) { *certainly_not_der = 1; } } CHECK(nlen[n] + nzlen[n] + nlenlen[n] <= 427); } /* The total length of the data to go, so far */ tlen = 2 + nlenlen[0] + nlen[0] + nzlen[0] + 2 + nlenlen[1] + nlen[1] + nzlen[1]; CHECK(tlen <= 856); /* The length of the garbage inside the tuple. */ elen = (der || indet) ? 0 : secp256k1_rand_int(980 - tlen) * secp256k1_rand_int(8) / 8; if (elen != 0) { *certainly_not_der = 1; } tlen += elen; CHECK(tlen <= 980); /* The length of the garbage after the end of the tuple. */ glen = der ? 0 : secp256k1_rand_int(990 - tlen) * secp256k1_rand_int(8) / 8; if (glen != 0) { *certainly_not_der = 1; } CHECK(tlen + glen <= 990); /* Write the tuple header. */ sig[(*len)++] = 0x30; if (indet) { /* Indeterminate length */ sig[(*len)++] = 0x80; *certainly_not_der = 1; } else { int tlenlen = tlen < 128 ? 0 : (tlen < 256 ? 1 : 2); if (!der) { int add = secp256k1_rand_int(127 - tlenlen) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256; tlenlen += add; if (add != 0) { *certainly_not_der = 1; } } if (tlenlen == 0) { /* Short length notation */ sig[(*len)++] = tlen; } else { /* Long length notation */ sig[(*len)++] = 128 + tlenlen; assign_big_endian(sig + *len, tlenlen, tlen); *len += tlenlen; } tlen += tlenlen; } tlen += 2; CHECK(tlen + glen <= 1119); for (n = 0; n < 2; n++) { /* Write the integer header. */ sig[(*len)++] = 0x02; if (nlenlen[n] == 0) { /* Short length notation */ sig[(*len)++] = nlen[n] + nzlen[n]; } else { /* Long length notation. */ sig[(*len)++] = 128 + nlenlen[n]; assign_big_endian(sig + *len, nlenlen[n], nlen[n] + nzlen[n]); *len += nlenlen[n]; } /* Write zero padding */ while (nzlen[n] > 0) { sig[(*len)++] = 0x00; nzlen[n]--; } if (nlen[n] == 32 && !nlow[n]) { /* Special extra 16 0xFF bytes in "high" 32-byte numbers */ int i; for (i = 0; i < 16; i++) { sig[(*len)++] = 0xFF; } nlen[n] -= 16; } /* Write first byte of number */ if (nlen[n] > 0) { sig[(*len)++] = nhbyte[n]; nlen[n]--; } /* Generate remaining random bytes of number */ secp256k1_rand_bytes_test(sig + *len, nlen[n]); *len += nlen[n]; nlen[n] = 0; } /* Generate random garbage inside tuple. */ secp256k1_rand_bytes_test(sig + *len, elen); *len += elen; /* Generate end-of-contents bytes. */ if (indet) { sig[(*len)++] = 0; sig[(*len)++] = 0; tlen += 2; } CHECK(tlen + glen <= 1121); /* Generate random garbage outside tuple. */ secp256k1_rand_bytes_test(sig + *len, glen); *len += glen; tlen += glen; CHECK(tlen <= 1121); CHECK(tlen == *len); } void run_ecdsa_der_parse(void) { int i,j; for (i = 0; i < 200 * count; i++) { unsigned char buffer[2048]; size_t buflen = 0; int certainly_der = 0; int certainly_not_der = 0; random_ber_signature(buffer, &buflen, &certainly_der, &certainly_not_der); CHECK(buflen <= 2048); for (j = 0; j < 16; j++) { int ret = 0; if (j > 0) { damage_array(buffer, &buflen); /* We don't know anything anymore about the DERness of the result */ certainly_der = 0; certainly_not_der = 0; } ret = test_ecdsa_der_parse(buffer, buflen, certainly_der, certainly_not_der); if (ret != 0) { size_t k; fprintf(stderr, "Failure %x on ", ret); for (k = 0; k < buflen; k++) { fprintf(stderr, "%02x ", buffer[k]); } fprintf(stderr, "\n"); } CHECK(ret == 0); } } } /* Tests several edge cases. */ void test_ecdsa_edge_cases(void) { int t; secp256k1_ecdsa_signature sig; /* Test the case where ECDSA recomputes a point that is infinity. */ { secp256k1_gej keyj; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_negate(&ss, &ss); secp256k1_scalar_inverse(&ss, &ss); secp256k1_scalar_set_int(&sr, 1); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &keyj, &sr); secp256k1_ge_set_gej(&key, &keyj); msg = ss; CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with r of zero fails. */ { const unsigned char pubkey_mods_zero[33] = { 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 0); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey_mods_zero, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with s of zero fails. */ { const unsigned char pubkey[33] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 0); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 1); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with message 0 passes. */ { const unsigned char pubkey[33] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }; const unsigned char pubkey2[33] = { 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x43 }; secp256k1_ge key; secp256k1_ge key2; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 2); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 2); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_set_int(&ss, 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0); } /* Verify signature with message 1 passes. */ { const unsigned char pubkey[33] = { 0x02, 0x14, 0x4e, 0x5a, 0x58, 0xef, 0x5b, 0x22, 0x6f, 0xd2, 0xe2, 0x07, 0x6a, 0x77, 0xcf, 0x05, 0xb4, 0x1d, 0xe7, 0x4a, 0x30, 0x98, 0x27, 0x8c, 0x93, 0xe6, 0xe6, 0x3c, 0x0b, 0xc4, 0x73, 0x76, 0x25 }; const unsigned char pubkey2[33] = { 0x02, 0x8a, 0xd5, 0x37, 0xed, 0x73, 0xd9, 0x40, 0x1d, 0xa0, 0x33, 0xd2, 0xdc, 0xf0, 0xaf, 0xae, 0x34, 0xcf, 0x5f, 0x96, 0x4c, 0x73, 0x28, 0x0f, 0x92, 0xc0, 0xf6, 0x9d, 0xd9, 0xb2, 0x09, 0x10, 0x62 }; const unsigned char csr[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xeb }; secp256k1_ge key; secp256k1_ge key2; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 1); secp256k1_scalar_set_b32(&sr, csr, NULL); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_set_int(&ss, 2); secp256k1_scalar_inverse_var(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0); } /* Verify signature with message -1 passes. */ { const unsigned char pubkey[33] = { 0x03, 0xaf, 0x97, 0xff, 0x7d, 0x3a, 0xf6, 0xa0, 0x02, 0x94, 0xbd, 0x9f, 0x4b, 0x2e, 0xd7, 0x52, 0x28, 0xdb, 0x49, 0x2a, 0x65, 0xcb, 0x1e, 0x27, 0x57, 0x9c, 0xba, 0x74, 0x20, 0xd5, 0x1d, 0x20, 0xf1 }; const unsigned char csr[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xee }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 1); secp256k1_scalar_negate(&msg, &msg); secp256k1_scalar_set_b32(&sr, csr, NULL); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); secp256k1_scalar_set_int(&ss, 3); secp256k1_scalar_inverse_var(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Signature where s would be zero. */ { secp256k1_pubkey pubkey; size_t siglen; int32_t ecount; unsigned char signature[72]; static const unsigned char nonce[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; static const unsigned char nonce2[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 }; const unsigned char key[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; unsigned char msg[32] = { 0x86, 0x41, 0x99, 0x81, 0x06, 0x23, 0x44, 0x53, 0xaa, 0x5f, 0x9d, 0x6a, 0x31, 0x78, 0xf4, 0xf7, 0xb8, 0x12, 0xe0, 0x0b, 0x81, 0x7a, 0x77, 0x62, 0x65, 0xdf, 0xdd, 0x31, 0xb9, 0x3e, 0x29, 0xa9, }; ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 0); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 0); msg[31] = 0xaa; CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 1); CHECK(ecount == 0); CHECK(secp256k1_ecdsa_sign(ctx, NULL, msg, key, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ecdsa_sign(ctx, &sig, NULL, key, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 2); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, NULL, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 1); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, key) == 1); CHECK(secp256k1_ecdsa_verify(ctx, NULL, msg, &pubkey) == 0); CHECK(ecount == 4); CHECK(secp256k1_ecdsa_verify(ctx, &sig, NULL, &pubkey) == 0); CHECK(ecount == 5); CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, NULL) == 0); CHECK(ecount == 6); CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 1); CHECK(ecount == 6); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0); CHECK(ecount == 7); /* That pubkeyload fails via an ARGCHECK is a little odd but makes sense because pubkeys are an opaque data type. */ CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 0); CHECK(ecount == 8); siglen = 72; CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, NULL, &siglen, &sig) == 0); CHECK(ecount == 9); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, NULL, &sig) == 0); CHECK(ecount == 10); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, NULL) == 0); CHECK(ecount == 11); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 1); CHECK(ecount == 11); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, NULL, signature, siglen) == 0); CHECK(ecount == 12); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, NULL, siglen) == 0); CHECK(ecount == 13); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, signature, siglen) == 1); CHECK(ecount == 13); siglen = 10; /* Too little room for a signature does not fail via ARGCHECK. */ CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 0); CHECK(ecount == 13); ecount = 0; CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, NULL) == 0); CHECK(ecount == 1); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, NULL, &sig) == 0); CHECK(ecount == 2); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, NULL) == 0); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, &sig) == 1); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, NULL, signature) == 0); CHECK(ecount == 4); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, NULL) == 0); CHECK(ecount == 5); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 1); CHECK(ecount == 5); memset(signature, 255, 64); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 0); CHECK(ecount == 5); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } /* Nonce function corner cases. */ for (t = 0; t < 2; t++) { static const unsigned char zero[32] = {0x00}; int i; unsigned char key[32]; unsigned char msg[32]; secp256k1_ecdsa_signature sig2; secp256k1_scalar sr[512], ss; const unsigned char *extra; extra = t == 0 ? NULL : zero; memset(msg, 0, 32); msg[31] = 1; /* High key results in signature failure. */ memset(key, 0xFF, 32); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0); CHECK(is_empty_signature(&sig)); /* Zero key results in signature failure. */ memset(key, 0, 32); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0); CHECK(is_empty_signature(&sig)); /* Nonce function failure results in signature failure. */ key[31] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_fail, extra) == 0); CHECK(is_empty_signature(&sig)); /* The retry loop successfully makes its way to the first good value. */ CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_retry, extra) == 1); CHECK(!is_empty_signature(&sig)); CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, nonce_function_rfc6979, extra) == 1); CHECK(!is_empty_signature(&sig2)); CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0); /* The default nonce function is deterministic. */ CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0); /* The default nonce function changes output with different messages. */ for(i = 0; i < 256; i++) { int j; msg[0] = i; CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2); for (j = 0; j < i; j++) { CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j])); } } msg[0] = 0; msg[31] = 2; /* The default nonce function changes output with different keys. */ for(i = 256; i < 512; i++) { int j; key[0] = i - 256; CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2); for (j = 0; j < i; j++) { CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j])); } } key[0] = 0; } { /* Check that optional nonce arguments do not have equivalent effect. */ const unsigned char zeros[32] = {0}; unsigned char nonce[32]; unsigned char nonce2[32]; unsigned char nonce3[32]; unsigned char nonce4[32]; VG_UNDEF(nonce,32); VG_UNDEF(nonce2,32); VG_UNDEF(nonce3,32); VG_UNDEF(nonce4,32); CHECK(nonce_function_rfc6979(nonce, zeros, zeros, NULL, NULL, 0) == 1); VG_CHECK(nonce,32); CHECK(nonce_function_rfc6979(nonce2, zeros, zeros, zeros, NULL, 0) == 1); VG_CHECK(nonce2,32); CHECK(nonce_function_rfc6979(nonce3, zeros, zeros, NULL, (void *)zeros, 0) == 1); VG_CHECK(nonce3,32); CHECK(nonce_function_rfc6979(nonce4, zeros, zeros, zeros, (void *)zeros, 0) == 1); VG_CHECK(nonce4,32); CHECK(memcmp(nonce, nonce2, 32) != 0); CHECK(memcmp(nonce, nonce3, 32) != 0); CHECK(memcmp(nonce, nonce4, 32) != 0); CHECK(memcmp(nonce2, nonce3, 32) != 0); CHECK(memcmp(nonce2, nonce4, 32) != 0); CHECK(memcmp(nonce3, nonce4, 32) != 0); } /* Privkey export where pubkey is the point at infinity. */ { unsigned char privkey[300]; unsigned char seckey[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, }; size_t outlen = 300; CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 0)); outlen = 300; CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 1)); } } void run_ecdsa_edge_cases(void) { test_ecdsa_edge_cases(); } #ifdef ENABLE_OPENSSL_TESTS EC_KEY *get_openssl_key(const unsigned char *key32) { unsigned char privkey[300]; size_t privkeylen; const unsigned char* pbegin = privkey; int compr = secp256k1_rand_bits(1); EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_secp256k1); CHECK(ec_privkey_export_der(ctx, privkey, &privkeylen, key32, compr)); CHECK(d2i_ECPrivateKey(&ec_key, &pbegin, privkeylen)); CHECK(EC_KEY_check_key(ec_key)); return ec_key; } void test_ecdsa_openssl(void) { secp256k1_gej qj; secp256k1_ge q; secp256k1_scalar sigr, sigs; secp256k1_scalar one; secp256k1_scalar msg2; secp256k1_scalar key, msg; EC_KEY *ec_key; unsigned int sigsize = 80; size_t secp_sigsize = 80; unsigned char message[32]; unsigned char signature[80]; unsigned char key32[32]; secp256k1_rand256_test(message); secp256k1_scalar_set_b32(&msg, message, NULL); random_scalar_order_test(&key); secp256k1_scalar_get_b32(key32, &key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &qj, &key); secp256k1_ge_set_gej(&q, &qj); ec_key = get_openssl_key(key32); CHECK(ec_key != NULL); CHECK(ECDSA_sign(0, message, sizeof(message), signature, &sigsize, ec_key)); CHECK(secp256k1_ecdsa_sig_parse(&sigr, &sigs, signature, sigsize)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg)); secp256k1_scalar_set_int(&one, 1); secp256k1_scalar_add(&msg2, &msg, &one); CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg2)); random_sign(&sigr, &sigs, &key, &msg, NULL); CHECK(secp256k1_ecdsa_sig_serialize(signature, &secp_sigsize, &sigr, &sigs)); CHECK(ECDSA_verify(0, message, sizeof(message), signature, secp_sigsize, ec_key) == 1); EC_KEY_free(ec_key); } void run_ecdsa_openssl(void) { int i; for (i = 0; i < 10*count; i++) { test_ecdsa_openssl(); } } #endif #ifdef ENABLE_MODULE_ECDH # include "modules/ecdh/tests_impl.h" #endif #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/tests_impl.h" #endif int main(int argc, char **argv) { unsigned char seed16[16] = {0}; unsigned char run32[32] = {0}; /* find iteration count */ if (argc > 1) { count = strtol(argv[1], NULL, 0); } /* find random seed */ if (argc > 2) { int pos = 0; const char* ch = argv[2]; while (pos < 16 && ch[0] != 0 && ch[1] != 0) { unsigned short sh; if (sscanf(ch, "%2hx", &sh)) { seed16[pos] = sh; } else { break; } ch += 2; pos++; } } else { FILE *frand = fopen("/dev/urandom", "r"); if ((frand == NULL) || !fread(&seed16, sizeof(seed16), 1, frand)) { uint64_t t = time(NULL) * (uint64_t)1337; seed16[0] ^= t; seed16[1] ^= t >> 8; seed16[2] ^= t >> 16; seed16[3] ^= t >> 24; seed16[4] ^= t >> 32; seed16[5] ^= t >> 40; seed16[6] ^= t >> 48; seed16[7] ^= t >> 56; } fclose(frand); } secp256k1_rand_seed(seed16); printf("test count = %i\n", count); printf("random seed = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", seed16[0], seed16[1], seed16[2], seed16[3], seed16[4], seed16[5], seed16[6], seed16[7], seed16[8], seed16[9], seed16[10], seed16[11], seed16[12], seed16[13], seed16[14], seed16[15]); /* initialize */ run_context_tests(); ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if (secp256k1_rand_bits(1)) { secp256k1_rand256(run32); CHECK(secp256k1_context_randomize(ctx, secp256k1_rand_bits(1) ? run32 : NULL)); } run_rand_bits(); run_rand_int(); run_sha256_tests(); run_hmac_sha256_tests(); run_rfc6979_hmac_sha256_tests(); #ifndef USE_NUM_NONE /* num tests */ run_num_smalltests(); #endif /* scalar tests */ run_scalar_tests(); /* field tests */ run_field_inv(); run_field_inv_var(); run_field_inv_all_var(); run_field_misc(); run_field_convert(); run_sqr(); run_sqrt(); /* group tests */ run_ge(); run_group_decompress(); /* ecmult tests */ run_wnaf(); run_point_times_order(); run_ecmult_chain(); run_ecmult_constants(); run_ecmult_gen_blind(); run_ecmult_const_tests(); run_ec_combine(); /* endomorphism tests */ #ifdef USE_ENDOMORPHISM run_endomorphism_tests(); #endif /* EC point parser test */ run_ec_pubkey_parse_test(); /* EC key edge cases */ run_eckey_edge_case_test(); #ifdef ENABLE_MODULE_ECDH /* ecdh tests */ run_ecdh_tests(); #endif /* ecdsa tests */ run_random_pubkeys(); run_ecdsa_der_parse(); run_ecdsa_sign_verify(); run_ecdsa_end_to_end(); run_ecdsa_edge_cases(); #ifdef ENABLE_OPENSSL_TESTS run_ecdsa_openssl(); #endif #ifdef ENABLE_MODULE_RECOVERY /* ECDSA pubkey recovery tests */ run_recovery_tests(); #endif secp256k1_rand256(run32); printf("random run = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", run32[0], run32[1], run32[2], run32[3], run32[4], run32[5], run32[6], run32[7], run32[8], run32[9], run32[10], run32[11], run32[12], run32[13], run32[14], run32[15]); /* shutdown */ secp256k1_context_destroy(ctx); printf("no problems found\n"); return 0; }
326844.c
#include <stdio.h> #include <assert.h> static inline int min(int a, int b) { return (a < b) ? a : b; } /* from current position to the end, we can caculate an hIndex array the hIndex will first ascend and then descend so the problem is to find the peak of the hIndex array we use binary search */ int hIndex(int* citations, int citationsSize) { if (citations == NULL || citationsSize == 0) return 0; if (citationsSize == 1) return min(citations[0], 1); int i = 0, j = citationsSize - 1; int h_prev, h_middle, h_next; while (i <= j) { int m = i + (j - i) / 2; h_prev = min(citations[m - 1], citationsSize - m + 1); h_middle = min(citations[m], citationsSize - m); h_next = min(citations[m + 1], citationsSize - m - 1); if (h_prev <= h_middle && h_middle > h_next) { break; } else if (h_middle <= h_next) { i = m + 1; } else if (h_middle > h_next) { j = m - 1; } else { i++; } } return h_middle; } int hIndex0(int* citations, int citationsSize) { if (citations == NULL || citationsSize == 0) return 0; int i = 0, j = citationsSize - 1; while (i <= j) { int m = i + (j - i) / 2; if (citations[m] >= citationsSize - m) { j = m - 1; } else { i = m + 1; } } return citationsSize - i; } int main() { int citations0[] = { 0, 1, 3, 5, 6 }; int citations1[] = { 0, 3, 3, 3, 4 }; int citations2[] = { 0, 3, 4, 4, 4, 4, 5, 5 }; assert(hIndex(citations0, sizeof(citations0) / sizeof(citations0[0])) == 3); assert(hIndex(citations1, sizeof(citations1) / sizeof(citations1[0])) == 3); assert(hIndex(citations2, sizeof(citations2) / sizeof(citations2[0])) == 4); printf("all tests passed!\n"); return 0; }
913375.c
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ #include "xsi.h" struct XSI_INFO xsi_info; int main(int argc, char **argv) { xsi_init_design(argc, argv); xsi_register_info(&xsi_info); xsi_register_min_prec_unit(-12); work_m_00000000003459270306_1208434039_init(); work_m_00000000003685903764_0542327438_init(); work_m_00000000000785409983_4113472356_init(); work_m_00000000000908013118_1976196353_init(); work_m_00000000004049972704_0922015392_init(); work_m_00000000002506138062_2100349821_init(); work_m_00000000004095159294_2049887419_init(); work_m_00000000000735187721_3296819782_init(); work_m_00000000004134447467_2073120511_init(); xsi_register_tops("work_m_00000000000735187721_3296819782"); xsi_register_tops("work_m_00000000004134447467_2073120511"); return xsi_run_simulation(argc, argv); }
280073.c
/* * Generic IXP4xx beeper driver * * Copyright (C) 2005 Tower Technologies * * based on nslu2-io.c * Copyright (C) 2004 Karen Spearel * * Author: Alessandro Zummo <[email protected]> * Maintainers: http://www.nslu2-linux.org/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/module.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <mach/hardware.h> MODULE_AUTHOR("Alessandro Zummo <[email protected]>"); MODULE_DESCRIPTION("ixp4xx beeper driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:ixp4xx-beeper"); static DEFINE_SPINLOCK(beep_lock); static void ixp4xx_spkr_control(unsigned int pin, unsigned int count) { unsigned long flags; spin_lock_irqsave(&beep_lock, flags); if (count) { gpio_line_config(pin, IXP4XX_GPIO_OUT); gpio_line_set(pin, IXP4XX_GPIO_LOW); *IXP4XX_OSRT2 = (count & ~IXP4XX_OST_RELOAD_MASK) | IXP4XX_OST_ENABLE; } else { gpio_line_config(pin, IXP4XX_GPIO_IN); gpio_line_set(pin, IXP4XX_GPIO_HIGH); *IXP4XX_OSRT2 = 0; } spin_unlock_irqrestore(&beep_lock, flags); } static int ixp4xx_spkr_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { unsigned int pin = (unsigned int) input_get_drvdata(dev); unsigned int count = 0; if (type != EV_SND) return -1; switch (code) { case SND_BELL: if (value) value = 1000; case SND_TONE: break; default: return -1; } if (value > 20 && value < 32767) count = (IXP4XX_TIMER_FREQ / (value * 4)) - 1; ixp4xx_spkr_control(pin, count); return 0; } static irqreturn_t ixp4xx_spkr_interrupt(int irq, void *dev_id) { /* clear interrupt */ *IXP4XX_OSST = IXP4XX_OSST_TIMER_2_PEND; /* flip the beeper output */ *IXP4XX_GPIO_GPOUTR ^= (1 << (unsigned int) dev_id); return IRQ_HANDLED; } static int __devinit ixp4xx_spkr_probe(struct platform_device *dev) { struct input_dev *input_dev; int err; input_dev = input_allocate_device(); if (!input_dev) return -ENOMEM; input_set_drvdata(input_dev, (void *) dev->id); input_dev->name = "ixp4xx beeper", input_dev->phys = "ixp4xx/gpio"; input_dev->id.bustype = BUS_HOST; input_dev->id.vendor = 0x001f; input_dev->id.product = 0x0001; input_dev->id.version = 0x0100; input_dev->dev.parent = &dev->dev; input_dev->evbit[0] = BIT_MASK(EV_SND); input_dev->sndbit[0] = BIT_MASK(SND_BELL) | BIT_MASK(SND_TONE); input_dev->event = ixp4xx_spkr_event; err = request_irq(IRQ_IXP4XX_TIMER2, &ixp4xx_spkr_interrupt, IRQF_DISABLED | IRQF_NO_SUSPEND, "ixp4xx-beeper", (void *) dev->id); if (err) goto err_free_device; err = input_register_device(input_dev); if (err) goto err_free_irq; platform_set_drvdata(dev, input_dev); return 0; err_free_irq: free_irq(IRQ_IXP4XX_TIMER2, dev); err_free_device: input_free_device(input_dev); return err; } static int __devexit ixp4xx_spkr_remove(struct platform_device *dev) { struct input_dev *input_dev = platform_get_drvdata(dev); unsigned int pin = (unsigned int) input_get_drvdata(input_dev); input_unregister_device(input_dev); platform_set_drvdata(dev, NULL); /* turn the speaker off */ disable_irq(IRQ_IXP4XX_TIMER2); ixp4xx_spkr_control(pin, 0); free_irq(IRQ_IXP4XX_TIMER2, dev); return 0; } static void ixp4xx_spkr_shutdown(struct platform_device *dev) { struct input_dev *input_dev = platform_get_drvdata(dev); unsigned int pin = (unsigned int) input_get_drvdata(input_dev); /* turn off the speaker */ disable_irq(IRQ_IXP4XX_TIMER2); ixp4xx_spkr_control(pin, 0); } static struct platform_driver ixp4xx_spkr_platform_driver = { .driver = { .name = "ixp4xx-beeper", .owner = THIS_MODULE, }, .probe = ixp4xx_spkr_probe, .remove = __devexit_p(ixp4xx_spkr_remove), .shutdown = ixp4xx_spkr_shutdown, }; static int __init ixp4xx_spkr_init(void) { return platform_driver_register(&ixp4xx_spkr_platform_driver); } static void __exit ixp4xx_spkr_exit(void) { platform_driver_unregister(&ixp4xx_spkr_platform_driver); } module_init(ixp4xx_spkr_init); module_exit(ixp4xx_spkr_exit);
626019.c
/* $NetBSD: panic.c,v 1.2 2002/05/15 04:07:43 lukem Exp $ */ #include <machine/stdarg.h> #include <stand.h> #include "libsa.h" __dead void panic(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); putchar('\n'); va_end(ap); breakpoint(); exit(); }
129712.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "win32/apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include <string.h> #include "apr_arch_inherit.h" APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else HANDLE hproc = GetCurrentProcess(); HANDLE newhand = NULL; if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } (*new_file) = (apr_file_t *) apr_pcalloc(p, sizeof(apr_file_t)); (*new_file)->filehand = newhand; (*new_file)->flags = old_file->flags & ~APR_INHERIT; (*new_file)->pool = p; (*new_file)->fname = apr_pstrdup(p, old_file->fname); (*new_file)->append = old_file->append; (*new_file)->buffered = FALSE; (*new_file)->ungetchar = old_file->ungetchar; #if APR_HAS_THREADS if (old_file->mutex) { apr_thread_mutex_create(&((*new_file)->mutex), APR_THREAD_MUTEX_DEFAULT, p); } #endif apr_pool_cleanup_register((*new_file)->pool, (void *)(*new_file), file_cleanup, apr_pool_cleanup_null); /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new_file)->pollset, 1, p, 0); return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ } #define stdin_handle 0x01 #define stdout_handle 0x02 #define stderr_handle 0x04 APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, apr_file_t *old_file, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else DWORD stdhandle = 0; HANDLE hproc = GetCurrentProcess(); HANDLE newhand = NULL; apr_int32_t newflags; /* dup2 is not supported literaly with native Windows handles. * We can, however, emulate dup2 for the standard i/o handles, * and close and replace other handles with duped handles. * The os_handle will change, however. */ if (new_file->filehand == GetStdHandle(STD_ERROR_HANDLE)) { stdhandle |= stderr_handle; } if (new_file->filehand == GetStdHandle(STD_OUTPUT_HANDLE)) { stdhandle |= stdout_handle; } if (new_file->filehand == GetStdHandle(STD_INPUT_HANDLE)) { stdhandle |= stdin_handle; } if (stdhandle) { if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, TRUE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } if (((stdhandle & stderr_handle) && !SetStdHandle(STD_ERROR_HANDLE, newhand)) || ((stdhandle & stdout_handle) && !SetStdHandle(STD_OUTPUT_HANDLE, newhand)) || ((stdhandle & stdin_handle) && !SetStdHandle(STD_INPUT_HANDLE, newhand))) { return apr_get_os_error(); } newflags = old_file->flags | APR_INHERIT; } else { if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } newflags = old_file->flags & ~APR_INHERIT; } if (new_file->filehand && (new_file->filehand != INVALID_HANDLE_VALUE)) { CloseHandle(new_file->filehand); } new_file->flags = newflags; new_file->filehand = newhand; new_file->fname = apr_pstrdup(new_file->pool, old_file->fname); new_file->append = old_file->append; new_file->buffered = FALSE; new_file->ungetchar = old_file->ungetchar; #if APR_HAS_THREADS if (old_file->mutex) { apr_thread_mutex_create(&(new_file->mutex), APR_THREAD_MUTEX_DEFAULT, p); } #endif return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ } APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { *new_file = (apr_file_t *)apr_palloc(p, sizeof(apr_file_t)); memcpy(*new_file, old_file, sizeof(apr_file_t)); (*new_file)->pool = p; if (old_file->buffered) { (*new_file)->buffer = apr_palloc(p, APR_FILE_BUFSIZE); if (old_file->direction == 1) { memcpy((*new_file)->buffer, old_file->buffer, old_file->bufpos); } else { memcpy((*new_file)->buffer, old_file->buffer, old_file->dataRead); } } if (old_file->mutex) { apr_thread_mutex_create(&((*new_file)->mutex), APR_THREAD_MUTEX_DEFAULT, p); apr_thread_mutex_destroy(old_file->mutex); } if (old_file->fname) { (*new_file)->fname = apr_pstrdup(p, old_file->fname); } if (!(old_file->flags & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register(p, (void *)(*new_file), file_cleanup, file_cleanup); } old_file->filehand = INVALID_HANDLE_VALUE; apr_pool_cleanup_kill(old_file->pool, (void *)old_file, file_cleanup); /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new_file)->pollset, 1, p, 0); return APR_SUCCESS; }
487485.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fscanf_63b.c Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc.label.xml Template File: sources-sink-63b.tmpl.c */ /* * @description * CWE: 680 Integer Overflow to Buffer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink * Sinks: * BadSink : Attempt to allocate array using length value from source * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fscanf_63b_badSink(int * dataPtr) { int data = *dataPtr; { size_t i; int *intPointer; /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value * so that the for loop doing the initialization causes a buffer overflow */ intPointer = (int*)malloc(data * sizeof(int)); for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ } printIntLine(intPointer[0]); free(intPointer); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fscanf_63b_goodG2BSink(int * dataPtr) { int data = *dataPtr; { size_t i; int *intPointer; /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value * so that the for loop doing the initialization causes a buffer overflow */ intPointer = (int*)malloc(data * sizeof(int)); for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ } printIntLine(intPointer[0]); free(intPointer); } } #endif /* OMITGOOD */
369540.c
/*************************************************************************** * * Copyright (C) 2007 - 2012, Rogvall Invest AB, <[email protected]> * * This software is licensed as described in the file COPYRIGHT, which * you should have received as part of this distribution. The terms * are also available at http://www.rogvall.se/docs/copyright.txt. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYRIGHT file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ // // EPX pixmap functions // // #include <stdlib.h> #include <memory.h> #include <math.h> #include "epx_simd_int.h" #include "../include/epx_pixmap.h" #include "../include/epx_colors.h" #include "../include/epx_simd.h" #include "../include/epx_backend.h" #define EPX_INLINE_COPY_SIZE 32 #define EPX_INLINE_FILL_SIZE 16 int epx_clip_both(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_rect_t* srp, epx_rect_t* drp); int epx_clip_dst(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_rect_t* srp, epx_rect_t* drp); // epx_copy - copy memory regions // this code must be fixed to handle overlap and implement memmove // semantics. This includes checking if src and dst point is to close // memory wise to use SIMD (|src-dst| < 16) // static inline void epx_copy(uint8_t* src, uint8_t* dst, size_t n) { memmove(dst, src, n); /* if (n < EPX_INLINE_COPY_SIZE) { while(n--) *dst++ = *src++; } else { SIMD_CALL(copy)(src,dst,n); } */ } static inline void epx_fill_32(uint8_t* ptr, uint8_t x0,uint8_t x1,uint8_t x2,uint8_t x3, size_t n) { uint32_t v; uint8_t* vp = (uint8_t*) &v; vp[0]=x0; vp[1]=x1; vp[2]=x2; vp[3]=x3; if (!SIMD_ENABLED() || (n < EPX_INLINE_FILL_SIZE)) { if (((((unsigned long)ptr) & 0x3) == 0) && (n > 3)) { uint32_t* ptr32 = (uint32_t*) ptr; while(n--) *ptr32++ = v; } else { while(n--) { *ptr++ = x0; *ptr++ = x1; *ptr++ = x2; *ptr++ = x3; } } } else { SIMD_CALL(fill_32)(ptr, v, n); } } static void epx_fill_24(uint8_t* ptr, uint8_t x0,uint8_t x1,uint8_t x2, size_t n) { if (((((unsigned long)ptr) & 0x3) == 0) && (n >= 4)) { uint32_t* ptr32 = (u_int32_t*) ptr; uint32_t v0, v1, v2; uint8_t* vp; vp = (uint8_t*) &v0; vp[0]=x0; vp[1]=x1; vp[2]=x2; vp[3]=x0; vp = (uint8_t*) &v1; vp[0]=x1; vp[1]=x2; vp[2]=x0; vp[3]=x1; vp = (uint8_t*) &v2; vp[0]=x2; vp[1]=x0; vp[2]=x1; vp[3]=x2; while(n >= 4) { *ptr32++ = v0; *ptr32++ = v1; *ptr32++ = v2; n -= 4; } ptr = (uint8_t*) ptr32; } if (n) { while(n--) { *ptr++ = x0; *ptr++ = x1; *ptr++ = x2; } } } static void epx_fill_16(uint8_t* ptr, uint8_t x0, uint8_t x1, size_t n) { if (n >= 2) { /* FIXME better treshold value */ size_t n32 = n / 2; epx_fill_32(ptr, x0, x1, x0, x1, n32); ptr += n32*2; n %= 2; } if (n) { if ((((unsigned long) ptr) & 0x1) == 0) { uint16_t v; uint8_t* vp = (uint8_t*) &v; uint16_t* ptr16 = (uint16_t*) ptr; vp[0]=x0; vp[1]=x1; while(n--) *ptr16++ = v; } else { while(n--) { *ptr++ = x0; *ptr++ = x1; } } } } static void epx_fill_8(uint8_t* ptr, uint8_t x0, size_t n) { if (n >= 4) { /* FIXME: better treshold value */ size_t n32 = n/4; epx_fill_32(ptr, x0, x0, x0, x0, n32); ptr += n32*4; n %= 4; } while(n--) *ptr++ = x0; } // swap_8 - may be used to swap two lines of data static void epx_swap_8(uint8_t* ptr1, uint8_t* ptr2, size_t n) { while(n--) { uint8_t t = *ptr1; *ptr1++ = *ptr2; *ptr2++ = t; } } // not yet #if 0 static void epx_move_area(uint8_t* src, int src_dx, int src_dy, epx_format_t src_pt, uint8_t* dst, int dst_dx, int dst_dy, epx_format_t dst_pt, int width, int height) { epx_pixel_unpack_t unpack_src = epx_pixel_unpack_func(src_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned width1 = width; while(width1--) { epx_pixel_t p = unpack_src(src1); pack_dst(p, dst1); src1 += src_dx; dst1 += dst_dx; } src += src_dy; dst += dst_dy; } } #endif // copy pixel area void epx_copy_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, unsigned int width, unsigned int height) { if ((dst < src) || (height <= 1)) { if (src_pt == dst_pt) { unsigned int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); unsigned int n = src_psz*width; while(height--) { epx_copy(src, dst, n); src += src_wb; dst += dst_wb; } } else { int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); epx_pixel_unpack_t unpack_src = epx_pixel_unpack_func(src_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned width1 = width; while(width1--) { epx_pixel_t p = unpack_src(src1); pack_dst(p, dst1); src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } } else { src += (src_wb*height); dst += (dst_wb*height); if (src_pt == dst_pt) { unsigned int n = EPX_PIXEL_BYTE_SIZE(src_pt)*width; while(height--) { src -= src_wb; dst -= dst_wb; epx_copy(src, dst, n); } } else { int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); epx_pixel_unpack_t unpack_src = epx_pixel_unpack_func(src_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* src1 = src-src_wb; uint8_t* dst1 = dst-dst_wb; unsigned int width1 = width; src = src1; dst = dst1; while(width1--) { epx_pixel_t p = unpack_src(src1); pack_dst(p, dst1); src1 += src_psz; dst1 += dst_psz; } } } } } /* fill pixel area (FIXME acceleration) */ void epx_fill_area(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t fill, unsigned int width, unsigned int height) { unsigned int psz = EPX_PIXEL_BYTE_SIZE(dst_pt); uint32_t cv = 0; uint8_t* cvp = (uint8_t*) &cv; epx_pixel_pack_t pack = epx_pixel_pack_func(dst_pt); pack(fill, cvp); switch(psz) { case 1: while(height--) { epx_fill_8(dst, cvp[0], width); dst += dst_wb; } break; case 2: while(height--) { epx_fill_16(dst, cvp[0], cvp[1], width); dst += dst_wb; } break; case 3: while(height--) { epx_fill_24(dst, cvp[0], cvp[1], cvp[2], width); dst += dst_wb; } break; case 4: while(height--) { epx_fill_32(dst, cvp[0], cvp[1], cvp[2], cvp[3], width); dst += dst_wb; } break; default: break; } } // // blend dst with ARGB/ABGR color (dst alpha is untouched) // caller MUST swap B/R for ABGR format // static void fill_area_blend_generic(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { int psz; epx_pixel_unpack_t unpack_dst; epx_pixel_pack_t pack_dst; psz = EPX_PIXEL_BYTE_SIZE(dst_pt); unpack_dst = epx_pixel_unpack_func(dst_pt); pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* dst1 = dst; int width1 = width; while(width1--) { epx_pixel_t d = unpack_dst(dst1); d = epx_pixel_blend(p.a, p, d); pack_dst(d, dst1); dst1 += psz; } dst += dst_wb; } } static void fill_area_blend_rgb24(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_rgb24)(dst, dst_wb, p, width, height); } static void fill_area_blend_bgr24(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_rgb24)(dst, dst_wb, epx_pixel_swap(p), width, height); } static void fill_area_blend_argb32(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_argb32)(dst, dst_wb, p, width, height); } static void fill_area_blend_abgr32(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_argb32)(dst, dst_wb,epx_pixel_swap(p), width,height); } static void fill_area_blend_rgba32(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_rgba32)(dst, dst_wb, p, width, height); } static void fill_area_blend_bgra32(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { if (!SIMD_ENABLED()) fill_area_blend_generic(dst, dst_wb, dst_pt, p, width, height); else SIMD_CALL(fill_area_blend_rgba32)(dst, dst_wb, epx_pixel_swap(p), width, height); } // fill pixel row with blending void epx_fill_area_blend(uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_t p, unsigned int width, unsigned int height) { switch(dst_pt) { case EPX_FORMAT_R8G8B8: fill_area_blend_rgb24(dst,dst_wb,dst_pt,p,width,height); break; case EPX_FORMAT_B8G8R8: fill_area_blend_bgr24(dst,dst_wb,dst_pt,p,width,height); break; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_B8G8R8X8_LE: fill_area_blend_argb32(dst,dst_wb,dst_pt,p,width,height); break; case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_R8G8B8A8_LE: case EPX_FORMAT_R8G8B8X8_LE: fill_area_blend_abgr32(dst,dst_wb,dst_pt,p,width,height); break; case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_X8B8G8R8_LE: fill_area_blend_rgba32(dst,dst_wb,dst_pt,p,width,height); break; case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_A8R8G8B8_LE: case EPX_FORMAT_X8R8G8B8_LE: fill_area_blend_bgra32(dst,dst_wb,dst_pt,p,width,height); break; default: goto generic; } return; generic: fill_area_blend_generic(dst,dst_wb,dst_pt,p,width,height); } /*! Experimental */ void epx_shade_area(uint8_t* dst, int dst_wb, epx_format_t dst_pt, unsigned int width, unsigned int height, epx_pixel_t Px0, epx_pixel_t Px1, epx_pixel_t Py0, epx_pixel_t Py1) { int psz = EPX_PIXEL_BYTE_SIZE(dst_pt); int height1 = height; int y = 0; epx_pixel_unpack_t unpack_dst = epx_pixel_unpack_func(dst_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); while(height1--) { uint8_t* dst1 = dst; unsigned int width1 = width; int x = 0; while(width1--) { epx_pixel_t d = unpack_dst(dst1); epx_pixel_t c0; epx_pixel_t c1; epx_pixel_t c2; c0 = epx_pixel_blend((x*255)/width, Px0, Px1); c1 = epx_pixel_blend((y*255)/height, Py0, Py1); c2 = epx_pixel_add(c0,c1); d = epx_pixel_blend(c2.a, c2, d); pack_dst(d, dst1); dst1 += psz; x++; } dst += dst_wb; y++; } } // FUNCTION: epx_blend_AREA ( ... ) #define AREA_FUNCTION epx_blend_AREA #define AREA_PARAMS_DECL #define AREA_OPERATION(s,d) epx_pixel_blend(s.a,s,d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUNCTION static void blend_area_generic(uint8_t* src,int src_wb,epx_format_t src_pt, uint8_t* dst,int dst_wb,epx_format_t dst_pt, unsigned int width, unsigned int height) { if (src_pt == dst_pt) { switch(src_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_A8R8G8B8_LE: while(height--) { epx_blend_row_rgba32(src, dst, width); src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8A8_LE: while(height--) { epx_blend_row_argb32(src, dst, width); src += src_wb; dst += dst_wb; } return; default: break; } } epx_blend_AREA(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); } static void blend_area_rgba32(uint8_t* src,int src_wb,epx_format_t src_pt, uint8_t* dst,int dst_wb,epx_format_t dst_pt, unsigned int width, unsigned int height) { if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) blend_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); else SIMD_CALL(blend_area_rgba32)(src,src_wb,dst,dst_wb,width,height); } static void blend_area_argb32(uint8_t* src,int src_wb,epx_format_t src_pt, uint8_t* dst,int dst_wb,epx_format_t dst_pt, unsigned int width, unsigned int height) { if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) blend_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); else SIMD_CALL(blend_area_argb32)(src,src_wb,dst,dst_wb,width,height); } void epx_blend_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, unsigned int width, unsigned int height) { if (!EPX_PIXEL_HAS_ALPHA(src_pt)) { epx_copy_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); return; } switch(src_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_A8R8G8B8_LE: blend_area_rgba32(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); break; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8A8_LE: blend_area_argb32(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); break; default: blend_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); break; } } // FUNCTION: epx_sum_area ( ... ) #define AREA_FUNCTION epx_sum_area #define AREA_PARAMS_DECL #define AREA_OPERATION(s,d) epx_pixel_add(s, d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUCNTION static inline epx_pixel_t alpha_pixel(uint8_t a, epx_pixel_t s, epx_pixel_t d) { d.r = epx_blend(a,s.r,d.r); d.g = epx_blend(a,s.g,d.g); d.b = epx_blend(a,s.b,d.b); return d; } // FUNCTION: epx_alpha_AREA ( ... ) #define AREA_FUNCTION epx_alpha_AREA #define AREA_PARAMS_DECL uint8_t alpha, #define AREA_OPERATION(s,d) alpha_pixel(alpha, s, d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUCNTION static void alpha_area_generic(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t alpha, unsigned int width, unsigned int height) { if (src_pt == dst_pt) { switch(src_pt) { case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_X8R8G8B8_LE: case EPX_FORMAT_A8R8G8B8_LE: case EPX_FORMAT_X8B8G8R8_LE: case EPX_FORMAT_A8B8G8R8_LE: while(height--) { epx_alpha_row_rgba32(src,dst,alpha,width); src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8X8_LE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8X8_LE: case EPX_FORMAT_R8G8B8A8_LE: while(height--) { epx_alpha_row_argb32(src,dst,alpha,width); src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_R8G8B8: case EPX_FORMAT_B8G8R8: while(height--) { epx_alpha_row_rgb24(src,dst,alpha,width); src += src_wb; dst += dst_wb; } return; default: break; } } epx_alpha_AREA(src,src_wb,src_pt,dst,dst_wb,dst_pt,alpha,width,height); } static void alpha_area_rgba32(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t a,unsigned int width, unsigned int height) { if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) alpha_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,a,width,height); else SIMD_CALL(alpha_area_rgba32)(src,src_wb,dst,dst_wb,a,width,height); } static void alpha_area_argb32(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t a,unsigned int width, unsigned int height) { if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) alpha_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,a,width,height); else SIMD_CALL(alpha_area_argb32)(src,src_wb,dst,dst_wb,a,width,height); } void epx_alpha_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t a, unsigned int width, unsigned int height) { switch(src_pt) { case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_X8R8G8B8_LE: case EPX_FORMAT_A8R8G8B8_LE: case EPX_FORMAT_X8B8G8R8_LE: case EPX_FORMAT_A8B8G8R8_LE: alpha_area_rgba32(src,src_wb,src_pt,dst,dst_wb,dst_pt,a,width,height); break; case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8X8_LE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8X8_LE: case EPX_FORMAT_R8G8B8A8_LE: alpha_area_argb32(src,src_wb,src_pt,dst,dst_wb,dst_pt,a,width,height); break; default: alpha_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,a,width,height); } } static inline epx_pixel_t fade_pixel(uint8_t fade, epx_pixel_t s, epx_pixel_t d) { uint8_t a = (s.a)*fade >> 8; d.r = epx_blend(a,s.r,d.r); d.g = epx_blend(a,s.g,d.g); d.b = epx_blend(a,s.b,d.b); d.a = epx_blend(a,s.a,d.a); return d; } // FUNCTION: epx_fade_AREA ( ... ) #define AREA_FUNCTION epx_fade_AREA #define AREA_PARAMS_DECL uint8_t fade, #define AREA_OPERATION(s,d) fade_pixel(fade, s, d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUCNTION static void fade_area_generic(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t fade, unsigned int width, unsigned int height) { if (fade == ALPHA_FACTOR_0) return; if (fade == ALPHA_FACTOR_1) { epx_blend_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); return; } if (src_pt == dst_pt) { switch(src_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_A8R8G8B8_LE: while(height--) { epx_fade_row_rgba32(src, dst, fade, width); src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8A8_LE: while(height--) { epx_fade_row_argb32(src, dst, fade, width); src += src_wb; dst += dst_wb; } return; default: break; } } else if (src_pt == EPX_FORMAT_A8) { // source r=g=b=0 switch(dst_pt) { case EPX_FORMAT_B8G8R8: case EPX_FORMAT_R8G8B8: while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned int width1 = width; while(width1--) { uint8_t a = (*src1*fade >> 8); dst1[0]=epx_blend(a,0,dst1[0]); dst1[1]=epx_blend(a,0,dst1[1]); dst1[2]=epx_blend(a,0,dst1[2]); src1++; dst1 += 3; } src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8A8_LE: while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned int width1 = width; // FIXME: use epx_add_blend_row_a8_argb32 (with color=0!) while(width1--) { uint8_t a = ((*src1)*fade >> 8); dst1[0]=epx_blend(a,src1[0],dst1[0]); // NEW dst1[1]=epx_blend(a,0,dst1[1]); dst1[2]=epx_blend(a,0,dst1[2]); dst1[3]=epx_blend(a,0,dst1[3]); src1++; dst1 += 4; } src += src_wb; dst += dst_wb; } return; case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_A8R8G8B8_LE: while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned int width1 = width; while(width1--) { uint8_t a = ((*src1)*fade >> 8); dst1[0]=epx_blend(a,0,dst1[0]); dst1[1]=epx_blend(a,0,dst1[1]); dst1[2]=epx_blend(a,0,dst1[2]); dst1[3]=epx_blend(a,src1[0],dst1[3]); src1++; dst1 += 4; } src += src_wb; dst += dst_wb; } return; default: { unsigned int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); epx_pixel_unpack_t unpack_dst = epx_pixel_unpack_func(dst_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned int width1 = width; while(width1--) { epx_pixel_t d = unpack_dst(dst1); uint8_t a = (*src1*fade >> 8); d.r = epx_blend(a,0,d.r); d.g = epx_blend(a,0,d.g); d.b = epx_blend(a,0,d.b); d.a = epx_blend(a,src1[0],d.a); pack_dst(d, dst1); src1++; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } return; } } } epx_fade_AREA(src, src_wb, src_pt, dst, dst_wb, dst_pt, fade, width, height); } static void fade_area_rgba32(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t fade, unsigned int width, unsigned int height) { if (fade == ALPHA_FACTOR_0) return; if (fade == ALPHA_FACTOR_1) { epx_blend_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); return; } if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) fade_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade, width,height); else SIMD_CALL(fade_area_rgba32)(src,src_wb,dst,dst_wb,fade,width,height); } static void fade_area_argb32(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t fade, unsigned int width, unsigned int height) { if (fade == ALPHA_FACTOR_0) return; if (fade == ALPHA_FACTOR_1) { epx_blend_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); return; } if (!SIMD_ENABLED() || (src_pt != dst_pt) || (width < 8)) fade_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade, width,height); else SIMD_CALL(fade_area_argb32)(src,src_wb,dst,dst_wb,fade,width,height); } void epx_fade_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t fade, unsigned int width, unsigned int height) { switch(src_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_A8R8G8B8_LE: fade_area_rgba32(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade,width,height); break; case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_X8B8G8R8_LE: case EPX_FORMAT_X8R8G8B8_LE: alpha_area_rgba32(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade, width,height); break; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_R8G8B8A8_LE: fade_area_argb32(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade,width,height); break; case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_B8G8R8X8_LE: case EPX_FORMAT_R8G8B8X8_LE: alpha_area_argb32(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade, width,height); break; default: fade_area_generic(src,src_wb,src_pt,dst,dst_wb,dst_pt,fade, width,height); break; } } void epx_shadow_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, unsigned int width, unsigned int height, epx_flags_t flags) { unsigned int src_psz; unsigned int dst_psz; epx_pixel_unpack_t unpack_dst; epx_pixel_unpack_t unpack_src; epx_pixel_pack_t pack_dst; src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); unpack_src = epx_pixel_unpack_func(src_pt); unpack_dst = epx_pixel_unpack_func(dst_pt); pack_dst = epx_pixel_pack_func(dst_pt); if (!(flags & EPX_FLAG_BLEND)) { while(height--) { uint8_t* dst1 = dst; uint8_t* src1 = src; unsigned int width1 = width; while(width1--) { epx_pixel_t s = unpack_src(src1); epx_pixel_t d = unpack_dst(dst1); uint8_t g = epx_pixel_luminance(s); d = epx_pixel_shadow(g, d); pack_dst(d, dst1); src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } else { while(height--) { uint8_t* dst1 = dst; uint8_t* src1 = src; unsigned int width1 = width; while(width1--) { epx_pixel_t s = unpack_src(src1); uint8_t g; if (s.a == EPX_ALPHA_OPAQUE) { epx_pixel_t d = unpack_dst(dst1); g = epx_pixel_luminance(s); d = epx_pixel_shadow(g, d); pack_dst(d, dst1); } else if (s.a == EPX_ALPHA_TRANSPARENT) { ; } else { epx_pixel_t d = unpack_dst(dst1); d = epx_pixel_blend(s.a, s, d); g = epx_pixel_luminance(d); d = epx_pixel_shadow(g, d); pack_dst(d, dst1); } src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } } /* * Add color (saturate) to each pixel in src and interpret * the alpha channel in color as fader value (i.e multiplier) * */ void epx_add_color_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, uint8_t fader, epx_pixel_t color, unsigned int width, unsigned int height, epx_flags_t flags) { unsigned int src_psz; unsigned int dst_psz; epx_pixel_unpack_t unpack_src; epx_pixel_unpack_t unpack_dst; epx_pixel_pack_t pack_dst; if ((fader == ALPHA_FACTOR_0) && (color.px == 0)) return; if ((fader == ALPHA_FACTOR_1) && (color.px == 0) && (src_pt != EPX_FORMAT_A8)) { // FIXME!!! if (flags&EPX_FLAG_BLEND) epx_blend_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); else epx_copy_area(src,src_wb,src_pt,dst,dst_wb,dst_pt,width,height); return; } if ((flags&EPX_FLAG_BLEND) == 0) // only blend sofar goto generic_area; if (!SIMD_ENABLED()) goto generic_area; if ((dst_pt == src_pt) && (width>=8)) { switch(src_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_X8B8G8R8_LE: SIMD_CALL(add_blend_area_rgba32)(src,src_wb,dst,dst_wb,fader, color,width,height); return; case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_A8R8G8B8_LE: case EPX_FORMAT_X8R8G8B8_LE: SIMD_CALL(add_blend_area_rgba32)(src,src_wb,dst,dst_wb,fader, epx_pixel_swap(color), width,height); return; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_B8G8R8X8_LE: SIMD_CALL(add_blend_area_argb32)(src,src_wb,dst,dst_wb,fader, color,width,height); return; case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_R8G8B8A8_LE: case EPX_FORMAT_R8G8B8X8_LE: SIMD_CALL(add_blend_area_argb32)(src,src_wb,dst,dst_wb,fader, epx_pixel_swap(color), width,height); return; default: goto generic_area; } } else if (src_pt == EPX_FORMAT_A8) { switch(dst_pt) { case EPX_FORMAT_R8G8B8A8_BE: case EPX_FORMAT_R8G8B8X8_BE: case EPX_FORMAT_A8B8G8R8_LE: case EPX_FORMAT_X8B8G8R8_LE: SIMD_CALL(add_blend_area_a8_rgba32)(src,src_wb,dst,dst_wb,fader, color,width,height); return; case EPX_FORMAT_B8G8R8A8_BE: case EPX_FORMAT_B8G8R8X8_BE: case EPX_FORMAT_A8R8G8B8_LE: case EPX_FORMAT_X8R8G8B8_LE: SIMD_CALL(add_blend_area_a8_rgba32)(src,src_wb,dst,dst_wb,fader, epx_pixel_swap(color), width,height); return; case EPX_FORMAT_A8R8G8B8_BE: case EPX_FORMAT_X8R8G8B8_BE: case EPX_FORMAT_B8G8R8A8_LE: case EPX_FORMAT_B8G8R8X8_LE: SIMD_CALL(add_blend_area_a8_argb32)(src,src_wb,dst,dst_wb,fader, color,width,height); return; case EPX_FORMAT_A8B8G8R8_BE: case EPX_FORMAT_X8B8G8R8_BE: case EPX_FORMAT_R8G8B8A8_LE: case EPX_FORMAT_R8G8B8X8_LE: SIMD_CALL(add_blend_area_a8_argb32)(src,src_wb,dst,dst_wb,fader, epx_pixel_swap(color), width,height); return; default: goto generic_area; } } generic_area: unpack_src = epx_pixel_unpack_func(src_pt); unpack_dst = epx_pixel_unpack_func(dst_pt); pack_dst = epx_pixel_pack_func(dst_pt); src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); if ((flags&EPX_FLAG_BLEND) == 0) { while(height--) { uint8_t* dst1 = dst; uint8_t* src1 = src; unsigned int width1 = width; while(width1--) { epx_pixel_t s = unpack_src(src1); s = epx_pixel_add(color,s); s.a = ((s.a * fader) >> 8); s = epx_pixel_shadow(s.a, s); pack_dst(s, dst1); src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } else { // add color with and blend // note! the slight difference in alpha handling while(height--) { uint8_t* dst1 = dst; uint8_t* src1 = src; unsigned int width1 = width; while(width1--) { epx_pixel_t d = unpack_dst(dst1); epx_pixel_t s = unpack_src(src1); uint8_t a; s = epx_pixel_add(color,s); a = ((s.a * fader) >> 8); d = epx_pixel_blend(a, s, d); pack_dst(d, dst1); src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } } #define EPX_AVG_MAX_N 128 /* special filter N_1 average N pixels */ static void filter_avg_N_1_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, unsigned int width, unsigned int height, int n, epx_flags_t flags) { int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); epx_pixel_unpack_t unpack_src = epx_pixel_unpack_func(src_pt); epx_pixel_unpack_t unpack_dst = epx_pixel_unpack_func(dst_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); int height1 = height; while(height1--) { uint8_t* src1 = src; uint8_t* dst1 = dst; uint32_t rs = 0; uint32_t gs = 0; uint32_t bs = 0; epx_pixel_t rgb[EPX_AVG_MAX_N]; int i = 0; unsigned int width1 = (n-1)/2; memset(rgb, 0, sizeof(rgb)); /* Do head part loading avg buffer */ while(width1--) { epx_pixel_t s = unpack_src(src1); rs = (rs + s.r) - rgb[i].r; gs = (gs + s.g) - rgb[i].g; bs = (bs + s.b) - rgb[i].b; rgb[i] = s; i = (i==n-1) ? 0 : (i + 1); src1 += src_psz; } /* Run middle part */ width1 = width - (n-1)/2; while(width1--) { epx_pixel_t s = unpack_src(src1); rs = (rs + s.r) - rgb[i].r; gs = (gs + s.g) - rgb[i].g; bs = (bs + s.b) - rgb[i].b; rgb[i] = s; i = (i==n-1) ? 0 : (i + 1); s.r = rs / n; s.g = gs / n; s.b = bs / n; if (flags & EPX_FLAG_BLEND) { epx_pixel_t d = unpack_dst(dst1); d = epx_pixel_blend(s.a, s, d); pack_dst(d, dst1); } else { pack_dst(s, dst1); } src1 += src_psz; dst1 += dst_psz; } /* Do tail part writing rest of dst */ width1 = n - ((n-1)/2); while(width1--) { epx_pixel_t s; rs = rs - rgb[i].r; gs = gs - rgb[i].g; bs = bs - rgb[i].b; i = (i==n-1) ? 0 : (i + 1); s.r = rs / n; s.g = gs / n; s.b = bs / n; if (flags & EPX_FLAG_BLEND) { epx_pixel_t d = unpack_dst(dst1); d = epx_pixel_blend(s.a, s, d); pack_dst(d, dst1); } else { pack_dst(s, dst1); } dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } // // FIXME: make it possible to have src = dst ! // FIXME: make this work ;-) // the factors should be? signed (fixpoint) // static void filter_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_filter_t* filter, unsigned int width, unsigned int height, epx_flags_t flags) { int n = filter->wh.width; if ((filter->wh.height == 1) && (n <= EPX_AVG_MAX_N) && (filter->fsum == (unsigned int) n)) { /* NOT Completly true ! */ filter_avg_N_1_area(src, src_wb, src_pt, dst, dst_wb, dst_pt, width, height, n, flags); } else { int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); epx_pixel_unpack_t unpack_src = epx_pixel_unpack_func(src_pt); epx_pixel_unpack_t unpack_dst = epx_pixel_unpack_func(dst_pt); epx_pixel_pack_t pack_dst = epx_pixel_pack_func(dst_pt); int height1 = height - (filter->wh.height-1); /* do special treat y=0..m2-1 and y=height-m2-1..height-1 */ /* do y=hh ... height-hh */ while(height1--) { uint8_t* src1 = src; uint8_t* dst1 = dst; unsigned int width1 = width - (filter->wh.width-1); src1 += (filter->wh.width >> 1)*src_psz; dst1 += (filter->wh.width >> 1)*dst_psz; /* do x=ww ... width-ww */ while(width1--) { int fh = filter->wh.height; epx_pixel_t d; epx_pixel_t s; uint8_t* src2 = src1; uint8_t* fptr = filter->factor; // uint32_t acc_a = 0; uint32_t acc_r = 0; uint32_t acc_g = 0; uint32_t acc_b = 0; while(fh--) { int fw = filter->wh.width; uint8_t* sptr = src2; // Should be able to use SIMD here! while(fw--) { uint8_t factor = *fptr++; epx_pixel_t t = unpack_src(sptr); // acc_a += factor*t.a; acc_r += factor*t.r; acc_g += factor*t.g; acc_b += factor*t.b; sptr += src_psz; } src2 += src_wb; // next source row } s.r = acc_r / filter->fsum; s.g = acc_g / filter->fsum; s.b = acc_b / filter->fsum; if (flags & EPX_FLAG_BLEND) { d = unpack_dst(dst1); d = epx_pixel_blend(s.a, s, d); pack_dst(d, dst1); } else { pack_dst(s, dst1); } src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } } /* interpolate a pixel (used for antialias and scaling etc) * blend the color at pixels in the surrounding of * float coordinate (x,y) */ inline epx_pixel_t epx_interp(epx_pixmap_t* pic, float x, float y) { // To get gcc 4.1.2 to shut up about implicit declaration // without having to resort to -std=99, which triggers a shitload // of compile errors. extern float truncf(float); extern float roundf(float); int y0 = truncf(y-0.5); int y1 = truncf(y+0.5); int x0 = truncf(x-0.5); int x1 = truncf(x+0.5); float not_used; float fy = modff(y-0.5, &not_used); float fx = modff(x-0.5, &not_used); float f0 = (1-fx)*(1-fy); float f1 = fx*(1-fy); float f2 = (1-fx)*fy; float f3 = fx*fy; epx_pixel_t p0,p1,p2,p3; uint8_t* ptr; epx_pixel_t p; if (epx_point_xy_in_rect(x0,y0, &pic->clip)) { ptr = EPX_PIXEL_ADDR(pic, x0, y0); p0 = pic->func.unpack(ptr); } else p0 = epx_pixel_transparent; if (epx_point_xy_in_rect(x1,y0, &pic->clip)) { ptr = EPX_PIXEL_ADDR(pic, x1, y0); p1 = pic->func.unpack(ptr); } else p1 = epx_pixel_transparent; if (epx_point_xy_in_rect(x0,y1, &pic->clip)) { ptr = EPX_PIXEL_ADDR(pic, x0, y1); p2 = pic->func.unpack(ptr); } else p2 = epx_pixel_transparent; if (epx_point_xy_in_rect(x1,y1, &pic->clip)) { ptr = EPX_PIXEL_ADDR(pic, x1, y1); p3 = pic->func.unpack(ptr); } else p3 = epx_pixel_transparent; // This could probably be done in ALTIVEC || SSE2 p.r = roundf(f0*p0.r + f1*p1.r + f2*p2.r + f3*p3.r); p.g = roundf(f0*p0.g + f1*p1.g + f2*p2.g + f3*p3.g); p.b = roundf(f0*p0.b + f1*p1.b + f2*p2.b + f3*p3.b); p.a = roundf(f0*p0.a + f1*p1.a + f2*p2.a + f3*p3.a); return p; } // Given source and destination rectangles, calculate the // source rectangle and the destination rectangles when both // source and destination are clipped // both rectangles will have the same dimension on return // return -1 if the destination rectangle is empty! int epx_clip_both(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_rect_t* srp, epx_rect_t* drp) { epx_rect_t r; // Set source rectangle and clip it epx_rect_set(srp, x_src, y_src, width, height); if (!epx_rect_intersect(srp, &src->clip, srp)) return -1; // empty // Set destination rectangle and clip it epx_rect_set(&r, x_dst, y_dst, srp->wh.width, srp->wh.height); if (!epx_rect_intersect(&r, &dst->clip, drp)) return -1; // empty // Adjust source rectangle according to destination srp->xy.x -= (r.xy.x - drp->xy.x); srp->xy.y -= (r.xy.y - drp->xy.y); srp->wh = drp->wh; return 0; } // Given source and destination rectangles, calculate the // destination rectangles when both destination are clipped // return -1 if the destination rectangle is empty! int epx_clip_dst(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_rect_t* srp, epx_rect_t* drp) { (void) src; epx_rect_t r; epx_rect_set(srp, x_src, y_src, width, height); // Set destination rectangle and clip it epx_rect_set(&r, x_dst, y_dst, width, height); if (!epx_rect_intersect(&r, &dst->clip, drp)) return -1; // empty // Adjust source rectangle according to destination srp->xy.x -= (r.xy.x - drp->xy.x); srp->xy.y -= (r.xy.y - drp->xy.y); srp->wh = drp->wh; return 0; } static void init_pixel_area_functions(epx_pixmap_functions_t* func, epx_format_t fmt) { switch(fmt) { case EPX_FORMAT_R8G8B8: // RGB func->fill_area_blend = fill_area_blend_rgb24; func->blend_area = epx_copy_area; // no alpha for blending func->alpha_area = alpha_area_generic; func->fade_area = alpha_area_generic; // src alpha = 1 break; case EPX_FORMAT_B8G8R8: // BGR func->fill_area_blend = fill_area_blend_bgr24; func->blend_area = epx_copy_area; // no src alpha func->alpha_area = alpha_area_generic; func->fade_area = alpha_area_generic; // src alpha = 1 break; case EPX_FORMAT_A8R8G8B8_BE: // ARGB case EPX_FORMAT_B8G8R8A8_LE: func->fill_area_blend = fill_area_blend_argb32; func->blend_area = blend_area_argb32; func->alpha_area = alpha_area_argb32; func->fade_area = fade_area_argb32; break; case EPX_FORMAT_X8R8G8B8_BE: // XRGB case EPX_FORMAT_B8G8R8X8_LE: func->fill_area_blend = fill_area_blend_argb32; func->blend_area = epx_copy_area; // src alpha = 1 func->alpha_area = alpha_area_argb32; func->fade_area = alpha_area_argb32; // src alpha = 1 break; case EPX_FORMAT_A8B8G8R8_BE: // ABGR case EPX_FORMAT_R8G8B8A8_LE: func->fill_area_blend = fill_area_blend_abgr32; func->blend_area = blend_area_argb32; func->alpha_area = alpha_area_argb32; func->fade_area = fade_area_argb32; break; case EPX_FORMAT_X8B8G8R8_BE: // XBGR case EPX_FORMAT_R8G8B8X8_LE: func->fill_area_blend = fill_area_blend_abgr32; func->blend_area = epx_copy_area; // no src alpha func->alpha_area = alpha_area_argb32; // abgr = argb for alpha func->fade_area = alpha_area_argb32; // src alpha = 1 break; case EPX_FORMAT_R8G8B8A8_BE: // RGBA case EPX_FORMAT_A8B8G8R8_LE: func->fill_area_blend = fill_area_blend_rgba32; func->blend_area = blend_area_rgba32; func->alpha_area = alpha_area_rgba32; func->fade_area = fade_area_rgba32; break; case EPX_FORMAT_R8G8B8X8_BE: // RGBX case EPX_FORMAT_X8B8G8R8_LE: func->fill_area_blend = fill_area_blend_rgba32; func->blend_area = epx_copy_area; // no src alpha func->alpha_area = alpha_area_rgba32; func->fade_area = alpha_area_rgba32; // src alpha = 1 break; case EPX_FORMAT_B8G8R8A8_BE: // BGRA case EPX_FORMAT_A8R8G8B8_LE: func->fill_area_blend = fill_area_blend_bgra32; func->blend_area = blend_area_rgba32; func->alpha_area = alpha_area_rgba32; func->fade_area = fade_area_rgba32; break; case EPX_FORMAT_B8G8R8X8_BE: // BGRX case EPX_FORMAT_X8R8G8B8_LE: func->fill_area_blend = fill_area_blend_bgra32; func->blend_area = epx_copy_area; // no src alpha func->alpha_area = alpha_area_rgba32; func->fade_area = alpha_area_rgba32; // src alpha = 1 break; default: func->fill_area_blend = fill_area_blend_generic; func->blend_area = blend_area_generic; func->alpha_area = alpha_area_generic; func->fade_area = fade_area_generic; break; } } int epx_pixmap_set_format(epx_pixmap_t* dst, epx_format_t fmt) { if (dst->pixel_format != fmt) { uint8_t* data0; unsigned int bytes_per_pixel = EPX_PIXEL_BYTE_SIZE(fmt); unsigned int bytes_per_row = bytes_per_pixel*dst->width; size_t sz; epx_pixel_unpack_t unpack; epx_pixel_pack_t pack; bytes_per_row += EPX_ALIGN_OFFS(bytes_per_row, EPX_ALIGNMENT); sz = bytes_per_row*dst->height; unpack = epx_pixel_unpack_func(fmt); pack = epx_pixel_pack_func(fmt); if ((unpack == NULL) || (pack == NULL)) return -1; if (sz > dst->sz) { // reallocate pixels if (!(data0 = (uint8_t*) realloc(dst->data0, sz+15))) return -1; dst->sz = sz; dst->data0 = data0; dst->data = data0 + EPX_ALIGN_OFFS(data0, EPX_ALIGNMENT); } dst->bytes_per_row = bytes_per_row; dst->bits_per_pixel = bytes_per_pixel*8; dst->bytes_per_pixel = bytes_per_pixel; dst->pixel_format = fmt; dst->func.unpack = unpack; dst->func.pack = pack; } return 0; } int epx_pixmap_init(epx_pixmap_t* dst, unsigned int width, unsigned int height, epx_format_t fmt) { uint8_t* data0; unsigned int bytes_per_pixel = EPX_PIXEL_BYTE_SIZE(fmt); unsigned int bytes_per_row = bytes_per_pixel*width; epx_pixel_unpack_t unpack; epx_pixel_pack_t pack; // initialize here to make sure destructor always will work EPX_OBJECT_INIT(dst, EPX_PIXMAP_TYPE); dst->data0 = 0; dst->data = 0; dst->backend = 0; dst->parent = 0; dst->user = 0; bytes_per_row += EPX_ALIGN_OFFS(bytes_per_row, EPX_ALIGNMENT); unpack = epx_pixel_unpack_func(fmt); pack = epx_pixel_pack_func(fmt); if ((unpack == NULL) || (pack == NULL)) return -1; if (!(data0 = (uint8_t*) malloc(bytes_per_row*height+15))) return -1; epx_rect_set(&dst->clip, 0, 0, width, height); epx_t2d_identity(&dst->ltm); dst->ctm = &dst->ltm; dst->width = width; dst->bytes_per_row = bytes_per_row; dst->height = height; dst->bits_per_pixel = bytes_per_pixel*8; dst->pixel_format = fmt; dst->func.unpack = unpack; dst->func.pack = pack; init_pixel_area_functions(&dst->func, fmt); dst->bytes_per_pixel = bytes_per_pixel; /* total number of bytes, not including padding */ dst->sz = bytes_per_row*height; dst->data0 = data0; dst->data = data0 + EPX_ALIGN_OFFS(data0, EPX_ALIGNMENT); return 0; } epx_pixmap_t* epx_pixmap_create(unsigned int width, unsigned int height, epx_format_t fmt) { epx_pixmap_t* px; if (!(px = (epx_pixmap_t*) malloc(sizeof(epx_pixmap_t)))) return 0; if (epx_pixmap_init(px, width, height, fmt) < 0) { free(px); return 0; } px->on_heap = 1; px->refc = 1; return px; } int epx_pixmap_init_copy(epx_pixmap_t* src, epx_pixmap_t* dst) { if (epx_pixmap_init(dst, src->width, src->height, src->pixel_format) < 0) return -1; if (!src->data0) // it's a sub_pixmap epx_copy_area(src->data, src->bytes_per_row, src->pixel_format, dst->data, dst->bytes_per_row, dst->pixel_format, src->width, src->height); else epx_copy(src->data, dst->data, src->sz); return 0; } // epx_pixmap_copy // Create an identical copy of src pixmap // epx_pixmap_t* epx_pixmap_copy(epx_pixmap_t* src) { epx_pixmap_t* dst; if (!(dst = (epx_pixmap_t*) malloc(sizeof(epx_pixmap_t)))) return 0; if (epx_pixmap_init_copy(src, dst) < 0) { free(dst); return 0; } dst->on_heap = 1; dst->refc = 1; return dst; } // epx_pixmap_sub_pixmap // Create an identical copy of src pixmap // width and height may be updated since the copy must be // inclusive, it is never extended // int epx_pixmap_init_sub_pixmap(epx_pixmap_t* src, epx_pixmap_t* dst, int x, int y, unsigned int width, unsigned int height) { epx_rect_t sr; epx_rect_t dr; epx_rect_set(&sr, 0, 0, src->width, src->height); epx_rect_set(&dr, x, y, width, height); epx_rect_intersect(&dr, &sr, &dr); EPX_OBJECT_INIT(dst, EPX_PIXMAP_TYPE); dst->backend = 0; dst->parent = src; epx_object_ref(src); // set a reference to parent epx_rect_set(&dst->clip, 0, 0, dr.wh.width, dr.wh.height); dst->width = dr.wh.width; dst->bytes_per_row = src->bytes_per_row; dst->height = dr.wh.height; dst->bits_per_pixel = src->bits_per_pixel; dst->pixel_format = src->pixel_format; dst->func = src->func; dst->sz = src->bytes_per_row*dr.wh.height; dst->data0 = 0; // signal sub-pixmap dst->data = EPX_PIXEL_ADDR(src, dr.xy.x, dr.xy.y); return 0; } epx_pixmap_t* epx_pixmap_sub_pixmap(epx_pixmap_t* src, int x, int y, unsigned int width, unsigned int height) { epx_pixmap_t* dst; if (!(dst = (epx_pixmap_t*) malloc(sizeof(epx_pixmap_t)))) return 0; if (epx_pixmap_init_sub_pixmap(src, dst, x, y, width, height) < 0) { free(dst); return 0; } dst->on_heap = 1; dst->refc = 1; return dst; } void epx_pixmap_destroy(epx_pixmap_t* pic) { epx_object_unref(pic); } // extern void epx_pixmap_detach(epx_pixmap_t*); void EPX_PIXMAP_TYPE_RELEASE(void* arg) { epx_pixmap_t* pixmap = (epx_pixmap_t*) arg; epx_backend_t* be; EPX_DBGFMT_MEM("EPIXMAP_TYPE_RELEASE: %p", arg); if ((be = pixmap->backend) != NULL) be->cb->pix_detach(be, pixmap); if (pixmap->data0) { free(pixmap->data0); pixmap->data0 = 0; } pixmap->data = 0; epx_object_unref(pixmap->parent); if (pixmap->on_heap) free(pixmap); } void epx_pixmap_set_clip(epx_pixmap_t* pic, epx_rect_t* clip) { epx_rect_t physRect; epx_rect_set(&physRect, 0, 0, pic->width, pic->height); epx_rect_intersect(clip, &physRect, &pic->clip); } /* put pixel given address */ static inline void put_apixel(uint8_t* addr, epx_pixel_unpack_t unpack, epx_pixel_pack_t pack, epx_flags_t flags, epx_pixel_t s) { if (((flags & EPX_FLAG_BLEND)==0) || (s.a == EPX_ALPHA_OPAQUE)) pack(s, addr); else if (s.a != EPX_ALPHA_TRANSPARENT) { epx_pixel_t d = unpack(addr); d = epx_pixel_blend(s.a, s, d); pack(d, addr); } } /* plot pixel, with fixed color */ void epx_pixmap_put_pixel(epx_pixmap_t* pic, int x, int y, epx_flags_t flags, epx_pixel_t p) { uint8_t* dst; if (!epx_point_xy_in_rect(x, y, &pic->clip)) return; dst = EPX_PIXEL_ADDR(pic,x,y); put_apixel(dst,pic->func.unpack,pic->func.pack,flags,p); } // epx_pixmap_PutPixels: // copy pixel data (0,0,width,height) => (x_dst,y_dst,width,height) // using blending function void epx_pixmap_put_pixels(epx_pixmap_t* dst, int x, int y, unsigned int width, unsigned int height, epx_format_t pixel_format, epx_flags_t flags, void* data, unsigned int len) { uint8_t* src_ptr; uint8_t* src_end; unsigned int src_psz = EPX_PIXEL_BYTE_SIZE(pixel_format); unsigned int src_wb = width*src_psz; epx_rect_t sr; epx_rect_t dr; epx_rect_t dr0 = {{x,y},{width,height}}; // Clip destination and check if we have any thing to copy if (!epx_rect_intersect(&dr0, &dst->clip, &dr)) return; sr.wh = dr.wh; sr.xy.x = (epx_rect_left(&dr) - epx_rect_left(&dr0)); sr.xy.y = (epx_rect_top(&dr) - epx_rect_top(&dr0)); src_ptr = ((uint8_t*)data) + (epx_rect_top(&sr)*src_wb) + (epx_rect_left(&sr)*src_psz); src_end = ((uint8_t*)data) + (epx_rect_bottom(&sr)*src_wb) + (epx_rect_right(&sr)*src_psz); // width,height pixelType and/or len is not matching if (src_end >= (((uint8_t*)data)+len)) return; if ((flags & (EPX_FLAG_BLEND|EPX_FLAG_SUM))==0) epx_copy_area(src_ptr, src_wb, pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); else if ((flags & (EPX_FLAG_BLEND|EPX_FLAG_SUM))==EPX_FLAG_SUM) { epx_sum_area(src_ptr, src_wb, pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); } else dst->func.blend_area(src_ptr, src_wb, pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); } // read a pixel epx_pixel_t epx_pixmap_get_pixel(epx_pixmap_t* pic, int x, int y) { uint8_t* src; if (!epx_point_xy_in_rect(x,y,&pic->clip)) return epx_pixel_black; src = EPX_PIXEL_ADDR(pic,x,y); return pic->func.unpack(src); } // Fill epx_pixmap_ with colors from p void epx_pixmap_fill(epx_pixmap_t* dst, epx_pixel_t p) { if (!dst->data0 || (dst->bytes_per_pixel==3)) { // a sub-pixmap epx_fill_area(dst->data, dst->bytes_per_row, dst->pixel_format, p, dst->width, dst->height); } else { uint32_t cv = 0; uint8_t* cvp = (uint8_t*) &cv; dst->func.pack(p, cvp); switch(dst->bytes_per_pixel) { case 1: epx_fill_8(dst->data, cvp[0], dst->sz); break; case 2: epx_fill_16(dst->data, cvp[0], cvp[1], dst->sz/2); break; case 4: epx_fill_32(dst->data, cvp[0], cvp[1], cvp[2], cvp[3], dst->sz/4); break; default: break; } } } void epx_pixmap_fill_area(epx_pixmap_t* pixmap, int x, int y, unsigned int width, unsigned int height, epx_pixel_t color, epx_flags_t flags) { uint8_t* ptr; epx_rect_t r; epx_rect_t r0 = {{x,y},{width,height}}; unsigned int psz; epx_format_t pt; int wb; if (!epx_rect_intersect(&r0, &pixmap->clip, &r)) return; pt = pixmap->pixel_format; psz = EPX_PIXEL_BYTE_SIZE(pt); wb = pixmap->bytes_per_row; ptr = ((uint8_t*)pixmap->data)+(r.xy.y*wb)+(r.xy.x*psz); if ((flags & EPX_FLAG_BLEND) && (color.a != EPX_ALPHA_OPAQUE)) pixmap->func.fill_area_blend(ptr, wb, pt, color, r.wh.width, r.wh.height); else epx_fill_area(ptr, wb, pt, color, r.wh.width, r.wh.height); } void epx_pixmap_fill_blend(epx_pixmap_t* dst, epx_pixel_t p) { dst->func.fill_area_blend(dst->data, dst->bytes_per_row, dst->pixel_format, p, dst->width, dst->height); } /* Flip the Pixmap (y direction) */ void epx_pixmap_flip(epx_pixmap_t* pic) { int n = pic->height/2; uint8_t* ptr1 = EPX_PIXEL_ADDR(pic, 0, 0); uint8_t* ptr2 = EPX_PIXEL_ADDR(pic, 0, pic->height-1); while(n--) { epx_swap_8(ptr1, ptr2, pic->bytes_per_row); ptr1 += pic->bytes_per_row; ptr2 -= pic->bytes_per_row; } } // copy area and shift lines left or right static inline void shift_area(uint8_t* src, int src_wb, int src_pt, uint8_t* dst, int dst_wb, int dst_pt, unsigned int width, unsigned int height, int amount) { if (amount > 0) { int psz = EPX_PIXEL_BYTE_SIZE(src_pt); src += amount*psz; width -= amount; } else { int psz = EPX_PIXEL_BYTE_SIZE(dst_pt); dst += (-amount)*psz; width -= (-amount); } while(height--) { epx_copy_row(src, src_pt, dst, dst_pt, width); src += src_wb; dst += dst_wb; } } /* copy area and shift lines left or right */ static inline void shift_area_rotate(uint8_t* src, int src_wb, int src_pt, uint8_t* dst, int dst_wb, int dst_pt, unsigned int width, unsigned int height, int amount) { int a = (amount < 0) ? -amount : amount; int src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); int dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); int n = width; int is_inline = (src == dst); uint8_t* src_from; uint8_t* dst_to; if (amount == 0) return; else if (amount > 0) { src_from = src; src += a*src_psz; n -= a; dst_to = dst + n*dst_psz; } else { n -= a; src_from = src+n*src_psz; dst_to = dst; dst += a*dst_psz; } n *= src_psz; a *= src_psz; if (is_inline) { uint8_t* save = malloc(a); while(height--) { memcpy(save, src_from, a); memmove(dst, src, n); memcpy(dst_to, save, a); src += src_wb; src_from += src_wb; dst += dst_wb; dst_to += dst_wb; } free(save); } else { /* not inline */ while(height--) { epx_copy_row(src, src_pt, dst, dst_pt, n); epx_copy_row(src_from, src_pt, dst_to, dst_pt, a); src += src_wb; src_from += src_wb; dst += dst_wb; dst_to += dst_wb; } } } /* * Copy pixmap data from src to dst, ignore clip region * if pixmap size is the same just memcpy * otherwise calculate the min area and copy that */ void epx_pixmap_copy_to(epx_pixmap_t* src, epx_pixmap_t* dst) { if (SIMD_ENABLED() && (src->width==dst->width) && (src->height == dst->height) && (src->sz == dst->sz) && (src->pixel_format == dst->pixel_format)) { SIMD_CALL(copy)(src->data, dst->data, src->sz); } else { int w = (src->width < dst->width) ? src->width : dst->width; int h = (src->height < dst->height) ? src->height : dst->height; epx_copy_area(src->data,src->bytes_per_row,src->pixel_format, dst->data,dst->bytes_per_row,dst->pixel_format, w,h); } } void epx_pixmap_scroll_left(epx_pixmap_t* src, epx_pixmap_t* dst, int rotate, unsigned int amount, epx_pixel_t fill) { int w = (src->width < dst->width) ? src->width : dst->width; int h = (src->height < dst->height) ? src->height : dst->height; int a = amount; if (rotate) shift_area_rotate(src->data, src->bytes_per_row, src->pixel_format, dst->data, dst->bytes_per_row, dst->pixel_format, w, h, a); else { shift_area(src->data, src->bytes_per_row, src->pixel_format, dst->data, dst->bytes_per_row, dst->pixel_format, w, h, a); epx_fill_area(dst->data+dst->bytes_per_pixel*(w-amount), dst->bytes_per_row,dst->pixel_format, fill, amount, h); } } void epx_pixmap_scroll_right(epx_pixmap_t* src, epx_pixmap_t* dst, int rotate, unsigned int amount, epx_pixel_t fill) { int w = (src->width < dst->width) ? src->width : dst->width; int h = (src->height < dst->height) ? src->height : dst->height; int a = amount; if (rotate) shift_area_rotate(src->data, src->bytes_per_row, src->pixel_format, dst->data, dst->bytes_per_row, dst->pixel_format, w, h, -a); else { shift_area(src->data, src->bytes_per_row, src->pixel_format, dst->data, dst->bytes_per_row, dst->pixel_format, w, h, -a); epx_fill_area(dst->data, dst->bytes_per_row, dst->pixel_format, fill, amount, h); } } void epx_pixmap_scroll_up(epx_pixmap_t* src, epx_pixmap_t* dst, int rotate, unsigned int amount, epx_pixel_t fill) { if ((amount >= src->height) && !rotate) epx_pixmap_fill(dst, fill); else { uint8_t* dst_ptr; uint8_t* src_ptr; int w = (src->width < dst->width) ? src->width : dst->width; int h; amount %= src->height; h = (src->height - amount); src_ptr = EPX_PIXEL_ADDR(src,0,amount); dst_ptr = EPX_PIXEL_ADDR(dst,0,0); if (rotate) { if (src == dst) { uint8_t* save = malloc(amount*src->width*dst->bytes_per_pixel); uint8_t* dst_save = EPX_PIXEL_ADDR(dst,0,0); epx_copy_area(dst_save, dst->bytes_per_row, dst->pixel_format, save, dst->bytes_per_row, dst->pixel_format, dst->width, amount); epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); dst_ptr = EPX_PIXEL_ADDR(dst,0,h); epx_copy_area(save, dst->bytes_per_row, dst->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, amount); free(save); } else { epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); dst_ptr = EPX_PIXEL_ADDR(dst,0,h); src_ptr = EPX_PIXEL_ADDR(src,0,0); epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, amount); } } else { epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); dst_ptr = EPX_PIXEL_ADDR(dst,0,h); epx_fill_area(dst_ptr, dst->bytes_per_row, dst->pixel_format, fill, dst->width, amount); } } } void epx_pixmap_scroll_down(epx_pixmap_t* src, epx_pixmap_t* dst, int rotate, unsigned int amount, epx_pixel_t fill) { if ((amount >= src->height) && !rotate) epx_pixmap_fill(dst, fill); else { uint8_t* dst_ptr; uint8_t* src_ptr; int w = (src->width < dst->width) ? src->width : dst->width; int h; amount %= src->height; h = (src->height - amount); src_ptr = EPX_PIXEL_ADDR(src,0,0); dst_ptr = EPX_PIXEL_ADDR(dst,0,amount); if (rotate) { if (src == dst) { uint8_t* save = malloc(amount*src->width*dst->bytes_per_pixel); uint8_t* dst_save = EPX_PIXEL_ADDR(dst,0,h); epx_copy_area(dst_save, dst->bytes_per_row, dst->pixel_format, save, dst->bytes_per_row, dst->pixel_format, dst->width, amount); epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); dst_ptr = EPX_PIXEL_ADDR(dst,0,0); epx_copy_area(save, dst->bytes_per_row, dst->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, amount); free(save); } else { epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); src_ptr = EPX_PIXEL_ADDR(src,0,h); dst_ptr = EPX_PIXEL_ADDR(dst,0,0); epx_copy_area(src_ptr, src->bytes_per_row, dst->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, amount); } } else { epx_copy_area(src_ptr, src->bytes_per_row, src->pixel_format, dst_ptr, dst->bytes_per_row, dst->pixel_format, w, h); dst_ptr = EPX_PIXEL_ADDR(dst,0,0); epx_fill_area(dst_ptr, dst->bytes_per_row, dst->pixel_format, fill, dst->width, amount); } } } /* scroll pixmap up/dow left/right rotate/fill */ void epx_pixmap_scroll(epx_pixmap_t* src, epx_pixmap_t* dst, int horizontal, int vertical, int rotate, epx_pixel_t fill) { if (vertical>0) epx_pixmap_scroll_up(src, dst, rotate, vertical, fill); else if (vertical < 0) epx_pixmap_scroll_down(src, dst, rotate, -vertical, fill); if (horizontal>0) epx_pixmap_scroll_right(src, dst, rotate, horizontal, fill); else if (horizontal < 0) epx_pixmap_scroll_left(src, dst, rotate, -horizontal, fill); } /* copy src rectangle (x1,y1,w,h) to dst rectangle (x2,y2,w,h) * blending the src with the dest */ void epx_pixmap_copy_area(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_flags_t flags) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; if ((flags & (EPX_FLAG_BLEND|EPX_FLAG_SUM))==0) epx_copy_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); else if ((flags & (EPX_FLAG_BLEND|EPX_FLAG_SUM))==EPX_FLAG_SUM) { epx_sum_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); } else src->func.blend_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); } /* copy src rectangle (x1,y1,w,h) to dst rectangle (x2,y2,w,h) * blending using alpha. */ void epx_pixmap_alpha_area(epx_pixmap_t* src,epx_pixmap_t* dst, uint8_t alpha, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; if (alpha == EPX_ALPHA_TRANSPARENT) return; else src->func.alpha_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, alpha, dr.wh.width, dr.wh.height); } /* copy src rectangle (x1,y1,w,h) to dst rectangle (x2,y2,w,h) * fade using fader value */ void epx_pixmap_fade_area(epx_pixmap_t* src,epx_pixmap_t* dst, uint8_t fade, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; src->func.fade_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, fade, dr.wh.width, dr.wh.height); } /* Shadow src rectangle (x1,y1,w,h) to dst rectangle (x2,y2,w,h) * this function will blend the pixels from source with * the luminance value as alpha. */ void epx_pixmap_shadow_area(epx_pixmap_t* src,epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_flags_t flags) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; epx_shadow_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height, flags); } void epx_pixmap_add_color_area(epx_pixmap_t* src,epx_pixmap_t* dst, uint8_t fade, epx_pixel_t color, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_flags_t flags) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; epx_add_color_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, fade, color, dr.wh.width, dr.wh.height, flags); } /* filter src rectangle (x1,y1,w,h) to dst rectangle (x2,y2,w,h) * blending using alpha. */ void epx_pixmap_filter_area(epx_pixmap_t* src,epx_pixmap_t* dst, epx_filter_t* filter, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height, epx_flags_t flags) { epx_rect_t sr, dr; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; filter_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, filter,dr.wh.width, dr.wh.height,flags); } /* * T = [ A B Tx ] [x] * [ C D Ty ] [y] * [1] * * x' = A*x + B*y + Tx * y' = C*x + D*y + Ty */ #define TRANSFORM(xp,yp,A,B,C,D,Tx,Ty,x,y) \ xp = (A)*(x) + (B)*(y) + (Tx); \ yp = (C)*(x) + (D)*(y) + (Ty) /* * Rotate a Pixmap x_dst and y_dst point out the rotation center * in the destination Pixmap * * R: [ cos(a) sin(a) ] * [-sin(a) cos(a) ] * * D = R * S * * R':[ cos(a) -sin(a) ] * [ sin(a) cos(a) ] * * S = R' * D * */ void epx_pixmap_rotate_area(epx_pixmap_t* src, epx_pixmap_t* dst, float angle, int x_src, int y_src, int xc_src, int yc_src, int xc_dst, int yc_dst, unsigned int width, unsigned int height, epx_flags_t flags) { epx_rect_t sr = {{x_src,y_src}, {width,height}}; epx_rect_t dr; float sa = sinf(angle); float ca = cosf(angle); float min_dx, max_dx; float min_dy, max_dy; float x, y; float xo, yo; if (!epx_rect_intersect(&sr, &src->clip, &sr)) return; dr = dst->clip; /* calculate dest * * min_dx, max_dx * min_dy, max_dy */ xo = xc_src - x_src; yo = yc_src - y_src; TRANSFORM(x,y, ca, sa, -sa, ca, 0, 0, -xo, -yo); min_dx = max_dx = x; min_dy = max_dy = y; TRANSFORM(x,y, ca, sa, -sa, ca, 0, 0, (width-1)-xo, -yo); min_dx = epx_min_float(min_dx, x); max_dx = epx_max_float(max_dx, x); min_dy = epx_min_float(min_dy, y); max_dy = epx_max_float(max_dy, y); TRANSFORM(x,y, ca, sa, -sa, ca, 0, 0, (width-1)-xo, (height-1)-yo); min_dx = epx_min_float(min_dx, x); max_dx = epx_max_float(max_dx, x); min_dy = epx_min_float(min_dy, y); max_dy = epx_max_float(max_dy, y); TRANSFORM(x,y, ca, sa, -sa, ca, 0, 0, -xo, (height-1)-yo); min_dx = epx_min_float(min_dx, x); max_dx = epx_max_float(max_dx, x); min_dy = epx_min_float(min_dy, y); max_dy = epx_max_float(max_dy, y); for (y = min_dy; y <= max_dy; y++) { for (x = min_dx; x <= max_dx; x++) { float xsf, ysf; int xs, ys; TRANSFORM(xsf,ysf, ca, -sa, sa, ca, xc_src, yc_src, x, y); xs = xsf; //nearbyintf(xsf); // round(xsf); ys = ysf; // nearbyintf(ysf); // round(ysf); if (epx_point_xy_in_rect(xs, ys, &sr)) { int xd = x + xc_dst; int yd = y + yc_dst; if (epx_point_xy_in_rect(xd, yd, &dr)) { uint8_t* dst_addr = EPX_PIXEL_ADDR(dst,xd,yd); epx_pixel_t p; if (flags & EPX_FLAG_AALIAS) p = epx_interp(src, xsf, ysf); else { uint8_t* src_addr = EPX_PIXEL_ADDR(src,xs,ys); p = src->func.unpack(src_addr); } put_apixel(dst_addr,dst->func.unpack,dst->func.pack,flags,p); } } } } } // // Take the src pixels and transform them to new width,height // and place pixels in dst. // void epx_pixmap_scale_area(epx_pixmap_t* src, epx_pixmap_t* dst, int x_src, int y_src, int x_dst, int y_dst, unsigned int w_src, unsigned int h_src, unsigned int w_dst, unsigned int h_dst, epx_flags_t flags) { epx_rect_t sr, dr; int y; unsigned h; float xs, ys; float ysf; if (epx_clip_dst(src,dst,x_src,y_src,x_dst,y_dst,w_dst,h_dst,&sr,&dr) < 0) return; // The inverted scale is: xs = w_src/(float) w_dst; ys = h_src/(float) h_dst; y = dr.xy.y; h = dr.wh.height; ysf = y_src; while(h--) { int x = dr.xy.x; unsigned w = dr.wh.width; uint8_t* dst_addr = EPX_PIXEL_ADDR(dst,x,y); unsigned int bytes_per_pixel = dst->bytes_per_pixel; float xsf = x_src; if (flags & EPX_FLAG_BLEND) { while(w--) { epx_pixel_t s = epx_interp(src, xsf, ysf); epx_pixel_t d = dst->func.unpack(dst_addr); d = epx_pixel_blend(s.a, s, d); dst->func.pack(d, dst_addr); dst_addr += bytes_per_pixel; xsf += xs; } } else { while(w--) { epx_pixel_t p = epx_interp(src, xsf, ysf); dst->func.pack(p, dst_addr); dst_addr += bytes_per_pixel; xsf += xs; } } y++; ysf += ys; } } // // Take the src pixels and transform them to new width,height // and place pixels in dst. // void epx_pixmap_scale(epx_pixmap_t* src, epx_pixmap_t* dst, unsigned int width, unsigned int height) { epx_pixmap_scale_area(src, dst, 0, 0, 0, 0, src->width, src->height, width, height, 0); } // // Binary operation Dst = Func(Fade,Color,Src,Dst) // void epx_binop_area(uint8_t* src, int src_wb, epx_format_t src_pt, uint8_t* dst, int dst_wb, epx_format_t dst_pt, epx_pixel_binary_op_t binop, unsigned int width, unsigned int height) { unsigned int src_psz; unsigned int dst_psz; epx_pixel_unpack_t unpack_dst; epx_pixel_unpack_t unpack_src; epx_pixel_pack_t pack_dst; src_psz = EPX_PIXEL_BYTE_SIZE(src_pt); dst_psz = EPX_PIXEL_BYTE_SIZE(dst_pt); unpack_src = epx_pixel_unpack_func(src_pt); unpack_dst = epx_pixel_unpack_func(dst_pt); pack_dst = epx_pixel_pack_func(dst_pt); while(height--) { uint8_t* dst1 = dst; uint8_t* src1 = src; unsigned int width1 = width; while(width1--) { epx_pixel_t d = unpack_dst(dst1); epx_pixel_t s = unpack_src(src1); d = binop(s,d); pack_dst(d, dst1); src1 += src_psz; dst1 += dst_psz; } src += src_wb; dst += dst_wb; } } static epx_pixel_t binop_clear(epx_pixel_t a, epx_pixel_t b) { (void) a; (void) b; return epx_pixel_transparent; } static epx_pixel_t binop_src(epx_pixel_t a, epx_pixel_t b) { (void) b; return epx_pixel_scale(a.a, a); } static epx_pixel_t binop_dst(epx_pixel_t a, epx_pixel_t b) { (void) a; return epx_pixel_scale(b.a, b); } static epx_pixel_t binop_src_over(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_over(a, b); } static epx_pixel_t binop_dst_over(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_over(b, a); } static epx_pixel_t binop_src_in(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_in(a, b); } static epx_pixel_t binop_dst_in(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_in(b, a); } static epx_pixel_t binop_src_out(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_out(a, b); } static epx_pixel_t binop_dst_out(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_out(b, a); } static epx_pixel_t binop_src_atop(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_atop(a, b); } static epx_pixel_t binop_dst_atop(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_atop(b, a); } static epx_pixel_t binop_xor(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_xor(a, b); } static epx_pixel_t binop_copy(epx_pixel_t a, epx_pixel_t b) { (void) b; return a; } static epx_pixel_t binop_src_blend(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_blend(a.a, a, b); } static epx_pixel_t binop_dst_blend(epx_pixel_t a, epx_pixel_t b) { return epx_pixel_blend(b.a, b, a); } epx_pixel_t epx_pixel_operation(epx_pixel_operation_t op, epx_pixel_t a, epx_pixel_t b) { switch(op) { case EPX_PIXEL_OP_CLEAR: return binop_clear(a,b); case EPX_PIXEL_OP_SRC: return binop_src(a,b); case EPX_PIXEL_OP_DST: return binop_dst(a,b); case EPX_PIXEL_OP_SRC_OVER: return binop_src_over(a,b); case EPX_PIXEL_OP_DST_OVER: return binop_dst_over(a,b); case EPX_PIXEL_OP_SRC_IN: return binop_src_in(a,b); case EPX_PIXEL_OP_DST_IN: return binop_dst_in(a,b); case EPX_PIXEL_OP_SRC_OUT: return binop_src_out(a,b); case EPX_PIXEL_OP_DST_OUT: return binop_dst_out(a,b); case EPX_PIXEL_OP_SRC_ATOP: return binop_src_atop(a,b); case EPX_PIXEL_OP_DST_ATOP: return binop_dst_atop(a,b); case EPX_PIXEL_OP_XOR: return binop_xor(a,b); case EPX_PIXEL_OP_COPY: return binop_copy(a,b); case EPX_PIXEL_OP_ADD: return epx_pixel_add(a,b); case EPX_PIXEL_OP_SUB: return epx_pixel_sub(a,b); case EPX_PIXEL_OP_SRC_BLEND: return binop_src_blend(a,b); case EPX_PIXEL_OP_DST_BLEND: return binop_dst_blend(a,b); default: return (epx_pixel_t)EPX_PIXEL_TRANSPARENT; } } // FUNCTION: epx_binop_sub_AREA ( ... ) #define AREA_FUNCTION epx_binop_sub_AREA #define AREA_PARAMS_DECL #define AREA_OPERATION(s,d) epx_pixel_sub(s,d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUNCTION // FUNCTION: epx_binop_add_AREA ( ... ) #define AREA_FUNCTION epx_binop_add_AREA #define AREA_PARAMS_DECL #define AREA_OPERATION(s,d) epx_pixel_add(s,d) #include "epx_area_body.i" #undef AREA_FUNCTION #undef AREA_PARAMS_DECL #undef AREA_OPERATION // END-FUNCTION void epx_pixmap_operation_area(epx_pixmap_t* src,epx_pixmap_t* dst, epx_pixel_operation_t op, int x_src, int y_src, int x_dst, int y_dst, unsigned int width, unsigned int height) { epx_rect_t sr, dr; epx_pixel_binary_op_t binop; if (epx_clip_both(src,dst,x_src,y_src,x_dst,y_dst, width, height, &sr, &dr) < 0) return; switch(op) { case EPX_PIXEL_OP_CLEAR: binop = binop_clear; break; case EPX_PIXEL_OP_SRC: binop = binop_src; break; case EPX_PIXEL_OP_DST: binop = binop_dst; break; case EPX_PIXEL_OP_SRC_OVER: binop = binop_src_over; break; case EPX_PIXEL_OP_DST_OVER: binop = binop_dst_over; break; case EPX_PIXEL_OP_SRC_IN: binop = binop_src_in; break; case EPX_PIXEL_OP_DST_IN: binop = binop_dst_in; break; case EPX_PIXEL_OP_SRC_OUT: binop = binop_src_out; break; case EPX_PIXEL_OP_DST_OUT: binop = binop_dst_out; break; case EPX_PIXEL_OP_SRC_ATOP: binop = binop_src_atop; break; case EPX_PIXEL_OP_DST_ATOP: binop = binop_dst_atop; break; case EPX_PIXEL_OP_XOR: binop = binop_xor; break; case EPX_PIXEL_OP_COPY: binop = binop_copy; break; case EPX_PIXEL_OP_ADD: epx_binop_add_AREA(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); return; case EPX_PIXEL_OP_SUB: epx_binop_sub_AREA(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, dr.wh.width, dr.wh.height); return; case EPX_PIXEL_OP_SRC_BLEND: binop = binop_src_blend; break; case EPX_PIXEL_OP_DST_BLEND: binop = binop_dst_blend; break; default: return; } epx_binop_area(EPX_PIXEL_ADDR(src,sr.xy.x,sr.xy.y), src->bytes_per_row, src->pixel_format, EPX_PIXEL_ADDR(dst,dr.xy.x,dr.xy.y), dst->bytes_per_row, dst->pixel_format, binop, dr.wh.width, dr.wh.height); }
548578.c
/* See LICENSE file for copyright and license details. */ #include "common.h" static int connect_tcp_ip(const char *host, int display) { uint16_t port = libaxl_get_tcp_port(display); int fd; abort(); /* XXX */ setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &(int){1}, sizeof(int)); setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int)); return -1; } static int connect_unix(const char *path) { struct sockaddr_un addr; int fd; fd = socket(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { liberror_save_backtrace(NULL); liberror_set_error_errno(strerror(errno), "socket", errno); return -1; } if (strlen(path) >= sizeof(addr.sun_path)) { liberror_save_backtrace(NULL); /* We could fix this with an O_PATH fd to the file, * but we will not as other libraries probably do * not do that, and there is something very wrong * with your setup if the name is too long for * `struct sockaddr_un`. */ close(fd); errno = ENAMETOOLONG; liberror_set_error_errno("Path to X display socket is too long", "libaxl_connect_without_handshake", ENAMETOOLONG); return -1; } addr.sun_family = AF_LOCAL; stpcpy(addr.sun_path, path); if (connect(fd, (void *)&addr, (socklen_t)sizeof(addr))) { liberror_save_backtrace(NULL); liberror_set_error_errno(strerror(errno), "connect", errno); return -1; } return fd; } static int connect_unix_abstract(const char *path, size_t len) { struct sockaddr_un addr; int fd; fd = socket(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { liberror_save_backtrace(NULL); liberror_set_error_errno(strerror(errno), "socket", errno); return -1; } addr.sun_family = AF_LOCAL; memcpy(addr.sun_path, path, len); if (connect(fd, (void *)&addr, (socklen_t)len)) { liberror_save_backtrace(NULL); liberror_set_error_errno(strerror(errno), "connect", errno); return -1; } return fd; } LIBAXL_CONNECTION * libaxl_connect_without_handshake(const char *host, const char *protocol, int display, int screen) { LIBAXL_CONNECTION *conn; char path[sizeof("@/tmp/.X11-unix/X-") + 3 * sizeof(int)]; int fd, len; if ((!protocol || !*protocol) && (!host || !*host)) { len = sprintf(path, "%c/tmp/.X11-unix/X%i", 0, display); fd = connect_unix(&path[1]); if (fd < 0) { fd = connect_unix_abstract(path, (size_t)len); if (fd >= 0) { liberror_pop_error(); } else { fd = connect_tcp_ip("localhost", display); if (fd >= 0) { liberror_pop_error(); liberror_pop_error(); } } } } else if (!protocol || !*protocol || !strcasecmp(protocol, "tcp") || !strcasecmp(protocol, "inet") || !strcasecmp(protocol, "tcp6") || !strcasecmp(protocol, "inet6")) { fd = connect_tcp_ip(host, display); } else if (!strcmp(protocol, "unix")) { fd = connect_unix(host); } else { liberror_save_backtrace(NULL); liberror_set_error("Display server uses unsupported underlaying protocol", "libaxl_connect_without_handshake", "libaxl", LIBAXL_ERROR_PROTOCOL_NOT_SUPPORTED); return NULL; } if (fd < 0) return NULL; conn = libaxl_create(fd); if (conn) conn->info.default_screen_number = screen < 0 ? 0 : screen; return conn; }
872942.c
/* * int stat(char *filename, struct stat *buf) * * Return information about a file in CP/M * * TODO: file date/time support for CP/M versions > 3.00 (MP/M II, etc) * * * Stefano 2019 * * * ----- * $Id: stat.c $ */ #include <sys/stat.h> #include <cpm.h> #include <stdio.h> #include <fcntl.h> #include <time.h> time_t doepoch(int days, int hours, int minutes) { return ((long)(days+2921)*86400L+(long)hours*3600L+(long)minutes*60L); } int stat(char *filename, struct stat *buf) { int inode; struct fcb *fc; struct sfcb *sfc; //unsigned char uid,pad; /* We lend a free FCB slot, but we leave the fc->use flag reset (no space reservation) */ if ( ( fc = getfcb() ) == NULL ) { return -1; } /* Test it is a real file, not a device */ if ( setfcb(fc,filename) != 0 ) { clearfcb(fc); // equals to fcb->use = 0; return -1; } /* Compute file size */ if ( bdos(CPM_CFS,fc) != 0 ) { clearfcb(fc); return -1; } buf->st_mode=0100777; /* regular file flag, rwxrwxrwx */ /* File size and block size, approx. at 128 bytes boundary */ buf->st_blksize = 128; /* Size of a CP/M block */ /* NOTE: file sizes >= 8MB will make st_blocks overflow, but st_size will still work */ buf->st_blocks = fc->ranrec[0] + 256 * fc->ranrec[1]; buf->st_size = (unsigned long) buf->st_blocks * 128L; if (fc->ranrec[2]&1) buf->st_size += 8388608L; /* UID & GID stuff */ buf->st_gid=0; buf->st_uid=fc->uid; /* Device stuff */ buf->st_dev=1; buf->st_rdev=0; /* Inode - try to make unique.. */ buf->st_ino=fc->ranrec[0]+filename[0]; /* Links */ buf->st_nlink=0; /* Date/Time */ buf->st_ctime=buf->st_mtime=buf->st_atime=0L; if (bdos(CPM_VERS,0) >= 0x30) { sfc=(void *)fc; if (bdos(102,sfc)!=0) { /* read file date stamps and password mode */ buf->st_mtime=doepoch(sfc->date,sfc->hours,sfc->minutes); buf->st_ctime=buf->st_atime=doepoch(sfc->c_date,sfc->c_hours,sfc->c_minutes); } } clearfcb(fc); return 0; }
247273.c
/* * SN9C2028 library * * Copyright (C) 2009 Theodore Kilgore <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define MODULE_NAME "sn9c2028" #include "gspca.h" MODULE_AUTHOR("Theodore Kilgore"); MODULE_DESCRIPTION("Sonix SN9C2028 USB Camera Driver"); MODULE_LICENSE("GPL"); /* specific webcam descriptor */ struct sd { struct gspca_dev gspca_dev; /* !! must be the first item */ u8 sof_read; u16 model; }; struct init_command { unsigned char instruction[6]; unsigned char to_read; /* length to read. 0 means no reply requested */ }; /* V4L2 controls supported by the driver */ static const struct ctrl sd_ctrls[] = { }; /* How to change the resolution of any of the VGA cams is unknown */ static const struct v4l2_pix_format vga_mode[] = { {640, 480, V4L2_PIX_FMT_SN9C2028, V4L2_FIELD_NONE, .bytesperline = 640, .sizeimage = 640 * 480 * 3 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0}, }; /* No way to change the resolution of the CIF cams is known */ static const struct v4l2_pix_format cif_mode[] = { {352, 288, V4L2_PIX_FMT_SN9C2028, V4L2_FIELD_NONE, .bytesperline = 352, .sizeimage = 352 * 288 * 3 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0}, }; /* the bytes to write are in gspca_dev->usb_buf */ static int sn9c2028_command(struct gspca_dev *gspca_dev, u8 *command) { int rc; PDEBUG(D_USBO, "sending command %02x%02x%02x%02x%02x%02x", command[0], command[1], command[2], command[3], command[4], command[5]); memcpy(gspca_dev->usb_buf, command, 6); rc = usb_control_msg(gspca_dev->dev, usb_sndctrlpipe(gspca_dev->dev, 0), USB_REQ_GET_CONFIGURATION, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, 2, 0, gspca_dev->usb_buf, 6, 500); if (rc < 0) { err("command write [%02x] error %d", gspca_dev->usb_buf[0], rc); return rc; } return 0; } static int sn9c2028_read1(struct gspca_dev *gspca_dev) { int rc; rc = usb_control_msg(gspca_dev->dev, usb_rcvctrlpipe(gspca_dev->dev, 0), USB_REQ_GET_STATUS, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, 1, 0, gspca_dev->usb_buf, 1, 500); if (rc != 1) { err("read1 error %d", rc); return (rc < 0) ? rc : -EIO; } PDEBUG(D_USBI, "read1 response %02x", gspca_dev->usb_buf[0]); return gspca_dev->usb_buf[0]; } static int sn9c2028_read4(struct gspca_dev *gspca_dev, u8 *reading) { int rc; rc = usb_control_msg(gspca_dev->dev, usb_rcvctrlpipe(gspca_dev->dev, 0), USB_REQ_GET_STATUS, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, 4, 0, gspca_dev->usb_buf, 4, 500); if (rc != 4) { err("read4 error %d", rc); return (rc < 0) ? rc : -EIO; } memcpy(reading, gspca_dev->usb_buf, 4); PDEBUG(D_USBI, "read4 response %02x%02x%02x%02x", reading[0], reading[1], reading[2], reading[3]); return rc; } static int sn9c2028_long_command(struct gspca_dev *gspca_dev, u8 *command) { int i, status; __u8 reading[4]; status = sn9c2028_command(gspca_dev, command); if (status < 0) return status; status = -1; for (i = 0; i < 256 && status < 2; i++) status = sn9c2028_read1(gspca_dev); if (status != 2) { err("long command status read error %d", status); return (status < 0) ? status : -EIO; } memset(reading, 0, 4); status = sn9c2028_read4(gspca_dev, reading); if (status < 0) return status; /* in general, the first byte of the response is the first byte of * the command, or'ed with 8 */ status = sn9c2028_read1(gspca_dev); if (status < 0) return status; return 0; } static int sn9c2028_short_command(struct gspca_dev *gspca_dev, u8 *command) { int err_code; err_code = sn9c2028_command(gspca_dev, command); if (err_code < 0) return err_code; err_code = sn9c2028_read1(gspca_dev); if (err_code < 0) return err_code; return 0; } /* this function is called at probe time */ static int sd_config(struct gspca_dev *gspca_dev, const struct usb_device_id *id) { struct sd *sd = (struct sd *) gspca_dev; struct cam *cam = &gspca_dev->cam; PDEBUG(D_PROBE, "SN9C2028 camera detected (vid/pid 0x%04X:0x%04X)", id->idVendor, id->idProduct); sd->model = id->idProduct; switch (sd->model) { case 0x7005: PDEBUG(D_PROBE, "Genius Smart 300 camera"); break; case 0x8000: PDEBUG(D_PROBE, "DC31VC"); break; case 0x8001: PDEBUG(D_PROBE, "Spy camera"); break; case 0x8003: PDEBUG(D_PROBE, "CIF camera"); break; case 0x8008: PDEBUG(D_PROBE, "Mini-Shotz ms-350 camera"); break; case 0x800a: PDEBUG(D_PROBE, "Vivitar 3350b type camera"); cam->input_flags = V4L2_IN_ST_VFLIP | V4L2_IN_ST_HFLIP; break; } switch (sd->model) { case 0x8000: case 0x8001: case 0x8003: cam->cam_mode = cif_mode; cam->nmodes = ARRAY_SIZE(cif_mode); break; default: cam->cam_mode = vga_mode; cam->nmodes = ARRAY_SIZE(vga_mode); } return 0; } /* this function is called at probe and resume time */ static int sd_init(struct gspca_dev *gspca_dev) { int status = -1; sn9c2028_read1(gspca_dev); sn9c2028_read1(gspca_dev); status = sn9c2028_read1(gspca_dev); return (status < 0) ? status : 0; } static int run_start_commands(struct gspca_dev *gspca_dev, struct init_command *cam_commands, int n) { int i, err_code = -1; for (i = 0; i < n; i++) { switch (cam_commands[i].to_read) { case 4: err_code = sn9c2028_long_command(gspca_dev, cam_commands[i].instruction); break; case 1: err_code = sn9c2028_short_command(gspca_dev, cam_commands[i].instruction); break; case 0: err_code = sn9c2028_command(gspca_dev, cam_commands[i].instruction); break; } if (err_code < 0) return err_code; } return 0; } static int start_spy_cam(struct gspca_dev *gspca_dev) { struct init_command spy_start_commands[] = { {{0x0c, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x20, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x21, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x22, 0x01, 0x04, 0x00, 0x00}, 4}, {{0x13, 0x23, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x24, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x16, 0x00, 0x00}, 4}, /* width 352 */ {{0x13, 0x26, 0x01, 0x12, 0x00, 0x00}, 4}, /* height 288 */ /* {{0x13, 0x27, 0x01, 0x28, 0x00, 0x00}, 4}, */ {{0x13, 0x27, 0x01, 0x68, 0x00, 0x00}, 4}, {{0x13, 0x28, 0x01, 0x09, 0x00, 0x00}, 4}, /* red gain ?*/ /* {{0x13, 0x28, 0x01, 0x00, 0x00, 0x00}, 4}, */ {{0x13, 0x29, 0x01, 0x00, 0x00, 0x00}, 4}, /* {{0x13, 0x29, 0x01, 0x0c, 0x00, 0x00}, 4}, */ {{0x13, 0x2a, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2b, 0x01, 0x00, 0x00, 0x00}, 4}, /* {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, */ {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x02, 0x00, 0x00}, 4}, /* {{0x13, 0x2e, 0x01, 0x09, 0x00, 0x00}, 4}, */ {{0x13, 0x2e, 0x01, 0x09, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x07, 0x00, 0x00}, 4}, {{0x12, 0x34, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x34, 0x01, 0xa1, 0x00, 0x00}, 4}, {{0x13, 0x35, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x02, 0x06, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x03, 0x13, 0x00, 0x00, 0x00}, 4}, /*don't mess with*/ /*{{0x11, 0x04, 0x06, 0x00, 0x00, 0x00}, 4}, observed */ {{0x11, 0x04, 0x00, 0x00, 0x00, 0x00}, 4}, /* brighter */ /*{{0x11, 0x05, 0x65, 0x00, 0x00, 0x00}, 4}, observed */ {{0x11, 0x05, 0x00, 0x00, 0x00, 0x00}, 4}, /* brighter */ {{0x11, 0x06, 0xb1, 0x00, 0x00, 0x00}, 4}, /* observed */ {{0x11, 0x07, 0x00, 0x00, 0x00, 0x00}, 4}, /*{{0x11, 0x08, 0x06, 0x00, 0x00, 0x00}, 4}, observed */ {{0x11, 0x08, 0x0b, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x09, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0a, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0b, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0c, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0d, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0e, 0x04, 0x00, 0x00, 0x00}, 4}, /* {{0x11, 0x0f, 0x00, 0x00, 0x00, 0x00}, 4}, */ /* brightness or gain. 0 is default. 4 is good * indoors at night with incandescent lighting */ {{0x11, 0x0f, 0x04, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x10, 0x06, 0x00, 0x00, 0x00}, 4}, /*hstart or hoffs*/ {{0x11, 0x11, 0x06, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x12, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x14, 0x02, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x13, 0x01, 0x00, 0x00, 0x00}, 4}, /* {{0x1b, 0x02, 0x06, 0x00, 0x00, 0x00}, 1}, observed */ {{0x1b, 0x02, 0x11, 0x00, 0x00, 0x00}, 1}, /* brighter */ /* {{0x1b, 0x13, 0x01, 0x00, 0x00, 0x00}, 1}, observed */ {{0x1b, 0x13, 0x11, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x34, 0xa1, 0x00, 0x00, 0x00}, 1}, /* compresses */ /* Camera should start to capture now. */ }; return run_start_commands(gspca_dev, spy_start_commands, ARRAY_SIZE(spy_start_commands)); } static int start_cif_cam(struct gspca_dev *gspca_dev) { struct init_command cif_start_commands[] = { {{0x0c, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, /* The entire sequence below seems redundant */ /* {{0x13, 0x20, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x21, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x22, 0x01, 0x06, 0x00, 0x00}, 4}, {{0x13, 0x23, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x24, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x16, 0x00, 0x00}, 4}, width? {{0x13, 0x26, 0x01, 0x12, 0x00, 0x00}, 4}, height? {{0x13, 0x27, 0x01, 0x68, 0x00, 0x00}, 4}, subsample? {{0x13, 0x28, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x29, 0x01, 0x20, 0x00, 0x00}, 4}, {{0x13, 0x2a, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2b, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x0f, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x0c, 0x00, 0x00}, 4}, {{0x12, 0x34, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x34, 0x01, 0xa1, 0x00, 0x00}, 4}, {{0x13, 0x35, 0x01, 0x00, 0x00, 0x00}, 4},*/ {{0x1b, 0x21, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x17, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x19, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x02, 0x06, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x03, 0x5a, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x04, 0x27, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x05, 0x01, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x12, 0x14, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x13, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x14, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x15, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x16, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x77, 0xa2, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x06, 0x0f, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x07, 0x14, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x08, 0x0f, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x09, 0x10, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x0e, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x0f, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x12, 0x07, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x10, 0x1f, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x11, 0x01, 0x00, 0x00, 0x00}, 1}, {{0x13, 0x25, 0x01, 0x16, 0x00, 0x00}, 1}, /* width/8 */ {{0x13, 0x26, 0x01, 0x12, 0x00, 0x00}, 1}, /* height/8 */ /* {{0x13, 0x27, 0x01, 0x68, 0x00, 0x00}, 4}, subsample? * {{0x13, 0x28, 0x01, 0x1e, 0x00, 0x00}, 4}, does nothing * {{0x13, 0x27, 0x01, 0x20, 0x00, 0x00}, 4}, */ /* {{0x13, 0x29, 0x01, 0x22, 0x00, 0x00}, 4}, * causes subsampling * but not a change in the resolution setting! */ {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x01, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x08, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x06, 0x00, 0x00}, 4}, {{0x13, 0x28, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x1b, 0x04, 0x6d, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x05, 0x03, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x36, 0x06, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x0e, 0x01, 0x00, 0x00, 0x00}, 1}, {{0x12, 0x27, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x1b, 0x0f, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x36, 0x05, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x10, 0x0f, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x02, 0x06, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x11, 0x01, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x34, 0xa1, 0x00, 0x00, 0x00}, 1},/* use compression */ /* Camera should start to capture now. */ }; return run_start_commands(gspca_dev, cif_start_commands, ARRAY_SIZE(cif_start_commands)); } static int start_ms350_cam(struct gspca_dev *gspca_dev) { struct init_command ms350_start_commands[] = { {{0x0c, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x16, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x20, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x21, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x22, 0x01, 0x04, 0x00, 0x00}, 4}, {{0x13, 0x23, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x24, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x16, 0x00, 0x00}, 4}, {{0x13, 0x26, 0x01, 0x12, 0x00, 0x00}, 4}, {{0x13, 0x27, 0x01, 0x28, 0x00, 0x00}, 4}, {{0x13, 0x28, 0x01, 0x09, 0x00, 0x00}, 4}, {{0x13, 0x29, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2a, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2b, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x0f, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x0c, 0x00, 0x00}, 4}, {{0x12, 0x34, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x34, 0x01, 0xa1, 0x00, 0x00}, 4}, {{0x13, 0x35, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x00, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x01, 0x70, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x02, 0x05, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x03, 0x5d, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x04, 0x07, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x05, 0x25, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x06, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x07, 0x09, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x08, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x09, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0a, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0b, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0c, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0d, 0x0c, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0e, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x0f, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x10, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x11, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x12, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x13, 0x63, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x15, 0x70, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x18, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x11, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x28, 0x00, 0x00}, 4}, /* width */ {{0x13, 0x26, 0x01, 0x1e, 0x00, 0x00}, 4}, /* height */ {{0x13, 0x28, 0x01, 0x09, 0x00, 0x00}, 4}, /* vstart? */ {{0x13, 0x27, 0x01, 0x28, 0x00, 0x00}, 4}, {{0x13, 0x29, 0x01, 0x40, 0x00, 0x00}, 4}, /* hstart? */ {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x0f, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x0c, 0x00, 0x00}, 4}, {{0x1b, 0x02, 0x05, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x11, 0x01, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x18, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x02, 0x0a, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x11, 0x01, 0x00, 0x00, 0x00}, 0}, /* Camera should start to capture now. */ }; return run_start_commands(gspca_dev, ms350_start_commands, ARRAY_SIZE(ms350_start_commands)); } static int start_genius_cam(struct gspca_dev *gspca_dev) { struct init_command genius_start_commands[] = { {{0x0c, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x16, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x10, 0x00, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x16, 0x00, 0x00}, 4}, {{0x13, 0x26, 0x01, 0x12, 0x00, 0x00}, 4}, /* "preliminary" width and height settings */ {{0x13, 0x28, 0x01, 0x0e, 0x00, 0x00}, 4}, {{0x13, 0x27, 0x01, 0x20, 0x00, 0x00}, 4}, {{0x13, 0x29, 0x01, 0x22, 0x00, 0x00}, 4}, {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x09, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x07, 0x00, 0x00}, 4}, {{0x11, 0x20, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x21, 0x2d, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x22, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x23, 0x03, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x10, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x11, 0x64, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x12, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x13, 0x91, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x14, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x15, 0x20, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x16, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x17, 0x60, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x20, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x21, 0x2d, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x22, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x23, 0x03, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x25, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x26, 0x02, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x27, 0x88, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x30, 0x38, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x31, 0x2a, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x32, 0x2a, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x33, 0x2a, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x34, 0x02, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x5b, 0x0a, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x28, 0x00, 0x00}, 4}, /* real width */ {{0x13, 0x26, 0x01, 0x1e, 0x00, 0x00}, 4}, /* real height */ {{0x13, 0x28, 0x01, 0x0e, 0x00, 0x00}, 4}, {{0x13, 0x27, 0x01, 0x20, 0x00, 0x00}, 4}, {{0x13, 0x29, 0x01, 0x62, 0x00, 0x00}, 4}, {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x0f, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x0c, 0x00, 0x00}, 4}, {{0x11, 0x20, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x21, 0x2a, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x22, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x23, 0x28, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x10, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x11, 0x04, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x12, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x13, 0x03, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x14, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x15, 0xe0, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x16, 0x02, 0x00, 0x00, 0x00}, 4}, {{0x11, 0x17, 0x80, 0x00, 0x00, 0x00}, 4}, {{0x1c, 0x20, 0x00, 0x2a, 0x00, 0x00}, 1}, {{0x1c, 0x20, 0x00, 0x2a, 0x00, 0x00}, 1}, {{0x20, 0x34, 0xa1, 0x00, 0x00, 0x00}, 0} /* Camera should start to capture now. */ }; return run_start_commands(gspca_dev, genius_start_commands, ARRAY_SIZE(genius_start_commands)); } static int start_vivitar_cam(struct gspca_dev *gspca_dev) { struct init_command vivitar_start_commands[] = { {{0x0c, 0x01, 0x00, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x20, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x21, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x22, 0x01, 0x01, 0x00, 0x00}, 4}, {{0x13, 0x23, 0x01, 0x01, 0x00, 0x00}, 4}, {{0x13, 0x24, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x25, 0x01, 0x28, 0x00, 0x00}, 4}, {{0x13, 0x26, 0x01, 0x1e, 0x00, 0x00}, 4}, {{0x13, 0x27, 0x01, 0x20, 0x00, 0x00}, 4}, {{0x13, 0x28, 0x01, 0x0a, 0x00, 0x00}, 4}, /* * Above is changed from OEM 0x0b. Fixes Bayer tiling. * Presumably gives a vertical shift of one row. */ {{0x13, 0x29, 0x01, 0x20, 0x00, 0x00}, 4}, /* Above seems to do horizontal shift. */ {{0x13, 0x2a, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2b, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x2c, 0x01, 0x02, 0x00, 0x00}, 4}, {{0x13, 0x2d, 0x01, 0x03, 0x00, 0x00}, 4}, {{0x13, 0x2e, 0x01, 0x0f, 0x00, 0x00}, 4}, {{0x13, 0x2f, 0x01, 0x0c, 0x00, 0x00}, 4}, /* Above three commands seem to relate to brightness. */ {{0x12, 0x34, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x13, 0x34, 0x01, 0xa1, 0x00, 0x00}, 4}, {{0x13, 0x35, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x1b, 0x12, 0x80, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x01, 0x77, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x02, 0x3a, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x12, 0x78, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x13, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x14, 0x80, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x15, 0x34, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x1b, 0x04, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x20, 0x44, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x23, 0xee, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x26, 0xa0, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x27, 0x9a, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x28, 0xa0, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x29, 0x30, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x2a, 0x80, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x2b, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x2f, 0x3d, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x30, 0x24, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x32, 0x86, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x60, 0xa9, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x61, 0x42, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x65, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x69, 0x38, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x6f, 0x88, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x70, 0x0b, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x71, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x74, 0x21, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x75, 0x86, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x76, 0x00, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x7d, 0xf3, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x17, 0x1c, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x18, 0xc0, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x19, 0x05, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x1a, 0xf6, 0x00, 0x00, 0x00}, 1}, /* {{0x13, 0x25, 0x01, 0x28, 0x00, 0x00}, 4}, {{0x13, 0x26, 0x01, 0x1e, 0x00, 0x00}, 4}, {{0x13, 0x28, 0x01, 0x0b, 0x00, 0x00}, 4}, */ {{0x20, 0x36, 0x06, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x10, 0x26, 0x00, 0x00, 0x00}, 1}, {{0x12, 0x27, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x1b, 0x76, 0x03, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x36, 0x05, 0x00, 0x00, 0x00}, 1}, {{0x1b, 0x00, 0x3f, 0x00, 0x00, 0x00}, 1}, /* Above is brightness; OEM driver setting is 0x10 */ {{0x12, 0x27, 0x01, 0x00, 0x00, 0x00}, 4}, {{0x20, 0x29, 0x30, 0x00, 0x00, 0x00}, 1}, {{0x20, 0x34, 0xa1, 0x00, 0x00, 0x00}, 1} }; return run_start_commands(gspca_dev, vivitar_start_commands, ARRAY_SIZE(vivitar_start_commands)); } static int sd_start(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int err_code; sd->sof_read = 0; switch (sd->model) { case 0x7005: err_code = start_genius_cam(gspca_dev); break; case 0x8001: err_code = start_spy_cam(gspca_dev); break; case 0x8003: err_code = start_cif_cam(gspca_dev); break; case 0x8008: err_code = start_ms350_cam(gspca_dev); break; case 0x800a: err_code = start_vivitar_cam(gspca_dev); break; default: err("Starting unknown camera, please report this"); return -ENXIO; } return err_code; } static void sd_stopN(struct gspca_dev *gspca_dev) { int result; __u8 data[6]; result = sn9c2028_read1(gspca_dev); if (result < 0) PDEBUG(D_ERR, "Camera Stop read failed"); memset(data, 0, 6); data[0] = 0x14; result = sn9c2028_command(gspca_dev, data); if (result < 0) PDEBUG(D_ERR, "Camera Stop command failed"); } /* Include sn9c2028 sof detection functions */ #include "sn9c2028.h" static void sd_pkt_scan(struct gspca_dev *gspca_dev, __u8 *data, /* isoc packet */ int len) /* iso packet length */ { unsigned char *sof; sof = sn9c2028_find_sof(gspca_dev, data, len); if (sof) { int n; /* finish decoding current frame */ n = sof - data; if (n > sizeof sn9c2028_sof_marker) n -= sizeof sn9c2028_sof_marker; else n = 0; gspca_frame_add(gspca_dev, LAST_PACKET, data, n); /* Start next frame. */ gspca_frame_add(gspca_dev, FIRST_PACKET, sn9c2028_sof_marker, sizeof sn9c2028_sof_marker); len -= sof - data; data = sof; } gspca_frame_add(gspca_dev, INTER_PACKET, data, len); } /* sub-driver description */ static const struct sd_desc sd_desc = { .name = MODULE_NAME, .ctrls = sd_ctrls, .nctrls = ARRAY_SIZE(sd_ctrls), .config = sd_config, .init = sd_init, .start = sd_start, .stopN = sd_stopN, .pkt_scan = sd_pkt_scan, }; /* -- module initialisation -- */ static const struct usb_device_id device_table[] = { {USB_DEVICE(0x0458, 0x7005)}, /* Genius Smart 300, version 2 */ /* The Genius Smart is untested. I can't find an owner ! */ /* {USB_DEVICE(0x0c45, 0x8000)}, DC31VC, Don't know this camera */ {USB_DEVICE(0x0c45, 0x8001)}, /* Wild Planet digital spy cam */ {USB_DEVICE(0x0c45, 0x8003)}, /* Several small CIF cameras */ /* {USB_DEVICE(0x0c45, 0x8006)}, Unknown VGA camera */ {USB_DEVICE(0x0c45, 0x8008)}, /* Mini-Shotz ms-350 */ {USB_DEVICE(0x0c45, 0x800a)}, /* Vivicam 3350B */ {} }; MODULE_DEVICE_TABLE(usb, device_table); /* -- device connect -- */ static int sd_probe(struct usb_interface *intf, const struct usb_device_id *id) { return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd), THIS_MODULE); } static struct usb_driver sd_driver = { .name = MODULE_NAME, .id_table = device_table, .probe = sd_probe, .disconnect = gspca_disconnect, #ifdef CONFIG_PM .suspend = gspca_suspend, .resume = gspca_resume, #endif }; /* -- module insert / remove -- */ static int __init sd_mod_init(void) { return usb_register(&sd_driver); } static void __exit sd_mod_exit(void) { usb_deregister(&sd_driver); } module_init(sd_mod_init); module_exit(sd_mod_exit);
260535.c
/* omega copyright (c) 1987,1988,1989 by Laurence Raphael Brothers */ /* lev.c */ #include "glob.h" /* Functions dealing with dungeon and country levels aside from actual level structure generation */ /* monsters for tactical encounters */ void make_country_monsters(terrain) short terrain; { pml tml,ml=NULL; static int plains[10] = {BUNNY,BUNNY,BLACKSNAKE,HAWK,IMPALA,WOLF,LION,BRIGAND,RANDOM}; static int forest[10] = {BUNNY,QUAIL,HAWK,BADGER,DEER,DEER,WOLF,BEAR,BRIGAND,RANDOM}; static int jungle[10] = {ANTEATER,PARROT,MAMBA,ANT,ANT,HYENA,HYENA,ELEPHANT,LION,RANDOM}; static int river[10] = {QUAIL,TROUT,TROUT,MANOWAR,BASS,BASS,CROC,CROC,BRIGAND,RANDOM}; static int swamp[10] = {BASS,BASS,CROC,CROC,BOGTHING,ANT,ANT,RANDOM,RANDOM,RANDOM}; static int desert[10] = {HAWK,HAWK,CAMEL,CAMEL,HYENA,HYENA,LION,LION,RANDOM,RANDOM}; static int tundra[10] = {WOLF,WOLF,BEAR,BEAR,DEER,DEER,RANDOM,RANDOM,RANDOM,RANDOM}; static int mountain[10] = {BUNNY,SHEEP,WOLF,WOLF,HAWK,HAWK,HAWK,RANDOM,RANDOM,RANDOM}; int *monsters,i,nummonsters; nummonsters = (random_range(5)+1) * (random_range(3)+1); switch(terrain) { case PLAINS: monsters = plains; break; case FOREST: monsters = forest; break; case JUNGLE: monsters = jungle; break; case RIVER: monsters = river; break; case SWAMP: monsters = swamp; break; case MOUNTAINS: case PASS: case VOLCANO: monsters = mountain; break; case DESERT: monsters = desert; break; case TUNDRA: monsters = tundra; break; default: monsters = NULL; } for(i=0;i<nummonsters;i++) { tml = ((pml) checkmalloc(sizeof(mltype))); tml->m = ((pmt) checkmalloc(sizeof(montype))); if (monsters == NULL) tml->m = m_create(random_range(WIDTH),random_range(LENGTH),TRUE,difficulty()); else { tml->m = make_creature(*(monsters+random_range(10))); tml->m->x = random_range(WIDTH); tml->m->y = random_range(LENGTH); } Level->site[tml->m->x][tml->m->y].creature = tml->m; tml->m->sense = WIDTH; if (m_statusp(tml->m,ONLYSWIM)) { Level->site[tml->m->x][tml->m->y].locchar = WATER; Level->site[tml->m->x][tml->m->y].p_locf = L_WATER; lset(tml->m->x, tml->m->y, CHANGED); } tml->next = ml; ml = tml; } Level->mlist = ml; } /* monstertype is more or less Current_Dungeon */ /* The caves and sewers get harder as you penetrate them; the castle is completely random, but also gets harder as it is explored; the astral and the volcano just stay hard... */ void populate_level(monstertype) int monstertype; { pml head,tml; int i,j,k,monsterid,nummonsters=(random_range(difficulty()/3)+1)*3+8; if (monstertype == E_CASTLE) nummonsters += 10; else if (monstertype == E_ASTRAL) nummonsters += 10; else if (monstertype == E_VOLCANO) nummonsters += 20; head = tml = ((pml) checkmalloc(sizeof(mltype))); for(k=0;k<nummonsters;k++) { findspace(&i,&j,-1); switch(monstertype) { case E_CAVES: if (Level->depth*10+random_range(100) > 150) monsterid = ML3+7; /* Goblin Shaman*/ else if (Level->depth*10+random_range(100) > 100) monsterid = ML2+9; /* Goblin Chieftain */ else if (random_range(100) > 50) monsterid = ML1+6; /* Goblin */ else monsterid = -1; /* IE, random monster */ break; case E_SEWERS: if (! random_range(3)) monsterid = -1; else switch(random_range(Level->depth+3)) { case 0: monsterid = ML1+3; break; /* sewer rat */ case 1: monsterid = ML1+4; break; /* aggravator fungus */ case 2: monsterid = ML1+5; break; /* blipper rat */ case 3: monsterid = ML2+1; break; /* night gaunt */ case 4: monsterid = ML2+5; break; /* transparent nasty */ case 5: monsterid = ML2+8; break; /* murk fungus */ case 6: monsterid = ML3+1; break; /* catoblepas */ case 7: monsterid = ML3+3; break; /* acid cloud */ case 8: monsterid = ML4+3; break; /* denebian slime devil */ case 9: monsterid = ML4+8; break; /* giant crocodile */ case 10: monsterid = ML5+1; break; /* tesla monster */ case 11: monsterid = ML5+7; break; /* shadow spirit */ case 12: monsterid = ML5+8; break; /* bogthing */ case 13: monsterid = ML6+2; break; /* water elemental */ case 14: monsterid = ML6+6; break; /* triton */ case 15: monsterid = ML7+3; break; /* ROUS */ default: monsterid = -1; break; } break; case E_ASTRAL: if (random_range(2)) /* random astral creatures */ switch(random_range(12)) { case 0: monsterid = ML3+14; break; /* thought form */ case 1: monsterid = ML4+11; break; /* astral fuzzy */ case 2: monsterid = ML4+15; break; /* ban sidhe */ case 3: monsterid = ML4+16; break; /* astral grue */ case 4: monsterid = ML5+7; break; /* shadow spirit */ case 5: monsterid = ML5+9; break; /* astral vampire */ case 6: monsterid = ML5+11; break; /* manaburst */ case 7: monsterid = ML6+9; break; /* rakshasa */ case 8: monsterid = ML7+4; break; /* illusory fiend */ case 9: monsterid = ML7+9; break; /* mirror master */ case 10: monsterid = ML7+10; break; /* elder etheric grue */ case 11: monsterid = ML8+8; break; /* shadow slayer */ } else if (random_range(2) && (Level->depth == 1)) /* plane of earth */ monsterid = ML6+3; /* earth elemental */ else if (random_range(2) && (Level->depth == 2)) /* plane of air */ monsterid = ML6+1; /* air elemental */ else if (random_range(2) && (Level->depth == 3)) /* plane of water */ monsterid = ML6+2; /* water elemental */ else if (random_range(2) && (Level->depth == 4)) /* plane of fire */ monsterid = ML6+0; /* fire elemental */ else if (random_range(2) && (Level->depth == 5)) /* deep astral */ switch (random_range(12)) { case 0:monsterid = ML2+1; break; /* night gaunt */ case 1:monsterid = ML4+12; break; /* servant of law */ case 2:monsterid = ML4+13; break; /* servant of chaos */ case 3:monsterid = ML5+4; break; /* lesser frost demon */ case 4:monsterid = ML5+12; break; /* outer circle demon */ case 5:monsterid = ML6+10; break; /* demon serpent */ case 6:monsterid = ML6+11; break; /* angel */ case 7:monsterid = ML7+14; break; /* inner circle demon */ case 8:monsterid = ML8+5; break; /* frost demon lord */ case 9:monsterid = ML8+11; break; /* high angel */ case 10:monsterid = ML9+7; break; /* prime circle demon */ case 11:monsterid = ML9+6; break; /* archangel */ } else monsterid = -1; break; case E_VOLCANO: if (random_range(2)) { do monsterid = random_range(ML10-ML4)+ML4; while (Monsters[monsterid].uniqueness != COMMON); } else switch(random_range(Level->depth/2+2)) { /* evil & fire creatures */ case 0: monsterid = ML4+5; break; case 1: monsterid = ML4+6; break; case 2: monsterid = ML5+0; break; case 3: monsterid = ML5+4; break; case 4: monsterid = ML5+5; break; case 5: monsterid = ML5+10; break; case 6: monsterid = ML6+0; break; case 7: monsterid = ML6+5; break; case 8: monsterid = ML6+9; break; case 9: monsterid = ML6+10; break; case 10: monsterid = ML7+1; break; case 11: monsterid = ML7+6; break; case 12: monsterid = ML7+11; break; case 13: monsterid = ML7+12; break; case 14: monsterid = ML7+14; break; case 15: monsterid = ML7+3; break; case 16: monsterid = ML8+3; break; case 17: monsterid = ML8+5; break; case 18: monsterid = ML8+8; break; case 19: monsterid = ML7+3; break; case 20: monsterid = ML9+5; break; case 21: monsterid = ML9+7; break; default: monsterid = -1; break; } break; case E_CASTLE: if (random_range(4)==1) { if (difficulty() < 5) monsterid = ML2+7; else if (difficulty() < 6) monsterid = ML5+6; else if (difficulty() < 8) monsterid = ML6+0; else monsterid = ML9+4; } else monsterid = -1; break; default: monsterid = -1; break; } if (monsterid > -1) Level->site[i][j].creature = make_creature(monsterid); else Level->site[i][j].creature = m_create(i,j,TRUE,difficulty()); Level->site[i][j].creature->x = i; Level->site[i][j].creature->y = j; if (m_statusp(Level->site[i][j].creature,ONLYSWIM)) { Level->site[i][j].locchar = WATER; Level->site[i][j].p_locf = L_WATER; lset(i, j, CHANGED); } tml->next = ((pml) checkmalloc(sizeof(mltype))); tml->next->m = Level->site[i][j].creature; tml = tml->next; } if (Level->mlist==NULL) { tml->next = NULL; Level->mlist = head->next; } else { tml->next = Level->mlist; Level->mlist = head->next; } } /* Add a wandering monster possibly */ void wandercheck() { int x,y; pml tml; if (random_range(MaxDungeonLevels) < difficulty()) { findspace(&x,&y,-1); tml = ((pml) checkmalloc(sizeof(mltype))); tml->next = Level->mlist; tml->m = Level->site[x][y].creature = m_create(x,y,WANDERING,difficulty()); Level->mlist = tml; } } /* call make_creature and place created monster on Level->mlist and Level */ void make_site_monster(i,j,mid) int i,j,mid; { pml ml = ((pml) checkmalloc(sizeof(mltype))); pmt m; if (mid > -1) Level->site[i][j].creature = (m = make_creature(mid)); else Level->site[i][j].creature = (m = m_create(i,j,WANDERING,difficulty())); m->x = i; m->y = j; ml->m = m; ml->next = Level->mlist; Level->mlist = ml; } /* make and return an appropriate monster for the level and depth*/ /* called by populate_level, doesn't actually add to mlist for some reason*/ /* eventually to be more intelligent */ pmt m_create(x,y,kind,level) int x,y,kind,level; { pmt newmonster; int monster_range; int mid; switch(level) { case 0:monster_range = ML1; break; case 1:monster_range = ML2; break; case 2:monster_range = ML3; break; case 3:monster_range = ML4; break; case 4:monster_range = ML5; break; case 5:monster_range = ML6; break; case 6:monster_range = ML7; break; case 7:monster_range = ML8; break; case 8:monster_range = ML9; break; case 9:monster_range = ML10; break; default:monster_range = NUMMONSTERS; break; } do mid = random_range(monster_range); while (Monsters[mid].uniqueness != COMMON); newmonster = make_creature(mid); /* no duplicates of unique monsters */ if (kind == WANDERING) m_status_set(newmonster,WANDERING); newmonster->x = x; newmonster->y = y; return(newmonster); } /* make creature # mid, totally random if mid == -1 */ /* make creature allocates space for the creature */ pmt make_creature(mid) int mid; { pmt newmonster = ((pmt) checkmalloc(sizeof(montype))); pob ob; int i,treasures; if (mid == -1) mid = random_range(ML9); *newmonster = Monsters[mid]; if ((mid == ML6+11) || (mid == ML8+11) || (mid == ML9+6)) { /* aux1 field of an angel is its deity */ if (Current_Environment == E_TEMPLE) newmonster->aux1 = Country[LastCountryLocX][LastCountryLocY].aux; else newmonster->aux1 = random_range(6)+1; strcpy(Str3,Monsters[mid].monstring); switch(newmonster->aux1) { case ODIN: strcat(Str3," of Odin"); break; case SET: strcat(Str3," of Set"); break; case HECATE: strcat(Str3," of Hecate"); break; case ATHENA: strcat(Str3," of Athena"); break; case DESTINY: strcat(Str3," of Destiny"); break; case DRUID: strcat(Str3," of the Balance"); break; } newmonster->monstring = salloc(Str3); } else if (mid == ML0+7 || mid == ML3+13) { /* generic 0th level human, or a were-human */ newmonster->monstring = mantype(); strcpy(Str1,"dead "); strcat(Str1,newmonster->monstring); newmonster->corpsestr = salloc(Str1); } else if ((newmonster->monchar&0xff) == '!') { /* the nymph/satyr and incubus/succubus */ if (Player.preference == 'f' || (Player.preference != 'm' && random_range(2))) { newmonster->monchar = 'n'|COL_RED; newmonster->monstring = "nymph"; newmonster->corpsestr = "dead nymph"; } else { newmonster->monchar = 's'|COL_RED; newmonster->monstring = "satyr"; newmonster->corpsestr = "dead satyr"; } if (newmonster->id == ML4+6) { if ((newmonster->monchar&0xff) == 'n') newmonster->corpsestr = "dead succubus"; else newmonster->corpsestr = "dead incubus"; } } if (mid == NPC) make_log_npc(newmonster); else if (mid == HISCORE_NPC) make_hiscore_npc(newmonster, random_range(15)); else { if (newmonster->sleep < random_range(100)) m_status_set(newmonster,AWAKE); if (newmonster->startthing > -1 && Objects[newmonster->startthing].uniqueness <= UNIQUE_MADE) { ob = ((pob) checkmalloc(sizeof(objtype))); *ob = Objects[newmonster->startthing]; m_pickup(newmonster,ob); } treasures = random_range(newmonster->treasure); for(i=0;i<treasures;i++) { do { ob = (pob) (create_object(newmonster->level)); if (ob && ob->uniqueness != COMMON) { free(ob); ob = NULL; } } while (!ob); m_pickup(newmonster,ob); } } newmonster->click = (Tick + 1) % 50; return(newmonster); } /* drop treasures randomly onto level */ void stock_level() { int i,j,k,numtreasures=2*random_range(difficulty()/4)+4; /* put cash anywhere, including walls, put other treasures only on floor */ for (k=0;k<numtreasures+10;k++) { do { i = random_range(WIDTH); j = random_range(LENGTH); } while (Level->site[i][j].locchar != FLOOR); make_site_treasure(i,j,difficulty()); i = random_range(WIDTH); j = random_range(LENGTH); Level->site[i][j].things = ((pol) checkmalloc(sizeof(oltype))); Level->site[i][j].things->thing = ((pob) checkmalloc(sizeof(objtype))); make_cash(Level->site[i][j].things->thing,difficulty()); Level->site[i][j].things->next = NULL; /* caves have more random cash strewn around */ if (Current_Dungeon == E_CAVES) { i = random_range(WIDTH); j = random_range(LENGTH); Level->site[i][j].things = ((pol) checkmalloc(sizeof(oltype))); Level->site[i][j].things->thing = ((pob) checkmalloc(sizeof(objtype))); make_cash(Level->site[i][j].things->thing,difficulty()); Level->site[i][j].things->next = NULL; i = random_range(WIDTH); j = random_range(LENGTH); Level->site[i][j].things = ((pol) checkmalloc(sizeof(oltype))); Level->site[i][j].things->thing = ((pob) checkmalloc(sizeof(objtype))); make_cash(Level->site[i][j].things->thing,difficulty()); Level->site[i][j].things->next = NULL; } } } /* make a new object (of at most level itemlevel) at site i,j on level*/ void make_site_treasure(i,j,itemlevel) int i,j,itemlevel; { pol tmp = ((pol) checkmalloc(sizeof(oltype))); do tmp->thing = ((pob) create_object(itemlevel)); while (!tmp->thing); tmp->next = Level->site[i][j].things; Level->site[i][j].things = tmp; } /* make a specific new object at site i,j on level*/ void make_specific_treasure(i,j,itemid) int i,j,itemid; { pol tmp; if (Objects[itemid].uniqueness == UNIQUE_TAKEN) return; tmp = ((pol) checkmalloc(sizeof(oltype))); tmp->thing = ((pob) checkmalloc(sizeof(objtype))); *(tmp->thing) = Objects[itemid]; tmp->next = Level->site[i][j].things; Level->site[i][j].things = tmp; } #ifndef MSDOS /* returns a "level of difficulty" based on current environment and depth in dungeon. Is somewhat arbitrary. value between 1 and 10. May not actually represent real difficulty, but instead level of items, monsters encountered. */ int difficulty() { int depth = 1; if (Level != NULL) depth = Level->depth; switch(Current_Environment) { case E_COUNTRYSIDE: return(7); case E_CITY: return(3); case E_VILLAGE: return(1); case E_TACTICAL_MAP: return(7); case E_SEWERS: return(depth/6)+3; case E_CASTLE: return(depth/4)+4; case E_CAVES: return(depth/3)+1; case E_VOLCANO: return(depth/4)+5; case E_ASTRAL: return(8); case E_ARENA: return(5); case E_HOVEL: return(3); case E_MANSION: return(7); case E_HOUSE: return(5); case E_DLAIR: return(9); case E_ABYSS: return(10); case E_STARPEAK: return(9); case E_CIRCLE: return(8); case E_MAGIC_ISLE: return(8); case E_TEMPLE: return(8); default: return(3); } } #endif
168988.c
/* -*- C -*- Copyright (C) 2009, 2010, 2012 Rocky Bernstein <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Unit test for lib/driver/gnu_linux.c */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "helper.h" int main(int argc, const char *argv[]) { CdIo_t *p_cdio; char **ppsz_drives=NULL; cdio_log_set_handler(log_handler); cdio_loglevel_default = (argc > 1) ? CDIO_LOG_DEBUG : CDIO_LOG_INFO; /* snprintf(psz_nrgfile, sizeof(psz_nrgfile)-1, "%s/%s", TEST_DIR, cue_file[i]); */ if (!cdio_have_driver(DRIVER_LINUX)) return(77); ppsz_drives = cdio_get_devices(DRIVER_DEVICE); if (!ppsz_drives) { printf("Can't find a CD-ROM drive. Skipping test.\n"); exit(77); } p_cdio = cdio_open_linux(ppsz_drives[0]); if (p_cdio) { const char *psz_source = NULL, *psz_scsi_tuple; lsn_t lsn; reset_counts(); lsn = cdio_get_track_lsn(p_cdio, CDIO_CD_MAX_TRACKS+1); assert_equal_int(CDIO_INVALID_LSN, lsn, "cdio_get_track_lsn with too large of a track number"); reset_counts(); check_get_arg_source(p_cdio, ppsz_drives[0]); check_mmc_supported(p_cdio, 3); psz_scsi_tuple = cdio_get_arg(p_cdio, "scsi-tuple"); if (psz_scsi_tuple == NULL) { fprintf(stderr, "cdio_get_arg(\"scsi-tuple\") returns NULL.\n"); cdio_destroy(p_cdio); exit(3); } if (cdio_loglevel_default == CDIO_LOG_DEBUG) printf("Drive '%s' has cdio_get_arg(\"scsi-tuple\") = '%s'\n", psz_source, psz_scsi_tuple); cdio_destroy(p_cdio); } p_cdio = cdio_open_am_linux(ppsz_drives[0], "MMC_RDWR"); if (p_cdio) { check_access_mode(p_cdio, "MMC_RDWR"); } cdio_destroy(p_cdio); cdio_free_device_list(ppsz_drives); return 0; }
366556.c
/* * Copyright 2019-present Open Networking Foundation * Copyright (c) 2003-2018, Great Software Laboratory Pvt. Ltd. * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include "log.h" #include "options.h" void parse_args(int argc, char **argv) { int args_set = 0; int c = 0; const struct option long_options[] = { {"config_file", required_argument, NULL, 'f'}, {0, 0, 0, 0} }; do { int option_index = 0; c = getopt_long(argc, argv, "f:", long_options, &option_index); if (c == -1) break; switch (c) { case 'f': break; default: log_msg(LOG_ERROR, "Unknown argument - %s.", argv[optind]); exit(0); } } while (c != -1); if ((args_set & REQ_ARGS) != REQ_ARGS) { log_msg(LOG_ERROR, "Usage: %s\n", argv[0]); for (c = 0; long_options[c].name; ++c) { log_msg(LOG_ERROR, "\t[ -%s | -%c ] %s\n", long_options[c].name, long_options[c].val, long_options[c].name); } exit(0); } } void log_buffer_free(char** buffer) { if(*buffer != NULL) free(*buffer); *buffer = NULL; } void convert_imsi_to_bcd_str(uint8_t *src, uint8_t* dest) { if (!src || !dest) { log_msg(LOG_ERROR, "invalid buffer pointers.\n"); return; } int len = BINARY_IMSI_LEN; int i = 0; for (; i < len - 1; i++) { dest[2 * i] = '0' + ((src[i] >> 4) & 0x0F); dest[2 * i + 1] = '0' + ((src[i]) & 0x0F); } dest[2 * (len-1)] = '0' + ((src[i] >> 4) & 0x0F); return; }
341210.c
/*- * BSD LICENSE * * Copyright (c) Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spdk/stdinc.h" #include "spdk_cunit.h" #include "spdk_internal/mock.h" #include "nvmf/ctrlr_bdev.c" SPDK_LOG_REGISTER_COMPONENT("nvmf", SPDK_LOG_NVMF) DEFINE_STUB(spdk_nvmf_request_complete, int, (struct spdk_nvmf_request *req), -1); DEFINE_STUB(spdk_bdev_get_name, const char *, (const struct spdk_bdev *bdev), "test"); struct spdk_bdev { uint32_t blocklen; uint64_t num_blocks; uint32_t md_len; }; uint32_t spdk_bdev_get_block_size(const struct spdk_bdev *bdev) { return bdev->blocklen; } uint64_t spdk_bdev_get_num_blocks(const struct spdk_bdev *bdev) { return bdev->num_blocks; } uint32_t spdk_bdev_get_optimal_io_boundary(const struct spdk_bdev *bdev) { abort(); return 0; } uint32_t spdk_bdev_get_md_size(const struct spdk_bdev *bdev) { return bdev->md_len; } DEFINE_STUB(spdk_bdev_comparev_and_writev_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, struct iovec *compare_iov, int compare_iovcnt, struct iovec *write_iov, int write_iovcnt, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_nvmf_ctrlr_process_io_cmd, int, (struct spdk_nvmf_request *req), 0); DEFINE_STUB_V(spdk_bdev_io_get_nvme_fused_status, (const struct spdk_bdev_io *bdev_io, uint32_t *cdw0, int *cmp_sct, int *cmp_sc, int *wr_sct, int *wr_sc)); DEFINE_STUB(spdk_bdev_is_md_interleaved, bool, (const struct spdk_bdev *bdev), false); DEFINE_STUB(spdk_bdev_get_dif_type, enum spdk_dif_type, (const struct spdk_bdev *bdev), SPDK_DIF_DISABLE); DEFINE_STUB(spdk_bdev_is_dif_head_of_md, bool, (const struct spdk_bdev *bdev), false); DEFINE_STUB(spdk_bdev_is_dif_check_enabled, bool, (const struct spdk_bdev *bdev, enum spdk_dif_check_type check_type), false); DEFINE_STUB(spdk_bdev_get_io_channel, struct spdk_io_channel *, (struct spdk_bdev_desc *desc), NULL); DEFINE_STUB(spdk_bdev_flush_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_unmap_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_io_type_supported, bool, (struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type), false); DEFINE_STUB(spdk_bdev_queue_io_wait, int, (struct spdk_bdev *bdev, struct spdk_io_channel *ch, struct spdk_bdev_io_wait_entry *entry), 0); DEFINE_STUB(spdk_bdev_write_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_writev_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, struct iovec *iov, int iovcnt, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_read_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_readv_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, struct iovec *iov, int iovcnt, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_write_zeroes_blocks, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, uint64_t offset_blocks, uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB(spdk_bdev_nvme_io_passthru, int, (struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes, spdk_bdev_io_completion_cb cb, void *cb_arg), 0); DEFINE_STUB_V(spdk_bdev_free_io, (struct spdk_bdev_io *bdev_io)); DEFINE_STUB(spdk_nvmf_subsystem_get_nqn, const char *, (const struct spdk_nvmf_subsystem *subsystem), NULL); struct spdk_nvmf_ns * spdk_nvmf_subsystem_get_ns(struct spdk_nvmf_subsystem *subsystem, uint32_t nsid) { abort(); return NULL; } struct spdk_nvmf_ns * spdk_nvmf_subsystem_get_first_ns(struct spdk_nvmf_subsystem *subsystem) { abort(); return NULL; } struct spdk_nvmf_ns * spdk_nvmf_subsystem_get_next_ns(struct spdk_nvmf_subsystem *subsystem, struct spdk_nvmf_ns *prev_ns) { abort(); return NULL; } DEFINE_STUB_V(spdk_bdev_io_get_nvme_status, (const struct spdk_bdev_io *bdev_io, uint32_t *cdw0, int *sct, int *sc)); int spdk_dif_ctx_init(struct spdk_dif_ctx *ctx, uint32_t block_size, uint32_t md_size, bool md_interleave, bool dif_loc, enum spdk_dif_type dif_type, uint32_t dif_flags, uint32_t init_ref_tag, uint16_t apptag_mask, uint16_t app_tag, uint32_t data_offset, uint16_t guard_seed) { ctx->block_size = block_size; ctx->md_size = md_size; ctx->init_ref_tag = init_ref_tag; return 0; } static void test_get_rw_params(void) { struct spdk_nvme_cmd cmd = {0}; uint64_t lba; uint64_t count; lba = 0; count = 0; to_le64(&cmd.cdw10, 0x1234567890ABCDEF); to_le32(&cmd.cdw12, 0x9875 | SPDK_NVME_IO_FLAGS_FORCE_UNIT_ACCESS); nvmf_bdev_ctrlr_get_rw_params(&cmd, &lba, &count); CU_ASSERT(lba == 0x1234567890ABCDEF); CU_ASSERT(count == 0x9875 + 1); /* NOTE: this field is 0's based, hence the +1 */ } static void test_lba_in_range(void) { /* Trivial cases (no overflow) */ CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 0, 1) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 0, 1000) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 0, 1001) == false); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 1, 999) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 1, 1000) == false); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 999, 1) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 1000, 1) == false); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(1000, 1001, 1) == false); /* Overflow edge cases */ CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(UINT64_MAX, 0, UINT64_MAX) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(UINT64_MAX, 1, UINT64_MAX) == false); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(UINT64_MAX, UINT64_MAX - 1, 1) == true); CU_ASSERT(nvmf_bdev_ctrlr_lba_in_range(UINT64_MAX, UINT64_MAX, 1) == false); } static void test_get_dif_ctx(void) { struct spdk_bdev bdev = {}; struct spdk_nvme_cmd cmd = {}; struct spdk_dif_ctx dif_ctx = {}; bool ret; bdev.md_len = 0; ret = spdk_nvmf_bdev_ctrlr_get_dif_ctx(&bdev, &cmd, &dif_ctx); CU_ASSERT(ret == false); to_le64(&cmd.cdw10, 0x1234567890ABCDEF); bdev.blocklen = 520; bdev.md_len = 8; ret = spdk_nvmf_bdev_ctrlr_get_dif_ctx(&bdev, &cmd, &dif_ctx); CU_ASSERT(ret == true); CU_ASSERT(dif_ctx.block_size = 520); CU_ASSERT(dif_ctx.md_size == 8); CU_ASSERT(dif_ctx.init_ref_tag == 0x90ABCDEF); } static void test_spdk_nvmf_bdev_ctrlr_compare_and_write_cmd(void) { int rc; struct spdk_bdev bdev = {}; struct spdk_bdev_desc *desc = NULL; struct spdk_io_channel ch = {}; struct spdk_nvmf_request cmp_req = {}; union nvmf_c2h_msg cmp_rsp = {}; struct spdk_nvmf_request write_req = {}; union nvmf_c2h_msg write_rsp = {}; struct spdk_nvmf_qpair qpair = {}; struct spdk_nvme_cmd cmp_cmd = {}; struct spdk_nvme_cmd write_cmd = {}; struct spdk_nvmf_ctrlr ctrlr = {}; struct spdk_nvmf_subsystem subsystem = {}; struct spdk_nvmf_ns ns = {}; struct spdk_nvmf_ns *subsys_ns[1] = {}; struct spdk_nvmf_poll_group group = {}; struct spdk_nvmf_subsystem_poll_group sgroups = {}; struct spdk_nvmf_subsystem_pg_ns_info ns_info = {}; bdev.blocklen = 512; bdev.num_blocks = 10; ns.bdev = &bdev; subsystem.id = 0; subsystem.max_nsid = 1; subsys_ns[0] = &ns; subsystem.ns = (struct spdk_nvmf_ns **)&subsys_ns; /* Enable controller */ ctrlr.vcprop.cc.bits.en = 1; ctrlr.subsys = &subsystem; group.num_sgroups = 1; sgroups.num_ns = 1; sgroups.ns_info = &ns_info; group.sgroups = &sgroups; qpair.ctrlr = &ctrlr; qpair.group = &group; cmp_req.qpair = &qpair; cmp_req.cmd = (union nvmf_h2c_msg *)&cmp_cmd; cmp_req.rsp = &cmp_rsp; cmp_cmd.nsid = 1; cmp_cmd.fuse = SPDK_NVME_CMD_FUSE_FIRST; cmp_cmd.opc = SPDK_NVME_OPC_COMPARE; write_req.qpair = &qpair; write_req.cmd = (union nvmf_h2c_msg *)&write_cmd; write_req.rsp = &write_rsp; write_cmd.nsid = 1; write_cmd.fuse = SPDK_NVME_CMD_FUSE_SECOND; write_cmd.opc = SPDK_NVME_OPC_WRITE; /* 1. SUCCESS */ cmp_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ cmp_cmd.cdw12 = 1; /* NLB: CDW12 bits 15:00, 0's based */ write_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ write_cmd.cdw12 = 1; /* NLB: CDW12 bits 15:00, 0's based */ write_req.length = (write_cmd.cdw12 + 1) * bdev.blocklen; rc = spdk_nvmf_bdev_ctrlr_compare_and_write_cmd(&bdev, desc, &ch, &cmp_req, &write_req); CU_ASSERT(rc == SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS); CU_ASSERT(cmp_rsp.nvme_cpl.status.sct == 0); CU_ASSERT(cmp_rsp.nvme_cpl.status.sc == 0); CU_ASSERT(write_rsp.nvme_cpl.status.sct == 0); CU_ASSERT(write_rsp.nvme_cpl.status.sc == 0); /* 2. Fused command start lba / num blocks mismatch */ cmp_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ cmp_cmd.cdw12 = 2; /* NLB: CDW12 bits 15:00, 0's based */ write_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ write_cmd.cdw12 = 1; /* NLB: CDW12 bits 15:00, 0's based */ write_req.length = (write_cmd.cdw12 + 1) * bdev.blocklen; rc = spdk_nvmf_bdev_ctrlr_compare_and_write_cmd(&bdev, desc, &ch, &cmp_req, &write_req); CU_ASSERT(rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE); CU_ASSERT(cmp_rsp.nvme_cpl.status.sct == 0); CU_ASSERT(cmp_rsp.nvme_cpl.status.sc == 0); CU_ASSERT(write_rsp.nvme_cpl.status.sct == SPDK_NVME_SCT_GENERIC); CU_ASSERT(write_rsp.nvme_cpl.status.sc == SPDK_NVME_SC_INVALID_FIELD); /* 3. SPDK_NVME_SC_LBA_OUT_OF_RANGE */ cmp_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ cmp_cmd.cdw12 = 100; /* NLB: CDW12 bits 15:00, 0's based */ write_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ write_cmd.cdw12 = 100; /* NLB: CDW12 bits 15:00, 0's based */ write_req.length = (write_cmd.cdw12 + 1) * bdev.blocklen; rc = spdk_nvmf_bdev_ctrlr_compare_and_write_cmd(&bdev, desc, &ch, &cmp_req, &write_req); CU_ASSERT(rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE); CU_ASSERT(cmp_rsp.nvme_cpl.status.sct == 0); CU_ASSERT(cmp_rsp.nvme_cpl.status.sc == 0); CU_ASSERT(write_rsp.nvme_cpl.status.sct == SPDK_NVME_SCT_GENERIC); CU_ASSERT(write_rsp.nvme_cpl.status.sc == SPDK_NVME_SC_LBA_OUT_OF_RANGE); /* 4. SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID */ cmp_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ cmp_cmd.cdw12 = 1; /* NLB: CDW12 bits 15:00, 0's based */ write_cmd.cdw10 = 1; /* SLBA: CDW10 and CDW11 */ write_cmd.cdw12 = 1; /* NLB: CDW12 bits 15:00, 0's based */ write_req.length = (write_cmd.cdw12 + 1) * bdev.blocklen - 1; rc = spdk_nvmf_bdev_ctrlr_compare_and_write_cmd(&bdev, desc, &ch, &cmp_req, &write_req); CU_ASSERT(rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE); CU_ASSERT(cmp_rsp.nvme_cpl.status.sct == 0); CU_ASSERT(cmp_rsp.nvme_cpl.status.sc == 0); CU_ASSERT(write_rsp.nvme_cpl.status.sct == SPDK_NVME_SCT_GENERIC); CU_ASSERT(write_rsp.nvme_cpl.status.sc == SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID); } int main(int argc, char **argv) { CU_pSuite suite = NULL; unsigned int num_failures; if (CU_initialize_registry() != CUE_SUCCESS) { return CU_get_error(); } suite = CU_add_suite("nvmf", NULL, NULL); if (suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if ( CU_add_test(suite, "get_rw_params", test_get_rw_params) == NULL || CU_add_test(suite, "lba_in_range", test_lba_in_range) == NULL || CU_add_test(suite, "get_dif_ctx", test_get_dif_ctx) == NULL || CU_add_test(suite, "spdk_nvmf_bdev_ctrlr_compare_and_write_cmd", test_spdk_nvmf_bdev_ctrlr_compare_and_write_cmd) == NULL ) { CU_cleanup_registry(); return CU_get_error(); } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); num_failures = CU_get_number_of_failures(); CU_cleanup_registry(); return num_failures; }
974921.c
#include <stdlib.h> #include <gio/gio.h> #include <gtk/gtk.h> #include "about_window.h" void exit_app() { exit(0); } void action_callback(GSimpleAction* simple_action, G_GNUC_UNUSED GVariant* parameter, G_GNUC_UNUSED gpointer* data) { g_print("Action %s clicked.\n", g_action_get_name(G_ACTION(simple_action))); } void activate(GApplication* app, G_GNUC_UNUSED gpointer* data) { GtkWidget* window; GSimpleAction* exit_action; GSimpleAction* about_action; GMenu* menu_bar; GMenu* file_menu; GMenu* help_menu; GMenuItem* menu_item_exit; GMenuItem* menu_item_about; menu_bar = g_menu_new(); file_menu = g_menu_new(); g_menu_append_submenu(menu_bar, "File", G_MENU_MODEL(file_menu)); help_menu = g_menu_new(); g_menu_append_submenu(menu_bar, "Help", G_MENU_MODEL(help_menu)); window = gtk_application_window_new(GTK_APPLICATION(app)); gtk_window_set_title(GTK_WINDOW(window), "Koyori"); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); exit_action = g_simple_action_new("Exit", NULL); about_action = g_simple_action_new("About", NULL); g_action_map_add_action(G_ACTION_MAP(app), G_ACTION(exit_action)); g_action_map_add_action(G_ACTION_MAP(app), G_ACTION(about_action)); g_signal_connect(exit_action, "activate", G_CALLBACK(exit_app), NULL); g_signal_connect(about_action, "activate", G_CALLBACK(create_about_window), NULL); menu_item_exit = g_menu_item_new("Exit", "app.Exit"); g_menu_append_item(file_menu, menu_item_exit); menu_item_about = g_menu_item_new("About", "app.About"); g_menu_append_item(help_menu, menu_item_about); gtk_application_set_menubar(GTK_APPLICATION(app), G_MENU_MODEL(menu_bar)); gtk_application_window_set_show_menubar(GTK_APPLICATION_WINDOW(window), TRUE); gtk_window_present(GTK_WINDOW(window)); g_object_unref(exit_action); g_object_unref(about_action); g_object_unref(menu_item_exit); g_object_unref(menu_item_about); g_object_unref(file_menu); g_object_unref(help_menu); g_object_unref(menu_bar); } int main(int argc, char** argv) { GtkApplication* app; int status; app = gtk_application_new("dev.vkcrose.koyori", G_APPLICATION_FLAGS_NONE); g_signal_connect(app, "activate", G_CALLBACK(activate), NULL); status = g_application_run(G_APPLICATION(app), argc, argv); g_object_unref(app); return status; }
101042.c
#include "cerberus.h" /* { dg-options "-ftree-loop-distribution" } */ extern void *memset(void *s, int c, __SIZE_TYPE__ n); extern int memcmp(const void *s1, const void *s2, __SIZE_TYPE__ n); /*extern int printf(const char *format, ...);*/ int main (void) { char A[30], B[30], C[30]; int i; /* prepare arrays */ memset(A, 1, 30); memset(B, 1, 30); for (i = 20; i-- > 10;) { A[i] = 0; B[i] = 0; } /* expected result */ memset(C, 1, 30); memset(C + 10, 0, 10); /* show result */ /* for (i = 0; i < 30; i++) printf("%d %d %d\n", A[i], B[i], C[i]); */ /* compare results */ if (memcmp(A, C, 30) || memcmp(B, C, 30)) abort(); return 0; }