filename
stringlengths
3
9
code
stringlengths
4
1.05M
712544.c
/* Copyright (c) 2018 Siguza * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, v. 2.0. **/ #include <stdint.h> #include "a64.h" static inline uint64_t Ones(uint8_t len) { return (((1ULL << ((len & 0x40) >> 1)) - 1) << 32) | ((1ULL << (len & 0x3f)) - 1); } uint64_t DecodeBitMasks(uint8_t N, uint8_t imms, uint8_t immr, uint8_t bits) { uint8_t len = (N << 6) | (~imms & 0x3f); len = (len & (1 << 6)) ? 6 : (len & (1 << 5)) ? 5 : (len & (1 << 4)) ? 4 : (len & (1 << 3)) ? 3 : (len & (1 << 2)) ? 2 : (len & (1 << 1)) ? 1 : (len & (1 << 0)) ? 0 : -1; uint64_t levels = Ones(len); uint64_t S = imms & levels; uint64_t R = immr & levels; uint8_t esize = 1 << len; uint64_t welem = Ones(S + 1); uint64_t wmask = (welem >> R) | ((welem & Ones(R % esize)) << (esize - (R % esize))); while(esize < bits) { wmask |= wmask << esize; esize <<= 1; } return wmask; }
25766.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 RNA */ #include <limits.h> #include <stdlib.h> #include "DNA_brush_types.h" #include "DNA_curve_types.h" #include "DNA_scene_types.h" #include "DNA_space_types.h" #include "DNA_userdef_types.h" #include "DNA_view3d_types.h" #include "BLI_math_base.h" #include "BLI_math_rotation.h" #include "BLI_utildefines.h" #include "BLT_translation.h" #include "BKE_addon.h" #include "BKE_appdir.h" #include "BKE_sound.h" #include "BKE_studiolight.h" #include "RNA_access.h" #include "RNA_define.h" #include "RNA_enum_types.h" #include "UI_interface_icons.h" #include "rna_internal.h" #include "WM_api.h" #include "WM_types.h" #include "BLT_lang.h" #ifdef WITH_OPENSUBDIV static const EnumPropertyItem opensubdiv_compute_type_items[] = { {USER_OPENSUBDIV_COMPUTE_NONE, "NONE", 0, "None", ""}, {USER_OPENSUBDIV_COMPUTE_CPU, "CPU", 0, "CPU", ""}, {USER_OPENSUBDIV_COMPUTE_OPENMP, "OPENMP", 0, "OpenMP", ""}, {USER_OPENSUBDIV_COMPUTE_OPENCL, "OPENCL", 0, "OpenCL", ""}, {USER_OPENSUBDIV_COMPUTE_CUDA, "CUDA", 0, "CUDA", ""}, {USER_OPENSUBDIV_COMPUTE_GLSL_TRANSFORM_FEEDBACK, "GLSL_TRANSFORM_FEEDBACK", 0, "GLSL Transform Feedback", ""}, {USER_OPENSUBDIV_COMPUTE_GLSL_COMPUTE, "GLSL_COMPUTE", 0, "GLSL Compute", ""}, {0, NULL, 0, NULL, NULL}, }; #endif const EnumPropertyItem rna_enum_preference_section_items[] = { {USER_SECTION_INTERFACE, "INTERFACE", 0, "Interface", ""}, {USER_SECTION_THEME, "THEMES", 0, "Themes", ""}, {USER_SECTION_VIEWPORT, "VIEWPORT", 0, "Viewport", ""}, {USER_SECTION_LIGHT, "LIGHTS", 0, "Lights", ""}, {USER_SECTION_EDITING, "EDITING", 0, "Editing", ""}, {USER_SECTION_ANIMATION, "ANIMATION", 0, "Animation", ""}, {0, "", 0, NULL, NULL}, {USER_SECTION_ADDONS, "ADDONS", 0, "Add-ons", ""}, #if 0 /* def WITH_USERDEF_WORKSPACES */ {0, "", 0, NULL, NULL}, {USER_SECTION_WORKSPACE_CONFIG, "WORKSPACE_CONFIG", 0, "Configuration File", ""}, {USER_SECTION_WORKSPACE_ADDONS, "WORKSPACE_ADDONS", 0, "Add-on Overrides", ""}, {USER_SECTION_WORKSPACE_KEYMAPS, "WORKSPACE_KEYMAPS", 0, "Keymap Overrides", ""}, #endif {0, "", 0, NULL, NULL}, {USER_SECTION_INPUT, "INPUT", 0, "Input", ""}, {USER_SECTION_NAVIGATION, "NAVIGATION", 0, "Navigation", ""}, {USER_SECTION_KEYMAP, "KEYMAP", 0, "Keymap", ""}, {0, "", 0, NULL, NULL}, {USER_SECTION_SYSTEM, "SYSTEM", 0, "System", ""}, {USER_SECTION_SAVE_LOAD, "SAVE_LOAD", 0, "Save & Load", ""}, {USER_SECTION_FILE_PATHS, "FILE_PATHS", 0, "File Paths", ""}, {0, "", 0, NULL, NULL}, {USER_SECTION_EXPERIMENTAL, "EXPERIMENTAL", 0, "Experimental", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem audio_device_items[] = { {0, "Null", 0, "None", "Null device - there will be no audio output"}, {0, NULL, 0, NULL, NULL}, }; const EnumPropertyItem rna_enum_navigation_mode_items[] = { {VIEW_NAVIGATION_WALK, "WALK", 0, "Walk", "Interactively walk or free navigate around the scene"}, {VIEW_NAVIGATION_FLY, "FLY", 0, "Fly", "Use fly dynamics to navigate the scene"}, {0, NULL, 0, NULL, NULL}, }; #if defined(WITH_INTERNATIONAL) || !defined(RNA_RUNTIME) static const EnumPropertyItem rna_enum_language_default_items[] = { {0, "DEFAULT", 0, "Automatic (Automatic)", "Automatically choose system's defined language if available, or fall-back to English"}, {0, NULL, 0, NULL, NULL}, }; #endif static const EnumPropertyItem rna_enum_studio_light_type_items[] = { {STUDIOLIGHT_TYPE_STUDIO, "STUDIO", 0, "Studio", ""}, {STUDIOLIGHT_TYPE_WORLD, "WORLD", 0, "World", ""}, {STUDIOLIGHT_TYPE_MATCAP, "MATCAP", 0, "MatCap", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem rna_enum_userdef_viewport_aa_items[] = { {SCE_DISPLAY_AA_OFF, "OFF", 0, "No Anti-Aliasing", "Scene will be rendering without any anti-aliasing"}, {SCE_DISPLAY_AA_FXAA, "FXAA", 0, "Single Pass Anti-Aliasing", "Scene will be rendered using a single pass anti-aliasing method (FXAA)"}, {SCE_DISPLAY_AA_SAMPLES_5, "5", 0, "5 Samples", "Scene will be rendered using 5 anti-aliasing samples"}, {SCE_DISPLAY_AA_SAMPLES_8, "8", 0, "8 Samples", "Scene will be rendered using 8 anti-aliasing samples"}, {SCE_DISPLAY_AA_SAMPLES_11, "11", 0, "11 Samples", "Scene will be rendered using 11 anti-aliasing samples"}, {SCE_DISPLAY_AA_SAMPLES_16, "16", 0, "16 Samples", "Scene will be rendered using 16 anti-aliasing samples"}, {SCE_DISPLAY_AA_SAMPLES_32, "32", 0, "32 Samples", "Scene will be rendered using 32 anti-aliasing samples"}, {0, NULL, 0, NULL, NULL}, }; #ifdef RNA_RUNTIME # include "BLI_math_vector.h" # include "DNA_object_types.h" # include "DNA_screen_types.h" # include "BKE_blender.h" # include "BKE_global.h" # include "BKE_idprop.h" # include "BKE_image.h" # include "BKE_main.h" # include "BKE_mesh_runtime.h" # include "BKE_paint.h" # include "BKE_pbvh.h" # include "BKE_preferences.h" # include "BKE_screen.h" # include "DEG_depsgraph.h" # include "GPU_capabilities.h" # include "GPU_select.h" # include "GPU_texture.h" # include "BLF_api.h" # include "BLI_path_util.h" # include "MEM_CacheLimiterC-Api.h" # include "MEM_guardedalloc.h" # include "UI_interface.h" # ifdef WITH_OPENSUBDIV # include "opensubdiv_capi.h" # endif # ifdef WITH_SDL_DYNLOAD # include "sdlew.h" # endif static void rna_userdef_version_get(PointerRNA *ptr, int *value) { UserDef *userdef = (UserDef *)ptr->data; value[0] = userdef->versionfile / 100; value[1] = userdef->versionfile % 100; value[2] = userdef->subversionfile; } /** Mark the preferences as being changed so they are saved on exit. */ # define USERDEF_TAG_DIRTY rna_userdef_is_dirty_update_impl() /** Use single function so we can more easily break-point it. */ void rna_userdef_is_dirty_update_impl(void) { /* We can't use 'ptr->data' because this update function * is used for themes and other nested data. */ if (U.runtime.is_dirty == false) { U.runtime.is_dirty = true; WM_main_add_notifier(NC_WINDOW, NULL); } } /** * Use as a fallback update handler, * never use 'ptr' unless its type is checked. */ void rna_userdef_is_dirty_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { rna_userdef_is_dirty_update_impl(); } /** Take care not to use this if we expet 'is_dirty' to be tagged. */ static void rna_userdef_ui_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_main_add_notifier(NC_WINDOW, NULL); } static void rna_userdef_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_main_add_notifier(NC_WINDOW, NULL); USERDEF_TAG_DIRTY; } static void rna_userdef_theme_update(Main *bmain, Scene *scene, PointerRNA *ptr) { /* Recreate gizmos when changing themes. */ WM_reinit_gizmomap_all(bmain); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_gizmo_update(Main *bmain, Scene *scene, PointerRNA *ptr) { WM_reinit_gizmomap_all(bmain); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_theme_update_icons(Main *bmain, Scene *scene, PointerRNA *ptr) { UI_icons_reload_internal_textures(); rna_userdef_theme_update(bmain, scene, ptr); } /* also used by buffer swap switching */ static void rna_userdef_dpi_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { /* font's are stored at each DPI level, without this we can easy load 100's of fonts */ BLF_cache_clear(); WM_main_add_notifier(NC_WINDOW, NULL); /* full redraw */ WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */ USERDEF_TAG_DIRTY; } static void rna_userdef_screen_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_main_add_notifier(NC_WINDOW, NULL); WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */ USERDEF_TAG_DIRTY; } static void rna_userdef_screen_update_header_default(Main *bmain, Scene *scene, PointerRNA *ptr) { if (U.uiflag & USER_HEADER_FROM_PREF) { for (bScreen *screen = bmain->screens.first; screen; screen = screen->id.next) { BKE_screen_header_alignment_reset(screen); } rna_userdef_screen_update(bmain, scene, ptr); } USERDEF_TAG_DIRTY; } static void rna_userdef_font_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BLF_cache_clear(); UI_reinit_font(); } static void rna_userdef_language_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BLT_lang_set(NULL); const char *uilng = BLT_lang_get(); if (STREQ(uilng, "en_US")) { U.transopts &= ~(USER_TR_IFACE | USER_TR_TOOLTIPS | USER_TR_NEWDATANAME); } else { U.transopts |= (USER_TR_IFACE | USER_TR_TOOLTIPS | USER_TR_NEWDATANAME); } USERDEF_TAG_DIRTY; } static void rna_userdef_asset_library_name_set(PointerRNA *ptr, const char *value) { bUserAssetLibrary *library = (bUserAssetLibrary *)ptr->data; BKE_preferences_asset_library_name_set(&U, library, value); } static void rna_userdef_script_autoexec_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { UserDef *userdef = (UserDef *)ptr->data; if (userdef->flag & USER_SCRIPT_AUTOEXEC_DISABLE) { G.f &= ~G_FLAG_SCRIPT_AUTOEXEC; } else { G.f |= G_FLAG_SCRIPT_AUTOEXEC; } USERDEF_TAG_DIRTY; } static void rna_userdef_load_ui_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { UserDef *userdef = (UserDef *)ptr->data; if (userdef->flag & USER_FILENOUI) { G.fileflags |= G_FILE_NO_UI; } else { G.fileflags &= ~G_FILE_NO_UI; } USERDEF_TAG_DIRTY; } static void rna_userdef_anisotropic_update(Main *bmain, Scene *scene, PointerRNA *ptr) { GPU_samplers_update(); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_gl_texture_limit_update(Main *bmain, Scene *scene, PointerRNA *ptr) { BKE_image_free_all_gputextures(bmain); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_undo_steps_set(PointerRNA *ptr, int value) { UserDef *userdef = (UserDef *)ptr->data; /* Do not allow 1 undo steps, useless and breaks undo/redo process (see T42531). */ userdef->undosteps = (value == 1) ? 2 : value; } static int rna_userdef_autokeymode_get(PointerRNA *ptr) { UserDef *userdef = (UserDef *)ptr->data; short retval = userdef->autokey_mode; if (!(userdef->autokey_mode & AUTOKEY_ON)) { retval |= AUTOKEY_ON; } return retval; } static void rna_userdef_autokeymode_set(PointerRNA *ptr, int value) { UserDef *userdef = (UserDef *)ptr->data; if (value == AUTOKEY_MODE_NORMAL) { userdef->autokey_mode |= (AUTOKEY_MODE_NORMAL - AUTOKEY_ON); userdef->autokey_mode &= ~(AUTOKEY_MODE_EDITKEYS - AUTOKEY_ON); } else if (value == AUTOKEY_MODE_EDITKEYS) { userdef->autokey_mode |= (AUTOKEY_MODE_EDITKEYS - AUTOKEY_ON); userdef->autokey_mode &= ~(AUTOKEY_MODE_NORMAL - AUTOKEY_ON); } } static void rna_userdef_anim_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_main_add_notifier(NC_SPACE | ND_SPACE_GRAPH, NULL); WM_main_add_notifier(NC_SPACE | ND_SPACE_DOPESHEET, NULL); USERDEF_TAG_DIRTY; } static void rna_userdef_tablet_api_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_init_tablet_api(); USERDEF_TAG_DIRTY; } # ifdef WITH_INPUT_NDOF static void rna_userdef_ndof_deadzone_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { UserDef *userdef = ptr->data; WM_ndof_deadzone_set(userdef->ndof_deadzone); USERDEF_TAG_DIRTY; } # endif static void rna_userdef_keyconfig_reload_update(bContext *C, Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { WM_keyconfig_reload(C); USERDEF_TAG_DIRTY; } static void rna_userdef_timecode_style_set(PointerRNA *ptr, int value) { UserDef *userdef = (UserDef *)ptr->data; int required_size = userdef->v2d_min_gridsize; /* Set the time-code style. */ userdef->timecode_style = value; /* Adjust the v2d grid-size if needed so that time-codes don't overlap * NOTE: most of these have been hand-picked to avoid overlaps while still keeping * things from getting too blown out. */ switch (value) { case USER_TIMECODE_MINIMAL: case USER_TIMECODE_SECONDS_ONLY: /* 35 is great most of the time, but not that great for full-blown */ required_size = 35; break; case USER_TIMECODE_SMPTE_MSF: required_size = 50; break; case USER_TIMECODE_SMPTE_FULL: /* the granddaddy! */ required_size = 65; break; case USER_TIMECODE_MILLISECONDS: required_size = 45; break; } if (U.v2d_min_gridsize < required_size) { U.v2d_min_gridsize = required_size; } } static int rna_UserDef_mouse_emulate_3_button_modifier_get(PointerRNA *ptr) { # if !defined(WIN32) UserDef *userdef = ptr->data; return userdef->mouse_emulate_3_button_modifier; # else UNUSED_VARS(ptr); return USER_EMU_MMB_MOD_ALT; # endif } static const EnumPropertyItem *rna_UseDef_active_section_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free) { UserDef *userdef = ptr->data; if ((userdef->flag & USER_DEVELOPER_UI) != 0) { *r_free = false; return rna_enum_preference_section_items; } EnumPropertyItem *items = NULL; int totitem = 0; for (const EnumPropertyItem *it = rna_enum_preference_section_items; it->identifier != NULL; it++) { if (it->value == USER_SECTION_EXPERIMENTAL) { continue; } RNA_enum_item_add(&items, &totitem, it); } RNA_enum_item_end(&items, &totitem); *r_free = true; return items; } static PointerRNA rna_UserDef_view_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesView, ptr->data); } static PointerRNA rna_UserDef_edit_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesEdit, ptr->data); } static PointerRNA rna_UserDef_input_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesInput, ptr->data); } static PointerRNA rna_UserDef_keymap_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesKeymap, ptr->data); } static PointerRNA rna_UserDef_filepaths_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesFilePaths, ptr->data); } static PointerRNA rna_UserDef_system_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_PreferencesSystem, ptr->data); } static void rna_UserDef_audio_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BKE_sound_init(bmain); USERDEF_TAG_DIRTY; } static void rna_Userdef_memcache_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { MEM_CacheLimiter_set_maximum(((size_t)U.memcachelimit) * 1024 * 1024); USERDEF_TAG_DIRTY; } static void rna_Userdef_disk_cache_dir_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { if (U.sequencer_disk_cache_dir[0] != '\0') { BLI_path_abs(U.sequencer_disk_cache_dir, BKE_main_blendfile_path_from_global()); BLI_path_slash_ensure(U.sequencer_disk_cache_dir); BLI_path_make_safe(U.sequencer_disk_cache_dir); } USERDEF_TAG_DIRTY; } static void rna_UserDef_weight_color_update(Main *bmain, Scene *scene, PointerRNA *ptr) { Object *ob; for (ob = bmain->objects.first; ob; ob = ob->id.next) { if (ob->mode & OB_MODE_WEIGHT_PAINT) { DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); } } rna_userdef_update(bmain, scene, ptr); } static void rna_UserDef_viewport_lights_update(Main *bmain, Scene *scene, PointerRNA *ptr) { /* If all lights are off gpu_draw resets them all, see: T27627, * so disallow them all to be disabled. */ if (U.light_param[0].flag == 0 && U.light_param[1].flag == 0 && U.light_param[2].flag == 0 && U.light_param[3].flag == 0) { SolidLight *light = ptr->data; light->flag |= 1; } WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D | NS_VIEW3D_GPU, NULL); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_autosave_update(Main *bmain, Scene *scene, PointerRNA *ptr) { wmWindowManager *wm = bmain->wm.first; if (wm) { WM_autosave_init(wm); } rna_userdef_update(bmain, scene, ptr); } # define RNA_USERDEF_EXPERIMENTAL_BOOLEAN_GET(member) \ static bool rna_userdef_experimental_##member##_get(PointerRNA *ptr) \ { \ UserDef *userdef = POINTER_OFFSET(ptr->data, -offsetof(UserDef, experimental)); \ return USER_EXPERIMENTAL_TEST(userdef, member); \ } static bAddon *rna_userdef_addon_new(void) { ListBase *addons_list = &U.addons; bAddon *addon = BKE_addon_new(); BLI_addtail(addons_list, addon); USERDEF_TAG_DIRTY; return addon; } static void rna_userdef_addon_remove(ReportList *reports, PointerRNA *addon_ptr) { ListBase *addons_list = &U.addons; bAddon *addon = addon_ptr->data; if (BLI_findindex(addons_list, addon) == -1) { BKE_report(reports, RPT_ERROR, "Add-on is no longer valid"); return; } BLI_remlink(addons_list, addon); BKE_addon_free(addon); RNA_POINTER_INVALIDATE(addon_ptr); USERDEF_TAG_DIRTY; } static bPathCompare *rna_userdef_pathcompare_new(void) { bPathCompare *path_cmp = MEM_callocN(sizeof(bPathCompare), "bPathCompare"); BLI_addtail(&U.autoexec_paths, path_cmp); USERDEF_TAG_DIRTY; return path_cmp; } static void rna_userdef_pathcompare_remove(ReportList *reports, PointerRNA *path_cmp_ptr) { bPathCompare *path_cmp = path_cmp_ptr->data; if (BLI_findindex(&U.autoexec_paths, path_cmp) == -1) { BKE_report(reports, RPT_ERROR, "Excluded path is no longer valid"); return; } BLI_freelinkN(&U.autoexec_paths, path_cmp); RNA_POINTER_INVALIDATE(path_cmp_ptr); USERDEF_TAG_DIRTY; } static void rna_userdef_temp_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BKE_tempdir_init(U.tempdir); USERDEF_TAG_DIRTY; } static void rna_userdef_text_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BLF_cache_clear(); UI_reinit_font(); WM_main_add_notifier(NC_WINDOW, NULL); USERDEF_TAG_DIRTY; } static PointerRNA rna_Theme_space_generic_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_ThemeSpaceGeneric, ptr->data); } static PointerRNA rna_Theme_gradient_colors_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_ThemeGradientColors, ptr->data); } static PointerRNA rna_Theme_space_gradient_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_ThemeSpaceGradient, ptr->data); } static PointerRNA rna_Theme_space_list_generic_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_ThemeSpaceListGeneric, ptr->data); } # ifdef WITH_OPENSUBDIV static const EnumPropertyItem *rna_userdef_opensubdiv_compute_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) { EnumPropertyItem *item = NULL; int totitem = 0; int evaluators = openSubdiv_getAvailableEvaluators(); RNA_enum_items_add_value( &item, &totitem, opensubdiv_compute_type_items, USER_OPENSUBDIV_COMPUTE_NONE); # define APPEND_COMPUTE(compute) \ if (evaluators & OPENSUBDIV_EVALUATOR_##compute) { \ RNA_enum_items_add_value( \ &item, &totitem, opensubdiv_compute_type_items, USER_OPENSUBDIV_COMPUTE_##compute); \ } \ ((void)0) APPEND_COMPUTE(CPU); APPEND_COMPUTE(OPENMP); APPEND_COMPUTE(OPENCL); APPEND_COMPUTE(CUDA); APPEND_COMPUTE(GLSL_TRANSFORM_FEEDBACK); APPEND_COMPUTE(GLSL_COMPUTE); # undef APPEND_COMPUTE RNA_enum_item_end(&item, &totitem); *r_free = true; return item; } static void rna_userdef_opensubdiv_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { Object *object; for (object = bmain->objects.first; object; object = object->id.next) { DEG_id_tag_update(&object->id, ID_RECALC_TRANSFORM); } USERDEF_TAG_DIRTY; } # endif static const EnumPropertyItem *rna_userdef_audio_device_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) { int index = 0; int totitem = 0; EnumPropertyItem *item = NULL; int i; char **names = BKE_sound_get_device_names(); for (i = 0; names[i]; i++) { EnumPropertyItem new_item = {i, names[i], 0, names[i], names[i]}; RNA_enum_item_add(&item, &totitem, &new_item); } # ifndef NDEBUG if (i == 0) { EnumPropertyItem new_item = {i, "SOUND_NONE", 0, "No Sound", ""}; RNA_enum_item_add(&item, &totitem, &new_item); } # endif /* may be unused */ UNUSED_VARS(index, audio_device_items); RNA_enum_item_end(&item, &totitem); *r_free = true; return item; } # ifdef WITH_INTERNATIONAL static const EnumPropertyItem *rna_lang_enum_properties_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *UNUSED(r_free)) { const EnumPropertyItem *items = BLT_lang_RNA_enum_properties(); if (items == NULL) { items = rna_enum_language_default_items; } return items; } # endif static IDProperty *rna_AddonPref_idprops(PointerRNA *ptr, bool create) { if (create && !ptr->data) { IDPropertyTemplate val = {0}; ptr->data = IDP_New(IDP_GROUP, &val, "RNA_AddonPreferences group"); } return ptr->data; } static PointerRNA rna_Addon_preferences_get(PointerRNA *ptr) { bAddon *addon = (bAddon *)ptr->data; bAddonPrefType *apt = BKE_addon_pref_type_find(addon->module, true); if (apt) { if (addon->prop == NULL) { IDPropertyTemplate val = {0}; addon->prop = IDP_New(IDP_GROUP, &val, addon->module); /* name is unimportant */ } return rna_pointer_inherit_refine(ptr, apt->rna_ext.srna, addon->prop); } else { return PointerRNA_NULL; } } static void rna_AddonPref_unregister(Main *UNUSED(bmain), StructRNA *type) { bAddonPrefType *apt = RNA_struct_blender_type_get(type); if (!apt) { return; } RNA_struct_free_extension(type, &apt->rna_ext); RNA_struct_free(&BLENDER_RNA, type); BKE_addon_pref_type_remove(apt); /* update while blender is running */ WM_main_add_notifier(NC_WINDOW, NULL); } static StructRNA *rna_AddonPref_register(Main *bmain, ReportList *reports, void *data, const char *identifier, StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free) { bAddonPrefType *apt, dummy_apt = {{'\0'}}; bAddon dummy_addon = {NULL}; PointerRNA dummy_ptr; // int have_function[1]; /* setup dummy addon-pref & addon-pref type to store static properties in */ RNA_pointer_create(NULL, &RNA_AddonPreferences, &dummy_addon, &dummy_ptr); /* validate the python class */ if (validate(&dummy_ptr, data, NULL /* have_function */) != 0) { return NULL; } BLI_strncpy(dummy_apt.idname, dummy_addon.module, sizeof(dummy_apt.idname)); if (strlen(identifier) >= sizeof(dummy_apt.idname)) { BKE_reportf(reports, RPT_ERROR, "Registering add-on preferences class: '%s' is too long, maximum length is %d", identifier, (int)sizeof(dummy_apt.idname)); return NULL; } /* check if we have registered this addon-pref type before, and remove it */ apt = BKE_addon_pref_type_find(dummy_addon.module, true); if (apt && apt->rna_ext.srna) { rna_AddonPref_unregister(bmain, apt->rna_ext.srna); } /* create a new addon-pref type */ apt = MEM_mallocN(sizeof(bAddonPrefType), "addonpreftype"); memcpy(apt, &dummy_apt, sizeof(dummy_apt)); BKE_addon_pref_type_add(apt); apt->rna_ext.srna = RNA_def_struct_ptr(&BLENDER_RNA, identifier, &RNA_AddonPreferences); apt->rna_ext.data = data; apt->rna_ext.call = call; apt->rna_ext.free = free; RNA_struct_blender_type_set(apt->rna_ext.srna, apt); // apt->draw = (have_function[0]) ? header_draw : NULL; /* update while blender is running */ WM_main_add_notifier(NC_WINDOW, NULL); return apt->rna_ext.srna; } /* placeholder, doesn't do anything useful yet */ static StructRNA *rna_AddonPref_refine(PointerRNA *ptr) { return (ptr->type) ? ptr->type : &RNA_AddonPreferences; } static float rna_ThemeUI_roundness_get(PointerRNA *ptr) { /* Remap from relative radius to 0..1 range. */ uiWidgetColors *tui = (uiWidgetColors *)ptr->data; return tui->roundness * 2.0f; } static void rna_ThemeUI_roundness_set(PointerRNA *ptr, float value) { uiWidgetColors *tui = (uiWidgetColors *)ptr->data; tui->roundness = value * 0.5f; } /* Studio Light */ static void rna_UserDef_studiolight_begin(CollectionPropertyIterator *iter, PointerRNA *UNUSED(ptr)) { rna_iterator_listbase_begin(iter, BKE_studiolight_listbase(), NULL); } static void rna_StudioLights_refresh(UserDef *UNUSED(userdef)) { BKE_studiolight_refresh(); } static void rna_StudioLights_remove(UserDef *UNUSED(userdef), StudioLight *studio_light) { BKE_studiolight_remove(studio_light); } static StudioLight *rna_StudioLights_load(UserDef *UNUSED(userdef), const char *path, int type) { return BKE_studiolight_load(path, type); } /* TODO: Make it accept arguments. */ static StudioLight *rna_StudioLights_new(UserDef *userdef, const char *name) { return BKE_studiolight_create(name, userdef->light_param, userdef->light_ambient); } /* StudioLight.name */ static void rna_UserDef_studiolight_name_get(PointerRNA *ptr, char *value) { StudioLight *sl = (StudioLight *)ptr->data; BLI_strncpy(value, sl->name, FILE_MAXFILE); } static int rna_UserDef_studiolight_name_length(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return strlen(sl->name); } /* StudioLight.path */ static void rna_UserDef_studiolight_path_get(PointerRNA *ptr, char *value) { StudioLight *sl = (StudioLight *)ptr->data; BLI_strncpy(value, sl->path, FILE_MAX); } static int rna_UserDef_studiolight_path_length(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return strlen(sl->path); } /* StudioLight.path_irr_cache */ static void rna_UserDef_studiolight_path_irr_cache_get(PointerRNA *ptr, char *value) { StudioLight *sl = (StudioLight *)ptr->data; if (sl->path_irr_cache) { BLI_strncpy(value, sl->path_irr_cache, FILE_MAX); } else { value[0] = '\0'; } } static int rna_UserDef_studiolight_path_irr_cache_length(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; if (sl->path_irr_cache) { return strlen(sl->path_irr_cache); } return 0; } /* StudioLight.path_sh_cache */ static void rna_UserDef_studiolight_path_sh_cache_get(PointerRNA *ptr, char *value) { StudioLight *sl = (StudioLight *)ptr->data; if (sl->path_sh_cache) { BLI_strncpy(value, sl->path_sh_cache, FILE_MAX); } else { value[0] = '\0'; } } static int rna_UserDef_studiolight_path_sh_cache_length(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; if (sl->path_sh_cache) { return strlen(sl->path_sh_cache); } return 0; } /* StudioLight.index */ static int rna_UserDef_studiolight_index_get(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return sl->index; } /* StudioLight.is_user_defined */ static bool rna_UserDef_studiolight_is_user_defined_get(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return (sl->flag & STUDIOLIGHT_USER_DEFINED) != 0; } /* StudioLight.is_user_defined */ static bool rna_UserDef_studiolight_has_specular_highlight_pass_get(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return sl->flag & STUDIOLIGHT_SPECULAR_HIGHLIGHT_PASS; } /* StudioLight.type */ static int rna_UserDef_studiolight_type_get(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return sl->flag & STUDIOLIGHT_FLAG_ORIENTATIONS; } static void rna_UserDef_studiolight_spherical_harmonics_coefficients_get(PointerRNA *ptr, float *values) { StudioLight *sl = (StudioLight *)ptr->data; float *value = values; for (int i = 0; i < STUDIOLIGHT_SH_EFFECTIVE_COEFS_LEN; i++) { copy_v3_v3(value, sl->spherical_harmonics_coefs[i]); value += 3; } } /* StudioLight.solid_lights */ static void rna_UserDef_studiolight_solid_lights_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; rna_iterator_array_begin(iter, sl->light, sizeof(*sl->light), ARRAY_SIZE(sl->light), 0, NULL); } static int rna_UserDef_studiolight_solid_lights_length(PointerRNA *ptr) { StudioLight *sl = (StudioLight *)ptr->data; return ARRAY_SIZE(sl->light); } /* StudioLight.light_ambient */ static void rna_UserDef_studiolight_light_ambient_get(PointerRNA *ptr, float *values) { StudioLight *sl = (StudioLight *)ptr->data; copy_v3_v3(values, sl->light_ambient); } int rna_show_statusbar_vram_editable(struct PointerRNA *UNUSED(ptr), const char **UNUSED(r_info)) { return GPU_mem_stats_supported() ? PROP_EDITABLE : 0; } #else # define USERDEF_TAG_DIRTY_PROPERTY_UPDATE_ENABLE \ RNA_define_fallback_property_update(0, "rna_userdef_is_dirty_update") # define USERDEF_TAG_DIRTY_PROPERTY_UPDATE_DISABLE RNA_define_fallback_property_update(0, NULL) /* TODO(sergey): This technically belongs to blenlib, but we don't link * makesrna against it. */ /* Get maximum addressable memory in megabytes, */ static size_t max_memory_in_megabytes(void) { /* Maximum addressable bytes on this platform. */ const size_t limit_bytes = (((size_t)1) << ((sizeof(size_t[8])) - 1)); /* Convert it to megabytes and return. */ return (limit_bytes >> 20); } /* Same as above, but clipped to int capacity. */ static int max_memory_in_megabytes_int(void) { const size_t limit_megabytes = max_memory_in_megabytes(); /* NOTE: The result will fit into integer. */ return (int)min_zz(limit_megabytes, (size_t)INT_MAX); } static void rna_def_userdef_theme_ui_font_style(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; static const EnumPropertyItem font_kerning_style[] = { {0, "UNFITTED", 0, "Unfitted", "Use scaled but un-grid-fitted kerning distances"}, {1, "FITTED", 0, "Fitted", "Use scaled and grid-fitted kerning distances"}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "ThemeFontStyle", NULL); RNA_def_struct_sdna(srna, "uiFontStyle"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Font Style", "Theme settings for Font"); prop = RNA_def_property(srna, "points", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 6, 24); RNA_def_property_ui_text(prop, "Points", "Font size in points"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "font_kerning_style", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "kerning"); RNA_def_property_enum_items(prop, font_kerning_style); RNA_def_property_ui_text(prop, "Kerning Style", "Which style to use for font kerning"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadow", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 0, 5); RNA_def_property_ui_text(prop, "Shadow Size", "Shadow size (0, 3 and 5 supported)"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadow_offset_x", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "shadx"); RNA_def_property_range(prop, -10, 10); RNA_def_property_ui_text(prop, "Shadow X Offset", "Shadow offset in pixels"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadow_offset_y", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "shady"); RNA_def_property_range(prop, -10, 10); RNA_def_property_ui_text(prop, "Shadow Y Offset", "Shadow offset in pixels"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadow_alpha", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "shadowalpha"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Shadow Alpha", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadow_value", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "shadowcolor"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Shadow Brightness", "Shadow color in gray value"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_ui_style(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; rna_def_userdef_theme_ui_font_style(brna); srna = RNA_def_struct(brna, "ThemeStyle", NULL); RNA_def_struct_sdna(srna, "uiStyle"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Style", "Theme settings for style sets"); prop = RNA_def_property(srna, "panel_title", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "paneltitle"); RNA_def_property_struct_type(prop, "ThemeFontStyle"); RNA_def_property_ui_text(prop, "Panel Title Font", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "widget_label", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "widgetlabel"); RNA_def_property_struct_type(prop, "ThemeFontStyle"); RNA_def_property_ui_text(prop, "Widget Label Style", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "widget", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "widget"); RNA_def_property_struct_type(prop, "ThemeFontStyle"); RNA_def_property_ui_text(prop, "Widget Style", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_ui_wcol(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeWidgetColors", NULL); RNA_def_struct_sdna(srna, "uiWidgetColors"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Widget Color Set", "Theme settings for widget color sets"); prop = RNA_def_property(srna, "outline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Outline", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Inner", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Inner Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "item", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Item", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Text Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "show_shaded", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "shaded", 1); RNA_def_property_ui_text(prop, "Shaded", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadetop", PROP_INT, PROP_NONE); RNA_def_property_range(prop, -100, 100); RNA_def_property_ui_text(prop, "Shade Top", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shadedown", PROP_INT, PROP_NONE); RNA_def_property_range(prop, -100, 100); RNA_def_property_ui_text(prop, "Shade Down", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "roundness", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_funcs( prop, "rna_ThemeUI_roundness_get", "rna_ThemeUI_roundness_set", NULL); RNA_def_property_ui_text(prop, "Roundness", "Amount of edge rounding"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_ui_wcol_state(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeWidgetStateColors", NULL); RNA_def_struct_sdna(srna, "uiWidgetStateColors"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text( srna, "Theme Widget State Color", "Theme settings for widget state colors"); prop = RNA_def_property(srna, "inner_anim", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Animated", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_anim_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Animated Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_key", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Keyframe", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_key_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Keyframe Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_driven", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Driven", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_driven_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Driven Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_overridden", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Overridden", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_overridden_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Overridden Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_changed", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Changed", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "inner_changed_sel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Changed Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "blend", PROP_FLOAT, PROP_FACTOR); RNA_def_property_ui_text(prop, "Blend", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_ui_panel(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemePanelColors", NULL); RNA_def_struct_sdna(srna, "uiPanelColors"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Panel Color", "Theme settings for panel colors"); prop = RNA_def_property(srna, "header", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_ui_text(prop, "Header", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_ui_text(prop, "Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "sub_back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_ui_text(prop, "Sub Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static const EnumPropertyItem rna_enum_userdef_theme_background_types_items[] = { {TH_BACKGROUND_SINGLE_COLOR, "SINGLE_COLOR", 0, "Single Color", "Use a solid color as viewport background"}, {TH_BACKGROUND_GRADIENT_LINEAR, "LINEAR", 0, "Linear Gradient", "Use a screen space vertical linear gradient as viewport background"}, {TH_BACKGROUND_GRADIENT_RADIAL, "RADIAL", 0, "Vignette", "Use a radial gradient as viewport background"}, {0, NULL, 0, NULL, NULL}, }; static void rna_def_userdef_theme_ui_gradient(BlenderRNA *brna) { /* Fake struct, keep this for compatible theme presets. */ StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeGradientColors", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text( srna, "Theme Background Color", "Theme settings for background colors and gradient"); prop = RNA_def_property(srna, "background_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "background_type"); RNA_def_property_enum_items(prop, rna_enum_userdef_theme_background_types_items); RNA_def_property_ui_text(prop, "Background Type", "Type of background in the 3D viewport"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "high_gradient", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "back"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gradient High/Off", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gradient", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "back_grad"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gradient Low", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_ui(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; rna_def_userdef_theme_ui_wcol(brna); rna_def_userdef_theme_ui_wcol_state(brna); rna_def_userdef_theme_ui_panel(brna); rna_def_userdef_theme_ui_gradient(brna); srna = RNA_def_struct(brna, "ThemeUserInterface", NULL); RNA_def_struct_sdna(srna, "ThemeUI"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text( srna, "Theme User Interface", "Theme settings for user interface elements"); prop = RNA_def_property(srna, "wcol_regular", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Regular Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_tool", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Tool Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_toolbar_item", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Toolbar Item Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_radio", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Radio Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_text", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Text Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_option", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Option Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_toggle", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Toggle Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_num", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Number Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_numslider", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Slider Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_box", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Box Backdrop Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_menu", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Menu Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_pulldown", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Pulldown Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_menu_back", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Menu Backdrop Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_pie_menu", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Pie Menu Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_tooltip", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Tooltip Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_menu_item", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Menu Item Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_scroll", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Scroll Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_progress", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Progress Bar Widget Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_list_item", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "List Item Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_state", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "State Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wcol_tab", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Tab Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "menu_shadow_fac", PROP_FLOAT, PROP_FACTOR); RNA_def_property_ui_text(prop, "Menu Shadow Strength", "Blending factor for menu shadows"); RNA_def_property_range(prop, 0.01f, 1.0f); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "menu_shadow_width", PROP_INT, PROP_PIXEL); RNA_def_property_ui_text( prop, "Menu Shadow Width", "Width of menu shadows, set to zero to disable"); RNA_def_property_range(prop, 0.0f, 24.0f); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_alpha", PROP_FLOAT, PROP_FACTOR); RNA_def_property_ui_text( prop, "Icon Alpha", "Transparency of icons in the interface, to reduce contrast"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_saturation", PROP_FLOAT, PROP_FACTOR); RNA_def_property_ui_text(prop, "Icon Saturation", "Saturation of icons in the interface"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "widget_emboss", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "widget_emboss"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text( prop, "Widget Emboss", "Color of the 1px shadow line underlying widgets"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "editor_outline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "editor_outline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Editor Outline", "Color of the outline of the editors and their round corners"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "widget_text_cursor", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "widget_text_cursor"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Text Cursor", "Color of the interface widgets text insertion cursor (caret)"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Transparent Grid */ prop = RNA_def_property(srna, "transparent_checker_primary", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "transparent_checker_primary"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Primary Color", "Primary color of checkerboard pattern indicating transparent areas"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "transparent_checker_secondary", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "transparent_checker_secondary"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Secondary Color", "Secondary color of checkerboard pattern indicating transparent areas"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "transparent_checker_size", PROP_INT, PROP_PIXEL); RNA_def_property_ui_text( prop, "Checkerboard Size", "Size of checkerboard pattern indicating transparent areas"); RNA_def_property_range(prop, 2, 48); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* axis */ prop = RNA_def_property(srna, "axis_x", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "xaxis"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "X Axis", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "axis_y", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "yaxis"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Y Axis", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "axis_z", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "zaxis"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Z Axis", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Generic gizmo colors. */ prop = RNA_def_property(srna, "gizmo_hi", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_hi"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gizmo_primary", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_primary"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo Primary", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gizmo_secondary", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_secondary"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo Secondary", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gizmo_view_align", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_view_align"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo View Align", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gizmo_a", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_a"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo A", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gizmo_b", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gizmo_b"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Gizmo B", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Icon colors. */ prop = RNA_def_property(srna, "icon_scene", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_scene"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scene", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_collection", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_collection"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Collection", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_object", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_object"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Object", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_object_data", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_object_data"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Object Data", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_modifier", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_modifier"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Modifier", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_shading", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_shading"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Shading", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_folder", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "icon_folder"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "File Folders", "Color of folders in the file browser"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "icon_border_intensity", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "icon_border_intensity"); RNA_def_property_ui_text( prop, "Icon Border", "Control the intensity of the border around themes icons"); RNA_def_property_ui_range(prop, 0.0, 1.0, 0.1, 2); RNA_def_property_update(prop, 0, "rna_userdef_theme_update_icons"); } static void rna_def_userdef_theme_space_common(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "title", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Title", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text_hi", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Text Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* header */ prop = RNA_def_property(srna, "header", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Header", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "header_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Header Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "header_text_hi", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Header Text Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* panel settings */ prop = RNA_def_property(srna, "panelcolors", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Panel Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* buttons */ /* if (! ELEM(spacetype, SPACE_PROPERTIES, SPACE_OUTLINER)) { */ prop = RNA_def_property(srna, "button", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Region Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "button_title", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Region Text Titles", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "button_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Region Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "button_text_hi", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Region Text Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "navigation_bar", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Navigation Bar Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "execution_buts", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Execution Region Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* tabs */ prop = RNA_def_property(srna, "tab_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Tab Active", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "tab_inactive", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Tab Inactive", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "tab_back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Tab Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "tab_outline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Tab Outline", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* } */ } static void rna_def_userdef_theme_space_gradient(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeSpaceGradient", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_ui_text(srna, "Theme Space Settings", ""); /* gradient/background settings */ prop = RNA_def_property(srna, "gradients", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "ThemeGradientColors"); RNA_def_property_pointer_funcs(prop, "rna_Theme_gradient_colors_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Gradient Colors", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_space_common(srna); } static void rna_def_userdef_theme_space_generic(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeSpaceGeneric", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_ui_text(srna, "Theme Space Settings", ""); prop = RNA_def_property(srna, "back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Window Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_space_common(srna); } /* list / channels */ static void rna_def_userdef_theme_space_list_generic(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeSpaceListGeneric", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_ui_text(srna, "Theme Space List Settings", ""); prop = RNA_def_property(srna, "list", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Source List", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "list_title", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Source List Title", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "list_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Source List Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "list_text_hi", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Source List Text Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_spaces_main(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "space", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "ThemeSpaceGeneric"); RNA_def_property_pointer_funcs(prop, "rna_Theme_space_generic_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Theme Space", "Settings for space"); } static void rna_def_userdef_theme_spaces_gradient(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "space", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "ThemeSpaceGradient"); RNA_def_property_pointer_funcs(prop, "rna_Theme_space_gradient_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Theme Space", "Settings for space"); } static void rna_def_userdef_theme_spaces_list_main(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "space_list", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "ThemeSpaceListGeneric"); RNA_def_property_pointer_funcs(prop, "rna_Theme_space_list_generic_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Theme Space List", "Settings for space list"); } static void rna_def_userdef_theme_spaces_vertex(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "vertex", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vertex", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vertex Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Vertex", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_size", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 32); RNA_def_property_ui_text(prop, "Vertex Size", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_bevel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vertex Bevel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_unreferenced", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vertex Group Unreferenced", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_spaces_edge(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "edge_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_seam", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Seam", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_sharp", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Sharp", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_crease", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Crease", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_bevel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Bevel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_facesel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge UV Face Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "freestyle_edge_mark", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Freestyle Edge Mark", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_spaces_face(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "face", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Face", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "face_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Face Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "face_dot", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Face Dot Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "facedot_size", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 10); RNA_def_property_ui_text(prop, "Face Dot Size", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "freestyle_face_mark", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Freestyle Face Mark", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "face_back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Face Orientation Back", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "face_front", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Face Orientation Front", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_spaces_paint_curves(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "paint_curve_handle", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Paint Curve Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "paint_curve_pivot", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Paint Curve Pivot", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_spaces_curves( StructRNA *srna, bool incl_nurbs, bool incl_lastsel, bool incl_vector, bool incl_verthandle) { PropertyRNA *prop; if (incl_nurbs) { prop = RNA_def_property(srna, "nurb_uline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nurb_uline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "NURBS U Lines", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "nurb_vline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nurb_vline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "NURBS V Lines", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "nurb_sel_uline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nurb_sel_uline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "NURBS Active U Lines", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "nurb_sel_vline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nurb_sel_vline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "NURBS Active V Lines", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "act_spline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "act_spline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Spline", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } prop = RNA_def_property(srna, "handle_free", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_free"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Free Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_auto", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_auto"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Auto Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); if (incl_vector) { prop = RNA_def_property(srna, "handle_vect", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_vect"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vector Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_sel_vect", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_sel_vect"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vector Handle Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } prop = RNA_def_property(srna, "handle_align", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_align"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Align Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_sel_free", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_sel_free"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Free Handle Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_sel_auto", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_sel_auto"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Auto Handle Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_sel_align", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_sel_align"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Align Handle Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); if (!incl_nurbs) { /* assume that when nurbs are off, this is for 2D (i.e. anim) editors */ prop = RNA_def_property(srna, "handle_auto_clamped", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_auto_clamped"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Auto-Clamped Handle", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_sel_auto_clamped", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "handle_sel_auto_clamped"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Auto-Clamped Handle Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } if (incl_lastsel) { prop = RNA_def_property(srna, "lastsel_point", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "lastsel_point"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Last Selected Point", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } if (incl_verthandle) { prop = RNA_def_property(srna, "handle_vertex", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Handle Vertex", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_vertex_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Handle Vertex Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "handle_vertex_size", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 100); RNA_def_property_ui_text(prop, "Handle Vertex Size", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } } static void rna_def_userdef_theme_spaces_gpencil(StructRNA *srna) { PropertyRNA *prop; prop = RNA_def_property(srna, "gp_vertex", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grease Pencil Vertex", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gp_vertex_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grease Pencil Vertex Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "gp_vertex_size", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 10); RNA_def_property_ui_text(prop, "Grease Pencil Vertex Size", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_view3d(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_view3d */ srna = RNA_def_struct(brna, "ThemeView3D", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme 3D View", "Theme settings for the 3D View"); rna_def_userdef_theme_spaces_gradient(srna); /* General Viewport options */ prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "clipping_border_3d", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Clipping Border", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Wire", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire_edit", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Wire Edit", "Color for wireframe when in edit mode, but edge selection is active"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Grease Pencil */ rna_def_userdef_theme_spaces_gpencil(srna); prop = RNA_def_property(srna, "text_grease_pencil", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "time_gp_keyframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Grease Pencil Keyframe", "Color for indicating Grease Pencil keyframes"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Object specific options */ prop = RNA_def_property(srna, "object_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Object Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "object_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "active"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Object", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text_keyframe", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "time_keyframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Object Keyframe", "Color for indicating Object keyframes"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Object type options */ prop = RNA_def_property(srna, "camera", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Camera", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "empty", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Empty", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "light", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "lamp"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Light", ""); RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_LIGHT); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "speaker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Speaker", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* Mesh Object specific */ rna_def_userdef_theme_spaces_vertex(srna); rna_def_userdef_theme_spaces_edge(srna); rna_def_userdef_theme_spaces_face(srna); /* Mesh Object specific curves*/ rna_def_userdef_theme_spaces_curves(srna, true, true, true, false); prop = RNA_def_property(srna, "extra_edge_len", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Length Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "extra_edge_angle", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Angle Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "extra_face_angle", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Face Angle Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "extra_face_area", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Face Area Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "editmesh_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Active Vertex/Edge/Face", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Face Normal", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vertex_normal", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vertex Normal", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "split_normal", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "loop_normal"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Split Normal", ""); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* Armature Object specific */ prop = RNA_def_property(srna, "bone_pose", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Bone Pose", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "bone_pose_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Bone Pose Active", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "bone_solid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Bone Solid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "bone_locked_weight", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text( prop, "Bone Locked Weight", "Shade for bones corresponding to a locked weight group during painting"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* misc */ prop = RNA_def_property(srna, "bundle_solid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "bundle_solid"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Bundle Solid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "camera_path", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "camera_path"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Camera Path", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "skin_root", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Skin Root", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "view_overlay", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "View Overlay", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "transform", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Transform", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_paint_curves(srna); prop = RNA_def_property(srna, "outline_width", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 5); RNA_def_property_ui_text(prop, "Outline Width", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "object_origin_size", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "obcenter_dia"); RNA_def_property_range(prop, 4, 10); RNA_def_property_ui_text( prop, "Object Origin Size", "Diameter in Pixels for Object/Light origin display"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_graph(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_graph */ srna = RNA_def_struct(brna, "ThemeGraphEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Graph Editor", "Theme settings for the graph editor"); rna_def_userdef_theme_spaces_main(srna); rna_def_userdef_theme_spaces_list_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_scrub_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scrubbing/Markers Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "window_sliders", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade1"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Window Sliders", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "channels_region", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade2"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Channels Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "dopesheet_channel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_channel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Dope Sheet Channel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "dopesheet_subchannel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_subchannel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Dope Sheet Sub-Channel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "channel_group", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "group"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Channel Group", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_channels_group", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "group_active"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Channel Group", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_range", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_preview_range"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Preview Range", "Color of preview range overlay"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_vertex(srna); rna_def_userdef_theme_spaces_curves(srna, false, true, true, true); } static void rna_def_userdef_theme_space_file(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_file */ srna = RNA_def_struct(brna, "ThemeFileBrowser", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme File Browser", "Theme settings for the File Browser"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "selected_file", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "hilite"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected File", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "row_alternate", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Alternate Rows", "Overlay color on every other row"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_outliner(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_outliner */ srna = RNA_def_struct(brna, "ThemeOutliner", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Outliner", "Theme settings for the Outliner"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "match", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Filter Match", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "selected_highlight", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Highlight", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "selected_object", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Objects", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_object", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Object", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edited_object", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Edited Object", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "row_alternate", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Alternate Rows", "Overlay color on every other row"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_userpref(BlenderRNA *brna) { StructRNA *srna; /* space_userpref */ srna = RNA_def_struct(brna, "ThemePreferences", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Preferences", "Theme settings for the Blender Preferences"); rna_def_userdef_theme_spaces_main(srna); } static void rna_def_userdef_theme_space_console(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_console */ srna = RNA_def_struct(brna, "ThemeConsole", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Console", "Theme settings for the Console"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "line_output", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_output"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Output", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "line_input", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_input"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Input", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "line_info", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_info"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Info", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "line_error", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_error"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Error", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "cursor", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_cursor"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Cursor", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_select"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Selection", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_info(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_info */ srna = RNA_def_struct(brna, "ThemeInfo", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Info", "Theme settings for Info"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "info_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Line Background", "Background color of selected line"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_selected_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Line Text Color", "Text color of selected line"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_error", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Error Icon Background", "Background color of Error icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_error_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Error Icon Foreground", "Foreground color of Error icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_warning", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Warning Icon Background", "Background color of Warning icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_warning_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Warning Icon Foreground", "Foreground color of Warning icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_info", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Info Icon Background", "Background color of Info icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_info_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Info Icon Foreground", "Foreground color of Info icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_debug", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Debug Icon Background", "Background color of Debug icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_debug_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Debug Icon Foreground", "Foreground color of Debug icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_property", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Property Icon Background", "Background color of Property icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_property_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Property Icon Foreground", "Foreground color of Property icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_operator", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Operator Icon Background", "Background color of Operator icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "info_operator_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Operator Icon Foreground", "Foreground color of Operator icon"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_text(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_text */ srna = RNA_def_struct(brna, "ThemeTextEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Text Editor", "Theme settings for the Text Editor"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "line_numbers", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "line_numbers"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Numbers", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "line_numbers_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "grid"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Line Numbers Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); /* no longer used */ # if 0 prop = RNA_def_property(srna, "scroll_bar", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade1"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Scroll Bar", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); # endif prop = RNA_def_property(srna, "selected_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade2"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "cursor", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "hilite"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Cursor", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_builtin", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxb"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Built-in", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_symbols", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxs"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Symbols", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_special", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxv"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Special", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_preprocessor", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxd"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax PreProcessor", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_reserved", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxr"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Reserved", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_comment", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxc"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Comment", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_string", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxl"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax String", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "syntax_numbers", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxn"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Syntax Numbers", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_node(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_node */ srna = RNA_def_struct(brna, "ThemeNodeEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Node Editor", "Theme settings for the Node Editor"); rna_def_userdef_theme_spaces_main(srna); rna_def_userdef_theme_spaces_list_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "node_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Node Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "node_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "active"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "wire"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Wires", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire_inner", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxr"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Wire Color", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "edge_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Wire Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "selected_text", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade2"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "node_backdrop", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxl"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Node Backdrop", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "converter_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxv"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Converter Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "color_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxb"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Color Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "group_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxc"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Group Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "group_socket_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "console_output"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Group Socket Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "movie"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Frame Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "matte_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxs"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Matte Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "distor_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxd"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Distort Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "noodle_curving", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "noodle_curving"); RNA_def_property_int_default(prop, 5); RNA_def_property_range(prop, 0, 10); RNA_def_property_ui_text(prop, "Noodle Curving", "Curving of the noodle"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "grid_levels", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "grid_levels"); RNA_def_property_int_default(prop, 2); RNA_def_property_range(prop, 0, 2); RNA_def_property_ui_text( prop, "Grid Levels", "Amount of grid lines displayed in the background"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "input_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "syntaxn"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Input Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "output_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_output"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Output Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "filter_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_filter"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Filter Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "vector_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_vector"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Vector Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "texture_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_texture"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Texture Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "shader_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_shader"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Shader Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "script_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_script"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Script Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "pattern_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_pattern"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Pattern Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "layout_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_layout"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Layout Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "geometry_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_geometry"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Geometry Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "attribute_node", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nodeclass_attribute"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Attribute Node", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_buts(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_buts */ srna = RNA_def_struct(brna, "ThemeProperties", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Properties", "Theme settings for the Properties"); prop = RNA_def_property(srna, "match", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Search Match", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_main(srna); } static void rna_def_userdef_theme_space_image(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_image */ srna = RNA_def_struct(brna, "ThemeImageEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Image Editor", "Theme settings for the Image Editor"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_vertex(srna); rna_def_userdef_theme_spaces_face(srna); prop = RNA_def_property(srna, "editmesh_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Active Vertex/Edge/Face", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "wire_edit", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Wire Edit", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "edge_select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Edge Select", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "scope_back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_back"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scope Region Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_face", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_face"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Face", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_edge", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_edge"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Edge", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_vert", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_vert"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Vertex", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_stitchable", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_stitchable"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Stitchable", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_unstitchable", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_unstitchable"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Unstitchable", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_stitch_active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_stitch_active"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Stitch Preview Active Island", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "uv_shadow", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "uv_shadow"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Texture paint/Modifier UVs", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatabg", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatabg"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatatext", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatatext"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_curves(srna, false, false, false, true); rna_def_userdef_theme_spaces_paint_curves(srna); } static void rna_def_userdef_theme_space_seq(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_seq */ srna = RNA_def_struct(brna, "ThemeSequenceEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Sequence Editor", "Theme settings for the Sequence Editor"); rna_def_userdef_theme_spaces_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "window_sliders", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade1"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Window Sliders", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "movie_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "movie"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Movie Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "movieclip_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "movieclip"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Clip Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "image_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "image"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Image Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "scene_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "scene"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Scene Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "audio_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "audio"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Audio Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "effect_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "effect"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Effect Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "color_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Color Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "meta_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "meta"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Meta Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "mask_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "mask"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Mask Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "text_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Text Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Strip", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "selected_strip", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Strips", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_scrub_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scrubbing/Markers Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "vertex_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Keyframe", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "draw_action", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "bone_pose"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Draw Action", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_back", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "preview_back"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Preview Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatabg", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatabg"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatatext", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatatext"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_range", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_preview_range"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Preview Range", "Color of preview range overlay"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "row_alternate", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Alternate Rows", "Overlay color on every other row"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_action(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_action */ srna = RNA_def_struct(brna, "ThemeDopeSheet", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Dope Sheet", "Theme settings for the Dope Sheet"); rna_def_userdef_theme_spaces_main(srna); rna_def_userdef_theme_spaces_list_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_scrub_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scrubbing/Markers Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "value_sliders", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "face"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Value Sliders", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "view_sliders", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade1"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "View Sliders", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "dopesheet_channel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_channel"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Dope Sheet Channel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "dopesheet_subchannel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_subchannel"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Dope Sheet Sub-Channel", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "channels", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade2"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Channels", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "channels_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "hilite"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Channels Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "channel_group", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "group"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Channel Group", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_channels_group", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "group_active"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Active Channel Group", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "long_key", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Long Key", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "long_key_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip_select"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Long Key Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_keyframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Keyframe", "Color of Keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_keyframe_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Keyframe Selected", "Color of selected keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_extreme", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_extreme"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Extreme Keyframe", "Color of extreme keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_extreme_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_extreme_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Extreme Keyframe Selected", "Color of selected extreme keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_breakdown", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_breakdown"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Breakdown Keyframe", "Color of breakdown keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_breakdown_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_breakdown_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Breakdown Keyframe Selected", "Color of selected breakdown keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_jitter", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_jitter"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Jitter Keyframe", "Color of jitter keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_jitter_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_jitter_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Jitter Keyframe Selected", "Color of selected jitter keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_movehold", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_movehold"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Moving Hold Keyframe", "Color of moving hold keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_movehold_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keytype_movehold_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Moving Hold Keyframe Selected", "Color of selected moving hold keyframe"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_border", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keyborder"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Keyframe Border", "Color of keyframe border"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_border_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keyborder_select"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Keyframe Border Selected", "Color of selected keyframe border"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_scale_factor", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "keyframe_scale_fac"); RNA_def_property_float_default(prop, 1.0f); RNA_def_property_ui_text( prop, "Keyframe Scale Factor", "Scale factor for adjusting the height of keyframes"); /* Note: These limits prevent buttons overlapping (min), and excessive size... (max) */ RNA_def_property_range(prop, 0.8f, 5.0f); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "summary", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_active"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Summary", "Color of summary channel"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_range", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_preview_range"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Preview Range", "Color of preview range overlay"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "interpolation_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_ipoline"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text( prop, "Interpolation Line", "Color of lines showing non-bezier interpolation modes"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_nla(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_nla */ srna = RNA_def_struct(brna, "ThemeNLAEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Nonlinear Animation", "Theme settings for the NLA Editor"); rna_def_userdef_theme_spaces_main(srna); rna_def_userdef_theme_spaces_list_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "view_sliders", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "shade1"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "View Sliders", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "dopesheet_channel", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "ds_channel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Channel", "Nonlinear Animation Channel"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "nla_track", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_track"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Track", "Nonlinear Animation Track"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_action", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_active"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Active Action", "Animation data-block has active action"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_action_unset", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_non_active"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text( prop, "No Active Action", "Animation data-block doesn't have active action"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "preview_range", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "anim_preview_range"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Preview Range", "Color of preview range overlay"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "strips", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Strips", "Action-Clip Strip - Unselected"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "strips_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Strips Selected", "Action-Clip Strip - Selected"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "transition_strips", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_transition"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Transitions", "Transition Strip - Unselected"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "transition_strips_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_transition_sel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Transitions Selected", "Transition Strip - Selected"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "meta_strips", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_meta"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Meta Strips", "Meta Strip - Unselected (for grouping related strips)"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "meta_strips_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_meta_sel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Meta Strips Selected", "Meta Strip - Selected (for grouping related strips)"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "sound_strips", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_sound"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Sound Strips", "Sound Strip - Unselected (for timing speaker sounds)"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "sound_strips_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_sound_sel"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Sound Strips Selected", "Sound Strip - Selected (for timing speaker sounds)"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "tweak", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_tweaking"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Tweak", "Color for strip/action being 'tweaked' or edited"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "tweak_duplicate", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "nla_tweakdupli"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Tweak Duplicate Flag", "Warning/error indicator color for strips referencing the strip being tweaked"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_border", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keyborder"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Keyframe Border", "Color of keyframe border"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "keyframe_border_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "keyborder_select"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Keyframe Border Selected", "Color of selected keyframe border"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_scrub_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scrubbing/Markers Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_colorset(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeBoneColorSet", NULL); RNA_def_struct_sdna(srna, "ThemeWireColor"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Bone Color Set", "Theme settings for bone color sets"); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "solid"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Regular", "Color used for the surface of bones"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "select", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Select", "Color used for selected bones"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active", "Color used for active bones"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "show_colored_constraints", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", TH_WIRECOLOR_CONSTCOLS); RNA_def_property_ui_text( prop, "Colored Constraints", "Allow the use of colors indicating constraints/keyed status"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_collection_color(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "ThemeCollectionColor", NULL); RNA_def_struct_sdna(srna, "ThemeCollectionColor"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Collection Color", "Theme settings for collection colors"); prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "color"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Color", "Collection Color Tag"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); } static void rna_def_userdef_theme_space_clip(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* space_clip */ srna = RNA_def_struct(brna, "ThemeClipEditor", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Clip Editor", "Theme settings for the Movie Clip Editor"); rna_def_userdef_theme_spaces_main(srna); rna_def_userdef_theme_spaces_list_main(srna); prop = RNA_def_property(srna, "grid", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Grid", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "marker_outline", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "marker_outline"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Marker Outline", "Color of marker's outline"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "marker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "marker"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Marker", "Color of marker"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "active_marker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "act_marker"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Active Marker", "Color of active marker"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "selected_marker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "sel_marker"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Selected Marker", "Color of selected marker"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "disabled_marker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "dis_marker"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Disabled Marker", "Color of disabled marker"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "locked_marker", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "lock_marker"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Locked Marker", "Color of locked marker"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "path_before", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "path_before"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Path Before", "Color of path before current frame"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "path_after", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "path_after"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Path After", "Color of path after current frame"); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "path_keyframe_before", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Path Before", "Color of path before current frame"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "path_keyframe_after", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Path After", "Color of path after current frame"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "frame_current", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "cframe"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Current Frame", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_scrub_background", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Scrubbing/Markers Region", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "time_marker_line_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Marker Line Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "strips", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Strips", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "strips_selected", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "strip_select"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Strips Selected", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatabg", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatabg"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Background", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); prop = RNA_def_property(srna, "metadatatext", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "metadatatext"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Metadata Text", ""); RNA_def_property_update(prop, 0, "rna_userdef_theme_update"); rna_def_userdef_theme_spaces_curves(srna, false, false, false, true); } static void rna_def_userdef_theme_space_topbar(BlenderRNA *brna) { StructRNA *srna; /* space_topbar */ srna = RNA_def_struct(brna, "ThemeTopBar", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Top Bar", "Theme settings for the Top Bar"); rna_def_userdef_theme_spaces_main(srna); } static void rna_def_userdef_theme_space_statusbar(BlenderRNA *brna) { StructRNA *srna; /* space_statusbar */ srna = RNA_def_struct(brna, "ThemeStatusBar", NULL); RNA_def_struct_sdna(srna, "ThemeSpace"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Theme Status Bar", "Theme settings for the Status Bar"); rna_def_userdef_theme_spaces_main(srna); } static void rna_def_userdef_themes(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; static const EnumPropertyItem active_theme_area[] = { {0, "USER_INTERFACE", ICON_WORKSPACE, "User Interface", ""}, {19, "STYLE", ICON_FONTPREVIEW, "Text Style", ""}, {18, "BONE_COLOR_SETS", ICON_COLOR, "Bone Color Sets", ""}, {1, "VIEW_3D", ICON_VIEW3D, "3D Viewport", ""}, {3, "GRAPH_EDITOR", ICON_GRAPH, "Graph Editor", ""}, {4, "DOPESHEET_EDITOR", ICON_ACTION, "Dope Sheet", ""}, {5, "NLA_EDITOR", ICON_NLA, "Nonlinear Animation", ""}, {6, "IMAGE_EDITOR", ICON_IMAGE, "UV/Image Editor", ""}, {7, "SEQUENCE_EDITOR", ICON_SEQUENCE, "Video Sequencer", ""}, {8, "TEXT_EDITOR", ICON_TEXT, "Text Editor", ""}, {9, "NODE_EDITOR", ICON_NODETREE, "Node Editor", ""}, {11, "PROPERTIES", ICON_PROPERTIES, "Properties", ""}, {12, "OUTLINER", ICON_OUTLINER, "Outliner", ""}, {14, "PREFERENCES", ICON_PREFERENCES, "Preferences", ""}, {15, "INFO", ICON_INFO, "Info", ""}, {16, "FILE_BROWSER", ICON_FILEBROWSER, "File Browser", ""}, {17, "CONSOLE", ICON_CONSOLE, "Python Console", ""}, {20, "CLIP_EDITOR", ICON_TRACKER, "Movie Clip Editor", ""}, {21, "TOPBAR", ICON_TOPBAR, "Top Bar", ""}, {22, "STATUSBAR", ICON_STATUSBAR, "Status Bar", ""}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "Theme", NULL); RNA_def_struct_sdna(srna, "bTheme"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text( srna, "Theme", "Theme settings defining draw style and colors in the user interface"); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_property_ui_text(prop, "Name", "Name of the theme"); RNA_def_struct_name_property(srna, prop); /* XXX: for now putting this in presets is silly - its just Default */ RNA_def_property_flag(prop, PROP_SKIP_SAVE); prop = RNA_def_property(srna, "theme_area", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "active_theme_area"); RNA_def_property_flag(prop, PROP_SKIP_SAVE); RNA_def_property_enum_items(prop, active_theme_area); RNA_def_property_ui_text(prop, "Active Theme Area", ""); prop = RNA_def_property(srna, "user_interface", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "tui"); RNA_def_property_struct_type(prop, "ThemeUserInterface"); RNA_def_property_ui_text(prop, "User Interface", ""); /* Space Types */ prop = RNA_def_property(srna, "view_3d", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_view3d"); RNA_def_property_struct_type(prop, "ThemeView3D"); RNA_def_property_ui_text(prop, "3D View", ""); prop = RNA_def_property(srna, "graph_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_graph"); RNA_def_property_struct_type(prop, "ThemeGraphEditor"); RNA_def_property_ui_text(prop, "Graph Editor", ""); prop = RNA_def_property(srna, "file_browser", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_file"); RNA_def_property_struct_type(prop, "ThemeFileBrowser"); RNA_def_property_ui_text(prop, "File Browser", ""); prop = RNA_def_property(srna, "nla_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_nla"); RNA_def_property_struct_type(prop, "ThemeNLAEditor"); RNA_def_property_ui_text(prop, "Nonlinear Animation", ""); prop = RNA_def_property(srna, "dopesheet_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_action"); RNA_def_property_struct_type(prop, "ThemeDopeSheet"); RNA_def_property_ui_text(prop, "Dope Sheet", ""); prop = RNA_def_property(srna, "image_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_image"); RNA_def_property_struct_type(prop, "ThemeImageEditor"); RNA_def_property_ui_text(prop, "Image Editor", ""); prop = RNA_def_property(srna, "sequence_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_sequencer"); RNA_def_property_struct_type(prop, "ThemeSequenceEditor"); RNA_def_property_ui_text(prop, "Sequence Editor", ""); prop = RNA_def_property(srna, "properties", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_properties"); RNA_def_property_struct_type(prop, "ThemeProperties"); RNA_def_property_ui_text(prop, "Properties", ""); prop = RNA_def_property(srna, "text_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_text"); RNA_def_property_struct_type(prop, "ThemeTextEditor"); RNA_def_property_ui_text(prop, "Text Editor", ""); prop = RNA_def_property(srna, "node_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_node"); RNA_def_property_struct_type(prop, "ThemeNodeEditor"); RNA_def_property_ui_text(prop, "Node Editor", ""); prop = RNA_def_property(srna, "outliner", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_outliner"); RNA_def_property_struct_type(prop, "ThemeOutliner"); RNA_def_property_ui_text(prop, "Outliner", ""); prop = RNA_def_property(srna, "info", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_info"); RNA_def_property_struct_type(prop, "ThemeInfo"); RNA_def_property_ui_text(prop, "Info", ""); prop = RNA_def_property(srna, "preferences", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_preferences"); RNA_def_property_struct_type(prop, "ThemePreferences"); RNA_def_property_ui_text(prop, "Preferences", ""); prop = RNA_def_property(srna, "console", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_console"); RNA_def_property_struct_type(prop, "ThemeConsole"); RNA_def_property_ui_text(prop, "Console", ""); prop = RNA_def_property(srna, "clip_editor", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_clip"); RNA_def_property_struct_type(prop, "ThemeClipEditor"); RNA_def_property_ui_text(prop, "Clip Editor", ""); prop = RNA_def_property(srna, "topbar", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_topbar"); RNA_def_property_struct_type(prop, "ThemeTopBar"); RNA_def_property_ui_text(prop, "Top Bar", ""); prop = RNA_def_property(srna, "statusbar", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "space_statusbar"); RNA_def_property_struct_type(prop, "ThemeStatusBar"); RNA_def_property_ui_text(prop, "Status Bar", ""); /* end space types */ prop = RNA_def_property(srna, "bone_color_sets", PROP_COLLECTION, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_collection_sdna(prop, NULL, "tarm", ""); RNA_def_property_struct_type(prop, "ThemeBoneColorSet"); RNA_def_property_ui_text(prop, "Bone Color Sets", ""); prop = RNA_def_property(srna, "collection_color", PROP_COLLECTION, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_collection_sdna(prop, NULL, "collection_color", ""); RNA_def_property_struct_type(prop, "ThemeCollectionColor"); RNA_def_property_ui_text(prop, "Collection Color", ""); } static void rna_def_userdef_addon(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "Addon", NULL); RNA_def_struct_sdna(srna, "bAddon"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Add-on", "Python add-ons to be loaded automatically"); prop = RNA_def_property(srna, "module", PROP_STRING, PROP_NONE); RNA_def_property_ui_text(prop, "Module", "Module name"); RNA_def_struct_name_property(srna, prop); /* Collection active property */ prop = RNA_def_property(srna, "preferences", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "AddonPreferences"); RNA_def_property_pointer_funcs(prop, "rna_Addon_preferences_get", NULL, NULL, NULL); } static void rna_def_userdef_studiolights(BlenderRNA *brna) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; srna = RNA_def_struct(brna, "StudioLights", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_ui_text(srna, "Studio Lights", "Collection of studio lights"); func = RNA_def_function(srna, "load", "rna_StudioLights_load"); RNA_def_function_ui_description(func, "Load studiolight from file"); parm = RNA_def_string( func, "path", NULL, 0, "File Path", "File path where the studio light file can be found"); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); parm = RNA_def_enum(func, "type", rna_enum_studio_light_type_items, STUDIOLIGHT_TYPE_WORLD, "Type", "The type for the new studio light"); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); parm = RNA_def_pointer(func, "studio_light", "StudioLight", "", "Newly created StudioLight"); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "new", "rna_StudioLights_new"); RNA_def_function_ui_description(func, "Create studiolight from default lighting"); parm = RNA_def_string( func, "path", NULL, 0, "Path", "Path to the file that will contain the lighting info (without extension)"); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); parm = RNA_def_pointer(func, "studio_light", "StudioLight", "", "Newly created StudioLight"); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_StudioLights_remove"); RNA_def_function_ui_description(func, "Remove a studio light"); parm = RNA_def_pointer(func, "studio_light", "StudioLight", "", "The studio light to remove"); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); func = RNA_def_function(srna, "refresh", "rna_StudioLights_refresh"); RNA_def_function_ui_description(func, "Refresh Studio Lights from disk"); } static void rna_def_userdef_studiolight(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; RNA_define_verify_sdna(false); srna = RNA_def_struct(brna, "StudioLight", NULL); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Studio Light", "Studio light"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_NONE); RNA_def_property_int_funcs(prop, "rna_UserDef_studiolight_index_get", NULL, NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Index", ""); prop = RNA_def_property(srna, "is_user_defined", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs(prop, "rna_UserDef_studiolight_is_user_defined_get", NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "User Defined", ""); prop = RNA_def_property(srna, "has_specular_highlight_pass", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs( prop, "rna_UserDef_studiolight_has_specular_highlight_pass_get", NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text( prop, "Has Specular Highlight", "Studio light image file has separate \"diffuse\" and \"specular\" passes"); prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_studio_light_type_items); RNA_def_property_enum_funcs(prop, "rna_UserDef_studiolight_type_get", NULL, NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Type", ""); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_property_string_funcs( prop, "rna_UserDef_studiolight_name_get", "rna_UserDef_studiolight_name_length", NULL); RNA_def_property_ui_text(prop, "Name", ""); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_struct_name_property(srna, prop); prop = RNA_def_property(srna, "path", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_funcs( prop, "rna_UserDef_studiolight_path_get", "rna_UserDef_studiolight_path_length", NULL); RNA_def_property_ui_text(prop, "Path", ""); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "solid_lights", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "light_param", ""); RNA_def_property_struct_type(prop, "UserSolidLight"); RNA_def_property_collection_funcs(prop, "rna_UserDef_studiolight_solid_lights_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_UserDef_studiolight_solid_lights_length", NULL, NULL, NULL); RNA_def_property_ui_text( prop, "Solid Lights", "Lights user to display objects in solid draw mode"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "light_ambient", PROP_FLOAT, PROP_COLOR); RNA_def_property_array(prop, 3); RNA_def_property_float_funcs(prop, "rna_UserDef_studiolight_light_ambient_get", NULL, NULL); RNA_def_property_ui_text( prop, "Ambient Color", "Color of the ambient light that uniformly lit the scene"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "path_irr_cache", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_funcs(prop, "rna_UserDef_studiolight_path_irr_cache_get", "rna_UserDef_studiolight_path_irr_cache_length", NULL); RNA_def_property_ui_text( prop, "Irradiance Cache Path", "Path where the irradiance cache is stored"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "path_sh_cache", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_funcs(prop, "rna_UserDef_studiolight_path_sh_cache_get", "rna_UserDef_studiolight_path_sh_cache_length", NULL); RNA_def_property_ui_text( prop, "SH Cache Path", "Path where the spherical harmonics cache is stored"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); const int spherical_harmonics_dim[] = {STUDIOLIGHT_SH_EFFECTIVE_COEFS_LEN, 3}; prop = RNA_def_property(srna, "spherical_harmonics_coefficients", PROP_FLOAT, PROP_COLOR); RNA_def_property_multi_array(prop, 2, spherical_harmonics_dim); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs( prop, "rna_UserDef_studiolight_spherical_harmonics_coefficients_get", NULL, NULL); RNA_define_verify_sdna(true); } static void rna_def_userdef_pathcompare(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "PathCompare", NULL); RNA_def_struct_sdna(srna, "bPathCompare"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Path Compare", "Match paths against this value"); prop = RNA_def_property(srna, "path", PROP_STRING, PROP_DIRPATH); RNA_def_property_ui_text(prop, "Path", ""); RNA_def_struct_name_property(srna, prop); prop = RNA_def_property(srna, "use_glob", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_PATHCMP_GLOB); RNA_def_property_ui_text(prop, "Use Wildcard", "Enable wildcard globbing"); } static void rna_def_userdef_addon_pref(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "AddonPreferences", NULL); RNA_def_struct_ui_text(srna, "Add-on Preferences", ""); RNA_def_struct_sdna(srna, "bAddon"); /* WARNING: only a bAddon during registration */ RNA_def_struct_refine_func(srna, "rna_AddonPref_refine"); RNA_def_struct_register_funcs(srna, "rna_AddonPref_register", "rna_AddonPref_unregister", NULL); RNA_def_struct_idprops_func(srna, "rna_AddonPref_idprops"); RNA_def_struct_flag(srna, STRUCT_NO_DATABLOCK_IDPROPERTIES); /* Mandatory! */ USERDEF_TAG_DIRTY_PROPERTY_UPDATE_DISABLE; /* registration */ RNA_define_verify_sdna(0); prop = RNA_def_property(srna, "bl_idname", PROP_STRING, PROP_NONE); RNA_def_property_string_sdna(prop, NULL, "module"); RNA_def_property_flag(prop, PROP_REGISTER); RNA_define_verify_sdna(1); USERDEF_TAG_DIRTY_PROPERTY_UPDATE_ENABLE; } static void rna_def_userdef_dothemes(BlenderRNA *brna) { rna_def_userdef_theme_ui_style(brna); rna_def_userdef_theme_ui(brna); rna_def_userdef_theme_space_generic(brna); rna_def_userdef_theme_space_gradient(brna); rna_def_userdef_theme_space_list_generic(brna); rna_def_userdef_theme_space_view3d(brna); rna_def_userdef_theme_space_graph(brna); rna_def_userdef_theme_space_file(brna); rna_def_userdef_theme_space_nla(brna); rna_def_userdef_theme_space_action(brna); rna_def_userdef_theme_space_image(brna); rna_def_userdef_theme_space_seq(brna); rna_def_userdef_theme_space_buts(brna); rna_def_userdef_theme_space_text(brna); rna_def_userdef_theme_space_node(brna); rna_def_userdef_theme_space_outliner(brna); rna_def_userdef_theme_space_info(brna); rna_def_userdef_theme_space_userpref(brna); rna_def_userdef_theme_space_console(brna); rna_def_userdef_theme_space_clip(brna); rna_def_userdef_theme_space_topbar(brna); rna_def_userdef_theme_space_statusbar(brna); rna_def_userdef_theme_colorset(brna); rna_def_userdef_theme_collection_color(brna); rna_def_userdef_themes(brna); } static void rna_def_userdef_solidlight(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; static float default_dir[3] = {0.0f, 0.0f, 1.0f}; static float default_col[3] = {0.8f, 0.8f, 0.8f}; srna = RNA_def_struct(brna, "UserSolidLight", NULL); RNA_def_struct_sdna(srna, "SolidLight"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Solid Light", "Light used for Studio lighting in solid draw mode"); prop = RNA_def_property(srna, "use", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", 1); RNA_def_property_boolean_default(prop, true); RNA_def_property_ui_text(prop, "Enabled", "Enable this light in solid draw mode"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "smooth", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "smooth"); RNA_def_property_float_default(prop, 0.5f); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Smooth", "Smooth the lighting from this light"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "direction", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_float_sdna(prop, NULL, "vec"); RNA_def_property_array(prop, 3); RNA_def_property_float_array_default(prop, default_dir); RNA_def_property_ui_text(prop, "Direction", "Direction that the light is shining"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "specular_color", PROP_FLOAT, PROP_COLOR); RNA_def_property_float_sdna(prop, NULL, "spec"); RNA_def_property_array(prop, 3); RNA_def_property_float_array_default(prop, default_col); RNA_def_property_ui_text(prop, "Specular Color", "Color of the light's specular highlight"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "diffuse_color", PROP_FLOAT, PROP_COLOR); RNA_def_property_float_sdna(prop, NULL, "col"); RNA_def_property_array(prop, 3); RNA_def_property_float_array_default(prop, default_col); RNA_def_property_ui_text(prop, "Diffuse Color", "Color of the light's diffuse highlight"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); } static void rna_def_userdef_walk_navigation(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "WalkNavigation", NULL); RNA_def_struct_sdna(srna, "WalkNavigation"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Walk Navigation", "Walk navigation settings"); prop = RNA_def_property(srna, "mouse_speed", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.01f, 10.0f); RNA_def_property_ui_text( prop, "Mouse Sensitivity", "Speed factor for when looking around, high values mean faster mouse movement"); prop = RNA_def_property(srna, "walk_speed", PROP_FLOAT, PROP_VELOCITY); RNA_def_property_range(prop, 0.01f, 100.0f); RNA_def_property_ui_text(prop, "Walk Speed", "Base speed for walking and flying"); prop = RNA_def_property(srna, "walk_speed_factor", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.01f, 10.0f); RNA_def_property_ui_text( prop, "Speed Factor", "Multiplication factor when using the fast or slow modifiers"); prop = RNA_def_property(srna, "view_height", PROP_FLOAT, PROP_UNIT_LENGTH); RNA_def_property_ui_range(prop, 0.1f, 10.0f, 0.1, 2); RNA_def_property_range(prop, 0.0f, 1000.0f); RNA_def_property_ui_text(prop, "View Height", "View distance from the floor when walking"); prop = RNA_def_property(srna, "jump_height", PROP_FLOAT, PROP_UNIT_LENGTH); RNA_def_property_ui_range(prop, 0.1f, 10.0f, 0.1, 2); RNA_def_property_range(prop, 0.1f, 100.0f); RNA_def_property_ui_text(prop, "Jump Height", "Maximum height of a jump"); prop = RNA_def_property(srna, "teleport_time", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.0f, 10.0f); RNA_def_property_ui_text( prop, "Teleport Duration", "Interval of time warp when teleporting in navigation mode"); prop = RNA_def_property(srna, "use_gravity", PROP_BOOLEAN, PROP_BOOLEAN); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_WALK_GRAVITY); RNA_def_property_ui_text(prop, "Gravity", "Walk with gravity, or free navigate"); prop = RNA_def_property(srna, "use_mouse_reverse", PROP_BOOLEAN, PROP_BOOLEAN); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_WALK_MOUSE_REVERSE); RNA_def_property_ui_text(prop, "Reverse Mouse", "Reverse the vertical movement of the mouse"); } static void rna_def_userdef_view(BlenderRNA *brna) { static const EnumPropertyItem timecode_styles[] = { {USER_TIMECODE_MINIMAL, "MINIMAL", 0, "Minimal Info", "Most compact representation, uses '+' as separator for sub-second frame numbers, " "with left and right truncation of the timecode as necessary"}, {USER_TIMECODE_SMPTE_FULL, "SMPTE", 0, "SMPTE (Full)", "Full SMPTE timecode (format is HH:MM:SS:FF)"}, {USER_TIMECODE_SMPTE_MSF, "SMPTE_COMPACT", 0, "SMPTE (Compact)", "SMPTE timecode showing minutes, seconds, and frames only - " "hours are also shown if necessary, but not by default"}, {USER_TIMECODE_MILLISECONDS, "MILLISECONDS", 0, "Compact with Milliseconds", "Similar to SMPTE (Compact), except that instead of frames, " "milliseconds are shown instead"}, {USER_TIMECODE_SECONDS_ONLY, "SECONDS_ONLY", 0, "Only Seconds", "Direct conversion of frame numbers to seconds"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem color_picker_types[] = { {USER_CP_CIRCLE_HSV, "CIRCLE_HSV", 0, "Circle (HSV)", "A circular Hue/Saturation color wheel, with " "Value slider"}, {USER_CP_CIRCLE_HSL, "CIRCLE_HSL", 0, "Circle (HSL)", "A circular Hue/Saturation color wheel, with " "Lightness slider"}, {USER_CP_SQUARE_SV, "SQUARE_SV", 0, "Square (SV + H)", "A square showing Saturation/Value, with Hue slider"}, {USER_CP_SQUARE_HS, "SQUARE_HS", 0, "Square (HS + V)", "A square showing Hue/Saturation, with Value slider"}, {USER_CP_SQUARE_HV, "SQUARE_HV", 0, "Square (HV + S)", "A square showing Hue/Value, with Saturation slider"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem zoom_frame_modes[] = { {ZOOM_FRAME_MODE_KEEP_RANGE, "KEEP_RANGE", 0, "Keep Range", ""}, {ZOOM_FRAME_MODE_SECONDS, "SECONDS", 0, "Seconds", ""}, {ZOOM_FRAME_MODE_KEYFRAMES, "KEYFRAMES", 0, "Keyframes", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem line_width[] = { {-1, "THIN", 0, "Thin", "Thinner lines than the default"}, {0, "AUTO", 0, "Default", "Automatic line width based on UI scale"}, {1, "THICK", 0, "Thick", "Thicker lines than the default"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem render_display_types[] = { {USER_RENDER_DISPLAY_NONE, "NONE", 0, "Keep User Interface", "Images are rendered without changing the user interface"}, {USER_RENDER_DISPLAY_SCREEN, "SCREEN", 0, "Maximized Area", "Images are rendered in a maximized Image Editor"}, {USER_RENDER_DISPLAY_AREA, "AREA", 0, "Image Editor", "Images are rendered in an Image Editor"}, {USER_RENDER_DISPLAY_WINDOW, "WINDOW", 0, "New Window", "Images are rendered in a new window"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem temp_space_display_types[] = { {USER_TEMP_SPACE_DISPLAY_FULLSCREEN, "SCREEN", /* Could be FULLSCREEN, but keeping it consistent with render_display_types */ 0, "Maximized Area", "Open the temporary editor in a maximized screen"}, {USER_TEMP_SPACE_DISPLAY_WINDOW, "WINDOW", 0, "New Window", "Open the temporary editor in a new window"}, {0, NULL, 0, NULL, NULL}, }; PropertyRNA *prop; StructRNA *srna; srna = RNA_def_struct(brna, "PreferencesView", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "View & Controls", "Preferences related to viewing data"); /* View */ prop = RNA_def_property(srna, "ui_scale", PROP_FLOAT, PROP_NONE); RNA_def_property_ui_text( prop, "UI Scale", "Changes the size of the fonts and widgets in the interface"); RNA_def_property_range(prop, 0.25f, 4.0f); RNA_def_property_ui_range(prop, 0.5f, 2.0f, 1, 2); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); prop = RNA_def_property(srna, "ui_line_width", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, line_width); RNA_def_property_ui_text( prop, "UI Line Width", "Changes the thickness of widget outlines, lines and dots in the interface"); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); /* display */ prop = RNA_def_property(srna, "show_tooltips", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_TOOLTIPS); RNA_def_property_ui_text( prop, "Tooltips", "Display tooltips (when off hold Alt to force display)"); prop = RNA_def_property(srna, "show_tooltips_python", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_TOOLTIPS_PYTHON); RNA_def_property_ui_text(prop, "Python Tooltips", "Show Python references in tooltips"); prop = RNA_def_property(srna, "show_developer_ui", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_DEVELOPER_UI); RNA_def_property_ui_text( prop, "Developer Extras", "Show options for developers (edit source in context menu, geometry indices)"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "show_object_info", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DRAWVIEWINFO); RNA_def_property_ui_text( prop, "Display Object Info", "Display objects name and frame number in 3D view"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "show_view_name", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SHOW_VIEWPORTNAME); RNA_def_property_ui_text( prop, "Show View Name", "Show the name of the view's direction in each 3D View"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "show_splash", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "uiflag", USER_SPLASH_DISABLE); RNA_def_property_ui_text(prop, "Show Splash", "Display splash screen on startup"); prop = RNA_def_property(srna, "show_playback_fps", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SHOW_FPS); RNA_def_property_ui_text( prop, "Show Playback FPS", "Show the frames per second screen refresh rate, while animation is played back"); RNA_def_property_update(prop, 0, "rna_userdef_update"); USERDEF_TAG_DIRTY_PROPERTY_UPDATE_DISABLE; prop = RNA_def_property(srna, "show_addons_enabled_only", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna( prop, NULL, "space_data.flag", USER_SPACEDATA_ADDONS_SHOW_ONLY_ENABLED); RNA_def_property_ui_text(prop, "Enabled Add-ons Only", "Only show enabled add-ons. Un-check to see all installed add-ons"); USERDEF_TAG_DIRTY_PROPERTY_UPDATE_ENABLE; static const EnumPropertyItem factor_display_items[] = { {USER_FACTOR_AS_FACTOR, "FACTOR", 0, "Factor", "Display factors as values between 0 and 1"}, {USER_FACTOR_AS_PERCENTAGE, "PERCENTAGE", 0, "Percentage", "Display factors as percentages"}, {0, NULL, 0, NULL, NULL}, }; prop = RNA_def_property(srna, "factor_display_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, factor_display_items); RNA_def_property_ui_text(prop, "Factor Display Type", "How factor values are displayed"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* Weight Paint */ prop = RNA_def_property(srna, "use_weight_color_range", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_CUSTOM_RANGE); RNA_def_property_ui_text( prop, "Use Weight Color Range", "Enable color range used for weight visualization in weight painting mode"); RNA_def_property_update(prop, 0, "rna_UserDef_weight_color_update"); prop = RNA_def_property(srna, "weight_color_range", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "coba_weight"); RNA_def_property_struct_type(prop, "ColorRamp"); RNA_def_property_ui_text(prop, "Weight Color Range", "Color range used for weight visualization in weight painting mode"); RNA_def_property_update(prop, 0, "rna_UserDef_weight_color_update"); prop = RNA_def_property(srna, "show_layout_ui", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "app_flag", USER_APP_LOCK_UI_LAYOUT); RNA_def_property_ui_text( prop, "Editor Corner Splitting", "Split and join editors by dragging from corners"); RNA_def_property_update(prop, 0, "rna_userdef_screen_update"); prop = RNA_def_property(srna, "show_navigate_ui", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SHOW_GIZMO_NAVIGATE); RNA_def_property_ui_text( prop, "Navigation Controls", "Show navigation controls in 2D and 3D views which do not have scroll bars"); RNA_def_property_update(prop, 0, "rna_userdef_gizmo_update"); /* menus */ prop = RNA_def_property(srna, "use_mouse_over_open", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_MENUOPENAUTO); RNA_def_property_ui_text( prop, "Open on Mouse Over", "Open menu buttons and pulldowns automatically when the mouse is hovering"); prop = RNA_def_property(srna, "open_toplevel_delay", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "menuthreshold1"); RNA_def_property_range(prop, 1, 40); RNA_def_property_ui_text( prop, "Top Level Menu Open Delay", "Time delay in 1/10 seconds before automatically opening top level menus"); prop = RNA_def_property(srna, "open_sublevel_delay", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "menuthreshold2"); RNA_def_property_range(prop, 1, 40); RNA_def_property_ui_text( prop, "Sub Level Menu Open Delay", "Time delay in 1/10 seconds before automatically opening sub level menus"); prop = RNA_def_property(srna, "color_picker_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, color_picker_types); RNA_def_property_enum_sdna(prop, NULL, "color_picker_type"); RNA_def_property_ui_text( prop, "Color Picker Type", "Different styles of displaying the color picker widget"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* pie menus */ prop = RNA_def_property(srna, "pie_initial_timeout", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text( prop, "Recenter Timeout", "Pie menus will use the initial mouse position as center for this amount of time " "(in 1/100ths of sec)"); prop = RNA_def_property(srna, "pie_tap_timeout", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text(prop, "Tap Key Timeout", "Pie menu button held longer than this will dismiss menu on release." "(in 1/100ths of sec)"); prop = RNA_def_property(srna, "pie_animation_timeout", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text( prop, "Animation Timeout", "Time needed to fully animate the pie to unfolded state (in 1/100ths of sec)"); prop = RNA_def_property(srna, "pie_menu_radius", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text(prop, "Radius", "Pie menu size in pixels"); prop = RNA_def_property(srna, "pie_menu_threshold", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text( prop, "Threshold", "Distance from center needed before a selection can be made"); prop = RNA_def_property(srna, "pie_menu_confirm", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text(prop, "Confirm Threshold", "Distance threshold after which selection is made (zero to disable)"); prop = RNA_def_property(srna, "use_save_prompt", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SAVE_PROMPT); RNA_def_property_ui_text( prop, "Save Prompt", "Ask for confirmation when quitting with unsaved changes"); prop = RNA_def_property(srna, "show_column_layout", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_PLAINMENUS); RNA_def_property_ui_text(prop, "Toolbox Column Layout", "Use a column layout for toolbox"); prop = RNA_def_property(srna, "use_directional_menus", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "uiflag", USER_MENUFIXEDORDER); RNA_def_property_ui_text(prop, "Contents Follow Opening Direction", "Otherwise menus, etc will always be top to bottom, left to right, " "no matter opening direction"); static const EnumPropertyItem header_align_items[] = { {0, "NONE", 0, "Keep Existing", "Keep existing header alignment"}, {USER_HEADER_FROM_PREF, "TOP", 0, "Top", "Top aligned on load"}, {USER_HEADER_FROM_PREF | USER_HEADER_BOTTOM, "BOTTOM", 0, "Bottom", "Bottom align on load (except for property editors)"}, {0, NULL, 0, NULL, NULL}, }; prop = RNA_def_property(srna, "header_align", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, header_align_items); RNA_def_property_enum_bitflag_sdna(prop, NULL, "uiflag"); RNA_def_property_ui_text(prop, "Header Position", "Default header position for new space-types"); RNA_def_property_update(prop, 0, "rna_userdef_screen_update_header_default"); prop = RNA_def_property(srna, "render_display_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, render_display_types); RNA_def_property_ui_text( prop, "Render Display Type", "Default location where rendered images will be displayed in"); prop = RNA_def_property(srna, "filebrowser_display_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, temp_space_display_types); RNA_def_property_ui_text(prop, "File Browser Display Type", "Default location where the File Editor will be displayed in"); static const EnumPropertyItem text_hinting_items[] = { {0, "AUTO", 0, "Auto", ""}, {USER_TEXT_HINTING_NONE, "NONE", 0, "None", ""}, {USER_TEXT_HINTING_SLIGHT, "SLIGHT", 0, "Slight", ""}, {USER_TEXT_HINTING_FULL, "FULL", 0, "Full", ""}, {0, NULL, 0, NULL, NULL}, }; /* mini axis */ static const EnumPropertyItem mini_axis_type_items[] = { {USER_MINI_AXIS_TYPE_NONE, "NONE", 0, "Off", ""}, {USER_MINI_AXIS_TYPE_MINIMAL, "MINIMAL", 0, "Simple Axis", ""}, {USER_MINI_AXIS_TYPE_GIZMO, "GIZMO", 0, "Interactive Navigation", ""}, {0, NULL, 0, NULL, NULL}, }; prop = RNA_def_property(srna, "mini_axis_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, mini_axis_type_items); RNA_def_property_ui_text(prop, "Mini Axes Type", "Show a small rotating 3D axes in the top right corner of the 3D View"); RNA_def_property_update(prop, 0, "rna_userdef_gizmo_update"); prop = RNA_def_property(srna, "mini_axis_size", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "rvisize"); RNA_def_property_range(prop, 10, 64); RNA_def_property_ui_text(prop, "Mini Axes Size", "The axes icon's size"); RNA_def_property_update(prop, 0, "rna_userdef_gizmo_update"); prop = RNA_def_property(srna, "mini_axis_brightness", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "rvibright"); RNA_def_property_range(prop, 0, 10); RNA_def_property_ui_text(prop, "Mini Axes Brightness", "Brightness of the icon"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "smooth_view", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "smooth_viewtx"); RNA_def_property_range(prop, 0, 1000); RNA_def_property_ui_text( prop, "Smooth View", "Time to animate the view in milliseconds, zero to disable"); prop = RNA_def_property(srna, "rotation_angle", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "pad_rot_angle"); RNA_def_property_range(prop, 0, 90); RNA_def_property_ui_text( prop, "Rotation Angle", "Rotation step for numerical pad keys (2 4 6 8)"); /* 3D transform widget */ prop = RNA_def_property(srna, "show_gizmo", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "gizmo_flag", USER_GIZMO_DRAW); RNA_def_property_ui_text(prop, "Gizmos", "Use transform gizmos by default"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "gizmo_size", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "gizmo_size"); RNA_def_property_range(prop, 10, 200); RNA_def_property_ui_text(prop, "Gizmo Size", "Diameter of the gizmo"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* Lookdev */ prop = RNA_def_property(srna, "lookdev_sphere_size", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "lookdev_sphere_size"); RNA_def_property_range(prop, 50, 400); RNA_def_property_ui_text(prop, "HDRI Preview Size", "Diameter of the HDRI preview spheres"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* View2D Grid Displays */ prop = RNA_def_property(srna, "view2d_grid_spacing_min", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "v2d_min_gridsize"); RNA_def_property_range( prop, 1, 500); /* XXX: perhaps the lower range should only go down to 5? */ RNA_def_property_ui_text(prop, "2D View Minimum Grid Spacing", "Minimum number of pixels between each gridline in 2D Viewports"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* TODO: add a setter for this, so that we can bump up the minimum size as necessary... */ prop = RNA_def_property(srna, "timecode_style", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, timecode_styles); RNA_def_property_enum_sdna(prop, NULL, "timecode_style"); RNA_def_property_enum_funcs(prop, NULL, "rna_userdef_timecode_style_set", NULL); RNA_def_property_ui_text( prop, "TimeCode Style", "Format of Time Codes displayed when not displaying timing in terms of frames"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "view_frame_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, zoom_frame_modes); RNA_def_property_enum_sdna(prop, NULL, "view_frame_type"); RNA_def_property_ui_text( prop, "Zoom to Frame Type", "How zooming to frame focuses around current frame"); prop = RNA_def_property(srna, "view_frame_keyframes", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 1, 500); RNA_def_property_ui_text(prop, "Zoom Keyframes", "Keyframes around cursor that we zoom around"); prop = RNA_def_property(srna, "view_frame_seconds", PROP_FLOAT, PROP_TIME); RNA_def_property_range(prop, 0.0, 10000.0); RNA_def_property_ui_text(prop, "Zoom Seconds", "Seconds around cursor that we zoom around"); /* Text. */ prop = RNA_def_property(srna, "use_text_antialiasing", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "text_render", USER_TEXT_DISABLE_AA); RNA_def_property_ui_text(prop, "Text Anti-Aliasing", "Draw user interface text anti-aliased"); RNA_def_property_update(prop, 0, "rna_userdef_text_update"); prop = RNA_def_property(srna, "text_hinting", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "text_render"); RNA_def_property_enum_items(prop, text_hinting_items); RNA_def_property_ui_text( prop, "Text Hinting", "Method for making user interface text render sharp"); RNA_def_property_update(prop, 0, "rna_userdef_text_update"); prop = RNA_def_property(srna, "font_path_ui", PROP_STRING, PROP_FILEPATH); RNA_def_property_string_sdna(prop, NULL, "font_path_ui"); RNA_def_property_ui_text(prop, "Interface Font", "Path to interface font"); RNA_def_property_update(prop, NC_WINDOW, "rna_userdef_font_update"); prop = RNA_def_property(srna, "font_path_ui_mono", PROP_STRING, PROP_FILEPATH); RNA_def_property_string_sdna(prop, NULL, "font_path_ui_mono"); RNA_def_property_ui_text(prop, "Monospaced Font", "Path to interface monospaced Font"); RNA_def_property_update(prop, NC_WINDOW, "rna_userdef_font_update"); /* Language. */ prop = RNA_def_property(srna, "language", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_language_default_items); # ifdef WITH_INTERNATIONAL RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_lang_enum_properties_itemf"); # endif RNA_def_property_ui_text(prop, "Language", "Language used for translation"); RNA_def_property_update(prop, NC_WINDOW, "rna_userdef_language_update"); prop = RNA_def_property(srna, "use_translate_tooltips", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "transopts", USER_TR_TOOLTIPS); RNA_def_property_ui_text(prop, "Translate Tooltips", "Translate the descriptions when hovering UI elements (recommended)"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "use_translate_interface", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "transopts", USER_TR_IFACE); RNA_def_property_ui_text( prop, "Translate Interface", "Translate all labels in menus, buttons and panels " "(note that this might make it hard to follow tutorials or the manual)"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "use_translate_new_dataname", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "transopts", USER_TR_NEWDATANAME); RNA_def_property_ui_text(prop, "Translate New Names", "Translate the names of new data-blocks (objects, materials...)"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* Statusbar. */ prop = RNA_def_property(srna, "show_statusbar_memory", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "statusbar_flag", STATUSBAR_SHOW_MEMORY); RNA_def_property_ui_text(prop, "Show Memory", "Show Blender memory usage"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO, "rna_userdef_update"); prop = RNA_def_property(srna, "show_statusbar_vram", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "statusbar_flag", STATUSBAR_SHOW_VRAM); RNA_def_property_ui_text(prop, "Show VRAM", "Show GPU video memory usage"); RNA_def_property_editable_func(prop, "rna_show_statusbar_vram_editable"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO, "rna_userdef_update"); prop = RNA_def_property(srna, "show_statusbar_version", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "statusbar_flag", STATUSBAR_SHOW_VERSION); RNA_def_property_ui_text(prop, "Show Version", "Show Blender version string"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO, "rna_userdef_update"); prop = RNA_def_property(srna, "show_statusbar_stats", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "statusbar_flag", STATUSBAR_SHOW_STATS); RNA_def_property_ui_text(prop, "Show Statistics", "Show scene statistics"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO, "rna_userdef_update"); } static void rna_def_userdef_edit(BlenderRNA *brna) { PropertyRNA *prop; StructRNA *srna; static const EnumPropertyItem auto_key_modes[] = { {AUTOKEY_MODE_NORMAL, "ADD_REPLACE_KEYS", 0, "Add/Replace", ""}, {AUTOKEY_MODE_EDITKEYS, "REPLACE_KEYS", 0, "Replace", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem material_link_items[] = { {0, "OBDATA", 0, "Object Data", "Toggle whether the material is linked to object data or the object block"}, {USER_MAT_ON_OB, "OBJECT", 0, "Object", "Toggle whether the material is linked to object data or the object block"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem object_align_items[] = { {0, "WORLD", 0, "World", "Align newly added objects to the world coordinate system"}, {USER_ADD_VIEWALIGNED, "VIEW", 0, "View", "Align newly added objects to the active 3D View direction"}, {USER_ADD_CURSORALIGNED, "CURSOR", 0, "3D Cursor", "Align newly added objects to the 3D Cursor's rotation"}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "PreferencesEdit", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Edit Methods", "Settings for interacting with Blender data"); /* Edit Methods */ prop = RNA_def_property(srna, "material_link", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, material_link_items); RNA_def_property_ui_text( prop, "Material Link To", "Toggle whether the material is linked to object data or the object block"); prop = RNA_def_property(srna, "object_align", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, object_align_items); RNA_def_property_ui_text( prop, "Align Object To", "When adding objects from a 3D View menu, either align them with that view or " "with the world"); prop = RNA_def_property(srna, "use_enter_edit_mode", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_ADD_EDITMODE); RNA_def_property_ui_text( prop, "Enter Edit Mode", "Enter Edit Mode automatically after adding a new object"); prop = RNA_def_property(srna, "collection_instance_empty_size", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.001f, FLT_MAX); RNA_def_property_ui_text(prop, "Collection Instance Empty Size", "Display size of the empty when new collection instances are created"); /* Undo */ prop = RNA_def_property(srna, "undo_steps", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "undosteps"); RNA_def_property_range(prop, 0, 256); RNA_def_property_int_funcs(prop, NULL, "rna_userdef_undo_steps_set", NULL); RNA_def_property_ui_text( prop, "Undo Steps", "Number of undo steps available (smaller values conserve memory)"); prop = RNA_def_property(srna, "undo_memory_limit", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "undomemory"); RNA_def_property_range(prop, 0, max_memory_in_megabytes_int()); RNA_def_property_ui_text( prop, "Undo Memory Size", "Maximum memory usage in megabytes (0 means unlimited)"); prop = RNA_def_property(srna, "use_global_undo", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_GLOBALUNDO); RNA_def_property_ui_text( prop, "Global Undo", "Global undo works by keeping a full copy of the file itself in memory, " "so takes extra memory"); /* auto keyframing */ prop = RNA_def_property(srna, "use_auto_keying", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "autokey_mode", AUTOKEY_ON); RNA_def_property_ui_text(prop, "Auto Keying Enable", "Automatic keyframe insertion for Objects and Bones " "(default setting used for new Scenes)"); prop = RNA_def_property(srna, "auto_keying_mode", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, auto_key_modes); RNA_def_property_enum_funcs( prop, "rna_userdef_autokeymode_get", "rna_userdef_autokeymode_set", NULL); RNA_def_property_ui_text(prop, "Auto Keying Mode", "Mode of automatic keyframe insertion for Objects and Bones " "(default setting used for new Scenes)"); prop = RNA_def_property(srna, "use_keyframe_insert_available", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_INSERTAVAIL); RNA_def_property_ui_text(prop, "Auto Keyframe Insert Available", "Automatic keyframe insertion in available F-Curves"); prop = RNA_def_property(srna, "use_auto_keying_warning", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_NOWARNING); RNA_def_property_ui_text( prop, "Show Auto Keying Warning", "Show warning indicators when transforming objects and bones if auto keying is enabled"); /* keyframing settings */ prop = RNA_def_property(srna, "use_keyframe_insert_needed", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_INSERTNEEDED); RNA_def_property_ui_text( prop, "Keyframe Insert Needed", "Keyframe insertion only when keyframe needed"); prop = RNA_def_property(srna, "use_visual_keying", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_AUTOMATKEY); RNA_def_property_ui_text( prop, "Visual Keying", "Use Visual keying automatically for constrained objects"); prop = RNA_def_property(srna, "use_insertkey_xyz_to_rgb", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "autokey_flag", AUTOKEY_FLAG_XYZ2RGB); RNA_def_property_ui_text( prop, "New F-Curve Colors - XYZ to RGB", "Color for newly added transformation F-Curves (Location, Rotation, Scale) " "and also Color is based on the transform axis"); prop = RNA_def_property(srna, "use_anim_channel_group_colors", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "animation_flag", USER_ANIM_SHOW_CHANNEL_GROUP_COLORS); RNA_def_property_ui_text( prop, "Channel Group Colors", "Use animation channel group colors; generally this is used to show bone group colors"); RNA_def_property_update(prop, 0, "rna_userdef_anim_update"); prop = RNA_def_property(srna, "fcurve_new_auto_smoothing", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_fcurve_auto_smoothing_items); RNA_def_property_enum_sdna(prop, NULL, "auto_smoothing_new"); RNA_def_property_ui_text(prop, "New Curve Smoothing Mode", "Auto Handle Smoothing mode used for newly added F-Curves"); prop = RNA_def_property(srna, "keyframe_new_interpolation_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_beztriple_interpolation_mode_items); RNA_def_property_enum_sdna(prop, NULL, "ipo_new"); RNA_def_property_ui_text(prop, "New Interpolation Type", "Interpolation mode used for first keyframe on newly added F-Curves " "(subsequent keyframes take interpolation from preceding keyframe)"); prop = RNA_def_property(srna, "keyframe_new_handle_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_keyframe_handle_type_items); RNA_def_property_enum_sdna(prop, NULL, "keyhandles_new"); RNA_def_property_ui_text(prop, "New Handles Type", "Handle type for handles of new keyframes"); /* frame numbers */ prop = RNA_def_property(srna, "use_negative_frames", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_NONEGFRAMES); RNA_def_property_ui_text(prop, "Allow Negative Frames", "Current frame number can be manually set to a negative value"); /* fcurve opacity */ prop = RNA_def_property(srna, "fcurve_unselected_alpha", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "fcu_inactive_alpha"); RNA_def_property_range(prop, 0.001f, 1.0f); RNA_def_property_ui_text( prop, "Unselected F-Curve Visibility", "Amount that unselected F-Curves stand out from the background (Graph Editor)"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL); /* grease pencil */ prop = RNA_def_property(srna, "grease_pencil_manhattan_distance", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "gp_manhattandist"); RNA_def_property_range(prop, 0, 100); RNA_def_property_ui_text(prop, "Grease Pencil Manhattan Distance", "Pixels moved by mouse per axis when drawing stroke"); prop = RNA_def_property(srna, "grease_pencil_euclidean_distance", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "gp_euclideandist"); RNA_def_property_range(prop, 0, 100); RNA_def_property_ui_text(prop, "Grease Pencil Euclidean Distance", "Distance moved by mouse when drawing stroke to include"); prop = RNA_def_property(srna, "grease_pencil_eraser_radius", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "gp_eraser"); RNA_def_property_range(prop, 1, 500); RNA_def_property_ui_text(prop, "Grease Pencil Eraser Radius", "Radius of eraser 'brush'"); prop = RNA_def_property(srna, "grease_pencil_default_color", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "gpencil_new_layer_col"); RNA_def_property_array(prop, 4); RNA_def_property_ui_text(prop, "Annotation Default Color", "Color of new annotation layers"); /* sculpt and paint */ prop = RNA_def_property(srna, "sculpt_paint_overlay_color", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_float_sdna(prop, NULL, "sculpt_paint_overlay_col"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Sculpt/Paint Overlay Color", "Color of texture overlay"); /* duplication linking */ prop = RNA_def_property(srna, "use_duplicate_mesh", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_MESH); RNA_def_property_ui_text( prop, "Duplicate Mesh", "Causes mesh data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_surface", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_SURF); RNA_def_property_ui_text( prop, "Duplicate Surface", "Causes surface data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_curve", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_CURVE); RNA_def_property_ui_text( prop, "Duplicate Curve", "Causes curve data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_text", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_FONT); RNA_def_property_ui_text( prop, "Duplicate Text", "Causes text data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_metaball", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_MBALL); RNA_def_property_ui_text( prop, "Duplicate Metaball", "Causes metaball data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_armature", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_ARM); RNA_def_property_ui_text( prop, "Duplicate Armature", "Causes armature data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_light", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_LAMP); RNA_def_property_ui_text( prop, "Duplicate Light", "Causes light data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_material", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_MAT); RNA_def_property_ui_text( prop, "Duplicate Material", "Causes material data to be duplicated with the object"); /* Not implemented, keep because this is useful functionality. */ # if 0 prop = RNA_def_property(srna, "use_duplicate_texture", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_TEX); RNA_def_property_ui_text( prop, "Duplicate Texture", "Causes texture data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_fcurve", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_FCURVE); RNA_def_property_ui_text( prop, "Duplicate F-Curve", "Causes F-curve data to be duplicated with the object"); # endif prop = RNA_def_property(srna, "use_duplicate_action", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_ACT); RNA_def_property_ui_text( prop, "Duplicate Action", "Causes actions to be duplicated with the data-blocks"); prop = RNA_def_property(srna, "use_duplicate_particle", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_PSYS); RNA_def_property_ui_text( prop, "Duplicate Particle", "Causes particle systems to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_lightprobe", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_LIGHTPROBE); RNA_def_property_ui_text( prop, "Duplicate Light Probe", "Causes light probe data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_grease_pencil", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_GPENCIL); RNA_def_property_ui_text( prop, "Duplicate GPencil", "Causes grease pencil data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_hair", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_HAIR); RNA_def_property_ui_text( prop, "Duplicate Hair", "Causes hair data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_pointcloud", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_POINTCLOUD); RNA_def_property_ui_text( prop, "Duplicate Point Cloud", "Causes point cloud data to be duplicated with the object"); prop = RNA_def_property(srna, "use_duplicate_volume", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "dupflag", USER_DUP_VOLUME); RNA_def_property_ui_text( prop, "Duplicate Volume", "Causes volume data to be duplicated with the object"); /* Currently only used for insert offset (aka auto-offset), * maybe also be useful for later stuff though. */ prop = RNA_def_property(srna, "node_margin", PROP_INT, PROP_PIXEL); RNA_def_property_int_sdna(prop, NULL, "node_margin"); RNA_def_property_ui_text( prop, "Auto-offset Margin", "Minimum distance between nodes for Auto-offsetting nodes"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* cursor */ prop = RNA_def_property(srna, "use_cursor_lock_adjust", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_LOCK_CURSOR_ADJUST); RNA_def_property_ui_text( prop, "Cursor Lock Adjust", "Place the cursor without 'jumping' to the new location (when lock-to-cursor is used)"); prop = RNA_def_property(srna, "use_mouse_depth_cursor", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DEPTH_CURSOR); RNA_def_property_ui_text( prop, "Cursor Surface Project", "Use the surface depth for cursor placement"); } static void rna_def_userdef_system(BlenderRNA *brna) { PropertyRNA *prop; StructRNA *srna; static const EnumPropertyItem gl_texture_clamp_items[] = { {0, "CLAMP_OFF", 0, "Off", ""}, {8192, "CLAMP_8192", 0, "8192", ""}, {4096, "CLAMP_4096", 0, "4096", ""}, {2048, "CLAMP_2048", 0, "2048", ""}, {1024, "CLAMP_1024", 0, "1024", ""}, {512, "CLAMP_512", 0, "512", ""}, {256, "CLAMP_256", 0, "256", ""}, {128, "CLAMP_128", 0, "128", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem anisotropic_items[] = { {1, "FILTER_0", 0, "Off", ""}, {2, "FILTER_2", 0, "2x", ""}, {4, "FILTER_4", 0, "4x", ""}, {8, "FILTER_8", 0, "8x", ""}, {16, "FILTER_16", 0, "16x", ""}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem audio_mixing_samples_items[] = { {256, "SAMPLES_256", 0, "256 Samples", "Set audio mixing buffer size to 256 samples"}, {512, "SAMPLES_512", 0, "512 Samples", "Set audio mixing buffer size to 512 samples"}, {1024, "SAMPLES_1024", 0, "1024 Samples", "Set audio mixing buffer size to 1024 samples"}, {2048, "SAMPLES_2048", 0, "2048 Samples", "Set audio mixing buffer size to 2048 samples"}, {4096, "SAMPLES_4096", 0, "4096 Samples", "Set audio mixing buffer size to 4096 samples"}, {8192, "SAMPLES_8192", 0, "8192 Samples", "Set audio mixing buffer size to 8192 samples"}, {16384, "SAMPLES_16384", 0, "16384 Samples", "Set audio mixing buffer size to 16384 samples"}, {32768, "SAMPLES_32768", 0, "32768 Samples", "Set audio mixing buffer size to 32768 samples"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem audio_rate_items[] = { # if 0 {8000, "RATE_8000", 0, "8 kHz", "Set audio sampling rate to 8000 samples per second"}, {11025, "RATE_11025", 0, "11.025 kHz", "Set audio sampling rate to 11025 samples per second"}, {16000, "RATE_16000", 0, "16 kHz", "Set audio sampling rate to 16000 samples per second"}, {22050, "RATE_22050", 0, "22.05 kHz", "Set audio sampling rate to 22050 samples per second"}, {32000, "RATE_32000", 0, "32 kHz", "Set audio sampling rate to 32000 samples per second"}, # endif {44100, "RATE_44100", 0, "44.1 kHz", "Set audio sampling rate to 44100 samples per second"}, {48000, "RATE_48000", 0, "48 kHz", "Set audio sampling rate to 48000 samples per second"}, # if 0 {88200, "RATE_88200", 0, "88.2 kHz", "Set audio sampling rate to 88200 samples per second"}, # endif {96000, "RATE_96000", 0, "96 kHz", "Set audio sampling rate to 96000 samples per second"}, {192000, "RATE_192000", 0, "192 kHz", "Set audio sampling rate to 192000 samples per second"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem audio_format_items[] = { {0x01, "U8", 0, "8-bit Unsigned", "Set audio sample format to 8-bit unsigned integer"}, {0x12, "S16", 0, "16-bit Signed", "Set audio sample format to 16-bit signed integer"}, {0x13, "S24", 0, "24-bit Signed", "Set audio sample format to 24-bit signed integer"}, {0x14, "S32", 0, "32-bit Signed", "Set audio sample format to 32-bit signed integer"}, {0x24, "FLOAT", 0, "32-bit Float", "Set audio sample format to 32-bit float"}, {0x28, "DOUBLE", 0, "64-bit Float", "Set audio sample format to 64-bit float"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem audio_channel_items[] = { {1, "MONO", 0, "Mono", "Set audio channels to mono"}, {2, "STEREO", 0, "Stereo", "Set audio channels to stereo"}, {4, "SURROUND4", 0, "4 Channels", "Set audio channels to 4 channels"}, {6, "SURROUND51", 0, "5.1 Surround", "Set audio channels to 5.1 surround sound"}, {8, "SURROUND71", 0, "7.1 Surround", "Set audio channels to 7.1 surround sound"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem image_draw_methods[] = { {IMAGE_DRAW_METHOD_AUTO, "AUTO", 0, "Automatic", "Automatically choose method based on GPU and image"}, {IMAGE_DRAW_METHOD_2DTEXTURE, "2DTEXTURE", 0, "2D Texture", "Use CPU for display transform and draw image with 2D texture"}, {IMAGE_DRAW_METHOD_GLSL, "GLSL", 0, "GLSL", "Use GLSL shaders for display transform and draw image with 2D texture"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem seq_disk_cache_compression_levels[] = { {USER_SEQ_DISK_CACHE_COMPRESSION_NONE, "NONE", 0, "None", "Requires fast storage, but uses minimum CPU resources"}, {USER_SEQ_DISK_CACHE_COMPRESSION_LOW, "LOW", 0, "Low", "Doesn't require fast storage and uses less CPU resources"}, {USER_SEQ_DISK_CACHE_COMPRESSION_HIGH, "HIGH", 0, "High", "Works on slower storage devices and uses most CPU resources"}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "PreferencesSystem", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "System & OpenGL", "Graphics driver and operating system settings"); /* UI settings. */ prop = RNA_def_property(srna, "ui_scale", PROP_FLOAT, PROP_NONE); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_sdna(prop, NULL, "dpi_fac"); RNA_def_property_ui_text( prop, "UI Scale", "Size multiplier to use when drawing custom user interface elements, so that " "they are scaled correctly on screens with different DPI. This value is based " "on operating system DPI settings and Blender display scale"); prop = RNA_def_property(srna, "ui_line_width", PROP_FLOAT, PROP_NONE); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_sdna(prop, NULL, "pixelsize"); RNA_def_property_ui_text( prop, "UI Line Width", "Suggested line thickness and point size in pixels, for add-ons drawing custom " "user interface elements, based on operating system settings and Blender UI scale"); prop = RNA_def_property(srna, "dpi", PROP_INT, PROP_NONE); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "pixel_size", PROP_FLOAT, PROP_NONE); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_sdna(prop, NULL, "pixelsize"); /* Memory */ prop = RNA_def_property(srna, "memory_cache_limit", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "memcachelimit"); RNA_def_property_range(prop, 0, max_memory_in_megabytes_int()); RNA_def_property_ui_text(prop, "Memory Cache Limit", "Memory cache limit (in megabytes)"); RNA_def_property_update(prop, 0, "rna_Userdef_memcache_update"); /* Sequencer disk cache */ prop = RNA_def_property(srna, "use_sequencer_disk_cache", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna( prop, NULL, "sequencer_disk_cache_flag", SEQ_CACHE_DISK_CACHE_ENABLE); RNA_def_property_ui_text(prop, "Use Disk Cache", "Store cached images to disk"); prop = RNA_def_property(srna, "sequencer_disk_cache_dir", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "sequencer_disk_cache_dir"); RNA_def_property_update(prop, 0, "rna_Userdef_disk_cache_dir_update"); RNA_def_property_ui_text(prop, "Disk Cache Directory", "Override default directory"); prop = RNA_def_property(srna, "sequencer_disk_cache_size_limit", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "sequencer_disk_cache_size_limit"); RNA_def_property_range(prop, 0, INT_MAX); RNA_def_property_ui_text(prop, "Disk Cache Limit", "Disk cache limit (in gigabytes)"); prop = RNA_def_property(srna, "sequencer_disk_cache_compression", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, seq_disk_cache_compression_levels); RNA_def_property_enum_sdna(prop, NULL, "sequencer_disk_cache_compression"); RNA_def_property_ui_text( prop, "Disk Cache Compression Level", "Smaller compression will result in larger files, but less decoding overhead"); prop = RNA_def_property(srna, "scrollback", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "scrollback"); RNA_def_property_range(prop, 32, 32768); RNA_def_property_ui_text( prop, "Scrollback", "Maximum number of lines to store for the console buffer"); /* OpenGL */ /* Viewport anti-aliasing */ prop = RNA_def_property(srna, "use_overlay_smooth_wire", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "gpu_flag", USER_GPU_FLAG_OVERLAY_SMOOTH_WIRE); RNA_def_property_ui_text( prop, "Overlay Smooth Wires", "Enable overlay smooth wires, reducing aliasing"); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); prop = RNA_def_property(srna, "use_edit_mode_smooth_wire", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna( prop, NULL, "gpu_flag", USER_GPU_FLAG_NO_EDIT_MODE_SMOOTH_WIRE); RNA_def_property_ui_text(prop, "Edit-Mode Smooth Wires", "Enable Edit-Mode edge smoothing, reducing aliasing, requires restart"); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); prop = RNA_def_property(srna, "use_region_overlap", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag2", USER_REGION_OVERLAP); RNA_def_property_ui_text( prop, "Region Overlap", "Draw tool/property regions over the main region"); RNA_def_property_update(prop, 0, "rna_userdef_dpi_update"); prop = RNA_def_property(srna, "viewport_aa", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, rna_enum_userdef_viewport_aa_items); RNA_def_property_ui_text( prop, "Viewport Anti-Aliasing", "Method of anti-aliasing in 3d viewport"); RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "solid_lights", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "light_param", ""); RNA_def_property_struct_type(prop, "UserSolidLight"); RNA_def_property_ui_text( prop, "Solid Lights", "Lights user to display objects in solid draw mode"); prop = RNA_def_property(srna, "light_ambient", PROP_FLOAT, PROP_COLOR); RNA_def_property_float_sdna(prop, NULL, "light_ambient"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Ambient Color", "Color of the ambient light that uniformly lit the scene"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "use_studio_light_edit", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "edit_studio_light", 1); RNA_def_property_ui_text( prop, "Edit Studio Light", "View the result of the studio light editor in the viewport"); RNA_def_property_update(prop, 0, "rna_UserDef_viewport_lights_update"); prop = RNA_def_property(srna, "gl_clip_alpha", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "glalphaclip"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text( prop, "Clip Alpha", "Clip alpha below this threshold in the 3D textured view"); RNA_def_property_update(prop, 0, "rna_userdef_update"); /* Textures */ prop = RNA_def_property(srna, "image_draw_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, image_draw_methods); RNA_def_property_enum_sdna(prop, NULL, "image_draw_method"); RNA_def_property_ui_text( prop, "Image Display Method", "Method used for displaying images on the screen"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "anisotropic_filter", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "anisotropic_filter"); RNA_def_property_enum_items(prop, anisotropic_items); RNA_def_property_enum_default(prop, 1); RNA_def_property_ui_text( prop, "Anisotropic Filter", "Quality of the anisotropic filtering (values greater than 1.0 enable anisotropic " "filtering)"); RNA_def_property_update(prop, 0, "rna_userdef_anisotropic_update"); prop = RNA_def_property(srna, "gl_texture_limit", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "glreslimit"); RNA_def_property_enum_items(prop, gl_texture_clamp_items); RNA_def_property_ui_text( prop, "GL Texture Limit", "Limit the texture size to save graphics memory"); RNA_def_property_update(prop, 0, "rna_userdef_gl_texture_limit_update"); prop = RNA_def_property(srna, "texture_time_out", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "textimeout"); RNA_def_property_range(prop, 0, 3600); RNA_def_property_ui_text( prop, "Texture Time Out", "Time since last access of a GL texture in seconds after which it is freed " "(set to 0 to keep textures allocated)"); prop = RNA_def_property(srna, "texture_collection_rate", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "texcollectrate"); RNA_def_property_range(prop, 1, 3600); RNA_def_property_ui_text( prop, "Texture Collection Rate", "Number of seconds between each run of the GL texture garbage collector"); prop = RNA_def_property(srna, "vbo_time_out", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "vbotimeout"); RNA_def_property_range(prop, 0, 3600); RNA_def_property_ui_text( prop, "VBO Time Out", "Time since last access of a GL Vertex buffer object in seconds after which it is freed " "(set to 0 to keep vbo allocated)"); prop = RNA_def_property(srna, "vbo_collection_rate", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "vbocollectrate"); RNA_def_property_range(prop, 1, 3600); RNA_def_property_ui_text( prop, "VBO Collection Rate", "Number of seconds between each run of the GL Vertex buffer object garbage collector"); /* Select */ prop = RNA_def_property(srna, "use_select_pick_depth", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "gpu_flag", USER_GPU_FLAG_NO_DEPT_PICK); RNA_def_property_ui_text(prop, "OpenGL Depth Picking", "Use the depth buffer for picking 3D View selection " "(without this the front most object may not be selected first)"); /* Audio */ prop = RNA_def_property(srna, "audio_mixing_buffer", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "mixbufsize"); RNA_def_property_enum_items(prop, audio_mixing_samples_items); RNA_def_property_ui_text( prop, "Audio Mixing Buffer", "Number of samples used by the audio mixing buffer"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); prop = RNA_def_property(srna, "audio_device", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "audiodevice"); RNA_def_property_enum_items(prop, audio_device_items); RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_userdef_audio_device_itemf"); RNA_def_property_ui_text(prop, "Audio Device", "Audio output device"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); prop = RNA_def_property(srna, "audio_sample_rate", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "audiorate"); RNA_def_property_enum_items(prop, audio_rate_items); RNA_def_property_ui_text(prop, "Audio Sample Rate", "Audio sample rate"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); prop = RNA_def_property(srna, "audio_sample_format", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "audioformat"); RNA_def_property_enum_items(prop, audio_format_items); RNA_def_property_ui_text(prop, "Audio Sample Format", "Audio sample format"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); prop = RNA_def_property(srna, "audio_channels", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "audiochannels"); RNA_def_property_enum_items(prop, audio_channel_items); RNA_def_property_ui_text(prop, "Audio Channels", "Audio channel count"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); # ifdef WITH_OPENSUBDIV prop = RNA_def_property(srna, "opensubdiv_compute_type", PROP_ENUM, PROP_NONE); RNA_def_property_flag(prop, PROP_ENUM_NO_CONTEXT); RNA_def_property_enum_sdna(prop, NULL, "opensubdiv_compute_type"); RNA_def_property_enum_items(prop, opensubdiv_compute_type_items); RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_userdef_opensubdiv_compute_type_itemf"); RNA_def_property_ui_text( prop, "OpenSubdiv Compute Type", "Type of computer back-end used with OpenSubdiv"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_PROPERTIES, "rna_userdef_opensubdiv_update"); # endif # ifdef WITH_CYCLES prop = RNA_def_property(srna, "legacy_compute_device_type", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "compute_device_type"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_flag(prop, PROP_HIDDEN); RNA_def_property_ui_text(prop, "Legacy Compute Device Type", "For backwards compatibility only"); # endif } static void rna_def_userdef_input(BlenderRNA *brna) { PropertyRNA *prop; StructRNA *srna; static const EnumPropertyItem view_rotation_items[] = { {0, "TURNTABLE", 0, "Turntable", "Turntable keeps the Z-axis upright while orbiting"}, {USER_TRACKBALL, "TRACKBALL", 0, "Trackball", "Trackball allows you to tumble your view at any angle"}, {0, NULL, 0, NULL, NULL}, }; # ifdef WITH_INPUT_NDOF static const EnumPropertyItem ndof_view_navigation_items[] = { {0, "FREE", 0, "Free", "Use full 6 degrees of freedom by default"}, {NDOF_MODE_ORBIT, "ORBIT", 0, "Orbit", "Orbit about the view center by default"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem ndof_view_rotation_items[] = { {NDOF_TURNTABLE, "TURNTABLE", 0, "Turntable", "Use turntable style rotation in the viewport"}, {0, "TRACKBALL", 0, "Trackball", "Use trackball style rotation in the viewport"}, {0, NULL, 0, NULL, NULL}, }; # endif /* WITH_INPUT_NDOF */ static const EnumPropertyItem tablet_api[] = { {USER_TABLET_AUTOMATIC, "AUTOMATIC", 0, "Automatic", "Automatically choose Wintab or Windows Ink depending on the device"}, {USER_TABLET_NATIVE, "WINDOWS_INK", 0, "Windows Ink", "Use native Windows Ink API, for modern tablet and pen devices. Requires Windows 8 or " "newer"}, {USER_TABLET_WINTAB, "WINTAB", 0, "Wintab", "Use Wintab driver for older tablets and Windows versions"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem view_zoom_styles[] = { {USER_ZOOM_CONT, "CONTINUE", 0, "Continue", "Continuous zooming. The zoom direction and speed depends on how far along the set Zoom " "Axis the mouse has moved"}, {USER_ZOOM_DOLLY, "DOLLY", 0, "Dolly", "Zoom in and out based on mouse movement along the set Zoom Axis"}, {USER_ZOOM_SCALE, "SCALE", 0, "Scale", "Zoom in and out as if you are scaling the view, mouse movements relative to center"}, {0, NULL, 0, NULL, NULL}, }; static const EnumPropertyItem view_zoom_axes[] = { {0, "VERTICAL", 0, "Vertical", "Zoom in and out based on vertical mouse movement"}, {USER_ZOOM_HORIZ, "HORIZONTAL", 0, "Horizontal", "Zoom in and out based on horizontal mouse movement"}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "PreferencesInput", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Input", "Settings for input devices"); prop = RNA_def_property(srna, "view_zoom_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "viewzoom"); RNA_def_property_enum_items(prop, view_zoom_styles); RNA_def_property_ui_text(prop, "Zoom Style", "Which style to use for viewport scaling"); prop = RNA_def_property(srna, "view_zoom_axis", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "uiflag"); RNA_def_property_enum_items(prop, view_zoom_axes); RNA_def_property_ui_text(prop, "Zoom Axis", "Axis of mouse movement to zoom in or out on"); prop = RNA_def_property(srna, "invert_mouse_zoom", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_ZOOM_INVERT); RNA_def_property_ui_text( prop, "Invert Zoom Direction", "Invert the axis of mouse movement for zooming"); prop = RNA_def_property(srna, "use_mouse_depth_navigate", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DEPTH_NAVIGATE); RNA_def_property_ui_text( prop, "Auto Depth", "Use the depth under the mouse to improve view pan/rotate/zoom functionality"); /* view zoom */ prop = RNA_def_property(srna, "use_zoom_to_mouse", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_ZOOM_TO_MOUSEPOS); RNA_def_property_ui_text(prop, "Zoom to Mouse Position", "Zoom in towards the mouse pointer's position in the 3D view, " "rather than the 2D window center"); /* view rotation */ prop = RNA_def_property(srna, "use_auto_perspective", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_AUTOPERSP); RNA_def_property_ui_text( prop, "Auto Perspective", "Automatically switch between orthographic and perspective when changing " "from top/front/side views"); prop = RNA_def_property(srna, "use_rotate_around_active", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_ORBIT_SELECTION); RNA_def_property_ui_text(prop, "Orbit Around Selection", "Use selection as the pivot point"); prop = RNA_def_property(srna, "view_rotate_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, view_rotation_items); RNA_def_property_ui_text(prop, "Orbit Method", "Orbit method in the viewport"); prop = RNA_def_property(srna, "use_mouse_continuous", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_CONTINUOUS_MOUSE); RNA_def_property_ui_text(prop, "Continuous Grab", "Allow moving the mouse outside the view on some manipulations " "(transform, ui control drag)"); prop = RNA_def_property(srna, "use_drag_immediately", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_RELEASECONFIRM); RNA_def_property_ui_text(prop, "Release Confirms", "Moving things with a mouse drag confirms when releasing the button"); prop = RNA_def_property(srna, "use_numeric_input_advanced", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_FLAG_NUMINPUT_ADVANCED); RNA_def_property_ui_text(prop, "Default to Advanced Numeric Input", "When entering numbers while transforming, " "default to advanced mode for full math expression evaluation"); /* View Navigation */ prop = RNA_def_property(srna, "navigation_mode", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "navigation_mode"); RNA_def_property_enum_items(prop, rna_enum_navigation_mode_items); RNA_def_property_ui_text(prop, "View Navigation", "Which method to use for viewport navigation"); prop = RNA_def_property(srna, "walk_navigation", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "walk_navigation"); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "WalkNavigation"); RNA_def_property_ui_text(prop, "Walk Navigation", "Settings for walk navigation mode"); prop = RNA_def_property(srna, "view_rotate_sensitivity_turntable", PROP_FLOAT, PROP_ANGLE); RNA_def_property_range(prop, DEG2RADF(0.001f), DEG2RADF(15.0f)); RNA_def_property_ui_range(prop, DEG2RADF(0.001f), DEG2RADF(15.0f), 1.0f, 2); RNA_def_property_ui_text(prop, "Orbit Sensitivity", "Rotation amount per-pixel to control how fast the viewport orbits"); prop = RNA_def_property(srna, "view_rotate_sensitivity_trackball", PROP_FLOAT, PROP_FACTOR); RNA_def_property_range(prop, 0.1f, 10.0f); RNA_def_property_ui_range(prop, 0.1f, 2.0f, 0.01f, 2); RNA_def_property_ui_text(prop, "Orbit Sensitivity", "Scale trackball orbit sensitivity"); /* tweak tablet & mouse preset */ prop = RNA_def_property(srna, "drag_threshold_mouse", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 255); RNA_def_property_ui_text(prop, "Mouse Drag Threshold", "Number of pixels to drag before a tweak/drag event is triggered " "for mouse/track-pad input " "(otherwise click events are detected)"); prop = RNA_def_property(srna, "drag_threshold_tablet", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 255); RNA_def_property_ui_text(prop, "Tablet Drag Threshold", "Number of pixels to drag before a tweak/drag event is triggered " "for tablet input " "(otherwise click events are detected)"); prop = RNA_def_property(srna, "drag_threshold", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 1, 255); RNA_def_property_ui_text(prop, "Drag Threshold", "Number of pixels to drag before a drag event is triggered " "for keyboard and other non mouse/tablet input " "(otherwise click events are detected)"); prop = RNA_def_property(srna, "move_threshold", PROP_INT, PROP_PIXEL); RNA_def_property_range(prop, 0, 255); RNA_def_property_ui_range(prop, 0, 10, 1, -1); RNA_def_property_ui_text(prop, "Motion Threshold", "Number of pixels to before the cursor is considered to have moved " "(used for cycling selected items on successive clicks)"); /* tablet pressure curve */ prop = RNA_def_property(srna, "pressure_threshold_max", PROP_FLOAT, PROP_FACTOR); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.01f, 3); RNA_def_property_ui_text( prop, "Max Threshold", "Raw input pressure value that is interpreted as 100% by Blender"); prop = RNA_def_property(srna, "pressure_softness", PROP_FLOAT, PROP_FACTOR); RNA_def_property_range(prop, -FLT_MAX, FLT_MAX); RNA_def_property_ui_range(prop, -1.0f, 1.0f, 0.1f, 2); RNA_def_property_ui_text( prop, "Softness", "Adjusts softness of the low pressure response onset using a gamma curve"); prop = RNA_def_property(srna, "tablet_api", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, tablet_api); RNA_def_property_ui_text( prop, "Tablet API", "Select the tablet API to use for pressure sensitivity"); RNA_def_property_update(prop, 0, "rna_userdef_tablet_api_update"); # ifdef WITH_INPUT_NDOF /* 3D mouse settings */ /* global options */ prop = RNA_def_property(srna, "ndof_sensitivity", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.01f, 40.0f); RNA_def_property_ui_text(prop, "Sensitivity", "Overall sensitivity of the 3D Mouse for panning"); prop = RNA_def_property(srna, "ndof_orbit_sensitivity", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.01f, 40.0f); RNA_def_property_ui_text( prop, "Orbit Sensitivity", "Overall sensitivity of the 3D Mouse for orbiting"); prop = RNA_def_property(srna, "ndof_deadzone", PROP_FLOAT, PROP_FACTOR); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text( prop, "Deadzone", "Threshold of initial movement needed from the device's rest position"); RNA_def_property_update(prop, 0, "rna_userdef_ndof_deadzone_update"); prop = RNA_def_property(srna, "ndof_pan_yz_swap_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_PAN_YZ_SWAP_AXIS); RNA_def_property_ui_text( prop, "Y/Z Swap Axis", "Pan using up/down on the device (otherwise forward/backward)"); prop = RNA_def_property(srna, "ndof_zoom_invert", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_ZOOM_INVERT); RNA_def_property_ui_text(prop, "Invert Zoom", "Zoom using opposite direction"); /* 3D view */ prop = RNA_def_property(srna, "ndof_show_guide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_SHOW_GUIDE); /* TODO: update description when fly-mode visuals are in place * ("projected position in fly mode"). */ RNA_def_property_ui_text( prop, "Show Navigation Guide", "Display the center and axis during rotation"); /* 3D view */ prop = RNA_def_property(srna, "ndof_view_navigate_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "ndof_flag"); RNA_def_property_enum_items(prop, ndof_view_navigation_items); RNA_def_property_ui_text(prop, "NDOF View Navigate", "Navigation style in the viewport"); prop = RNA_def_property(srna, "ndof_view_rotate_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "ndof_flag"); RNA_def_property_enum_items(prop, ndof_view_rotation_items); RNA_def_property_ui_text(prop, "NDOF View Rotation", "Rotation style in the viewport"); /* 3D view: yaw */ prop = RNA_def_property(srna, "ndof_rotx_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_ROTX_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert Pitch (X) Axis", ""); /* 3D view: pitch */ prop = RNA_def_property(srna, "ndof_roty_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_ROTY_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert Yaw (Y) Axis", ""); /* 3D view: roll */ prop = RNA_def_property(srna, "ndof_rotz_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_ROTZ_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert Roll (Z) Axis", ""); /* 3D view: pan x */ prop = RNA_def_property(srna, "ndof_panx_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_PANX_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert X Axis", ""); /* 3D view: pan y */ prop = RNA_def_property(srna, "ndof_pany_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_PANY_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert Y Axis", ""); /* 3D view: pan z */ prop = RNA_def_property(srna, "ndof_panz_invert_axis", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_PANZ_INVERT_AXIS); RNA_def_property_ui_text(prop, "Invert Z Axis", ""); /* 3D view: fly */ prop = RNA_def_property(srna, "ndof_lock_horizon", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_LOCK_HORIZON); RNA_def_property_ui_text(prop, "Lock Horizon", "Keep horizon level while flying with 3D Mouse"); prop = RNA_def_property(srna, "ndof_fly_helicopter", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ndof_flag", NDOF_FLY_HELICOPTER); RNA_def_property_ui_text(prop, "Helicopter Mode", "Device up/down directly controls the Z position of the 3D viewport"); /* let Python know whether NDOF is enabled */ prop = RNA_def_boolean(srna, "use_ndof", true, "", ""); # else prop = RNA_def_boolean(srna, "use_ndof", false, "", ""); # endif /* WITH_INPUT_NDOF */ RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "mouse_double_click_time", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "dbl_click_time"); RNA_def_property_range(prop, 1, 1000); RNA_def_property_ui_text(prop, "Double Click Timeout", "Time/delay (in ms) for a double click"); prop = RNA_def_property(srna, "use_mouse_emulate_3_button", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_TWOBUTTONMOUSE); RNA_def_property_ui_text( prop, "Emulate 3 Button Mouse", "Emulate Middle Mouse with Alt+Left Mouse"); RNA_def_property_flag(prop, PROP_CONTEXT_UPDATE); RNA_def_property_update(prop, 0, "rna_userdef_keyconfig_reload_update"); static const EnumPropertyItem mouse_emulate_3_button_modifier[] = { {USER_EMU_MMB_MOD_ALT, "ALT", 0, "Alt", ""}, {USER_EMU_MMB_MOD_OSKEY, "OSKEY", 0, "OS-Key", ""}, {0, NULL, 0, NULL, NULL}, }; prop = RNA_def_property(srna, "mouse_emulate_3_button_modifier", PROP_ENUM, PROP_NONE); /* Only needed because of WIN32 inability to support the option. */ RNA_def_property_enum_funcs(prop, "rna_UserDef_mouse_emulate_3_button_modifier_get", NULL, NULL); RNA_def_property_enum_items(prop, mouse_emulate_3_button_modifier); RNA_def_property_ui_text( prop, "Emulate 3 Button Modifier", "Hold this modifier to emulate the middle mouse button"); RNA_def_property_flag(prop, PROP_CONTEXT_UPDATE); RNA_def_property_update(prop, 0, "rna_userdef_keyconfig_reload_update"); prop = RNA_def_property(srna, "use_emulate_numpad", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_NONUMPAD); RNA_def_property_ui_text( prop, "Emulate Numpad", "Main 1 to 0 keys act as the numpad ones (useful for laptops)"); prop = RNA_def_property(srna, "invert_zoom_wheel", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_WHEELZOOMDIR); RNA_def_property_ui_text(prop, "Wheel Invert Zoom", "Swap the Mouse Wheel zoom direction"); } static void rna_def_userdef_keymap(BlenderRNA *brna) { PropertyRNA *prop; StructRNA *srna = RNA_def_struct(brna, "PreferencesKeymap", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Keymap", "Shortcut setup for keyboards and other input devices"); prop = RNA_def_property(srna, "show_ui_keyconfig", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna( prop, NULL, "space_data.flag", USER_SPACEDATA_INPUT_HIDE_UI_KEYCONFIG); RNA_def_property_ui_text(prop, "Show UI Key-Config", ""); prop = RNA_def_property(srna, "active_keyconfig", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "keyconfigstr"); RNA_def_property_ui_text(prop, "Key Config", "The name of the active key configuration"); } static void rna_def_userdef_filepaths_asset_library(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "UserAssetLibrary", NULL); RNA_def_struct_sdna(srna, "bUserAssetLibrary"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text( srna, "Asset Library", "Settings to define a reusable library for Asset Browsers to use"); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_property_ui_text( prop, "Name", "Identifier (not necessarily unique) for the asset library"); RNA_def_property_string_funcs(prop, NULL, NULL, "rna_userdef_asset_library_name_set"); RNA_def_struct_name_property(srna, prop); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "path", PROP_STRING, PROP_DIRPATH); RNA_def_property_ui_text( prop, "Path", "Path to a directory with .blend files to use as an asset library"); RNA_def_property_update(prop, 0, "rna_userdef_update"); } static void rna_def_userdef_filepaths(BlenderRNA *brna) { PropertyRNA *prop; StructRNA *srna; static const EnumPropertyItem anim_player_presets[] = { {0, "INTERNAL", 0, "Internal", "Built-in animation player"}, {2, "DJV", 0, "DJV", "Open source frame player: http://djv.sourceforge.net"}, {3, "FRAMECYCLER", 0, "FrameCycler", "Frame player from IRIDAS"}, {4, "RV", 0, "RV", "Frame player from Tweak Software"}, {5, "MPLAYER", 0, "MPlayer", "Media player for video and PNG/JPEG/SGI image sequences"}, {50, "CUSTOM", 0, "Custom", "Custom animation player executable path"}, {0, NULL, 0, NULL, NULL}, }; srna = RNA_def_struct(brna, "PreferencesFilePaths", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "File Paths", "Default paths for external files"); prop = RNA_def_property(srna, "show_hidden_files_datablocks", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_HIDE_DOT); RNA_def_property_ui_text(prop, "Hide Dot Files/Data-blocks", "Hide files and data-blocks if their name start with a dot (.*)"); prop = RNA_def_property(srna, "use_filter_files", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_FILTERFILEEXTS); RNA_def_property_ui_text(prop, "Filter File Extensions", "Display only files with extensions in the image select window"); prop = RNA_def_property(srna, "hide_recent_locations", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_HIDE_RECENT); RNA_def_property_ui_text( prop, "Hide Recent Locations", "Hide recent locations in the file selector"); prop = RNA_def_property(srna, "hide_system_bookmarks", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_HIDE_SYSTEM_BOOKMARKS); RNA_def_property_ui_text( prop, "Hide System Bookmarks", "Hide system bookmarks in the file selector"); prop = RNA_def_property(srna, "use_relative_paths", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_RELPATHS); RNA_def_property_ui_text( prop, "Relative Paths", "Default relative path option for the file selector"); prop = RNA_def_property(srna, "use_file_compression", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_FILECOMPRESS); RNA_def_property_ui_text( prop, "Compress File", "Enable file compression when saving .blend files"); prop = RNA_def_property(srna, "use_load_ui", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_FILENOUI); RNA_def_property_ui_text(prop, "Load UI", "Load user interface setup when loading .blend files"); RNA_def_property_update(prop, 0, "rna_userdef_load_ui_update"); prop = RNA_def_property(srna, "use_scripts_auto_execute", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_SCRIPT_AUTOEXEC_DISABLE); RNA_def_property_ui_text(prop, "Auto Run Python Scripts", "Allow any .blend file to run scripts automatically " "(unsafe with blend files from an untrusted source)"); RNA_def_property_update(prop, 0, "rna_userdef_script_autoexec_update"); prop = RNA_def_property(srna, "use_tabs_as_spaces", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_TXT_TABSTOSPACES_DISABLE); RNA_def_property_ui_text( prop, "Tabs as Spaces", "Automatically convert all new tabs into spaces for new and loaded text files"); /* Directories */ prop = RNA_def_property(srna, "font_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "fontdir"); RNA_def_property_ui_text( prop, "Fonts Directory", "The default directory to search for loading fonts"); prop = RNA_def_property(srna, "texture_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "textudir"); RNA_def_property_ui_text( prop, "Textures Directory", "The default directory to search for textures"); prop = RNA_def_property(srna, "render_output_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "renderdir"); RNA_def_property_ui_text(prop, "Render Output Directory", "The default directory for rendering output, for new scenes"); prop = RNA_def_property(srna, "script_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "pythondir"); RNA_def_property_ui_text( prop, "Python Scripts Directory", "Alternate script path, matching the default layout with subdirectories: " "startup, add-ons and modules (requires restart)"); /* TODO, editing should reset sys.path! */ prop = RNA_def_property(srna, "i18n_branches_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "i18ndir"); RNA_def_property_ui_text( prop, "Translation Branches Directory", "The path to the '/branches' directory of your local svn-translation copy, " "to allow translating from the UI"); prop = RNA_def_property(srna, "sound_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "sounddir"); RNA_def_property_ui_text(prop, "Sounds Directory", "The default directory to search for sounds"); prop = RNA_def_property(srna, "temporary_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "tempdir"); RNA_def_property_ui_text( prop, "Temporary Directory", "The directory for storing temporary save files"); RNA_def_property_update(prop, 0, "rna_userdef_temp_update"); prop = RNA_def_property(srna, "render_cache_directory", PROP_STRING, PROP_DIRPATH); RNA_def_property_string_sdna(prop, NULL, "render_cachedir"); RNA_def_property_ui_text(prop, "Render Cache Path", "Where to cache raw render results"); prop = RNA_def_property(srna, "image_editor", PROP_STRING, PROP_FILEPATH); RNA_def_property_string_sdna(prop, NULL, "image_editor"); RNA_def_property_ui_text(prop, "Image Editor", "Path to an image editor"); prop = RNA_def_property(srna, "animation_player", PROP_STRING, PROP_FILEPATH); RNA_def_property_string_sdna(prop, NULL, "anim_player"); RNA_def_property_ui_text( prop, "Animation Player", "Path to a custom animation/frame sequence player"); prop = RNA_def_property(srna, "animation_player_preset", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "anim_player_preset"); RNA_def_property_enum_items(prop, anim_player_presets); RNA_def_property_ui_text( prop, "Animation Player Preset", "Preset configs for external animation players"); /* Autosave */ prop = RNA_def_property(srna, "save_version", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "versions"); RNA_def_property_range(prop, 0, 32); RNA_def_property_ui_text( prop, "Save Versions", "The number of old versions to maintain in the current directory, when manually saving"); prop = RNA_def_property(srna, "use_auto_save_temporary_files", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_AUTOSAVE); RNA_def_property_ui_text(prop, "Auto Save Temporary Files", "Automatic saving of temporary files in temp directory, " "uses process ID (sculpt and edit mode data won't be saved)"); RNA_def_property_update(prop, 0, "rna_userdef_autosave_update"); prop = RNA_def_property(srna, "auto_save_time", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "savetime"); RNA_def_property_range(prop, 1, 60); RNA_def_property_ui_text( prop, "Auto Save Time", "The time (in minutes) to wait between automatic temporary saves"); RNA_def_property_update(prop, 0, "rna_userdef_autosave_update"); prop = RNA_def_property(srna, "recent_files", PROP_INT, PROP_NONE); RNA_def_property_range(prop, 0, 30); RNA_def_property_ui_text( prop, "Recent Files", "Maximum number of recently opened files to remember"); prop = RNA_def_property(srna, "use_save_preview_images", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_SAVE_PREVIEWS); RNA_def_property_ui_text(prop, "Save Preview Images", "Enables automatic saving of preview images in the .blend file"); rna_def_userdef_filepaths_asset_library(brna); prop = RNA_def_property(srna, "asset_libraries", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "UserAssetLibrary"); RNA_def_property_ui_text(prop, "Asset Libraries", ""); } static void rna_def_userdef_experimental(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "PreferencesExperimental", NULL); RNA_def_struct_sdna(srna, "UserDef_Experimental"); RNA_def_struct_nested(brna, srna, "Preferences"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Experimental", "Experimental features"); prop = RNA_def_property(srna, "use_undo_legacy", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_undo_legacy", 1); RNA_def_property_ui_text( prop, "Undo Legacy", "Use legacy undo (slower than the new default one, but may be more stable in some cases)"); prop = RNA_def_property(srna, "use_new_point_cloud_type", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_new_point_cloud_type", 1); RNA_def_property_ui_text( prop, "New Point Cloud Type", "Enable the new point cloud type in the ui"); prop = RNA_def_property(srna, "use_new_hair_type", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_new_hair_type", 1); RNA_def_property_ui_text(prop, "New Hair Type", "Enable the new hair type in the ui"); prop = RNA_def_property(srna, "use_cycles_debug", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_cycles_debug", 1); RNA_def_property_ui_text(prop, "Cycles Debug", "Enable Cycles debugging options for developers"); RNA_def_property_update(prop, 0, "rna_userdef_update"); prop = RNA_def_property(srna, "use_sculpt_vertex_colors", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_sculpt_vertex_colors", 1); RNA_def_property_ui_text(prop, "Sculpt Vertex Colors", "Use the new Vertex Painting system"); prop = RNA_def_property(srna, "use_switch_object_operator", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_switch_object_operator", 1); RNA_def_property_ui_text( prop, "Switch Object Operator", "Enable the operator to switch objects by pressing D"); prop = RNA_def_property(srna, "use_sculpt_tools_tilt", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_sculpt_tools_tilt", 1); RNA_def_property_ui_text( prop, "Sculpt Mode Tilt Support", "Support for pen tablet tilt events in Sculpt Mode"); prop = RNA_def_property(srna, "use_object_add_tool", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_object_add_tool", 1); RNA_def_property_ui_text( prop, "Add Object Tool", "Show add object tool in the toolbar in Object Mode and Edit Mode"); } static void rna_def_userdef_addon_collection(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "Addons"); srna = RNA_def_struct(brna, "Addons", NULL); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "User Add-ons", "Collection of add-ons"); func = RNA_def_function(srna, "new", "rna_userdef_addon_new"); RNA_def_function_flag(func, FUNC_NO_SELF); RNA_def_function_ui_description(func, "Add a new add-on"); /* return type */ parm = RNA_def_pointer(func, "addon", "Addon", "", "Add-on data"); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_userdef_addon_remove"); RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_REPORTS); RNA_def_function_ui_description(func, "Remove add-on"); parm = RNA_def_pointer(func, "addon", "Addon", "", "Add-on to remove"); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR); RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0); } static void rna_def_userdef_autoexec_path_collection(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "PathCompareCollection"); srna = RNA_def_struct(brna, "PathCompareCollection", NULL); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Paths Compare", "Collection of paths"); func = RNA_def_function(srna, "new", "rna_userdef_pathcompare_new"); RNA_def_function_flag(func, FUNC_NO_SELF); RNA_def_function_ui_description(func, "Add a new path"); /* return type */ parm = RNA_def_pointer(func, "pathcmp", "PathCompare", "", ""); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_userdef_pathcompare_remove"); RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_REPORTS); RNA_def_function_ui_description(func, "Remove path"); parm = RNA_def_pointer(func, "pathcmp", "PathCompare", "", ""); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR); RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0); } void RNA_def_userdef(BlenderRNA *brna) { USERDEF_TAG_DIRTY_PROPERTY_UPDATE_ENABLE; StructRNA *srna; PropertyRNA *prop; rna_def_userdef_dothemes(brna); rna_def_userdef_solidlight(brna); rna_def_userdef_walk_navigation(brna); srna = RNA_def_struct(brna, "Preferences", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_clear_flag(srna, STRUCT_UNDO); RNA_def_struct_ui_text(srna, "Preferences", "Global preferences"); prop = RNA_def_property(srna, "active_section", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "space_data.section_active"); RNA_def_property_enum_items(prop, rna_enum_preference_section_items); RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_UseDef_active_section_itemf"); RNA_def_property_ui_text( prop, "Active Section", "Active section of the preferences shown in the user interface"); RNA_def_property_update(prop, 0, "rna_userdef_ui_update"); /* don't expose this directly via the UI, modify via an operator */ prop = RNA_def_property(srna, "app_template", PROP_STRING, PROP_NONE); RNA_def_property_string_sdna(prop, NULL, "app_template"); RNA_def_property_ui_text(prop, "Application Template", ""); prop = RNA_def_property(srna, "themes", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "themes", NULL); RNA_def_property_struct_type(prop, "Theme"); RNA_def_property_ui_text(prop, "Themes", ""); prop = RNA_def_property(srna, "ui_styles", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "uistyles", NULL); RNA_def_property_struct_type(prop, "ThemeStyle"); RNA_def_property_ui_text(prop, "Styles", ""); prop = RNA_def_property(srna, "addons", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "addons", NULL); RNA_def_property_struct_type(prop, "Addon"); RNA_def_property_ui_text(prop, "Add-on", ""); rna_def_userdef_addon_collection(brna, prop); prop = RNA_def_property(srna, "autoexec_paths", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "autoexec_paths", NULL); RNA_def_property_struct_type(prop, "PathCompare"); RNA_def_property_ui_text(prop, "Auto-Execution Paths", ""); rna_def_userdef_autoexec_path_collection(brna, prop); /* nested structs */ prop = RNA_def_property(srna, "view", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesView"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_view_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "View & Controls", "Preferences related to viewing data"); prop = RNA_def_property(srna, "edit", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesEdit"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_edit_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Edit Methods", "Settings for interacting with Blender data"); prop = RNA_def_property(srna, "inputs", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesInput"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_input_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Inputs", "Settings for input devices"); prop = RNA_def_property(srna, "keymap", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesKeymap"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_keymap_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Keymap", "Shortcut setup for keyboards and other input devices"); prop = RNA_def_property(srna, "filepaths", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesFilePaths"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_filepaths_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "File Paths", "Default paths for external files"); prop = RNA_def_property(srna, "system", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesSystem"); RNA_def_property_pointer_funcs(prop, "rna_UserDef_system_get", NULL, NULL, NULL); RNA_def_property_ui_text( prop, "System & OpenGL", "Graphics driver and operating system settings"); prop = RNA_def_property(srna, "experimental", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_struct_type(prop, "PreferencesExperimental"); RNA_def_property_ui_text( prop, "Experimental", "Settings for features that are still early in their development stage"); prop = RNA_def_int_vector(srna, "version", 3, NULL, 0, INT_MAX, "Version", "Version of Blender the userpref.blend was saved with", 0, INT_MAX); RNA_def_property_int_funcs(prop, "rna_userdef_version_get", NULL, NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_flag(prop, PROP_THICK_WRAP); /* StudioLight Collection */ prop = RNA_def_property(srna, "studio_lights", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "StudioLight"); RNA_def_property_srna(prop, "StudioLights"); RNA_def_property_collection_funcs(prop, "rna_UserDef_studiolight_begin", "rna_iterator_listbase_next", "rna_iterator_listbase_end", "rna_iterator_listbase_get", NULL, NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Studio Lights", ""); /* Preferences Flags */ prop = RNA_def_property(srna, "use_preferences_save", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "pref_flag", USER_PREF_FLAG_SAVE); RNA_def_property_ui_text(prop, "Save on Exit", "Save preferences on exit when modified " "(unless factory settings have been loaded)"); prop = RNA_def_property(srna, "is_dirty", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "runtime.is_dirty", 0); RNA_def_property_ui_text(prop, "Dirty", "Preferences have changed"); RNA_def_property_update(prop, 0, "rna_userdef_ui_update"); rna_def_userdef_view(brna); rna_def_userdef_edit(brna); rna_def_userdef_input(brna); rna_def_userdef_keymap(brna); rna_def_userdef_filepaths(brna); rna_def_userdef_system(brna); rna_def_userdef_addon(brna); rna_def_userdef_addon_pref(brna); rna_def_userdef_studiolights(brna); rna_def_userdef_studiolight(brna); rna_def_userdef_pathcompare(brna); rna_def_userdef_experimental(brna); USERDEF_TAG_DIRTY_PROPERTY_UPDATE_DISABLE; } #endif
552716.c
/* lnknxt.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Table of constant values */ static integer c__0 = 0; /* $Procedure LNKNXT ( LNK, next node ) */ integer lnknxt_(integer *node, integer *pool) { /* System generated locals */ integer ret_val; /* Local variables */ extern /* Subroutine */ int chkin_(char *, ftnlen), sigerr_(char *, ftnlen), chkout_(char *, ftnlen), setmsg_(char *, ftnlen), errint_(char *, integer *, ftnlen); /* $ Abstract */ /* Find the node following a specified node in a doubly linked list */ /* pool. */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Required_Reading */ /* None. */ /* $ Keywords */ /* LIST */ /* $ Declarations */ /* $ Brief_I/O */ /* VARIABLE I/O DESCRIPTION */ /* -------- --- -------------------------------------------------- */ /* NODE I Number of an allocated node. */ /* POOL I A doubly linked list pool. */ /* LBPOOL P Lower bound of pool column indices. */ /* The function returns the number of the successor of the node */ /* indicated by NODE. */ /* $ Detailed_Input */ /* NODE is the number of an allocated node in POOL. */ /* POOL is a doubly linked list pool. */ /* $ Detailed_Output */ /* The function returns the number of the successor of the node */ /* indicated by NODE. If NODE is the tail node of a list, the */ /* function returns the negative of the node number of the head */ /* of the list. */ /* $ Parameters */ /* LBPOOL is the lower bound of the column indices of the POOL */ /* array. The columns indexed LBPOOL to 0 are reserved */ /* as a control area for the pool. */ /* $ Exceptions */ /* 1) If NODE is the tail node of a list, the function returns the */ /* negative of the node number of the head of the list. */ /* 2) If NODE is not a valid node number, the error */ /* SPICE(INVALIDNODE) is signaled. The value 0 is returned. */ /* 3) If NODE is not the number of an allocated node, the error */ /* SPICE(UNALLOCATEDNODE) is signaled. The value 0 is returned. */ /* $ Files */ /* None. */ /* $ Particulars */ /* The raison d'etre of this routine is to allow forward traversal */ /* of lists in a doubly linked list pool. */ /* Traversing a list is often performed in cases where the list is */ /* used to index elements of a data structure, and the elements */ /* indexed by the list must be searched. */ /* To traverse a list in backward order, use LNKPRV. */ /* $ Examples */ /* 1) Let POOL be doubly linked list pool, and let */ /* 3 <--> 7 <--> 1 */ /* be a list in the pool. The table below shows the effects */ /* of function references to LNKNXT, where nodes in this list */ /* are used as inputs: */ /* Function reference Value Returned */ /* ------------------ -------------- */ /* LNKNXT ( 3, POOL ) 7 */ /* LNKNXT ( 7, POOL ) 1 */ /* LNKNXT ( 1, POOL ) -3 */ /* 2) Forward traversal of a list: Let POOL be a doubly linked */ /* list pool, and let NODE be an allocated node in the pool. */ /* To traverse the list containing NODE in forward order */ /* and print out the nodes of the list, we can use the */ /* following code fragment: */ /* C */ /* C Find the head of the list containing NODE. */ /* C */ /* NEXT = LNKHL ( NODE, POOL ) */ /* C */ /* C Traverse the list, printing out node numbers */ /* C as we go. */ /* C */ /* WRITE (*,*) 'The list, in forward order, is: ' */ /* DO WHILE ( NEXT .GT. 0 ) */ /* WRITE (*,*) NEXT */ /* NEXT = LNKNXT ( NEXT, POOL ) */ /* END DO */ /* $ Restrictions */ /* 1) Linked list pools must be initialized via the routine */ /* LNKINI. Failure to initialize a linked list pool */ /* will almost certainly lead to confusing results. */ /* $ Literature_References */ /* None. */ /* $ Author_and_Institution */ /* N.J. Bachman (JPL) */ /* J. Diaz del Rio (ODC Space) */ /* W.L. Taber (JPL) */ /* $ Version */ /* - SPICELIB Version 1.0.1, 24-NOV-2021 (JDR) */ /* Edited the header to comply with NAIF standard. */ /* - SPICELIB Version 1.0.0, 19-DEC-1995 (NJB) (WLT) */ /* -& */ /* $ Index_Entries */ /* return next node in linked list */ /* -& */ /* Local parameters */ /* The control area contains 3 elements. They are: */ /* The "size" of the pool, that is, the number */ /* of nodes in the pool. */ /* The number of free nodes in the pool. */ /* The "free pointer," which is the column index of the first free */ /* node. */ /* Parameters defining the row and column indices of these control */ /* elements are given below. */ /* Each assigned node consists of a backward pointer and a forward */ /* pointer. */ /* +-------------+ +-------------+ +-------------+ */ /* | forward--> | | forward--> | | forward--> | */ /* +-------------+ ... +-------------+ ... +-------------+ */ /* | <--backward | | <--backward | | <--backward | */ /* +-------------+ +-------------+ +-------------+ */ /* node 1 node I node SIZE */ /* Free nodes say that that's what they are. The way they say it */ /* is by containing the value FREE in their backward pointers. */ /* Needless to say, FREE is a value that cannot be a valid pointer. */ /* If the node is out of range, something's very wrong. */ if (*node < 1 || *node > pool[10]) { ret_val = 0; chkin_("LNKNXT", (ftnlen)6); setmsg_("NODE was #; valid range is 1 to #.", (ftnlen)34); errint_("#", node, (ftnlen)1); errint_("#", &pool[10], (ftnlen)1); sigerr_("SPICE(INVALIDNODE)", (ftnlen)18); chkout_("LNKNXT", (ftnlen)6); return ret_val; /* We don't do free nodes. */ } else if (pool[(*node << 1) + 11] == 0) { ret_val = 0; chkin_("LNKNXT", (ftnlen)6); setmsg_("NODE was #; backward pointer = #; forward pointer = #. \"FR" "EE\" is #)", (ftnlen)67); errint_("#", node, (ftnlen)1); errint_("#", &pool[(*node << 1) + 11], (ftnlen)1); errint_("#", &pool[(*node << 1) + 10], (ftnlen)1); errint_("#", &c__0, (ftnlen)1); sigerr_("SPICE(UNALLOCATEDNODE)", (ftnlen)22); chkout_("LNKNXT", (ftnlen)6); return ret_val; } /* Just return the forward pointer of NODE. */ ret_val = pool[(*node << 1) + 10]; return ret_val; } /* lnknxt_ */
575050.c
/* delay.c file 编写者:lisn3188 网址:www.chiplab7.com 作者E-mail:[email protected] 编译环境:MDK-Lite Version: 4.23 初版时间: 2012-04-25 测试: 本程序已在第七实验室的mini IMU上完成测试 功能: 提供精确的延时API 有微秒级 和毫秒级延时 ------------------------------------ */ #include "delay.h" #if 0 static u8 fac_us = 0;//us延时倍乘数 static u16 fac_ms = 0;//ms延时倍乘数 #endif #include "freertos/include/FreeRTOS.h" #include "freertos/include/task.h" //初始化延迟函数 //SYSTICK的时钟固定为HCLK时钟的1/8 //SYSCLK:系统时钟 /**************************实现函数******************************************** *函数原型: void delay_init(u8 SYSCLK) *功  能: 初始化延迟系统,使延时程序进入可用状态 *******************************************************************************/ #if 0 void delay_init(u8 SYSCLK) { SysTick->CTRL &= 0xfffffffb; //bit2清空,选择外部时钟 HCLK/8 fac_us = SYSCLK / 8; fac_ms = (u16)fac_us * 1000; } #endif //延时nms //注意nms的范围 //SysTick->LOAD为24位寄存器,所以,最大延时为: //nms<=0xffffff*8*1000/SYSCLK //SYSCLK单位为Hz,nms单位为ms /**************************实现函数******************************************** *函数原型: void delay_ms(u16 nms) *功  能: 毫秒级延时 延时nms nms<=1864 *******************************************************************************/ void delay_ms(u16 nms) { #if 0 u32 temp; SysTick->LOAD = (u32)nms * fac_ms;//时间加载(SysTick->LOAD为24bit) SysTick->VAL = 0x00; //清空计数器 SysTick->CTRL = 0x01; //开始倒数 do { temp = SysTick->CTRL; } while(temp & 0x01 && !(temp & (1<<16)));//等待时间到达 SysTick->CTRL = 0x00; //关闭计数器 SysTick->VAL = 0X00; //清空计数器 #else vTaskDelay(1 / portTICK_RATE_MS); #endif } //延时nus //nus为要延时的us数. /**************************实现函数******************************************** *函数原型: void delay_us(u32 nus) *功  能: 微秒级延时 延时nus nms<=1864 *******************************************************************************/ void delay_us(u32 nus) { #if 0 u32 temp; SysTick->LOAD=nus*fac_us; //时间加载 SysTick->VAL=0x00; //清空计数器 SysTick->CTRL=0x01; //开始倒数 do { temp = SysTick->CTRL; } while(temp & 0x01 && !(temp & (1<<16)));//等待时间到达 SysTick->CTRL = 0x00; //关闭计数器 SysTick->VAL = 0X00; //清空计数器 #endif uint8_t i; for(i=0;i<nus*5;i++) __DMB(); } #if 0 void delay(u32 x) { u32 i,j; for(i=0;i<x;i++) for(j=0;j<500;j++); } #endif
354068.c
#include "text_input.h" #include "../assets.h" #define TEXT_INPUT_PADDING 2 void on_keyboard_key(int key, void* user_data); void on_keyboard_bakspace(void* user_data); void on_keyboard_done(void* user_data); void rr_ui_text_input_init_keyboard_sprite(rrUiTextInput* text_input); void rr_ui_text_input_init(rrUiTextInput* text_input, rrInput* input, rrRenderer* renderer, rrPoint* pos) { text_input->_input = input; text_input->_renderer = renderer; text_input->strbuf = cutil_strbuf_create_with_cstring("W"); text_input->width_override = 0; text_input->text_entered_callback = NULL; text_input->callback_data = NULL; rr_point_copy(&text_input->element.position, pos); text_input->element.active = 0; text_input->onscreen_keyboard = rr_ui_onscreen_keyboard_create(renderer, input); text_input->onscreen_keyboard->on_char = on_keyboard_key; text_input->onscreen_keyboard->on_backspace = on_keyboard_bakspace; text_input->onscreen_keyboard->on_done = on_keyboard_done; text_input->onscreen_keyboard->user_data = text_input; /* 'W' used for layout height measurement purposes only. */ rr_ui_text_input_init_keyboard_sprite(text_input); cutil_strbuf_pop_back(text_input->strbuf); } void rr_ui_text_input_uninit(rrUiTextInput* text_input) { cutil_strbuf_destroy(text_input->strbuf); rr_ui_onscreen_keyboard_destroy(text_input->onscreen_keyboard); } void rr_ui_text_input_show(rrUiTextInput* text_input) { cutil_strbuf_clear(text_input->strbuf); rr_ui_onscreen_keyboard_show(text_input->onscreen_keyboard); } void rr_ui_text_input_draw(rrUiTextInput* text_input) { rrColor color; rrRect draw_rect; rrPoint draw_pos; rr_ui_text_input_get_rect(text_input, &draw_rect); rr_color_white(&color); rr_renderer_color(text_input->_renderer, &color); rr_renderer_fill_rect(text_input->_renderer, &draw_rect); if (text_input->element.active) { rr_color_black(&color); rr_renderer_color(text_input->_renderer, &color); rr_renderer_draw_rect(text_input->_renderer, &draw_rect); } rr_point_copy(&draw_pos, &text_input->element.position); draw_pos.x += TEXT_INPUT_PADDING; draw_pos.y += TEXT_INPUT_PADDING; if (cutil_strbuf_length(text_input->strbuf) > 0) rr_renderer_draw_sprite(text_input->_renderer, text_input->_text_sprite, &draw_pos); if (text_input->onscreen_keyboard->active) { rr_ui_onscreen_keyboard_draw(text_input->onscreen_keyboard); } } void rr_ui_text_input_get_rect(rrUiTextInput* text_input, rrRect* rect) { rect->x = text_input->element.position.x; rect->y = text_input->element.position.y; if (text_input->width_override > 0) rect->w = text_input->width_override + (2 * TEXT_INPUT_PADDING); else rect->w = text_input->_text_sprite->rect.w + (2 * TEXT_INPUT_PADDING); rect->h = text_input->_text_sprite->rect.h + (2 * TEXT_INPUT_PADDING); } void rr_ui_text_input_init_keyboard_sprite(rrUiTextInput* text_input) { rrColor color; rr_color_black(&color); text_input->_text_sprite = rr_renderer_create_text(text_input->_renderer, RR_FONT_BUTTON, cutil_strbuf_cstring(text_input->strbuf)); rr_renderer_set_sprite_tint_color(text_input->_renderer, text_input->_text_sprite, &color); } void rr_ui_text_input_update(rrUiTextInput* text_input) { if (!text_input->element.active) return; if (rr_input_button_down(text_input->_input, RR_INPUT_BUTTON_ACCEPT) && !text_input->onscreen_keyboard->active) rr_ui_onscreen_keyboard_show(text_input->onscreen_keyboard); else if (text_input->onscreen_keyboard->active) { rr_ui_onscreen_keyboard_update(text_input->onscreen_keyboard); } } void on_keyboard_key(int key, void* user_data) { rrUiTextInput* text_input = (rrUiTextInput*)user_data; cutil_strbuf_append_char(text_input->strbuf, (char)key); rr_renderer_update_text_sprite(text_input->_renderer, text_input->_text_sprite, RR_FONT_BUTTON, cutil_strbuf_cstring(text_input->strbuf)); } void on_keyboard_bakspace(void* user_data) { rrUiTextInput* text_input = (rrUiTextInput*)user_data; cutil_strbuf_pop_back(text_input->strbuf); rr_renderer_update_text_sprite(text_input->_renderer, text_input->_text_sprite, RR_FONT_BUTTON, cutil_strbuf_cstring(text_input->strbuf)); } void on_keyboard_done(void* user_data) { rrUiTextInput* text_input = (rrUiTextInput*)user_data; text_input->onscreen_keyboard->active = 0; if (text_input->text_entered_callback) text_input->text_entered_callback(text_input->callback_data); } const char* rr_ui_text_get_str(rrUiTextInput* text_input) { return cutil_strbuf_cstring(text_input->strbuf); }
908293.c
#include <stdlib.h> //Definition for singly-linked list. struct ListNode { int val; struct ListNode *next; }; struct ListNode *createNode(int val) { struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->next = NULL; node->val = val; return node; } typedef struct { struct ListNode **data; int *dataColSize; int dataSize; int c; //capacity int s; //size (count of all element) int p; //push index int v; //pop index } DinnerPlates; DinnerPlates *dinnerPlatesCreate(int capacity) { int size = 100000; DinnerPlates *plates = (DinnerPlates *)malloc(sizeof(DinnerPlates)); plates->dataSize = 0; plates->data = (struct ListNode *)malloc(sizeof(struct ListNode *) * size); memset(plates->data, 0, sizeof(struct ListNode *) * size); plates->dataColSize = (int *)malloc(sizeof(int) * size); memset(plates->dataColSize, 0, sizeof(int) * size); plates->c = capacity; plates->s = plates->p = plates->v = 0; return plates; } void dinnerPlatesPush(DinnerPlates *obj, int val) { ++obj->s; while (obj->p < obj->dataSize && obj->dataColSize[obj->p] == obj->c) ++obj->p; if (obj->p >= obj->dataSize) obj->p = obj->dataSize++; struct ListNode *node = createNode(val); node->next = obj->data[obj->p]; obj->data[obj->p] = node; ++obj->dataColSize[obj->p]; if (obj->p > obj->v) obj->v = obj->p; } int dinnerPlatesPop(DinnerPlates *obj) { if (obj->s == 0) return -1; --obj->s; int res = -1; while (obj->v >= 0 && obj->dataColSize[obj->v] == 0) --obj->v; res = obj->data[obj->v]->val; obj->data[obj->v] = obj->data[obj->v]->next; --obj->dataColSize[obj->v]; if (obj->p > obj->v) obj->p = obj->v; return res; } int dinnerPlatesPopAtStack(DinnerPlates *obj, int index) { int res = -1; if (index < obj->dataSize) { if (obj->data[index]) { --obj->s; --obj->dataColSize[index]; res = obj->data[index]->val; obj->data[index] = obj->data[index]->next; if (obj->p > index) obj->p = index; } } return res; } void dinnerPlatesFree(DinnerPlates *obj) { if (obj) { for (int i = 0; i < obj->dataSize; ++i) { for (struct ListNode *node = obj->data[i]; node;) { struct ListNode *deleted_node = node; node = node->next; free(deleted_node); } } free(obj); } } /** * Your DinnerPlates struct will be instantiated and called as such: * DinnerPlates* obj = dinnerPlatesCreate(capacity); * dinnerPlatesPush(obj, val); * int param_2 = dinnerPlatesPop(obj); * int param_3 = dinnerPlatesPopAtStack(obj, index); * dinnerPlatesFree(obj); */
838764.c
/** * @file * Dynamic pool memory manager * * lwIP has dedicated pools for many structures (netconn, protocol control blocks, * packet buffers, ...). All these pools are managed here. */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <[email protected]> * */ /** * @defgroup mempool Memory pools * @ingroup infrastructure * Custom memory pools */ #include "lwip/opt.h" #include "lwip/memp.h" #include "lwip/sys.h" #include "lwip/stats.h" #include <string.h> /* Make sure we include everything we need for size calculation required by memp_std.h */ #include "lwip/pbuf.h" #include "lwip/raw.h" #include "lwip/udp.h" #include "lwip/tcp.h" #include "lwip/priv/tcp_priv.h" #include "lwip/ip4_frag.h" #include "lwip/netbuf.h" #include "lwip/api.h" #include "lwip/priv/tcpip_priv.h" #include "lwip/priv/api_msg.h" #include "lwip/sockets.h" #include "lwip/netifapi.h" #include "lwip/etharp.h" #include "lwip/igmp.h" #include "lwip/timeouts.h" /* needed by default MEMP_NUM_SYS_TIMEOUT */ #include "netif/ppp/ppp_opts.h" #include "lwip/netdb.h" #include "lwip/dns.h" #include "lwip/nd6.h" #include "lwip/ip6_frag.h" #include "lwip/mld6.h" #define LWIP_MEMPOOL(name,num,size,desc) LWIP_MEMPOOL_DECLARE(name,num,size,desc) #include "lwip/priv/memp_std.h" const struct memp_desc* const memp_pools[MEMP_MAX] = { #define LWIP_MEMPOOL(name,num,size,desc) &memp_ ## name, #include "lwip/priv/memp_std.h" }; #if MEMP_MEM_MALLOC && MEMP_OVERFLOW_CHECK >= 2 #undef MEMP_OVERFLOW_CHECK /* MEMP_OVERFLOW_CHECK >= 2 does not work with MEMP_MEM_MALLOC, use 1 instead */ #define MEMP_OVERFLOW_CHECK 1 #endif #if MEMP_SANITY_CHECK && !MEMP_MEM_MALLOC /** * Check that memp-lists don't form a circle, using "Floyd's cycle-finding algorithm". */ static int memp_sanity(const struct memp_desc *desc) { struct memp *t, *h; t = *desc->tab; if (t != NULL) { for (h = t->next; (t != NULL) && (h != NULL); t = t->next, h = ((h->next != NULL) ? h->next->next : NULL)) { if (t == h) { return 0; } } } return 1; } #endif /* MEMP_SANITY_CHECK && !MEMP_MEM_MALLOC */ #if MEMP_OVERFLOW_CHECK /** * Check if a memp element was victim of an overflow * (e.g. the restricted area after it has been altered) * * @param p the memp element to check * @param memp_type the pool p comes from */ static void memp_overflow_check_element_overflow(struct memp *p, const struct memp_desc *desc) { u16_t k; u8_t *m; #if MEMP_SANITY_REGION_AFTER_ALIGNED > 0 m = (u8_t*)p + MEMP_SIZE + desc->size; for (k = 0; k < MEMP_SANITY_REGION_AFTER_ALIGNED; k++) { if (m[k] != 0xcd) { char errstr[128] = "detected memp overflow in pool "; strcat(errstr, desc->desc); LWIP_ASSERT(errstr, 0); } } #endif } /** * Check if a memp element was victim of an underflow * (e.g. the restricted area before it has been altered) * * @param p the memp element to check * @param memp_type the pool p comes from */ static void memp_overflow_check_element_underflow(struct memp *p, const struct memp_desc *desc) { u16_t k; u8_t *m; #if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0 m = (u8_t*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED; for (k = 0; k < MEMP_SANITY_REGION_BEFORE_ALIGNED; k++) { if (m[k] != 0xcd) { char errstr[128] = "detected memp underflow in pool "; strcat(errstr, desc->desc); LWIP_ASSERT(errstr, 0); } } #endif } /** * Initialize the restricted area of on memp element. */ static void memp_overflow_init_element(struct memp *p, const struct memp_desc *desc) { u8_t *m; #if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0 m = (u8_t*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED; memset(m, 0xcd, MEMP_SANITY_REGION_BEFORE_ALIGNED); #endif #if MEMP_SANITY_REGION_AFTER_ALIGNED > 0 m = (u8_t*)p + MEMP_SIZE + desc->size; memset(m, 0xcd, MEMP_SANITY_REGION_AFTER_ALIGNED); #endif } #if MEMP_OVERFLOW_CHECK >= 2 /** * Do an overflow check for all elements in every pool. * * @see memp_overflow_check_element for a description of the check */ static void memp_overflow_check_all(void) { u16_t i, j; struct memp *p; SYS_ARCH_DECL_PROTECT(old_level); SYS_ARCH_PROTECT(old_level); for (i = 0; i < MEMP_MAX; ++i) { p = (struct memp *)(size_t)(memp_pools[i]->base); for (j = 0; j < memp_pools[i]->num; ++j) { memp_overflow_check_element_overflow(p, memp_pools[i]); memp_overflow_check_element_underflow(p, memp_pools[i]); p = (struct memp*)(size_t)((u8_t*)p + MEMP_SIZE + memp_pools[i]->size + MEMP_SANITY_REGION_AFTER_ALIGNED); } } SYS_ARCH_UNPROTECT(old_level); } #endif /* MEMP_OVERFLOW_CHECK >= 2 */ #if !MEMP_MEM_MALLOC /** * Initialize the restricted areas of all memp elements in a pool. */ static void memp_overflow_init(const struct memp_desc *desc) { u16_t i; struct memp *p; p = (struct memp*)LWIP_MEM_ALIGN(desc->base); for (i = 0; i < desc->num; ++i) { memp_overflow_init_element(p, desc); p = (struct memp*)(size_t)((u8_t*)p + MEMP_SIZE + desc->size + MEMP_SANITY_REGION_AFTER_ALIGNED); } } #endif /* !MEMP_MEM_MALLOC */ #endif /* MEMP_OVERFLOW_CHECK */ /** * Initialize custom memory pool. * Related functions: memp_malloc_pool, memp_free_pool * * @param desc pool to initialize */ void memp_init_pool(const struct memp_desc *desc) { #if MEMP_MEM_MALLOC LWIP_UNUSED_ARG(desc); #else int i; struct memp *memp; *desc->tab = NULL; memp = (struct memp*)LWIP_MEM_ALIGN(desc->base); /* create a linked list of memp elements */ for (i = 0; i < desc->num; ++i) { memp->next = *desc->tab; *desc->tab = memp; /* cast through void* to get rid of alignment warnings */ memp = (struct memp *)(void *)((u8_t *)memp + MEMP_SIZE + desc->size #if MEMP_OVERFLOW_CHECK + MEMP_SANITY_REGION_AFTER_ALIGNED #endif ); } #if MEMP_OVERFLOW_CHECK memp_overflow_init(desc); #endif /* MEMP_OVERFLOW_CHECK */ #endif /* !MEMP_MEM_MALLOC */ #if MEMP_STATS #if !MEMP_MEM_MALLOC desc->stats->avail = desc->num; #endif /* !MEMP_MEM_MALLOC */ #if defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY desc->stats->name = desc->desc; #endif /* defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY */ #endif /* MEMP_STATS */ } /** * Initializes lwIP built-in pools. * Related functions: memp_malloc, memp_free * * Carves out memp_memory into linked lists for each pool-type. */ void memp_init(void) { u16_t i; /* for every pool: */ for (i = 0; i < LWIP_ARRAYSIZE(memp_pools); i++) { memp_init_pool(memp_pools[i]); #if LWIP_STATS && MEMP_STATS lwip_stats.memp[i] = memp_pools[i]->stats; #endif } #if MEMP_OVERFLOW_CHECK >= 2 /* check everything a first time to see if it worked */ memp_overflow_check_all(); #endif /* MEMP_OVERFLOW_CHECK >= 2 */ } static void* #if !MEMP_OVERFLOW_CHECK do_memp_malloc_pool(const struct memp_desc *desc) #else do_memp_malloc_pool_fn(const struct memp_desc *desc, const char* file, const int line) #endif { struct memp *memp; SYS_ARCH_DECL_PROTECT(old_level); #if MEMP_MEM_MALLOC memp = (struct memp *)mem_malloc(MEMP_SIZE + MEMP_ALIGN_SIZE(desc->size)); SYS_ARCH_PROTECT(old_level); #else /* MEMP_MEM_MALLOC */ SYS_ARCH_PROTECT(old_level); memp = *desc->tab; #if MEMP_OVERFLOW_CHECK == 1 memp_overflow_check_element_overflow(memp, desc); memp_overflow_check_element_underflow(memp, desc); #endif /* MEMP_OVERFLOW_CHECK */ #endif /* MEMP_MEM_MALLOC */ if (memp != NULL) { #if !MEMP_MEM_MALLOC *desc->tab = memp->next; #if MEMP_OVERFLOW_CHECK memp->next = NULL; #endif /* MEMP_OVERFLOW_CHECK */ #endif /* !MEMP_MEM_MALLOC */ #if MEMP_OVERFLOW_CHECK memp->file = file; memp->line = line; #if MEMP_MEM_MALLOC memp_overflow_init_element(memp, desc); #endif /* MEMP_MEM_MALLOC */ #endif /* MEMP_OVERFLOW_CHECK */ LWIP_ASSERT("memp_malloc: memp properly aligned", ((mem_ptr_t)memp % MEM_ALIGNMENT) == 0); #if MEMP_STATS desc->stats->used++; if (desc->stats->used > desc->stats->max) { desc->stats->max = desc->stats->used; } #endif SYS_ARCH_UNPROTECT(old_level); /* cast through u8_t* to get rid of alignment warnings */ return ((u8_t*)memp + MEMP_SIZE); } else { LWIP_DEBUGF(MEMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("memp_malloc: out of memory in pool %s\n", desc->desc)); #if MEMP_STATS desc->stats->err++; #endif } SYS_ARCH_UNPROTECT(old_level); return NULL; } /** * Get an element from a custom pool. * * @param desc the pool to get an element from * * @return a pointer to the allocated memory or a NULL pointer on error */ void * #if !MEMP_OVERFLOW_CHECK memp_malloc_pool(const struct memp_desc *desc) #else memp_malloc_pool_fn(const struct memp_desc *desc, const char* file, const int line) #endif { LWIP_ASSERT("invalid pool desc", desc != NULL); if (desc == NULL) { return NULL; } #if !MEMP_OVERFLOW_CHECK return do_memp_malloc_pool(desc); #else return do_memp_malloc_pool_fn(desc, file, line); #endif } /** * Get an element from a specific pool. * * @param type the pool to get an element from * * @return a pointer to the allocated memory or a NULL pointer on error */ void * #if !MEMP_OVERFLOW_CHECK memp_malloc(memp_t type) #else memp_malloc_fn(memp_t type, const char* file, const int line) #endif { void *memp; LWIP_ERROR("memp_malloc: type < MEMP_MAX", (type < MEMP_MAX), return NULL;); #if MEMP_OVERFLOW_CHECK >= 2 memp_overflow_check_all(); #endif /* MEMP_OVERFLOW_CHECK >= 2 */ #if !MEMP_OVERFLOW_CHECK memp = do_memp_malloc_pool(memp_pools[type]); #else memp = do_memp_malloc_pool_fn(memp_pools[type], file, line); #endif return memp; } static void do_memp_free_pool(const struct memp_desc* desc, void *mem) { struct memp *memp; SYS_ARCH_DECL_PROTECT(old_level); LWIP_ASSERT("memp_free: mem properly aligned", ((mem_ptr_t)mem % MEM_ALIGNMENT) == 0); /* cast through void* to get rid of alignment warnings */ memp = (struct memp *)(void *)((u8_t*)mem - MEMP_SIZE); SYS_ARCH_PROTECT(old_level); #if MEMP_OVERFLOW_CHECK == 1 memp_overflow_check_element_overflow(memp, desc); memp_overflow_check_element_underflow(memp, desc); #endif /* MEMP_OVERFLOW_CHECK */ #if MEMP_STATS desc->stats->used--; #endif #if MEMP_MEM_MALLOC LWIP_UNUSED_ARG(desc); SYS_ARCH_UNPROTECT(old_level); mem_free(memp); #else /* MEMP_MEM_MALLOC */ memp->next = *desc->tab; *desc->tab = memp; #if MEMP_SANITY_CHECK LWIP_ASSERT("memp sanity", memp_sanity(desc)); #endif /* MEMP_SANITY_CHECK */ SYS_ARCH_UNPROTECT(old_level); #endif /* !MEMP_MEM_MALLOC */ } /** * Put a custom pool element back into its pool. * * @param desc the pool where to put mem * @param mem the memp element to free */ void memp_free_pool(const struct memp_desc* desc, void *mem) { LWIP_ASSERT("invalid pool desc", desc != NULL); if ((desc == NULL) || (mem == NULL)) { return; } do_memp_free_pool(desc, mem); } /** * Put an element back into its pool. * * @param type the pool where to put mem * @param mem the memp element to free */ void memp_free(memp_t type, void *mem) { #ifdef LWIP_HOOK_MEMP_AVAILABLE struct memp *old_first; #endif LWIP_ERROR("memp_free: type < MEMP_MAX", (type < MEMP_MAX), return;); #if MEMP_OVERFLOW_CHECK >= 2 memp_overflow_check_all(); #endif /* MEMP_OVERFLOW_CHECK >= 2 */ #ifdef LWIP_HOOK_MEMP_AVAILABLE old_first = memp_pools[type].tab; #endif do_memp_free_pool(memp_pools[type], mem); #ifdef LWIP_HOOK_MEMP_AVAILABLE if (old_first == NULL) { LWIP_HOOK_MEMP_AVAILABLE(type); } #endif }
285351.c
#include <tk.h> #if defined(__WIN32__) || defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include <windows.h> # undef WIN32_LEAN_AND_MEAN #endif #include <math.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "gencyl.h" #include "tkogl.h" #ifndef PI /* The ubiquitous PI constant */ #define PI 3.14159265358979323846264338327950288 #endif /* Constants that define the various flags for rendering a generic * cylinder */ #define STITCH_ENDS 0x01 /* Stitch together the ends of the cyl */ #define STITCH_LOOPS 0x02 /* Close the cross-sections of the cyl */ #define SHADE_SMOOTH_ROWS 0x04 /* Average normals across rows */ #define SHADE_SMOOTH_COLS 0x08 /* Average normals across columns */ #define TEXTURE_GEN 0x10 /* Generate texture coordinates */ #define ADAPTIVE 0x20 /* Average only normals which form a small angle */ #define CLOSE_FIRST 0x40 /* Close first cross section */ #define CLOSE_LAST 0x80 /* Close last cross section */ /*--------------------------------------------------------------------------- * * General operations with vectors and transformation matrices * *---------------------------------------------------------------------------*/ typedef GLfloat Vector [3]; typedef GLfloat Matrix [4][4]; static void MatrixMult (Matrix m1, Matrix m2, Matrix result) { /* Multiplies m1 by m2 storing the result in result */ int i, j, k; Matrix tmp; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { tmp [i][j] = 0.0; for (k = 0; k < 4; k++) { tmp [i][j] += m1 [i][k] * m2 [k][j]; } } } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { result [i][j] = tmp [i][j]; } } } static void TransformVector (const Vector v, Matrix m, Vector result) { /* Applies affine linear transformation m to v storing the result in * result */ int i, j; Vector tmp; for (i = 0; i < 3; i++) { tmp [i] = m [i][3]; for (j = 0; j < 3; j++) { tmp [i] += m [i][j] * v [j]; } } for (i = 0; i < 3; i++) { result [i] = tmp [i]; } } static void NormalizeVector (Vector v) { /* Makes v a unit vector */ GLfloat hypot = (GLfloat) sqrt (v [0] * v [0] + v [1] * v [1] + v [2] * v [2]); if (hypot == 0.0) { return; } v [0] /= hypot; v [1] /= hypot; v [2] /= hypot; } static void AddVector (const Vector v1, const Vector v2, Vector result) { /* Adds v1 to v2 and stores in result */ result [0] = v1 [0] + v2 [0]; result [1] = v1 [1] + v2 [1]; result [2] = v1 [2] + v2 [2]; } #define InitVector(v,a,b,c) {v[0]=a; v[1]=b; v[2]=c;} #define CopyVector(dst,src) {dst[0]=src[0];dst[1]=src[1];dst[2]=src[2];} #define DotProduct(a,b) (a[0]*b[0]+a[1]*b[1]+a[2]*b[2]) #if 0 static void ComputeTriangleNormal2 (const Vector v1, const Vector v2, const Vector v3, Vector normal) { /* Computes the normal of the triangle given by the three vertices v1, v2, v3 * and stores it in the vector given by normal */ Vector e1, e2; InitVector (e1, v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]); InitVector (e2, v3[0] - v2[0], v3[1] - v2[1], v3[2] - v2[2]); normal [0] = e1[1]*e2[2]-e1[2]*e2[1]; normal [1] = e2[0]*e1[2]-e2[2]*e1[0]; normal [2] = e1[0]*e2[1]-e1[1]*e2[0]; } static void ComputeQuadNormal (const Vector v1, const Vector v2, const Vector v3, const Vector v4, Vector normal) { /* Computes the normal at vertex v1 of the quadrilateral given * by v1-v2-v3-v4 and stores it in the vector given by normal */ Vector normal1, normal2; GLfloat size1, size2; ComputeTriangleNormal2 (v1, v2, v3, normal1); ComputeTriangleNormal2 (v3, v4, v1, normal2); size1 = normal1[0]*normal1[0]+normal1[1]*normal1[1]+normal1[2]*normal1[2]; size2 = normal2[0]*normal2[0]+normal2[1]*normal2[1]+normal2[2]*normal2[2]; if (size1 > 100*size2) { normal [0] = normal1 [0]/size1; normal [1] = normal1 [1]/size1; normal [2] = normal1 [1]/size1; } else if (size2 > 100*size1) { normal [0] = normal2 [0]/size2; normal [1] = normal2 [1]/size2; normal [2] = normal2 [1]/size2; } else { AddVector (normal1, normal2, normal); NormalizeVector (normal); } } #endif static void ComputeQuadNormal2 (const Vector v1, const Vector v2, const Vector v3, const Vector v4, Vector normal) { /* Computes the squared normal at vertex v1 of the quadrilateral given * by v1-v2-v3-v4 and stores it in the vector given by normal */ normal [0] = (v4 [1] - v1 [1]) * (v4 [2] + v1[2]); normal [1] = (v4 [2] - v1 [2]) * (v4 [0] + v1[0]); normal [2] = (v4 [0] - v1 [0]) * (v4 [1] + v1[1]); normal [0] += (v1 [1] - v2 [1]) * (v1 [2] + v2[2]); normal [1] += (v1 [2] - v2 [2]) * (v1 [0] + v2[0]); normal [2] += (v1 [0] - v2 [0]) * (v1 [1] + v2[1]); normal [0] += (v2 [1] - v3 [1]) * (v2 [2] + v3[2]); normal [1] += (v2 [2] - v3 [2]) * (v2 [0] + v3[0]); normal [2] += (v2 [0] - v3 [0]) * (v2 [1] + v3[1]); normal [0] += (v3 [1] - v4 [1]) * (v3 [2] + v4[2]); normal [1] += (v3 [2] - v4 [2]) * (v3 [0] + v4[0]); normal [2] += (v3 [0] - v4 [0]) * (v3 [1] + v4[1]); } /*--------------------------------------------------------------------------- * * Management of cross sections * *---------------------------------------------------------------------------*/ typedef struct { Vector * vtx; /* Vertex Coordinates */ Vector * normalUL, /* Normal to the Up Left Side of the vertex */ * normalUR, /* Normal to the Up Right Side of the vertex */ * normalDL, /* Normal to the Down Left Side of the vertex */ * normalDR ; /* Normal to the Down Right Side of the vertex */ int nvtx, /* Number of vertices in cross section */ vtxsize; /* Number of vertices allocated in vtx */ } CrossSection; static CrossSection* NewCrossSection () { /* Allocates a new cross section structure */ CrossSection * result = (CrossSection*) malloc (sizeof (CrossSection)); assert (result != NULL); result->nvtx = 0; result->vtxsize = 8; result->vtx = (Vector*) malloc (sizeof (Vector)*result->vtxsize); result->normalUL = result->normalUR = result->normalDL = result->normalDR = NULL; assert (result->vtx != NULL); return result; } static void FreeCrossSection (CrossSection * s) { /* Deallocates the memory associated with cross-section s */ assert (s != NULL); assert (s->vtx != NULL); if (s->normalUL != NULL) free(s->normalUL); if (s->normalUR != NULL) free(s->normalUR); if (s->normalDL != NULL) free(s->normalDL); if (s->normalDR != NULL) free(s->normalDR); free (s->vtx); free (s); } static void AddCrossSectionVtx (CrossSection * s, GLfloat x, GLfloat y, GLfloat z) { /* Stores another vertex with coords (x,y,0) as the next vertex in * cross section 's' */ assert (s != NULL); if (s->vtxsize == s->nvtx) { s->vtxsize *= 2; s->vtx = (Vector*) realloc (s->vtx, sizeof(Vector)*s->vtxsize); assert (s->vtx != NULL); } s->vtx [s->nvtx][0] = x; s->vtx [s->nvtx][1] = y; s->vtx [s->nvtx][2] = z; s->nvtx++; } static CrossSection* PolygonCrossSection (GLfloat radius, int nsides) { /* Returns a cross section which is a regular polygon with 'nsides' sides * and radius 'radius' */ GLfloat x, y, ang, incAng; int i; CrossSection *cross = NewCrossSection (); incAng = (GLfloat)(PI * 2 / nsides); ang = 0.0; for (i = 0; i < nsides; i++) { x = (GLfloat)(radius * sin (ang)); y = (GLfloat)(radius * cos (ang)); AddCrossSectionVtx (cross, x, y, 0.0); ang += incAng; } return cross; } static void TransformCrossSection (CrossSection* s, Matrix m) { /* Apply transformation m to cross section s */ int i; for (i = 0; i < s->nvtx; i++) { TransformVector (s->vtx [i], m, s->vtx [i]); } } static void DupCrossSection (const CrossSection* src, CrossSection* dst) { /* Make dst an exact copy of src */ if (dst->vtxsize < src->vtxsize) { dst->vtxsize = src->vtxsize; dst->vtx = (Vector*) realloc (dst->vtx, sizeof(Vector)*dst->vtxsize); assert (dst->vtx != NULL); } dst->nvtx = src->nvtx; memcpy (dst->vtx, src->vtx, sizeof (Vector)*dst->nvtx); } static void ExpandCrossSection (const CrossSection* src, CrossSection* dst, int ndst) { /* Make dst a copy of src expanded to have n vertices */ int i, nsrc; nsrc = src->nvtx; assert (nsrc < ndst); if (dst->vtxsize < ndst) { dst->vtxsize = ndst; dst->vtx = (Vector*) realloc (dst->vtx, sizeof (Vector)*ndst); } dst->nvtx = ndst; for (i = 0; i < ndst; i++) { memcpy (&(dst->vtx [i]), &(src->vtx [i*nsrc/ndst]), sizeof(Vector)); } } static void CrossSectionNormal2 (const CrossSection* cross, Vector normal) { /* Computes a non-normalized vector that is normal to the cross section */ int ivtx, prev; int nvtx = cross->nvtx; Vector * vtx = cross->vtx; prev = nvtx; normal [0] = normal [1] = normal [2] = 0.0; for (ivtx = 0; ivtx < cross->nvtx; ivtx++) { normal [0] += (vtx[prev] [1] - vtx[ivtx] [1]) * (vtx[prev] [2] + vtx[ivtx][2]); normal [1] += (vtx[prev] [2] - vtx[ivtx] [2]) * (vtx[prev] [0] + vtx[ivtx][0]); normal [2] += (vtx[prev] [0] - vtx[ivtx] [0]) * (vtx[prev] [1] + vtx[ivtx][1]); prev = ivtx; } } /*--------------------------------------------------------------------------- * * Model management * *---------------------------------------------------------------------------*/ typedef struct { double smin, smax, tmin, tmax; int flags; int ncross, sizecross; double adaptivethreshold; CrossSection** cross; } Model; static Model * NewModel () { /* Allocates a new model and returns a pointer to it */ Model* result; result = (Model*) malloc (sizeof (Model)); result->adaptivethreshold = 0; result->ncross = 0; result->sizecross = 8; result->cross = (CrossSection**) malloc (sizeof (CrossSection*) * result->sizecross); assert (result->cross != NULL); return result; } static void FreeModel (Model* model) { /* Deallocates all memory associated with model model */ int i; for (i = 0; i < model->ncross; i++) { FreeCrossSection (model->cross [i]); } free (model->cross); } static void AddModelCrossSection (Model* model, CrossSection* cross) { /* Adds another cross section to the model */ if (model->sizecross == model->ncross) { model->sizecross *= 2; model->cross = (CrossSection**) realloc (model->cross, sizeof (CrossSection*) * model->sizecross); } model->cross [model->ncross++] = cross; } static void UniformCrossSectionLengths (Model * model) { /* Force all CrossSections to be of uniform length */ int icross, maxlength; maxlength = 0; for (icross = 0; icross < model->ncross; icross++) { if (model->cross [icross]->nvtx > maxlength) { maxlength = model->cross [icross]->nvtx; } } for (icross = 0; icross < model->ncross; icross++) { if (model->cross [icross]->nvtx < maxlength) { CrossSection* tmp = NewCrossSection (); ExpandCrossSection (model->cross [icross], tmp, maxlength); FreeCrossSection (model->cross [icross]); model->cross [icross] = tmp; } } } static void ComputeModelNormals (Model* model) { /* Computes normals for each vertex of the model */ int icross, ivtx, prevvtx; int flags = model->flags; CrossSection *thisCross, *nextCross, *prevCross = NULL; Vector *a, *b, *c, *d; int nvtx = model->cross [0]->nvtx; /* Assume every cross section has the same number of vertices */ assert (model->ncross > 1); assert (nvtx > 1); /* First compute Up Right normals (face normals) */ for (icross = 0; icross < model->ncross; icross++) { thisCross = model->cross [icross]; assert (thisCross->nvtx == nvtx); thisCross->normalUR = (Vector*) malloc (sizeof (Vector) * nvtx); if (icross+1 == model->ncross) { if (flags&STITCH_ENDS) { /* Assume last cross section wraps with first cross section */ nextCross = model->cross [0]; } else { /* Last Cross section repeats normals at right from previous cross sections */ assert (prevCross != NULL); memcpy (thisCross->normalUR, prevCross->normalUR, sizeof (Vector) * nvtx); break; } } else { nextCross = model->cross [icross+1]; } for (ivtx = 0; ivtx < nvtx; ivtx++) { if (ivtx+1 == nvtx) { if (flags&STITCH_LOOPS) { /* Assume last vertex wraps with first */ b = &(thisCross->vtx [0]); c = &(nextCross->vtx [0]); } else { /* Last Vertex repeats normal above from previous vertex */ CopyVector (thisCross->normalUR[ivtx], thisCross->normalUR[ivtx-1]); break; } } else { b = &(thisCross->vtx [ivtx+1]); c = &(nextCross->vtx [ivtx+1]); } a = &(thisCross->vtx [ivtx]); d = &(nextCross->vtx [ivtx]); ComputeQuadNormal2 (*a, *d, *c, *b, thisCross->normalUR [ivtx]); NormalizeVector (thisCross->normalUR [ivtx]); } prevCross = thisCross; } /* If only face normals are needed, return here */ if ((flags&(SHADE_SMOOTH_ROWS | SHADE_SMOOTH_COLS)) == 0) return; /* Copy normals to the remaining 3 directions */ for (icross = 0; icross < model->ncross; icross++) { thisCross = model->cross [icross]; thisCross->normalUL = (Vector*) malloc (sizeof (Vector) * nvtx); thisCross->normalDR = (Vector*) malloc (sizeof (Vector) * nvtx); thisCross->normalDL = (Vector*) malloc (sizeof (Vector) * nvtx); if (icross == 0) { if (flags&STITCH_ENDS) { /* Assume first cross section wraps with last cross section */ prevCross = model->cross [model->ncross-1]; } else { /* First Cross section repeats normals at left from the right*/ prevCross = thisCross; } } else { prevCross = model->cross [icross-1]; } for (ivtx = 0; ivtx < nvtx; ivtx++) { if (ivtx == 0) { if (flags&STITCH_LOOPS) { /* Assume last vertex wraps with first */ prevvtx = nvtx-1; } else { /* First Vertex repeats normal below from above */ prevvtx = 0; } } else { prevvtx = ivtx-1; } CopyVector (thisCross->normalUL [ivtx], prevCross->normalUR [ivtx]); CopyVector (thisCross->normalDR [ivtx], thisCross->normalUR [prevvtx]); CopyVector (thisCross->normalDL [ivtx], prevCross->normalUR [prevvtx]); } } /* Smooth Normals */ for (icross = 0; icross < model->ncross; icross++) { thisCross = model->cross [icross]; for (ivtx = 0; ivtx < nvtx; ivtx++) { if ((flags & SHADE_SMOOTH_ROWS)) { Vector tmp; if (!(flags&ADAPTIVE)|| DotProduct(thisCross->normalUL [ivtx], thisCross->normalUR [ivtx]) > model->adaptivethreshold) { AddVector (thisCross->normalUL [ivtx], thisCross->normalUR [ivtx], tmp); NormalizeVector (tmp); CopyVector (thisCross->normalUL [ivtx], tmp); CopyVector (thisCross->normalUR [ivtx], tmp); } if (!(flags&ADAPTIVE)|| DotProduct(thisCross->normalDL [ivtx], thisCross->normalDR [ivtx]) > model->adaptivethreshold) { AddVector (thisCross->normalDL [ivtx], thisCross->normalDR [ivtx], tmp); NormalizeVector (tmp); CopyVector (thisCross->normalDL [ivtx], tmp); CopyVector (thisCross->normalDR [ivtx], tmp); } } if (flags & SHADE_SMOOTH_COLS) { Vector tmp; if (!(flags&ADAPTIVE)|| DotProduct(thisCross->normalUL [ivtx], thisCross->normalDL [ivtx]) > model->adaptivethreshold) { AddVector (thisCross->normalUL [ivtx], thisCross->normalDL [ivtx], tmp); NormalizeVector (tmp); CopyVector (thisCross->normalUL [ivtx], tmp); CopyVector (thisCross->normalDL [ivtx], tmp); } if (!(flags&ADAPTIVE)|| DotProduct(thisCross->normalUR [ivtx], thisCross->normalDR [ivtx]) > model->adaptivethreshold) { AddVector (thisCross->normalUR [ivtx], thisCross->normalDR [ivtx], tmp); NormalizeVector (tmp); CopyVector (thisCross->normalUR [ivtx], tmp); CopyVector (thisCross->normalDR [ivtx], tmp); } } } } } static void ComputeModelBBox (Tcl_Interp* interp, Model* model) { /* Computes the model's bounding box and stores it as two elements in the Interp's result: one for the minimum corner and another for the maximum corner */ Vector min; Vector max; char buf [200]; int icross, ivtx, icoord, ifirst = 1; for (icross = 0; icross < model->ncross; icross++) { CrossSection *cross = model->cross [icross]; for (ivtx = 0; ivtx < cross->nvtx; ivtx++) { if (ifirst) { for (icoord = 0; icoord < 3; icoord++) { min [icoord] = max [icoord] = cross->vtx [ivtx][icoord]; } ifirst = 0; } else { for (icoord = 0; icoord < 3; icoord++) { if (cross->vtx [ivtx][icoord] < min[icoord]) { min [icoord] = cross->vtx [ivtx][icoord]; } if (cross->vtx [ivtx][icoord] > max[icoord]) { max [icoord] = cross->vtx [ivtx][icoord]; } } } } } sprintf (buf, "min %f %f %f", min[0], min[1], min[2]); Tcl_AppendElement (interp, buf); sprintf (buf, "max %f %f %f", max[0], max[1], max[2]); Tcl_AppendElement (interp, buf); } static void RenderModel (Model* model) { /* Renders the surface between each pair of cross sections */ int icross, previcross, ivtx, previvtx; int ncross = model->ncross; int flags = model->flags; int nvtx = model->cross [0]->nvtx; int gentex = (flags & TEXTURE_GEN) != 0; GLfloat texcoord [2]; GLfloat texincr [2]; texcoord [0] = (GLfloat)model->tmin; if (flags&STITCH_ENDS) { icross = 0; previcross = ncross-1; texincr [0] = (GLfloat)((model->tmax-model->tmin) / ncross); } else { icross = 1; previcross = 0; texincr [0] = (GLfloat)((model->tmax-model->tmin) / (ncross-1)); } if (flags&STITCH_LOOPS) { texincr [1] = (GLfloat)((model->smax-model->smin) / nvtx); } else { texincr [1] = (GLfloat)((model->smax-model->smin) / (nvtx-1)); } while (icross < ncross) { CrossSection *a = model->cross [previcross]; CrossSection *b = model->cross [icross]; assert (a->nvtx == b->nvtx); if (flags & STITCH_LOOPS) { ivtx = 0; previvtx = nvtx-1; } else { ivtx = 1; previvtx = 0; } texcoord [1] = (GLfloat)model->smin; if (flags & (SHADE_SMOOTH_COLS|SHADE_SMOOTH_ROWS)) { /* One normal per vertex */ for (; ivtx < nvtx; ivtx++) { glBegin (GL_TRIANGLE_STRIP); if (gentex) glTexCoord2f (texcoord [0], texcoord [1]); glNormal3fv (a->normalUR [previvtx]); glVertex3fv (a->vtx [previvtx]); if (gentex) glTexCoord2f (texcoord [0]+texincr[0], texcoord [1]); glNormal3fv (b->normalUL [previvtx]); glVertex3fv (b->vtx [previvtx]); if (gentex) glTexCoord2f (texcoord [0], texcoord [1]+texincr[1]); glNormal3fv (a->normalDR [ivtx]); glVertex3fv (a->vtx [ivtx]); if (gentex) glTexCoord2f (texcoord [0]+texincr[0], texcoord [1]+texincr[1]); glNormal3fv (b->normalDL [ivtx]); glVertex3fv (b->vtx [ivtx]); previvtx = ivtx; if (gentex) texcoord [1] += texincr [1]; glEnd (); } } else { for (; ivtx < nvtx; ivtx++) { glBegin (GL_TRIANGLE_STRIP); if (gentex) glTexCoord2f (texcoord [0], texcoord [1]); glNormal3fv (a->normalUR [previvtx]); glVertex3fv (a->vtx [previvtx]); if (gentex) glTexCoord2f (texcoord [0]+texincr[0], texcoord [1]); glVertex3fv (b->vtx [previvtx]); if (gentex) glTexCoord2f (texcoord [0], texcoord [1]+texincr[1]); glVertex3fv (a->vtx [ivtx]); if (gentex) glTexCoord2f (texcoord [0]+texincr[0], texcoord [1]+texincr[1]); glVertex3fv (b->vtx [ivtx]); previvtx = ivtx; if (gentex) texcoord [1] += texincr [1]; glEnd(); } } previcross = icross; if (gentex) texcoord [0] += texincr [0]; icross++; } if (flags&(CLOSE_FIRST|CLOSE_LAST)) { GLUtriangulatorObj* obj; Vector normal; GLdouble v [3]; obj = gluNewTess(); gluTessCallback(obj, GLU_BEGIN, glBegin); gluTessCallback(obj, GLU_VERTEX, glVertex3fv); gluTessCallback(obj, GLU_END, glEnd); if (flags&CLOSE_FIRST) { CrossSection *a = model->cross [0]; CrossSectionNormal2 (a, normal); NormalizeVector (normal); glNormal3fv (normal); gluBeginPolygon (obj); for (ivtx = 0; ivtx < nvtx; ivtx++) { v [0] = a->vtx [ivtx][0]; v [1] = a->vtx [ivtx][1]; v [2] = a->vtx [ivtx][2]; gluTessVertex (obj, v, &(a->vtx [ivtx][0])); } gluEndPolygon (obj); } if (flags&CLOSE_LAST) { CrossSection *a = model->cross [model->ncross-1]; CrossSectionNormal2 (a, normal); NormalizeVector (normal); normal [0] = -normal [0]; normal [1] = -normal [1]; normal [2] = -normal [2]; glNormal3fv (normal); gluBeginPolygon (obj); for (ivtx = nvtx-1; ivtx >= 0; ivtx--) { v [0] = a->vtx [ivtx][0]; v [1] = a->vtx [ivtx][1]; v [2] = a->vtx [ivtx][2]; gluTessVertex (obj, v, &(a->vtx [ivtx][0])); } gluEndPolygon (obj); } gluDeleteTess (obj); } } /*-------------------------------------------------------------------------- * * Main Procedure for generating generic cylinders * *--------------------------------------------------------------------------*/ int GenericCylinder (Tcl_Interp *interp, int argc, char* argv []) { #define ERRMSG(msg) \ { Tcl_AppendResult (interp, (msg), (char*) NULL);\ result = TCL_ERROR;\ goto done; } #define ERRMSG2(msg1, msg2) \ { Tcl_AppendResult (interp, (msg1), (msg2), (char*) NULL);\ result = TCL_ERROR;\ goto done; } #define I { \ {1, 0, 0, 0}, \ {0, 1, 0, 0}, \ {0, 0, 1, 0}, \ {0, 0, 0, 1} \ } int result = TCL_OK; Matrix transf = I; CrossSection *currentCross = NewCrossSection (); Model* model = NewModel (); int iarg; int dlist = -1; model->flags = STITCH_LOOPS | SHADE_SMOOTH_ROWS | SHADE_SMOOTH_COLS; model->adaptivethreshold = 0; AddCrossSectionVtx (currentCross, -1.0, -1.0, 0.0); AddCrossSectionVtx (currentCross, -1.0, 1.0, 0.0); AddCrossSectionVtx (currentCross, 1.0, 1.0, 0.0); AddCrossSectionVtx (currentCross, 1.0, -1.0, 0.0); for (iarg = 2; iarg < argc; iarg++) { int len = (int)strlen (argv [iarg]); if (strncmp (argv [iarg], "-plot", len) == 0) { CrossSection* cross = NewCrossSection (); DupCrossSection (currentCross, cross); TransformCrossSection (cross, transf); AddModelCrossSection (model, cross); } else if (strncmp (argv [iarg], "-displaylist", len) == 0) { iarg++; if (strcmp (argv [iarg], "none") == 0) { dlist = 0; } else { result = Tcl_GetInt (interp, argv [iarg], &dlist); if (result != TCL_OK) goto done; } } else if (strncmp (argv [iarg], "-cross", len) == 0) { FreeCrossSection (currentCross); currentCross = NewCrossSection (); while (iarg+3 < argc && !isalpha (argv [iarg+1][1])) { double x, y, z; if (Tcl_GetDouble (interp, argv [iarg+1], &x) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+2], &y) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+3], &z) != TCL_OK) { ERRMSG ("\n error in -cross"); } AddCrossSectionVtx (currentCross, (GLfloat)x, (GLfloat)y, (GLfloat)z); iarg += 3; } } else if (strncmp (argv [iarg], "-polygon", len) == 0) { double radius; int nsides; if (iarg+2 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &radius) != TCL_OK || Tcl_GetInt (interp, argv [iarg+2], &nsides) != TCL_OK) { ERRMSG ("\nError in -polygon"); } iarg += 2; FreeCrossSection (currentCross); currentCross = PolygonCrossSection ((GLfloat)radius, nsides); } else if (strncmp (argv [iarg], "-stitch", len) == 0) { if (iarg+1 >= argc) ERRMSG ("No value for -stitch"); iarg++; len = (int)strlen (argv [iarg]); if (strncmp (argv [iarg], "both", len) == 0) { model->flags |= STITCH_LOOPS | STITCH_ENDS; } else if (strncmp (argv [iarg], "none", len) == 0) { model->flags &= ~(STITCH_LOOPS | STITCH_ENDS); } else if (strncmp (argv [iarg], "ends", len) == 0) { model->flags |= STITCH_ENDS; model->flags &= ~STITCH_LOOPS; } else if (strncmp (argv [iarg], "loops", len) == 0) { model->flags &= ~STITCH_ENDS; model->flags |= STITCH_LOOPS; } else { ERRMSG2 ("Should be 'both', 'none', 'loops' or 'ends':", argv [iarg]); } } else if (strncmp (argv [iarg], "-close", len) == 0) { if (iarg+1 >= argc) ERRMSG ("No value for -close"); iarg++; len = (int)strlen (argv [iarg]); if (strncmp (argv [iarg], "both", len) == 0) { model->flags |= CLOSE_FIRST | CLOSE_LAST; } else if (strncmp (argv [iarg], "none", len) == 0) { model->flags &= ~(CLOSE_FIRST | CLOSE_LAST); } else if (strncmp (argv [iarg], "first", len) == 0) { model->flags |= CLOSE_FIRST; model->flags &= ~CLOSE_LAST; } else if (strncmp (argv [iarg], "last", len) == 0) { model->flags &= ~CLOSE_LAST; model->flags |= CLOSE_FIRST; } else { ERRMSG2 ("Should be 'both', 'none', 'first' or 'last':", argv [iarg]); } } else if (strncmp (argv [iarg], "-shade", len) == 0) { if (iarg+1 >= argc) ERRMSG ("No value for -shade"); iarg++; len = (int)strlen (argv [iarg]); if (strncmp (argv [iarg], "smooth", len) == 0) { model->flags |= SHADE_SMOOTH_COLS | SHADE_SMOOTH_ROWS; } else if (strncmp (argv [iarg], "flat", len) == 0) { model->flags &= ~(SHADE_SMOOTH_COLS | SHADE_SMOOTH_ROWS); } else if (strncmp (argv [iarg], "smoothrows", len) == 0) { model->flags &= ~SHADE_SMOOTH_COLS; model->flags |= SHADE_SMOOTH_ROWS; } else if (strncmp (argv [iarg], "smoothcols", len) == 0) { model->flags &= ~SHADE_SMOOTH_ROWS; model->flags |= SHADE_SMOOTH_COLS; } else { ERRMSG2 ("Should be 'flat', 'smooth', 'smoothrows' or 'smoothcols':", argv [iarg]); } } else if (strncmp (argv [iarg], "-adaptive", len) == 0) { double ang; model->flags |= ADAPTIVE; if (iarg+1 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &ang) != TCL_OK) ERRMSG ("\nError in -adaptive"); model->adaptivethreshold = cos(ang*PI/180); iarg++; } else if (strncmp (argv [iarg], "-texgen", len) == 0) { double smin, smax, tmin, tmax; model->flags |= TEXTURE_GEN; if (iarg+4 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &smin) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+2], &smax) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+3], &tmin) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+4], &tmax) != TCL_OK) ERRMSG ("\nError in -rotate"); iarg += 4; model->smin = smin; model->smax = smax; model->tmin = tmin; model->tmax = tmax; } else if (strncmp (argv [iarg], "-identity", len) == 0) { Matrix ident = I; memcpy (transf, ident, sizeof (Matrix)); } else if (strncmp (argv [iarg], "-rotate", len) == 0) { double angle, x, y, z, norm, sint, cost; Matrix m = I; if (iarg+4 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &angle) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+2], &x) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+3], &y) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+4], &z) != TCL_OK) ERRMSG ("\nError in -rotate"); iarg += 4; norm = sqrt (x*x+y*y+z*z); if (norm == 0.0) ERRMSG ("Null Vector"); x /= norm; y /= norm; z /= norm; angle *= PI/180; sint = sin(angle); cost = cos(angle); m [0][0] = (GLfloat)(x*x + cost * (1 - x*x) + sint * 0); m [0][1] = (GLfloat)(x*y + cost * (0 - x*y) + sint * (-z)); m [0][2] = (GLfloat)(x*z + cost * (0 - x*z) + sint * (y)); m [1][0] = (GLfloat)(y*x + cost * (0 - y*x) + sint * (z)); m [1][1] = (GLfloat)(y*y + cost * (1 - y*y) + sint * 0); m [1][2] = (GLfloat)(y*z + cost * (0 - y*z) + sint * (-x)); m [2][0] = (GLfloat)(z*x + cost * (0 - z*x) + sint * (-y)); m [2][1] = (GLfloat)(z*y + cost * (0 - z*y) + sint * (x)); m [2][2] = (GLfloat)(z*z + cost * (1 - z*z) + sint * 0); MatrixMult (m, transf, transf); } else if (strncmp (argv [iarg], "-translate", len) == 0) { double x, y, z; Matrix m = I; if (iarg+3 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &x) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+2], &y) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+3], &z) != TCL_OK) ERRMSG ("\nError in -translate"); iarg += 3; m [0][3] = (GLfloat)x; m [1][3] = (GLfloat)y; m [2][3] = (GLfloat)z; MatrixMult (m, transf, transf); } else if (strncmp (argv [iarg], "-scale", len) == 0) { double x, y, z; Matrix m = I; if (iarg+3 >= argc || Tcl_GetDouble (interp, argv [iarg+1], &x) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+2], &y) != TCL_OK || Tcl_GetDouble (interp, argv [iarg+3], &z) != TCL_OK) ERRMSG ("\nError in -scale"); iarg += 3; m [0][0] = (GLfloat)x; m [1][1] = (GLfloat)y; m [2][2] = (GLfloat)z; MatrixMult (m, transf, transf); } else { ERRMSG2 ("No such option: ", argv [iarg]); } } done: if (result == TCL_OK) { char buf [100]; if (dlist == -1) dlist = glGenLists (1); if (dlist != 0) glNewList (dlist, GL_COMPILE); UniformCrossSectionLengths (model); ComputeModelNormals (model); RenderModel (model); if (dlist != 0) { glEndList (); sprintf (buf, "displaylist %d", dlist); } Tcl_AppendElement (interp, buf); ComputeModelBBox (interp, model); } FreeModel (model); return result; }
784884.c
/* @(#)e_gamma_r.c 1.3 95/01/18 */ /* $FreeBSD: head/lib/msun/src/e_gamma_r.c 176451 2008-02-22 02:30:36Z das $ */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== * */ /* __ieee754_gamma_r(x, signgamp) * Reentrant version of the logarithm of the Gamma function * with user provide pointer for the sign of Gamma(x). * * Method: See __ieee754_lgamma_r */ #include "math.h" #include "math_private.h" double __ieee754_gamma_r(double x, int *signgamp) { return __ieee754_lgamma_r(x,signgamp); }
931711.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: Gustavo Lopes <[email protected]> | +----------------------------------------------------------------------+ */ #include <php.h> #include "php_sockets.h" #include "sendrecvmsg.h" #include "conversions.h" #include <limits.h> #include <Zend/zend_llist.h> #ifdef ZTS #include <TSRM/TSRM.h> #endif #define MAX_USER_BUFF_SIZE ((size_t)(100*1024*1024)) #define DEFAULT_BUFF_SIZE 8192 #define MAX_ARRAY_KEY_SIZE 128 #ifdef PHP_WIN32 #include "windows_common.h" #include <Mswsock.h> #define IPV6_RECVPKTINFO IPV6_PKTINFO #define IPV6_RECVHOPLIMIT IPV6_HOPLIMIT #define msghdr _WSAMSG static GUID WSARecvMsg_GUID = WSAID_WSARECVMSG; static __declspec(thread) LPFN_WSARECVMSG WSARecvMsg = NULL; inline ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) { DWORD recvd = 0, bytesReturned; if (WSARecvMsg == NULL) { int res = WSAIoctl((SOCKET) sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSARecvMsg_GUID, sizeof(WSARecvMsg_GUID), &WSARecvMsg, sizeof(WSARecvMsg), &bytesReturned, NULL, NULL); if (res != 0) { return -1; } } msg->dwFlags = (DWORD)flags; return WSARecvMsg((SOCKET)sockfd, msg, &recvd, NULL, NULL) == 0 ? (ssize_t)recvd : -1; } inline ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) { DWORD sent = 0; return WSASendMsg((SOCKET)sockfd, (struct msghdr*)msg, (DWORD)flags, &sent, NULL, NULL) == 0 ? (ssize_t)sent : -1; } #endif #define LONG_CHECK_VALID_INT(l) \ do { \ if ((l) < INT_MIN && (l) > INT_MAX) { \ php_error_docref0(NULL, E_WARNING, "The value " ZEND_LONG_FMT " does not fit inside " \ "the boundaries of a native integer", (l)); \ return; \ } \ } while (0) static struct { int initialized; HashTable ht; } ancillary_registry; static void ancillary_registery_free_elem(zval *el) { pefree(Z_PTR_P(el), 1); } #ifdef ZTS static MUTEX_T ancillary_mutex; #endif static void init_ancillary_registry(void) { ancillary_reg_entry entry; anc_reg_key key; ancillary_registry.initialized = 1; zend_hash_init(&ancillary_registry.ht, 32, NULL, ancillary_registery_free_elem, 1); #define PUT_ENTRY(sizev, var_size, calc, from, to, level, type) \ entry.size = sizev; \ entry.var_el_size = var_size; \ entry.calc_space = calc; \ entry.from_array = from; \ entry.to_array = to; \ key.cmsg_level = level; \ key.cmsg_type = type; \ zend_hash_str_update_mem(&ancillary_registry.ht, (char*)&key, sizeof(key) - 1, (void*)&entry, sizeof(entry)) #if defined(IPV6_PKTINFO) && HAVE_IPV6 PUT_ENTRY(sizeof(struct in6_pktinfo), 0, 0, from_zval_write_in6_pktinfo, to_zval_read_in6_pktinfo, IPPROTO_IPV6, IPV6_PKTINFO); #endif #if defined(IPV6_HOPLIMIT) && HAVE_IPV6 PUT_ENTRY(sizeof(int), 0, 0, from_zval_write_int, to_zval_read_int, IPPROTO_IPV6, IPV6_HOPLIMIT); #endif #if defined(IPV6_TCLASS) && HAVE_IPV6 PUT_ENTRY(sizeof(int), 0, 0, from_zval_write_int, to_zval_read_int, IPPROTO_IPV6, IPV6_TCLASS); #endif #ifdef SO_PASSCRED PUT_ENTRY(sizeof(struct ucred), 0, 0, from_zval_write_ucred, to_zval_read_ucred, SOL_SOCKET, SCM_CREDENTIALS); #endif #ifdef SCM_RIGHTS PUT_ENTRY(0, sizeof(int), calculate_scm_rights_space, from_zval_write_fd_array, to_zval_read_fd_array, SOL_SOCKET, SCM_RIGHTS); #endif } static void destroy_ancillary_registry(void) { if (ancillary_registry.initialized) { zend_hash_destroy(&ancillary_registry.ht); ancillary_registry.initialized = 0; } } ancillary_reg_entry *get_ancillary_reg_entry(int cmsg_level, int msg_type) { anc_reg_key key = { cmsg_level, msg_type }; ancillary_reg_entry *entry; #ifdef ZTS tsrm_mutex_lock(ancillary_mutex); #endif if (!ancillary_registry.initialized) { init_ancillary_registry(); } #ifdef ZTS tsrm_mutex_unlock(ancillary_mutex); #endif if ((entry = zend_hash_str_find_ptr(&ancillary_registry.ht, (char*)&key, sizeof(key) - 1)) != NULL) { return entry; } else { return NULL; } } PHP_FUNCTION(socket_sendmsg) { zval *zsocket, *zmsg; zend_long flags = 0; php_socket *php_sock; struct msghdr *msghdr; zend_llist *allocations; struct err_s err = {0}; ssize_t res; /* zmsg should be passed by ref */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra|l", &zsocket, &zmsg, &flags) == FAILURE) { return; } LONG_CHECK_VALID_INT(flags); if ((php_sock = (php_socket *)zend_fetch_resource(Z_RES_P(zsocket), php_sockets_le_socket_name, php_sockets_le_socket())) == NULL) { RETURN_FALSE; } msghdr = from_zval_run_conversions(zmsg, php_sock, from_zval_write_msghdr_send, sizeof(*msghdr), "msghdr", &allocations, &err); if (err.has_error) { err_msg_dispose(&err); RETURN_FALSE; } res = sendmsg(php_sock->bsd_socket, msghdr, (int)flags); if (res != -1) { zend_llist_destroy(allocations); efree(allocations); RETURN_LONG((zend_long)res); } else { PHP_SOCKET_ERROR(php_sock, "error in sendmsg", errno); RETURN_FALSE; } } PHP_FUNCTION(socket_recvmsg) { zval *zsocket, *zmsg; zend_long flags = 0; php_socket *php_sock; ssize_t res; struct msghdr *msghdr; zend_llist *allocations; struct err_s err = {0}; //ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra|l", &zsocket, &zmsg, &flags) == FAILURE) { return; } LONG_CHECK_VALID_INT(flags); if ((php_sock = (php_socket *)zend_fetch_resource(Z_RES_P(zsocket), php_sockets_le_socket_name, php_sockets_le_socket())) == NULL) { RETURN_FALSE; } msghdr = from_zval_run_conversions(zmsg, php_sock, from_zval_write_msghdr_recv, sizeof(*msghdr), "msghdr", &allocations, &err); if (err.has_error) { err_msg_dispose(&err); RETURN_FALSE; } res = recvmsg(php_sock->bsd_socket, msghdr, (int)flags); if (res != -1) { zval *zres, tmp; struct key_value kv[] = { {KEY_RECVMSG_RET, sizeof(KEY_RECVMSG_RET), &res}, {0} }; zres = to_zval_run_conversions((char *)msghdr, to_zval_read_msghdr, "msghdr", kv, &err, &tmp); /* we don;t need msghdr anymore; free it */ msghdr = NULL; allocations_dispose(&allocations); zval_ptr_dtor(zmsg); if (!err.has_error) { ZVAL_COPY_VALUE(zmsg, zres); } else { err_msg_dispose(&err); ZVAL_FALSE(zmsg); /* no need to destroy/free zres -- it's NULL in this circumstance */ assert(zres == NULL); } } else { SOCKETS_G(last_error) = errno; php_error_docref(NULL, E_WARNING, "error in recvmsg [%d]: %s", errno, sockets_strerror(errno)); RETURN_FALSE; } RETURN_LONG((zend_long)res); } PHP_FUNCTION(socket_cmsg_space) { zend_long level, type, n = 0; ancillary_reg_entry *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll|l", &level, &type, &n) == FAILURE) { return; } LONG_CHECK_VALID_INT(level); LONG_CHECK_VALID_INT(type); LONG_CHECK_VALID_INT(n); if (n < 0) { php_error_docref0(NULL, E_WARNING, "The third argument " "cannot be negative"); return; } entry = get_ancillary_reg_entry(level, type); if (entry == NULL) { php_error_docref0(NULL, E_WARNING, "The pair level " ZEND_LONG_FMT "/type " ZEND_LONG_FMT " is " "not supported by PHP", level, type); return; } if (entry->var_el_size > 0 && n > (zend_long)((ZEND_LONG_MAX - entry->size - CMSG_SPACE(0) - 15L) / entry->var_el_size)) { /* the -15 is to account for any padding CMSG_SPACE may add after the data */ php_error_docref0(NULL, E_WARNING, "The value for the " "third argument (" ZEND_LONG_FMT ") is too large", n); return; } RETURN_LONG((zend_long)CMSG_SPACE(entry->size + n * entry->var_el_size)); } #if HAVE_IPV6 int php_do_setsockopt_ipv6_rfc3542(php_socket *php_sock, int level, int optname, zval *arg4) { struct err_s err = {0}; zend_llist *allocations = NULL; void *opt_ptr; socklen_t optlen; int retval; assert(level == IPPROTO_IPV6); switch (optname) { #ifdef IPV6_PKTINFO case IPV6_PKTINFO: #ifdef PHP_WIN32 if (Z_TYPE_P(arg4) == IS_ARRAY) { php_error_docref0(NULL, E_WARNING, "Windows does not " "support sticky IPV6_PKTINFO"); return FAILURE; } else { /* windows has no IPV6_RECVPKTINFO, and uses IPV6_PKTINFO * for the same effect. We define IPV6_RECVPKTINFO to be * IPV6_PKTINFO, so assume the assume user used IPV6_RECVPKTINFO */ return 1; } #endif opt_ptr = from_zval_run_conversions(arg4, php_sock, from_zval_write_in6_pktinfo, sizeof(struct in6_pktinfo), "in6_pktinfo", &allocations, &err); if (err.has_error) { err_msg_dispose(&err); return FAILURE; } optlen = sizeof(struct in6_pktinfo); goto dosockopt; #endif } /* we also support IPV6_TCLASS, but that can be handled by the default * integer optval handling in the caller */ return 1; dosockopt: retval = setsockopt(php_sock->bsd_socket, level, optname, opt_ptr, optlen); if (retval != 0) { PHP_SOCKET_ERROR(php_sock, "unable to set socket option", errno); } allocations_dispose(&allocations); return retval != 0 ? FAILURE : SUCCESS; } int php_do_getsockopt_ipv6_rfc3542(php_socket *php_sock, int level, int optname, zval *result) { struct err_s err = {0}; void *buffer; socklen_t size; int res; to_zval_read_field *reader; assert(level == IPPROTO_IPV6); switch (optname) { #ifdef IPV6_PKTINFO case IPV6_PKTINFO: size = sizeof(struct in6_pktinfo); reader = &to_zval_read_in6_pktinfo; break; #endif default: return 1; } buffer = ecalloc(1, size); res = getsockopt(php_sock->bsd_socket, level, optname, buffer, &size); if (res != 0) { PHP_SOCKET_ERROR(php_sock, "unable to get socket option", errno); } else { zval tmp; zval *zv = to_zval_run_conversions(buffer, reader, "in6_pktinfo", empty_key_value_list, &err, &tmp); if (err.has_error) { err_msg_dispose(&err); res = -1; } else { ZVAL_COPY_VALUE(result, zv); } } efree(buffer); return res == 0 ? SUCCESS : FAILURE; } #endif /* HAVE_IPV6 */ void php_socket_sendrecvmsg_init(INIT_FUNC_ARGS) { /* IPv6 ancillary data */ #if defined(IPV6_RECVPKTINFO) && HAVE_IPV6 REGISTER_LONG_CONSTANT("IPV6_RECVPKTINFO", IPV6_RECVPKTINFO, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_PKTINFO", IPV6_PKTINFO, CONST_CS | CONST_PERSISTENT); #endif #if defined(IPV6_RECVHOPLIMIT) && HAVE_IPV6 REGISTER_LONG_CONSTANT("IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_HOPLIMIT", IPV6_HOPLIMIT, CONST_CS | CONST_PERSISTENT); #endif /* would require some effort: REGISTER_LONG_CONSTANT("IPV6_RECVRTHDR", IPV6_RECVRTHDR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS, CONST_CS | CONST_PERSISTENT); */ #if defined(IPV6_RECVTCLASS) && HAVE_IPV6 REGISTER_LONG_CONSTANT("IPV6_RECVTCLASS", IPV6_RECVTCLASS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_TCLASS", IPV6_TCLASS, CONST_CS | CONST_PERSISTENT); #endif /* REGISTER_LONG_CONSTANT("IPV6_RTHDR", IPV6_RTHDR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_HOPOPTS", IPV6_HOPOPTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IPV6_DSTOPTS", IPV6_DSTOPTS, CONST_CS | CONST_PERSISTENT); */ #ifdef SCM_RIGHTS REGISTER_LONG_CONSTANT("SCM_RIGHTS", SCM_RIGHTS, CONST_CS | CONST_PERSISTENT); #endif #ifdef SO_PASSCRED REGISTER_LONG_CONSTANT("SCM_CREDENTIALS", SCM_CREDENTIALS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SO_PASSCRED", SO_PASSCRED, CONST_CS | CONST_PERSISTENT); #endif #ifdef ZTS ancillary_mutex = tsrm_mutex_alloc(); #endif } void php_socket_sendrecvmsg_shutdown(SHUTDOWN_FUNC_ARGS) { #ifdef ZTS tsrm_mutex_free(ancillary_mutex); #endif destroy_ancillary_registry(); }
916057.c
/* Copyright (C) 1991, 1992 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <ansidecl.h> #include <errno.h> #include <stddef.h> #include <termios.h> #include <unistd.h> #include "bsdtty.h" #include <sys/file.h> /* Flush pending data on FD. */ int DEFUN(tcflush, (fd, queue_selector), int fd AND int queue_selector) { int arg; switch (queue_selector) { case TCIFLUSH: arg = FREAD; break; case TCOFLUSH: arg = FWRITE; break; case TCIOFLUSH: arg = FREAD | FWRITE; break; default: errno = EINVAL; return -1; } return __ioctl (fd, TIOCFLUSH, (PTR) &arg); }
163934.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct CircularList { struct CircularList* next; int data; }*ptrCircularList; typedef ptrCircularList* ListHead; typedef struct CircularList List; ListHead newList(void); bool isEmpty(ListHead listHead); bool destroyList(ListHead listHead); bool insertTopList(ListHead listHead, int data); bool insertBottomList(ListHead listHead, int data); bool insertSorted(ListHead listHead, int data); bool removeTopList(ListHead listHead); bool removeBottomList(ListHead listHead); bool removeElement(ListHead listHead, int data); bool printList(ListHead listHead); ListHead newList(void) { ListHead listHead = NULL; listHead = (ListHead)malloc(sizeof(ptrCircularList)); if(listHead != NULL) *listHead = NULL; return listHead; } bool isEmpty(ListHead listHead) { if(listHead == NULL || *listHead == NULL) return true; return false; } bool destroyList(ListHead listHead) { ptrCircularList freeNode; ptrCircularList scrollList; if(listHead == NULL && *listHead == NULL) return false; if(listHead != NULL && *listHead == NULL) { free(listHead); return true; } scrollList = *listHead; while(*listHead != scrollList->next) { freeNode = scrollList; scrollList = scrollList->next; free(freeNode); } free(freeNode); free(listHead); return true; } bool insertTopList(ListHead listHead, int data) { ptrCircularList newElement = NULL; ptrCircularList scrollList; if(listHead == NULL) return false; newElement = (ptrCircularList)malloc(sizeof(List)); if(newElement == NULL) { puts("Memory Allocation Error"); return false; } if(*listHead == NULL) { newElement->data = data; newElement->next = newElement; *listHead = newElement; } else { scrollList = *listHead; while(scrollList->next != *listHead) scrollList = scrollList->next; scrollList->next = newElement; newElement->next = *listHead; *listHead = newElement; } return true; } bool insertBottomList(ListHead listHead, int data) { ptrCircularList newElement = NULL; ptrCircularList scrollList; if(listHead == NULL) return false; newElement = (ptrCircularList)malloc(sizeof(List)); if(newElement == NULL) { puts("Memory Allocation Error"); return false; } newElement->data = data; if(*listHead == NULL) { newElement->next = newElement; *listHead = newElement; } else { scrollList = *listHead; while(scrollList->next != *listHead) scrollList = scrollList->next; scrollList->next = newElement; newElement->next = *listHead; } return true; } bool insertSorted(ListHead listHead, int data) { ptrCircularList newElement = NULL; ptrCircularList scrollList; ptrCircularList current; ptrCircularList previous; if(listHead == NULL) return false; newElement = (ptrCircularList)malloc(sizeof(List)); if(newElement == NULL) { puts("Memory Allocation Error"); return false; } newElement->data = data; if(*listHead == NULL) { newElement->next = newElement; *listHead = newElement; } else { scrollList = *listHead; if((*listHead)->data > data) { while(scrollList->next != *listHead) scrollList = scrollList->next; newElement->next = *listHead; scrollList->next = newElement; *listHead = newElement; return true; } current = (*listHead)->next; previous = *listHead; while(current != *listHead && current->data < data) { previous = current; current = current->next; } previous->next = newElement; newElement->next = current; } return true; } bool removeTopList(ListHead listHead) { ptrCircularList scrollList; ptrCircularList freeNode; if(listHead == NULL || *listHead == NULL) return false; if((*listHead)->next = *listHead) { free(*listHead); *listHead = NULL; } else { scrollList = *listHead; while(scrollList->next != *listHead) scrollList = scrollList->next; freeNode = *listHead; scrollList->next = freeNode->next; *listHead = freeNode->next; free(freeNode); } return true; } bool removeBottomList(ListHead listHead) { ptrCircularList current; ptrCircularList previous; ptrCircularList freeNode; if(listHead == NULL || *listHead == NULL) return false; if((*listHead)->next == *listHead) { free(*listHead); *listHead = NULL; } else { current = *listHead; while(current->next != *listHead) { previous = current; current = current->next; } previous->next = current->next; } return true; } bool removeElement(ListHead listHead, int data) { ptrCircularList current; ptrCircularList previous; ptrCircularList freeNode; if(listHead == NULL || *listHead == NULL) return false; current = *listHead; if(current->data == data) { if(current == current->next) { free(*listHead); *listHead = NULL; } else { while(current->next != *listHead) { current = current->next; } freeNode = *listHead; current->next = freeNode->next; *listHead = freeNode->next; free(freeNode); } } else { previous = current; current = current->next; while(current != *listHead && current->data != data) { previous = current; current = current->next; } if(current == *listHead) return false; previous->next = current->next; free(current); } return true; } bool printList(ListHead listHead) { ptrCircularList scrollList; if(listHead == NULL || *listHead == NULL) return false; scrollList = *listHead; do { printf("%i\n",scrollList->data); scrollList = scrollList->next; }while(scrollList->next != (*listHead)->next); return true; } int main(int argc, char const *argv[]) { ListHead list; list = newList(); insertSorted(list,3); insertSorted(list,1); insertSorted(list,4); insertSorted(list,2); insertSorted(list,0); removeElement(list,0); printList(list); return 0; }
242151.c
/* File: D:\WACKER\tdll\termhdl.c (Created: 10-Dec-1993) * * Copyright 1994 by Hilgraeve Inc. -- Monroe, MI * All rights reserved * * $Revision: 2 $ * $Date: 2/05/99 3:21p $ */ #include <windows.h> #pragma hdrstop #include <string.h> #include "stdtyp.h" #include <term\res.h> #include "tdll.h" #include "globals.h" #include "mc.h" #include "assert.h" #include "session.h" #include "timers.h" #include "update.h" #include <emu\emu.h> #include "tchar.h" #include "term.h" #include "term.hh" // This structure never referenced directly. Instead, a pointer is // stored to this array. Was easier to initialize by being static. static const COLORREF crEmuColors[MAX_EMUCOLORS] = { RGB( 0, 0, 0), // black RGB( 0, 0, 128), // blue RGB( 0, 128, 0), // green RGB( 0, 128, 128), // cyan RGB(128, 0, 0), // red RGB(128, 0, 128), // magenta RGB(128, 128, 32), // yellow RGB(192, 192, 192), // white (lt gray) RGB(128, 128, 128), // black (gray) RGB( 0, 0, 255), // intense blue RGB( 0, 255, 0), // intense green RGB( 0, 255, 255), // intense cyan RGB(255, 0, 0), // intense red RGB(255, 0, 255), // intense magenta RGB(255, 255, 0), // intense yellow RGB(255, 255, 255) // intense white }; static BOOL AllocTxtBuf(ECHAR ***fpalpstr, int const sRows, int const sCols); static BOOL AllocAttrBuf(PSTATTR **fpapst, const int sRows, const int sCols); static void FreeTxtBuf(ECHAR ***fpalpstr, const int sRows); static void FreeAttrBuf(PSTATTR **fpapst, const int sRows); static BOOL termAllocBkBuf(const HHTERM hhTerm); static void termFreeBkBuf(const HHTERM hhTerm); static void GetDefaultDBCSFont(const HHTERM hhTerm); static int APIENTRY EnumFontCallback(LPLOGFONT lplf, LPTEXTMETRIC lptm, DWORD dwType, LPVOID lpData); /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * RegisterTerminalClass * * DESCRIPTION: * Registers the terminal class. Called in InitApplication() * * ARGUMENTS: * hInstance - Instance handle of app. * * RETURNS: * BOOL * */ BOOL RegisterTerminalClass(const HINSTANCE hInstance) { WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; wc.lpfnWndProc = (WNDPROC)TermProc; wc.cbClsExtra = 0; wc.cbWndExtra = sizeof(LONG_PTR); wc.hInstance = hInstance; wc.hIcon = 0; wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = 0; wc.lpszMenuName = 0; wc.lpszClassName = TERM_CLASS; if (RegisterClass(&wc) == FALSE) { assert(FALSE); return FALSE; } return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * CreateTerminalWindow * * DESCRIPTION: * Creates a terminal window. * * ARGUMENTS: * hwndSession - session window handle. * * RETURNS: * hwnd or zero. * */ HWND CreateTerminalWindow(const HWND hwndSession) { HWND hwnd; hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, TERM_CLASS, "", WS_CHILD | WS_HSCROLL | WS_VSCROLL | WS_CLIPSIBLINGS | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndSession, (HMENU)IDC_TERMINAL_WIN, glblQueryDllHinst(), 0 ); if (hwnd == 0) { assert(FALSE); return 0; } return hwnd; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * CreateTerminalHdl * * DESCRIPTION: * Creates an internal terminal handle. * * ARGUMENTS: * hSession - session handle * hwndTerm - terminal window handle. * * RETURNS: * HHTERM or zero on error. * */ HHTERM CreateTerminalHdl(const HWND hwndTerm) { HHTERM hhTerm; hhTerm = (HHTERM)malloc(sizeof(*hhTerm)); if (hhTerm == 0) { assert(FALSE); return 0; } memset(hhTerm, 0, sizeof(*hhTerm)); hhTerm->hwnd = hwndTerm; hhTerm->hwndSession = GetParent(hwndTerm); hhTerm->hSession = (HSESSION)GetWindowLongPtr(GetParent(hwndTerm), GWLP_USERDATA); /* --- ProcessMessage() aquires a session handle from here. --- */ SetWindowLongPtr(hwndTerm, 0, (LONG_PTR)hhTerm->hSession); hhTerm->iRows = 24; // standard, loading an emulator could change it. hhTerm->iCols = 80; // standard, loading an emulator could change it. hhTerm->pacrEmuColors = crEmuColors; hhTerm->xBezel = BEZEL_SIZE; hhTerm->xIndent = 3; hhTerm->fCursorTracking = TRUE; hhTerm->fCursorsLinked = TRUE; hhTerm->fBlink = TRUE; hhTerm->uBlinkRate = GetCaretBlinkTime(); hhTerm->iCurType = EMU_CURSOR_LINE; hhTerm->hUpdate = updateCreate(hhTerm->hSession); memset(hhTerm->underscores, '_', MAX_EMUCOLS); hhTerm->underscores[MAX_EMUCOLS-1] = TEXT('\0'); if (hhTerm->hUpdate == 0) return 0; // Allocate space for terminal text and attributes. if (AllocTxtBuf(&hhTerm->fplpstrTxt, MAX_EMUROWS, MAX_EMUCOLS) == FALSE) return 0; if (AllocAttrBuf(&hhTerm->fppstAttr, MAX_EMUROWS, MAX_EMUCOLS) == FALSE) return 0; if (termSysColorChng(hhTerm) == FALSE) return 0; if (termSetFont(hhTerm, 0) == FALSE) return 0; if (termAllocBkBuf(hhTerm) == FALSE) return 0; return hhTerm; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * DestroyTerminalHdl * * DESCRIPTION: * Gracefully cleans up the terminal handle. * * ARGUMENTS: * hhTerm - internal terminal handle. * * RETURNS: * void * */ void DestroyTerminalHdl(const HHTERM hhTerm) { if (hhTerm == 0) return; if (hhTerm->hUpdate) updateDestroy(hhTerm->hUpdate); //TODO: destroy terminal window. FreeTxtBuf(&hhTerm->fplpstrTxt, MAX_EMUROWS); FreeAttrBuf(&hhTerm->fppstAttr, MAX_EMUROWS); /* --- Delete fonts --- */ if (hhTerm->hFont) DeleteObject(hhTerm->hFont); //if (hhTerm->hUFont) // DeleteObject(hhTerm->hUFont); if (hhTerm->hDblHiFont) DeleteObject(hhTerm->hDblHiFont); //if (hhTerm->hDblHiUFont) // DeleteObject(hhTerm->hDblHiUFont); if (hhTerm->hDblWiFont) DeleteObject(hhTerm->hDblWiFont); //if (hhTerm->hDblWiUFont) // DeleteObject(hhTerm->hDblWiUFont); if (hhTerm->hDblHiWiFont) DeleteObject(hhTerm->hDblHiWiFont); //if (hhTerm->hDblHiWiUFont) // DeleteObject(hhTerm->hDblHiWiUFont); /* --- Delete alternate symbol fonts --- */ if (hhTerm->hSymFont) DeleteObject(hhTerm->hSymFont); //if (hhTerm->hSymUFont) // DeleteObject(hhTerm->hSymUFont); if (hhTerm->hSymDblHiFont) DeleteObject(hhTerm->hSymDblHiFont); //if (hhTerm->hSymDblHiUFont) // DeleteObject(hhTerm->hSymDblHiUFont); if (hhTerm->hSymDblWiFont) DeleteObject(hhTerm->hSymDblWiFont); //if (hhTerm->hSymDblWiUFont) // DeleteObject(hhTerm->hSymDblWiUFont); if (hhTerm->hSymDblHiWiFont) DeleteObject(hhTerm->hSymDblHiWiFont); //if (hhTerm->hSymDblHiWiUFont) // DeleteObject(hhTerm->hSymDblHiWiUFont); /* --- Other stuff --- */ if (hhTerm->hbrushTerminal) DeleteObject(hhTerm->hbrushTerminal); if (hhTerm->hDkGrayPen) DeleteObject(hhTerm->hDkGrayPen); if (hhTerm->hLtGrayPen) DeleteObject(hhTerm->hLtGrayPen); if (hhTerm->hbrushTermHatch) DeleteObject(hhTerm->hbrushTermHatch); if (hhTerm->hbrushBackHatch) DeleteObject(hhTerm->hbrushBackHatch); if (hhTerm->hbrushDivider) DeleteObject(hhTerm->hbrushDivider); if (hhTerm->hbrushHighlight) DeleteObject(hhTerm->hbrushHighlight); if (hhTerm->hCursorTimer) TimerDestroy(&hhTerm->hCursorTimer); if (hhTerm->fplpstrBkTxt) termFreeBkBuf(hhTerm); free(hhTerm); return; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * AllocTxtBuf * * DESCRIPTION: * Allocates text buffer for terminal image. * * ARGUMENTS: * fpalpstr - pointer to pointer to buffer array. * sRows - number of rows * sCols - number of cols in each row. * * RETURNS: * BOOL * */ static BOOL AllocTxtBuf(ECHAR ***fpalpstr, int const sRows, int const sCols) { register int i; FreeTxtBuf(fpalpstr, sRows); // free any old stuff if ((*fpalpstr = (ECHAR **)malloc((unsigned int)sRows * sizeof(ECHAR *))) == 0) { assert(FALSE); return FALSE; } memset(*fpalpstr, 0, (unsigned int)sRows * sizeof(ECHAR *)); for (i = 0 ; i < sRows ; ++i) { if (((*fpalpstr)[i] = (ECHAR *)malloc(sizeof(ECHAR) * (unsigned int)sCols)) == 0) { FreeTxtBuf(fpalpstr, sRows); assert(FALSE); return FALSE; } ECHAR_Fill((*fpalpstr)[i], ETEXT(' '), (unsigned int)sCols); } return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * AllocAttrBuf * * DESCRIPTION: * Allocates attribute buffer for terminal image. * * ARGUMENTS: * fpapst - pointer to pointer to buffer array. * sRows - number of rows * sCols - number of cols in each row. * * RETURNS: * BOOL * */ static BOOL AllocAttrBuf(PSTATTR **fpapst, const int sRows, const int sCols) { register int i, j; STATTR stAttr; memset(&stAttr, 0, sizeof(STATTR)); stAttr.txtclr = (unsigned int)GetNearestColorIndex(GetSysColor(COLOR_WINDOWTEXT)); stAttr.bkclr = (unsigned int)GetNearestColorIndex(GetSysColor(COLOR_WINDOW)); FreeAttrBuf(fpapst, sRows); // free any old stuff if ((*fpapst = (PSTATTR *)malloc((unsigned int)sRows * sizeof(PSTATTR))) == 0) { assert(FALSE); return FALSE; } for (i = 0 ; i < sRows ; ++i) { if (((*fpapst)[i] = (PSTATTR)malloc(sizeof(STATTR) * (unsigned int)sCols)) == 0) { FreeAttrBuf(fpapst, sRows); // free any old stuff assert(FALSE); return FALSE; } for (j = 0 ; j < sCols ; ++j) MemCopy((*fpapst)[i]+j, &stAttr, sizeof(STATTR)); } return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * FreeTxtBuf * * DESCRIPTION: * Free-up any allocated buffers for terminal text image * * ARGUMENTS: * fpalpstr - pointer to pointer to buffer array. * sRows - number of rows * sCols - number of cols in each row. * * RETURNS: * void * */ static void FreeTxtBuf(ECHAR ***fpalpstr, const int sRows) { register int i; ECHAR **alpstr = *fpalpstr; if (alpstr) { for (i = 0 ; *alpstr && i < sRows ; ++i) { free(*alpstr); *alpstr = NULL; alpstr += 1; } free(*fpalpstr); *fpalpstr = 0; } return; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * FreeAttrBuf * * DESCRIPTION: * Free-up any allocated buffers for terminal attribute image * * ARGUMENTS: * fpapst - pointer to pointer to buffer array. * sRows - number of rows * sCols - number of cols in each row. * * RETURNS: * void * */ static void FreeAttrBuf(PSTATTR **fpapst, const int sRows) { register int i; PSTATTR *apst = *fpapst; if (apst) { for (i = 0 ; *apst && i < sRows ; ++i) { free(*apst); *apst = NULL; apst += 1; } free(*fpapst); *fpapst = 0; } return; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * termSysColorChng * * DESCRIPTION: * Creates new brushes because system colors have changed. Also used * during initialization of terminal window. * * ARGUMENTS: * hhTerm - internal terminal handle. * * RETURNS: * void * */ BOOL termSysColorChng(const HHTERM hhTerm) { #define HATCH_PATTERN HS_BDIAGONAL HBRUSH hBrush; HPEN hPen; COLORREF cr; hhTerm->crBackScrl = GetSysColor(COLOR_BTNFACE); hhTerm->crBackScrlTxt = GetSysColor(COLOR_BTNTEXT); hhTerm->hBlackPen = GetStockObject(BLACK_PEN); hhTerm->hWhitePen = GetStockObject(WHITE_PEN); /* ----------------------- */ cr = GetSysColor(COLOR_WINDOW); if ((hBrush = CreateSolidBrush(cr)) == 0) { assert(FALSE); return FALSE; } hhTerm->crTerm = cr; if (hhTerm->hbrushTerminal) DeleteObject(hhTerm->hbrushTerminal); hhTerm->hbrushTerminal = hBrush; /* ----------------------- */ cr = GetSysColor(COLOR_BTNFACE); if ((hBrush = CreateSolidBrush(cr)) == 0) { assert(FALSE); return FALSE; } hhTerm->crBackScrl = cr; if (hhTerm->hbrushBackScrl) DeleteObject(hhTerm->hbrushBackScrl); hhTerm->hbrushBackScrl = hBrush; /* ----------------------- */ cr = GetSysColor(COLOR_BTNSHADOW); if ((hBrush = CreateSolidBrush(cr)) == 0) { assert(FALSE); return FALSE; } if (hhTerm->hbrushDivider) DeleteObject(hhTerm->hbrushDivider); hhTerm->hbrushDivider = hBrush; /* ----------------------- */ cr = GetSysColor(COLOR_HIGHLIGHT); if ((hBrush = CreateSolidBrush(cr)) == 0) { assert(FALSE); return FALSE; } if (hhTerm->hbrushHighlight) DeleteObject(hhTerm->hbrushHighlight); hhTerm->hbrushHighlight = hBrush; /* ----------------------- */ cr = GetSysColor(COLOR_BTNFACE); if ((hPen = CreatePen(PS_SOLID, 0, cr)) == 0) { assert(FALSE); return FALSE; } if (hhTerm->hLtGrayPen) DeleteObject(hhTerm->hLtGrayPen); hhTerm->hLtGrayPen = hPen; /* ----------------------- */ hBrush = CreateHatchBrush(HATCH_PATTERN, GetSysColor(COLOR_BTNFACE)); if (hBrush == 0) { assert(FALSE); return FALSE; } if (hhTerm->hbrushTermHatch) DeleteObject(hhTerm->hbrushTermHatch); hhTerm->hbrushTermHatch = hBrush; /* ----------------------- */ hBrush = CreateHatchBrush(HATCH_PATTERN, GetSysColor(COLOR_BTNSHADOW)); if (hBrush == 0) { assert(FALSE); return FALSE; } if (hhTerm->hbrushBackHatch) DeleteObject(hhTerm->hbrushBackHatch); hhTerm->hbrushBackHatch = hBrush; /* ----------------------- */ cr = GetSysColor(COLOR_BTNSHADOW); if ((hPen = CreatePen(PS_SOLID, 0, cr)) == 0) { assert(FALSE); return FALSE; } if (hhTerm->hDkGrayPen) DeleteObject(hhTerm->hDkGrayPen); hhTerm->hDkGrayPen = hPen; return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * termSetFont * * DESCRIPTION: * Sets the terminal font to the given font. If hFont is zero, * termSetFont() trys to create a default font. * * ARGUMENTS: * hhTerm - internal term handle. * plf - pointer to logfont * * RETURNS: * BOOL * */ BOOL termSetFont(const HHTERM hhTerm, const PLOGFONT plf) { HDC hdc; LOGFONT lf; HFONT hFont; char ach[256]; TEXTMETRIC tm; int nSize1, nSize2; int nCharSet; if (plf == 0) { // No font, use the default font for HyperTerminal // (usually New Courier) memset(&lf, 0, sizeof(LOGFONT)); // Someone added these different font sizes using the resource file // without consulting me. Seems pretty stupid to do it this way. // - mrw:3/5/96 // For VGA screens, we need a smaller font. // if (LoadString(glblQueryDllHinst(), IDS_TERM_DEF_VGA_SIZE, ach, sizeof(ach))) { nSize1 = atoi(ach); } else { nSize1 = -11; } if (LoadString(glblQueryDllHinst(), IDS_TERM_DEF_NONVGA_SIZE, ach, sizeof(ach))) { nSize2 = atoi(ach); } else { nSize2 = -15; } lf.lfHeight = (GetSystemMetrics(SM_CXSCREEN) < 810) ? nSize1 : nSize2; // mrw:3/5/96 - Font comes out really dinky on high res screens. // #if defined(INCL_USE_TERMINAL_FONT) if (GetSystemMetrics(SM_CXSCREEN) >= 1024) lf.lfHeight = -19; #endif lf.lfPitchAndFamily = FIXED_PITCH | MONO_FONT; if (LoadString(glblQueryDllHinst(), IDS_TERM_DEF_FONT, ach, sizeof(ach))) { strncpy(lf.lfFaceName, ach, sizeof(lf.lfFaceName)); lf.lfFaceName[sizeof(lf.lfFaceName)-1] = TEXT('\0'); } if (LoadString(glblQueryDllHinst(), IDS_TERM_DEF_CHARSET, ach, sizeof(ach))) { nCharSet = atoi(ach); lf.lfCharSet = (BYTE)nCharSet; } hFont = CreateFontIndirect(&lf); if (hFont == 0) { //*lf.lfCharSet = ANSI_CHARSET; //*hFont = CreateFontIndirect(&lf); //*if (hFont == 0) { assert(FALSE); return FALSE; } } } else { hFont = CreateFontIndirect(plf); if (hFont == 0) { assert(FALSE); return FALSE; } } /* --- Ok, we have our base font, blast the previous fonts --- */ if (hhTerm->hFont) { DeleteObject(hhTerm->hFont); hhTerm->hFont = 0; } if (hhTerm->hDblHiFont) { DeleteObject(hhTerm->hDblHiFont); hhTerm->hDblHiFont = 0; } if (hhTerm->hDblWiFont) { DeleteObject(hhTerm->hDblWiFont); hhTerm->hDblWiFont = 0; } if (hhTerm->hDblHiWiFont) { DeleteObject(hhTerm->hDblHiWiFont); hhTerm->hDblHiWiFont = 0; } /* --- And the symbol fonts --- */ if (hhTerm->hSymFont) { DeleteObject(hhTerm->hSymFont); hhTerm->hSymFont = 0; } if (hhTerm->hSymDblHiFont) { DeleteObject(hhTerm->hSymDblHiFont); hhTerm->hSymDblHiFont = 0; } if (hhTerm->hSymDblWiFont) { DeleteObject(hhTerm->hSymDblWiFont); hhTerm->hSymDblWiFont = 0; } if (hhTerm->hSymDblHiWiFont) { DeleteObject(hhTerm->hSymDblHiWiFont); hhTerm->hSymDblHiWiFont = 0; } /* --- Commit to the new font --- */ hhTerm->hFont = hFont; if (GetObject(hFont, sizeof(LOGFONT), &lf) == 0) { assert(FALSE); return FALSE; } /* --- save what we really got --- */ hhTerm->lf = lf; /* --- Get size of selected font. --- */ hdc = GetDC(hhTerm->hwnd); hFont = (HFONT)SelectObject(hdc, hFont); GetTextMetrics(hdc, &tm); SelectObject(hdc, hFont); ReleaseDC(hhTerm->hwnd, hdc); hhTerm->xChar = tm.tmAveCharWidth; hhTerm->yChar = tm.tmHeight; #if defined(FAR_EAST) if ((tm.tmMaxCharWidth % 2) == 0) { hhTerm->iEvenFont = TRUE; } else { hhTerm->iEvenFont = FALSE; } #else hhTerm->iEvenFont = TRUE; //mrw:10/10/95 #endif // We need to know if the font is italic because it changes the // way we draw. The italic fonts are regular fonts sheared. The // shear causes the character to draw into the next text box. // This really messes us up. To get around the problem, when // we're italic, we simply repaint the whole line when an text // comes in. - mrw,12/19/94 // hhTerm->fItalic = tm.tmItalic; /* --- Set bezel size based on font --- */ hhTerm->xBezel = BEZEL_SIZE; if (hhTerm->yChar < BEZEL_SIZE) { hhTerm->xBezel = max(5+OUTDENT, hhTerm->yChar); } switch (hhTerm->iCurType) { case EMU_CURSOR_LINE: default: hhTerm->iHstCurSiz = GetSystemMetrics(SM_CYBORDER) * 2; break; case EMU_CURSOR_BLOCK: hhTerm->iHstCurSiz = hhTerm->yChar; break; case EMU_CURSOR_NONE: hhTerm->iHstCurSiz = 0; break; } return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * termMakeFont * * DESCRIPTION: * When user selects a font, we only create the standard non-underlined * font. If the paint routines encounter an attribute that needs a * a different font, then we create it on the spot. This is more * economic since often we won't need all 8 fonts for a given session. * * ARGUMENTS: * hhTerm - internal terminal handle * fUnderline - font is underlined * fHigh - font is double high * fWide - font is double wide * * RETURNS: * 0 on error, hFont on success. * */ HFONT termMakeFont(const HHTERM hhTerm, const BOOL fUnderline, const BOOL fHigh, const BOOL fWide, const BOOL fSymbol) { LOGFONT lf; HFONT hFont; lf = hhTerm->lf; lf.lfWidth = hhTerm->xChar; if (fSymbol) { //lf.lfCharSet = SYMBOL_CHARSET; StrCharCopy(lf.lfFaceName, "Arial Alternative Symbol"); } if (fUnderline) lf.lfUnderline = 1; if (fHigh) lf.lfHeight *= 2; if (fWide) lf.lfWidth *= 2; if ((hFont = CreateFontIndirect(&lf)) == 0) assert(FALSE); return hFont; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * fAllocBkBuf * * DESCRIPTION: * Allocates buffer space for backscroll text * * ARGUMENTS: * hhTerm - internal terminal handle * * RETURNS: * BOOL * */ static BOOL termAllocBkBuf(const HHTERM hhTerm) { register int i; // This number should be big enough so that a maximized window of // backscroll text can be displayed. hhTerm->iMaxPhysicalBkRows = hhTerm->iPhysicalBkRows = min(5000, (GetSystemMetrics(SM_CYFULLSCREEN) / hhTerm->yChar) + 1); if ((hhTerm->fplpstrBkTxt = malloc((unsigned int)hhTerm->iMaxPhysicalBkRows * sizeof(ECHAR *))) == 0) { return FALSE; } for (i = 0 ; i < hhTerm->iMaxPhysicalBkRows ; ++i) { if ((hhTerm->fplpstrBkTxt[i] = malloc(MAX_EMUCOLS * sizeof(ECHAR))) == 0) { termFreeBkBuf(hhTerm); return FALSE; } ECHAR_Fill(hhTerm->fplpstrBkTxt[i], ETEXT(' '), MAX_EMUCOLS); } return TRUE; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * FreeBkBuf * * DESCRIPTION: * Frees space allocated to backscroll buffer. * * ARGUMENTS: * hhTerm - internal terminal handle * * RETURNS: * void * */ static void termFreeBkBuf(const HHTERM hhTerm) { register int i; for (i = 0 ; i < hhTerm->iMaxPhysicalBkRows ; ++i) { if (hhTerm->fplpstrBkTxt[i]) { free(hhTerm->fplpstrBkTxt[i]); hhTerm->fplpstrBkTxt[i] = NULL; } } free(hhTerm->fplpstrBkTxt); hhTerm->fplpstrBkTxt = NULL; return; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * FUNCTION: * GetNearestColorIndex * * DESCRIPTION: * Duplicates a palette function that I couldn't get to work. Basicly, * the emulator has a table of colors it is allowed to use. When the * user picks a color, this function returns the index of the color that * most closely matches. How does it do this you say? Well, imagine * the problem as 3D space. The pallete colors all map into this space. * The goal is to find the pallete color closest to the given colorref * value. Borrowing from the 10th grade algrebra we know that: * * X^2 + Y^2 + Z^2 = C^2 * * The distance between two points is then: * * (X - X')^2 + (Y - Y')^2 + (Z - Z') = C'^2 * * The point with the smallest C'^2 value wins! * * ARGUMENTS: * COLORREF *acr - color table to use for matching * COLORREF cr - color to match. * * RETURNS: * An index of the closest matching color. * */ int GetNearestColorIndex(COLORREF cr) { int i, idx = 0; unsigned int R, G, B; unsigned long C, CMin = (unsigned long)-1; for (i = 0 ; i < DIM(crEmuColors) ; ++i) { R = GetRValue(crEmuColors[i]) - GetRValue(cr); R *= R; G = GetGValue(crEmuColors[i]) - GetGValue(cr); G *= G; B = GetBValue(crEmuColors[i]) - GetBValue(cr); B *= B; C = (ULONG)(R + G + B); if (C < CMin) { CMin = C; idx = i; if (C == 0) // we matched! break; } } return idx; }
265617.c
/**************************************************************************** * boards/arm/stm32/stm32f103-minimum/src/stm32_bringup.c * * Copyright (C) 2016-2017 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * 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 name NuttX 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/mount.h> #include <stdbool.h> #include <stdio.h> #include <syslog.h> #include <debug.h> #include <errno.h> #include <nuttx/board.h> #include <nuttx/timers/oneshot.h> #ifdef CONFIG_USBMONITOR # include <nuttx/usb/usbmonitor.h> #endif #include "stm32.h" #ifdef CONFIG_STM32_OTGFS # include "stm32_usbhost.h" #endif #ifdef CONFIG_BUTTONS # include <nuttx/input/buttons.h> #endif #ifdef CONFIG_USERLED # include <nuttx/leds/userled.h> #endif #ifdef CONFIG_USERLED # include <nuttx/leds/userled.h> #endif #ifdef CONFIG_VIDEO_FB # include <nuttx/video/fb.h> #endif #include "stm32f103_minimum.h" /* Conditional logic in stm32f103_minimum.h will determine if certain features * are supported. Tests for these features need to be made after including * stm32f103_minimum.h. */ #ifdef HAVE_RTC_DRIVER # include <nuttx/timers/rtc.h> # include "stm32_rtc.h" #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Checking needed by W25 Flash */ #define HAVE_W25 1 /* Can't support the W25 device if it SPI1 or W25 support is not enabled */ #if !defined(CONFIG_STM32_SPI1) || !defined(CONFIG_MTD_W25) # undef HAVE_W25 #endif /* Can't support W25 features if mountpoints are disabled */ #ifdef CONFIG_DISABLE_MOUNTPOINT # undef HAVE_W25 #endif /* Default W25 minor number */ #if defined(HAVE_W25) && !defined(CONFIG_NSH_W25MINOR) # define CONFIG_NSH_W25MINOR 0 #endif /* Checking needed by MMC/SDCard */ #ifdef CONFIG_NSH_MMCSDMINOR # define MMCSD_MINOR CONFIG_NSH_MMCSDMINOR #else # define MMCSD_MINOR 0 #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: stm32_bringup * * Description: * Perform architecture-specific initialization * * CONFIG_BOARD_LATE_INITIALIZE=y : * Called from board_late_initialize(). * * CONFIG_BOARD_LATE_INITIALIZE=n && CONFIG_LIB_BOARDCTL=y : * Called from the NSH library * ****************************************************************************/ int stm32_bringup(void) { #ifdef CONFIG_ONESHOT struct oneshot_lowerhalf_s *os = NULL; #endif int ret = OK; #ifdef CONFIG_DEV_GPIO ret = stm32_gpio_initialize(); if (ret < 0) { syslog(LOG_ERR, "Failed to initialize GPIO Driver: %d\n", ret); return ret; } #endif #ifdef CONFIG_VIDEO_FB /* Initialize and register the framebuffer driver */ ret = fb_register(0, 0); if (ret < 0) { syslog(LOG_ERR, "ERROR: fb_register() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_ZEROCROSS /* Configure the zero-crossing driver */ ret = stm32_zerocross_initialize(); if (ret < 0) { syslog(LOG_ERR, "Failed to initialize Zero-Cross, error %d\n", ret); return ret; } #endif #ifdef CONFIG_MMCSD ret = stm32_mmcsd_initialize(MMCSD_MINOR); if (ret < 0) { syslog(LOG_ERR, "Failed to initialize SD slot %d: %d\n", ret); return ret; } #endif #ifdef CONFIG_SENSORS_BMP180 ret = stm32_bmp180initialize("/dev/press0"); if (ret < 0) { syslog(LOG_ERR, "Failed to initialize BMP180, error %d\n", ret); return ret; } #endif #ifdef HAVE_W25 /* Initialize and register the W25 FLASH file system. */ ret = stm32_w25initialize(CONFIG_NSH_W25MINOR); if (ret < 0) { syslog(LOG_ERR, "ERROR: Failed to initialize W25 minor %d: %d\n", CONFIG_NSH_W25MINOR, ret); return ret; } #endif #ifdef CONFIG_FS_PROCFS /* Mount the procfs file system */ ret = mount(NULL, STM32_PROCFS_MOUNTPOINT, "procfs", 0, NULL); if (ret < 0) { syslog(LOG_ERR, "ERROR: Failed to mount procfs at %s: %d\n", STM32_PROCFS_MOUNTPOINT, ret); } #endif #ifdef HAVE_AT24 /* Initialize the AT24 driver */ ret = stm32_at24_automount(AT24_MINOR); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_at24_automount failed: %d\n", ret); return ret; } #endif /* HAVE_AT24 */ #ifdef CONFIG_PWM /* Initialize PWM and register the PWM device. */ ret = stm32_pwm_setup(); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_pwm_setup() failed: %d\n", ret); } #endif #ifdef CONFIG_AUDIO_TONE /* Configure and initialize the tone generator. */ ret = stm32_tone_setup(); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_tone_setup() failed: %d\n", ret); } #endif #ifdef CONFIG_LEDS_APA102 /* Configure and initialize the APA102 LED Strip. */ ret = stm32_apa102init("/dev/leddrv0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_apa102init() failed: %d\n", ret); } #endif #ifdef CONFIG_LM75_I2C /* Configure and initialize the LM75 sensor */ ret = stm32_lm75initialize("/dev/temp"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_lm75initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_RGBLED /* Configure and initialize the RGB LED. */ ret = stm32_rgbled_setup(); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_rgbled_setup() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_HCSR04 /* Configure and initialize the HC-SR04 distance sensor */ ret = stm32_hcsr04_initialize("/dev/dist0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_hcsr04_initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_MAX6675 ret = stm32_max6675initialize("/dev/temp0"); if (ret < 0) { serr("ERROR: stm32_max6675initialize failed: %d\n", ret); } #endif #ifdef CONFIG_CAN_MCP2515 /* Configure and initialize the MCP2515 CAN device */ ret = stm32_mcp2515initialize("/dev/can0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_mcp2515initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_CL_MFRC522 ret = stm32_mfrc522initialize("/dev/rfid0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_mfrc522initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_ONESHOT os = oneshot_initialize(1, 10); if (os) { ret = oneshot_register("/dev/oneshot", os); } #endif #ifdef CONFIG_BUTTONS /* Register the BUTTON driver */ ret = btn_lower_initialize("/dev/buttons"); if (ret < 0) { syslog(LOG_ERR, "ERROR: btn_lower_initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_INPUT_NUNCHUCK /* Register the Nunchuck driver */ ret = nunchuck_initialize("/dev/nunchuck0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: nunchuck_initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_QENCODER /* Initialize and register the qencoder driver */ ret = stm32_qencoder_initialize("/dev/qe0", CONFIG_STM32F103MINIMUM_QETIMER); if (ret != OK) { syslog(LOG_ERR, "ERROR: Failed to register the qencoder: %d\n", ret); } #endif #ifdef CONFIG_USERLED /* Register the LED driver */ ret = userled_lower_initialize("/dev/userleds"); if (ret < 0) { syslog(LOG_ERR, "ERROR: userled_lower_initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_APDS9960 /* Register the APDS-9960 gesture sensor */ ret = stm32_apds9960initialize("/dev/gest0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_apds9960initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_SENSORS_VEML6070 /* Register the UV-A light sensor */ ret = stm32_veml6070initialize("/dev/uvlight0"); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_veml6070initialize() failed: %d\n", ret); } #endif #ifdef CONFIG_ADC /* Initialize ADC and register the ADC driver. */ ret = stm32_adc_setup(); if (ret < 0) { syslog(LOG_ERR, "ERROR: stm32_adc_setup failed: %d\n", ret); } #endif #if defined(CONFIG_WL_NRF24L01) /* Initialize the NRF24L01 wireless module */ stm32_wlinitialize(); #endif return ret; }
463169.c
#include <stdlib.h> void *alloc(size_t size) { void *ret = calloc(1, size); if (ret == NULL) { abort(); } return ret; }
930499.c
/* * Copyright (c) 2020 Stephanos Ioannidis <[email protected]> * Copyright (C) 2010-2020 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include <ztest.h> #include <zephyr.h> #include <stdlib.h> #include <arm_math.h> #include <arm_const_structs.h> #include "../../common/test_common.h" #include "rf64.pat" #define SNR_ERROR_THRESH ((float64_t)250) static void test_arm_rfft_f64_real_backend( bool inverse, const u64_t *input, const u64_t *ref, size_t length) { arm_rfft_fast_instance_f64 inst; float64_t *output, *scratch; /* Initialise instance */ arm_rfft_fast_init_f64(&inst, length); /* Allocate output buffer */ output = malloc(length * sizeof(float64_t)); zassert_not_null(output, ASSERT_MSG_BUFFER_ALLOC_FAILED); scratch = calloc(length + 2, sizeof(float64_t)); /* see #24701 */ zassert_not_null(scratch, ASSERT_MSG_BUFFER_ALLOC_FAILED); /* Load data in place */ memcpy(scratch, input, length * sizeof(float64_t)); /* Run test function */ arm_rfft_fast_f64(&inst, scratch, output, inverse); /* Validate output */ zassert_true( test_snr_error_f64(length, output, (float64_t *)ref, SNR_ERROR_THRESH), ASSERT_MSG_SNR_LIMIT_EXCEED); /* Free output buffer */ free(output); free(scratch); } static void test_arm_rfft_f64_real( const u64_t *input, const u64_t *ref, size_t length) { test_arm_rfft_f64_real_backend(false, input, ref, length); } DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_32, in_rfft_noisy_32, ref_rfft_noisy_32, 32); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_64, in_rfft_noisy_64, ref_rfft_noisy_64, 64); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_128, in_rfft_noisy_128, ref_rfft_noisy_128, 128); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_256, in_rfft_noisy_256, ref_rfft_noisy_256, 256); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_512, in_rfft_noisy_512, ref_rfft_noisy_512, 512); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_1024, in_rfft_noisy_1024, ref_rfft_noisy_1024, 1024); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_2048, in_rfft_noisy_2048, ref_rfft_noisy_2048, 2048); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, noisy_4096, in_rfft_noisy_4096, ref_rfft_noisy_4096, 4096); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_32, in_rfft_step_32, ref_rfft_step_32, 32); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_64, in_rfft_step_64, ref_rfft_step_64, 64); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_128, in_rfft_step_128, ref_rfft_step_128, 128); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_256, in_rfft_step_256, ref_rfft_step_256, 256); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_512, in_rfft_step_512, ref_rfft_step_512, 512); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_1024, in_rfft_step_1024, ref_rfft_step_1024, 1024); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_2048, in_rfft_step_2048, ref_rfft_step_2048, 2048); DEFINE_TEST_VARIANT3(arm_rfft_f64_real, step_4096, in_rfft_step_4096, ref_rfft_step_4096, 4096); static void test_arm_rifft_f64_real( const u64_t *input, const u64_t *ref, size_t length) { test_arm_rfft_f64_real_backend(true, input, ref, length); } DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_32, in_rifft_noisy_32, in_rfft_noisy_32, 32); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_64, in_rifft_noisy_64, in_rfft_noisy_64, 64); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_128, in_rifft_noisy_128, in_rfft_noisy_128, 128); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_256, in_rifft_noisy_256, in_rfft_noisy_256, 256); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_512, in_rifft_noisy_512, in_rfft_noisy_512, 512); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_1024, in_rifft_noisy_1024, in_rfft_noisy_1024, 1024); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_2048, in_rifft_noisy_2048, in_rfft_noisy_2048, 2048); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, noisy_4096, in_rifft_noisy_4096, in_rfft_noisy_4096, 4096); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_32, in_rifft_step_32, in_rfft_step_32, 32); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_64, in_rifft_step_64, in_rfft_step_64, 64); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_128, in_rifft_step_128, in_rfft_step_128, 128); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_256, in_rifft_step_256, in_rfft_step_256, 256); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_512, in_rifft_step_512, in_rfft_step_512, 512); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_1024, in_rifft_step_1024, in_rfft_step_1024, 1024); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_2048, in_rifft_step_2048, in_rfft_step_2048, 2048); DEFINE_TEST_VARIANT3(arm_rifft_f64_real, step_4096, in_rifft_step_4096, in_rfft_step_4096, 4096); void test_transform_rf64(void) { ztest_test_suite(transform_rf64, ztest_unit_test(test_arm_rfft_f64_real_noisy_32), ztest_unit_test(test_arm_rifft_f64_real_noisy_32), ztest_unit_test(test_arm_rfft_f64_real_noisy_64), ztest_unit_test(test_arm_rifft_f64_real_noisy_64), ztest_unit_test(test_arm_rfft_f64_real_noisy_128), ztest_unit_test(test_arm_rifft_f64_real_noisy_128), ztest_unit_test(test_arm_rfft_f64_real_noisy_256), ztest_unit_test(test_arm_rifft_f64_real_noisy_256), ztest_unit_test(test_arm_rfft_f64_real_noisy_512), ztest_unit_test(test_arm_rifft_f64_real_noisy_512), ztest_unit_test(test_arm_rfft_f64_real_noisy_1024), ztest_unit_test(test_arm_rifft_f64_real_noisy_1024), ztest_unit_test(test_arm_rfft_f64_real_noisy_2048), ztest_unit_test(test_arm_rifft_f64_real_noisy_2048), ztest_unit_test(test_arm_rfft_f64_real_noisy_4096), ztest_unit_test(test_arm_rifft_f64_real_noisy_4096), ztest_unit_test(test_arm_rfft_f64_real_step_32), ztest_unit_test(test_arm_rifft_f64_real_step_32), ztest_unit_test(test_arm_rfft_f64_real_step_64), ztest_unit_test(test_arm_rifft_f64_real_step_64), ztest_unit_test(test_arm_rfft_f64_real_step_128), ztest_unit_test(test_arm_rifft_f64_real_step_128), ztest_unit_test(test_arm_rfft_f64_real_step_256), ztest_unit_test(test_arm_rifft_f64_real_step_256), ztest_unit_test(test_arm_rfft_f64_real_step_512), ztest_unit_test(test_arm_rifft_f64_real_step_512), ztest_unit_test(test_arm_rfft_f64_real_step_1024), ztest_unit_test(test_arm_rifft_f64_real_step_1024), ztest_unit_test(test_arm_rfft_f64_real_step_2048), ztest_unit_test(test_arm_rifft_f64_real_step_2048), ztest_unit_test(test_arm_rfft_f64_real_step_4096), ztest_unit_test(test_arm_rifft_f64_real_step_4096) ); ztest_run_test_suite(transform_rf64); }
161467.c
#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" // 0x00000001 System.Object IActivationFactory::ActivateInstance() // 0x00000002 System.Void System.__Il2CppComObject::Finalize() extern void __Il2CppComObject_Finalize_m720B2062F661A0770A32D24B731AD4AFE314A5CD (void); // 0x00000003 System.Void System.__Il2CppComDelegate::Finalize() extern void __Il2CppComDelegate_Finalize_mC9F8EA94444C3AF0A43CC723A23EE4D8B7984F8C (void); static Il2CppMethodPointer s_methodPointers[3] = { NULL, __Il2CppComObject_Finalize_m720B2062F661A0770A32D24B731AD4AFE314A5CD, __Il2CppComDelegate_Finalize_mC9F8EA94444C3AF0A43CC723A23EE4D8B7984F8C, }; static const int32_t s_InvokerIndices[3] = { 0, 5976, 5976, }; IL2CPP_EXTERN_C const Il2CppCodeGenModule g___Generated_CodeGenModule; const Il2CppCodeGenModule g___Generated_CodeGenModule = { "__Generated", 3, s_methodPointers, 0, NULL, s_InvokerIndices, 0, NULL, 0, NULL, 0, NULL, NULL, NULL, // module initializer, NULL, NULL, NULL, };
146321.c
/* Categories of Unicode characters. Copyright (C) 2002, 2006-2007, 2009-2020 Free Software Foundation, Inc. Written by Bruno Haible <[email protected]>, 2002. This program is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * 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. or both in parallel, as here. 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 program. If not, see <https://www.gnu.org/licenses/>. */ #include <config.h> /* Specification. */ #include "unictype.h" /* Define u_categ_Pi table. */ #include "categ_Pi.h" const uc_general_category_t UC_CATEGORY_Pi = { UC_CATEGORY_MASK_Pi, 0, { &u_categ_Pi } };
306173.c
// // Created by Francis McCabe on 2/19/21. // #include <assert.h> #include <globals.h> #include "taskP.h" #include "termP.h" #include "engineP.h" #include "heapP.h" #include "buddy.h" logical traceTasks = False; // stack operation tracing integer minStackSize = 256; /* What is the smallest stack size */ integer stackRegionSize = (1 << 23); /* 64M cells is default max stack size */ static long tskSize(specialClassPo cl, termPo o); static termPo tskCopy(specialClassPo cl, termPo dst, termPo src); static termPo tskScan(specialClassPo cl, specialHelperFun helper, void *c, termPo o); static logical tskCmp(specialClassPo cl, termPo o1, termPo o2); static integer tskHash(specialClassPo cl, termPo o); static retCode tskDisp(ioPo out, termPo t, integer precision, integer depth, logical alt); static termPo tskFinalizer(specialClassPo class, termPo o); SpecialClass TaskClass = { .clss = Null, .sizeFun = tskSize, .copyFun = tskCopy, .scanFun = tskScan, .finalizer = tskFinalizer, .compFun = tskCmp, .hashFun = tskHash, .dispFun = tskDisp }; static MethodRec underFlowMethod = { .clss = Null, .codeSize = 2, .arity = 0, .lclcnt = 0, .pool = Null, .locals = Null, .code = {Underflow, 0} }; clssPo taskClass = (clssPo) &TaskClass; static integer stackCount = 0; static buddyRegionPo stackRegion; static framePo firstFrame(taskPo tsk); void initTasks() { TaskClass.clss = specialClass; underFlowMethod.clss = methodClass; integer regionSize = (1 << lg2(stackRegionSize)); #ifdef TRACESTACK if (traceTasks) outMsg(logFile, "setting stack region to %d words\n", regionSize); #endif stackRegion = createRegion(regionSize, minStackSize); } taskPo C_TASK(termPo t) { assert(hasClass(t, taskClass)); return (taskPo) t; } taskPo allocateTask(heapPo H, integer sze, methodPo underFlow, TaskState state, taskPo attachment) { if (sze > stackRegionSize) syserr("tried to allocate too large a stack"); sze = (1 << lg2(2 * sze - 1)) - 1; // Adjust stack size to be just under a power of two int root = gcAddRoot(H, (ptrPo) &attachment); taskPo tsk = (taskPo) allocateObject(H, taskClass, StackCellCount); tsk->stkMem = (ptrPo) allocateBuddy(stackRegion, sze); if (tsk->stkMem == Null) { syserr("Ran out of stack space"); } tsk->sze = sze; tsk->hwm = sze; tsk->sp = &tsk->stkMem[sze]; tsk->fp = (framePo) &tsk->stkMem[sze]; tsk->attachment = attachment; tsk->state = state; tsk->hash = stackCount++; #ifdef TRACESTACK if (traceTasks) outMsg(logFile, "establish stack of %d words\n", sze); #endif pushFrame(tsk, underFlow, tsk->fp, tsk->sp); gcReleaseRoot(H, root); return tsk; } TaskState taskState(taskPo tsk) { return tsk->state; } retCode setTaskState(taskPo tsk, TaskState state) { switch (tsk->state) { case suspended: tsk->state = state; return Ok; case active: if (state != suspended && state != moribund) return Error; else { tsk->state = state; return Ok; } case moribund: return Error; } } framePo currFrame(taskPo tsk) { return tsk->fp; } integer stackHwm(taskPo tsk) { return tsk->hwm; } void propagateHwm(taskPo tsk) { integer hwm = tsk->hwm; while (tsk->attachment != Null) { tsk = tsk->attachment; if (tsk->hwm < hwm) tsk->hwm = hwm; } } framePo pushFrame(taskPo tsk, methodPo mtd, framePo fp, ptrPo sp) { framePo f = (framePo) (sp) - 1; assert(f >= (framePo) (tsk->stkMem)); f->prog = mtd; f->pc = entryPoint(mtd); f->fp = fp; tsk->fp = f; tsk->sp = (ptrPo) f; integer lclCnt = lclCount(mtd); /* How many locals do we have */ sp = (ptrPo) tsk->fp - lclCnt; #ifdef TRACEEXEC for (integer ix = 0; ix < lclCnt; ix++) sp[ix] = voidEnum; #endif return f; } long tskSize(specialClassPo cl, termPo o) { return StackCellCount; } void taskSanityCheck(taskPo tsk) { assert( tsk != Null && tsk->sp >= tsk->stkMem && tsk->sp <= &tsk->stkMem[tsk->sze] && tsk->fp >= (framePo) tsk->stkMem && tsk->fp <= (framePo) &tsk->stkMem[tsk->sze]); if (tsk->stkMem != Null) assert(!inFreeBlock(stackRegion, tsk->stkMem)); } void verifyTask(taskPo tsk, heapPo H) { if (tsk->stkMem != Null) { taskSanityCheck(tsk); ptrPo sp = tsk->sp; framePo fp = tsk->fp; ptrPo limit = tsk->stkMem + tsk->sze; while (sp < limit) { assert(sp <= (ptrPo) fp); while (sp < (ptrPo) fp) validPtr(H, *sp++); sp = (ptrPo) (fp + 1); fp = fp->fp; } switch (taskState(tsk)) { case active: case suspended: verifyTask(tsk->attachment, H); break; default: return; } } } termPo tskCopy(specialClassPo cl, termPo dst, termPo src) { taskPo ss = C_TASK(src); taskPo ds = (taskPo) dst; // Dest not yet a valid stack structure *ds = *ss; // Copy the structural part return ((termPo) ds) + StackCellCount; } logical tskCmp(specialClassPo cl, termPo o1, termPo o2) { return o1 == o2; } integer tskHash(specialClassPo cl, termPo o) { return C_TASK(o)->hash; } integer stackNo(taskPo tsk) { return tsk->hash; } termPo popStack(taskPo tsk) { assert(tsk->sp < stackLimit(tsk)); return *tsk->sp++; } termPo topStack(taskPo tsk) { assert(tsk->sp < (ptrPo) tsk->fp); return tsk->sp[0]; } termPo peekStack(taskPo tsk, integer delta) { assert(tsk->sp + delta < (ptrPo) tsk->fp); return tsk->sp[delta]; } void pushStack(taskPo tsk, termPo ptr) { assert(tsk->sp > tsk->stkMem); *--tsk->sp = ptr; } void moveStack2Stack(taskPo totsk, taskPo fromtsk, integer count) { assert(validStkPtr(fromtsk, fromtsk->sp + count)); assert(stkHasSpace(totsk, count)); ptrPo src = fromtsk->sp + count; ptrPo dst = totsk->sp; for (integer ix = count; ix > 0; ix--) { *--dst = *--src; } totsk->sp = dst; fromtsk->sp += count; } termPo tskScan(specialClassPo cl, specialHelperFun helper, void *c, termPo o) { taskPo tsk = C_TASK(o); assert(tsk != Null); if (tsk->stkMem != Null) { #ifdef TRACEMEM if (traceTasks) taskSanityCheck(tsk); if (traceMemory) { outMsg(logFile, "scan stack %d\n%_", tsk->hash); } #endif ptrPo sp = tsk->sp; framePo fp = tsk->fp; ptrPo limit = tsk->stkMem + tsk->sze; while (sp < limit) { assert(sp <= (ptrPo) fp); while (sp < (ptrPo) fp) helper(sp++, c); integer off = insOffset(fp->prog, fp->pc); helper((ptrPo) &fp->prog, c); fp->pc = pcAddr(fp->prog, off); sp = (ptrPo) (fp + 1); fp = fp->fp; } } if (tsk->attachment != Null) helper((ptrPo) &tsk->attachment, c); return o + StackCellCount; } termPo tskFinalizer(specialClassPo class, termPo o) { taskPo tsk = C_TASK(o); if (tsk->stkMem != Null) { release(stackRegion, (voidPtr) tsk->stkMem); tsk->stkMem = Null; } return o + StackCellCount; } char *stackStateName(TaskState ste) { switch (ste) { case active: return "active"; case suspended: return "suspended"; case moribund: return "moribund"; default: return "unknown state"; } } retCode tskDisp(ioPo out, termPo t, integer precision, integer depth, logical alt) { taskPo tsk = C_TASK(t); framePo first = firstFrame(tsk); if (first != Null && first != tsk->fp) return outMsg(out, "(.stack %d:[%s] %M .. %M.)", tsk->hash, stackStateName(tsk->state), tsk->fp->prog, first->prog); else return outMsg(out, "(.stack %d:[%s] %M.)", tsk->hash, stackStateName(tsk->state), tsk->fp->prog); } taskPo glueOnStack(heapPo H, taskPo tsk, integer size, integer saveArity) { int root = gcAddRoot(H, (ptrPo) &tsk); assert(size >= minStackSize && taskState(tsk) != moribund); taskPo newStack = allocateTask(H, size, &underFlowMethod, taskState(tsk), tsk); moveStack2Stack(newStack, tsk, saveArity); propagateHwm(newStack); gcReleaseRoot(H, root); return newStack; } taskPo spinupStack(heapPo H, taskPo tsk, integer size) { assert(size >= minStackSize); return allocateTask(H, size, &underFlowMethod, suspended, Null); } taskPo attachTask(taskPo tsk, taskPo seg) { #ifdef TRACESTACK if (traceTasks) outMsg(logFile, "attach stack %T to %T\n", seg, tsk); #endif assert(taskState(tsk) == active); taskPo s = seg; taskPo f = s; while (s != Null && taskState(s) == suspended) { setTaskState(s, active); f = s; s = s->attachment; } assert(taskState(f) == active && f->attachment == Null); f->attachment = tsk; return seg; } // Get the stack immediately below the identified parent taskPo detachTask(taskPo basetsk, taskPo parent) { #ifdef TRACESTACK if (traceTasks) outMsg(logFile, "detach %T up to %T\n", basetsk, parent); #endif assert(taskState(parent) == active); taskPo s = basetsk; while (s != Null && s != parent) { s->state = suspended; s = basetsk->attachment; } if (s == Null || s->attachment == Null) return Null; else { taskPo ss = s->attachment; s->attachment = Null; s->state = suspended; return ss; } } taskPo dropTask(taskPo tsk) { #ifdef TRACESTACK if (traceTasks) outMsg(logFile, "drop stack %T\n%_", tsk); #endif taskPo previous = tsk->attachment; tsk->state = moribund; release(stackRegion, (voidPtr) tsk->stkMem); tsk->stkMem = Null; tsk->sze = -1; return previous; } framePo firstFrame(taskPo tsk) { framePo fp = tsk->fp; framePo f = fp; framePo limit = (framePo) (tsk->stkMem + tsk->sze); while (fp < limit) { f = fp; fp = fp->fp; } if (f < limit) return f; else return Null; }
409678.c
/* * $Id: ad_end.c 922 2001-05-31 14:10:48Z karsten $ * * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "adio.h" #include "adio_extern.h" void ADIO_End(int *error_code) { ADIOI_Flatlist_node *curr, *next; ADIOI_Malloc_async *tmp; ADIOI_Malloc_req *tmp1; /* FPRINTF(stderr, "reached end\n"); */ /* delete the flattened datatype list */ curr = ADIOI_Flatlist; while (curr) { if (curr->blocklens) ADIOI_Free(curr->blocklens); if (curr->indices) ADIOI_Free(curr->indices); next = curr->next; ADIOI_Free(curr); curr = next; } ADIOI_Flatlist = NULL; if (ADIOI_Async_list_head) { FPRINTF(stderr, "ADIO_End: Error! There are outstanding nonblocking I/O operations!\n"); MPI_Abort(MPI_COMM_WORLD, 1); } /* free list of available ADIOI_Async_nodes. */ while (ADIOI_Malloc_async_head) { ADIOI_Free(ADIOI_Malloc_async_head->ptr); tmp = ADIOI_Malloc_async_head; ADIOI_Malloc_async_head = ADIOI_Malloc_async_head->next; ADIOI_Free(tmp); } ADIOI_Async_avail_head = ADIOI_Async_avail_tail = NULL; ADIOI_Malloc_async_head = ADIOI_Malloc_async_tail = NULL; /* free all available request objects */ while (ADIOI_Malloc_req_head) { ADIOI_Free(ADIOI_Malloc_req_head->ptr); tmp1 = ADIOI_Malloc_req_head; ADIOI_Malloc_req_head = ADIOI_Malloc_req_head->next; ADIOI_Free(tmp1); } ADIOI_Malloc_req_head = ADIOI_Malloc_req_tail = NULL; /* free file, request, and info tables used for Fortran interface */ if (ADIOI_Ftable) ADIOI_Free(ADIOI_Ftable); if (ADIOI_Reqtable) ADIOI_Free(ADIOI_Reqtable); #ifndef HAVE_MPI_INFO if (MPIR_Infotable) ADIOI_Free(MPIR_Infotable); #endif #ifdef MPICH if(ADIOI_DFLT_ERR_HANDLER) MPI_Errhandler_free(&ADIOI_DFLT_ERR_HANDLER); #endif *error_code = MPI_SUCCESS; } /* This is the delete callback function associated with ADIO_Init_keyval when MPI_COMM_WORLD is freed */ int ADIOI_End_call(MPI_Comm comm, int keyval, void *attribute_val, void *extra_state) { int error_code; ADIO_End(&error_code); return error_code; }
321635.c
/**************************************************************************** * Copyright (c) 1998-2001,2002 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim <[email protected]> 1992,1995 * * and: Eric S. Raymond <[email protected]> * ****************************************************************************/ /* ** lib_box.c ** ** The routine wborder(). ** */ #include <curses.priv.h> MODULE_ID("$Id: lib_box.c,v 1.21 2002/09/15 01:04:27 tom Exp $") #if USE_WIDEC_SUPPORT static inline chtype _my_render(WINDOW *win, chtype ch) { NCURSES_CH_T wch; SetChar2(wch, ch); wch = _nc_render(win, wch); return CharOf(wch) | AttrOf(wch); } #define RENDER_WITH_DEFAULT(ch,def) w ## ch = _my_render(win, (ch == 0) ? def : ch) #else #define RENDER_WITH_DEFAULT(ch,def) w ## ch = _nc_render(win, (ch == 0) ? def : ch) #endif NCURSES_EXPORT(int) wborder(WINDOW *win, chtype ls, chtype rs, chtype ts, chtype bs, chtype tl, chtype tr, chtype bl, chtype br) { NCURSES_SIZE_T i; NCURSES_SIZE_T endx, endy; chtype wls, wrs, wts, wbs, wtl, wtr, wbl, wbr; T((T_CALLED("wborder(%p,%s,%s,%s,%s,%s,%s,%s,%s)"), win, _tracechtype2(1, ls), _tracechtype2(2, rs), _tracechtype2(3, ts), _tracechtype2(4, bs), _tracechtype2(5, tl), _tracechtype2(6, tr), _tracechtype2(7, bl), _tracechtype2(8, br))); if (!win) returnCode(ERR); RENDER_WITH_DEFAULT(ls, ACS_VLINE); RENDER_WITH_DEFAULT(rs, ACS_VLINE); RENDER_WITH_DEFAULT(ts, ACS_HLINE); RENDER_WITH_DEFAULT(bs, ACS_HLINE); RENDER_WITH_DEFAULT(tl, ACS_ULCORNER); RENDER_WITH_DEFAULT(tr, ACS_URCORNER); RENDER_WITH_DEFAULT(bl, ACS_LLCORNER); RENDER_WITH_DEFAULT(br, ACS_LRCORNER); T(("using %s, %s, %s, %s, %s, %s, %s, %s", _tracechtype2(1, wls), _tracechtype2(2, wrs), _tracechtype2(3, wts), _tracechtype2(4, wbs), _tracechtype2(5, wtl), _tracechtype2(6, wtr), _tracechtype2(7, wbl), _tracechtype2(8, wbr))); endx = win->_maxx; endy = win->_maxy; for (i = 0; i <= endx; i++) { SetChar2(win->_line[0].text[i], wts); SetChar2(win->_line[endy].text[i], wbs); } win->_line[endy].firstchar = win->_line[0].firstchar = 0; win->_line[endy].lastchar = win->_line[0].lastchar = endx; for (i = 0; i <= endy; i++) { SetChar2(win->_line[i].text[0], wls); SetChar2(win->_line[i].text[endx], wrs); win->_line[i].firstchar = 0; win->_line[i].lastchar = endx; } SetChar2(win->_line[0].text[0], wtl); SetChar2(win->_line[0].text[endx], wtr); SetChar2(win->_line[endy].text[0], wbl); SetChar2(win->_line[endy].text[endx], wbr); _nc_synchook(win); returnCode(OK); }
895275.c
/* * Copyright (C) 2007-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ /* * this application calls a user-written function that contains a bad code pattern. */ #include <stdio.h> #include <stdlib.h> #include <string.h> extern void bad_jump(); int main(int argc, char* argv[]) { char* buffer; buffer = (char*)malloc(64); strcpy(buffer, "abc"); printf("%s\n", buffer); bad_jump(); printf("returned from bad_jump.\n"); free(buffer); return 0; }
588909.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__pair_int32 // A.*B function (eWiseMult): GB_AemultB__pair_int32 // A*D function (colscale): GB_AxD__pair_int32 // D*A function (rowscale): GB_DxB__pair_int32 // C+=A function (dense accum): GB_Cdense_accumA__pair_int32 // C+=x function (dense accum): GB_Cdense_accumX__pair_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pair_int32 // C type: int32_t // A type: int32_t // B type: int32_t // BinaryOp: cij = 1 #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) cij = Ax [pA] ; // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) cij = Bx [pB] ; #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = 1 ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_PAIR || GxB_NO_INT32 || GxB_NO_PAIR_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__pair_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += A, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumA__pair_int32 ( GrB_Matrix C, const GrB_Matrix A, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += x, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumX__pair_int32 ( GrB_Matrix C, const GB_void *p_ywork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { int32_t ywork = (*((int32_t *) p_ywork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__pair_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__pair_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__pair_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__pair_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } #endif
228640.c
/** ****************************************************************************** * @file usb_hcd_int.c * @author MCD Application Team * @version V2.1.0 * @date 19-March-2012 * @brief Host driver interrupt subroutines ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "usb_core.h" #include "usb_defines.h" #include "usb_hcd_int.h" #if defined (__CC_ARM) /*!< ARM Compiler */ #pragma O0 #elif defined (__GNUC__) /*!< GNU Compiler */ #pragma GCC optimize ("O0") #elif defined (__TASKING__) /*!< TASKING Compiler */ #pragma optimize=0 #endif /* __CC_ARM */ /** @addtogroup USB_OTG_DRIVER * @{ */ /** @defgroup USB_HCD_INT * @brief This file contains the interrupt subroutines for the Host mode. * @{ */ /** @defgroup USB_HCD_INT_Private_Defines * @{ */ /** * @} */ /** @defgroup USB_HCD_INT_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup USB_HCD_INT_Private_Macros * @{ */ /** * @} */ /** @defgroup USB_HCD_INT_Private_Variables * @{ */ /** * @} */ /** @defgroup USB_HCD_INT_Private_FunctionPrototypes * @{ */ static uint32_t USB_OTG_USBH_handle_sof_ISR(USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_port_ISR(USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_hc_ISR (USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_hc_n_In_ISR (USB_OTG_CORE_HANDLE *pdev , uint32_t num); static uint32_t USB_OTG_USBH_handle_hc_n_Out_ISR (USB_OTG_CORE_HANDLE *pdev , uint32_t num); static uint32_t USB_OTG_USBH_handle_rx_qlvl_ISR (USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_nptxfempty_ISR (USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_ptxfempty_ISR (USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_Disconnect_ISR (USB_OTG_CORE_HANDLE *pdev); static uint32_t USB_OTG_USBH_handle_IncompletePeriodicXfer_ISR (USB_OTG_CORE_HANDLE *pdev); /** * @} */ /** @defgroup USB_HCD_INT_Private_Functions * @{ */ /** * @brief HOST_Handle_ISR * This function handles all USB Host Interrupts * @param pdev: Selected device * @retval status */ uint32_t USBH_OTG_ISR_Handler (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTSTS_TypeDef gintsts; uint32_t retval = 0; gintsts.d32 = 0; /* Check if HOST Mode */ if (USB_OTG_IsHostMode(pdev)) { gintsts.d32 = USB_OTG_ReadCoreItr(pdev); if (!gintsts.d32) { return 0; } if (gintsts.b.sofintr) { retval |= USB_OTG_USBH_handle_sof_ISR (pdev); } if (gintsts.b.rxstsqlvl) { retval |= USB_OTG_USBH_handle_rx_qlvl_ISR (pdev); } if (gintsts.b.nptxfempty) { retval |= USB_OTG_USBH_handle_nptxfempty_ISR (pdev); } if (gintsts.b.ptxfempty) { retval |= USB_OTG_USBH_handle_ptxfempty_ISR (pdev); } if (gintsts.b.hcintr) { retval |= USB_OTG_USBH_handle_hc_ISR (pdev); } if (gintsts.b.portintr) { retval |= USB_OTG_USBH_handle_port_ISR (pdev); } if (gintsts.b.disconnect) { retval |= USB_OTG_USBH_handle_Disconnect_ISR (pdev); } if (gintsts.b.incomplisoout) { retval |= USB_OTG_USBH_handle_IncompletePeriodicXfer_ISR (pdev); } } return retval; } /** * @brief USB_OTG_USBH_handle_hc_ISR * This function indicates that one or more host channels has a pending * @param pdev: Selected device * @retval status */ static uint32_t USB_OTG_USBH_handle_hc_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_HAINT_TypeDef haint; USB_OTG_HCCHAR_TypeDef hcchar; uint32_t i = 0; uint32_t retval = 0; /* Clear appropriate bits in HCINTn to clear the interrupt bit in * GINTSTS */ haint.d32 = USB_OTG_ReadHostAllChannels_intr(pdev); for (i = 0; i < pdev->cfg.host_channels ; i++) { if (haint.b.chint & (1 << i)) { hcchar.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[i]->HCCHAR); if (hcchar.b.epdir) { retval |= USB_OTG_USBH_handle_hc_n_In_ISR (pdev, i); } else { retval |= USB_OTG_USBH_handle_hc_n_Out_ISR (pdev, i); } } } return retval; } /** * @brief USB_OTG_otg_hcd_handle_sof_intr * Handles the start-of-frame interrupt in host mode. * @param pdev: Selected device * @retval status */ static uint32_t USB_OTG_USBH_handle_sof_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTSTS_TypeDef gintsts; gintsts.d32 = 0; USBH_HCD_INT_fops->SOF(pdev); /* Clear interrupt */ gintsts.b.sofintr = 1; USB_OTG_WRITE_REG32(&pdev->regs.GREGS->GINTSTS, gintsts.d32); return 1; } /** * @brief USB_OTG_USBH_handle_Disconnect_ISR * Handles disconnect event. * @param pdev: Selected device * @retval status */ static uint32_t USB_OTG_USBH_handle_Disconnect_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTSTS_TypeDef gintsts; gintsts.d32 = 0; USBH_HCD_INT_fops->DevDisconnected(pdev); /* Clear interrupt */ gintsts.b.disconnect = 1; USB_OTG_WRITE_REG32(&pdev->regs.GREGS->GINTSTS, gintsts.d32); return 1; } #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ /** * @brief USB_OTG_USBH_handle_nptxfempty_ISR * Handles non periodic tx fifo empty. * @param pdev: Selected device * @retval status */ static uint32_t USB_OTG_USBH_handle_nptxfempty_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTMSK_TypeDef intmsk; USB_OTG_HNPTXSTS_TypeDef hnptxsts; uint16_t len_words , len; hnptxsts.d32 = USB_OTG_READ_REG32(&pdev->regs.GREGS->HNPTXSTS); len_words = (pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len + 3) / 4; while ((hnptxsts.b.nptxfspcavail > len_words)&& (pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len != 0)) { len = hnptxsts.b.nptxfspcavail * 4; if (len > pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len) { /* Last packet */ len = pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len; intmsk.d32 = 0; intmsk.b.nptxfempty = 1; USB_OTG_MODIFY_REG32( &pdev->regs.GREGS->GINTMSK, intmsk.d32, 0); } len_words = (pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len + 3) / 4; USB_OTG_WritePacket (pdev , pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_buff, hnptxsts.b.nptxqtop.chnum, len); pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_buff += len; pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_len -= len; pdev->host.hc[hnptxsts.b.nptxqtop.chnum].xfer_count += len; hnptxsts.d32 = USB_OTG_READ_REG32(&pdev->regs.GREGS->HNPTXSTS); } return 1; } #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ /** * @brief USB_OTG_USBH_handle_ptxfempty_ISR * Handles periodic tx fifo empty * @param pdev: Selected device * @retval status */ static uint32_t USB_OTG_USBH_handle_ptxfempty_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTMSK_TypeDef intmsk; USB_OTG_HPTXSTS_TypeDef hptxsts; uint16_t len_words , len; hptxsts.d32 = USB_OTG_READ_REG32(&pdev->regs.HREGS->HPTXSTS); len_words = (pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len + 3) / 4; while ((hptxsts.b.ptxfspcavail > len_words)&& (pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len != 0)) { len = hptxsts.b.ptxfspcavail * 4; if (len > pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len) { len = pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len; /* Last packet */ intmsk.d32 = 0; intmsk.b.ptxfempty = 1; USB_OTG_MODIFY_REG32( &pdev->regs.GREGS->GINTMSK, intmsk.d32, 0); } len_words = (pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len + 3) / 4; USB_OTG_WritePacket (pdev , pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_buff, hptxsts.b.ptxqtop.chnum, len); pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_buff += len; pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_len -= len; pdev->host.hc[hptxsts.b.ptxqtop.chnum].xfer_count += len; hptxsts.d32 = USB_OTG_READ_REG32(&pdev->regs.HREGS->HPTXSTS); } return 1; } /** * @brief USB_OTG_USBH_handle_port_ISR * This function determines which interrupt conditions have occurred * @param pdev: Selected device * @retval status */ #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ static uint32_t USB_OTG_USBH_handle_port_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_HPRT0_TypeDef hprt0; USB_OTG_HPRT0_TypeDef hprt0_dup; USB_OTG_HCFG_TypeDef hcfg; uint32_t do_reset = 0; uint32_t retval = 0; hcfg.d32 = 0; hprt0.d32 = 0; hprt0_dup.d32 = 0; hprt0.d32 = USB_OTG_READ_REG32(pdev->regs.HPRT0); hprt0_dup.d32 = USB_OTG_READ_REG32(pdev->regs.HPRT0); /* Clear the interrupt bits in GINTSTS */ hprt0_dup.b.prtena = 0; hprt0_dup.b.prtconndet = 0; hprt0_dup.b.prtenchng = 0; hprt0_dup.b.prtovrcurrchng = 0; /* Port Connect Detected */ if (hprt0.b.prtconndet) { hprt0_dup.b.prtconndet = 1; USBH_HCD_INT_fops->DevConnected(pdev); retval |= 1; } /* Port Enable Changed */ if (hprt0.b.prtenchng) { hprt0_dup.b.prtenchng = 1; if (hprt0.b.prtena == 1) { USBH_HCD_INT_fops->DevConnected(pdev); if ((hprt0.b.prtspd == HPRT0_PRTSPD_LOW_SPEED) || (hprt0.b.prtspd == HPRT0_PRTSPD_FULL_SPEED)) { hcfg.d32 = USB_OTG_READ_REG32(&pdev->regs.HREGS->HCFG); if (hprt0.b.prtspd == HPRT0_PRTSPD_LOW_SPEED) { USB_OTG_WRITE_REG32(&pdev->regs.HREGS->HFIR, 6000 ); if (hcfg.b.fslspclksel != HCFG_6_MHZ) { if(pdev->cfg.phy_itface == USB_OTG_EMBEDDED_PHY) { USB_OTG_InitFSLSPClkSel(pdev ,HCFG_6_MHZ ); } do_reset = 1; } } else { USB_OTG_WRITE_REG32(&pdev->regs.HREGS->HFIR, 48000 ); if (hcfg.b.fslspclksel != HCFG_48_MHZ) { USB_OTG_InitFSLSPClkSel(pdev ,HCFG_48_MHZ ); do_reset = 1; } } } else { do_reset = 1; } } } /* Overcurrent Change Interrupt */ if (hprt0.b.prtovrcurrchng) { hprt0_dup.b.prtovrcurrchng = 1; retval |= 1; } if (do_reset) { USB_OTG_ResetPort(pdev); } /* Clear Port Interrupts */ USB_OTG_WRITE_REG32(pdev->regs.HPRT0, hprt0_dup.d32); return retval; } #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ /** * @brief USB_OTG_USBH_handle_hc_n_Out_ISR * Handles interrupt for a specific Host Channel * @param pdev: Selected device * @param hc_num: Channel number * @retval status */ uint32_t USB_OTG_USBH_handle_hc_n_Out_ISR (USB_OTG_CORE_HANDLE *pdev , uint32_t num) { USB_OTG_HCINTn_TypeDef hcint; USB_OTG_HCINTMSK_TypeDef hcintmsk; USB_OTG_HC_REGS *hcreg; USB_OTG_HCCHAR_TypeDef hcchar; hcreg = pdev->regs.HC_REGS[num]; hcint.d32 = USB_OTG_READ_REG32(&hcreg->HCINT); hcintmsk.d32 = USB_OTG_READ_REG32(&hcreg->HCINTMSK); hcint.d32 = hcint.d32 & hcintmsk.d32; hcchar.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[num]->HCCHAR); if (hcint.b.ahberr) { CLEAR_HC_INT(hcreg ,ahberr); UNMASK_HOST_INT_CHH (num); } else if (hcint.b.ack) { CLEAR_HC_INT(hcreg , ack); } else if (hcint.b.frmovrun) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg ,frmovrun); } else if (hcint.b.xfercompl) { pdev->host.ErrCnt[num] = 0; UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , xfercompl); pdev->host.HC_Status[num] = HC_XFRC; } else if (hcint.b.stall) { CLEAR_HC_INT(hcreg , stall); UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); pdev->host.HC_Status[num] = HC_STALL; } else if (hcint.b.nak) { pdev->host.ErrCnt[num] = 0; UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , nak); pdev->host.HC_Status[num] = HC_NAK; } else if (hcint.b.xacterr) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); pdev->host.ErrCnt[num] ++; pdev->host.HC_Status[num] = HC_XACTERR; CLEAR_HC_INT(hcreg , xacterr); } else if (hcint.b.nyet) { pdev->host.ErrCnt[num] = 0; UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , nyet); pdev->host.HC_Status[num] = HC_NYET; } else if (hcint.b.datatglerr) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , nak); pdev->host.HC_Status[num] = HC_DATATGLERR; CLEAR_HC_INT(hcreg , datatglerr); } else if (hcint.b.chhltd) { MASK_HOST_INT_CHH (num); if(pdev->host.HC_Status[num] == HC_XFRC) { pdev->host.URB_State[num] = URB_DONE; if (hcchar.b.eptype == EP_TYPE_BULK) { pdev->host.hc[num].toggle_out ^= 1; } } else if(pdev->host.HC_Status[num] == HC_NAK) { pdev->host.URB_State[num] = URB_NOTREADY; } else if(pdev->host.HC_Status[num] == HC_NYET) { if(pdev->host.hc[num].do_ping == 1) { USB_OTG_HC_DoPing(pdev, num); } pdev->host.URB_State[num] = URB_NOTREADY; } else if(pdev->host.HC_Status[num] == HC_STALL) { pdev->host.URB_State[num] = URB_STALL; } else if(pdev->host.HC_Status[num] == HC_XACTERR) { if (pdev->host.ErrCnt[num] == 3) { pdev->host.URB_State[num] = URB_ERROR; pdev->host.ErrCnt[num] = 0; } } CLEAR_HC_INT(hcreg , chhltd); } return 1; } #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ /** * @brief USB_OTG_USBH_handle_hc_n_In_ISR * Handles interrupt for a specific Host Channel * @param pdev: Selected device * @param hc_num: Channel number * @retval status */ uint32_t USB_OTG_USBH_handle_hc_n_In_ISR (USB_OTG_CORE_HANDLE *pdev , uint32_t num) { USB_OTG_HCINTn_TypeDef hcint; USB_OTG_HCINTMSK_TypeDef hcintmsk; USB_OTG_HCCHAR_TypeDef hcchar; USB_OTG_HCTSIZn_TypeDef hctsiz; USB_OTG_HC_REGS *hcreg; hcreg = pdev->regs.HC_REGS[num]; hcint.d32 = USB_OTG_READ_REG32(&hcreg->HCINT); hcintmsk.d32 = USB_OTG_READ_REG32(&hcreg->HCINTMSK); hcint.d32 = hcint.d32 & hcintmsk.d32; hcchar.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[num]->HCCHAR); hcintmsk.d32 = 0; if (hcint.b.ahberr) { CLEAR_HC_INT(hcreg ,ahberr); UNMASK_HOST_INT_CHH (num); } else if (hcint.b.ack) { CLEAR_HC_INT(hcreg ,ack); } else if (hcint.b.stall) { UNMASK_HOST_INT_CHH (num); pdev->host.HC_Status[num] = HC_STALL; CLEAR_HC_INT(hcreg , nak); /* Clear the NAK Condition */ CLEAR_HC_INT(hcreg , stall); /* Clear the STALL Condition */ hcint.b.nak = 0; /* NOTE: When there is a 'stall', reset also nak, else, the pdev->host.HC_Status = HC_STALL will be overwritten by 'nak' in code below */ USB_OTG_HC_Halt(pdev, num); } else if (hcint.b.datatglerr) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , nak); pdev->host.HC_Status[num] = HC_DATATGLERR; CLEAR_HC_INT(hcreg , datatglerr); } if (hcint.b.frmovrun) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg ,frmovrun); } else if (hcint.b.xfercompl) { if (pdev->cfg.dma_enable == 1) { hctsiz.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[num]->HCTSIZ); pdev->host.XferCnt[num] = pdev->host.hc[num].xfer_len - hctsiz.b.xfersize; } pdev->host.HC_Status[num] = HC_XFRC; pdev->host.ErrCnt [num]= 0; CLEAR_HC_INT(hcreg , xfercompl); if ((hcchar.b.eptype == EP_TYPE_CTRL)|| (hcchar.b.eptype == EP_TYPE_BULK)) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , nak); pdev->host.hc[num].toggle_in ^= 1; } else if(hcchar.b.eptype == EP_TYPE_INTR) { hcchar.b.oddfrm = 1; USB_OTG_WRITE_REG32(&pdev->regs.HC_REGS[num]->HCCHAR, hcchar.d32); pdev->host.URB_State[num] = URB_DONE; } } else if (hcint.b.chhltd) { MASK_HOST_INT_CHH (num); if(pdev->host.HC_Status[num] == HC_XFRC) { pdev->host.URB_State[num] = URB_DONE; } else if (pdev->host.HC_Status[num] == HC_STALL) { pdev->host.URB_State[num] = URB_STALL; } else if((pdev->host.HC_Status[num] == HC_XACTERR) || (pdev->host.HC_Status[num] == HC_DATATGLERR)) { pdev->host.ErrCnt[num] = 0; pdev->host.URB_State[num] = URB_ERROR; } else if(hcchar.b.eptype == EP_TYPE_INTR) { pdev->host.hc[num].toggle_in ^= 1; } CLEAR_HC_INT(hcreg , chhltd); } else if (hcint.b.xacterr) { UNMASK_HOST_INT_CHH (num); pdev->host.ErrCnt[num] ++; pdev->host.HC_Status[num] = HC_XACTERR; USB_OTG_HC_Halt(pdev, num); CLEAR_HC_INT(hcreg , xacterr); } else if (hcint.b.nak) { if(hcchar.b.eptype == EP_TYPE_INTR) { UNMASK_HOST_INT_CHH (num); USB_OTG_HC_Halt(pdev, num); } else if ((hcchar.b.eptype == EP_TYPE_CTRL)|| (hcchar.b.eptype == EP_TYPE_BULK)) { /* re-activate the channel */ hcchar.b.chen = 1; hcchar.b.chdis = 0; USB_OTG_WRITE_REG32(&pdev->regs.HC_REGS[num]->HCCHAR, hcchar.d32); } pdev->host.HC_Status[num] = HC_NAK; CLEAR_HC_INT(hcreg , nak); } return 1; } /** * @brief USB_OTG_USBH_handle_rx_qlvl_ISR * Handles the Rx Status Queue Level Interrupt * @param pdev: Selected device * @retval status */ #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ static uint32_t USB_OTG_USBH_handle_rx_qlvl_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GRXFSTS_TypeDef grxsts; USB_OTG_GINTMSK_TypeDef intmsk; USB_OTG_HCTSIZn_TypeDef hctsiz; USB_OTG_HCCHAR_TypeDef hcchar; __IO uint8_t channelnum =0; uint32_t count; /* Disable the Rx Status Queue Level interrupt */ intmsk.d32 = 0; intmsk.b.rxstsqlvl = 1; USB_OTG_MODIFY_REG32( &pdev->regs.GREGS->GINTMSK, intmsk.d32, 0); grxsts.d32 = USB_OTG_READ_REG32(&pdev->regs.GREGS->GRXSTSP); channelnum = grxsts.b.chnum; hcchar.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[channelnum]->HCCHAR); switch (grxsts.b.pktsts) { case GRXSTS_PKTSTS_IN: /* Read the data into the host buffer. */ if ((grxsts.b.bcnt > 0) && (pdev->host.hc[channelnum].xfer_buff != (void *)0)) { USB_OTG_ReadPacket(pdev, pdev->host.hc[channelnum].xfer_buff, grxsts.b.bcnt); /*manage multiple Xfer */ pdev->host.hc[grxsts.b.chnum].xfer_buff += grxsts.b.bcnt; pdev->host.hc[grxsts.b.chnum].xfer_count += grxsts.b.bcnt; count = pdev->host.hc[channelnum].xfer_count; pdev->host.XferCnt[channelnum] = count; hctsiz.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[channelnum]->HCTSIZ); if(hctsiz.b.pktcnt > 0) { /* re-activate the channel when more packets are expected */ hcchar.b.chen = 1; hcchar.b.chdis = 0; USB_OTG_WRITE_REG32(&pdev->regs.HC_REGS[channelnum]->HCCHAR, hcchar.d32); } } break; case GRXSTS_PKTSTS_IN_XFER_COMP: case GRXSTS_PKTSTS_DATA_TOGGLE_ERR: case GRXSTS_PKTSTS_CH_HALTED: default: break; } /* Enable the Rx Status Queue Level interrupt */ intmsk.b.rxstsqlvl = 1; USB_OTG_MODIFY_REG32(&pdev->regs.GREGS->GINTMSK, 0, intmsk.d32); return 1; } /** * @brief USB_OTG_USBH_handle_IncompletePeriodicXfer_ISR * Handles the incomplete Periodic transfer Interrupt * @param pdev: Selected device * @retval status */ #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma optimize = none #endif /* __CC_ARM */ static uint32_t USB_OTG_USBH_handle_IncompletePeriodicXfer_ISR (USB_OTG_CORE_HANDLE *pdev) { USB_OTG_GINTSTS_TypeDef gintsts; USB_OTG_HCCHAR_TypeDef hcchar; hcchar.d32 = USB_OTG_READ_REG32(&pdev->regs.HC_REGS[0]->HCCHAR); hcchar.b.chen = 1; hcchar.b.chdis = 1; USB_OTG_WRITE_REG32(&pdev->regs.HC_REGS[0]->HCCHAR, hcchar.d32); gintsts.d32 = 0; /* Clear interrupt */ gintsts.b.incomplisoout = 1; USB_OTG_WRITE_REG32(&pdev->regs.GREGS->GINTSTS, gintsts.d32); return 1; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
8761.c
/* * Program from Example 1 of * 2014TACAS - Leike, Heizmann - Ranking Templates for Linear Loops * * Date: 2014-06-29 * Author: Jan Leike */ typedef enum {false, true} bool; extern int __VERIFIER_nondet_int(void); int main() { int q, y; q = __VERIFIER_nondet_int(); y = __VERIFIER_nondet_int(); while (q > 0) { if (y > 0) { q = q - y - 1; } else { q = q + y - 1; } } return 0; }
767319.c
#include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); __visible struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; MODULE_INFO(intree, "Y"); static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends=vfio"; MODULE_INFO(srcversion, "FED0C42FA1B02B78175ED80");
181121.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" volatile uint32_t t0 = 8770111U; int64_t x18 = 4917730608639671LL; static int64_t t1 = -4LL; int8_t x23 = 43; int64_t x32 = 175287763316729754LL; uint8_t x37 = UINT8_MAX; static int64_t x39 = INT64_MAX; int16_t x44 = INT16_MAX; uint64_t x70 = 88374698782LLU; uint8_t x76 = 0U; int32_t t9 = -41896842; int32_t t10 = -86838399; uint16_t x85 = UINT16_MAX; volatile int16_t x87 = -1; static uint64_t x97 = 204200114LLU; uint16_t x126 = 666U; volatile uint16_t x128 = 7U; uint32_t t13 = 901440U; int64_t x143 = 3448893111047LL; uint8_t x144 = 0U; static int64_t x151 = -1LL; int64_t x162 = -14539432191929592LL; uint16_t x182 = 14U; int32_t x183 = INT32_MIN; int8_t x207 = INT8_MIN; uint8_t x213 = 29U; uint64_t x222 = 834251514604LLU; uint64_t t26 = UINT64_MAX; uint8_t x251 = 119U; volatile int8_t x252 = 54; uint64_t t27 = 11322473765944LLU; volatile int8_t x263 = INT8_MIN; int64_t t29 = 171891747084139LL; int8_t x267 = INT8_MIN; int64_t x292 = -230910399904727674LL; static int64_t x308 = INT64_MIN; volatile int32_t t35 = 870; static uint64_t x317 = 8LLU; int16_t x323 = INT16_MAX; volatile uint32_t x330 = 10U; volatile int16_t x338 = INT16_MIN; uint16_t x360 = 1575U; volatile uint64_t t41 = 15339518036178LLU; int16_t x362 = INT16_MIN; int8_t x379 = INT8_MIN; static int32_t x385 = 58961; static uint64_t x416 = UINT64_MAX; uint32_t x421 = 247204U; int16_t x424 = INT16_MIN; static int16_t x451 = -1960; int8_t x452 = -7; volatile int16_t x478 = -1; volatile uint64_t t54 = 844923728582LLU; static uint64_t x493 = 2689615854LLU; volatile uint32_t x497 = 3U; uint8_t x501 = 23U; static int32_t t57 = 0; uint8_t x522 = 29U; uint64_t x541 = 50001705LLU; int32_t x544 = INT32_MIN; volatile uint32_t x545 = UINT32_MAX; volatile int16_t x546 = -1; volatile uint32_t x570 = UINT32_MAX; int16_t x571 = -1; static uint32_t t64 = 132739944U; uint64_t x574 = 39161129783254358LLU; uint8_t x616 = 0U; int8_t x651 = -63; volatile uint32_t t70 = 4U; uint8_t x678 = 2U; volatile int32_t x687 = INT32_MIN; uint64_t t73 = 291469LLU; uint16_t x701 = 12948U; int64_t x746 = -1LL; int16_t x769 = -1; volatile int8_t x797 = INT8_MIN; uint64_t x805 = UINT64_MAX; volatile int64_t x806 = INT64_MAX; volatile uint8_t x823 = 1U; uint16_t x829 = 21U; uint32_t x845 = 6U; int8_t x848 = INT8_MIN; uint16_t x853 = UINT16_MAX; uint64_t x860 = UINT64_MAX; uint32_t x889 = 265205632U; static uint32_t x900 = 133804282U; int32_t x924 = 314419; uint32_t t95 = 83413632U; int8_t x933 = 0; int8_t x935 = 2; static uint32_t t96 = 31734921U; int32_t x949 = 2; int8_t x953 = INT8_MIN; int32_t x971 = 43765892; static int32_t x988 = -1; volatile uint32_t x1002 = UINT32_MAX; uint64_t x1037 = UINT64_MAX; int64_t x1039 = -575759130519781LL; static uint8_t x1069 = UINT8_MAX; int16_t x1071 = INT16_MIN; volatile int8_t x1072 = INT8_MAX; uint64_t x1078 = UINT64_MAX; int8_t x1111 = -1; volatile uint32_t t112 = 240300U; static int32_t x1113 = INT32_MIN; int32_t x1116 = INT32_MIN; uint64_t t114 = 1412726036560677LLU; int32_t x1143 = INT32_MIN; int32_t t118 = 342503; uint16_t x1150 = UINT16_MAX; static int64_t x1163 = -14661021806LL; volatile int32_t t122 = -37; uint16_t x1212 = 3552U; volatile uint64_t t124 = 225941LLU; uint64_t x1234 = 6392075LLU; int8_t x1238 = 0; uint32_t x1240 = 939649657U; volatile uint32_t t126 = 1790176U; uint64_t x1250 = UINT64_MAX; uint16_t x1266 = 377U; uint16_t x1267 = 14481U; int16_t x1286 = 1; uint8_t x1288 = UINT8_MAX; uint64_t x1289 = 1505LLU; volatile int16_t x1312 = INT16_MIN; uint16_t x1315 = UINT16_MAX; volatile int16_t x1316 = INT16_MAX; static int16_t x1321 = INT16_MIN; int16_t x1324 = INT16_MAX; uint64_t t136 = 19456041745722032LLU; uint16_t x1329 = 1U; int64_t x1339 = -66432835776LL; volatile int8_t x1355 = INT8_MIN; volatile uint32_t x1361 = UINT32_MAX; uint16_t x1362 = 0U; volatile int8_t x1368 = -1; uint64_t x1374 = UINT64_MAX; static int16_t x1383 = 0; volatile uint64_t t145 = 3995956581053LLU; volatile uint32_t x1390 = UINT32_MAX; uint64_t x1397 = 100746264531748063LLU; uint8_t x1415 = 0U; static int32_t x1417 = -1; int16_t x1419 = -18; uint64_t x1441 = UINT64_MAX; volatile uint8_t x1468 = 1U; int8_t x1482 = INT8_MAX; volatile int32_t t153 = 499704; int16_t x1500 = 1; volatile int32_t t154 = -2890; uint64_t x1507 = 561900125537442LLU; int16_t x1513 = -1; int16_t x1515 = INT16_MAX; uint32_t x1526 = 47198U; volatile int64_t x1555 = INT64_MIN; volatile uint64_t t159 = 5920541881LLU; int32_t x1557 = INT32_MIN; uint64_t t161 = 51LLU; int64_t x1587 = INT64_MIN; static int32_t x1627 = -1; volatile uint32_t t167 = 248U; static volatile uint64_t t168 = 42138795LLU; static uint8_t x1642 = 0U; uint16_t x1648 = 0U; static volatile uint64_t x1663 = 1188888LLU; uint64_t t171 = UINT64_MAX; uint64_t x1672 = UINT64_MAX; int32_t x1686 = -1; int8_t x1688 = 1; static volatile uint64_t t174 = 129632693500LLU; uint64_t x1693 = 30332080933684642LLU; static uint8_t x1698 = 0U; int8_t x1699 = INT8_MAX; volatile uint64_t t177 = UINT64_MAX; volatile int8_t x1719 = -1; uint64_t x1741 = 374514LLU; int32_t x1742 = -498906866; volatile uint32_t x1744 = UINT32_MAX; volatile uint16_t x1752 = 2U; volatile uint64_t x1777 = 19481925892970974LLU; int64_t x1788 = 695578LL; uint16_t x1801 = 1U; volatile int16_t x1804 = 163; volatile int16_t x1808 = 1; uint8_t x1809 = UINT8_MAX; int16_t x1810 = 8; int8_t x1811 = 1; volatile int32_t t188 = -148781233; static volatile uint32_t x1817 = UINT32_MAX; int32_t x1840 = INT32_MAX; static int32_t x1871 = INT32_MIN; static uint64_t x1881 = UINT64_MAX; volatile int16_t x1883 = -1; static int16_t x1934 = INT16_MAX; static uint8_t x1936 = 92U; static volatile uint32_t t199 = 600854836U; void f0(void) { static uint32_t x1 = 172805700U; int16_t x2 = -1; int16_t x3 = INT16_MAX; int32_t x4 = -1; t0 = ((x1|x2)<<(x3>x4)); if (t0 != 4294967294U) { NG(); } else { ; } } void f1(void) { static int16_t x17 = 192; int64_t x19 = INT64_MIN; static int8_t x20 = INT8_MAX; t1 = ((x17|x18)<<(x19>x20)); if (t1 != 4917730608639735LL) { NG(); } else { ; } } void f2(void) { static uint16_t x21 = 45U; uint32_t x22 = 248068240U; volatile uint32_t x24 = 1242517409U; volatile uint32_t t2 = 146278U; t2 = ((x21|x22)<<(x23>x24)); if (t2 != 248068285U) { NG(); } else { ; } } void f3(void) { int16_t x25 = INT16_MAX; uint32_t x26 = 105231892U; volatile int32_t x27 = INT32_MAX; int16_t x28 = INT16_MIN; volatile uint32_t t3 = 20U; t3 = ((x25|x26)<<(x27>x28)); if (t3 != 210501630U) { NG(); } else { ; } } void f4(void) { int64_t x29 = 0LL; static int16_t x30 = 1; int32_t x31 = -1; static int64_t t4 = -12015771LL; t4 = ((x29|x30)<<(x31>x32)); if (t4 != 1LL) { NG(); } else { ; } } void f5(void) { uint32_t x38 = 1001U; static int32_t x40 = -1; static uint32_t t5 = 114236U; t5 = ((x37|x38)<<(x39>x40)); if (t5 != 2046U) { NG(); } else { ; } } void f6(void) { uint32_t x41 = 43U; uint8_t x42 = 0U; uint16_t x43 = 239U; uint32_t t6 = 1U; t6 = ((x41|x42)<<(x43>x44)); if (t6 != 43U) { NG(); } else { ; } } void f7(void) { uint64_t x61 = 6668LLU; int8_t x62 = INT8_MIN; int64_t x63 = INT64_MIN; uint16_t x64 = 7U; volatile uint64_t t7 = 15172112697249LLU; t7 = ((x61|x62)<<(x63>x64)); if (t7 != 18446744073709551500LLU) { NG(); } else { ; } } void f8(void) { static int32_t x69 = INT32_MIN; int8_t x71 = INT8_MIN; volatile int16_t x72 = INT16_MAX; uint64_t t8 = 92582133830LLU; t8 = ((x69|x70)<<(x71>x72)); if (t8 != 18446744071889937182LLU) { NG(); } else { ; } } void f9(void) { int32_t x73 = 24842; static uint8_t x74 = 10U; static uint8_t x75 = UINT8_MAX; t9 = ((x73|x74)<<(x75>x76)); if (t9 != 49684) { NG(); } else { ; } } void f10(void) { uint16_t x81 = UINT16_MAX; int16_t x82 = INT16_MAX; volatile uint64_t x83 = 0LLU; int16_t x84 = INT16_MIN; t10 = ((x81|x82)<<(x83>x84)); if (t10 != 65535) { NG(); } else { ; } } void f11(void) { static uint64_t x86 = 2005380462594824LLU; uint8_t x88 = UINT8_MAX; static uint64_t t11 = 100LLU; t11 = ((x85|x86)<<(x87>x88)); if (t11 != 2005380462608383LLU) { NG(); } else { ; } } void f12(void) { uint8_t x98 = UINT8_MAX; int32_t x99 = -1; int64_t x100 = -1LL; static uint64_t t12 = 59490LLU; t12 = ((x97|x98)<<(x99>x100)); if (t12 != 204200191LLU) { NG(); } else { ; } } void f13(void) { uint32_t x125 = 357328316U; int64_t x127 = INT64_MAX; t13 = ((x125|x126)<<(x127>x128)); if (t13 != 714657660U) { NG(); } else { ; } } void f14(void) { int64_t x129 = INT64_MAX; volatile int64_t x130 = 0LL; uint16_t x131 = 16212U; int64_t x132 = 104091803LL; int64_t t14 = INT64_MAX; t14 = ((x129|x130)<<(x131>x132)); if (t14 != INT64_MAX) { NG(); } else { ; } } void f15(void) { static volatile uint32_t x133 = UINT32_MAX; uint32_t x134 = 6U; uint8_t x135 = 23U; int64_t x136 = -126267LL; volatile uint32_t t15 = 309044U; t15 = ((x133|x134)<<(x135>x136)); if (t15 != 4294967294U) { NG(); } else { ; } } void f16(void) { uint32_t x141 = 12U; static volatile int16_t x142 = -1; volatile uint32_t t16 = 84U; t16 = ((x141|x142)<<(x143>x144)); if (t16 != 4294967294U) { NG(); } else { ; } } void f17(void) { uint16_t x149 = 19519U; int16_t x150 = 12090; int8_t x152 = -8; volatile int32_t t17 = 61931; t17 = ((x149|x150)<<(x151>x152)); if (t17 != 56958) { NG(); } else { ; } } void f18(void) { uint64_t x153 = UINT64_MAX; volatile int16_t x154 = INT16_MIN; int64_t x155 = 2729LL; uint64_t x156 = UINT64_MAX; uint64_t t18 = UINT64_MAX; t18 = ((x153|x154)<<(x155>x156)); if (t18 != UINT64_MAX) { NG(); } else { ; } } void f19(void) { uint64_t x161 = 18824LLU; int32_t x163 = INT32_MIN; int16_t x164 = INT16_MAX; uint64_t t19 = 236468342286637LLU; t19 = ((x161|x162)<<(x163>x164)); if (t19 != 18432204641517624200LLU) { NG(); } else { ; } } void f20(void) { uint8_t x181 = 1U; int64_t x184 = 389340LL; int32_t t20 = -129548882; t20 = ((x181|x182)<<(x183>x184)); if (t20 != 15) { NG(); } else { ; } } void f21(void) { int8_t x205 = INT8_MAX; uint64_t x206 = 1057225067251006LLU; int8_t x208 = 1; uint64_t t21 = 1272322630LLU; t21 = ((x205|x206)<<(x207>x208)); if (t21 != 1057225067251071LLU) { NG(); } else { ; } } void f22(void) { int8_t x214 = 7; static uint64_t x215 = 15586LLU; int8_t x216 = INT8_MIN; int32_t t22 = 33248754; t22 = ((x213|x214)<<(x215>x216)); if (t22 != 31) { NG(); } else { ; } } void f23(void) { uint16_t x217 = 1819U; uint8_t x218 = UINT8_MAX; int16_t x219 = -1; static int8_t x220 = INT8_MIN; volatile int32_t t23 = -6; t23 = ((x217|x218)<<(x219>x220)); if (t23 != 4094) { NG(); } else { ; } } void f24(void) { uint32_t x221 = 121174U; static volatile int8_t x223 = INT8_MAX; int32_t x224 = INT32_MIN; volatile uint64_t t24 = 169LLU; t24 = ((x221|x222)<<(x223>x224)); if (t24 != 1668503042044LLU) { NG(); } else { ; } } void f25(void) { uint64_t x225 = UINT64_MAX; static uint8_t x226 = UINT8_MAX; static int64_t x227 = INT64_MAX; uint8_t x228 = 12U; uint64_t t25 = 27374025LLU; t25 = ((x225|x226)<<(x227>x228)); if (t25 != 18446744073709551614LLU) { NG(); } else { ; } } void f26(void) { int64_t x229 = INT64_MIN; uint64_t x230 = UINT64_MAX; volatile uint8_t x231 = UINT8_MAX; int32_t x232 = 3994; t26 = ((x229|x230)<<(x231>x232)); if (t26 != UINT64_MAX) { NG(); } else { ; } } void f27(void) { uint64_t x249 = 17571742663079938LLU; volatile int32_t x250 = 1; t27 = ((x249|x250)<<(x251>x252)); if (t27 != 35143485326159878LLU) { NG(); } else { ; } } void f28(void) { int8_t x257 = 0; uint8_t x258 = UINT8_MAX; int8_t x259 = INT8_MIN; uint64_t x260 = 383652878LLU; int32_t t28 = 21556750; t28 = ((x257|x258)<<(x259>x260)); if (t28 != 510) { NG(); } else { ; } } void f29(void) { int64_t x261 = 5607049076581LL; volatile int16_t x262 = INT16_MAX; uint16_t x264 = 0U; t29 = ((x261|x262)<<(x263>x264)); if (t29 != 5607049101311LL) { NG(); } else { ; } } void f30(void) { static uint32_t x265 = UINT32_MAX; int8_t x266 = -1; int64_t x268 = 6LL; volatile uint32_t t30 = UINT32_MAX; t30 = ((x265|x266)<<(x267>x268)); if (t30 != UINT32_MAX) { NG(); } else { ; } } void f31(void) { uint8_t x269 = 3U; uint64_t x270 = UINT64_MAX; static int8_t x271 = INT8_MIN; uint32_t x272 = UINT32_MAX; volatile uint64_t t31 = UINT64_MAX; t31 = ((x269|x270)<<(x271>x272)); if (t31 != UINT64_MAX) { NG(); } else { ; } } void f32(void) { uint64_t x289 = 155429LLU; volatile int32_t x290 = INT32_MAX; volatile int64_t x291 = INT64_MIN; volatile uint64_t t32 = 5768LLU; t32 = ((x289|x290)<<(x291>x292)); if (t32 != 2147483647LLU) { NG(); } else { ; } } void f33(void) { uint64_t x305 = UINT64_MAX; int64_t x306 = INT64_MIN; int32_t x307 = -2; volatile uint64_t t33 = 55551682065822957LLU; t33 = ((x305|x306)<<(x307>x308)); if (t33 != 18446744073709551614LLU) { NG(); } else { ; } } void f34(void) { int16_t x309 = INT16_MAX; volatile uint16_t x310 = 16277U; uint64_t x311 = 178119227LLU; volatile uint64_t x312 = UINT64_MAX; int32_t t34 = -256; t34 = ((x309|x310)<<(x311>x312)); if (t34 != 32767) { NG(); } else { ; } } void f35(void) { static int8_t x313 = INT8_MAX; uint16_t x314 = 1701U; uint16_t x315 = 2898U; volatile uint64_t x316 = 966998371438623109LLU; t35 = ((x313|x314)<<(x315>x316)); if (t35 != 1791) { NG(); } else { ; } } void f36(void) { int32_t x318 = -55530; static int8_t x319 = INT8_MIN; static uint64_t x320 = 3930582342106435255LLU; uint64_t t36 = 60374LLU; t36 = ((x317|x318)<<(x319>x320)); if (t36 != 18446744073709440572LLU) { NG(); } else { ; } } void f37(void) { static uint8_t x321 = 3U; uint16_t x322 = 1288U; int64_t x324 = INT64_MIN; static volatile int32_t t37 = 10940; t37 = ((x321|x322)<<(x323>x324)); if (t37 != 2582) { NG(); } else { ; } } void f38(void) { int8_t x329 = 3; int32_t x331 = 4435529; int64_t x332 = INT64_MAX; uint32_t t38 = 17782U; t38 = ((x329|x330)<<(x331>x332)); if (t38 != 11U) { NG(); } else { ; } } void f39(void) { uint32_t x337 = UINT32_MAX; int32_t x339 = INT32_MAX; uint8_t x340 = 52U; static uint32_t t39 = 13162647U; t39 = ((x337|x338)<<(x339>x340)); if (t39 != 4294967294U) { NG(); } else { ; } } void f40(void) { static uint32_t x353 = 1665U; int64_t x354 = 37829274909154LL; uint64_t x355 = 268731184248580LLU; volatile int32_t x356 = INT32_MIN; volatile int64_t t40 = -410966968423384LL; t40 = ((x353|x354)<<(x355>x356)); if (t40 != 37829274910691LL) { NG(); } else { ; } } void f41(void) { int32_t x357 = INT32_MIN; uint64_t x358 = UINT64_MAX; volatile uint32_t x359 = 865693U; t41 = ((x357|x358)<<(x359>x360)); if (t41 != 18446744073709551614LLU) { NG(); } else { ; } } void f42(void) { uint64_t x361 = UINT64_MAX; int32_t x363 = INT32_MIN; int16_t x364 = INT16_MIN; uint64_t t42 = UINT64_MAX; t42 = ((x361|x362)<<(x363>x364)); if (t42 != UINT64_MAX) { NG(); } else { ; } } void f43(void) { uint64_t x365 = 3065006126165LLU; static volatile int32_t x366 = -145572388; int64_t x367 = INT64_MIN; int8_t x368 = INT8_MIN; uint64_t t43 = 57403664389LLU; t43 = ((x365|x366)<<(x367>x368)); if (t43 != 18446744073572974045LLU) { NG(); } else { ; } } void f44(void) { volatile uint8_t x377 = 18U; int8_t x378 = 1; volatile int16_t x380 = 572; volatile int32_t t44 = -288207; t44 = ((x377|x378)<<(x379>x380)); if (t44 != 19) { NG(); } else { ; } } void f45(void) { uint16_t x386 = 217U; static int8_t x387 = INT8_MIN; static volatile int8_t x388 = INT8_MIN; static volatile int32_t t45 = 1764865; t45 = ((x385|x386)<<(x387>x388)); if (t45 != 59097) { NG(); } else { ; } } void f46(void) { int8_t x389 = 6; uint32_t x390 = UINT32_MAX; static int32_t x391 = -1; int64_t x392 = -113LL; static volatile uint32_t t46 = 7978U; t46 = ((x389|x390)<<(x391>x392)); if (t46 != 4294967294U) { NG(); } else { ; } } void f47(void) { static uint8_t x393 = 2U; volatile int16_t x394 = INT16_MAX; int32_t x395 = -1; static int8_t x396 = -1; volatile int32_t t47 = 24; t47 = ((x393|x394)<<(x395>x396)); if (t47 != 32767) { NG(); } else { ; } } void f48(void) { static uint32_t x397 = UINT32_MAX; uint16_t x398 = 4225U; int8_t x399 = -1; int32_t x400 = -29541557; uint32_t t48 = 298U; t48 = ((x397|x398)<<(x399>x400)); if (t48 != 4294967294U) { NG(); } else { ; } } void f49(void) { int8_t x413 = INT8_MAX; uint8_t x414 = 9U; static int32_t x415 = INT32_MIN; volatile int32_t t49 = -3212; t49 = ((x413|x414)<<(x415>x416)); if (t49 != 127) { NG(); } else { ; } } void f50(void) { static int8_t x422 = -1; uint64_t x423 = 182377632LLU; uint32_t t50 = UINT32_MAX; t50 = ((x421|x422)<<(x423>x424)); if (t50 != UINT32_MAX) { NG(); } else { ; } } void f51(void) { volatile int16_t x429 = 161; int64_t x430 = INT64_MAX; int16_t x431 = INT16_MIN; int64_t x432 = 3432320694108LL; volatile int64_t t51 = INT64_MAX; t51 = ((x429|x430)<<(x431>x432)); if (t51 != INT64_MAX) { NG(); } else { ; } } void f52(void) { static uint8_t x449 = UINT8_MAX; uint32_t x450 = 39U; uint32_t t52 = 32335U; t52 = ((x449|x450)<<(x451>x452)); if (t52 != 255U) { NG(); } else { ; } } void f53(void) { uint64_t x477 = 7787094392806LLU; int16_t x479 = -1; static uint32_t x480 = 250400U; volatile uint64_t t53 = 767933LLU; t53 = ((x477|x478)<<(x479>x480)); if (t53 != 18446744073709551614LLU) { NG(); } else { ; } } void f54(void) { uint64_t x489 = 117589448017369217LLU; int8_t x490 = -48; uint16_t x491 = 59U; uint16_t x492 = 32U; t54 = ((x489|x490)<<(x491>x492)); if (t54 != 18446744073709551522LLU) { NG(); } else { ; } } void f55(void) { static int16_t x494 = -1; int64_t x495 = INT64_MIN; int8_t x496 = INT8_MIN; volatile uint64_t t55 = UINT64_MAX; t55 = ((x493|x494)<<(x495>x496)); if (t55 != UINT64_MAX) { NG(); } else { ; } } void f56(void) { static int64_t x498 = INT64_MAX; static int8_t x499 = 0; uint8_t x500 = 1U; int64_t t56 = INT64_MAX; t56 = ((x497|x498)<<(x499>x500)); if (t56 != INT64_MAX) { NG(); } else { ; } } void f57(void) { uint16_t x502 = 1U; int64_t x503 = INT64_MAX; uint64_t x504 = 16847397501800012LLU; t57 = ((x501|x502)<<(x503>x504)); if (t57 != 46) { NG(); } else { ; } } void f58(void) { uint64_t x505 = UINT64_MAX; volatile uint16_t x506 = 5545U; uint32_t x507 = 4559068U; volatile int8_t x508 = INT8_MIN; volatile uint64_t t58 = UINT64_MAX; t58 = ((x505|x506)<<(x507>x508)); if (t58 != UINT64_MAX) { NG(); } else { ; } } void f59(void) { int8_t x521 = 1; uint8_t x523 = 1U; static int8_t x524 = INT8_MAX; int32_t t59 = -18820159; t59 = ((x521|x522)<<(x523>x524)); if (t59 != 29) { NG(); } else { ; } } void f60(void) { uint64_t x537 = UINT64_MAX; int32_t x538 = -50019778; static int32_t x539 = INT32_MIN; int64_t x540 = -1LL; static uint64_t t60 = UINT64_MAX; t60 = ((x537|x538)<<(x539>x540)); if (t60 != UINT64_MAX) { NG(); } else { ; } } void f61(void) { uint32_t x542 = 28844U; uint64_t x543 = 1058LLU; uint64_t t61 = 1954735LLU; t61 = ((x541|x542)<<(x543>x544)); if (t61 != 50001837LLU) { NG(); } else { ; } } void f62(void) { int8_t x547 = INT8_MIN; int16_t x548 = 1; uint32_t t62 = UINT32_MAX; t62 = ((x545|x546)<<(x547>x548)); if (t62 != UINT32_MAX) { NG(); } else { ; } } void f63(void) { volatile uint32_t x557 = 59U; static int32_t x558 = -1; uint32_t x559 = 103662518U; volatile uint16_t x560 = 1U; uint32_t t63 = 14878426U; t63 = ((x557|x558)<<(x559>x560)); if (t63 != 4294967294U) { NG(); } else { ; } } void f64(void) { static volatile int8_t x569 = -24; uint64_t x572 = 485860041088361972LLU; t64 = ((x569|x570)<<(x571>x572)); if (t64 != 4294967294U) { NG(); } else { ; } } void f65(void) { volatile int8_t x573 = -1; int16_t x575 = INT16_MIN; uint8_t x576 = 0U; uint64_t t65 = UINT64_MAX; t65 = ((x573|x574)<<(x575>x576)); if (t65 != UINT64_MAX) { NG(); } else { ; } } void f66(void) { int64_t x613 = 2790643196351832LL; int8_t x614 = INT8_MAX; int16_t x615 = -9; int64_t t66 = 923649990536LL; t66 = ((x613|x614)<<(x615>x616)); if (t66 != 2790643196351871LL) { NG(); } else { ; } } void f67(void) { uint64_t x621 = UINT64_MAX; int8_t x622 = INT8_MAX; int64_t x623 = -240508LL; volatile int16_t x624 = 5385; uint64_t t67 = UINT64_MAX; t67 = ((x621|x622)<<(x623>x624)); if (t67 != UINT64_MAX) { NG(); } else { ; } } void f68(void) { volatile int16_t x629 = INT16_MAX; uint32_t x630 = 113996400U; int32_t x631 = -1831876; volatile int64_t x632 = -1LL; volatile uint32_t t68 = 6U; t68 = ((x629|x630)<<(x631>x632)); if (t68 != 113999871U) { NG(); } else { ; } } void f69(void) { static int16_t x637 = -1; volatile uint32_t x638 = 28036962U; int64_t x639 = INT64_MIN; int64_t x640 = 63581653LL; volatile uint32_t t69 = UINT32_MAX; t69 = ((x637|x638)<<(x639>x640)); if (t69 != UINT32_MAX) { NG(); } else { ; } } void f70(void) { static int16_t x649 = -181; uint32_t x650 = UINT32_MAX; int64_t x652 = INT64_MIN; t70 = ((x649|x650)<<(x651>x652)); if (t70 != 4294967294U) { NG(); } else { ; } } void f71(void) { int64_t x653 = 23947037106793859LL; static uint64_t x654 = 1097683096LLU; int16_t x655 = INT16_MAX; int8_t x656 = INT8_MIN; uint64_t t71 = 7466832143LLU; t71 = ((x653|x654)<<(x655>x656)); if (t71 != 47894076403153718LLU) { NG(); } else { ; } } void f72(void) { uint8_t x677 = UINT8_MAX; volatile int32_t x679 = INT32_MAX; uint8_t x680 = 7U; static volatile int32_t t72 = 1; t72 = ((x677|x678)<<(x679>x680)); if (t72 != 510) { NG(); } else { ; } } void f73(void) { volatile int8_t x685 = INT8_MAX; uint64_t x686 = 3LLU; int32_t x688 = INT32_MAX; t73 = ((x685|x686)<<(x687>x688)); if (t73 != 127LLU) { NG(); } else { ; } } void f74(void) { int64_t x689 = 12654448LL; uint32_t x690 = 490249U; static uint8_t x691 = 78U; int64_t x692 = 0LL; static volatile int64_t t74 = -280313157LL; t74 = ((x689|x690)<<(x691>x692)); if (t74 != 26148594LL) { NG(); } else { ; } } void f75(void) { uint64_t x702 = 123487480LLU; static int8_t x703 = -1; static volatile int64_t x704 = INT64_MIN; volatile uint64_t t75 = 60LLU; t75 = ((x701|x702)<<(x703>x704)); if (t75 != 247000568LLU) { NG(); } else { ; } } void f76(void) { uint8_t x713 = UINT8_MAX; int32_t x714 = 3695990; static int16_t x715 = -1; int16_t x716 = -30; static volatile int32_t t76 = 1184039; t76 = ((x713|x714)<<(x715>x716)); if (t76 != 7392254) { NG(); } else { ; } } void f77(void) { int8_t x733 = -1; volatile uint64_t x734 = 69241789358262LLU; int32_t x735 = INT32_MIN; volatile int32_t x736 = 2127014; uint64_t t77 = UINT64_MAX; t77 = ((x733|x734)<<(x735>x736)); if (t77 != UINT64_MAX) { NG(); } else { ; } } void f78(void) { volatile uint64_t x745 = 105293532303LLU; int16_t x747 = INT16_MAX; int16_t x748 = 0; static volatile uint64_t t78 = 7776LLU; t78 = ((x745|x746)<<(x747>x748)); if (t78 != 18446744073709551614LLU) { NG(); } else { ; } } void f79(void) { volatile uint64_t x770 = 2210132088043372243LLU; int16_t x771 = -1; int32_t x772 = INT32_MIN; volatile uint64_t t79 = 5254435119LLU; t79 = ((x769|x770)<<(x771>x772)); if (t79 != 18446744073709551614LLU) { NG(); } else { ; } } void f80(void) { uint64_t x777 = UINT64_MAX; int32_t x778 = -1; uint16_t x779 = 3U; int32_t x780 = INT32_MAX; volatile uint64_t t80 = UINT64_MAX; t80 = ((x777|x778)<<(x779>x780)); if (t80 != UINT64_MAX) { NG(); } else { ; } } void f81(void) { uint32_t x781 = 11317U; static int32_t x782 = 2293972; int8_t x783 = INT8_MAX; uint8_t x784 = 3U; volatile uint32_t t81 = 6553988U; t81 = ((x781|x782)<<(x783>x784)); if (t81 != 4610538U) { NG(); } else { ; } } void f82(void) { uint32_t x798 = 4U; int8_t x799 = -1; int32_t x800 = -13; volatile uint32_t t82 = 16072040U; t82 = ((x797|x798)<<(x799>x800)); if (t82 != 4294967048U) { NG(); } else { ; } } void f83(void) { volatile int32_t x807 = -621808436; static int64_t x808 = INT64_MIN; volatile uint64_t t83 = 14140961911LLU; t83 = ((x805|x806)<<(x807>x808)); if (t83 != 18446744073709551614LLU) { NG(); } else { ; } } void f84(void) { int64_t x821 = 16681308514918991LL; uint32_t x822 = 103163230U; int8_t x824 = 0; static volatile int64_t t84 = -12LL; t84 = ((x821|x822)<<(x823>x824)); if (t84 != 33362617097473726LL) { NG(); } else { ; } } void f85(void) { volatile int16_t x830 = INT16_MAX; uint32_t x831 = UINT32_MAX; volatile int64_t x832 = -1LL; volatile int32_t t85 = 1006; t85 = ((x829|x830)<<(x831>x832)); if (t85 != 65534) { NG(); } else { ; } } void f86(void) { volatile uint8_t x846 = UINT8_MAX; static int32_t x847 = -632; volatile uint32_t t86 = 0U; t86 = ((x845|x846)<<(x847>x848)); if (t86 != 255U) { NG(); } else { ; } } void f87(void) { volatile int32_t x854 = 29086573; int8_t x855 = INT8_MIN; volatile uint64_t x856 = 671LLU; volatile int32_t t87 = -32896796; t87 = ((x853|x854)<<(x855>x856)); if (t87 != 58195966) { NG(); } else { ; } } void f88(void) { uint16_t x857 = UINT16_MAX; volatile uint8_t x858 = UINT8_MAX; static uint16_t x859 = 2U; static int32_t t88 = 287067; t88 = ((x857|x858)<<(x859>x860)); if (t88 != 65535) { NG(); } else { ; } } void f89(void) { int8_t x861 = INT8_MAX; uint16_t x862 = UINT16_MAX; int32_t x863 = INT32_MIN; uint8_t x864 = 10U; volatile int32_t t89 = 116143132; t89 = ((x861|x862)<<(x863>x864)); if (t89 != 65535) { NG(); } else { ; } } void f90(void) { static uint64_t x865 = 10825LLU; uint16_t x866 = UINT16_MAX; uint16_t x867 = 117U; int8_t x868 = INT8_MIN; volatile uint64_t t90 = 0LLU; t90 = ((x865|x866)<<(x867>x868)); if (t90 != 131070LLU) { NG(); } else { ; } } void f91(void) { uint64_t x890 = 3117679930166LLU; volatile uint16_t x891 = UINT16_MAX; static int8_t x892 = INT8_MAX; static uint64_t t91 = 29730877548LLU; t91 = ((x889|x890)<<(x891>x892)); if (t91 != 6235755511660LLU) { NG(); } else { ; } } void f92(void) { static uint64_t x897 = 14598549699970LLU; volatile int32_t x898 = 193502; static uint8_t x899 = 3U; static uint64_t t92 = 34139934822107168LLU; t92 = ((x897|x898)<<(x899>x900)); if (t92 != 14598549733342LLU) { NG(); } else { ; } } void f93(void) { int8_t x913 = INT8_MAX; uint64_t x914 = 1466976368448LLU; static volatile int64_t x915 = INT64_MAX; volatile uint64_t x916 = UINT64_MAX; volatile uint64_t t93 = 5928LLU; t93 = ((x913|x914)<<(x915>x916)); if (t93 != 1466976368511LLU) { NG(); } else { ; } } void f94(void) { static uint64_t x921 = 3LLU; static int16_t x922 = INT16_MIN; uint32_t x923 = 300U; static volatile uint64_t t94 = 7LLU; t94 = ((x921|x922)<<(x923>x924)); if (t94 != 18446744073709518851LLU) { NG(); } else { ; } } void f95(void) { uint16_t x925 = UINT16_MAX; uint32_t x926 = UINT32_MAX; static uint32_t x927 = 64685U; int8_t x928 = INT8_MAX; t95 = ((x925|x926)<<(x927>x928)); if (t95 != 4294967294U) { NG(); } else { ; } } void f96(void) { static uint32_t x934 = 0U; uint16_t x936 = 17U; t96 = ((x933|x934)<<(x935>x936)); if (t96 != 0U) { NG(); } else { ; } } void f97(void) { uint8_t x950 = UINT8_MAX; int64_t x951 = INT64_MAX; uint64_t x952 = UINT64_MAX; int32_t t97 = -16887218; t97 = ((x949|x950)<<(x951>x952)); if (t97 != 255) { NG(); } else { ; } } void f98(void) { uint64_t x954 = 47099LLU; static volatile uint64_t x955 = 304556LLU; int8_t x956 = INT8_MIN; static uint64_t t98 = 0LLU; t98 = ((x953|x954)<<(x955>x956)); if (t98 != 18446744073709551611LLU) { NG(); } else { ; } } void f99(void) { int8_t x969 = -5; volatile uint32_t x970 = 22U; int32_t x972 = INT32_MAX; uint32_t t99 = UINT32_MAX; t99 = ((x969|x970)<<(x971>x972)); if (t99 != UINT32_MAX) { NG(); } else { ; } } void f100(void) { uint64_t x985 = 2925742179LLU; uint32_t x986 = 25647U; volatile int64_t x987 = -31760090873512780LL; uint64_t t100 = 4LLU; t100 = ((x985|x986)<<(x987>x988)); if (t100 != 2925751407LLU) { NG(); } else { ; } } void f101(void) { int32_t x1001 = 403375963; uint8_t x1003 = 27U; static int64_t x1004 = -1LL; volatile uint32_t t101 = 14154U; t101 = ((x1001|x1002)<<(x1003>x1004)); if (t101 != 4294967294U) { NG(); } else { ; } } void f102(void) { volatile int16_t x1005 = INT16_MAX; volatile uint64_t x1006 = 21007373LLU; static int64_t x1007 = -26060696855327424LL; uint64_t x1008 = UINT64_MAX; volatile uint64_t t102 = 11763LLU; t102 = ((x1005|x1006)<<(x1007>x1008)); if (t102 != 21037055LLU) { NG(); } else { ; } } void f103(void) { volatile uint16_t x1009 = UINT16_MAX; volatile int8_t x1010 = INT8_MAX; int64_t x1011 = -204LL; static uint16_t x1012 = UINT16_MAX; static volatile int32_t t103 = 224; t103 = ((x1009|x1010)<<(x1011>x1012)); if (t103 != 65535) { NG(); } else { ; } } void f104(void) { int16_t x1025 = -1; uint64_t x1026 = 60353240578LLU; uint8_t x1027 = 5U; uint16_t x1028 = 3U; uint64_t t104 = 578979LLU; t104 = ((x1025|x1026)<<(x1027>x1028)); if (t104 != 18446744073709551614LLU) { NG(); } else { ; } } void f105(void) { int64_t x1038 = INT64_MIN; int32_t x1040 = INT32_MAX; uint64_t t105 = UINT64_MAX; t105 = ((x1037|x1038)<<(x1039>x1040)); if (t105 != UINT64_MAX) { NG(); } else { ; } } void f106(void) { volatile int64_t x1049 = INT64_MAX; volatile int32_t x1050 = INT32_MAX; uint32_t x1051 = 161790U; static int8_t x1052 = INT8_MIN; int64_t t106 = INT64_MAX; t106 = ((x1049|x1050)<<(x1051>x1052)); if (t106 != INT64_MAX) { NG(); } else { ; } } void f107(void) { static int16_t x1061 = 3790; static volatile uint16_t x1062 = 3U; static int8_t x1063 = 49; int16_t x1064 = 62; int32_t t107 = 481635226; t107 = ((x1061|x1062)<<(x1063>x1064)); if (t107 != 3791) { NG(); } else { ; } } void f108(void) { uint64_t x1070 = 241130727767921LLU; volatile uint64_t t108 = 1457141LLU; t108 = ((x1069|x1070)<<(x1071>x1072)); if (t108 != 241130727768063LLU) { NG(); } else { ; } } void f109(void) { int16_t x1077 = -599; uint64_t x1079 = UINT64_MAX; static uint8_t x1080 = 6U; volatile uint64_t t109 = 701165533287562349LLU; t109 = ((x1077|x1078)<<(x1079>x1080)); if (t109 != 18446744073709551614LLU) { NG(); } else { ; } } void f110(void) { uint16_t x1085 = UINT16_MAX; uint32_t x1086 = 1069U; uint32_t x1087 = 0U; int16_t x1088 = 80; uint32_t t110 = 23882U; t110 = ((x1085|x1086)<<(x1087>x1088)); if (t110 != 65535U) { NG(); } else { ; } } void f111(void) { int16_t x1105 = 0; uint32_t x1106 = UINT32_MAX; uint32_t x1107 = UINT32_MAX; int8_t x1108 = 0; volatile uint32_t t111 = 228421U; t111 = ((x1105|x1106)<<(x1107>x1108)); if (t111 != 4294967294U) { NG(); } else { ; } } void f112(void) { static uint32_t x1109 = 501594U; uint16_t x1110 = 160U; int16_t x1112 = 1; t112 = ((x1109|x1110)<<(x1111>x1112)); if (t112 != 501754U) { NG(); } else { ; } } void f113(void) { static uint32_t x1114 = UINT32_MAX; uint16_t x1115 = 15U; volatile uint32_t t113 = 43546629U; t113 = ((x1113|x1114)<<(x1115>x1116)); if (t113 != 4294967294U) { NG(); } else { ; } } void f114(void) { int16_t x1117 = INT16_MIN; volatile uint64_t x1118 = 1LLU; uint8_t x1119 = 10U; int64_t x1120 = INT64_MAX; t114 = ((x1117|x1118)<<(x1119>x1120)); if (t114 != 18446744073709518849LLU) { NG(); } else { ; } } void f115(void) { volatile uint16_t x1125 = 449U; uint32_t x1126 = UINT32_MAX; static int16_t x1127 = INT16_MAX; int8_t x1128 = INT8_MIN; static volatile uint32_t t115 = 28622389U; t115 = ((x1125|x1126)<<(x1127>x1128)); if (t115 != 4294967294U) { NG(); } else { ; } } void f116(void) { uint32_t x1133 = UINT32_MAX; int32_t x1134 = -1; int8_t x1135 = 1; int8_t x1136 = 0; volatile uint32_t t116 = 0U; t116 = ((x1133|x1134)<<(x1135>x1136)); if (t116 != 4294967294U) { NG(); } else { ; } } void f117(void) { static int16_t x1137 = INT16_MIN; uint32_t x1138 = 117947902U; int16_t x1139 = 20; int32_t x1140 = INT32_MIN; volatile uint32_t t117 = 88081867U; t117 = ((x1137|x1138)<<(x1139>x1140)); if (t117 != 4294933500U) { NG(); } else { ; } } void f118(void) { int8_t x1141 = 1; uint16_t x1142 = 3U; uint64_t x1144 = 406603399571048LLU; t118 = ((x1141|x1142)<<(x1143>x1144)); if (t118 != 6) { NG(); } else { ; } } void f119(void) { uint32_t x1149 = 945802U; static int8_t x1151 = INT8_MIN; volatile int64_t x1152 = INT64_MAX; volatile uint32_t t119 = 0U; t119 = ((x1149|x1150)<<(x1151>x1152)); if (t119 != 983039U) { NG(); } else { ; } } void f120(void) { uint64_t x1161 = 2172959938175055972LLU; volatile int64_t x1162 = -79LL; int16_t x1164 = INT16_MAX; uint64_t t120 = 88986LLU; t120 = ((x1161|x1162)<<(x1163>x1164)); if (t120 != 18446744073709551605LLU) { NG(); } else { ; } } void f121(void) { static int32_t x1185 = -1; uint64_t x1186 = 3225044213390511666LLU; volatile int32_t x1187 = -1; uint8_t x1188 = 87U; static volatile uint64_t t121 = UINT64_MAX; t121 = ((x1185|x1186)<<(x1187>x1188)); if (t121 != UINT64_MAX) { NG(); } else { ; } } void f122(void) { static volatile uint16_t x1189 = 6375U; static int16_t x1190 = INT16_MAX; int32_t x1191 = INT32_MIN; int16_t x1192 = 1; t122 = ((x1189|x1190)<<(x1191>x1192)); if (t122 != 32767) { NG(); } else { ; } } void f123(void) { uint8_t x1209 = 44U; uint32_t x1210 = UINT32_MAX; static uint32_t x1211 = 1596684021U; uint32_t t123 = 31318026U; t123 = ((x1209|x1210)<<(x1211>x1212)); if (t123 != 4294967294U) { NG(); } else { ; } } void f124(void) { static int8_t x1225 = INT8_MIN; uint64_t x1226 = 107LLU; int16_t x1227 = -1; int64_t x1228 = INT64_MIN; t124 = ((x1225|x1226)<<(x1227>x1228)); if (t124 != 18446744073709551574LLU) { NG(); } else { ; } } void f125(void) { volatile int16_t x1233 = INT16_MIN; static uint8_t x1235 = 1U; int16_t x1236 = 9; volatile uint64_t t125 = 25067LLU; t125 = ((x1233|x1234)<<(x1235>x1236)); if (t125 != 18446744073709521163LLU) { NG(); } else { ; } } void f126(void) { static uint32_t x1237 = UINT32_MAX; volatile int16_t x1239 = -1; t126 = ((x1237|x1238)<<(x1239>x1240)); if (t126 != 4294967294U) { NG(); } else { ; } } void f127(void) { uint8_t x1241 = UINT8_MAX; int64_t x1242 = INT64_MAX; volatile uint64_t x1243 = 7958852333450099LLU; int64_t x1244 = -1LL; int64_t t127 = INT64_MAX; t127 = ((x1241|x1242)<<(x1243>x1244)); if (t127 != INT64_MAX) { NG(); } else { ; } } void f128(void) { uint8_t x1249 = UINT8_MAX; uint8_t x1251 = UINT8_MAX; int8_t x1252 = 36; static volatile uint64_t t128 = 157811692452LLU; t128 = ((x1249|x1250)<<(x1251>x1252)); if (t128 != 18446744073709551614LLU) { NG(); } else { ; } } void f129(void) { uint16_t x1253 = 1U; static volatile uint64_t x1254 = UINT64_MAX; static int16_t x1255 = -1; int64_t x1256 = -1LL; uint64_t t129 = UINT64_MAX; t129 = ((x1253|x1254)<<(x1255>x1256)); if (t129 != UINT64_MAX) { NG(); } else { ; } } void f130(void) { uint32_t x1261 = 999578547U; int16_t x1262 = INT16_MIN; int64_t x1263 = -1LL; uint32_t x1264 = 15561U; uint32_t t130 = 1U; t130 = ((x1261|x1262)<<(x1263>x1264)); if (t130 != 4294958003U) { NG(); } else { ; } } void f131(void) { int32_t x1265 = 337; static uint32_t x1268 = 24U; int32_t t131 = 385656; t131 = ((x1265|x1266)<<(x1267>x1268)); if (t131 != 754) { NG(); } else { ; } } void f132(void) { int32_t x1285 = INT32_MAX; volatile uint32_t x1287 = 6U; int32_t t132 = INT32_MAX; t132 = ((x1285|x1286)<<(x1287>x1288)); if (t132 != INT32_MAX) { NG(); } else { ; } } void f133(void) { static uint32_t x1290 = 124883U; volatile uint32_t x1291 = UINT32_MAX; volatile int64_t x1292 = -495111LL; uint64_t t133 = 318276301474LLU; t133 = ((x1289|x1290)<<(x1291>x1292)); if (t133 != 249830LLU) { NG(); } else { ; } } void f134(void) { volatile uint8_t x1309 = 1U; static uint64_t x1310 = 70686593118266461LLU; volatile uint64_t x1311 = 916585441980LLU; static uint64_t t134 = 62677963569LLU; t134 = ((x1309|x1310)<<(x1311>x1312)); if (t134 != 70686593118266461LLU) { NG(); } else { ; } } void f135(void) { int16_t x1313 = INT16_MAX; uint16_t x1314 = 6U; static volatile int32_t t135 = 0; t135 = ((x1313|x1314)<<(x1315>x1316)); if (t135 != 65534) { NG(); } else { ; } } void f136(void) { volatile uint64_t x1322 = 23431025296534LLU; uint16_t x1323 = 105U; t136 = ((x1321|x1322)<<(x1323>x1324)); if (t136 != 18446744073709520022LLU) { NG(); } else { ; } } void f137(void) { int64_t x1330 = 345867626813934LL; int32_t x1331 = INT32_MIN; volatile int8_t x1332 = INT8_MIN; int64_t t137 = 60621734LL; t137 = ((x1329|x1330)<<(x1331>x1332)); if (t137 != 345867626813935LL) { NG(); } else { ; } } void f138(void) { volatile uint16_t x1337 = UINT16_MAX; uint32_t x1338 = UINT32_MAX; uint8_t x1340 = UINT8_MAX; static volatile uint32_t t138 = UINT32_MAX; t138 = ((x1337|x1338)<<(x1339>x1340)); if (t138 != UINT32_MAX) { NG(); } else { ; } } void f139(void) { uint8_t x1353 = 2U; volatile uint16_t x1354 = 0U; uint8_t x1356 = 5U; int32_t t139 = 15; t139 = ((x1353|x1354)<<(x1355>x1356)); if (t139 != 2) { NG(); } else { ; } } void f140(void) { volatile int64_t x1357 = INT64_MAX; uint16_t x1358 = 9507U; volatile int16_t x1359 = 2120; volatile uint32_t x1360 = 5774U; volatile int64_t t140 = INT64_MAX; t140 = ((x1357|x1358)<<(x1359>x1360)); if (t140 != INT64_MAX) { NG(); } else { ; } } void f141(void) { int32_t x1363 = -1; int64_t x1364 = INT64_MIN; static volatile uint32_t t141 = 1871514U; t141 = ((x1361|x1362)<<(x1363>x1364)); if (t141 != 4294967294U) { NG(); } else { ; } } void f142(void) { uint32_t x1365 = 2102U; uint16_t x1366 = 2041U; static int8_t x1367 = INT8_MIN; uint32_t t142 = 3908U; t142 = ((x1365|x1366)<<(x1367>x1368)); if (t142 != 4095U) { NG(); } else { ; } } void f143(void) { uint32_t x1369 = 2402U; volatile int8_t x1370 = INT8_MIN; uint32_t x1371 = UINT32_MAX; static volatile uint16_t x1372 = UINT16_MAX; volatile uint32_t t143 = 3335774U; t143 = ((x1369|x1370)<<(x1371>x1372)); if (t143 != 4294967236U) { NG(); } else { ; } } void f144(void) { uint8_t x1373 = UINT8_MAX; int16_t x1375 = 13; int64_t x1376 = INT64_MIN; volatile uint64_t t144 = 1606317LLU; t144 = ((x1373|x1374)<<(x1375>x1376)); if (t144 != 18446744073709551614LLU) { NG(); } else { ; } } void f145(void) { uint8_t x1381 = 1U; uint64_t x1382 = 25800665702940LLU; uint8_t x1384 = 67U; t145 = ((x1381|x1382)<<(x1383>x1384)); if (t145 != 25800665702941LLU) { NG(); } else { ; } } void f146(void) { int64_t x1389 = 4694108LL; int8_t x1391 = INT8_MIN; int32_t x1392 = INT32_MAX; int64_t t146 = 390160867094LL; t146 = ((x1389|x1390)<<(x1391>x1392)); if (t146 != 4294967295LL) { NG(); } else { ; } } void f147(void) { static volatile int64_t x1398 = 8643795LL; volatile uint64_t x1399 = 46777536088LLU; int64_t x1400 = -1LL; volatile uint64_t t147 = 857515703441791877LLU; t147 = ((x1397|x1398)<<(x1399>x1400)); if (t147 != 100746264531952863LLU) { NG(); } else { ; } } void f148(void) { static volatile int64_t x1413 = 101815651LL; static volatile uint16_t x1414 = UINT16_MAX; uint32_t x1416 = 6866U; volatile int64_t t148 = -130873246476LL; t148 = ((x1413|x1414)<<(x1415>x1416)); if (t148 != 101842943LL) { NG(); } else { ; } } void f149(void) { uint32_t x1418 = UINT32_MAX; uint16_t x1420 = UINT16_MAX; volatile uint32_t t149 = UINT32_MAX; t149 = ((x1417|x1418)<<(x1419>x1420)); if (t149 != UINT32_MAX) { NG(); } else { ; } } void f150(void) { int32_t x1442 = INT32_MAX; volatile int16_t x1443 = -1; int32_t x1444 = INT32_MIN; volatile uint64_t t150 = 61LLU; t150 = ((x1441|x1442)<<(x1443>x1444)); if (t150 != 18446744073709551614LLU) { NG(); } else { ; } } void f151(void) { uint16_t x1457 = 36U; volatile uint8_t x1458 = 9U; int16_t x1459 = 15; static int32_t x1460 = -3614394; int32_t t151 = -10; t151 = ((x1457|x1458)<<(x1459>x1460)); if (t151 != 90) { NG(); } else { ; } } void f152(void) { int8_t x1465 = INT8_MIN; uint32_t x1466 = 253947952U; int64_t x1467 = INT64_MIN; uint32_t t152 = 20577U; t152 = ((x1465|x1466)<<(x1467>x1468)); if (t152 != 4294967216U) { NG(); } else { ; } } void f153(void) { uint16_t x1481 = 15582U; volatile uint8_t x1483 = 2U; int8_t x1484 = INT8_MAX; t153 = ((x1481|x1482)<<(x1483>x1484)); if (t153 != 15615) { NG(); } else { ; } } void f154(void) { volatile uint8_t x1497 = UINT8_MAX; static uint8_t x1498 = UINT8_MAX; int8_t x1499 = INT8_MIN; t154 = ((x1497|x1498)<<(x1499>x1500)); if (t154 != 255) { NG(); } else { ; } } void f155(void) { uint32_t x1505 = 3164094U; uint32_t x1506 = UINT32_MAX; int16_t x1508 = 3; uint32_t t155 = 1535618U; t155 = ((x1505|x1506)<<(x1507>x1508)); if (t155 != 4294967294U) { NG(); } else { ; } } void f156(void) { static uint64_t x1514 = 123LLU; volatile int64_t x1516 = INT64_MAX; volatile uint64_t t156 = UINT64_MAX; t156 = ((x1513|x1514)<<(x1515>x1516)); if (t156 != UINT64_MAX) { NG(); } else { ; } } void f157(void) { int8_t x1525 = -1; uint32_t x1527 = 191553334U; uint16_t x1528 = UINT16_MAX; uint32_t t157 = 20U; t157 = ((x1525|x1526)<<(x1527>x1528)); if (t157 != 4294967294U) { NG(); } else { ; } } void f158(void) { uint32_t x1549 = 2457U; uint8_t x1550 = 10U; volatile int32_t x1551 = -7; static int16_t x1552 = INT16_MIN; uint32_t t158 = 1937130U; t158 = ((x1549|x1550)<<(x1551>x1552)); if (t158 != 4918U) { NG(); } else { ; } } void f159(void) { int64_t x1553 = 2101LL; volatile uint64_t x1554 = 1091670LLU; uint32_t x1556 = UINT32_MAX; t159 = ((x1553|x1554)<<(x1555>x1556)); if (t159 != 1091703LLU) { NG(); } else { ; } } void f160(void) { uint32_t x1558 = UINT32_MAX; int64_t x1559 = -24460908084LL; uint64_t x1560 = UINT64_MAX; uint32_t t160 = UINT32_MAX; t160 = ((x1557|x1558)<<(x1559>x1560)); if (t160 != UINT32_MAX) { NG(); } else { ; } } void f161(void) { uint64_t x1569 = 1LLU; int32_t x1570 = -27800; static int64_t x1571 = 12LL; uint32_t x1572 = 3U; t161 = ((x1569|x1570)<<(x1571>x1572)); if (t161 != 18446744073709496018LLU) { NG(); } else { ; } } void f162(void) { uint64_t x1577 = 106318LLU; static volatile uint16_t x1578 = 21U; static volatile int8_t x1579 = -1; int8_t x1580 = 59; uint64_t t162 = 71LLU; t162 = ((x1577|x1578)<<(x1579>x1580)); if (t162 != 106335LLU) { NG(); } else { ; } } void f163(void) { int16_t x1581 = INT16_MIN; uint64_t x1582 = 1237LLU; static int16_t x1583 = INT16_MAX; int16_t x1584 = 1706; uint64_t t163 = 2LLU; t163 = ((x1581|x1582)<<(x1583>x1584)); if (t163 != 18446744073709488554LLU) { NG(); } else { ; } } void f164(void) { uint64_t x1585 = UINT64_MAX; int32_t x1586 = INT32_MIN; int16_t x1588 = -1; uint64_t t164 = UINT64_MAX; t164 = ((x1585|x1586)<<(x1587>x1588)); if (t164 != UINT64_MAX) { NG(); } else { ; } } void f165(void) { int64_t x1617 = 99766429499LL; static uint8_t x1618 = UINT8_MAX; volatile int16_t x1619 = 56; uint32_t x1620 = 114U; volatile int64_t t165 = 223201LL; t165 = ((x1617|x1618)<<(x1619>x1620)); if (t165 != 99766429695LL) { NG(); } else { ; } } void f166(void) { uint32_t x1625 = UINT32_MAX; uint8_t x1626 = 1U; static uint8_t x1628 = 95U; static uint32_t t166 = UINT32_MAX; t166 = ((x1625|x1626)<<(x1627>x1628)); if (t166 != UINT32_MAX) { NG(); } else { ; } } void f167(void) { static uint32_t x1629 = UINT32_MAX; static int8_t x1630 = INT8_MIN; volatile int8_t x1631 = -1; uint32_t x1632 = 290868U; t167 = ((x1629|x1630)<<(x1631>x1632)); if (t167 != 4294967294U) { NG(); } else { ; } } void f168(void) { int16_t x1637 = INT16_MIN; uint64_t x1638 = UINT64_MAX; static int32_t x1639 = 200; int32_t x1640 = 2; t168 = ((x1637|x1638)<<(x1639>x1640)); if (t168 != 18446744073709551614LLU) { NG(); } else { ; } } void f169(void) { int32_t x1641 = 0; int8_t x1643 = INT8_MIN; uint32_t x1644 = 570U; static volatile int32_t t169 = -3582518; t169 = ((x1641|x1642)<<(x1643>x1644)); if (t169 != 0) { NG(); } else { ; } } void f170(void) { volatile uint8_t x1645 = 5U; int16_t x1646 = 2; volatile uint64_t x1647 = 6246LLU; int32_t t170 = 8383; t170 = ((x1645|x1646)<<(x1647>x1648)); if (t170 != 14) { NG(); } else { ; } } void f171(void) { uint64_t x1661 = UINT64_MAX; static volatile int64_t x1662 = -1LL; int64_t x1664 = INT64_MAX; t171 = ((x1661|x1662)<<(x1663>x1664)); if (t171 != UINT64_MAX) { NG(); } else { ; } } void f172(void) { uint16_t x1669 = UINT16_MAX; static uint8_t x1670 = 3U; int16_t x1671 = 1; int32_t t172 = 23; t172 = ((x1669|x1670)<<(x1671>x1672)); if (t172 != 65535) { NG(); } else { ; } } void f173(void) { uint32_t x1681 = 20U; int32_t x1682 = INT32_MAX; int32_t x1683 = -1; int64_t x1684 = 813826850217555LL; uint32_t t173 = 61876186U; t173 = ((x1681|x1682)<<(x1683>x1684)); if (t173 != 2147483647U) { NG(); } else { ; } } void f174(void) { volatile uint64_t x1685 = 9489597397228LLU; uint64_t x1687 = 42872168715693LLU; t174 = ((x1685|x1686)<<(x1687>x1688)); if (t174 != 18446744073709551614LLU) { NG(); } else { ; } } void f175(void) { int64_t x1694 = INT64_MIN; volatile uint8_t x1695 = 7U; int16_t x1696 = 61; volatile uint64_t t175 = 1610508917453LLU; t175 = ((x1693|x1694)<<(x1695>x1696)); if (t175 != 9253704117788460450LLU) { NG(); } else { ; } } void f176(void) { uint64_t x1697 = 4015100241391LLU; volatile int64_t x1700 = 106LL; uint64_t t176 = 1475446959523LLU; t176 = ((x1697|x1698)<<(x1699>x1700)); if (t176 != 8030200482782LLU) { NG(); } else { ; } } void f177(void) { uint64_t x1701 = UINT64_MAX; static volatile int32_t x1702 = INT32_MAX; static uint8_t x1703 = 92U; static volatile uint16_t x1704 = 1757U; t177 = ((x1701|x1702)<<(x1703>x1704)); if (t177 != UINT64_MAX) { NG(); } else { ; } } void f178(void) { static uint32_t x1709 = 2U; volatile uint64_t x1710 = 1803703924LLU; static int16_t x1711 = INT16_MAX; int64_t x1712 = INT64_MAX; uint64_t t178 = 1607975689LLU; t178 = ((x1709|x1710)<<(x1711>x1712)); if (t178 != 1803703926LLU) { NG(); } else { ; } } void f179(void) { uint32_t x1717 = UINT32_MAX; static volatile uint8_t x1718 = 7U; uint64_t x1720 = 5728254LLU; uint32_t t179 = 5645077U; t179 = ((x1717|x1718)<<(x1719>x1720)); if (t179 != 4294967294U) { NG(); } else { ; } } void f180(void) { int32_t x1743 = 10146; volatile uint64_t t180 = 678617059781916184LLU; t180 = ((x1741|x1742)<<(x1743>x1744)); if (t180 != 18446744073210953726LLU) { NG(); } else { ; } } void f181(void) { int64_t x1749 = 27391550464LL; int32_t x1750 = INT32_MAX; int8_t x1751 = INT8_MIN; static volatile int64_t t181 = 66LL; t181 = ((x1749|x1750)<<(x1751>x1752)); if (t181 != 27917287423LL) { NG(); } else { ; } } void f182(void) { int8_t x1753 = INT8_MIN; static uint32_t x1754 = 14776421U; uint32_t x1755 = 4414U; volatile int64_t x1756 = 1543358502505441LL; uint32_t t182 = 1733714600U; t182 = ((x1753|x1754)<<(x1755>x1756)); if (t182 != 4294967269U) { NG(); } else { ; } } void f183(void) { uint64_t x1778 = UINT64_MAX; volatile int32_t x1779 = -1; int8_t x1780 = INT8_MAX; volatile uint64_t t183 = UINT64_MAX; t183 = ((x1777|x1778)<<(x1779>x1780)); if (t183 != UINT64_MAX) { NG(); } else { ; } } void f184(void) { int64_t x1781 = INT64_MIN; uint64_t x1782 = 29823648867027LLU; volatile int8_t x1783 = 7; static volatile int32_t x1784 = INT32_MIN; uint64_t t184 = 568674LLU; t184 = ((x1781|x1782)<<(x1783>x1784)); if (t184 != 59647297734054LLU) { NG(); } else { ; } } void f185(void) { int16_t x1785 = INT16_MAX; int64_t x1786 = 59LL; int8_t x1787 = -42; int64_t t185 = -1LL; t185 = ((x1785|x1786)<<(x1787>x1788)); if (t185 != 32767LL) { NG(); } else { ; } } void f186(void) { int64_t x1802 = 907979846417LL; int64_t x1803 = INT64_MAX; int64_t t186 = -56612196699203LL; t186 = ((x1801|x1802)<<(x1803>x1804)); if (t186 != 1815959692834LL) { NG(); } else { ; } } void f187(void) { static volatile uint16_t x1805 = 95U; int64_t x1806 = 0LL; int8_t x1807 = 6; volatile int64_t t187 = -2004LL; t187 = ((x1805|x1806)<<(x1807>x1808)); if (t187 != 190LL) { NG(); } else { ; } } void f188(void) { int8_t x1812 = -53; t188 = ((x1809|x1810)<<(x1811>x1812)); if (t188 != 510) { NG(); } else { ; } } void f189(void) { int8_t x1813 = INT8_MAX; int8_t x1814 = 9; static int8_t x1815 = INT8_MIN; int64_t x1816 = -1LL; int32_t t189 = 5300674; t189 = ((x1813|x1814)<<(x1815>x1816)); if (t189 != 127) { NG(); } else { ; } } void f190(void) { int32_t x1818 = INT32_MAX; uint8_t x1819 = 8U; volatile uint64_t x1820 = 89340381LLU; volatile uint32_t t190 = UINT32_MAX; t190 = ((x1817|x1818)<<(x1819>x1820)); if (t190 != UINT32_MAX) { NG(); } else { ; } } void f191(void) { uint32_t x1837 = UINT32_MAX; uint16_t x1838 = UINT16_MAX; volatile uint8_t x1839 = 1U; volatile uint32_t t191 = UINT32_MAX; t191 = ((x1837|x1838)<<(x1839>x1840)); if (t191 != UINT32_MAX) { NG(); } else { ; } } void f192(void) { uint16_t x1853 = UINT16_MAX; uint8_t x1854 = UINT8_MAX; uint8_t x1855 = 12U; int64_t x1856 = 18600LL; static volatile int32_t t192 = 7357475; t192 = ((x1853|x1854)<<(x1855>x1856)); if (t192 != 65535) { NG(); } else { ; } } void f193(void) { static uint32_t x1865 = UINT32_MAX; static int8_t x1866 = INT8_MAX; static int8_t x1867 = INT8_MIN; int32_t x1868 = INT32_MIN; uint32_t t193 = 20616816U; t193 = ((x1865|x1866)<<(x1867>x1868)); if (t193 != 4294967294U) { NG(); } else { ; } } void f194(void) { volatile uint64_t x1869 = UINT64_MAX; int64_t x1870 = -19867539898187869LL; static int32_t x1872 = 16276; volatile uint64_t t194 = UINT64_MAX; t194 = ((x1869|x1870)<<(x1871>x1872)); if (t194 != UINT64_MAX) { NG(); } else { ; } } void f195(void) { static uint8_t x1882 = 28U; uint64_t x1884 = 351156601988403643LLU; volatile uint64_t t195 = 216LLU; t195 = ((x1881|x1882)<<(x1883>x1884)); if (t195 != 18446744073709551614LLU) { NG(); } else { ; } } void f196(void) { int8_t x1897 = -1; uint32_t x1898 = 0U; uint32_t x1899 = UINT32_MAX; static volatile int32_t x1900 = -1; uint32_t t196 = UINT32_MAX; t196 = ((x1897|x1898)<<(x1899>x1900)); if (t196 != UINT32_MAX) { NG(); } else { ; } } void f197(void) { static int32_t x1901 = INT32_MIN; uint64_t x1902 = UINT64_MAX; int64_t x1903 = -3LL; int8_t x1904 = INT8_MIN; static uint64_t t197 = 13573878LLU; t197 = ((x1901|x1902)<<(x1903>x1904)); if (t197 != 18446744073709551614LLU) { NG(); } else { ; } } void f198(void) { uint64_t x1925 = 482003118988762LLU; int64_t x1926 = 2247593483137772935LL; int8_t x1927 = INT8_MIN; int64_t x1928 = INT64_MAX; static volatile uint64_t t198 = 87981055608191783LLU; t198 = ((x1925|x1926)<<(x1927>x1928)); if (t198 != 2247787134624267743LLU) { NG(); } else { ; } } void f199(void) { volatile uint32_t x1933 = 1588485U; uint16_t x1935 = 53U; t199 = ((x1933|x1934)<<(x1935>x1936)); if (t199 != 1605631U) { 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; }
875733.c
/* * Copyright 2010-2019, Tarantool AUTHORS, please see AUTHORS file. * * 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 <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> 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 "guava.h" #include <stdint.h> /** * This is implements a consistent hashing algorithm * A Fast, Minimal Memory, Consistent Hash Algorithm * John Lamping, Eric Veach */ static const int64_t K = 2862933555777941757; static const double D = 0x1.0p31; static inline double lcg(int64_t *state) { return (double )((int32_t)(((uint64_t )*state >> 33) + 1)) / D; } int32_t guava(int64_t state, int32_t buckets) { int32_t candidate = 0; int32_t next; while (1) { state = K * state + 1; next = (int32_t)((candidate + 1) / lcg(&state)); if (next >= 0 && next < buckets) candidate = next; else return candidate; } }
852075.c
#include <std.h> #include <daemons.h> #include <spell.h> #include <magic.h> inherit SPELL; int bonus; void create() { ::create(); set_spell_name("celestial healing"); set_spell_level(([ "mage" : 1, "cleric" : 1, "magus" : 1 ])); set_spell_sphere("conjuration_summoning"); set_syntax("cast CLASS celestial healing [on TARGET]"); set_damage_desc("fast healing 1"); set_description("You anoint a wounded creature with the blood of an outsider with the good subtype (such as an angel) or holy water, giving it faster healing. For the duration of the spell you'll have a good aura. %^BOLD%^%^RED%^See also:%^RESET%^ status effects"); set_helpful_spell(1); } string query_casting_string() { return "%^BOLD%^%^ORANGE%^"+caster->QCN+" %^BOLD%^%^ORANGE%^spells an %^ORANGE%^i%^WHITE%^n%^ORANGE%^f%^WHITE%^ernal %^WHITE%^inc%^ORANGE%^a%^WHITE%^nt%^ORANGE%^a%^ORANGE%^t%^WHITE%^ion.%^RESET%^ "; } int preSpell() { if (!target) { target = caster; } if (target->query_property("fast_healing_spell") || target->query_property("hidden alignment")) { tell_object(caster, "%^BOLD%^%^WHITE%^You feel your spell repelled..."); return 0; } return 1; } void spell_effect() { if (!target) { target = caster; } if (!objectp(target)) { TO->remove(); return; } if (!objectp(caster)) { TO->remove(); return; } tell_room(place, "%^ORANGE%^An %^ORANGE%^i%^BOLD%^%^ORANGE%^l%^RESET%^%^ORANGE%^l%^BOLD%^%^ORANGE%^ustri%^RESET%^%^ORANGE%^o%^ORANGE%^u%^BOLD%^%^ORANGE%^s %^ORANGE%^ha%^RESET%^%^ORANGE%^l%^BOLD%^%^ORANGE%^o%^RESET%^%^ORANGE%^ shines above " + target->QCN + "' head.", target); { int duration = clevel * ROUND_LENGTH * 12; tell_object(target, "%^ORANGE%^An %^ORANGE%^i%^BOLD%^%^ORANGE%^l%^RESET%^%^ORANGE%^l%^BOLD%^%^ORANGE%^ustri%^RESET%^%^ORANGE%^o%^ORANGE%^u%^BOLD%^%^ORANGE%^s %^ORANGE%^ha%^RESET%^%^ORANGE%^l%^BOLD%^%^ORANGE%^o%^RESET%^%^ORANGE%^ shines above your head."); target->set_property("spelled", ({ TO })); target->set_property("fast healing", 1); target->set_property("fast_healing_spell", 1); target->set_property("hidden alignment", 4); spell_successful(); addSpellToCaster(); spell_duration = duration; set_end_time(); call_out("dest_effect",spell_duration); } } void dest_effect() { if (objectp(target)) { tell_object(target, "%^BOLD%^%^ORANGE%^The celestial light abandons your blood.%^RESET%^"); target->remove_property_value("spelled", ({ TO })); target->set_property("fast healing", -1); target->remove_property("fast_healing_spell"); target->remove_property("hidden alignment"); } ::dest_effect(); if (objectp(TO)) { TO->remove(); } }
766091.c
/* * Copyright (C) 2010-2011 Canonical Ltd <[email protected]> * Copyright (C) 2011-2012 Linaro Ltd <[email protected]> * * 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. * * Standard functionality for the common clock API. See Documentation/clk.txt */ #include <linux/clk-private.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/err.h> #include <linux/list.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/device.h> #include <linux/init.h> #include <linux/sched.h> static DEFINE_SPINLOCK(enable_lock); static DEFINE_MUTEX(prepare_lock); static struct task_struct *prepare_owner; static struct task_struct *enable_owner; static int prepare_refcnt; static int enable_refcnt; static HLIST_HEAD(clk_root_list); static HLIST_HEAD(clk_orphan_list); static LIST_HEAD(clk_notifier_list); /*** locking ***/ static void clk_prepare_lock(void) { if (!mutex_trylock(&prepare_lock)) { if (prepare_owner == current) { prepare_refcnt++; return; } mutex_lock(&prepare_lock); } WARN_ON_ONCE(prepare_owner != NULL); WARN_ON_ONCE(prepare_refcnt != 0); prepare_owner = current; prepare_refcnt = 1; } static void clk_prepare_unlock(void) { WARN_ON_ONCE(prepare_owner != current); WARN_ON_ONCE(prepare_refcnt == 0); if (--prepare_refcnt) return; prepare_owner = NULL; mutex_unlock(&prepare_lock); } static unsigned long clk_enable_lock(void) { unsigned long flags; if (!spin_trylock_irqsave(&enable_lock, flags)) { if (enable_owner == current) { enable_refcnt++; return flags; } spin_lock_irqsave(&enable_lock, flags); } WARN_ON_ONCE(enable_owner != NULL); WARN_ON_ONCE(enable_refcnt != 0); enable_owner = current; enable_refcnt = 1; return flags; } static void clk_enable_unlock(unsigned long flags) { WARN_ON_ONCE(enable_owner != current); WARN_ON_ONCE(enable_refcnt == 0); if (--enable_refcnt) return; enable_owner = NULL; spin_unlock_irqrestore(&enable_lock, flags); } /*** debugfs support ***/ #ifdef CONFIG_COMMON_CLK_DEBUG #include <linux/debugfs.h> static struct dentry *rootdir; static struct dentry *orphandir; static int inited = 0; static void clk_summary_show_one(struct seq_file *s, struct clk *c, int level) { if (!c) return; seq_printf(s, "%*s%-*s %-11d %-12d %-10lu", level * 3 + 1, "", 30 - level * 3, c->name, c->enable_count, c->prepare_count, clk_get_rate(c)); seq_printf(s, "\n"); } static void clk_summary_show_subtree(struct seq_file *s, struct clk *c, int level) { struct clk *child; if (!c) return; clk_summary_show_one(s, c, level); hlist_for_each_entry(child, &c->children, child_node) clk_summary_show_subtree(s, child, level + 1); } static int clk_summary_show(struct seq_file *s, void *data) { struct clk *c; seq_printf(s, " clock enable_cnt prepare_cnt rate\n"); seq_printf(s, "---------------------------------------------------------------------\n"); clk_prepare_lock(); hlist_for_each_entry(c, &clk_root_list, child_node) clk_summary_show_subtree(s, c, 0); hlist_for_each_entry(c, &clk_orphan_list, child_node) clk_summary_show_subtree(s, c, 0); clk_prepare_unlock(); return 0; } static int clk_summary_open(struct inode *inode, struct file *file) { return single_open(file, clk_summary_show, inode->i_private); } static const struct file_operations clk_summary_fops = { .open = clk_summary_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void clk_dump_one(struct seq_file *s, struct clk *c, int level) { if (!c) return; seq_printf(s, "\"%s\": { ", c->name); seq_printf(s, "\"enable_count\": %d,", c->enable_count); seq_printf(s, "\"prepare_count\": %d,", c->prepare_count); seq_printf(s, "\"rate\": %lu", clk_get_rate(c)); } static void clk_dump_subtree(struct seq_file *s, struct clk *c, int level) { struct clk *child; if (!c) return; clk_dump_one(s, c, level); hlist_for_each_entry(child, &c->children, child_node) { seq_printf(s, ","); clk_dump_subtree(s, child, level + 1); } seq_printf(s, "}"); } static int clk_dump(struct seq_file *s, void *data) { struct clk *c; bool first_node = true; seq_printf(s, "{"); clk_prepare_lock(); hlist_for_each_entry(c, &clk_root_list, child_node) { if (!first_node) seq_printf(s, ","); first_node = false; clk_dump_subtree(s, c, 0); } hlist_for_each_entry(c, &clk_orphan_list, child_node) { seq_printf(s, ","); clk_dump_subtree(s, c, 0); } clk_prepare_unlock(); seq_printf(s, "}"); return 0; } static int clk_dump_open(struct inode *inode, struct file *file) { return single_open(file, clk_dump, inode->i_private); } static const struct file_operations clk_dump_fops = { .open = clk_dump_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /* caller must hold prepare_lock */ static int clk_debug_create_one(struct clk *clk, struct dentry *pdentry) { struct dentry *d; int ret = -ENOMEM; if (!clk || !pdentry) { ret = -EINVAL; goto out; } d = debugfs_create_dir(clk->name, pdentry); if (!d) goto out; clk->dentry = d; d = debugfs_create_u32("clk_rate", S_IRUGO, clk->dentry, (u32 *)&clk->rate); if (!d) goto err_out; d = debugfs_create_x32("clk_flags", S_IRUGO, clk->dentry, (u32 *)&clk->flags); if (!d) goto err_out; d = debugfs_create_u32("clk_prepare_count", S_IRUGO, clk->dentry, (u32 *)&clk->prepare_count); if (!d) goto err_out; d = debugfs_create_u32("clk_enable_count", S_IRUGO, clk->dentry, (u32 *)&clk->enable_count); if (!d) goto err_out; d = debugfs_create_u32("clk_notifier_count", S_IRUGO, clk->dentry, (u32 *)&clk->notifier_count); if (!d) goto err_out; ret = 0; goto out; err_out: debugfs_remove(clk->dentry); out: return ret; } /* caller must hold prepare_lock */ static int clk_debug_create_subtree(struct clk *clk, struct dentry *pdentry) { struct clk *child; int ret = -EINVAL;; if (!clk || !pdentry) goto out; ret = clk_debug_create_one(clk, pdentry); if (ret) goto out; hlist_for_each_entry(child, &clk->children, child_node) clk_debug_create_subtree(child, clk->dentry); ret = 0; out: return ret; } /** * clk_debug_register - add a clk node to the debugfs clk tree * @clk: the clk being added to the debugfs clk tree * * Dynamically adds a clk to the debugfs clk tree if debugfs has been * initialized. Otherwise it bails out early since the debugfs clk tree * will be created lazily by clk_debug_init as part of a late_initcall. * * Caller must hold prepare_lock. Only clk_init calls this function (so * far) so this is taken care. */ static int clk_debug_register(struct clk *clk) { struct clk *parent; struct dentry *pdentry; int ret = 0; if (!inited) goto out; parent = clk->parent; /* * Check to see if a clk is a root clk. Also check that it is * safe to add this clk to debugfs */ if (!parent) if (clk->flags & CLK_IS_ROOT) pdentry = rootdir; else pdentry = orphandir; else if (parent->dentry) pdentry = parent->dentry; else goto out; ret = clk_debug_create_subtree(clk, pdentry); out: return ret; } /** * clk_debug_reparent - reparent clk node in the debugfs clk tree * @clk: the clk being reparented * @new_parent: the new clk parent, may be NULL * * Rename clk entry in the debugfs clk tree if debugfs has been * initialized. Otherwise it bails out early since the debugfs clk tree * will be created lazily by clk_debug_init as part of a late_initcall. * * Caller must hold prepare_lock. */ static void clk_debug_reparent(struct clk *clk, struct clk *new_parent) { struct dentry *d; struct dentry *new_parent_d; if (!inited) return; if (new_parent) new_parent_d = new_parent->dentry; else new_parent_d = orphandir; d = debugfs_rename(clk->dentry->d_parent, clk->dentry, new_parent_d, clk->name); if (d) clk->dentry = d; else pr_debug("%s: failed to rename debugfs entry for %s\n", __func__, clk->name); } /** * clk_debug_init - lazily create the debugfs clk tree visualization * * clks are often initialized very early during boot before memory can * be dynamically allocated and well before debugfs is setup. * clk_debug_init walks the clk tree hierarchy while holding * prepare_lock and creates the topology as part of a late_initcall, * thus insuring that clks initialized very early will still be * represented in the debugfs clk tree. This function should only be * called once at boot-time, and all other clks added dynamically will * be done so with clk_debug_register. */ static int __init clk_debug_init(void) { struct clk *clk; struct dentry *d; rootdir = debugfs_create_dir("clk", NULL); if (!rootdir) return -ENOMEM; d = debugfs_create_file("clk_summary", S_IRUGO, rootdir, NULL, &clk_summary_fops); if (!d) return -ENOMEM; d = debugfs_create_file("clk_dump", S_IRUGO, rootdir, NULL, &clk_dump_fops); if (!d) return -ENOMEM; orphandir = debugfs_create_dir("orphans", rootdir); if (!orphandir) return -ENOMEM; clk_prepare_lock(); hlist_for_each_entry(clk, &clk_root_list, child_node) clk_debug_create_subtree(clk, rootdir); hlist_for_each_entry(clk, &clk_orphan_list, child_node) clk_debug_create_subtree(clk, orphandir); inited = 1; clk_prepare_unlock(); return 0; } late_initcall(clk_debug_init); #else static inline int clk_debug_register(struct clk *clk) { return 0; } static inline void clk_debug_reparent(struct clk *clk, struct clk *new_parent) { } #endif /* caller must hold prepare_lock */ static void clk_unprepare_unused_subtree(struct clk *clk) { struct clk *child; if (!clk) return; hlist_for_each_entry(child, &clk->children, child_node) clk_unprepare_unused_subtree(child); if (clk->prepare_count) return; if (clk->flags & CLK_IGNORE_UNUSED) return; if (__clk_is_prepared(clk)) { if (clk->ops->unprepare_unused) clk->ops->unprepare_unused(clk->hw); else if (clk->ops->unprepare) clk->ops->unprepare(clk->hw); } } /* caller must hold prepare_lock */ static void clk_disable_unused_subtree(struct clk *clk) { struct clk *child; unsigned long flags; if (!clk) goto out; hlist_for_each_entry(child, &clk->children, child_node) clk_disable_unused_subtree(child); flags = clk_enable_lock(); if (clk->enable_count) goto unlock_out; if (clk->flags & CLK_IGNORE_UNUSED) goto unlock_out; /* * some gate clocks have special needs during the disable-unused * sequence. call .disable_unused if available, otherwise fall * back to .disable */ if (__clk_is_enabled(clk)) { if (clk->ops->disable_unused) clk->ops->disable_unused(clk->hw); else if (clk->ops->disable) clk->ops->disable(clk->hw); } unlock_out: clk_enable_unlock(flags); out: return; } static bool clk_ignore_unused; static int __init clk_ignore_unused_setup(char *__unused) { clk_ignore_unused = true; return 1; } __setup("clk_ignore_unused", clk_ignore_unused_setup); static int clk_disable_unused(void) { struct clk *clk; if (clk_ignore_unused) { pr_warn("clk: Not disabling unused clocks\n"); return 0; } clk_prepare_lock(); hlist_for_each_entry(clk, &clk_root_list, child_node) clk_disable_unused_subtree(clk); hlist_for_each_entry(clk, &clk_orphan_list, child_node) clk_disable_unused_subtree(clk); hlist_for_each_entry(clk, &clk_root_list, child_node) clk_unprepare_unused_subtree(clk); hlist_for_each_entry(clk, &clk_orphan_list, child_node) clk_unprepare_unused_subtree(clk); clk_prepare_unlock(); return 0; } late_initcall_sync(clk_disable_unused); /*** helper functions ***/ const char *__clk_get_name(struct clk *clk) { return !clk ? NULL : clk->name; } EXPORT_SYMBOL_GPL(__clk_get_name); struct clk_hw *__clk_get_hw(struct clk *clk) { return !clk ? NULL : clk->hw; } u8 __clk_get_num_parents(struct clk *clk) { return !clk ? 0 : clk->num_parents; } struct clk *__clk_get_parent(struct clk *clk) { return !clk ? NULL : clk->parent; } struct clk *clk_get_parent_by_index(struct clk *clk, u8 index) { if (!clk || index >= clk->num_parents) return NULL; else if (!clk->parents) return __clk_lookup(clk->parent_names[index]); else if (!clk->parents[index]) return clk->parents[index] = __clk_lookup(clk->parent_names[index]); else return clk->parents[index]; } unsigned int __clk_get_enable_count(struct clk *clk) { return !clk ? 0 : clk->enable_count; } unsigned int __clk_get_prepare_count(struct clk *clk) { return !clk ? 0 : clk->prepare_count; } unsigned long __clk_get_rate(struct clk *clk) { unsigned long ret; if (!clk) { ret = 0; goto out; } ret = clk->rate; if (clk->flags & CLK_IS_ROOT) goto out; if (!clk->parent) ret = 0; out: return ret; } unsigned long __clk_get_flags(struct clk *clk) { return !clk ? 0 : clk->flags; } EXPORT_SYMBOL_GPL(__clk_get_flags); bool __clk_is_prepared(struct clk *clk) { int ret; if (!clk) return false; /* * .is_prepared is optional for clocks that can prepare * fall back to software usage counter if it is missing */ if (!clk->ops->is_prepared) { ret = clk->prepare_count ? 1 : 0; goto out; } ret = clk->ops->is_prepared(clk->hw); out: return !!ret; } bool __clk_is_enabled(struct clk *clk) { int ret; if (!clk) return false; /* * .is_enabled is only mandatory for clocks that gate * fall back to software usage counter if .is_enabled is missing */ if (!clk->ops->is_enabled) { ret = clk->enable_count ? 1 : 0; goto out; } ret = clk->ops->is_enabled(clk->hw); out: return !!ret; } static struct clk *__clk_lookup_subtree(const char *name, struct clk *clk) { struct clk *child; struct clk *ret; if (!strcmp(clk->name, name)) return clk; hlist_for_each_entry(child, &clk->children, child_node) { ret = __clk_lookup_subtree(name, child); if (ret) return ret; } return NULL; } struct clk *__clk_lookup(const char *name) { struct clk *root_clk; struct clk *ret; if (!name) return NULL; /* search the 'proper' clk tree first */ hlist_for_each_entry(root_clk, &clk_root_list, child_node) { ret = __clk_lookup_subtree(name, root_clk); if (ret) return ret; } /* if not found, then search the orphan tree */ hlist_for_each_entry(root_clk, &clk_orphan_list, child_node) { ret = __clk_lookup_subtree(name, root_clk); if (ret) return ret; } return NULL; } /* * Helper for finding best parent to provide a given frequency. This can be used * directly as a determine_rate callback (e.g. for a mux), or from a more * complex clock that may combine a mux with other operations. */ long __clk_mux_determine_rate(struct clk_hw *hw, unsigned long rate, unsigned long *best_parent_rate, struct clk **best_parent_p) { struct clk *clk = hw->clk, *parent, *best_parent = NULL; int i, num_parents; unsigned long parent_rate, best = 0; /* if NO_REPARENT flag set, pass through to current parent */ if (clk->flags & CLK_SET_RATE_NO_REPARENT) { parent = clk->parent; if (clk->flags & CLK_SET_RATE_PARENT) best = __clk_round_rate(parent, rate); else if (parent) best = __clk_get_rate(parent); else best = __clk_get_rate(clk); goto out; } /* find the parent that can provide the fastest rate <= rate */ num_parents = clk->num_parents; for (i = 0; i < num_parents; i++) { parent = clk_get_parent_by_index(clk, i); if (!parent) continue; if (clk->flags & CLK_SET_RATE_PARENT) parent_rate = __clk_round_rate(parent, rate); else parent_rate = __clk_get_rate(parent); if (parent_rate <= rate && parent_rate > best) { best_parent = parent; best = parent_rate; } } out: if (best_parent) *best_parent_p = best_parent; *best_parent_rate = best; return best; } /*** clk api ***/ void __clk_unprepare(struct clk *clk) { if (!clk) return; if (WARN_ON(clk->prepare_count == 0)) return; if (--clk->prepare_count > 0) return; WARN_ON(clk->enable_count > 0); if (clk->ops->unprepare) clk->ops->unprepare(clk->hw); __clk_unprepare(clk->parent); } /** * clk_unprepare - undo preparation of a clock source * @clk: the clk being unprepared * * clk_unprepare may sleep, which differentiates it from clk_disable. In a * simple case, clk_unprepare can be used instead of clk_disable to gate a clk * if the operation may sleep. One example is a clk which is accessed over * I2c. In the complex case a clk gate operation may require a fast and a slow * part. It is this reason that clk_unprepare and clk_disable are not mutually * exclusive. In fact clk_disable must be called before clk_unprepare. */ void clk_unprepare(struct clk *clk) { clk_prepare_lock(); __clk_unprepare(clk); clk_prepare_unlock(); } EXPORT_SYMBOL_GPL(clk_unprepare); int __clk_prepare(struct clk *clk) { int ret = 0; if (!clk) return 0; if (clk->prepare_count == 0) { ret = __clk_prepare(clk->parent); if (ret) return ret; if (clk->ops->prepare) { ret = clk->ops->prepare(clk->hw); if (ret) { __clk_unprepare(clk->parent); return ret; } } } clk->prepare_count++; return 0; } /** * clk_prepare - prepare a clock source * @clk: the clk being prepared * * clk_prepare may sleep, which differentiates it from clk_enable. In a simple * case, clk_prepare can be used instead of clk_enable to ungate a clk if the * operation may sleep. One example is a clk which is accessed over I2c. In * the complex case a clk ungate operation may require a fast and a slow part. * It is this reason that clk_prepare and clk_enable are not mutually * exclusive. In fact clk_prepare must be called before clk_enable. * Returns 0 on success, -EERROR otherwise. */ int clk_prepare(struct clk *clk) { int ret; clk_prepare_lock(); ret = __clk_prepare(clk); clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_prepare); static void __clk_disable(struct clk *clk) { if (!clk) return; if (WARN_ON(IS_ERR(clk))) return; if (WARN_ON(clk->enable_count == 0)) return; if (--clk->enable_count > 0) return; if (clk->ops->disable) clk->ops->disable(clk->hw); __clk_disable(clk->parent); } /** * clk_disable - gate a clock * @clk: the clk being gated * * clk_disable must not sleep, which differentiates it from clk_unprepare. In * a simple case, clk_disable can be used instead of clk_unprepare to gate a * clk if the operation is fast and will never sleep. One example is a * SoC-internal clk which is controlled via simple register writes. In the * complex case a clk gate operation may require a fast and a slow part. It is * this reason that clk_unprepare and clk_disable are not mutually exclusive. * In fact clk_disable must be called before clk_unprepare. */ void clk_disable(struct clk *clk) { unsigned long flags; flags = clk_enable_lock(); __clk_disable(clk); clk_enable_unlock(flags); } EXPORT_SYMBOL_GPL(clk_disable); static int __clk_enable(struct clk *clk) { int ret = 0; if (!clk) return 0; if (WARN_ON(clk->prepare_count == 0)) return -ESHUTDOWN; if (clk->enable_count == 0) { ret = __clk_enable(clk->parent); if (ret) return ret; if (clk->ops->enable) { ret = clk->ops->enable(clk->hw); if (ret) { __clk_disable(clk->parent); return ret; } } } clk->enable_count++; return 0; } /** * clk_enable - ungate a clock * @clk: the clk being ungated * * clk_enable must not sleep, which differentiates it from clk_prepare. In a * simple case, clk_enable can be used instead of clk_prepare to ungate a clk * if the operation will never sleep. One example is a SoC-internal clk which * is controlled via simple register writes. In the complex case a clk ungate * operation may require a fast and a slow part. It is this reason that * clk_enable and clk_prepare are not mutually exclusive. In fact clk_prepare * must be called before clk_enable. Returns 0 on success, -EERROR * otherwise. */ int clk_enable(struct clk *clk) { unsigned long flags; int ret; flags = clk_enable_lock(); ret = __clk_enable(clk); clk_enable_unlock(flags); return ret; } EXPORT_SYMBOL_GPL(clk_enable); /** * __clk_round_rate - round the given rate for a clk * @clk: round the rate of this clock * @rate: the rate which is to be rounded * * Caller must hold prepare_lock. Useful for clk_ops such as .set_rate */ unsigned long __clk_round_rate(struct clk *clk, unsigned long rate) { unsigned long parent_rate = 0; struct clk *parent; if (!clk) return 0; parent = clk->parent; if (parent) parent_rate = parent->rate; if (clk->ops->determine_rate) return clk->ops->determine_rate(clk->hw, rate, &parent_rate, &parent); else if (clk->ops->round_rate) return clk->ops->round_rate(clk->hw, rate, &parent_rate); else if (clk->flags & CLK_SET_RATE_PARENT) return __clk_round_rate(clk->parent, rate); else return clk->rate; } /** * clk_round_rate - round the given rate for a clk * @clk: the clk for which we are rounding a rate * @rate: the rate which is to be rounded * * Takes in a rate as input and rounds it to a rate that the clk can actually * use which is then returned. If clk doesn't support round_rate operation * then the parent rate is returned. */ long clk_round_rate(struct clk *clk, unsigned long rate) { unsigned long ret; clk_prepare_lock(); ret = __clk_round_rate(clk, rate); clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_round_rate); /** * __clk_notify - call clk notifier chain * @clk: struct clk * that is changing rate * @msg: clk notifier type (see include/linux/clk.h) * @old_rate: old clk rate * @new_rate: new clk rate * * Triggers a notifier call chain on the clk rate-change notification * for 'clk'. Passes a pointer to the struct clk and the previous * and current rates to the notifier callback. Intended to be called by * internal clock code only. Returns NOTIFY_DONE from the last driver * called if all went well, or NOTIFY_STOP or NOTIFY_BAD immediately if * a driver returns that. */ static int __clk_notify(struct clk *clk, unsigned long msg, unsigned long old_rate, unsigned long new_rate) { struct clk_notifier *cn; struct clk_notifier_data cnd; int ret = NOTIFY_DONE; cnd.clk = clk; cnd.old_rate = old_rate; cnd.new_rate = new_rate; list_for_each_entry(cn, &clk_notifier_list, node) { if (cn->clk == clk) { ret = srcu_notifier_call_chain(&cn->notifier_head, msg, &cnd); break; } } return ret; } /** * __clk_recalc_rates * @clk: first clk in the subtree * @msg: notification type (see include/linux/clk.h) * * Walks the subtree of clks starting with clk and recalculates rates as it * goes. Note that if a clk does not implement the .recalc_rate callback then * it is assumed that the clock will take on the rate of its parent. * * clk_recalc_rates also propagates the POST_RATE_CHANGE notification, * if necessary. * * Caller must hold prepare_lock. */ static void __clk_recalc_rates(struct clk *clk, unsigned long msg) { unsigned long old_rate; unsigned long parent_rate = 0; struct clk *child; old_rate = clk->rate; if (clk->parent) parent_rate = clk->parent->rate; if (clk->ops->recalc_rate) clk->rate = clk->ops->recalc_rate(clk->hw, parent_rate); else clk->rate = parent_rate; /* * ignore NOTIFY_STOP and NOTIFY_BAD return values for POST_RATE_CHANGE * & ABORT_RATE_CHANGE notifiers */ if (clk->notifier_count && msg) __clk_notify(clk, msg, old_rate, clk->rate); hlist_for_each_entry(child, &clk->children, child_node) __clk_recalc_rates(child, msg); } /** * clk_get_rate - return the rate of clk * @clk: the clk whose rate is being returned * * Simply returns the cached rate of the clk, unless CLK_GET_RATE_NOCACHE flag * is set, which means a recalc_rate will be issued. * If clk is NULL then returns 0. */ unsigned long clk_get_rate(struct clk *clk) { unsigned long rate; clk_prepare_lock(); if (clk && (clk->flags & CLK_GET_RATE_NOCACHE)) __clk_recalc_rates(clk, 0); rate = __clk_get_rate(clk); clk_prepare_unlock(); return rate; } EXPORT_SYMBOL_GPL(clk_get_rate); static int clk_fetch_parent_index(struct clk *clk, struct clk *parent) { int i; if (!clk->parents) { clk->parents = kcalloc(clk->num_parents, sizeof(struct clk *), GFP_KERNEL); if (!clk->parents) return -ENOMEM; } /* * find index of new parent clock using cached parent ptrs, * or if not yet cached, use string name comparison and cache * them now to avoid future calls to __clk_lookup. */ for (i = 0; i < clk->num_parents; i++) { if (clk->parents[i] == parent) return i; if (clk->parents[i]) continue; if (!strcmp(clk->parent_names[i], parent->name)) { clk->parents[i] = __clk_lookup(parent->name); return i; } } return -EINVAL; } static void clk_reparent(struct clk *clk, struct clk *new_parent) { hlist_del(&clk->child_node); if (new_parent) { /* avoid duplicate POST_RATE_CHANGE notifications */ if (new_parent->new_child == clk) new_parent->new_child = NULL; hlist_add_head(&clk->child_node, &new_parent->children); } else { hlist_add_head(&clk->child_node, &clk_orphan_list); } clk->parent = new_parent; } static int __clk_set_parent(struct clk *clk, struct clk *parent, u8 p_index) { unsigned long flags; int ret = 0; struct clk *old_parent = clk->parent; /* * Migrate prepare state between parents and prevent race with * clk_enable(). * * If the clock is not prepared, then a race with * clk_enable/disable() is impossible since we already have the * prepare lock (future calls to clk_enable() need to be preceded by * a clk_prepare()). * * If the clock is prepared, migrate the prepared state to the new * parent and also protect against a race with clk_enable() by * forcing the clock and the new parent on. This ensures that all * future calls to clk_enable() are practically NOPs with respect to * hardware and software states. * * See also: Comment for clk_set_parent() below. */ if (clk->prepare_count) { __clk_prepare(parent); clk_enable(parent); clk_enable(clk); } /* update the clk tree topology */ flags = clk_enable_lock(); clk_reparent(clk, parent); clk_enable_unlock(flags); /* change clock input source */ if (parent && clk->ops->set_parent) ret = clk->ops->set_parent(clk->hw, p_index); if (ret) { flags = clk_enable_lock(); clk_reparent(clk, old_parent); clk_enable_unlock(flags); if (clk->prepare_count) { clk_disable(clk); clk_disable(parent); __clk_unprepare(parent); } return ret; } /* * Finish the migration of prepare state and undo the changes done * for preventing a race with clk_enable(). */ if (clk->prepare_count) { clk_disable(clk); clk_disable(old_parent); __clk_unprepare(old_parent); } /* update debugfs with new clk tree topology */ clk_debug_reparent(clk, parent); return 0; } /** * __clk_speculate_rates * @clk: first clk in the subtree * @parent_rate: the "future" rate of clk's parent * * Walks the subtree of clks starting with clk, speculating rates as it * goes and firing off PRE_RATE_CHANGE notifications as necessary. * * Unlike clk_recalc_rates, clk_speculate_rates exists only for sending * pre-rate change notifications and returns early if no clks in the * subtree have subscribed to the notifications. Note that if a clk does not * implement the .recalc_rate callback then it is assumed that the clock will * take on the rate of its parent. * * Caller must hold prepare_lock. */ static int __clk_speculate_rates(struct clk *clk, unsigned long parent_rate) { struct clk *child; unsigned long new_rate; int ret = NOTIFY_DONE; if (clk->ops->recalc_rate) new_rate = clk->ops->recalc_rate(clk->hw, parent_rate); else new_rate = parent_rate; /* abort rate change if a driver returns NOTIFY_BAD or NOTIFY_STOP */ if (clk->notifier_count) ret = __clk_notify(clk, PRE_RATE_CHANGE, clk->rate, new_rate); if (ret & NOTIFY_STOP_MASK) goto out; hlist_for_each_entry(child, &clk->children, child_node) { ret = __clk_speculate_rates(child, new_rate); if (ret & NOTIFY_STOP_MASK) break; } out: return ret; } static void clk_calc_subtree(struct clk *clk, unsigned long new_rate, struct clk *new_parent, u8 p_index) { struct clk *child; clk->new_rate = new_rate; clk->new_parent = new_parent; clk->new_parent_index = p_index; /* include clk in new parent's PRE_RATE_CHANGE notifications */ clk->new_child = NULL; if (new_parent && new_parent != clk->parent) new_parent->new_child = clk; hlist_for_each_entry(child, &clk->children, child_node) { if (child->ops->recalc_rate) child->new_rate = child->ops->recalc_rate(child->hw, new_rate); else child->new_rate = new_rate; clk_calc_subtree(child, child->new_rate, NULL, 0); } } /* * calculate the new rates returning the topmost clock that has to be * changed. */ static struct clk *clk_calc_new_rates(struct clk *clk, unsigned long rate) { struct clk *top = clk; struct clk *old_parent, *parent; unsigned long best_parent_rate = 0; unsigned long new_rate; int p_index = 0; /* sanity */ if (IS_ERR_OR_NULL(clk)) return NULL; /* save parent rate, if it exists */ parent = old_parent = clk->parent; if (parent) best_parent_rate = parent->rate; /* find the closest rate and parent clk/rate */ if (clk->ops->determine_rate) { new_rate = clk->ops->determine_rate(clk->hw, rate, &best_parent_rate, &parent); } else if (clk->ops->round_rate) { new_rate = clk->ops->round_rate(clk->hw, rate, &best_parent_rate); } else if (!parent || !(clk->flags & CLK_SET_RATE_PARENT)) { /* pass-through clock without adjustable parent */ clk->new_rate = clk->rate; return NULL; } else { /* pass-through clock with adjustable parent */ top = clk_calc_new_rates(parent, rate); new_rate = parent->new_rate; goto out; } /* some clocks must be gated to change parent */ if (parent != old_parent && (clk->flags & CLK_SET_PARENT_GATE) && clk->prepare_count) { pr_debug("%s: %s not gated but wants to reparent\n", __func__, clk->name); return NULL; } /* try finding the new parent index */ if (parent) { p_index = clk_fetch_parent_index(clk, parent); if (p_index < 0) { pr_debug("%s: clk %s can not be parent of clk %s\n", __func__, parent->name, clk->name); return NULL; } } if ((clk->flags & CLK_SET_RATE_PARENT) && parent && best_parent_rate != parent->rate) top = clk_calc_new_rates(parent, best_parent_rate); out: clk_calc_subtree(clk, new_rate, parent, p_index); return top; } /* * Notify about rate changes in a subtree. Always walk down the whole tree * so that in case of an error we can walk down the whole tree again and * abort the change. */ static struct clk *clk_propagate_rate_change(struct clk *clk, unsigned long event) { struct clk *child, *tmp_clk, *fail_clk = NULL; int ret = NOTIFY_DONE; if (clk->rate == clk->new_rate) return NULL; if (clk->notifier_count) { ret = __clk_notify(clk, event, clk->rate, clk->new_rate); if (ret & NOTIFY_STOP_MASK) fail_clk = clk; } hlist_for_each_entry(child, &clk->children, child_node) { /* Skip children who will be reparented to another clock */ if (child->new_parent && child->new_parent != clk) continue; tmp_clk = clk_propagate_rate_change(child, event); if (tmp_clk) fail_clk = tmp_clk; } /* handle the new child who might not be in clk->children yet */ if (clk->new_child) { tmp_clk = clk_propagate_rate_change(clk->new_child, event); if (tmp_clk) fail_clk = tmp_clk; } return fail_clk; } /* * walk down a subtree and set the new rates notifying the rate * change on the way */ static void clk_change_rate(struct clk *clk) { struct clk *child; unsigned long old_rate; unsigned long best_parent_rate = 0; old_rate = clk->rate; /* set parent */ if (clk->new_parent && clk->new_parent != clk->parent) __clk_set_parent(clk, clk->new_parent, clk->new_parent_index); if (clk->parent) best_parent_rate = clk->parent->rate; if (clk->ops->set_rate) clk->ops->set_rate(clk->hw, clk->new_rate, best_parent_rate); if (clk->ops->recalc_rate) clk->rate = clk->ops->recalc_rate(clk->hw, best_parent_rate); else clk->rate = best_parent_rate; if (clk->notifier_count && old_rate != clk->rate) __clk_notify(clk, POST_RATE_CHANGE, old_rate, clk->rate); hlist_for_each_entry(child, &clk->children, child_node) { /* Skip children who will be reparented to another clock */ if (child->new_parent && child->new_parent != clk) continue; clk_change_rate(child); } /* handle the new child who might not be in clk->children yet */ if (clk->new_child) clk_change_rate(clk->new_child); } /** * clk_set_rate - specify a new rate for clk * @clk: the clk whose rate is being changed * @rate: the new rate for clk * * In the simplest case clk_set_rate will only adjust the rate of clk. * * Setting the CLK_SET_RATE_PARENT flag allows the rate change operation to * propagate up to clk's parent; whether or not this happens depends on the * outcome of clk's .round_rate implementation. If *parent_rate is unchanged * after calling .round_rate then upstream parent propagation is ignored. If * *parent_rate comes back with a new rate for clk's parent then we propagate * up to clk's parent and set its rate. Upward propagation will continue * until either a clk does not support the CLK_SET_RATE_PARENT flag or * .round_rate stops requesting changes to clk's parent_rate. * * Rate changes are accomplished via tree traversal that also recalculates the * rates for the clocks and fires off POST_RATE_CHANGE notifiers. * * Returns 0 on success, -EERROR otherwise. */ int clk_set_rate(struct clk *clk, unsigned long rate) { struct clk *top, *fail_clk; int ret = 0; if (!clk) return 0; /* prevent racing with updates to the clock topology */ clk_prepare_lock(); /* bail early if nothing to do */ if (rate == clk_get_rate(clk)) goto out; if ((clk->flags & CLK_SET_RATE_GATE) && clk->prepare_count) { ret = -EBUSY; goto out; } /* calculate new rates and get the topmost changed clock */ top = clk_calc_new_rates(clk, rate); if (!top) { ret = -EINVAL; goto out; } /* notify that we are about to change rates */ fail_clk = clk_propagate_rate_change(top, PRE_RATE_CHANGE); if (fail_clk) { pr_warn("%s: failed to set %s rate\n", __func__, fail_clk->name); clk_propagate_rate_change(top, ABORT_RATE_CHANGE); ret = -EBUSY; goto out; } /* change the rates */ clk_change_rate(top); out: clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_set_rate); /** * clk_get_parent - return the parent of a clk * @clk: the clk whose parent gets returned * * Simply returns clk->parent. Returns NULL if clk is NULL. */ struct clk *clk_get_parent(struct clk *clk) { struct clk *parent; clk_prepare_lock(); parent = __clk_get_parent(clk); clk_prepare_unlock(); return parent; } EXPORT_SYMBOL_GPL(clk_get_parent); /* * .get_parent is mandatory for clocks with multiple possible parents. It is * optional for single-parent clocks. Always call .get_parent if it is * available and WARN if it is missing for multi-parent clocks. * * For single-parent clocks without .get_parent, first check to see if the * .parents array exists, and if so use it to avoid an expensive tree * traversal. If .parents does not exist then walk the tree with __clk_lookup. */ static struct clk *__clk_init_parent(struct clk *clk) { struct clk *ret = NULL; u8 index; /* handle the trivial cases */ if (!clk->num_parents) goto out; if (clk->num_parents == 1) { if (IS_ERR_OR_NULL(clk->parent)) ret = clk->parent = __clk_lookup(clk->parent_names[0]); ret = clk->parent; goto out; } if (!clk->ops->get_parent) { WARN(!clk->ops->get_parent, "%s: multi-parent clocks must implement .get_parent\n", __func__); goto out; }; /* * Do our best to cache parent clocks in clk->parents. This prevents * unnecessary and expensive calls to __clk_lookup. We don't set * clk->parent here; that is done by the calling function */ index = clk->ops->get_parent(clk->hw); if (!clk->parents) clk->parents = kcalloc(clk->num_parents, sizeof(struct clk *), GFP_KERNEL); ret = clk_get_parent_by_index(clk, index); out: return ret; } void __clk_reparent(struct clk *clk, struct clk *new_parent) { clk_reparent(clk, new_parent); clk_debug_reparent(clk, new_parent); __clk_recalc_rates(clk, POST_RATE_CHANGE); } /** * clk_set_parent - switch the parent of a mux clk * @clk: the mux clk whose input we are switching * @parent: the new input to clk * * Re-parent clk to use parent as its new input source. If clk is in * prepared state, the clk will get enabled for the duration of this call. If * that's not acceptable for a specific clk (Eg: the consumer can't handle * that, the reparenting is glitchy in hardware, etc), use the * CLK_SET_PARENT_GATE flag to allow reparenting only when clk is unprepared. * * After successfully changing clk's parent clk_set_parent will update the * clk topology, sysfs topology and propagate rate recalculation via * __clk_recalc_rates. * * Returns 0 on success, -EERROR otherwise. */ int clk_set_parent(struct clk *clk, struct clk *parent) { int ret = 0; int p_index = 0; unsigned long p_rate = 0; if (!clk) return 0; if (!clk->ops) return -EINVAL; /* verify ops for for multi-parent clks */ if ((clk->num_parents > 1) && (!clk->ops->set_parent)) return -ENOSYS; /* prevent racing with updates to the clock topology */ clk_prepare_lock(); if (clk->parent == parent) goto out; /* check that we are allowed to re-parent if the clock is in use */ if ((clk->flags & CLK_SET_PARENT_GATE) && clk->prepare_count) { ret = -EBUSY; goto out; } /* try finding the new parent index */ if (parent) { p_index = clk_fetch_parent_index(clk, parent); p_rate = parent->rate; if (p_index < 0) { pr_debug("%s: clk %s can not be parent of clk %s\n", __func__, parent->name, clk->name); ret = p_index; goto out; } } /* propagate PRE_RATE_CHANGE notifications */ ret = __clk_speculate_rates(clk, p_rate); /* abort if a driver objects */ if (ret & NOTIFY_STOP_MASK) goto out; /* do the re-parent */ ret = __clk_set_parent(clk, parent, p_index); /* propagate rate recalculation accordingly */ if (ret) __clk_recalc_rates(clk, ABORT_RATE_CHANGE); else __clk_recalc_rates(clk, POST_RATE_CHANGE); out: clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_set_parent); /** * __clk_init - initialize the data structures in a struct clk * @dev: device initializing this clk, placeholder for now * @clk: clk being initialized * * Initializes the lists in struct clk, queries the hardware for the * parent and rate and sets them both. */ int __clk_init(struct device *dev, struct clk *clk) { int i, ret = 0; struct clk *orphan; struct hlist_node *tmp2; if (!clk) return -EINVAL; clk_prepare_lock(); /* check to see if a clock with this name is already registered */ if (__clk_lookup(clk->name)) { pr_debug("%s: clk %s already initialized\n", __func__, clk->name); ret = -EEXIST; goto out; } /* check that clk_ops are sane. See Documentation/clk.txt */ if (clk->ops->set_rate && !((clk->ops->round_rate || clk->ops->determine_rate) && clk->ops->recalc_rate)) { pr_warning("%s: %s must implement .round_rate or .determine_rate in addition to .recalc_rate\n", __func__, clk->name); ret = -EINVAL; goto out; } if (clk->ops->set_parent && !clk->ops->get_parent) { pr_warning("%s: %s must implement .get_parent & .set_parent\n", __func__, clk->name); ret = -EINVAL; goto out; } /* throw a WARN if any entries in parent_names are NULL */ for (i = 0; i < clk->num_parents; i++) WARN(!clk->parent_names[i], "%s: invalid NULL in %s's .parent_names\n", __func__, clk->name); /* * Allocate an array of struct clk *'s to avoid unnecessary string * look-ups of clk's possible parents. This can fail for clocks passed * in to clk_init during early boot; thus any access to clk->parents[] * must always check for a NULL pointer and try to populate it if * necessary. * * If clk->parents is not NULL we skip this entire block. This allows * for clock drivers to statically initialize clk->parents. */ if (clk->num_parents > 1 && !clk->parents) { clk->parents = kcalloc(clk->num_parents, sizeof(struct clk *), GFP_KERNEL); /* * __clk_lookup returns NULL for parents that have not been * clk_init'd; thus any access to clk->parents[] must check * for a NULL pointer. We can always perform lazy lookups for * missing parents later on. */ if (clk->parents) for (i = 0; i < clk->num_parents; i++) clk->parents[i] = __clk_lookup(clk->parent_names[i]); } clk->parent = __clk_init_parent(clk); /* * Populate clk->parent if parent has already been __clk_init'd. If * parent has not yet been __clk_init'd then place clk in the orphan * list. If clk has set the CLK_IS_ROOT flag then place it in the root * clk list. * * Every time a new clk is clk_init'd then we walk the list of orphan * clocks and re-parent any that are children of the clock currently * being clk_init'd. */ if (clk->parent) hlist_add_head(&clk->child_node, &clk->parent->children); else if (clk->flags & CLK_IS_ROOT) hlist_add_head(&clk->child_node, &clk_root_list); else hlist_add_head(&clk->child_node, &clk_orphan_list); /* * Set clk's rate. The preferred method is to use .recalc_rate. For * simple clocks and lazy developers the default fallback is to use the * parent's rate. If a clock doesn't have a parent (or is orphaned) * then rate is set to zero. */ if (clk->ops->recalc_rate) clk->rate = clk->ops->recalc_rate(clk->hw, __clk_get_rate(clk->parent)); else if (clk->parent) clk->rate = clk->parent->rate; else clk->rate = 0; /* * walk the list of orphan clocks and reparent any that are children of * this clock */ hlist_for_each_entry_safe(orphan, tmp2, &clk_orphan_list, child_node) { if (orphan->num_parents && orphan->ops->get_parent) { i = orphan->ops->get_parent(orphan->hw); if (!strcmp(clk->name, orphan->parent_names[i])) __clk_reparent(orphan, clk); continue; } for (i = 0; i < orphan->num_parents; i++) if (!strcmp(clk->name, orphan->parent_names[i])) { __clk_reparent(orphan, clk); break; } } /* * optional platform-specific magic * * The .init callback is not used by any of the basic clock types, but * exists for weird hardware that must perform initialization magic. * Please consider other ways of solving initialization problems before * using this callback, as its use is discouraged. */ if (clk->ops->init) clk->ops->init(clk->hw); clk_debug_register(clk); out: clk_prepare_unlock(); return ret; } /** * __clk_register - register a clock and return a cookie. * * Same as clk_register, except that the .clk field inside hw shall point to a * preallocated (generally statically allocated) struct clk. None of the fields * of the struct clk need to be initialized. * * The data pointed to by .init and .clk field shall NOT be marked as init * data. * * __clk_register is only exposed via clk-private.h and is intended for use with * very large numbers of clocks that need to be statically initialized. It is * a layering violation to include clk-private.h from any code which implements * a clock's .ops; as such any statically initialized clock data MUST be in a * separate C file from the logic that implements its operations. Returns 0 * on success, otherwise an error code. */ struct clk *__clk_register(struct device *dev, struct clk_hw *hw) { int ret; struct clk *clk; clk = hw->clk; clk->name = hw->init->name; clk->ops = hw->init->ops; clk->hw = hw; clk->flags = hw->init->flags; clk->parent_names = hw->init->parent_names; clk->num_parents = hw->init->num_parents; ret = __clk_init(dev, clk); if (ret) return ERR_PTR(ret); return clk; } EXPORT_SYMBOL_GPL(__clk_register); /** * clk_register - allocate a new clock, register it and return an opaque cookie * @dev: device that is registering this clock * @hw: link to hardware-specific clock data * * clk_register is the primary interface for populating the clock tree with new * clock nodes. It returns a pointer to the newly allocated struct clk which * cannot be dereferenced by driver code but may be used in conjuction with the * rest of the clock API. In the event of an error clk_register will return an * error code; drivers must test for an error code after calling clk_register. */ struct clk *clk_register(struct device *dev, struct clk_hw *hw) { int i, ret; struct clk *clk; clk = kzalloc(sizeof(*clk), GFP_KERNEL); if (!clk) { pr_err("%s: could not allocate clk\n", __func__); ret = -ENOMEM; goto fail_out; } clk->name = kstrdup(hw->init->name, GFP_KERNEL); if (!clk->name) { pr_err("%s: could not allocate clk->name\n", __func__); ret = -ENOMEM; goto fail_name; } clk->ops = hw->init->ops; clk->hw = hw; clk->flags = hw->init->flags; clk->num_parents = hw->init->num_parents; hw->clk = clk; /* allocate local copy in case parent_names is __initdata */ clk->parent_names = kcalloc(clk->num_parents, sizeof(char *), GFP_KERNEL); if (!clk->parent_names) { pr_err("%s: could not allocate clk->parent_names\n", __func__); ret = -ENOMEM; goto fail_parent_names; } /* copy each string name in case parent_names is __initdata */ for (i = 0; i < clk->num_parents; i++) { clk->parent_names[i] = kstrdup(hw->init->parent_names[i], GFP_KERNEL); if (!clk->parent_names[i]) { pr_err("%s: could not copy parent_names\n", __func__); ret = -ENOMEM; goto fail_parent_names_copy; } } ret = __clk_init(dev, clk); if (!ret) return clk; fail_parent_names_copy: while (--i >= 0) kfree(clk->parent_names[i]); kfree(clk->parent_names); fail_parent_names: kfree(clk->name); fail_name: kfree(clk); fail_out: return ERR_PTR(ret); } EXPORT_SYMBOL_GPL(clk_register); /** * clk_unregister - unregister a currently registered clock * @clk: clock to unregister * * Currently unimplemented. */ void clk_unregister(struct clk *clk) {} EXPORT_SYMBOL_GPL(clk_unregister); static void devm_clk_release(struct device *dev, void *res) { clk_unregister(*(struct clk **)res); } /** * devm_clk_register - resource managed clk_register() * @dev: device that is registering this clock * @hw: link to hardware-specific clock data * * Managed clk_register(). Clocks returned from this function are * automatically clk_unregister()ed on driver detach. See clk_register() for * more information. */ struct clk *devm_clk_register(struct device *dev, struct clk_hw *hw) { struct clk *clk; struct clk **clkp; clkp = devres_alloc(devm_clk_release, sizeof(*clkp), GFP_KERNEL); if (!clkp) return ERR_PTR(-ENOMEM); clk = clk_register(dev, hw); if (!IS_ERR(clk)) { *clkp = clk; devres_add(dev, clkp); } else { devres_free(clkp); } return clk; } EXPORT_SYMBOL_GPL(devm_clk_register); static int devm_clk_match(struct device *dev, void *res, void *data) { struct clk *c = res; if (WARN_ON(!c)) return 0; return c == data; } /** * devm_clk_unregister - resource managed clk_unregister() * @clk: clock to unregister * * Deallocate a clock allocated with devm_clk_register(). Normally * this function will not need to be called and the resource management * code will ensure that the resource is freed. */ void devm_clk_unregister(struct device *dev, struct clk *clk) { WARN_ON(devres_release(dev, devm_clk_release, devm_clk_match, clk)); } EXPORT_SYMBOL_GPL(devm_clk_unregister); /*** clk rate change notifiers ***/ /** * clk_notifier_register - add a clk rate change notifier * @clk: struct clk * to watch * @nb: struct notifier_block * with callback info * * Request notification when clk's rate changes. This uses an SRCU * notifier because we want it to block and notifier unregistrations are * uncommon. The callbacks associated with the notifier must not * re-enter into the clk framework by calling any top-level clk APIs; * this will cause a nested prepare_lock mutex. * * Pre-change notifier callbacks will be passed the current, pre-change * rate of the clk via struct clk_notifier_data.old_rate. The new, * post-change rate of the clk is passed via struct * clk_notifier_data.new_rate. * * Post-change notifiers will pass the now-current, post-change rate of * the clk in both struct clk_notifier_data.old_rate and struct * clk_notifier_data.new_rate. * * Abort-change notifiers are effectively the opposite of pre-change * notifiers: the original pre-change clk rate is passed in via struct * clk_notifier_data.new_rate and the failed post-change rate is passed * in via struct clk_notifier_data.old_rate. * * clk_notifier_register() must be called from non-atomic context. * Returns -EINVAL if called with null arguments, -ENOMEM upon * allocation failure; otherwise, passes along the return value of * srcu_notifier_chain_register(). */ int clk_notifier_register(struct clk *clk, struct notifier_block *nb) { struct clk_notifier *cn; int ret = -ENOMEM; if (!clk || !nb) return -EINVAL; clk_prepare_lock(); /* search the list of notifiers for this clk */ list_for_each_entry(cn, &clk_notifier_list, node) if (cn->clk == clk) break; /* if clk wasn't in the notifier list, allocate new clk_notifier */ if (cn->clk != clk) { cn = kzalloc(sizeof(struct clk_notifier), GFP_KERNEL); if (!cn) goto out; cn->clk = clk; srcu_init_notifier_head(&cn->notifier_head); list_add(&cn->node, &clk_notifier_list); } ret = srcu_notifier_chain_register(&cn->notifier_head, nb); clk->notifier_count++; out: clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_notifier_register); /** * clk_notifier_unregister - remove a clk rate change notifier * @clk: struct clk * * @nb: struct notifier_block * with callback info * * Request no further notification for changes to 'clk' and frees memory * allocated in clk_notifier_register. * * Returns -EINVAL if called with null arguments; otherwise, passes * along the return value of srcu_notifier_chain_unregister(). */ int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb) { struct clk_notifier *cn = NULL; int ret = -EINVAL; if (!clk || !nb) return -EINVAL; clk_prepare_lock(); list_for_each_entry(cn, &clk_notifier_list, node) if (cn->clk == clk) break; if (cn->clk == clk) { ret = srcu_notifier_chain_unregister(&cn->notifier_head, nb); clk->notifier_count--; /* XXX the notifier code should handle this better */ if (!cn->notifier_head.head) { srcu_cleanup_notifier_head(&cn->notifier_head); list_del(&cn->node); kfree(cn); } } else { ret = -ENOENT; } clk_prepare_unlock(); return ret; } EXPORT_SYMBOL_GPL(clk_notifier_unregister); #ifdef CONFIG_OF /** * struct of_clk_provider - Clock provider registration structure * @link: Entry in global list of clock providers * @node: Pointer to device tree node of clock provider * @get: Get clock callback. Returns NULL or a struct clk for the * given clock specifier * @data: context pointer to be passed into @get callback */ struct of_clk_provider { struct list_head link; struct device_node *node; struct clk *(*get)(struct of_phandle_args *clkspec, void *data); void *data; }; extern struct of_device_id __clk_of_table[]; static const struct of_device_id __clk_of_table_sentinel __used __section(__clk_of_table_end); static LIST_HEAD(of_clk_providers); static DEFINE_MUTEX(of_clk_lock); struct clk *of_clk_src_simple_get(struct of_phandle_args *clkspec, void *data) { return data; } EXPORT_SYMBOL_GPL(of_clk_src_simple_get); struct clk *of_clk_src_onecell_get(struct of_phandle_args *clkspec, void *data) { struct clk_onecell_data *clk_data = data; unsigned int idx = clkspec->args[0]; if (idx >= clk_data->clk_num) { pr_err("%s: invalid clock index %d\n", __func__, idx); return ERR_PTR(-EINVAL); } return clk_data->clks[idx]; } EXPORT_SYMBOL_GPL(of_clk_src_onecell_get); /** * of_clk_add_provider() - Register a clock provider for a node * @np: Device node pointer associated with clock provider * @clk_src_get: callback for decoding clock * @data: context pointer for @clk_src_get callback. */ int of_clk_add_provider(struct device_node *np, struct clk *(*clk_src_get)(struct of_phandle_args *clkspec, void *data), void *data) { struct of_clk_provider *cp; cp = kzalloc(sizeof(struct of_clk_provider), GFP_KERNEL); if (!cp) return -ENOMEM; cp->node = of_node_get(np); cp->data = data; cp->get = clk_src_get; mutex_lock(&of_clk_lock); list_add(&cp->link, &of_clk_providers); mutex_unlock(&of_clk_lock); pr_debug("Added clock from %s\n", np->full_name); return 0; } EXPORT_SYMBOL_GPL(of_clk_add_provider); /** * of_clk_del_provider() - Remove a previously registered clock provider * @np: Device node pointer associated with clock provider */ void of_clk_del_provider(struct device_node *np) { struct of_clk_provider *cp; mutex_lock(&of_clk_lock); list_for_each_entry(cp, &of_clk_providers, link) { if (cp->node == np) { list_del(&cp->link); of_node_put(cp->node); kfree(cp); break; } } mutex_unlock(&of_clk_lock); } EXPORT_SYMBOL_GPL(of_clk_del_provider); struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec) { struct of_clk_provider *provider; struct clk *clk = ERR_PTR(-ENOENT); /* Check if we have such a provider in our array */ mutex_lock(&of_clk_lock); list_for_each_entry(provider, &of_clk_providers, link) { if (provider->node == clkspec->np) clk = provider->get(clkspec, provider->data); if (!IS_ERR(clk)) break; } mutex_unlock(&of_clk_lock); return clk; } int of_clk_get_parent_count(struct device_node *np) { return of_count_phandle_with_args(np, "clocks", "#clock-cells"); } EXPORT_SYMBOL_GPL(of_clk_get_parent_count); const char *of_clk_get_parent_name(struct device_node *np, int index) { struct of_phandle_args clkspec; const char *clk_name; int rc; if (index < 0) return NULL; rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index, &clkspec); if (rc) return NULL; if (of_property_read_string_index(clkspec.np, "clock-output-names", clkspec.args_count ? clkspec.args[0] : 0, &clk_name) < 0) clk_name = clkspec.np->name; of_node_put(clkspec.np); return clk_name; } EXPORT_SYMBOL_GPL(of_clk_get_parent_name); /** * of_clk_init() - Scan and init clock providers from the DT * @matches: array of compatible values and init functions for providers. * * This function scans the device tree for matching clock providers and * calls their initialization functions */ void __init of_clk_init(const struct of_device_id *matches) { const struct of_device_id *match; struct device_node *np; if (!matches) matches = __clk_of_table; for_each_matching_node_and_match(np, matches, &match) { of_clk_init_cb_t clk_init_cb = match->data; clk_init_cb(np); } } #endif
501585.c
extern float __VERIFIER_nondet_float(void); extern int __VERIFIER_nondet_int(void); typedef enum {false, true} bool; bool __VERIFIER_nondet_bool(void) { return __VERIFIER_nondet_int() != 0; } int main() { bool _J3876, _x__J3876; bool _J3864, _x__J3864; bool _EL_U_3847, _x__EL_U_3847; float x_8, _x_x_8; float x_6, _x_x_6; float x_24, _x_x_24; float x_9, _x_x_9; bool _EL_U_3850, _x__EL_U_3850; float x_26, _x_x_26; float x_28, _x_x_28; float x_1, _x_x_1; float x_15, _x_x_15; float x_0, _x_x_0; float x_5, _x_x_5; float x_2, _x_x_2; float x_21, _x_x_21; float x_3, _x_x_3; float x_22, _x_x_22; float x_10, _x_x_10; float x_7, _x_x_7; float x_12, _x_x_12; float x_11, _x_x_11; float x_14, _x_x_14; float x_13, _x_x_13; float x_16, _x_x_16; float x_17, _x_x_17; float x_19, _x_x_19; float x_20, _x_x_20; float x_23, _x_x_23; float x_25, _x_x_25; float x_35, _x_x_35; float x_27, _x_x_27; float x_29, _x_x_29; float x_18, _x_x_18; float x_31, _x_x_31; float x_32, _x_x_32; float x_33, _x_x_33; float x_4, _x_x_4; float x_30, _x_x_30; float x_34, _x_x_34; int __steps_to_fair = __VERIFIER_nondet_int(); _J3876 = __VERIFIER_nondet_bool(); _J3864 = __VERIFIER_nondet_bool(); _EL_U_3847 = __VERIFIER_nondet_bool(); x_8 = __VERIFIER_nondet_float(); x_6 = __VERIFIER_nondet_float(); x_24 = __VERIFIER_nondet_float(); x_9 = __VERIFIER_nondet_float(); _EL_U_3850 = __VERIFIER_nondet_bool(); x_26 = __VERIFIER_nondet_float(); x_28 = __VERIFIER_nondet_float(); x_1 = __VERIFIER_nondet_float(); x_15 = __VERIFIER_nondet_float(); x_0 = __VERIFIER_nondet_float(); x_5 = __VERIFIER_nondet_float(); x_2 = __VERIFIER_nondet_float(); x_21 = __VERIFIER_nondet_float(); x_3 = __VERIFIER_nondet_float(); x_22 = __VERIFIER_nondet_float(); x_10 = __VERIFIER_nondet_float(); x_7 = __VERIFIER_nondet_float(); x_12 = __VERIFIER_nondet_float(); x_11 = __VERIFIER_nondet_float(); x_14 = __VERIFIER_nondet_float(); x_13 = __VERIFIER_nondet_float(); x_16 = __VERIFIER_nondet_float(); x_17 = __VERIFIER_nondet_float(); x_19 = __VERIFIER_nondet_float(); x_20 = __VERIFIER_nondet_float(); x_23 = __VERIFIER_nondet_float(); x_25 = __VERIFIER_nondet_float(); x_35 = __VERIFIER_nondet_float(); x_27 = __VERIFIER_nondet_float(); x_29 = __VERIFIER_nondet_float(); x_18 = __VERIFIER_nondet_float(); x_31 = __VERIFIER_nondet_float(); x_32 = __VERIFIER_nondet_float(); x_33 = __VERIFIER_nondet_float(); x_4 = __VERIFIER_nondet_float(); x_30 = __VERIFIER_nondet_float(); x_34 = __VERIFIER_nondet_float(); bool __ok = (1 && (((_EL_U_3850 || ( !(( !(-1.0 <= (x_9 + (-1.0 * x_24)))) || ((-18.0 <= (x_6 + (-1.0 * x_8))) || _EL_U_3847)))) && ( !_J3864)) && ( !_J3876))); while (__steps_to_fair >= 0 && __ok) { if ((_J3864 && _J3876)) { __steps_to_fair = __VERIFIER_nondet_int(); } else { __steps_to_fair--; } _x__J3876 = __VERIFIER_nondet_bool(); _x__J3864 = __VERIFIER_nondet_bool(); _x__EL_U_3847 = __VERIFIER_nondet_bool(); _x_x_8 = __VERIFIER_nondet_float(); _x_x_6 = __VERIFIER_nondet_float(); _x_x_24 = __VERIFIER_nondet_float(); _x_x_9 = __VERIFIER_nondet_float(); _x__EL_U_3850 = __VERIFIER_nondet_bool(); _x_x_26 = __VERIFIER_nondet_float(); _x_x_28 = __VERIFIER_nondet_float(); _x_x_1 = __VERIFIER_nondet_float(); _x_x_15 = __VERIFIER_nondet_float(); _x_x_0 = __VERIFIER_nondet_float(); _x_x_5 = __VERIFIER_nondet_float(); _x_x_2 = __VERIFIER_nondet_float(); _x_x_21 = __VERIFIER_nondet_float(); _x_x_3 = __VERIFIER_nondet_float(); _x_x_22 = __VERIFIER_nondet_float(); _x_x_10 = __VERIFIER_nondet_float(); _x_x_7 = __VERIFIER_nondet_float(); _x_x_12 = __VERIFIER_nondet_float(); _x_x_11 = __VERIFIER_nondet_float(); _x_x_14 = __VERIFIER_nondet_float(); _x_x_13 = __VERIFIER_nondet_float(); _x_x_16 = __VERIFIER_nondet_float(); _x_x_17 = __VERIFIER_nondet_float(); _x_x_19 = __VERIFIER_nondet_float(); _x_x_20 = __VERIFIER_nondet_float(); _x_x_23 = __VERIFIER_nondet_float(); _x_x_25 = __VERIFIER_nondet_float(); _x_x_35 = __VERIFIER_nondet_float(); _x_x_27 = __VERIFIER_nondet_float(); _x_x_29 = __VERIFIER_nondet_float(); _x_x_18 = __VERIFIER_nondet_float(); _x_x_31 = __VERIFIER_nondet_float(); _x_x_32 = __VERIFIER_nondet_float(); _x_x_33 = __VERIFIER_nondet_float(); _x_x_4 = __VERIFIER_nondet_float(); _x_x_30 = __VERIFIER_nondet_float(); _x_x_34 = __VERIFIER_nondet_float(); __ok = ((((((((((((((((((((((((((((((((((((((((x_32 + (-1.0 * _x_x_0)) <= -16.0) && (((x_30 + (-1.0 * _x_x_0)) <= -2.0) && (((x_29 + (-1.0 * _x_x_0)) <= -1.0) && (((x_28 + (-1.0 * _x_x_0)) <= -17.0) && (((x_27 + (-1.0 * _x_x_0)) <= -13.0) && (((x_25 + (-1.0 * _x_x_0)) <= -12.0) && (((x_23 + (-1.0 * _x_x_0)) <= -1.0) && (((x_22 + (-1.0 * _x_x_0)) <= -7.0) && (((x_18 + (-1.0 * _x_x_0)) <= -12.0) && (((x_15 + (-1.0 * _x_x_0)) <= -2.0) && (((x_13 + (-1.0 * _x_x_0)) <= -8.0) && (((x_12 + (-1.0 * _x_x_0)) <= -10.0) && (((x_11 + (-1.0 * _x_x_0)) <= -17.0) && (((x_8 + (-1.0 * _x_x_0)) <= -18.0) && (((x_6 + (-1.0 * _x_x_0)) <= -10.0) && (((x_4 + (-1.0 * _x_x_0)) <= -17.0) && (((x_1 + (-1.0 * _x_x_0)) <= -8.0) && ((x_2 + (-1.0 * _x_x_0)) <= -5.0)))))))))))))))))) && (((x_32 + (-1.0 * _x_x_0)) == -16.0) || (((x_30 + (-1.0 * _x_x_0)) == -2.0) || (((x_29 + (-1.0 * _x_x_0)) == -1.0) || (((x_28 + (-1.0 * _x_x_0)) == -17.0) || (((x_27 + (-1.0 * _x_x_0)) == -13.0) || (((x_25 + (-1.0 * _x_x_0)) == -12.0) || (((x_23 + (-1.0 * _x_x_0)) == -1.0) || (((x_22 + (-1.0 * _x_x_0)) == -7.0) || (((x_18 + (-1.0 * _x_x_0)) == -12.0) || (((x_15 + (-1.0 * _x_x_0)) == -2.0) || (((x_13 + (-1.0 * _x_x_0)) == -8.0) || (((x_12 + (-1.0 * _x_x_0)) == -10.0) || (((x_11 + (-1.0 * _x_x_0)) == -17.0) || (((x_8 + (-1.0 * _x_x_0)) == -18.0) || (((x_6 + (-1.0 * _x_x_0)) == -10.0) || (((x_4 + (-1.0 * _x_x_0)) == -17.0) || (((x_1 + (-1.0 * _x_x_0)) == -8.0) || ((x_2 + (-1.0 * _x_x_0)) == -5.0))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_1)) <= -15.0) && (((x_32 + (-1.0 * _x_x_1)) <= -18.0) && (((x_29 + (-1.0 * _x_x_1)) <= -20.0) && (((x_26 + (-1.0 * _x_x_1)) <= -8.0) && (((x_24 + (-1.0 * _x_x_1)) <= -7.0) && (((x_23 + (-1.0 * _x_x_1)) <= -2.0) && (((x_20 + (-1.0 * _x_x_1)) <= -17.0) && (((x_19 + (-1.0 * _x_x_1)) <= -15.0) && (((x_16 + (-1.0 * _x_x_1)) <= -16.0) && (((x_12 + (-1.0 * _x_x_1)) <= -6.0) && (((x_11 + (-1.0 * _x_x_1)) <= -3.0) && (((x_8 + (-1.0 * _x_x_1)) <= -16.0) && (((x_7 + (-1.0 * _x_x_1)) <= -13.0) && (((x_5 + (-1.0 * _x_x_1)) <= -8.0) && (((x_4 + (-1.0 * _x_x_1)) <= -17.0) && (((x_3 + (-1.0 * _x_x_1)) <= -19.0) && (((x_0 + (-1.0 * _x_x_1)) <= -16.0) && ((x_1 + (-1.0 * _x_x_1)) <= -10.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_1)) == -15.0) || (((x_32 + (-1.0 * _x_x_1)) == -18.0) || (((x_29 + (-1.0 * _x_x_1)) == -20.0) || (((x_26 + (-1.0 * _x_x_1)) == -8.0) || (((x_24 + (-1.0 * _x_x_1)) == -7.0) || (((x_23 + (-1.0 * _x_x_1)) == -2.0) || (((x_20 + (-1.0 * _x_x_1)) == -17.0) || (((x_19 + (-1.0 * _x_x_1)) == -15.0) || (((x_16 + (-1.0 * _x_x_1)) == -16.0) || (((x_12 + (-1.0 * _x_x_1)) == -6.0) || (((x_11 + (-1.0 * _x_x_1)) == -3.0) || (((x_8 + (-1.0 * _x_x_1)) == -16.0) || (((x_7 + (-1.0 * _x_x_1)) == -13.0) || (((x_5 + (-1.0 * _x_x_1)) == -8.0) || (((x_4 + (-1.0 * _x_x_1)) == -17.0) || (((x_3 + (-1.0 * _x_x_1)) == -19.0) || (((x_0 + (-1.0 * _x_x_1)) == -16.0) || ((x_1 + (-1.0 * _x_x_1)) == -10.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_2)) <= -12.0) && (((x_29 + (-1.0 * _x_x_2)) <= -6.0) && (((x_28 + (-1.0 * _x_x_2)) <= -12.0) && (((x_27 + (-1.0 * _x_x_2)) <= -16.0) && (((x_25 + (-1.0 * _x_x_2)) <= -15.0) && (((x_23 + (-1.0 * _x_x_2)) <= -7.0) && (((x_19 + (-1.0 * _x_x_2)) <= -4.0) && (((x_18 + (-1.0 * _x_x_2)) <= -6.0) && (((x_17 + (-1.0 * _x_x_2)) <= -18.0) && (((x_16 + (-1.0 * _x_x_2)) <= -1.0) && (((x_15 + (-1.0 * _x_x_2)) <= -4.0) && (((x_14 + (-1.0 * _x_x_2)) <= -8.0) && (((x_13 + (-1.0 * _x_x_2)) <= -20.0) && (((x_11 + (-1.0 * _x_x_2)) <= -7.0) && (((x_9 + (-1.0 * _x_x_2)) <= -9.0) && (((x_8 + (-1.0 * _x_x_2)) <= -7.0) && (((x_0 + (-1.0 * _x_x_2)) <= -12.0) && ((x_7 + (-1.0 * _x_x_2)) <= -6.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_2)) == -12.0) || (((x_29 + (-1.0 * _x_x_2)) == -6.0) || (((x_28 + (-1.0 * _x_x_2)) == -12.0) || (((x_27 + (-1.0 * _x_x_2)) == -16.0) || (((x_25 + (-1.0 * _x_x_2)) == -15.0) || (((x_23 + (-1.0 * _x_x_2)) == -7.0) || (((x_19 + (-1.0 * _x_x_2)) == -4.0) || (((x_18 + (-1.0 * _x_x_2)) == -6.0) || (((x_17 + (-1.0 * _x_x_2)) == -18.0) || (((x_16 + (-1.0 * _x_x_2)) == -1.0) || (((x_15 + (-1.0 * _x_x_2)) == -4.0) || (((x_14 + (-1.0 * _x_x_2)) == -8.0) || (((x_13 + (-1.0 * _x_x_2)) == -20.0) || (((x_11 + (-1.0 * _x_x_2)) == -7.0) || (((x_9 + (-1.0 * _x_x_2)) == -9.0) || (((x_8 + (-1.0 * _x_x_2)) == -7.0) || (((x_0 + (-1.0 * _x_x_2)) == -12.0) || ((x_7 + (-1.0 * _x_x_2)) == -6.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_3)) <= -1.0) && (((x_33 + (-1.0 * _x_x_3)) <= -11.0) && (((x_28 + (-1.0 * _x_x_3)) <= -11.0) && (((x_24 + (-1.0 * _x_x_3)) <= -6.0) && (((x_22 + (-1.0 * _x_x_3)) <= -10.0) && (((x_21 + (-1.0 * _x_x_3)) <= -7.0) && (((x_19 + (-1.0 * _x_x_3)) <= -12.0) && (((x_17 + (-1.0 * _x_x_3)) <= -19.0) && (((x_14 + (-1.0 * _x_x_3)) <= -16.0) && (((x_12 + (-1.0 * _x_x_3)) <= -3.0) && (((x_11 + (-1.0 * _x_x_3)) <= -9.0) && (((x_9 + (-1.0 * _x_x_3)) <= -4.0) && (((x_8 + (-1.0 * _x_x_3)) <= -7.0) && (((x_7 + (-1.0 * _x_x_3)) <= -3.0) && (((x_6 + (-1.0 * _x_x_3)) <= -18.0) && (((x_3 + (-1.0 * _x_x_3)) <= -12.0) && (((x_1 + (-1.0 * _x_x_3)) <= -20.0) && ((x_2 + (-1.0 * _x_x_3)) <= -2.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_3)) == -1.0) || (((x_33 + (-1.0 * _x_x_3)) == -11.0) || (((x_28 + (-1.0 * _x_x_3)) == -11.0) || (((x_24 + (-1.0 * _x_x_3)) == -6.0) || (((x_22 + (-1.0 * _x_x_3)) == -10.0) || (((x_21 + (-1.0 * _x_x_3)) == -7.0) || (((x_19 + (-1.0 * _x_x_3)) == -12.0) || (((x_17 + (-1.0 * _x_x_3)) == -19.0) || (((x_14 + (-1.0 * _x_x_3)) == -16.0) || (((x_12 + (-1.0 * _x_x_3)) == -3.0) || (((x_11 + (-1.0 * _x_x_3)) == -9.0) || (((x_9 + (-1.0 * _x_x_3)) == -4.0) || (((x_8 + (-1.0 * _x_x_3)) == -7.0) || (((x_7 + (-1.0 * _x_x_3)) == -3.0) || (((x_6 + (-1.0 * _x_x_3)) == -18.0) || (((x_3 + (-1.0 * _x_x_3)) == -12.0) || (((x_1 + (-1.0 * _x_x_3)) == -20.0) || ((x_2 + (-1.0 * _x_x_3)) == -2.0)))))))))))))))))))) && ((((x_32 + (-1.0 * _x_x_4)) <= -14.0) && (((x_31 + (-1.0 * _x_x_4)) <= -7.0) && (((x_29 + (-1.0 * _x_x_4)) <= -4.0) && (((x_27 + (-1.0 * _x_x_4)) <= -5.0) && (((x_26 + (-1.0 * _x_x_4)) <= -2.0) && (((x_25 + (-1.0 * _x_x_4)) <= -2.0) && (((x_21 + (-1.0 * _x_x_4)) <= -10.0) && (((x_19 + (-1.0 * _x_x_4)) <= -11.0) && (((x_15 + (-1.0 * _x_x_4)) <= -20.0) && (((x_14 + (-1.0 * _x_x_4)) <= -19.0) && (((x_12 + (-1.0 * _x_x_4)) <= -10.0) && (((x_8 + (-1.0 * _x_x_4)) <= -17.0) && (((x_7 + (-1.0 * _x_x_4)) <= -16.0) && (((x_5 + (-1.0 * _x_x_4)) <= -9.0) && (((x_4 + (-1.0 * _x_x_4)) <= -12.0) && (((x_3 + (-1.0 * _x_x_4)) <= -11.0) && (((x_1 + (-1.0 * _x_x_4)) <= -2.0) && ((x_2 + (-1.0 * _x_x_4)) <= -2.0)))))))))))))))))) && (((x_32 + (-1.0 * _x_x_4)) == -14.0) || (((x_31 + (-1.0 * _x_x_4)) == -7.0) || (((x_29 + (-1.0 * _x_x_4)) == -4.0) || (((x_27 + (-1.0 * _x_x_4)) == -5.0) || (((x_26 + (-1.0 * _x_x_4)) == -2.0) || (((x_25 + (-1.0 * _x_x_4)) == -2.0) || (((x_21 + (-1.0 * _x_x_4)) == -10.0) || (((x_19 + (-1.0 * _x_x_4)) == -11.0) || (((x_15 + (-1.0 * _x_x_4)) == -20.0) || (((x_14 + (-1.0 * _x_x_4)) == -19.0) || (((x_12 + (-1.0 * _x_x_4)) == -10.0) || (((x_8 + (-1.0 * _x_x_4)) == -17.0) || (((x_7 + (-1.0 * _x_x_4)) == -16.0) || (((x_5 + (-1.0 * _x_x_4)) == -9.0) || (((x_4 + (-1.0 * _x_x_4)) == -12.0) || (((x_3 + (-1.0 * _x_x_4)) == -11.0) || (((x_1 + (-1.0 * _x_x_4)) == -2.0) || ((x_2 + (-1.0 * _x_x_4)) == -2.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_5)) <= -15.0) && (((x_33 + (-1.0 * _x_x_5)) <= -17.0) && (((x_28 + (-1.0 * _x_x_5)) <= -3.0) && (((x_27 + (-1.0 * _x_x_5)) <= -14.0) && (((x_24 + (-1.0 * _x_x_5)) <= -3.0) && (((x_22 + (-1.0 * _x_x_5)) <= -8.0) && (((x_21 + (-1.0 * _x_x_5)) <= -10.0) && (((x_18 + (-1.0 * _x_x_5)) <= -8.0) && (((x_17 + (-1.0 * _x_x_5)) <= -15.0) && (((x_14 + (-1.0 * _x_x_5)) <= -10.0) && (((x_13 + (-1.0 * _x_x_5)) <= -13.0) && (((x_11 + (-1.0 * _x_x_5)) <= -5.0) && (((x_9 + (-1.0 * _x_x_5)) <= -7.0) && (((x_8 + (-1.0 * _x_x_5)) <= -5.0) && (((x_7 + (-1.0 * _x_x_5)) <= -16.0) && (((x_6 + (-1.0 * _x_x_5)) <= -3.0) && (((x_4 + (-1.0 * _x_x_5)) <= -7.0) && ((x_5 + (-1.0 * _x_x_5)) <= -7.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_5)) == -15.0) || (((x_33 + (-1.0 * _x_x_5)) == -17.0) || (((x_28 + (-1.0 * _x_x_5)) == -3.0) || (((x_27 + (-1.0 * _x_x_5)) == -14.0) || (((x_24 + (-1.0 * _x_x_5)) == -3.0) || (((x_22 + (-1.0 * _x_x_5)) == -8.0) || (((x_21 + (-1.0 * _x_x_5)) == -10.0) || (((x_18 + (-1.0 * _x_x_5)) == -8.0) || (((x_17 + (-1.0 * _x_x_5)) == -15.0) || (((x_14 + (-1.0 * _x_x_5)) == -10.0) || (((x_13 + (-1.0 * _x_x_5)) == -13.0) || (((x_11 + (-1.0 * _x_x_5)) == -5.0) || (((x_9 + (-1.0 * _x_x_5)) == -7.0) || (((x_8 + (-1.0 * _x_x_5)) == -5.0) || (((x_7 + (-1.0 * _x_x_5)) == -16.0) || (((x_6 + (-1.0 * _x_x_5)) == -3.0) || (((x_4 + (-1.0 * _x_x_5)) == -7.0) || ((x_5 + (-1.0 * _x_x_5)) == -7.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_6)) <= -10.0) && (((x_33 + (-1.0 * _x_x_6)) <= -19.0) && (((x_31 + (-1.0 * _x_x_6)) <= -15.0) && (((x_29 + (-1.0 * _x_x_6)) <= -12.0) && (((x_27 + (-1.0 * _x_x_6)) <= -5.0) && (((x_26 + (-1.0 * _x_x_6)) <= -3.0) && (((x_23 + (-1.0 * _x_x_6)) <= -9.0) && (((x_20 + (-1.0 * _x_x_6)) <= -14.0) && (((x_19 + (-1.0 * _x_x_6)) <= -2.0) && (((x_18 + (-1.0 * _x_x_6)) <= -7.0) && (((x_17 + (-1.0 * _x_x_6)) <= -18.0) && (((x_15 + (-1.0 * _x_x_6)) <= -6.0) && (((x_13 + (-1.0 * _x_x_6)) <= -2.0) && (((x_11 + (-1.0 * _x_x_6)) <= -7.0) && (((x_9 + (-1.0 * _x_x_6)) <= -8.0) && (((x_7 + (-1.0 * _x_x_6)) <= -6.0) && (((x_0 + (-1.0 * _x_x_6)) <= -6.0) && ((x_1 + (-1.0 * _x_x_6)) <= -16.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_6)) == -10.0) || (((x_33 + (-1.0 * _x_x_6)) == -19.0) || (((x_31 + (-1.0 * _x_x_6)) == -15.0) || (((x_29 + (-1.0 * _x_x_6)) == -12.0) || (((x_27 + (-1.0 * _x_x_6)) == -5.0) || (((x_26 + (-1.0 * _x_x_6)) == -3.0) || (((x_23 + (-1.0 * _x_x_6)) == -9.0) || (((x_20 + (-1.0 * _x_x_6)) == -14.0) || (((x_19 + (-1.0 * _x_x_6)) == -2.0) || (((x_18 + (-1.0 * _x_x_6)) == -7.0) || (((x_17 + (-1.0 * _x_x_6)) == -18.0) || (((x_15 + (-1.0 * _x_x_6)) == -6.0) || (((x_13 + (-1.0 * _x_x_6)) == -2.0) || (((x_11 + (-1.0 * _x_x_6)) == -7.0) || (((x_9 + (-1.0 * _x_x_6)) == -8.0) || (((x_7 + (-1.0 * _x_x_6)) == -6.0) || (((x_0 + (-1.0 * _x_x_6)) == -6.0) || ((x_1 + (-1.0 * _x_x_6)) == -16.0)))))))))))))))))))) && ((((x_28 + (-1.0 * _x_x_7)) <= -3.0) && (((x_25 + (-1.0 * _x_x_7)) <= -15.0) && (((x_23 + (-1.0 * _x_x_7)) <= -17.0) && (((x_22 + (-1.0 * _x_x_7)) <= -3.0) && (((x_21 + (-1.0 * _x_x_7)) <= -19.0) && (((x_20 + (-1.0 * _x_x_7)) <= -13.0) && (((x_19 + (-1.0 * _x_x_7)) <= -16.0) && (((x_18 + (-1.0 * _x_x_7)) <= -11.0) && (((x_17 + (-1.0 * _x_x_7)) <= -11.0) && (((x_16 + (-1.0 * _x_x_7)) <= -19.0) && (((x_11 + (-1.0 * _x_x_7)) <= -10.0) && (((x_9 + (-1.0 * _x_x_7)) <= -16.0) && (((x_6 + (-1.0 * _x_x_7)) <= -6.0) && (((x_5 + (-1.0 * _x_x_7)) <= -8.0) && (((x_4 + (-1.0 * _x_x_7)) <= -14.0) && (((x_3 + (-1.0 * _x_x_7)) <= -10.0) && (((x_0 + (-1.0 * _x_x_7)) <= -17.0) && ((x_2 + (-1.0 * _x_x_7)) <= -2.0)))))))))))))))))) && (((x_28 + (-1.0 * _x_x_7)) == -3.0) || (((x_25 + (-1.0 * _x_x_7)) == -15.0) || (((x_23 + (-1.0 * _x_x_7)) == -17.0) || (((x_22 + (-1.0 * _x_x_7)) == -3.0) || (((x_21 + (-1.0 * _x_x_7)) == -19.0) || (((x_20 + (-1.0 * _x_x_7)) == -13.0) || (((x_19 + (-1.0 * _x_x_7)) == -16.0) || (((x_18 + (-1.0 * _x_x_7)) == -11.0) || (((x_17 + (-1.0 * _x_x_7)) == -11.0) || (((x_16 + (-1.0 * _x_x_7)) == -19.0) || (((x_11 + (-1.0 * _x_x_7)) == -10.0) || (((x_9 + (-1.0 * _x_x_7)) == -16.0) || (((x_6 + (-1.0 * _x_x_7)) == -6.0) || (((x_5 + (-1.0 * _x_x_7)) == -8.0) || (((x_4 + (-1.0 * _x_x_7)) == -14.0) || (((x_3 + (-1.0 * _x_x_7)) == -10.0) || (((x_0 + (-1.0 * _x_x_7)) == -17.0) || ((x_2 + (-1.0 * _x_x_7)) == -2.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_8)) <= -10.0) && (((x_32 + (-1.0 * _x_x_8)) <= -16.0) && (((x_31 + (-1.0 * _x_x_8)) <= -8.0) && (((x_29 + (-1.0 * _x_x_8)) <= -4.0) && (((x_25 + (-1.0 * _x_x_8)) <= -14.0) && (((x_24 + (-1.0 * _x_x_8)) <= -13.0) && (((x_22 + (-1.0 * _x_x_8)) <= -14.0) && (((x_21 + (-1.0 * _x_x_8)) <= -15.0) && (((x_20 + (-1.0 * _x_x_8)) <= -8.0) && (((x_19 + (-1.0 * _x_x_8)) <= -17.0) && (((x_16 + (-1.0 * _x_x_8)) <= -5.0) && (((x_15 + (-1.0 * _x_x_8)) <= -3.0) && (((x_14 + (-1.0 * _x_x_8)) <= -11.0) && (((x_13 + (-1.0 * _x_x_8)) <= -1.0) && (((x_12 + (-1.0 * _x_x_8)) <= -4.0) && (((x_3 + (-1.0 * _x_x_8)) <= -19.0) && (((x_0 + (-1.0 * _x_x_8)) <= -20.0) && ((x_2 + (-1.0 * _x_x_8)) <= -1.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_8)) == -10.0) || (((x_32 + (-1.0 * _x_x_8)) == -16.0) || (((x_31 + (-1.0 * _x_x_8)) == -8.0) || (((x_29 + (-1.0 * _x_x_8)) == -4.0) || (((x_25 + (-1.0 * _x_x_8)) == -14.0) || (((x_24 + (-1.0 * _x_x_8)) == -13.0) || (((x_22 + (-1.0 * _x_x_8)) == -14.0) || (((x_21 + (-1.0 * _x_x_8)) == -15.0) || (((x_20 + (-1.0 * _x_x_8)) == -8.0) || (((x_19 + (-1.0 * _x_x_8)) == -17.0) || (((x_16 + (-1.0 * _x_x_8)) == -5.0) || (((x_15 + (-1.0 * _x_x_8)) == -3.0) || (((x_14 + (-1.0 * _x_x_8)) == -11.0) || (((x_13 + (-1.0 * _x_x_8)) == -1.0) || (((x_12 + (-1.0 * _x_x_8)) == -4.0) || (((x_3 + (-1.0 * _x_x_8)) == -19.0) || (((x_0 + (-1.0 * _x_x_8)) == -20.0) || ((x_2 + (-1.0 * _x_x_8)) == -1.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_9)) <= -17.0) && (((x_29 + (-1.0 * _x_x_9)) <= -1.0) && (((x_28 + (-1.0 * _x_x_9)) <= -10.0) && (((x_27 + (-1.0 * _x_x_9)) <= -11.0) && (((x_26 + (-1.0 * _x_x_9)) <= -3.0) && (((x_20 + (-1.0 * _x_x_9)) <= -8.0) && (((x_18 + (-1.0 * _x_x_9)) <= -17.0) && (((x_17 + (-1.0 * _x_x_9)) <= -4.0) && (((x_14 + (-1.0 * _x_x_9)) <= -1.0) && (((x_13 + (-1.0 * _x_x_9)) <= -13.0) && (((x_12 + (-1.0 * _x_x_9)) <= -1.0) && (((x_11 + (-1.0 * _x_x_9)) <= -3.0) && (((x_10 + (-1.0 * _x_x_9)) <= -15.0) && (((x_9 + (-1.0 * _x_x_9)) <= -13.0) && (((x_3 + (-1.0 * _x_x_9)) <= -14.0) && (((x_2 + (-1.0 * _x_x_9)) <= -20.0) && (((x_0 + (-1.0 * _x_x_9)) <= -12.0) && ((x_1 + (-1.0 * _x_x_9)) <= -9.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_9)) == -17.0) || (((x_29 + (-1.0 * _x_x_9)) == -1.0) || (((x_28 + (-1.0 * _x_x_9)) == -10.0) || (((x_27 + (-1.0 * _x_x_9)) == -11.0) || (((x_26 + (-1.0 * _x_x_9)) == -3.0) || (((x_20 + (-1.0 * _x_x_9)) == -8.0) || (((x_18 + (-1.0 * _x_x_9)) == -17.0) || (((x_17 + (-1.0 * _x_x_9)) == -4.0) || (((x_14 + (-1.0 * _x_x_9)) == -1.0) || (((x_13 + (-1.0 * _x_x_9)) == -13.0) || (((x_12 + (-1.0 * _x_x_9)) == -1.0) || (((x_11 + (-1.0 * _x_x_9)) == -3.0) || (((x_10 + (-1.0 * _x_x_9)) == -15.0) || (((x_9 + (-1.0 * _x_x_9)) == -13.0) || (((x_3 + (-1.0 * _x_x_9)) == -14.0) || (((x_2 + (-1.0 * _x_x_9)) == -20.0) || (((x_0 + (-1.0 * _x_x_9)) == -12.0) || ((x_1 + (-1.0 * _x_x_9)) == -9.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_10)) <= -20.0) && (((x_32 + (-1.0 * _x_x_10)) <= -2.0) && (((x_30 + (-1.0 * _x_x_10)) <= -5.0) && (((x_26 + (-1.0 * _x_x_10)) <= -19.0) && (((x_24 + (-1.0 * _x_x_10)) <= -3.0) && (((x_22 + (-1.0 * _x_x_10)) <= -13.0) && (((x_20 + (-1.0 * _x_x_10)) <= -5.0) && (((x_19 + (-1.0 * _x_x_10)) <= -9.0) && (((x_14 + (-1.0 * _x_x_10)) <= -8.0) && (((x_13 + (-1.0 * _x_x_10)) <= -20.0) && (((x_12 + (-1.0 * _x_x_10)) <= -6.0) && (((x_11 + (-1.0 * _x_x_10)) <= -12.0) && (((x_8 + (-1.0 * _x_x_10)) <= -13.0) && (((x_4 + (-1.0 * _x_x_10)) <= -11.0) && (((x_3 + (-1.0 * _x_x_10)) <= -5.0) && (((x_2 + (-1.0 * _x_x_10)) <= -17.0) && (((x_0 + (-1.0 * _x_x_10)) <= -2.0) && ((x_1 + (-1.0 * _x_x_10)) <= -12.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_10)) == -20.0) || (((x_32 + (-1.0 * _x_x_10)) == -2.0) || (((x_30 + (-1.0 * _x_x_10)) == -5.0) || (((x_26 + (-1.0 * _x_x_10)) == -19.0) || (((x_24 + (-1.0 * _x_x_10)) == -3.0) || (((x_22 + (-1.0 * _x_x_10)) == -13.0) || (((x_20 + (-1.0 * _x_x_10)) == -5.0) || (((x_19 + (-1.0 * _x_x_10)) == -9.0) || (((x_14 + (-1.0 * _x_x_10)) == -8.0) || (((x_13 + (-1.0 * _x_x_10)) == -20.0) || (((x_12 + (-1.0 * _x_x_10)) == -6.0) || (((x_11 + (-1.0 * _x_x_10)) == -12.0) || (((x_8 + (-1.0 * _x_x_10)) == -13.0) || (((x_4 + (-1.0 * _x_x_10)) == -11.0) || (((x_3 + (-1.0 * _x_x_10)) == -5.0) || (((x_2 + (-1.0 * _x_x_10)) == -17.0) || (((x_0 + (-1.0 * _x_x_10)) == -2.0) || ((x_1 + (-1.0 * _x_x_10)) == -12.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_11)) <= -10.0) && (((x_32 + (-1.0 * _x_x_11)) <= -7.0) && (((x_29 + (-1.0 * _x_x_11)) <= -15.0) && (((x_28 + (-1.0 * _x_x_11)) <= -1.0) && (((x_27 + (-1.0 * _x_x_11)) <= -14.0) && (((x_26 + (-1.0 * _x_x_11)) <= -8.0) && (((x_24 + (-1.0 * _x_x_11)) <= -5.0) && (((x_19 + (-1.0 * _x_x_11)) <= -8.0) && (((x_16 + (-1.0 * _x_x_11)) <= -19.0) && (((x_15 + (-1.0 * _x_x_11)) <= -7.0) && (((x_13 + (-1.0 * _x_x_11)) <= -17.0) && (((x_11 + (-1.0 * _x_x_11)) <= -3.0) && (((x_10 + (-1.0 * _x_x_11)) <= -4.0) && (((x_9 + (-1.0 * _x_x_11)) <= -14.0) && (((x_8 + (-1.0 * _x_x_11)) <= -20.0) && (((x_7 + (-1.0 * _x_x_11)) <= -8.0) && (((x_3 + (-1.0 * _x_x_11)) <= -4.0) && ((x_4 + (-1.0 * _x_x_11)) <= -7.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_11)) == -10.0) || (((x_32 + (-1.0 * _x_x_11)) == -7.0) || (((x_29 + (-1.0 * _x_x_11)) == -15.0) || (((x_28 + (-1.0 * _x_x_11)) == -1.0) || (((x_27 + (-1.0 * _x_x_11)) == -14.0) || (((x_26 + (-1.0 * _x_x_11)) == -8.0) || (((x_24 + (-1.0 * _x_x_11)) == -5.0) || (((x_19 + (-1.0 * _x_x_11)) == -8.0) || (((x_16 + (-1.0 * _x_x_11)) == -19.0) || (((x_15 + (-1.0 * _x_x_11)) == -7.0) || (((x_13 + (-1.0 * _x_x_11)) == -17.0) || (((x_11 + (-1.0 * _x_x_11)) == -3.0) || (((x_10 + (-1.0 * _x_x_11)) == -4.0) || (((x_9 + (-1.0 * _x_x_11)) == -14.0) || (((x_8 + (-1.0 * _x_x_11)) == -20.0) || (((x_7 + (-1.0 * _x_x_11)) == -8.0) || (((x_3 + (-1.0 * _x_x_11)) == -4.0) || ((x_4 + (-1.0 * _x_x_11)) == -7.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_12)) <= -1.0) && (((x_30 + (-1.0 * _x_x_12)) <= -10.0) && (((x_24 + (-1.0 * _x_x_12)) <= -18.0) && (((x_23 + (-1.0 * _x_x_12)) <= -11.0) && (((x_22 + (-1.0 * _x_x_12)) <= -14.0) && (((x_21 + (-1.0 * _x_x_12)) <= -14.0) && (((x_20 + (-1.0 * _x_x_12)) <= -11.0) && (((x_19 + (-1.0 * _x_x_12)) <= -18.0) && (((x_16 + (-1.0 * _x_x_12)) <= -14.0) && (((x_15 + (-1.0 * _x_x_12)) <= -10.0) && (((x_11 + (-1.0 * _x_x_12)) <= -3.0) && (((x_10 + (-1.0 * _x_x_12)) <= -12.0) && (((x_9 + (-1.0 * _x_x_12)) <= -7.0) && (((x_8 + (-1.0 * _x_x_12)) <= -7.0) && (((x_6 + (-1.0 * _x_x_12)) <= -9.0) && (((x_5 + (-1.0 * _x_x_12)) <= -14.0) && (((x_0 + (-1.0 * _x_x_12)) <= -19.0) && ((x_4 + (-1.0 * _x_x_12)) <= -11.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_12)) == -1.0) || (((x_30 + (-1.0 * _x_x_12)) == -10.0) || (((x_24 + (-1.0 * _x_x_12)) == -18.0) || (((x_23 + (-1.0 * _x_x_12)) == -11.0) || (((x_22 + (-1.0 * _x_x_12)) == -14.0) || (((x_21 + (-1.0 * _x_x_12)) == -14.0) || (((x_20 + (-1.0 * _x_x_12)) == -11.0) || (((x_19 + (-1.0 * _x_x_12)) == -18.0) || (((x_16 + (-1.0 * _x_x_12)) == -14.0) || (((x_15 + (-1.0 * _x_x_12)) == -10.0) || (((x_11 + (-1.0 * _x_x_12)) == -3.0) || (((x_10 + (-1.0 * _x_x_12)) == -12.0) || (((x_9 + (-1.0 * _x_x_12)) == -7.0) || (((x_8 + (-1.0 * _x_x_12)) == -7.0) || (((x_6 + (-1.0 * _x_x_12)) == -9.0) || (((x_5 + (-1.0 * _x_x_12)) == -14.0) || (((x_0 + (-1.0 * _x_x_12)) == -19.0) || ((x_4 + (-1.0 * _x_x_12)) == -11.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_13)) <= -4.0) && (((x_34 + (-1.0 * _x_x_13)) <= -1.0) && (((x_33 + (-1.0 * _x_x_13)) <= -15.0) && (((x_32 + (-1.0 * _x_x_13)) <= -11.0) && (((x_31 + (-1.0 * _x_x_13)) <= -20.0) && (((x_28 + (-1.0 * _x_x_13)) <= -2.0) && (((x_27 + (-1.0 * _x_x_13)) <= -20.0) && (((x_26 + (-1.0 * _x_x_13)) <= -5.0) && (((x_23 + (-1.0 * _x_x_13)) <= -13.0) && (((x_20 + (-1.0 * _x_x_13)) <= -3.0) && (((x_19 + (-1.0 * _x_x_13)) <= -19.0) && (((x_15 + (-1.0 * _x_x_13)) <= -8.0) && (((x_14 + (-1.0 * _x_x_13)) <= -8.0) && (((x_13 + (-1.0 * _x_x_13)) <= -11.0) && (((x_12 + (-1.0 * _x_x_13)) <= -16.0) && (((x_10 + (-1.0 * _x_x_13)) <= -8.0) && (((x_1 + (-1.0 * _x_x_13)) <= -5.0) && ((x_2 + (-1.0 * _x_x_13)) <= -12.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_13)) == -4.0) || (((x_34 + (-1.0 * _x_x_13)) == -1.0) || (((x_33 + (-1.0 * _x_x_13)) == -15.0) || (((x_32 + (-1.0 * _x_x_13)) == -11.0) || (((x_31 + (-1.0 * _x_x_13)) == -20.0) || (((x_28 + (-1.0 * _x_x_13)) == -2.0) || (((x_27 + (-1.0 * _x_x_13)) == -20.0) || (((x_26 + (-1.0 * _x_x_13)) == -5.0) || (((x_23 + (-1.0 * _x_x_13)) == -13.0) || (((x_20 + (-1.0 * _x_x_13)) == -3.0) || (((x_19 + (-1.0 * _x_x_13)) == -19.0) || (((x_15 + (-1.0 * _x_x_13)) == -8.0) || (((x_14 + (-1.0 * _x_x_13)) == -8.0) || (((x_13 + (-1.0 * _x_x_13)) == -11.0) || (((x_12 + (-1.0 * _x_x_13)) == -16.0) || (((x_10 + (-1.0 * _x_x_13)) == -8.0) || (((x_1 + (-1.0 * _x_x_13)) == -5.0) || ((x_2 + (-1.0 * _x_x_13)) == -12.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_14)) <= -1.0) && (((x_32 + (-1.0 * _x_x_14)) <= -7.0) && (((x_28 + (-1.0 * _x_x_14)) <= -11.0) && (((x_27 + (-1.0 * _x_x_14)) <= -1.0) && (((x_25 + (-1.0 * _x_x_14)) <= -6.0) && (((x_20 + (-1.0 * _x_x_14)) <= -17.0) && (((x_19 + (-1.0 * _x_x_14)) <= -5.0) && (((x_17 + (-1.0 * _x_x_14)) <= -16.0) && (((x_15 + (-1.0 * _x_x_14)) <= -16.0) && (((x_14 + (-1.0 * _x_x_14)) <= -3.0) && (((x_13 + (-1.0 * _x_x_14)) <= -2.0) && (((x_12 + (-1.0 * _x_x_14)) <= -7.0) && (((x_10 + (-1.0 * _x_x_14)) <= -20.0) && (((x_9 + (-1.0 * _x_x_14)) <= -17.0) && (((x_8 + (-1.0 * _x_x_14)) <= -4.0) && (((x_4 + (-1.0 * _x_x_14)) <= -14.0) && (((x_0 + (-1.0 * _x_x_14)) <= -10.0) && ((x_2 + (-1.0 * _x_x_14)) <= -15.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_14)) == -1.0) || (((x_32 + (-1.0 * _x_x_14)) == -7.0) || (((x_28 + (-1.0 * _x_x_14)) == -11.0) || (((x_27 + (-1.0 * _x_x_14)) == -1.0) || (((x_25 + (-1.0 * _x_x_14)) == -6.0) || (((x_20 + (-1.0 * _x_x_14)) == -17.0) || (((x_19 + (-1.0 * _x_x_14)) == -5.0) || (((x_17 + (-1.0 * _x_x_14)) == -16.0) || (((x_15 + (-1.0 * _x_x_14)) == -16.0) || (((x_14 + (-1.0 * _x_x_14)) == -3.0) || (((x_13 + (-1.0 * _x_x_14)) == -2.0) || (((x_12 + (-1.0 * _x_x_14)) == -7.0) || (((x_10 + (-1.0 * _x_x_14)) == -20.0) || (((x_9 + (-1.0 * _x_x_14)) == -17.0) || (((x_8 + (-1.0 * _x_x_14)) == -4.0) || (((x_4 + (-1.0 * _x_x_14)) == -14.0) || (((x_0 + (-1.0 * _x_x_14)) == -10.0) || ((x_2 + (-1.0 * _x_x_14)) == -15.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_15)) <= -4.0) && (((x_33 + (-1.0 * _x_x_15)) <= -17.0) && (((x_32 + (-1.0 * _x_x_15)) <= -11.0) && (((x_28 + (-1.0 * _x_x_15)) <= -17.0) && (((x_27 + (-1.0 * _x_x_15)) <= -9.0) && (((x_25 + (-1.0 * _x_x_15)) <= -9.0) && (((x_24 + (-1.0 * _x_x_15)) <= -19.0) && (((x_22 + (-1.0 * _x_x_15)) <= -14.0) && (((x_21 + (-1.0 * _x_x_15)) <= -1.0) && (((x_18 + (-1.0 * _x_x_15)) <= -3.0) && (((x_16 + (-1.0 * _x_x_15)) <= -16.0) && (((x_15 + (-1.0 * _x_x_15)) <= -14.0) && (((x_14 + (-1.0 * _x_x_15)) <= -15.0) && (((x_13 + (-1.0 * _x_x_15)) <= -14.0) && (((x_10 + (-1.0 * _x_x_15)) <= -4.0) && (((x_8 + (-1.0 * _x_x_15)) <= -15.0) && (((x_4 + (-1.0 * _x_x_15)) <= -4.0) && ((x_5 + (-1.0 * _x_x_15)) <= -3.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_15)) == -4.0) || (((x_33 + (-1.0 * _x_x_15)) == -17.0) || (((x_32 + (-1.0 * _x_x_15)) == -11.0) || (((x_28 + (-1.0 * _x_x_15)) == -17.0) || (((x_27 + (-1.0 * _x_x_15)) == -9.0) || (((x_25 + (-1.0 * _x_x_15)) == -9.0) || (((x_24 + (-1.0 * _x_x_15)) == -19.0) || (((x_22 + (-1.0 * _x_x_15)) == -14.0) || (((x_21 + (-1.0 * _x_x_15)) == -1.0) || (((x_18 + (-1.0 * _x_x_15)) == -3.0) || (((x_16 + (-1.0 * _x_x_15)) == -16.0) || (((x_15 + (-1.0 * _x_x_15)) == -14.0) || (((x_14 + (-1.0 * _x_x_15)) == -15.0) || (((x_13 + (-1.0 * _x_x_15)) == -14.0) || (((x_10 + (-1.0 * _x_x_15)) == -4.0) || (((x_8 + (-1.0 * _x_x_15)) == -15.0) || (((x_4 + (-1.0 * _x_x_15)) == -4.0) || ((x_5 + (-1.0 * _x_x_15)) == -3.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_16)) <= -3.0) && (((x_33 + (-1.0 * _x_x_16)) <= -10.0) && (((x_31 + (-1.0 * _x_x_16)) <= -18.0) && (((x_27 + (-1.0 * _x_x_16)) <= -18.0) && (((x_20 + (-1.0 * _x_x_16)) <= -19.0) && (((x_19 + (-1.0 * _x_x_16)) <= -1.0) && (((x_18 + (-1.0 * _x_x_16)) <= -12.0) && (((x_15 + (-1.0 * _x_x_16)) <= -11.0) && (((x_13 + (-1.0 * _x_x_16)) <= -7.0) && (((x_12 + (-1.0 * _x_x_16)) <= -1.0) && (((x_10 + (-1.0 * _x_x_16)) <= -14.0) && (((x_9 + (-1.0 * _x_x_16)) <= -3.0) && (((x_8 + (-1.0 * _x_x_16)) <= -7.0) && (((x_7 + (-1.0 * _x_x_16)) <= -20.0) && (((x_6 + (-1.0 * _x_x_16)) <= -2.0) && (((x_5 + (-1.0 * _x_x_16)) <= -2.0) && (((x_0 + (-1.0 * _x_x_16)) <= -5.0) && ((x_2 + (-1.0 * _x_x_16)) <= -18.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_16)) == -3.0) || (((x_33 + (-1.0 * _x_x_16)) == -10.0) || (((x_31 + (-1.0 * _x_x_16)) == -18.0) || (((x_27 + (-1.0 * _x_x_16)) == -18.0) || (((x_20 + (-1.0 * _x_x_16)) == -19.0) || (((x_19 + (-1.0 * _x_x_16)) == -1.0) || (((x_18 + (-1.0 * _x_x_16)) == -12.0) || (((x_15 + (-1.0 * _x_x_16)) == -11.0) || (((x_13 + (-1.0 * _x_x_16)) == -7.0) || (((x_12 + (-1.0 * _x_x_16)) == -1.0) || (((x_10 + (-1.0 * _x_x_16)) == -14.0) || (((x_9 + (-1.0 * _x_x_16)) == -3.0) || (((x_8 + (-1.0 * _x_x_16)) == -7.0) || (((x_7 + (-1.0 * _x_x_16)) == -20.0) || (((x_6 + (-1.0 * _x_x_16)) == -2.0) || (((x_5 + (-1.0 * _x_x_16)) == -2.0) || (((x_0 + (-1.0 * _x_x_16)) == -5.0) || ((x_2 + (-1.0 * _x_x_16)) == -18.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_17)) <= -17.0) && (((x_33 + (-1.0 * _x_x_17)) <= -9.0) && (((x_30 + (-1.0 * _x_x_17)) <= -11.0) && (((x_28 + (-1.0 * _x_x_17)) <= -9.0) && (((x_27 + (-1.0 * _x_x_17)) <= -4.0) && (((x_26 + (-1.0 * _x_x_17)) <= -20.0) && (((x_22 + (-1.0 * _x_x_17)) <= -12.0) && (((x_21 + (-1.0 * _x_x_17)) <= -3.0) && (((x_20 + (-1.0 * _x_x_17)) <= -14.0) && (((x_18 + (-1.0 * _x_x_17)) <= -3.0) && (((x_15 + (-1.0 * _x_x_17)) <= -16.0) && (((x_13 + (-1.0 * _x_x_17)) <= -8.0) && (((x_7 + (-1.0 * _x_x_17)) <= -16.0) && (((x_6 + (-1.0 * _x_x_17)) <= -1.0) && (((x_5 + (-1.0 * _x_x_17)) <= -17.0) && (((x_4 + (-1.0 * _x_x_17)) <= -7.0) && (((x_0 + (-1.0 * _x_x_17)) <= -20.0) && ((x_1 + (-1.0 * _x_x_17)) <= -10.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_17)) == -17.0) || (((x_33 + (-1.0 * _x_x_17)) == -9.0) || (((x_30 + (-1.0 * _x_x_17)) == -11.0) || (((x_28 + (-1.0 * _x_x_17)) == -9.0) || (((x_27 + (-1.0 * _x_x_17)) == -4.0) || (((x_26 + (-1.0 * _x_x_17)) == -20.0) || (((x_22 + (-1.0 * _x_x_17)) == -12.0) || (((x_21 + (-1.0 * _x_x_17)) == -3.0) || (((x_20 + (-1.0 * _x_x_17)) == -14.0) || (((x_18 + (-1.0 * _x_x_17)) == -3.0) || (((x_15 + (-1.0 * _x_x_17)) == -16.0) || (((x_13 + (-1.0 * _x_x_17)) == -8.0) || (((x_7 + (-1.0 * _x_x_17)) == -16.0) || (((x_6 + (-1.0 * _x_x_17)) == -1.0) || (((x_5 + (-1.0 * _x_x_17)) == -17.0) || (((x_4 + (-1.0 * _x_x_17)) == -7.0) || (((x_0 + (-1.0 * _x_x_17)) == -20.0) || ((x_1 + (-1.0 * _x_x_17)) == -10.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_18)) <= -3.0) && (((x_31 + (-1.0 * _x_x_18)) <= -15.0) && (((x_30 + (-1.0 * _x_x_18)) <= -10.0) && (((x_29 + (-1.0 * _x_x_18)) <= -8.0) && (((x_28 + (-1.0 * _x_x_18)) <= -15.0) && (((x_27 + (-1.0 * _x_x_18)) <= -8.0) && (((x_25 + (-1.0 * _x_x_18)) <= -15.0) && (((x_23 + (-1.0 * _x_x_18)) <= -4.0) && (((x_21 + (-1.0 * _x_x_18)) <= -7.0) && (((x_19 + (-1.0 * _x_x_18)) <= -10.0) && (((x_16 + (-1.0 * _x_x_18)) <= -16.0) && (((x_15 + (-1.0 * _x_x_18)) <= -16.0) && (((x_14 + (-1.0 * _x_x_18)) <= -10.0) && (((x_13 + (-1.0 * _x_x_18)) <= -5.0) && (((x_12 + (-1.0 * _x_x_18)) <= -13.0) && (((x_9 + (-1.0 * _x_x_18)) <= -1.0) && (((x_6 + (-1.0 * _x_x_18)) <= -16.0) && ((x_7 + (-1.0 * _x_x_18)) <= -13.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_18)) == -3.0) || (((x_31 + (-1.0 * _x_x_18)) == -15.0) || (((x_30 + (-1.0 * _x_x_18)) == -10.0) || (((x_29 + (-1.0 * _x_x_18)) == -8.0) || (((x_28 + (-1.0 * _x_x_18)) == -15.0) || (((x_27 + (-1.0 * _x_x_18)) == -8.0) || (((x_25 + (-1.0 * _x_x_18)) == -15.0) || (((x_23 + (-1.0 * _x_x_18)) == -4.0) || (((x_21 + (-1.0 * _x_x_18)) == -7.0) || (((x_19 + (-1.0 * _x_x_18)) == -10.0) || (((x_16 + (-1.0 * _x_x_18)) == -16.0) || (((x_15 + (-1.0 * _x_x_18)) == -16.0) || (((x_14 + (-1.0 * _x_x_18)) == -10.0) || (((x_13 + (-1.0 * _x_x_18)) == -5.0) || (((x_12 + (-1.0 * _x_x_18)) == -13.0) || (((x_9 + (-1.0 * _x_x_18)) == -1.0) || (((x_6 + (-1.0 * _x_x_18)) == -16.0) || ((x_7 + (-1.0 * _x_x_18)) == -13.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_19)) <= -1.0) && (((x_33 + (-1.0 * _x_x_19)) <= -17.0) && (((x_32 + (-1.0 * _x_x_19)) <= -14.0) && (((x_31 + (-1.0 * _x_x_19)) <= -20.0) && (((x_29 + (-1.0 * _x_x_19)) <= -2.0) && (((x_28 + (-1.0 * _x_x_19)) <= -15.0) && (((x_27 + (-1.0 * _x_x_19)) <= -15.0) && (((x_21 + (-1.0 * _x_x_19)) <= -3.0) && (((x_20 + (-1.0 * _x_x_19)) <= -3.0) && (((x_19 + (-1.0 * _x_x_19)) <= -6.0) && (((x_15 + (-1.0 * _x_x_19)) <= -3.0) && (((x_14 + (-1.0 * _x_x_19)) <= -7.0) && (((x_13 + (-1.0 * _x_x_19)) <= -12.0) && (((x_10 + (-1.0 * _x_x_19)) <= -2.0) && (((x_7 + (-1.0 * _x_x_19)) <= -13.0) && (((x_6 + (-1.0 * _x_x_19)) <= -15.0) && (((x_0 + (-1.0 * _x_x_19)) <= -15.0) && ((x_5 + (-1.0 * _x_x_19)) <= -16.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_19)) == -1.0) || (((x_33 + (-1.0 * _x_x_19)) == -17.0) || (((x_32 + (-1.0 * _x_x_19)) == -14.0) || (((x_31 + (-1.0 * _x_x_19)) == -20.0) || (((x_29 + (-1.0 * _x_x_19)) == -2.0) || (((x_28 + (-1.0 * _x_x_19)) == -15.0) || (((x_27 + (-1.0 * _x_x_19)) == -15.0) || (((x_21 + (-1.0 * _x_x_19)) == -3.0) || (((x_20 + (-1.0 * _x_x_19)) == -3.0) || (((x_19 + (-1.0 * _x_x_19)) == -6.0) || (((x_15 + (-1.0 * _x_x_19)) == -3.0) || (((x_14 + (-1.0 * _x_x_19)) == -7.0) || (((x_13 + (-1.0 * _x_x_19)) == -12.0) || (((x_10 + (-1.0 * _x_x_19)) == -2.0) || (((x_7 + (-1.0 * _x_x_19)) == -13.0) || (((x_6 + (-1.0 * _x_x_19)) == -15.0) || (((x_0 + (-1.0 * _x_x_19)) == -15.0) || ((x_5 + (-1.0 * _x_x_19)) == -16.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_20)) <= -9.0) && (((x_34 + (-1.0 * _x_x_20)) <= -13.0) && (((x_33 + (-1.0 * _x_x_20)) <= -3.0) && (((x_32 + (-1.0 * _x_x_20)) <= -15.0) && (((x_27 + (-1.0 * _x_x_20)) <= -19.0) && (((x_26 + (-1.0 * _x_x_20)) <= -6.0) && (((x_24 + (-1.0 * _x_x_20)) <= -6.0) && (((x_23 + (-1.0 * _x_x_20)) <= -18.0) && (((x_22 + (-1.0 * _x_x_20)) <= -2.0) && (((x_21 + (-1.0 * _x_x_20)) <= -4.0) && (((x_20 + (-1.0 * _x_x_20)) <= -9.0) && (((x_19 + (-1.0 * _x_x_20)) <= -5.0) && (((x_16 + (-1.0 * _x_x_20)) <= -17.0) && (((x_12 + (-1.0 * _x_x_20)) <= -17.0) && (((x_6 + (-1.0 * _x_x_20)) <= -12.0) && (((x_5 + (-1.0 * _x_x_20)) <= -8.0) && (((x_0 + (-1.0 * _x_x_20)) <= -6.0) && ((x_3 + (-1.0 * _x_x_20)) <= -15.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_20)) == -9.0) || (((x_34 + (-1.0 * _x_x_20)) == -13.0) || (((x_33 + (-1.0 * _x_x_20)) == -3.0) || (((x_32 + (-1.0 * _x_x_20)) == -15.0) || (((x_27 + (-1.0 * _x_x_20)) == -19.0) || (((x_26 + (-1.0 * _x_x_20)) == -6.0) || (((x_24 + (-1.0 * _x_x_20)) == -6.0) || (((x_23 + (-1.0 * _x_x_20)) == -18.0) || (((x_22 + (-1.0 * _x_x_20)) == -2.0) || (((x_21 + (-1.0 * _x_x_20)) == -4.0) || (((x_20 + (-1.0 * _x_x_20)) == -9.0) || (((x_19 + (-1.0 * _x_x_20)) == -5.0) || (((x_16 + (-1.0 * _x_x_20)) == -17.0) || (((x_12 + (-1.0 * _x_x_20)) == -17.0) || (((x_6 + (-1.0 * _x_x_20)) == -12.0) || (((x_5 + (-1.0 * _x_x_20)) == -8.0) || (((x_0 + (-1.0 * _x_x_20)) == -6.0) || ((x_3 + (-1.0 * _x_x_20)) == -15.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_21)) <= -16.0) && (((x_32 + (-1.0 * _x_x_21)) <= -9.0) && (((x_31 + (-1.0 * _x_x_21)) <= -17.0) && (((x_29 + (-1.0 * _x_x_21)) <= -11.0) && (((x_27 + (-1.0 * _x_x_21)) <= -11.0) && (((x_25 + (-1.0 * _x_x_21)) <= -6.0) && (((x_24 + (-1.0 * _x_x_21)) <= -2.0) && (((x_18 + (-1.0 * _x_x_21)) <= -8.0) && (((x_17 + (-1.0 * _x_x_21)) <= -13.0) && (((x_16 + (-1.0 * _x_x_21)) <= -3.0) && (((x_13 + (-1.0 * _x_x_21)) <= -1.0) && (((x_11 + (-1.0 * _x_x_21)) <= -18.0) && (((x_9 + (-1.0 * _x_x_21)) <= -7.0) && (((x_6 + (-1.0 * _x_x_21)) <= -6.0) && (((x_4 + (-1.0 * _x_x_21)) <= -9.0) && (((x_3 + (-1.0 * _x_x_21)) <= -19.0) && (((x_0 + (-1.0 * _x_x_21)) <= -18.0) && ((x_2 + (-1.0 * _x_x_21)) <= -6.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_21)) == -16.0) || (((x_32 + (-1.0 * _x_x_21)) == -9.0) || (((x_31 + (-1.0 * _x_x_21)) == -17.0) || (((x_29 + (-1.0 * _x_x_21)) == -11.0) || (((x_27 + (-1.0 * _x_x_21)) == -11.0) || (((x_25 + (-1.0 * _x_x_21)) == -6.0) || (((x_24 + (-1.0 * _x_x_21)) == -2.0) || (((x_18 + (-1.0 * _x_x_21)) == -8.0) || (((x_17 + (-1.0 * _x_x_21)) == -13.0) || (((x_16 + (-1.0 * _x_x_21)) == -3.0) || (((x_13 + (-1.0 * _x_x_21)) == -1.0) || (((x_11 + (-1.0 * _x_x_21)) == -18.0) || (((x_9 + (-1.0 * _x_x_21)) == -7.0) || (((x_6 + (-1.0 * _x_x_21)) == -6.0) || (((x_4 + (-1.0 * _x_x_21)) == -9.0) || (((x_3 + (-1.0 * _x_x_21)) == -19.0) || (((x_0 + (-1.0 * _x_x_21)) == -18.0) || ((x_2 + (-1.0 * _x_x_21)) == -6.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_22)) <= -7.0) && (((x_33 + (-1.0 * _x_x_22)) <= -5.0) && (((x_30 + (-1.0 * _x_x_22)) <= -19.0) && (((x_29 + (-1.0 * _x_x_22)) <= -15.0) && (((x_26 + (-1.0 * _x_x_22)) <= -3.0) && (((x_25 + (-1.0 * _x_x_22)) <= -18.0) && (((x_21 + (-1.0 * _x_x_22)) <= -10.0) && (((x_19 + (-1.0 * _x_x_22)) <= -7.0) && (((x_18 + (-1.0 * _x_x_22)) <= -1.0) && (((x_14 + (-1.0 * _x_x_22)) <= -17.0) && (((x_12 + (-1.0 * _x_x_22)) <= -1.0) && (((x_9 + (-1.0 * _x_x_22)) <= -9.0) && (((x_8 + (-1.0 * _x_x_22)) <= -14.0) && (((x_7 + (-1.0 * _x_x_22)) <= -20.0) && (((x_6 + (-1.0 * _x_x_22)) <= -5.0) && (((x_5 + (-1.0 * _x_x_22)) <= -15.0) && (((x_1 + (-1.0 * _x_x_22)) <= -18.0) && ((x_4 + (-1.0 * _x_x_22)) <= -2.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_22)) == -7.0) || (((x_33 + (-1.0 * _x_x_22)) == -5.0) || (((x_30 + (-1.0 * _x_x_22)) == -19.0) || (((x_29 + (-1.0 * _x_x_22)) == -15.0) || (((x_26 + (-1.0 * _x_x_22)) == -3.0) || (((x_25 + (-1.0 * _x_x_22)) == -18.0) || (((x_21 + (-1.0 * _x_x_22)) == -10.0) || (((x_19 + (-1.0 * _x_x_22)) == -7.0) || (((x_18 + (-1.0 * _x_x_22)) == -1.0) || (((x_14 + (-1.0 * _x_x_22)) == -17.0) || (((x_12 + (-1.0 * _x_x_22)) == -1.0) || (((x_9 + (-1.0 * _x_x_22)) == -9.0) || (((x_8 + (-1.0 * _x_x_22)) == -14.0) || (((x_7 + (-1.0 * _x_x_22)) == -20.0) || (((x_6 + (-1.0 * _x_x_22)) == -5.0) || (((x_5 + (-1.0 * _x_x_22)) == -15.0) || (((x_1 + (-1.0 * _x_x_22)) == -18.0) || ((x_4 + (-1.0 * _x_x_22)) == -2.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_23)) <= -3.0) && (((x_32 + (-1.0 * _x_x_23)) <= -7.0) && (((x_29 + (-1.0 * _x_x_23)) <= -17.0) && (((x_27 + (-1.0 * _x_x_23)) <= -11.0) && (((x_25 + (-1.0 * _x_x_23)) <= -16.0) && (((x_24 + (-1.0 * _x_x_23)) <= -14.0) && (((x_23 + (-1.0 * _x_x_23)) <= -8.0) && (((x_22 + (-1.0 * _x_x_23)) <= -13.0) && (((x_21 + (-1.0 * _x_x_23)) <= -2.0) && (((x_18 + (-1.0 * _x_x_23)) <= -18.0) && (((x_15 + (-1.0 * _x_x_23)) <= -2.0) && (((x_11 + (-1.0 * _x_x_23)) <= -11.0) && (((x_10 + (-1.0 * _x_x_23)) <= -8.0) && (((x_9 + (-1.0 * _x_x_23)) <= -20.0) && (((x_8 + (-1.0 * _x_x_23)) <= -2.0) && (((x_6 + (-1.0 * _x_x_23)) <= -16.0) && (((x_0 + (-1.0 * _x_x_23)) <= -15.0) && ((x_3 + (-1.0 * _x_x_23)) <= -17.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_23)) == -3.0) || (((x_32 + (-1.0 * _x_x_23)) == -7.0) || (((x_29 + (-1.0 * _x_x_23)) == -17.0) || (((x_27 + (-1.0 * _x_x_23)) == -11.0) || (((x_25 + (-1.0 * _x_x_23)) == -16.0) || (((x_24 + (-1.0 * _x_x_23)) == -14.0) || (((x_23 + (-1.0 * _x_x_23)) == -8.0) || (((x_22 + (-1.0 * _x_x_23)) == -13.0) || (((x_21 + (-1.0 * _x_x_23)) == -2.0) || (((x_18 + (-1.0 * _x_x_23)) == -18.0) || (((x_15 + (-1.0 * _x_x_23)) == -2.0) || (((x_11 + (-1.0 * _x_x_23)) == -11.0) || (((x_10 + (-1.0 * _x_x_23)) == -8.0) || (((x_9 + (-1.0 * _x_x_23)) == -20.0) || (((x_8 + (-1.0 * _x_x_23)) == -2.0) || (((x_6 + (-1.0 * _x_x_23)) == -16.0) || (((x_0 + (-1.0 * _x_x_23)) == -15.0) || ((x_3 + (-1.0 * _x_x_23)) == -17.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_24)) <= -20.0) && (((x_32 + (-1.0 * _x_x_24)) <= -17.0) && (((x_31 + (-1.0 * _x_x_24)) <= -6.0) && (((x_28 + (-1.0 * _x_x_24)) <= -19.0) && (((x_25 + (-1.0 * _x_x_24)) <= -5.0) && (((x_24 + (-1.0 * _x_x_24)) <= -20.0) && (((x_22 + (-1.0 * _x_x_24)) <= -8.0) && (((x_21 + (-1.0 * _x_x_24)) <= -11.0) && (((x_20 + (-1.0 * _x_x_24)) <= -7.0) && (((x_18 + (-1.0 * _x_x_24)) <= -11.0) && (((x_15 + (-1.0 * _x_x_24)) <= -14.0) && (((x_14 + (-1.0 * _x_x_24)) <= -19.0) && (((x_9 + (-1.0 * _x_x_24)) <= -15.0) && (((x_7 + (-1.0 * _x_x_24)) <= -14.0) && (((x_5 + (-1.0 * _x_x_24)) <= -9.0) && (((x_4 + (-1.0 * _x_x_24)) <= -19.0) && (((x_1 + (-1.0 * _x_x_24)) <= -7.0) && ((x_2 + (-1.0 * _x_x_24)) <= -14.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_24)) == -20.0) || (((x_32 + (-1.0 * _x_x_24)) == -17.0) || (((x_31 + (-1.0 * _x_x_24)) == -6.0) || (((x_28 + (-1.0 * _x_x_24)) == -19.0) || (((x_25 + (-1.0 * _x_x_24)) == -5.0) || (((x_24 + (-1.0 * _x_x_24)) == -20.0) || (((x_22 + (-1.0 * _x_x_24)) == -8.0) || (((x_21 + (-1.0 * _x_x_24)) == -11.0) || (((x_20 + (-1.0 * _x_x_24)) == -7.0) || (((x_18 + (-1.0 * _x_x_24)) == -11.0) || (((x_15 + (-1.0 * _x_x_24)) == -14.0) || (((x_14 + (-1.0 * _x_x_24)) == -19.0) || (((x_9 + (-1.0 * _x_x_24)) == -15.0) || (((x_7 + (-1.0 * _x_x_24)) == -14.0) || (((x_5 + (-1.0 * _x_x_24)) == -9.0) || (((x_4 + (-1.0 * _x_x_24)) == -19.0) || (((x_1 + (-1.0 * _x_x_24)) == -7.0) || ((x_2 + (-1.0 * _x_x_24)) == -14.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_25)) <= -18.0) && (((x_33 + (-1.0 * _x_x_25)) <= -7.0) && (((x_32 + (-1.0 * _x_x_25)) <= -10.0) && (((x_30 + (-1.0 * _x_x_25)) <= -19.0) && (((x_28 + (-1.0 * _x_x_25)) <= -15.0) && (((x_26 + (-1.0 * _x_x_25)) <= -14.0) && (((x_25 + (-1.0 * _x_x_25)) <= -11.0) && (((x_24 + (-1.0 * _x_x_25)) <= -14.0) && (((x_23 + (-1.0 * _x_x_25)) <= -6.0) && (((x_22 + (-1.0 * _x_x_25)) <= -6.0) && (((x_20 + (-1.0 * _x_x_25)) <= -6.0) && (((x_17 + (-1.0 * _x_x_25)) <= -18.0) && (((x_16 + (-1.0 * _x_x_25)) <= -8.0) && (((x_14 + (-1.0 * _x_x_25)) <= -7.0) && (((x_9 + (-1.0 * _x_x_25)) <= -8.0) && (((x_7 + (-1.0 * _x_x_25)) <= -17.0) && (((x_0 + (-1.0 * _x_x_25)) <= -2.0) && ((x_3 + (-1.0 * _x_x_25)) <= -3.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_25)) == -18.0) || (((x_33 + (-1.0 * _x_x_25)) == -7.0) || (((x_32 + (-1.0 * _x_x_25)) == -10.0) || (((x_30 + (-1.0 * _x_x_25)) == -19.0) || (((x_28 + (-1.0 * _x_x_25)) == -15.0) || (((x_26 + (-1.0 * _x_x_25)) == -14.0) || (((x_25 + (-1.0 * _x_x_25)) == -11.0) || (((x_24 + (-1.0 * _x_x_25)) == -14.0) || (((x_23 + (-1.0 * _x_x_25)) == -6.0) || (((x_22 + (-1.0 * _x_x_25)) == -6.0) || (((x_20 + (-1.0 * _x_x_25)) == -6.0) || (((x_17 + (-1.0 * _x_x_25)) == -18.0) || (((x_16 + (-1.0 * _x_x_25)) == -8.0) || (((x_14 + (-1.0 * _x_x_25)) == -7.0) || (((x_9 + (-1.0 * _x_x_25)) == -8.0) || (((x_7 + (-1.0 * _x_x_25)) == -17.0) || (((x_0 + (-1.0 * _x_x_25)) == -2.0) || ((x_3 + (-1.0 * _x_x_25)) == -3.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_26)) <= -16.0) && (((x_34 + (-1.0 * _x_x_26)) <= -14.0) && (((x_30 + (-1.0 * _x_x_26)) <= -11.0) && (((x_29 + (-1.0 * _x_x_26)) <= -13.0) && (((x_27 + (-1.0 * _x_x_26)) <= -6.0) && (((x_23 + (-1.0 * _x_x_26)) <= -10.0) && (((x_22 + (-1.0 * _x_x_26)) <= -17.0) && (((x_21 + (-1.0 * _x_x_26)) <= -18.0) && (((x_20 + (-1.0 * _x_x_26)) <= -8.0) && (((x_16 + (-1.0 * _x_x_26)) <= -9.0) && (((x_15 + (-1.0 * _x_x_26)) <= -15.0) && (((x_11 + (-1.0 * _x_x_26)) <= -6.0) && (((x_10 + (-1.0 * _x_x_26)) <= -9.0) && (((x_9 + (-1.0 * _x_x_26)) <= -2.0) && (((x_6 + (-1.0 * _x_x_26)) <= -16.0) && (((x_5 + (-1.0 * _x_x_26)) <= -14.0) && (((x_3 + (-1.0 * _x_x_26)) <= -17.0) && ((x_4 + (-1.0 * _x_x_26)) <= -4.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_26)) == -16.0) || (((x_34 + (-1.0 * _x_x_26)) == -14.0) || (((x_30 + (-1.0 * _x_x_26)) == -11.0) || (((x_29 + (-1.0 * _x_x_26)) == -13.0) || (((x_27 + (-1.0 * _x_x_26)) == -6.0) || (((x_23 + (-1.0 * _x_x_26)) == -10.0) || (((x_22 + (-1.0 * _x_x_26)) == -17.0) || (((x_21 + (-1.0 * _x_x_26)) == -18.0) || (((x_20 + (-1.0 * _x_x_26)) == -8.0) || (((x_16 + (-1.0 * _x_x_26)) == -9.0) || (((x_15 + (-1.0 * _x_x_26)) == -15.0) || (((x_11 + (-1.0 * _x_x_26)) == -6.0) || (((x_10 + (-1.0 * _x_x_26)) == -9.0) || (((x_9 + (-1.0 * _x_x_26)) == -2.0) || (((x_6 + (-1.0 * _x_x_26)) == -16.0) || (((x_5 + (-1.0 * _x_x_26)) == -14.0) || (((x_3 + (-1.0 * _x_x_26)) == -17.0) || ((x_4 + (-1.0 * _x_x_26)) == -4.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_27)) <= -17.0) && (((x_32 + (-1.0 * _x_x_27)) <= -11.0) && (((x_31 + (-1.0 * _x_x_27)) <= -12.0) && (((x_29 + (-1.0 * _x_x_27)) <= -15.0) && (((x_27 + (-1.0 * _x_x_27)) <= -17.0) && (((x_26 + (-1.0 * _x_x_27)) <= -17.0) && (((x_25 + (-1.0 * _x_x_27)) <= -4.0) && (((x_20 + (-1.0 * _x_x_27)) <= -6.0) && (((x_19 + (-1.0 * _x_x_27)) <= -1.0) && (((x_17 + (-1.0 * _x_x_27)) <= -6.0) && (((x_15 + (-1.0 * _x_x_27)) <= -4.0) && (((x_13 + (-1.0 * _x_x_27)) <= -10.0) && (((x_10 + (-1.0 * _x_x_27)) <= -8.0) && (((x_9 + (-1.0 * _x_x_27)) <= -15.0) && (((x_6 + (-1.0 * _x_x_27)) <= -14.0) && (((x_5 + (-1.0 * _x_x_27)) <= -17.0) && (((x_1 + (-1.0 * _x_x_27)) <= -16.0) && ((x_2 + (-1.0 * _x_x_27)) <= -15.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_27)) == -17.0) || (((x_32 + (-1.0 * _x_x_27)) == -11.0) || (((x_31 + (-1.0 * _x_x_27)) == -12.0) || (((x_29 + (-1.0 * _x_x_27)) == -15.0) || (((x_27 + (-1.0 * _x_x_27)) == -17.0) || (((x_26 + (-1.0 * _x_x_27)) == -17.0) || (((x_25 + (-1.0 * _x_x_27)) == -4.0) || (((x_20 + (-1.0 * _x_x_27)) == -6.0) || (((x_19 + (-1.0 * _x_x_27)) == -1.0) || (((x_17 + (-1.0 * _x_x_27)) == -6.0) || (((x_15 + (-1.0 * _x_x_27)) == -4.0) || (((x_13 + (-1.0 * _x_x_27)) == -10.0) || (((x_10 + (-1.0 * _x_x_27)) == -8.0) || (((x_9 + (-1.0 * _x_x_27)) == -15.0) || (((x_6 + (-1.0 * _x_x_27)) == -14.0) || (((x_5 + (-1.0 * _x_x_27)) == -17.0) || (((x_1 + (-1.0 * _x_x_27)) == -16.0) || ((x_2 + (-1.0 * _x_x_27)) == -15.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_28)) <= -19.0) && (((x_34 + (-1.0 * _x_x_28)) <= -8.0) && (((x_33 + (-1.0 * _x_x_28)) <= -1.0) && (((x_32 + (-1.0 * _x_x_28)) <= -7.0) && (((x_29 + (-1.0 * _x_x_28)) <= -6.0) && (((x_28 + (-1.0 * _x_x_28)) <= -8.0) && (((x_26 + (-1.0 * _x_x_28)) <= -3.0) && (((x_24 + (-1.0 * _x_x_28)) <= -3.0) && (((x_23 + (-1.0 * _x_x_28)) <= -14.0) && (((x_19 + (-1.0 * _x_x_28)) <= -2.0) && (((x_18 + (-1.0 * _x_x_28)) <= -15.0) && (((x_17 + (-1.0 * _x_x_28)) <= -9.0) && (((x_12 + (-1.0 * _x_x_28)) <= -19.0) && (((x_10 + (-1.0 * _x_x_28)) <= -3.0) && (((x_9 + (-1.0 * _x_x_28)) <= -10.0) && (((x_8 + (-1.0 * _x_x_28)) <= -6.0) && (((x_0 + (-1.0 * _x_x_28)) <= -14.0) && ((x_4 + (-1.0 * _x_x_28)) <= -9.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_28)) == -19.0) || (((x_34 + (-1.0 * _x_x_28)) == -8.0) || (((x_33 + (-1.0 * _x_x_28)) == -1.0) || (((x_32 + (-1.0 * _x_x_28)) == -7.0) || (((x_29 + (-1.0 * _x_x_28)) == -6.0) || (((x_28 + (-1.0 * _x_x_28)) == -8.0) || (((x_26 + (-1.0 * _x_x_28)) == -3.0) || (((x_24 + (-1.0 * _x_x_28)) == -3.0) || (((x_23 + (-1.0 * _x_x_28)) == -14.0) || (((x_19 + (-1.0 * _x_x_28)) == -2.0) || (((x_18 + (-1.0 * _x_x_28)) == -15.0) || (((x_17 + (-1.0 * _x_x_28)) == -9.0) || (((x_12 + (-1.0 * _x_x_28)) == -19.0) || (((x_10 + (-1.0 * _x_x_28)) == -3.0) || (((x_9 + (-1.0 * _x_x_28)) == -10.0) || (((x_8 + (-1.0 * _x_x_28)) == -6.0) || (((x_0 + (-1.0 * _x_x_28)) == -14.0) || ((x_4 + (-1.0 * _x_x_28)) == -9.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_29)) <= -15.0) && (((x_33 + (-1.0 * _x_x_29)) <= -10.0) && (((x_32 + (-1.0 * _x_x_29)) <= -13.0) && (((x_30 + (-1.0 * _x_x_29)) <= -16.0) && (((x_28 + (-1.0 * _x_x_29)) <= -12.0) && (((x_25 + (-1.0 * _x_x_29)) <= -5.0) && (((x_22 + (-1.0 * _x_x_29)) <= -15.0) && (((x_18 + (-1.0 * _x_x_29)) <= -5.0) && (((x_15 + (-1.0 * _x_x_29)) <= -12.0) && (((x_14 + (-1.0 * _x_x_29)) <= -8.0) && (((x_12 + (-1.0 * _x_x_29)) <= -5.0) && (((x_11 + (-1.0 * _x_x_29)) <= -7.0) && (((x_10 + (-1.0 * _x_x_29)) <= -10.0) && (((x_8 + (-1.0 * _x_x_29)) <= -19.0) && (((x_7 + (-1.0 * _x_x_29)) <= -15.0) && (((x_5 + (-1.0 * _x_x_29)) <= -1.0) && (((x_0 + (-1.0 * _x_x_29)) <= -2.0) && ((x_1 + (-1.0 * _x_x_29)) <= -10.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_29)) == -15.0) || (((x_33 + (-1.0 * _x_x_29)) == -10.0) || (((x_32 + (-1.0 * _x_x_29)) == -13.0) || (((x_30 + (-1.0 * _x_x_29)) == -16.0) || (((x_28 + (-1.0 * _x_x_29)) == -12.0) || (((x_25 + (-1.0 * _x_x_29)) == -5.0) || (((x_22 + (-1.0 * _x_x_29)) == -15.0) || (((x_18 + (-1.0 * _x_x_29)) == -5.0) || (((x_15 + (-1.0 * _x_x_29)) == -12.0) || (((x_14 + (-1.0 * _x_x_29)) == -8.0) || (((x_12 + (-1.0 * _x_x_29)) == -5.0) || (((x_11 + (-1.0 * _x_x_29)) == -7.0) || (((x_10 + (-1.0 * _x_x_29)) == -10.0) || (((x_8 + (-1.0 * _x_x_29)) == -19.0) || (((x_7 + (-1.0 * _x_x_29)) == -15.0) || (((x_5 + (-1.0 * _x_x_29)) == -1.0) || (((x_0 + (-1.0 * _x_x_29)) == -2.0) || ((x_1 + (-1.0 * _x_x_29)) == -10.0)))))))))))))))))))) && ((((x_35 + (-1.0 * _x_x_30)) <= -19.0) && (((x_33 + (-1.0 * _x_x_30)) <= -12.0) && (((x_32 + (-1.0 * _x_x_30)) <= -17.0) && (((x_31 + (-1.0 * _x_x_30)) <= -4.0) && (((x_30 + (-1.0 * _x_x_30)) <= -19.0) && (((x_29 + (-1.0 * _x_x_30)) <= -9.0) && (((x_26 + (-1.0 * _x_x_30)) <= -9.0) && (((x_25 + (-1.0 * _x_x_30)) <= -1.0) && (((x_21 + (-1.0 * _x_x_30)) <= -7.0) && (((x_20 + (-1.0 * _x_x_30)) <= -6.0) && (((x_18 + (-1.0 * _x_x_30)) <= -6.0) && (((x_17 + (-1.0 * _x_x_30)) <= -18.0) && (((x_15 + (-1.0 * _x_x_30)) <= -8.0) && (((x_14 + (-1.0 * _x_x_30)) <= -19.0) && (((x_11 + (-1.0 * _x_x_30)) <= -16.0) && (((x_10 + (-1.0 * _x_x_30)) <= -17.0) && (((x_0 + (-1.0 * _x_x_30)) <= -12.0) && ((x_2 + (-1.0 * _x_x_30)) <= -10.0)))))))))))))))))) && (((x_35 + (-1.0 * _x_x_30)) == -19.0) || (((x_33 + (-1.0 * _x_x_30)) == -12.0) || (((x_32 + (-1.0 * _x_x_30)) == -17.0) || (((x_31 + (-1.0 * _x_x_30)) == -4.0) || (((x_30 + (-1.0 * _x_x_30)) == -19.0) || (((x_29 + (-1.0 * _x_x_30)) == -9.0) || (((x_26 + (-1.0 * _x_x_30)) == -9.0) || (((x_25 + (-1.0 * _x_x_30)) == -1.0) || (((x_21 + (-1.0 * _x_x_30)) == -7.0) || (((x_20 + (-1.0 * _x_x_30)) == -6.0) || (((x_18 + (-1.0 * _x_x_30)) == -6.0) || (((x_17 + (-1.0 * _x_x_30)) == -18.0) || (((x_15 + (-1.0 * _x_x_30)) == -8.0) || (((x_14 + (-1.0 * _x_x_30)) == -19.0) || (((x_11 + (-1.0 * _x_x_30)) == -16.0) || (((x_10 + (-1.0 * _x_x_30)) == -17.0) || (((x_0 + (-1.0 * _x_x_30)) == -12.0) || ((x_2 + (-1.0 * _x_x_30)) == -10.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_31)) <= -5.0) && (((x_33 + (-1.0 * _x_x_31)) <= -12.0) && (((x_32 + (-1.0 * _x_x_31)) <= -8.0) && (((x_30 + (-1.0 * _x_x_31)) <= -5.0) && (((x_29 + (-1.0 * _x_x_31)) <= -11.0) && (((x_26 + (-1.0 * _x_x_31)) <= -3.0) && (((x_22 + (-1.0 * _x_x_31)) <= -6.0) && (((x_21 + (-1.0 * _x_x_31)) <= -9.0) && (((x_20 + (-1.0 * _x_x_31)) <= -11.0) && (((x_18 + (-1.0 * _x_x_31)) <= -19.0) && (((x_17 + (-1.0 * _x_x_31)) <= -14.0) && (((x_16 + (-1.0 * _x_x_31)) <= -13.0) && (((x_14 + (-1.0 * _x_x_31)) <= -8.0) && (((x_13 + (-1.0 * _x_x_31)) <= -19.0) && (((x_7 + (-1.0 * _x_x_31)) <= -17.0) && (((x_5 + (-1.0 * _x_x_31)) <= -18.0) && (((x_0 + (-1.0 * _x_x_31)) <= -3.0) && ((x_3 + (-1.0 * _x_x_31)) <= -5.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_31)) == -5.0) || (((x_33 + (-1.0 * _x_x_31)) == -12.0) || (((x_32 + (-1.0 * _x_x_31)) == -8.0) || (((x_30 + (-1.0 * _x_x_31)) == -5.0) || (((x_29 + (-1.0 * _x_x_31)) == -11.0) || (((x_26 + (-1.0 * _x_x_31)) == -3.0) || (((x_22 + (-1.0 * _x_x_31)) == -6.0) || (((x_21 + (-1.0 * _x_x_31)) == -9.0) || (((x_20 + (-1.0 * _x_x_31)) == -11.0) || (((x_18 + (-1.0 * _x_x_31)) == -19.0) || (((x_17 + (-1.0 * _x_x_31)) == -14.0) || (((x_16 + (-1.0 * _x_x_31)) == -13.0) || (((x_14 + (-1.0 * _x_x_31)) == -8.0) || (((x_13 + (-1.0 * _x_x_31)) == -19.0) || (((x_7 + (-1.0 * _x_x_31)) == -17.0) || (((x_5 + (-1.0 * _x_x_31)) == -18.0) || (((x_0 + (-1.0 * _x_x_31)) == -3.0) || ((x_3 + (-1.0 * _x_x_31)) == -5.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_32)) <= -3.0) && (((x_28 + (-1.0 * _x_x_32)) <= -14.0) && (((x_26 + (-1.0 * _x_x_32)) <= -6.0) && (((x_25 + (-1.0 * _x_x_32)) <= -14.0) && (((x_21 + (-1.0 * _x_x_32)) <= -19.0) && (((x_17 + (-1.0 * _x_x_32)) <= -12.0) && (((x_16 + (-1.0 * _x_x_32)) <= -4.0) && (((x_15 + (-1.0 * _x_x_32)) <= -13.0) && (((x_14 + (-1.0 * _x_x_32)) <= -15.0) && (((x_12 + (-1.0 * _x_x_32)) <= -16.0) && (((x_11 + (-1.0 * _x_x_32)) <= -9.0) && (((x_10 + (-1.0 * _x_x_32)) <= -1.0) && (((x_9 + (-1.0 * _x_x_32)) <= -5.0) && (((x_7 + (-1.0 * _x_x_32)) <= -6.0) && (((x_5 + (-1.0 * _x_x_32)) <= -11.0) && (((x_4 + (-1.0 * _x_x_32)) <= -5.0) && (((x_0 + (-1.0 * _x_x_32)) <= -4.0) && ((x_2 + (-1.0 * _x_x_32)) <= -11.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_32)) == -3.0) || (((x_28 + (-1.0 * _x_x_32)) == -14.0) || (((x_26 + (-1.0 * _x_x_32)) == -6.0) || (((x_25 + (-1.0 * _x_x_32)) == -14.0) || (((x_21 + (-1.0 * _x_x_32)) == -19.0) || (((x_17 + (-1.0 * _x_x_32)) == -12.0) || (((x_16 + (-1.0 * _x_x_32)) == -4.0) || (((x_15 + (-1.0 * _x_x_32)) == -13.0) || (((x_14 + (-1.0 * _x_x_32)) == -15.0) || (((x_12 + (-1.0 * _x_x_32)) == -16.0) || (((x_11 + (-1.0 * _x_x_32)) == -9.0) || (((x_10 + (-1.0 * _x_x_32)) == -1.0) || (((x_9 + (-1.0 * _x_x_32)) == -5.0) || (((x_7 + (-1.0 * _x_x_32)) == -6.0) || (((x_5 + (-1.0 * _x_x_32)) == -11.0) || (((x_4 + (-1.0 * _x_x_32)) == -5.0) || (((x_0 + (-1.0 * _x_x_32)) == -4.0) || ((x_2 + (-1.0 * _x_x_32)) == -11.0)))))))))))))))))))) && ((((x_33 + (-1.0 * _x_x_33)) <= -20.0) && (((x_32 + (-1.0 * _x_x_33)) <= -12.0) && (((x_31 + (-1.0 * _x_x_33)) <= -9.0) && (((x_29 + (-1.0 * _x_x_33)) <= -20.0) && (((x_25 + (-1.0 * _x_x_33)) <= -15.0) && (((x_23 + (-1.0 * _x_x_33)) <= -10.0) && (((x_22 + (-1.0 * _x_x_33)) <= -3.0) && (((x_21 + (-1.0 * _x_x_33)) <= -14.0) && (((x_19 + (-1.0 * _x_x_33)) <= -2.0) && (((x_17 + (-1.0 * _x_x_33)) <= -9.0) && (((x_16 + (-1.0 * _x_x_33)) <= -3.0) && (((x_15 + (-1.0 * _x_x_33)) <= -9.0) && (((x_14 + (-1.0 * _x_x_33)) <= -9.0) && (((x_13 + (-1.0 * _x_x_33)) <= -10.0) && (((x_12 + (-1.0 * _x_x_33)) <= -19.0) && (((x_3 + (-1.0 * _x_x_33)) <= -3.0) && (((x_0 + (-1.0 * _x_x_33)) <= -9.0) && ((x_1 + (-1.0 * _x_x_33)) <= -1.0)))))))))))))))))) && (((x_33 + (-1.0 * _x_x_33)) == -20.0) || (((x_32 + (-1.0 * _x_x_33)) == -12.0) || (((x_31 + (-1.0 * _x_x_33)) == -9.0) || (((x_29 + (-1.0 * _x_x_33)) == -20.0) || (((x_25 + (-1.0 * _x_x_33)) == -15.0) || (((x_23 + (-1.0 * _x_x_33)) == -10.0) || (((x_22 + (-1.0 * _x_x_33)) == -3.0) || (((x_21 + (-1.0 * _x_x_33)) == -14.0) || (((x_19 + (-1.0 * _x_x_33)) == -2.0) || (((x_17 + (-1.0 * _x_x_33)) == -9.0) || (((x_16 + (-1.0 * _x_x_33)) == -3.0) || (((x_15 + (-1.0 * _x_x_33)) == -9.0) || (((x_14 + (-1.0 * _x_x_33)) == -9.0) || (((x_13 + (-1.0 * _x_x_33)) == -10.0) || (((x_12 + (-1.0 * _x_x_33)) == -19.0) || (((x_3 + (-1.0 * _x_x_33)) == -3.0) || (((x_0 + (-1.0 * _x_x_33)) == -9.0) || ((x_1 + (-1.0 * _x_x_33)) == -1.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_34)) <= -20.0) && (((x_33 + (-1.0 * _x_x_34)) <= -10.0) && (((x_31 + (-1.0 * _x_x_34)) <= -10.0) && (((x_29 + (-1.0 * _x_x_34)) <= -14.0) && (((x_25 + (-1.0 * _x_x_34)) <= -6.0) && (((x_20 + (-1.0 * _x_x_34)) <= -9.0) && (((x_19 + (-1.0 * _x_x_34)) <= -6.0) && (((x_17 + (-1.0 * _x_x_34)) <= -5.0) && (((x_16 + (-1.0 * _x_x_34)) <= -19.0) && (((x_14 + (-1.0 * _x_x_34)) <= -10.0) && (((x_13 + (-1.0 * _x_x_34)) <= -14.0) && (((x_12 + (-1.0 * _x_x_34)) <= -15.0) && (((x_10 + (-1.0 * _x_x_34)) <= -8.0) && (((x_9 + (-1.0 * _x_x_34)) <= -13.0) && (((x_7 + (-1.0 * _x_x_34)) <= -7.0) && (((x_5 + (-1.0 * _x_x_34)) <= -9.0) && (((x_0 + (-1.0 * _x_x_34)) <= -7.0) && ((x_3 + (-1.0 * _x_x_34)) <= -2.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_34)) == -20.0) || (((x_33 + (-1.0 * _x_x_34)) == -10.0) || (((x_31 + (-1.0 * _x_x_34)) == -10.0) || (((x_29 + (-1.0 * _x_x_34)) == -14.0) || (((x_25 + (-1.0 * _x_x_34)) == -6.0) || (((x_20 + (-1.0 * _x_x_34)) == -9.0) || (((x_19 + (-1.0 * _x_x_34)) == -6.0) || (((x_17 + (-1.0 * _x_x_34)) == -5.0) || (((x_16 + (-1.0 * _x_x_34)) == -19.0) || (((x_14 + (-1.0 * _x_x_34)) == -10.0) || (((x_13 + (-1.0 * _x_x_34)) == -14.0) || (((x_12 + (-1.0 * _x_x_34)) == -15.0) || (((x_10 + (-1.0 * _x_x_34)) == -8.0) || (((x_9 + (-1.0 * _x_x_34)) == -13.0) || (((x_7 + (-1.0 * _x_x_34)) == -7.0) || (((x_5 + (-1.0 * _x_x_34)) == -9.0) || (((x_0 + (-1.0 * _x_x_34)) == -7.0) || ((x_3 + (-1.0 * _x_x_34)) == -2.0)))))))))))))))))))) && ((((x_34 + (-1.0 * _x_x_35)) <= -13.0) && (((x_33 + (-1.0 * _x_x_35)) <= -9.0) && (((x_32 + (-1.0 * _x_x_35)) <= -9.0) && (((x_31 + (-1.0 * _x_x_35)) <= -1.0) && (((x_29 + (-1.0 * _x_x_35)) <= -17.0) && (((x_27 + (-1.0 * _x_x_35)) <= -16.0) && (((x_24 + (-1.0 * _x_x_35)) <= -11.0) && (((x_23 + (-1.0 * _x_x_35)) <= -19.0) && (((x_19 + (-1.0 * _x_x_35)) <= -6.0) && (((x_17 + (-1.0 * _x_x_35)) <= -4.0) && (((x_13 + (-1.0 * _x_x_35)) <= -4.0) && (((x_11 + (-1.0 * _x_x_35)) <= -14.0) && (((x_9 + (-1.0 * _x_x_35)) <= -19.0) && (((x_7 + (-1.0 * _x_x_35)) <= -12.0) && (((x_3 + (-1.0 * _x_x_35)) <= -20.0) && (((x_2 + (-1.0 * _x_x_35)) <= -2.0) && (((x_0 + (-1.0 * _x_x_35)) <= -11.0) && ((x_1 + (-1.0 * _x_x_35)) <= -20.0)))))))))))))))))) && (((x_34 + (-1.0 * _x_x_35)) == -13.0) || (((x_33 + (-1.0 * _x_x_35)) == -9.0) || (((x_32 + (-1.0 * _x_x_35)) == -9.0) || (((x_31 + (-1.0 * _x_x_35)) == -1.0) || (((x_29 + (-1.0 * _x_x_35)) == -17.0) || (((x_27 + (-1.0 * _x_x_35)) == -16.0) || (((x_24 + (-1.0 * _x_x_35)) == -11.0) || (((x_23 + (-1.0 * _x_x_35)) == -19.0) || (((x_19 + (-1.0 * _x_x_35)) == -6.0) || (((x_17 + (-1.0 * _x_x_35)) == -4.0) || (((x_13 + (-1.0 * _x_x_35)) == -4.0) || (((x_11 + (-1.0 * _x_x_35)) == -14.0) || (((x_9 + (-1.0 * _x_x_35)) == -19.0) || (((x_7 + (-1.0 * _x_x_35)) == -12.0) || (((x_3 + (-1.0 * _x_x_35)) == -20.0) || (((x_2 + (-1.0 * _x_x_35)) == -2.0) || (((x_0 + (-1.0 * _x_x_35)) == -11.0) || ((x_1 + (-1.0 * _x_x_35)) == -20.0)))))))))))))))))))) && ((((_EL_U_3847 == (_x__EL_U_3847 || (-18.0 <= (_x_x_6 + (-1.0 * _x_x_8))))) && (_EL_U_3850 == (_x__EL_U_3850 || ( !((_x__EL_U_3847 || (-18.0 <= (_x_x_6 + (-1.0 * _x_x_8)))) || ( !(-1.0 <= (_x_x_9 + (-1.0 * _x_x_24))))))))) && (_x__J3864 == (( !(_J3864 && _J3876)) && ((_J3864 && _J3876) || (((-18.0 <= (x_6 + (-1.0 * x_8))) || ( !((-18.0 <= (x_6 + (-1.0 * x_8))) || _EL_U_3847))) || _J3864))))) && (_x__J3876 == (( !(_J3864 && _J3876)) && ((_J3864 && _J3876) || ((( !(( !(-1.0 <= (x_9 + (-1.0 * x_24)))) || ((-18.0 <= (x_6 + (-1.0 * x_8))) || _EL_U_3847))) || ( !(_EL_U_3850 || ( !(( !(-1.0 <= (x_9 + (-1.0 * x_24)))) || ((-18.0 <= (x_6 + (-1.0 * x_8))) || _EL_U_3847)))))) || _J3876)))))); _J3876 = _x__J3876; _J3864 = _x__J3864; _EL_U_3847 = _x__EL_U_3847; x_8 = _x_x_8; x_6 = _x_x_6; x_24 = _x_x_24; x_9 = _x_x_9; _EL_U_3850 = _x__EL_U_3850; x_26 = _x_x_26; x_28 = _x_x_28; x_1 = _x_x_1; x_15 = _x_x_15; x_0 = _x_x_0; x_5 = _x_x_5; x_2 = _x_x_2; x_21 = _x_x_21; x_3 = _x_x_3; x_22 = _x_x_22; x_10 = _x_x_10; x_7 = _x_x_7; x_12 = _x_x_12; x_11 = _x_x_11; x_14 = _x_x_14; x_13 = _x_x_13; x_16 = _x_x_16; x_17 = _x_x_17; x_19 = _x_x_19; x_20 = _x_x_20; x_23 = _x_x_23; x_25 = _x_x_25; x_35 = _x_x_35; x_27 = _x_x_27; x_29 = _x_x_29; x_18 = _x_x_18; x_31 = _x_x_31; x_32 = _x_x_32; x_33 = _x_x_33; x_4 = _x_x_4; x_30 = _x_x_30; x_34 = _x_x_34; } }
671220.c
//===--------------- fixtfsi_test.c - Test __fixtfsi ----------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file tests __fixtfsi for the compiler_rt library. // //===----------------------------------------------------------------------===// #include <stdio.h> #if __LDBL_MANT_DIG__ == 113 #include "fp_test.h" int __fixtfsi(long double a); int test__fixtfsi(long double a, int expected) { int x = __fixtfsi(a); int ret = (x != expected); if (ret){ printf("error in test__fixtfsi(%.20Lf) = %d, " "expected %d\n", a, x, expected); } return ret; } char assumption_1[sizeof(long double) * CHAR_BIT == 128] = {0}; #endif int main() { #if __LDBL_MANT_DIG__ == 113 if (test__fixtfsi(makeInf128(), 0x7fffffff)) return 1; if (test__fixtfsi(0, 0x0)) return 1; if (test__fixtfsi(0x1.23456789abcdefp+5, 0x24)) return 1; if (test__fixtfsi(0x1.23456789abcdefp-3, 0x0)) return 1; if (test__fixtfsi(0x1.23456789abcdefp+20, 0x123456)) return 1; if (test__fixtfsi(0x1.23456789abcdefp+40, 0x7fffffff)) return 1; if (test__fixtfsi(0x1.23456789abcdefp+256, 0x7fffffff)) return 1; if (test__fixtfsi(-0x1.23456789abcdefp+20, 0xffedcbaa)) return 1; if (test__fixtfsi(-0x1.23456789abcdefp+40, 0x80000001)) return 1; #else printf("skipped\n"); #endif return 0; }
962582.c
// unordered_map<string, unordered_map<string, string>>: #define i_key_str #define i_val_str #define i_tag sect #include <stc/csmap.h> #define i_key_str #define i_val csmap_sect #define i_valdel csmap_sect_del #define i_tag conf #include <stc/csmap.h> void add(csmap_conf* map, const char* section, const char* entry, const char* value) { csmap_sect *smap = &csmap_conf_insert(map, cstr_from(section), csmap_sect_init()).ref->second; csmap_sect_emplace_or_assign(smap, entry, value); } bool contains(csmap_conf* map, const char* section, const char* entry) { csmap_conf_value_t *val = csmap_conf_get(map, section); return val && csmap_sect_get(&val->second, entry); } int main(void) { c_auto (csmap_conf, map) { add(&map, "user", "name", "Joe"); add(&map, "user", "groups", "proj1,proj3"); add(&map, "group", "proj1", "Energy"); add(&map, "group", "proj2", "Windy"); add(&map, "group", "proj3", "Oil"); add(&map, "admin", "employees", "2302"); add(&map, "group", "proj2", "Wind"); // Update printf("contains: %d\n", contains(&map, "group", "employees")); printf("contains: %d\n", contains(&map, "admin", "name")); printf("contains: %d\n", contains(&map, "admin", "employees")); c_foreach (i, csmap_conf, map) c_foreach (j, csmap_sect, i.ref->second) printf("%s: %s - %s\n", i.ref->first.str, j.ref->first.str, j.ref->second.str); } }
656566.c
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <linux/if_ether.h> #include <linux/in.h> #define BUFFER_MAX 2048 typedef int int32; typedef unsigned int u_int32; typedef unsigned char u_char; typedef unsigned short u_short; //参考内核 struct ethhdr 定义 (include/uapi/linux/if_ether.h) typedef struct eth_hdr { char h_dest[6]; char h_source[6]; short h_proto; }__attribute__((packed)); //参考内核 struct iphdr 定义(include/uapi/linux/ip.h) typedef struct iphdr{ #ifdef __LITTLE_ENDIAN_BIFIELD u_char ip_len:4, ip_ver:4; #else u_char ip_ver:4, ip_len:4; #endif u_char tos; u_short total_len; u_short id; u_short flags_off; u_char ttl; u_char protocol; u_short check; u_int32 saddr; u_int32 daddr; }__attribute__((packed)); int main(int argc, char *argv[]) { int sock; char buffer[BUFFER_MAX]; int len; struct eth_hdr *mac_hdr; struct iphdr *ip_hdr; char* p; if( (sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0 ){ printf("Create socket error.\n"); exit(0); } while(1){ len = recvfrom(sock, buffer, BUFFER_MAX, 0, NULL, NULL); if (len < 46) { printf("Catch packet length error.\n" ); close(sock); exit(0); } printf("截获内容长度 %d\n", len); mac_hdr = buffer; ip_hdr = buffer + sizeof(struct ethhdr); printf("源 MAC:%X:%X:%X:%X:%X:%X", (u_char)mac_hdr->h_source[0], (u_char)mac_hdr->h_source[1], (u_char)mac_hdr->h_source[2], (u_char)mac_hdr->h_source[3], (u_char)mac_hdr->h_source[4], (u_char)mac_hdr->h_source[5] ); printf(" ==> 目的 MAC:%X:%X:%X:%X:%X\n", (u_char)mac_hdr->h_dest[0], (u_char)mac_hdr->h_dest[1], (u_char)mac_hdr->h_dest[2], (u_char)mac_hdr->h_dest[3], (u_char)mac_hdr->h_dest[4], (u_char)mac_hdr->h_dest[5] ); p = (char*)&ip_hdr->saddr; printf("源 IP: %d.%d.%d.%d", (u_char)p[0], (u_char)p[1], (u_char)p[2], (u_char)p[3] ); p = (char*)&ip_hdr->daddr; printf(" ==> 目的 IP: %d.%d.%d.%d\n", (u_char)p[0], (u_char)p[1], (u_char)p[2], (u_char)p[3] ); printf("协议类型:"); switch(ip_hdr->protocol) { case IPPROTO_ICMP: printf("ICMP"); break; case IPPROTO_IGMP: printf("IGMP"); break; case IPPROTO_IPIP: printf("IPIP"); break; case IPPROTO_TCP: printf("TCP"); break; case IPPROTO_UDP: printf("UDP"); break; case IPPROTO_RAW: printf("RAW"); break; default: printf("Unknown type"); break; } printf("\n\n"); } close(sock); return 0; }
416734.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* This indenter doesn't really work, it's here for no particular reason. */ #include "zend.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_indent.h" #define zendtext LANG_SCNG(yy_text) #define zendleng LANG_SCNG(yy_leng) static void handle_whitespace(int *emit_whitespace) { unsigned char c; int i; for (c=0; c<128; c++) { if (emit_whitespace[c]>0) { for (i=0; i<emit_whitespace[c]; i++) { zend_write((char *) &c, 1); } } } memset(emit_whitespace, 0, sizeof(int)*256); } ZEND_API void zend_indent() { zval token; int token_type; int in_string=0; int nest_level=0; int emit_whitespace[256]; int i; TSRMLS_FETCH(); memset(emit_whitespace, 0, sizeof(int)*256); /* highlight stuff coming back from zendlex() */ token.type = 0; while ((token_type=lex_scan(&token TSRMLS_CC))) { switch (token_type) { case T_INLINE_HTML: zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); break; case T_WHITESPACE: { token.type = 0; /* eat whitespace, emit newlines */ for (i=0; i<LANG_SCNG(yy_leng); i++) { emit_whitespace[(unsigned char) LANG_SCNG(yy_text)[i]]++; } continue; } break; case '"': in_string = !in_string; /* break missing intentionally */ default: if (token.type==0) { /* keyword */ switch (token_type) { case ',': ZEND_PUTS(", "); goto dflt_printout; break; case '{': nest_level++; if (emit_whitespace['\n']>0) { ZEND_PUTS(" {\n"); memset(emit_whitespace, 0, sizeof(int)*256); } else { ZEND_PUTS("{"); } break; case '}': nest_level--; if (emit_whitespace['\n']==0) { ZEND_PUTS("\n"); } for (i=0; i<nest_level; i++) { ZEND_PUTS(" "); } goto dflt_printout; break; dflt_printout: default: if (emit_whitespace['\n']>0) { for (i=0; i<emit_whitespace['\n']; i++) { ZEND_PUTS("\n"); } memset(emit_whitespace, 0, sizeof(int)*256); for (i=0; i<nest_level; i++) { ZEND_PUTS(" "); } } else { handle_whitespace(emit_whitespace); } zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); break; } } else { handle_whitespace(emit_whitespace); if (in_string) { zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); /* a part of a string */ } else { zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); } } break; } if (token.type == IS_STRING) { switch (token_type) { case T_OPEN_TAG: case T_CLOSE_TAG: case T_WHITESPACE: break; default: efree(token.value.str.val); break; } } token.type = 0; } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
431072.c
/* * Copyright 2010 Piotr Caban 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 */ #include "config.h" #include <stdarg.h> #include "msvcp90.h" #include "windef.h" #include "winbase.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(msvcp); #define CLASS_IS_SIMPLE_TYPE 1 #define CLASS_HAS_VIRTUAL_BASE_CLASS 4 void WINAPI _CxxThrowException(exception*,const cxx_exception_type*); /* vtables */ extern const vtable_ptr MSVCP_exception_vtable; extern const vtable_ptr MSVCP_bad_alloc_vtable; extern const vtable_ptr MSVCP_logic_error_vtable; extern const vtable_ptr MSVCP_length_error_vtable; extern const vtable_ptr MSVCP_out_of_range_vtable; extern const vtable_ptr MSVCP_invalid_argument_vtable; extern const vtable_ptr MSVCP_runtime_error_vtable; extern const vtable_ptr MSVCP_failure_vtable; static void MSVCP_type_info_dtor(type_info * _this) { free(_this->name); } /* Unexported */ DEFINE_THISCALL_WRAPPER(MSVCP_type_info_vector_dtor,8) void * __thiscall MSVCP_type_info_vector_dtor(type_info * _this, unsigned int flags) { TRACE("(%p %x)\n", _this, flags); if (flags & 2) { /* we have an array, with the number of elements stored before the first object */ INT_PTR i, *ptr = (INT_PTR *)_this - 1; for (i = *ptr - 1; i >= 0; i--) MSVCP_type_info_dtor(_this + i); MSVCRT_operator_delete(ptr); } else { MSVCP_type_info_dtor(_this); if (flags & 1) MSVCRT_operator_delete(_this); } return _this; } DEFINE_RTTI_DATA0( type_info, 0, ".?AVtype_info@@" ) static exception* MSVCP_exception_ctor(exception *this, const char **name) { TRACE("(%p %s)\n", this, *name); this->vtable = &MSVCP_exception_vtable; if(*name) { unsigned int name_len = strlen(*name) + 1; this->name = malloc(name_len); memcpy(this->name, *name, name_len); this->do_free = TRUE; } else { this->name = NULL; this->do_free = FALSE; } return this; } DEFINE_THISCALL_WRAPPER(MSVCP_exception_copy_ctor,8) exception* __thiscall MSVCP_exception_copy_ctor(exception *this, const exception *rhs) { TRACE("(%p,%p)\n", this, rhs); if(!rhs->do_free) { this->vtable = &MSVCP_exception_vtable; this->name = rhs->name; this->do_free = FALSE; } else MSVCP_exception_ctor(this, (const char**)&rhs->name); TRACE("name = %s\n", this->name); return this; } DEFINE_THISCALL_WRAPPER(MSVCP_exception_dtor,4) void __thiscall MSVCP_exception_dtor(exception *this) { TRACE("(%p)\n", this); this->vtable = &MSVCP_exception_vtable; if(this->do_free) free(this->name); } DEFINE_THISCALL_WRAPPER(MSVCP_exception_vector_dtor, 8) void * __thiscall MSVCP_exception_vector_dtor(exception *this, unsigned int flags) { TRACE("%p %x\n", this, flags); if(flags & 2) { /* we have an array, with the number of elements stored before the first object */ INT_PTR i, *ptr = (INT_PTR *)this-1; for(i=*ptr-1; i>=0; i--) MSVCP_exception_dtor(this+i); MSVCRT_operator_delete(ptr); } else { MSVCP_exception_dtor(this); if(flags & 1) MSVCRT_operator_delete(this); } return this; } DEFINE_RTTI_DATA0(exception, 0, ".?AVexception@std@@") DEFINE_CXX_DATA0(exception, MSVCP_exception_dtor) /* bad_alloc class data */ typedef exception bad_alloc; static bad_alloc* MSVCP_bad_alloc_ctor(bad_alloc *this, const char **name) { TRACE("%p %s\n", this, *name); MSVCP_exception_ctor(this, name); this->vtable = &MSVCP_bad_alloc_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_bad_alloc_copy_ctor, 8) bad_alloc* __thiscall MSVCP_bad_alloc_copy_ctor(bad_alloc *this, const bad_alloc *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_exception_copy_ctor(this, rhs); this->vtable = &MSVCP_bad_alloc_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_bad_alloc_dtor, 4) void __thiscall MSVCP_bad_alloc_dtor(bad_alloc *this) { TRACE("%p\n", this); MSVCP_exception_dtor(this); } DEFINE_THISCALL_WRAPPER(MSVCP_bad_alloc_vector_dtor, 8) void * __thiscall MSVCP_bad_alloc_vector_dtor(bad_alloc *this, unsigned int flags) { TRACE("%p %x\n", this, flags); if(flags & 2) { /* we have an array, with the number of elements stored before the first object */ INT_PTR i, *ptr = (INT_PTR *)this-1; for(i=*ptr-1; i>=0; i--) MSVCP_bad_alloc_dtor(this+i); MSVCRT_operator_delete(ptr); } else { MSVCP_bad_alloc_dtor(this); if(flags & 1) MSVCRT_operator_delete(this); } return this; } DEFINE_THISCALL_WRAPPER(MSVCP_what_exception,4) const char* __thiscall MSVCP_what_exception(exception * this) { TRACE("(%p) returning %s\n", this, this->name); return this->name ? this->name : "Unknown exception"; } DEFINE_RTTI_DATA1(bad_alloc, 0, &exception_rtti_base_descriptor, ".?AVbad_alloc@std@@") DEFINE_CXX_DATA1(bad_alloc, &exception_cxx_type_info, MSVCP_bad_alloc_dtor) /* logic_error class data */ typedef struct _logic_error { exception e; basic_string_char str; } logic_error; static logic_error* MSVCP_logic_error_ctor( logic_error *this, const char **name) { TRACE("%p %s\n", this, *name); this->e.vtable = &MSVCP_logic_error_vtable; this->e.name = NULL; this->e.do_free = FALSE; MSVCP_basic_string_char_ctor_cstr(&this->str, *name); return this; } DEFINE_THISCALL_WRAPPER(MSVCP_logic_error_copy_ctor, 8) logic_error* __thiscall MSVCP_logic_error_copy_ctor( logic_error *this, logic_error *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_exception_copy_ctor(&this->e, &rhs->e); MSVCP_basic_string_char_copy_ctor(&this->str, &rhs->str); this->e.vtable = &MSVCP_logic_error_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_logic_error_dtor, 4) void __thiscall MSVCP_logic_error_dtor(logic_error *this) { TRACE("%p\n", this); MSVCP_exception_dtor(&this->e); MSVCP_basic_string_char_dtor(&this->str); } DEFINE_THISCALL_WRAPPER(MSVCP_logic_error_vector_dtor, 8) void* __thiscall MSVCP_logic_error_vector_dtor( logic_error *this, unsigned int flags) { TRACE("%p %x\n", this, flags); if(flags & 2) { /* we have an array, with the number of elements stored before the first object */ INT_PTR i, *ptr = (INT_PTR *)this-1; for(i=*ptr-1; i>=0; i--) MSVCP_logic_error_dtor(this+i); MSVCRT_operator_delete(ptr); } else { MSVCP_logic_error_dtor(this); if(flags & 1) MSVCRT_operator_delete(this); } return this; } DEFINE_THISCALL_WRAPPER(MSVCP_logic_error_what, 4) const char* __thiscall MSVCP_logic_error_what(logic_error *this) { TRACE("%p\n", this); return MSVCP_basic_string_char_c_str(&this->str); } DEFINE_RTTI_DATA1(logic_error, 0, &exception_rtti_base_descriptor, ".?AVlogic_error@std@@") DEFINE_CXX_DATA1(logic_error, &exception_cxx_type_info, MSVCP_logic_error_dtor) /* length_error class data */ typedef logic_error length_error; static length_error* MSVCP_length_error_ctor( length_error *this, const char **name) { TRACE("%p %s\n", this, *name); MSVCP_logic_error_ctor(this, name); this->e.vtable = &MSVCP_length_error_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_length_error_copy_ctor, 8) length_error* __thiscall MSVCP_length_error_copy_ctor( length_error *this, length_error *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_logic_error_copy_ctor(this, rhs); this->e.vtable = &MSVCP_length_error_vtable; return this; } DEFINE_RTTI_DATA2(length_error, 0, &logic_error_rtti_base_descriptor, &exception_rtti_base_descriptor, ".?AVlength_error@std@@") DEFINE_CXX_DATA2(length_error, &logic_error_cxx_type_info, &exception_cxx_type_info, MSVCP_logic_error_dtor) /* out_of_range class data */ typedef logic_error out_of_range; static out_of_range* MSVCP_out_of_range_ctor( out_of_range *this, const char **name) { TRACE("%p %s\n", this, *name); MSVCP_logic_error_ctor(this, name); this->e.vtable = &MSVCP_out_of_range_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_out_of_range_copy_ctor, 8) out_of_range* __thiscall MSVCP_out_of_range_copy_ctor( out_of_range *this, out_of_range *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_logic_error_copy_ctor(this, rhs); this->e.vtable = &MSVCP_out_of_range_vtable; return this; } DEFINE_RTTI_DATA2(out_of_range, 0, &logic_error_rtti_base_descriptor, &exception_rtti_base_descriptor, ".?AVout_of_range@std@@") DEFINE_CXX_DATA2(out_of_range, &logic_error_cxx_type_info, &exception_cxx_type_info, MSVCP_logic_error_dtor) /* invalid_argument class data */ typedef logic_error invalid_argument; static invalid_argument* MSVCP_invalid_argument_ctor( invalid_argument *this, const char **name) { TRACE("%p %s\n", this, *name); MSVCP_logic_error_ctor(this, name); this->e.vtable = &MSVCP_invalid_argument_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_invalid_argument_copy_ctor, 8) invalid_argument* __thiscall MSVCP_invalid_argument_copy_ctor( invalid_argument *this, invalid_argument *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_logic_error_copy_ctor(this, rhs); this->e.vtable = &MSVCP_invalid_argument_vtable; return this; } DEFINE_RTTI_DATA2(invalid_argument, 0, &logic_error_rtti_base_descriptor, &exception_rtti_base_descriptor, ".?AVinvalid_argument@std@@") DEFINE_CXX_DATA2(invalid_argument, &logic_error_cxx_type_info, &exception_cxx_type_info, MSVCP_logic_error_dtor) /* runtime_error class data */ typedef struct { exception e; basic_string_char str; } runtime_error; static runtime_error* MSVCP_runtime_error_ctor( runtime_error *this, const char **name) { TRACE("%p %s\n", this, *name); this->e.vtable = &MSVCP_runtime_error_vtable; this->e.name = NULL; this->e.do_free = FALSE; MSVCP_basic_string_char_ctor_cstr(&this->str, *name); return this; } DEFINE_THISCALL_WRAPPER(MSVCP_runtime_error_copy_ctor, 8) runtime_error* __thiscall MSVCP_runtime_error_copy_ctor( runtime_error *this, runtime_error *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_exception_copy_ctor(&this->e, &rhs->e); MSVCP_basic_string_char_copy_ctor(&this->str, &rhs->str); this->e.vtable = &MSVCP_runtime_error_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_runtime_error_dtor, 4) void __thiscall MSVCP_runtime_error_dtor(runtime_error *this) { TRACE("%p\n", this); MSVCP_exception_dtor(&this->e); MSVCP_basic_string_char_dtor(&this->str); } DEFINE_THISCALL_WRAPPER(MSVCP_runtime_error_vector_dtor, 8) void* __thiscall MSVCP_runtime_error_vector_dtor( runtime_error *this, unsigned int flags) { TRACE("%p %x\n", this, flags); if(flags & 2) { /* we have an array, with the number of elements stored before the first object */ INT_PTR i, *ptr = (INT_PTR *)this-1; for(i=*ptr-1; i>=0; i--) MSVCP_runtime_error_dtor(this+i); MSVCRT_operator_delete(ptr); } else { MSVCP_runtime_error_dtor(this); if(flags & 1) MSVCRT_operator_delete(this); } return this; } DEFINE_THISCALL_WRAPPER(MSVCP_runtime_error_what, 4) const char* __thiscall MSVCP_runtime_error_what(runtime_error *this) { TRACE("%p\n", this); return MSVCP_basic_string_char_c_str(&this->str); } DEFINE_RTTI_DATA1(runtime_error, 0, &exception_rtti_base_descriptor, ".?AVruntime_error@std@@") DEFINE_CXX_DATA1(runtime_error, &exception_cxx_type_info, MSVCP_runtime_error_dtor) /* failure class data */ typedef runtime_error failure; static failure* MSVCP_failure_ctor( failure *this, const char **name) { TRACE("%p %s\n", this, *name); MSVCP_runtime_error_ctor(this, name); this->e.vtable = &MSVCP_failure_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_failure_copy_ctor, 8) failure* __thiscall MSVCP_failure_copy_ctor( failure *this, failure *rhs) { TRACE("%p %p\n", this, rhs); MSVCP_runtime_error_copy_ctor(this, rhs); this->e.vtable = &MSVCP_failure_vtable; return this; } DEFINE_THISCALL_WRAPPER(MSVCP_failure_dtor, 4) void __thiscall MSVCP_failure_dtor(failure *this) { TRACE("%p\n", this); MSVCP_runtime_error_dtor(this); } DEFINE_THISCALL_WRAPPER(MSVCP_failure_vector_dtor, 8) void* __thiscall MSVCP_failure_vector_dtor( failure *this, unsigned int flags) { TRACE("%p %x\n", this, flags); return MSVCP_runtime_error_vector_dtor(this, flags); } DEFINE_THISCALL_WRAPPER(MSVCP_failure_what, 4) const char* __thiscall MSVCP_failure_what(failure *this) { TRACE("%p\n", this); return MSVCP_runtime_error_what(this); } DEFINE_RTTI_DATA2(failure, 0, &runtime_error_rtti_base_descriptor, &exception_rtti_base_descriptor, ".?AVfailure@std@@") DEFINE_CXX_DATA2(failure, &runtime_error_cxx_type_info, &exception_cxx_type_info, MSVCP_runtime_error_dtor) /* ?_Nomemory@std@@YAXXZ */ void __cdecl _Nomemory(void) { TRACE("()\n"); throw_exception(EXCEPTION_BAD_ALLOC, NULL); } /* ?_Xmem@tr1@std@@YAXXZ */ void __cdecl _Xmem(void) { TRACE("()\n"); throw_exception(EXCEPTION_BAD_ALLOC, NULL); } /* ?_Xinvalid_argument@std@@YAXPBD@Z */ /* ?_Xinvalid_argument@std@@YAXPEBD@Z */ void __cdecl _Xinvalid_argument(const char *str) { TRACE("(%s)\n", debugstr_a(str)); throw_exception(EXCEPTION_INVALID_ARGUMENT, str); } /* ?_Xlength_error@std@@YAXPBD@Z */ /* ?_Xlength_error@std@@YAXPEBD@Z */ void __cdecl _Xlength_error(const char *str) { TRACE("(%s)\n", debugstr_a(str)); throw_exception(EXCEPTION_LENGTH_ERROR, str); } /* ?_Xout_of_range@std@@YAXPBD@Z */ /* ?_Xout_of_range@std@@YAXPEBD@Z */ void __cdecl _Xout_of_range(const char *str) { TRACE("(%s)\n", debugstr_a(str)); throw_exception(EXCEPTION_OUT_OF_RANGE, str); } /* ?_Xruntime_error@std@@YAXPBD@Z */ /* ?_Xruntime_error@std@@YAXPEBD@Z */ void __cdecl _Xruntime_error(const char *str) { TRACE("(%s)\n", debugstr_a(str)); throw_exception(EXCEPTION_RUNTIME_ERROR, str); } /* ?uncaught_exception@std@@YA_NXZ */ MSVCP_bool __cdecl MSVCP__uncaught_exception(void) { return __uncaught_exception(); } #ifndef __GNUC__ void __asm_dummy_vtables(void) { #endif __ASM_VTABLE(type_info, VTABLE_ADD_FUNC(MSVCP_type_info_vector_dtor)); __ASM_VTABLE(exception, VTABLE_ADD_FUNC(MSVCP_exception_vector_dtor) VTABLE_ADD_FUNC(MSVCP_what_exception)); __ASM_VTABLE(bad_alloc, VTABLE_ADD_FUNC(MSVCP_bad_alloc_vector_dtor) VTABLE_ADD_FUNC(MSVCP_what_exception)); __ASM_VTABLE(logic_error, VTABLE_ADD_FUNC(MSVCP_logic_error_vector_dtor) VTABLE_ADD_FUNC(MSVCP_logic_error_what)); __ASM_VTABLE(length_error, VTABLE_ADD_FUNC(MSVCP_logic_error_vector_dtor) VTABLE_ADD_FUNC(MSVCP_logic_error_what)); __ASM_VTABLE(out_of_range, VTABLE_ADD_FUNC(MSVCP_logic_error_vector_dtor) VTABLE_ADD_FUNC(MSVCP_logic_error_what)); __ASM_VTABLE(invalid_argument, VTABLE_ADD_FUNC(MSVCP_logic_error_vector_dtor) VTABLE_ADD_FUNC(MSVCP_logic_error_what)); __ASM_VTABLE(runtime_error, VTABLE_ADD_FUNC(MSVCP_runtime_error_vector_dtor) VTABLE_ADD_FUNC(MSVCP_runtime_error_what)); __ASM_VTABLE(failure, VTABLE_ADD_FUNC(MSVCP_failure_vector_dtor) VTABLE_ADD_FUNC(MSVCP_failure_what)); #ifndef __GNUC__ } #endif /* Internal: throws selected exception */ void throw_exception(exception_type et, const char *str) { const char *addr = str; switch(et) { case EXCEPTION_RERAISE: _CxxThrowException(NULL, NULL); case EXCEPTION: { exception e; MSVCP_exception_ctor(&e, &addr); _CxxThrowException(&e, &exception_cxx_type); } case EXCEPTION_BAD_ALLOC: { bad_alloc e; MSVCP_bad_alloc_ctor(&e, &addr); _CxxThrowException(&e, &bad_alloc_cxx_type); } case EXCEPTION_LOGIC_ERROR: { logic_error e; MSVCP_logic_error_ctor(&e, &addr); _CxxThrowException((exception*)&e, &logic_error_cxx_type); } case EXCEPTION_LENGTH_ERROR: { length_error e; MSVCP_length_error_ctor(&e, &addr); _CxxThrowException((exception*)&e, &length_error_cxx_type); } case EXCEPTION_OUT_OF_RANGE: { out_of_range e; MSVCP_out_of_range_ctor(&e, &addr); _CxxThrowException((exception*)&e, &out_of_range_cxx_type); } case EXCEPTION_INVALID_ARGUMENT: { invalid_argument e; MSVCP_invalid_argument_ctor(&e, &addr); _CxxThrowException((exception*)&e, &invalid_argument_cxx_type); } case EXCEPTION_RUNTIME_ERROR: { runtime_error e; MSVCP_runtime_error_ctor(&e, &addr); _CxxThrowException((exception*)&e, &runtime_error_cxx_type); } case EXCEPTION_FAILURE: { failure e; MSVCP_failure_ctor(&e, &addr); _CxxThrowException((exception*)&e, &failure_cxx_type); } } } void init_exception(void *base) { #ifdef __x86_64__ init_type_info_rtti(base); init_exception_rtti(base); init_bad_alloc_rtti(base); init_logic_error_rtti(base); init_length_error_rtti(base); init_out_of_range_rtti(base); init_invalid_argument_rtti(base); init_runtime_error_rtti(base); init_failure_rtti(base); init_exception_cxx(base); init_bad_alloc_cxx(base); init_logic_error_cxx(base); init_length_error_cxx(base); init_out_of_range_cxx(base); init_invalid_argument_cxx(base); init_runtime_error_cxx(base); init_failure_cxx(base); #endif }
68731.c
/*- * Copyright (c) 1991, 1993, 1995 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * 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. * * @(#)ufs_inode.c 8.9 (Berkeley) 5/14/95 */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/ufs/ufs/ufs_inode.c 235626 2012-05-18 19:48:38Z mckusick $"); #include "opt_quota.h" #include "opt_ufs.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/vnode.h> #include <sys/lock.h> #include <sys/mount.h> #include <sys/malloc.h> #include <sys/mutex.h> #include <ufs/ufs/extattr.h> #include <ufs/ufs/quota.h> #include <ufs/ufs/inode.h> #include <ufs/ufs/ufsmount.h> #include <ufs/ufs/ufs_extern.h> #ifdef UFS_DIRHASH #include <ufs/ufs/dir.h> #include <ufs/ufs/dirhash.h> #endif #ifdef UFS_GJOURNAL #include <ufs/ufs/gjournal.h> #endif /* * Last reference to an inode. If necessary, write or delete it. */ int ufs_inactive(ap) struct vop_inactive_args /* { struct vnode *a_vp; struct thread *a_td; } */ *ap; { struct vnode *vp = ap->a_vp; struct inode *ip = VTOI(vp); struct thread *td = ap->a_td; mode_t mode; int error = 0; off_t isize; struct mount *mp; mp = NULL; /* * Ignore inodes related to stale file handles. */ if (ip->i_mode == 0) goto out; #ifdef UFS_GJOURNAL ufs_gjournal_close(vp); #endif #ifdef QUOTA /* * Before moving off the active list, we must be sure that * any modified quotas have been pushed since these will no * longer be checked once the vnode is on the inactive list. */ qsyncvp(vp); #endif if ((ip->i_effnlink == 0 && DOINGSOFTDEP(vp)) || (ip->i_nlink <= 0 && !UFS_RDONLY(ip))) { loop: if (vn_start_secondary_write(vp, &mp, V_NOWAIT) != 0) { /* Cannot delete file while file system is suspended */ if ((vp->v_iflag & VI_DOOMED) != 0) { /* Cannot return before file is deleted */ (void) vn_start_secondary_write(vp, &mp, V_WAIT); } else { MNT_ILOCK(mp); if ((mp->mnt_kern_flag & (MNTK_SUSPEND2 | MNTK_SUSPENDED)) == 0) { MNT_IUNLOCK(mp); goto loop; } /* * Fail to inactivate vnode now and * let ffs_snapshot() clean up after * it has resumed the file system. */ VI_LOCK(vp); vp->v_iflag |= VI_OWEINACT; VI_UNLOCK(vp); MNT_IUNLOCK(mp); return (0); } } } isize = ip->i_size; if (ip->i_ump->um_fstype == UFS2) isize += ip->i_din2->di_extsize; if (ip->i_effnlink <= 0 && isize && !UFS_RDONLY(ip)) error = UFS_TRUNCATE(vp, (off_t)0, IO_EXT | IO_NORMAL, NOCRED, td); if (ip->i_nlink <= 0 && ip->i_mode && !UFS_RDONLY(ip)) { #ifdef QUOTA if (!getinoquota(ip)) (void)chkiq(ip, -1, NOCRED, FORCE); #endif #ifdef UFS_EXTATTR ufs_extattr_vnode_inactive(vp, td); #endif /* * Setting the mode to zero needs to wait for the inode * to be written just as does a change to the link count. * So, rather than creating a new entry point to do the * same thing, we just use softdep_change_linkcnt(). */ DIP_SET(ip, i_rdev, 0); mode = ip->i_mode; ip->i_mode = 0; DIP_SET(ip, i_mode, 0); ip->i_flag |= IN_CHANGE | IN_UPDATE; if (DOINGSOFTDEP(vp)) softdep_change_linkcnt(ip); UFS_VFREE(vp, ip->i_number, mode); } if (ip->i_flag & (IN_ACCESS | IN_CHANGE | IN_MODIFIED | IN_UPDATE)) { if ((ip->i_flag & (IN_CHANGE | IN_UPDATE | IN_MODIFIED)) == 0 && mp == NULL && vn_start_secondary_write(vp, &mp, V_NOWAIT)) { mp = NULL; ip->i_flag &= ~IN_ACCESS; } else { if (mp == NULL) (void) vn_start_secondary_write(vp, &mp, V_WAIT); UFS_UPDATE(vp, 0); } } out: /* * If we are done with the inode, reclaim it * so that it can be reused immediately. */ if (ip->i_mode == 0) vrecycle(vp, td); if (mp != NULL) vn_finished_secondary_write(mp); return (error); } void ufs_prepare_reclaim(struct vnode *vp) { struct inode *ip; #ifdef QUOTA int i; #endif ip = VTOI(vp); vnode_destroy_vobject(vp); #ifdef QUOTA for (i = 0; i < MAXQUOTAS; i++) { if (ip->i_dquot[i] != NODQUOT) { dqrele(vp, ip->i_dquot[i]); ip->i_dquot[i] = NODQUOT; } } #endif #ifdef UFS_DIRHASH if (ip->i_dirhash != NULL) ufsdirhash_free(ip); #endif } /* * Reclaim an inode so that it can be used for other purposes. */ int ufs_reclaim(ap) struct vop_reclaim_args /* { struct vnode *a_vp; struct thread *a_td; } */ *ap; { struct vnode *vp = ap->a_vp; struct inode *ip = VTOI(vp); struct ufsmount *ump = ip->i_ump; ufs_prepare_reclaim(vp); if (ip->i_flag & IN_LAZYMOD) ip->i_flag |= IN_MODIFIED; UFS_UPDATE(vp, 0); /* * Remove the inode from its hash chain. */ vfs_hash_remove(vp); /* * Lock the clearing of v_data so ffs_lock() can inspect it * prior to obtaining the lock. */ VI_LOCK(vp); vp->v_data = 0; VI_UNLOCK(vp); UFS_IFREE(ump, ip); return (0); }
597845.c
/* Copyright (c) 2017 Pieter Wuille * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "internal.h" #include <stdlib.h> #include <stdint.h> #include <include/wally_address.h> #include <include/wally_script.h> #include <include/wally_crypto.h> #include "script.h" #ifdef BUILD_ELEMENTS static uint64_t blech32_polymod_step(uint64_t pre) { uint8_t b = pre >> 55; return ((pre & 0x7fffffffffffffULL) << 5) ^ (-((b >> 0) & 1) & 0x7d52fba40bd886ULL) ^ (-((b >> 1) & 1) & 0x5e8dbf1a03950cULL) ^ (-((b >> 2) & 1) & 0x1c3a3c74072a18ULL) ^ (-((b >> 3) & 1) & 0x385d72fa0e5139ULL) ^ (-((b >> 4) & 1) & 0x7093e5a608865bULL); } static const char *blech32_charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; static const int8_t blech32_charset_rev[128] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 }; #define WALLY_BLECH32_MAXLEN ((size_t) 1000) static int blech32_encode(char *output, const char *hrp, const uint8_t *data, size_t data_len, size_t max_input_len) { uint64_t chk = 1; size_t i = 0; while (hrp[i] != 0) { int ch = hrp[i]; if (ch < 33 || ch > 126) { return 0; } if (ch >= 'A' && ch <= 'Z') return 0; chk = blech32_polymod_step(chk) ^ (ch >> 5); ++i; } if (i + 13 + data_len > max_input_len) return 0; chk = blech32_polymod_step(chk); while (*hrp != 0) { chk = blech32_polymod_step(chk) ^ (*hrp & 0x1f); *(output++) = *(hrp++); } *(output++) = '1'; for (i = 0; i < data_len; ++i) { if (*data >> 5) return 0; chk = blech32_polymod_step(chk) ^ (*data); *(output++) = blech32_charset[*(data++)]; } for (i = 0; i < 12; ++i) { chk = blech32_polymod_step(chk); } chk ^= 1; for (i = 0; i < 12; ++i) { *(output++) = blech32_charset[(chk >> ((11 - i) * 5)) & 0x1f]; } *output = 0; return 1; } static int blech32_decode(char *hrp, uint8_t *data, size_t *data_len, const char *input, size_t max_input_len) { uint64_t chk = 1; size_t i; size_t input_len = strlen(input); size_t hrp_len; int have_lower = 0, have_upper = 0; if (input_len < 8 || input_len > max_input_len) { return 0; } *data_len = 0; while (*data_len < input_len && input[(input_len - 1) - *data_len] != '1') { ++(*data_len); } if (1 + *data_len >= input_len || *data_len < 12) { return 0; } hrp_len = input_len - (1 + *data_len); *(data_len) -= 12; for (i = 0; i < hrp_len; ++i) { int ch = input[i]; if (ch < 33 || ch > 126) { return 0; } if (ch >= 'a' && ch <= 'z') { have_lower = 1; } else if (ch >= 'A' && ch <= 'Z') { have_upper = 1; ch = (ch - 'A') + 'a'; } hrp[i] = ch; chk = blech32_polymod_step(chk) ^ (ch >> 5); } hrp[i] = 0; chk = blech32_polymod_step(chk); for (i = 0; i < hrp_len; ++i) { chk = blech32_polymod_step(chk) ^ (input[i] & 0x1f); } ++i; while (i < input_len) { int v = (input[i] & 0x80) ? -1 : blech32_charset_rev[(int)input[i]]; if (input[i] >= 'a' && input[i] <= 'z') have_lower = 1; if (input[i] >= 'A' && input[i] <= 'Z') have_upper = 1; if (v == -1) { return 0; } chk = blech32_polymod_step(chk) ^ v; if (i + 12 < input_len) { data[i - (1 + hrp_len)] = v; } ++i; } if (have_lower && have_upper) { return 0; } return chk == 1; } static int blech32_convert_bits(uint8_t *out, size_t *outlen, int outbits, const uint8_t *in, size_t inlen, int inbits, int pad) { uint32_t val = 0; int bits = 0; uint32_t maxv = (((uint32_t)1) << outbits) - 1; while (inlen--) { val = (val << inbits) | *(in++); bits += inbits; while (bits >= outbits) { bits -= outbits; out[(*outlen)++] = (val >> bits) & maxv; } } if (pad) { if (bits) { out[(*outlen)++] = (val << (outbits - bits)) & maxv; } } else if (((val << (outbits - bits)) & maxv) || bits >= inbits) { return 0; } return 1; } static int blech32_addr_encode(char *output, const char *hrp, int witver, const uint8_t *witprog, size_t witprog_len) { uint8_t data[WALLY_BLECH32_MAXLEN]; size_t datalen = 0; if (witver > 16) goto fail; if (witver == 0 && witprog_len != 53 && witprog_len != 65) goto fail; if (witprog_len < 2 || witprog_len > 65) goto fail; data[0] = witver; blech32_convert_bits(data + 1, &datalen, 5, witprog, witprog_len, 8, 1); ++datalen; return blech32_encode(output, hrp, data, datalen, WALLY_BLECH32_MAXLEN); fail: wally_clear_2(data, sizeof(data), (void *)witprog, witprog_len); return 0; } static int blech32_addr_decode(int *witver, uint8_t *witdata, size_t *witdata_len, const char *hrp, const char *addr) { uint8_t data[WALLY_BLECH32_MAXLEN]; char hrp_actual[WALLY_BLECH32_MAXLEN]; size_t data_len; if (!blech32_decode(hrp_actual, data, &data_len, addr, WALLY_BLECH32_MAXLEN)) goto fail; if (data_len == 0 || data_len > (WALLY_BLECH32_MAXLEN - 4)) goto fail; if (strncmp(hrp, hrp_actual, WALLY_BLECH32_MAXLEN - 5) != 0) goto fail; if (data[0] > 16) goto fail; *witdata_len = 0; if (!blech32_convert_bits(witdata, witdata_len, 8, data + 1, data_len - 1, 5, 0)) goto fail; if (*witdata_len < 2 || *witdata_len > 65) goto fail; if (data[0] == 0 && *witdata_len != 53 && *witdata_len != 65) goto fail; *witver = data[0]; return 1; fail: wally_clear_2(data, sizeof(data), hrp_actual, sizeof(hrp_actual)); return 0; } int wally_confidential_addr_to_addr_segwit( const char *address, const char *confidential_addr_family, const char *addr_family, char **output) { unsigned char buf[WALLY_BLECH32_MAXLEN]; unsigned char *hash_bytes_p = &buf[EC_PUBLIC_KEY_LEN - 2]; int witver = 0; size_t written = 0; int ret; if (output) *output = NULL; if (!address || !output) return WALLY_EINVAL; if (!blech32_addr_decode(&witver, buf, &written, confidential_addr_family, address)) ret = WALLY_EINVAL; else if (witver != 0 || (written != 53 && written != 65)) ret = WALLY_EINVAL; /* Only v0 witness programs are currently allowed */ else { written = written - EC_PUBLIC_KEY_LEN + 2; hash_bytes_p[0] = (unsigned char) witver; hash_bytes_p[1] = (unsigned char) (written - 2); ret = wally_addr_segwit_from_bytes(hash_bytes_p, written, addr_family, 0, output); } wally_clear(buf, sizeof(buf)); return ret; } int wally_confidential_addr_segwit_to_ec_public_key( const char *address, const char *confidential_addr_family, unsigned char *bytes_out, size_t len) { unsigned char buf[WALLY_BLECH32_MAXLEN]; int witver = 0; size_t written = 0; int ret = WALLY_OK; if (!address || !bytes_out || !confidential_addr_family || len != EC_PUBLIC_KEY_LEN) return WALLY_EINVAL; /* Only v0 witness programs are currently allowed */ if (!blech32_addr_decode(&witver, buf, &written, confidential_addr_family, address)) ret = WALLY_EINVAL; else if (witver != 0 || (written != 53 && written != 65)) ret = WALLY_EINVAL; else memcpy(bytes_out, buf, EC_PUBLIC_KEY_LEN); wally_clear(buf, sizeof(buf)); return ret; } int wally_confidential_addr_from_addr_segwit( const char *address, const char *addr_family, const char *confidential_addr_family, const unsigned char *pub_key, size_t pub_key_len, char **output) { char result[WALLY_BLECH32_MAXLEN + 1]; unsigned char buf[EC_PUBLIC_KEY_LEN + SHA256_LEN]; unsigned char *hash_bytes_p = &buf[EC_PUBLIC_KEY_LEN - 2]; size_t written = SHA256_LEN + 2; int ret; if (output) *output = NULL; if (!address || !addr_family || !confidential_addr_family || !pub_key || pub_key_len != EC_PUBLIC_KEY_LEN || !output || strlen(confidential_addr_family) >= WALLY_BLECH32_MAXLEN) return WALLY_EINVAL; /* get v0 witness programs script */ ret = wally_addr_segwit_to_bytes(address, addr_family, 0, hash_bytes_p, written, &written); if (ret == WALLY_OK) { if ((written != (HASH160_LEN + 2)) && (written != (SHA256_LEN + 2))) ret = WALLY_EINVAL; else { /* Copy the confidentialKey / v0 witness programs */ memcpy(buf, pub_key, pub_key_len); written -= 2; /* ignore witnessVersion & hashSize */ written += EC_PUBLIC_KEY_LEN; if (!blech32_addr_encode(result, confidential_addr_family, 0, buf, written)) return WALLY_ERROR; *output = wally_strdup(result); ret = (*output) ? WALLY_OK : WALLY_ENOMEM; } } wally_clear(buf, sizeof(buf)); wally_clear(result, sizeof(result)); return ret; } #endif /* BUILD_ELEMENTS */
538007.c
/* * Copyright 2005-2019 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. */ /************************************* * Enrico Fucile **************************************/ #include "grib_api_internal.h" /* This is used by make_class.pl START_CLASS_DEF CLASS = accessor SUPER = grib_accessor_class_variable IMPLEMENTS = init;pack_double;pack_long;pack_string;pack_bytes END_CLASS_DEF */ /* START_CLASS_IMP */ /* Don't edit anything between START_CLASS_IMP and END_CLASS_IMP Instead edit values between START_CLASS_DEF and END_CLASS_DEF or edit "accessor.class" and rerun ./make_class.pl */ static int pack_bytes(grib_accessor*,const unsigned char*, size_t *len); static int pack_double(grib_accessor*, const double* val,size_t *len); static int pack_long(grib_accessor*, const long* val,size_t *len); static int pack_string(grib_accessor*, const char*, size_t *len); static void init(grib_accessor*,const long, grib_arguments* ); static void init_class(grib_accessor_class*); typedef struct grib_accessor_constant { grib_accessor att; /* Members defined in gen */ /* Members defined in variable */ double dval; char* cval; int type; /* Members defined in constant */ } grib_accessor_constant; extern grib_accessor_class* grib_accessor_class_variable; static grib_accessor_class _grib_accessor_class_constant = { &grib_accessor_class_variable, /* super */ "constant", /* name */ sizeof(grib_accessor_constant), /* size */ 0, /* inited */ &init_class, /* init_class */ &init, /* init */ 0, /* post_init */ 0, /* free mem */ 0, /* describes himself */ 0, /* get length of section */ 0, /* get length of string */ 0, /* get number of values */ 0, /* get number of bytes */ 0, /* get offset to bytes */ 0, /* get native type */ 0, /* get sub_section */ 0, /* grib_pack procedures long */ 0, /* grib_pack procedures long */ &pack_long, /* grib_pack procedures long */ 0, /* grib_unpack procedures long */ &pack_double, /* grib_pack procedures double */ 0, /* grib_unpack procedures double */ &pack_string, /* grib_pack procedures string */ 0, /* grib_unpack procedures string */ 0, /* grib_pack array procedures string */ 0, /* grib_unpack array procedures string */ &pack_bytes, /* grib_pack procedures bytes */ 0, /* grib_unpack procedures bytes */ 0, /* pack_expression */ 0, /* notify_change */ 0, /* update_size */ 0, /* preferred_size */ 0, /* resize */ 0, /* nearest_smaller_value */ 0, /* next accessor */ 0, /* compare vs. another accessor */ 0, /* unpack only ith value */ 0, /* unpack a subarray */ 0, /* clear */ 0, /* clone accessor */ }; grib_accessor_class* grib_accessor_class_constant = &_grib_accessor_class_constant; static void init_class(grib_accessor_class* c) { c->dump = (*(c->super))->dump; c->next_offset = (*(c->super))->next_offset; c->string_length = (*(c->super))->string_length; c->value_count = (*(c->super))->value_count; c->byte_count = (*(c->super))->byte_count; c->byte_offset = (*(c->super))->byte_offset; c->get_native_type = (*(c->super))->get_native_type; c->sub_section = (*(c->super))->sub_section; c->pack_missing = (*(c->super))->pack_missing; c->is_missing = (*(c->super))->is_missing; c->unpack_long = (*(c->super))->unpack_long; c->unpack_double = (*(c->super))->unpack_double; c->unpack_string = (*(c->super))->unpack_string; c->pack_string_array = (*(c->super))->pack_string_array; c->unpack_string_array = (*(c->super))->unpack_string_array; c->unpack_bytes = (*(c->super))->unpack_bytes; c->pack_expression = (*(c->super))->pack_expression; c->notify_change = (*(c->super))->notify_change; c->update_size = (*(c->super))->update_size; c->preferred_size = (*(c->super))->preferred_size; c->resize = (*(c->super))->resize; c->nearest_smaller_value = (*(c->super))->nearest_smaller_value; c->next = (*(c->super))->next; c->compare = (*(c->super))->compare; c->unpack_double_element = (*(c->super))->unpack_double_element; c->unpack_double_subarray = (*(c->super))->unpack_double_subarray; c->clear = (*(c->super))->clear; c->make_clone = (*(c->super))->make_clone; } /* END_CLASS_IMP */ void accessor_constant_set_type(grib_accessor* a,int type) { grib_accessor_constant* self = (grib_accessor_constant*)a; self->type=type; } void accessor_constant_set_dval(grib_accessor* a,double dval) { grib_accessor_constant* self = (grib_accessor_constant*)a; self->dval=dval; } static void init(grib_accessor* a, const long len , grib_arguments* arg ) { a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY; } static int pack_bytes(grib_accessor* a,const unsigned char* val, size_t *len) { return GRIB_READ_ONLY; } static int pack_double(grib_accessor* a, const double* val,size_t *len) { return GRIB_READ_ONLY; } static int pack_long(grib_accessor* a, const long* val,size_t *len) { return GRIB_READ_ONLY; } static int pack_string(grib_accessor* a, const char* val, size_t *len) { return GRIB_READ_ONLY; }
778255.c
/************************************************************************/ /* ed.c */ /* */ /* This module is the front end to the Turing environment for Windows. */ /************************************************************************/ /*******************/ /* System includes */ /*******************/ #include <windows.h> #include <commctrl.h> #include <crtdbg.h> #include <stdio.h> //#include <signal.h> /****************/ /* Self include */ /****************/ #include "ed.h" /******************/ /* Other includes */ /******************/ #include "eddde.h" #include "edfail.h" #include "edfalse.h" #include "edprog.h" #include "edprop.h" #include "edrun.h" #include "edsplash.h" #include "edwin.h" #include "dbgalloc.h" #include "eddialogs.h" /**********/ /* Macros */ /**********/ /*************/ /* Constants */ /*************/ // This should be set to the number of different window types + 1 #define NUM_ACCELERATORS (LAST_WINDOW_TYPE + 1) // Command line options #define OPTION_ADMIN "-admin" #define OPTION_LOG_STR "-log" #define OPTION_WRITE_ALL_PREFS_STR "-writepref" #define OPTION_NO_INITIAL_WINDOW "-nowindow" #define OPTION_DISPLAY_HELP_STR "-?" #define OPTION_TESTSUITE "-testsuite" #define OPTION_AUTORUN "-run" #define OPTION_COMPILEFILE "-compile" // Argumens for MyProcessCommandLineArguments #define PROCESS_OPTIONS TRUE #define IGNORE_OPTIONS FALSE /*********/ /* Types */ /*********/ typedef struct WindowList { HWND window; int windowKind; // activeIndex is a counter that is set to the current index whenever a // window is activated. The WINDOW_TYPE_EDIT with the highest value // is the last WINDOW_TYPE_EDIT to have been active. int activeIndex; struct WindowList *next; } WindowList, *WindowListPtr; typedef struct WindowMessage { BOOL useNotify; int message; WPARAM wParam; LPARAM lParam; } WindowMessage; /********************/ /* Static constants */ /********************/ /********************/ /* Static variables */ /********************/ // Properties of the status window static BOOL stPropertiesChanged; // The accelerators static HACCEL stAccelerator [NUM_ACCELERATORS]; // The active window. Send accelerator events to this window. static HWND stActiveWindow = NULL; static HWND stActiveModelessDialog = NULL; static int stLastActiveCounter = 1; static int stActiveWindowKind; // There are times when only a specific window is allowed to be active. // (Such as when a window has a dialog in front of it.) This is all // needed because Windows doesn't implement task modal dialogs correctly // and messes up short cuts when there's a window modal dialog around. static HWND stModalDialog = NULL; // static WindowListPtr stWindowListHeader = NULL; static BOOL stAlreadyExiting = FALSE; // Logging command line option set static BOOL stLogging = FALSE; // Don't open an initial window (used when DDE commands coming) static BOOL stNoWindow = FALSE; // Admin command line option set static BOOL stWantToBecomeAdmin = FALSE; // Run file on startup static BOOL stAutoRunPrograms = FALSE; static FilePath stAutoRunFile; // Compile file on startup static BOOL stCompilePrograms = FALSE; static FilePath stCompileFile; // Test suite command line option set static BOOL stRunningTestSuite = FALSE; static FilePath stTestSuiteFile; // Mutex indicating Ready is running static HANDLE stReadyRunningMutex; static HANDLE stMemoryLogHandle = NULL; #ifdef _MEMORY_CHECK // Memory state holder static _CrtMemState stCRTMemState; #endif // #ifdef _MEMORY_CHECK /******************************/ /* Static callback procedures */ /******************************/ static BOOL CALLBACK MyCheckControlProcedure (HWND pmDialog, UINT pmMessage, WPARAM pmWParam, LPARAM pmLParam); /*********************/ /* Static procedures */ /*********************/ static BOOL MyInitModules (void); static BOOL MyInit (void); static BOOL MyCheckCommonControlVersion (void); static BOOL MyConfirmExit (HWND pmWindow); static void MyFreeCommandLineArguments (int pmNumArgs, char *pmArgs[]); static void MyGetCommandLineArguments (char *pmCmdLine, int *pmNumArgs, int *pmNumOptionArgs, char ***pmArgs); static BOOL MyProcessCommandLineArguments (int pmNumArgs, char *pmArgs[], BOOL pmProcessOptions); static DWORD MyProcessEvents (void); static void MyProcessMessage (MSG *pmMessagePtr); static BOOL MySetForegroundWindow (HWND pmWindow); static void MySignalHandler (int pmSignalNo); /***********************/ /* External procedures */ /***********************/ extern char *tmpnam (char *string); /********************************************************/ /* WinMain */ /* */ /* Called by the system when the program is first run. */ /*********************************** *********************/ int WINAPI WinMain (HINSTANCE pmApplicationInstance, HINSTANCE pmPrevInstance, PSTR pmCmdLine, int pmCmdShow) { BOOL myAllowMoreThanOneRun = FALSE; int myNumArgs, myNumOptionArgs; char **myArgs; DWORD myReturnValue; HWND myWindow; int cnt; // If the program is started up with the Shift and Ctrl keys both pressed, // then start the logging. if (((GetKeyState (VK_SHIFT) & 0x8000) != 0) && ((GetKeyState (VK_CONTROL) & 0x8000) != 0)) { stLogging = TRUE; debugModeEnabled = TRUE; } else { stLogging = FALSE; debugModeEnabled = FALSE; } // If the program is started up with the Alt and Ctrl keys both pressed, // then start the allow more than one copy of Turing. Mostly used to // debug network applications if (((GetKeyState (VK_MENU) & 0x8000) != 0) && ((GetKeyState (VK_CONTROL) & 0x8000) != 0)) { myAllowMoreThanOneRun = TRUE; } // Many routines use these, so we initialize it immediately. gProgram.applicationInstance = pmApplicationInstance; strcpy (gProgram.environmentName, "Environment"); InitCommonControls (); // Initialize the installation dependent stuff. EdProg_Init should be // called before just about anything else. if (!EdProg_Init ()) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } // Split the command line arguments into an array MyGetCommandLineArguments (pmCmdLine, &myNumArgs, &myNumOptionArgs, &myArgs); // // Code to prevent more than one instance of Ready running at a time // if (myAllowMoreThanOneRun) { char *myTempName; if ((myTempName = tmpnam (NULL)) != NULL) { stReadyRunningMutex = CreateMutex (NULL, TRUE, myTempName); } else { stReadyRunningMutex = CreateMutex (NULL, TRUE, "TuringTemp"); } } else if (gProgram.isTuring) { stReadyRunningMutex = CreateMutex (NULL, TRUE, "TuringRunningMutex"); } else if (gProgram.isJava) { stReadyRunningMutex = CreateMutex (NULL, TRUE, "ReadyRunningMutex"); } if ((stReadyRunningMutex != NULL) && (GetLastError () == ERROR_ALREADY_EXISTS)) { char myEditWindowClassName [1024]; HWND myForegroundWindow, myChildWindow; BOOL myWindowDisplayed = FALSE; // Check to see if there are any files being opened by the commands // line call. If there are, pass them via DDE to the currently // open Ready // Process the command line arguments (most imporantly, turn on logging) if (MyProcessCommandLineArguments (myNumArgs, myArgs, IGNORE_OPTIONS)) { EdDDE_TellReadyOpen (myNumArgs, myArgs); } EdGUI_LoadString (IDS_EDIT_MDI_FRAME_WINDOW_NAME, myEditWindowClassName, sizeof (myEditWindowClassName)); myWindow = FindWindow (myEditWindowClassName, NULL); if (myWindow == NULL) { EdGUI_LoadString (IDS_EDIT_WINDOW_NAME, myEditWindowClassName, sizeof (myEditWindowClassName)); myWindow = FindWindow (myEditWindowClassName, NULL); } if (myWindow != NULL) { myChildWindow = GetLastActivePopup (myWindow); myWindowDisplayed = MySetForegroundWindow (myWindow); if (myWindow != myChildWindow) { myWindowDisplayed = MySetForegroundWindow (myChildWindow); } } myForegroundWindow = GetForegroundWindow (); if ((myForegroundWindow != myWindow) && (myForegroundWindow != myChildWindow)) { if (gProgram.isTuring) { EdGUI_Message1 (NULL, MB_OK, IDS_TURING_ALREADY_OPEN_TITLE, IDS_TURING_ALREADY_OPEN_MESSAGE); } else if (gProgram.isJava) { EdGUI_Message1 (NULL, MB_OK, IDS_READY_ALREADY_OPEN_TITLE, IDS_READY_ALREADY_OPEN_MESSAGE); } } return 0; } // // Check Common Control Version Number // if (!MyCheckCommonControlVersion ()) { return 0; } // Process the command line arguments (most imporantly, turn on logging) if (!MyProcessCommandLineArguments (myNumArgs, myArgs, PROCESS_OPTIONS)) { return 0; } if (!MyInitModules ()) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_INIT_FAILURE_MESSAGE); return 0; } if (stRunningTestSuite) { FilePath myCurrentDirectory, myTestSuiteFile; EdFile_GetCurrentDirectory (myCurrentDirectory); EdFile_CombinePath (myCurrentDirectory, stTestSuiteFile, myTestSuiteFile); EdRun_TestSuite (myTestSuiteFile, NULL); return 0; } if (stAutoRunPrograms) { FilePath myCurrentDirectory; EdFile_GetCurrentDirectory (myCurrentDirectory); EdRun_RunProgramNoEditor (myCurrentDirectory,stAutoRunFile); return 0; } if (stCompilePrograms) { int myStatus; FilePath myBytecodeFile; const char *myPtr; strcpy (myBytecodeFile, stCompileFile); myPtr = EdFile_GetFileSuffix (myBytecodeFile); strcpy (&myBytecodeFile [myPtr - myBytecodeFile], ".tbc"); myStatus = EdRun_CreateByteCodeFile (stCompileFile,myBytecodeFile); return 0; } if (myNumArgs == myNumOptionArgs) { // If we're opening up a window via DDE and we're in beginner mode, // the system expects to see the initial window already created. // Otherwise we don't need to create the initial window. if (!stNoWindow || gProperties.beginnerMode) { myWindow = EdWin_Create (NULL, NULL, 0, gProperties.beginnerMode, gProperties.oneWindowMode); } } else { if (gProperties.beginnerMode) { // Attempting to open more than one file is not allowed // in beginner mode if (myNumArgs - myNumOptionArgs > 1) { EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_FAILURE_TITLE, IDS_CMD_LINE_FAILURE_MESSAGE); } // Open the first file. for (cnt = 0 ; cnt < myNumArgs ; cnt++) { if (myArgs [cnt] [0] != 0) { FilePath myPathName; char *myDummy; GetFullPathName (myArgs [cnt], PATHNAME_LENGTH, myPathName, &myDummy); myWindow = EdWin_Create (myPathName, NULL, 0, gProperties.beginnerMode, gProperties.oneWindowMode); if (myWindow == NULL) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } break; } } } // if (gProperties.beginnerMode) else { if (gProperties.oneWindowMode) { // In one window mode, we create only one window for the first // file and then call EdWin_AddFile for the rest int myCounter = 0; while (myCounter < myNumArgs) { if (myArgs [myCounter] [0] != 0) { FilePath myPathName; char *myDummy; GetFullPathName (myArgs [myCounter], PATHNAME_LENGTH, myPathName, &myDummy); myWindow = EdWin_Create (myPathName, NULL, 0, gProperties.beginnerMode, gProperties.oneWindowMode); if (myWindow == NULL) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } myCounter++; break; } } // while // Now open the rest of the files into the same window for (cnt = myCounter ; cnt < myNumArgs ; cnt++) { if (myArgs [cnt] [0] != 0) { EdWin_AddFile (myWindow, myArgs [cnt], NULL, 0); if (myWindow == NULL) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } } } // for } // if (gProperties.oneWindowMode) else { // Open each file into a new window for (cnt = 0 ; cnt < myNumArgs ; cnt++) { if (myArgs [cnt] [0] != 0) { FilePath myPathName; char *myDummy; GetFullPathName (myArgs [cnt], PATHNAME_LENGTH, myPathName, &myDummy); myWindow = EdWin_Create (myPathName, NULL, 0, gProperties.beginnerMode, gProperties.oneWindowMode); if (myWindow == NULL) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } } // if } // for } // if (!gProperties.oneWindowMode) } // if (!gProperties.beginnerMode) } // if (myNumArgs != myNumOptionArgs) if (myWindow == NULL) { EdGUI_Message1 (NULL, 0, IDS_INIT_FAILURE_TITLE, IDS_UNABLE_TO_OPEN_WINDOW); return 0; } if (!gProperties.skipSplashScreen) { // Start the splash screen EdSplash_Create (FALSE); } MyFreeCommandLineArguments (myNumArgs, myArgs); #ifdef _MEMORY_CHECK // Set the memory state after everything is (presumably initialized) if (gProperties.debug) { _CrtMemCheckpoint (&stCRTMemState); } #endif // #ifdef _MEMORY_CHECK /* __try { */ // Main body of the program. Process all events here. myReturnValue = MyProcessEvents (); /* } __except (EdFail_CrashHandler (GetExceptionInformation())) { } */ // Release mutex to allow another copy of Ready to exist ReleaseMutex (stReadyRunningMutex); // Quitting procedures here EdRec_WriteRecentFiles (); EdDDE_Finalize (); EdWin_Finalize (); EdFile_Finalize (); EdFail_Finalize (); // This returns the exception filter to the default handler if (gProperties.catchExceptions) { SetUnhandledExceptionFilter ((LPTOP_LEVEL_EXCEPTION_FILTER) NULL); } #ifdef _MEMORY_CHECK if (gProperties.debug) { Ed_CreateMemoryLogFile (); // Debugging information about memory leaks _CrtDumpMemoryLeaks (); } #endif // #ifdef _MEMORY_CHECK if (stMemoryLogHandle != NULL) { BOOL myDebugEmpty; myDebugEmpty = (GetFileSize (stMemoryLogHandle, NULL) == 0); CloseHandle (stMemoryLogHandle); // Delete the file if it's empty. if (myDebugEmpty) { FilePath myPathName; EdFile_ConstructPath (myPathName, FROM_STARTUP, IDS_MEMORY_LEAK_FILE); if (!DeleteFile (myPathName)) { // Write to log EdLog_Log ("Unable to delete empty debug file. Error = %d", GetLastError ()); } } } return myReturnValue; } // WinMain /************************************************************************/ /* Ed_PropertiesSet */ /************************************************************************/ void Ed_PropertiesSet (Ed_Properties pmProperties) { // EdGlob has no initialization sequence EdDDE_PropertiesSet (); EdFile_PropertiesSet (); EdGUI_PropertiesSet (); EdLog_PropertiesSet (pmProperties.logProperties); EdRun_PropertiesSet (); EdSplash_PropertiesSet (); EdWin_PropertiesSet (pmProperties.winProperties); stPropertiesChanged = TRUE; } // Ed_PropertiesSet /************************************************************************/ /* Ed_PropertiesImplementChanges */ /************************************************************************/ void Ed_PropertiesImplementChanges () { WindowListPtr myWindowListEntry; if (stPropertiesChanged) { // EdGlob has no initialization sequence EdDDE_PropertiesImplementChanges (); EdFile_PropertiesImplementChanges (); EdGUI_PropertiesImplementChanges (); EdLog_PropertiesImplementChanges (); EdRun_PropertiesImplementChanges (); EdSplash_PropertiesImplementChanges (); myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { switch (myWindowListEntry -> windowKind) { case WINDOW_TYPE_EDIT: EdWin_PropertiesImplementChanges ( myWindowListEntry -> window); EdWin_SetWindowTitle (myWindowListEntry -> window); break; // case WINDOW_TYPE_CONSOLE: // EdCon_PropertiesImplementChanges ( // myWindowListEntry -> window); // break; default: EdFail_Fatal (IDS_UNEXPECTED_WINDOW_KIND, __FILE__, __LINE__, 0, myWindowListEntry -> windowKind); } myWindowListEntry = myWindowListEntry -> next; } stPropertiesChanged = FALSE; } } // Ed_PropertiesImplementChanges /************************************************************************/ /* Ed_AddToWindowList */ /************************************************************************/ void Ed_AddToWindowList (HWND pmWindow, int pmWindowKind) { WindowListPtr myWindowListEntry; myWindowListEntry = (WindowListPtr) malloc (sizeof (WindowList)); myWindowListEntry -> window = pmWindow; myWindowListEntry -> windowKind = pmWindowKind; myWindowListEntry -> next = stWindowListHeader; stWindowListHeader = myWindowListEntry; } // Ed_AddToWindowList /************************************************************************/ /* Ed_CatchExceptions */ /************************************************************************/ BOOL Ed_CatchExceptions (void) { return gProperties.catchExceptions; } // Ed_CatchExceptions /************************************************************************/ /* Ed_CheckWindowPreemption */ /************************************************************************/ BOOL Ed_CheckWindowPreemption (void) { if ((stModalDialog != NULL) && IsWindow (stModalDialog)) { SetForegroundWindow (stModalDialog); return TRUE; } return FALSE; } // Ed_CheckWindowPreemption /************************************************************************/ /* Ed_ClearBreakpoints */ /************************************************************************/ void Ed_ClearBreakpoints (void) { Ed_EnumerateFiles (EdDisp_ClearBreakpoints, NULL); } // Ed_ClearBreakpoints /************************************************************************/ /* Ed_CreateMemoryLogFile */ /************************************************************************/ void Ed_CreateMemoryLogFile (void) { // Has memory log file been created static BOOL myStMemoryLogFileCreated = FALSE; if (!myStMemoryLogFileCreated) { FilePath myPathName; EdFile_ConstructPath (myPathName, FROM_STARTUP, IDS_MEMORY_LEAK_FILE); stMemoryLogHandle = CreateFile (myPathName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); _CrtSetReportMode (_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile (_CRT_WARN, stMemoryLogHandle); _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile (_CRT_ERROR, stMemoryLogHandle); _CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile (_CRT_ASSERT, stMemoryLogHandle); myStMemoryLogFileCreated = TRUE; } } // Ed_CreateMemoryLogFile /************************************************************************/ /* Ed_CreateRecentMenu */ /************************************************************************/ void Ed_CreateRecentMenu (void) { WindowListPtr myWindowListEntry; myWindowListEntry = stWindowListHeader; // For each window, create the menu. while (myWindowListEntry != NULL) { if (myWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) { EdWin_CreateRecentMenu (myWindowListEntry -> window); } myWindowListEntry = myWindowListEntry -> next; } // while (for each window) } // Ed_CreateRecentMenu /************************************************************************/ /* Ed_DumpMemory */ /************************************************************************/ void Ed_DumpMemory (void) { #ifdef _MEMORY_CHECK Ed_CreateMemoryLogFile (); _CrtMemDumpAllObjectsSince (&stCRTMemState); #endif // #ifdef _MEMORY_CHECK } // Ed_DumpMemory /************************************************************************/ /* Ed_EnableAllWindows */ /************************************************************************/ void Ed_EnableAllWindows (BOOL pmEnable, HWND pmWindow) { HWND myWindow; WindowListPtr myWindowListEntry; // Get the top-level window from the pmWindow parameter myWindow = pmWindow; while (GetParent (myWindow) != NULL) { myWindow = GetParent (myWindow); } stModalDialog = NULL; myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { if (myWindowListEntry -> window != myWindow) { EnableWindow (myWindowListEntry -> window, pmEnable); } myWindowListEntry = myWindowListEntry -> next; } } // Ed_EnableAllWindows /************************************************************************/ /* Ed_EnumerateFiles */ /************************************************************************/ void Ed_EnumerateFiles (void (*enumProc) (char *, HWND, HWND, void *, void *), void *pmUserParam) { // Note this must be reworked to handle one window mode WindowListPtr myWindowListEntry; myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { if (myWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) { EdWin_EnumerateFiles (myWindowListEntry -> window, enumProc, pmUserParam); } myWindowListEntry = myWindowListEntry -> next; } } // Ed_EnumerateFiles /************************************************************************/ /* Ed_EnumerateWindows */ /************************************************************************/ void Ed_EnumerateWindows (void (*enumProc) (HWND, void *), void *pmUserParam) { // Note this must be reworked to handle one window mode WindowListPtr myWindowListEntry; myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { if (myWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) { (*enumProc) (myWindowListEntry -> window, pmUserParam); } myWindowListEntry = myWindowListEntry -> next; } } // Ed_EnumerateWindows /************************************************************************/ /* Ed_ExitApplication */ /************************************************************************/ void Ed_ExitApplication (HWND pmWindow, BOOL pmImmediate) { WindowListPtr myWindowListEntry, myNextWindowListEntry; EdWin_ShowStatus (pmWindow, "Exiting %s", gProgram.environmentName); // Confirm Exit if (!pmImmediate && (!MyConfirmExit (pmWindow))) { EdWin_ShowStatus (pmWindow, "Exit Cancelled"); return; } stAlreadyExiting = TRUE; // Kill any running program EdRun_KillRunningProgramAndQuit (pmWindow); Sleep (40); // Give enough time for the system to kill the process // Close all open windows. If any are left open, then we don't quit myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { myNextWindowListEntry = myWindowListEntry -> next; SendMessage (myWindowListEntry -> window, WM_CLOSE, 0, 0); myWindowListEntry = myNextWindowListEntry; } stAlreadyExiting = FALSE; // The window may already be gone by this point. Make certain it's // still a legit window before displaying the status message if (IsWindow (pmWindow)) { EdWin_ShowStatus (pmWindow, "Exit Cancelled"); } } // Ed_ExitApplication /************************************************************************/ /* Ed_GetExampleDirectories */ /* */ /* This function reads the "examples.txt" file located in the */ /* <Ready Dir>\"Examples" folder and returns the list of labels along */ /* with the directory to copy. Note it caches the list, so multiple */ /* calls result in the file being read once. */ /************************************************************************/ Examples *Ed_GetExampleDirectories (HWND pmWindow) { FilePath myExamplesPathName; char *myLine, *myPtr; char *myBuffer; int myLineNumber = 0; DWORD myFileSize; Example *myExample, *myLastExample = NULL; static Examples *stExamples = NULL; static BOOL stExamplesInitialized = FALSE; if (stExamplesInitialized) { return stExamples; } stExamplesInitialized = TRUE; EdFile_ConstructPath (myExamplesPathName, IDS_EXAMPLES_DIR, IDS_EXAMPLES_FILE); // Read file into buffer myBuffer = EdFile_ReadFileIntoBuffer (NULL, myExamplesPathName, &myFileSize, OK_IF_NOT_FOUND); if (myBuffer == NULL) { stExamples = EXAMPLES_NOT_FOUND; return stExamples; } EdFile_ReadLineFromBuffer (myBuffer, myFileSize, READ_FIRST); while (TRUE) { // Read a line from the file myLine = EdFile_ReadLineFromBuffer (myBuffer, 0, READ_NEXT); if (myLine == NULL) { break; } myLineNumber++; // Trim whitespace EdGlob_Trim (myLine); myPtr = myLine; // Check for comment or blank line if ((*myPtr == '#') || (*myPtr == ';') || (*myPtr == 0)) { continue; } myPtr = strchr (myLine, '\t'); if (myPtr == NULL) { // Error - Missing tab EdGUI_Message1 (pmWindow, 0, IDS_BAD_EXAMPLES_TITLE, IDS_MISSING_TAB, myLineNumber, myExamplesPathName); stExamples = EXAMPLES_BAD_FORMAT; break; } *myPtr++ = 0; EdGlob_Trim (myLine); EdGlob_Trim (myPtr); if (strchr (myPtr, '\t') != NULL) { // Error - Too many tabs EdGUI_Message1 (pmWindow, 0, IDS_BAD_EXAMPLES_TITLE, IDS_MISSING_TAB, myLineNumber, myExamplesPathName); stExamples = EXAMPLES_BAD_FORMAT; break; } // Initialize stExamples, if necessary if (stExamples == NULL) { stExamples = (Examples *) malloc (sizeof (Examples)); if (stExamples == NULL) { EdGUI_Message1 (pmWindow, 0, IDS_BAD_EXAMPLES_TITLE, IDS_OUTOFMEMORY); stExamples = EXAMPLES_OUT_OF_MEMORY; break; } stExamples -> numExamples = 0; stExamples -> head = NULL; } // Create and fill the Example buffer myExample = (Example *) malloc (sizeof (Example)); if (myExample == NULL) { EdGUI_Message1 (pmWindow, 0, IDS_BAD_EXAMPLES_TITLE, IDS_OUTOFMEMORY); stExamples = EXAMPLES_OUT_OF_MEMORY; break; } myExample -> label = (char *) malloc (strlen (myLine) + 1); strcpy (myExample -> label, myLine); myExample -> directoryName = (char *) malloc (strlen (myPtr) + 1); strcpy (myExample -> directoryName, myPtr); myExample -> next = NULL; // Add to the end of the list if (myLastExample == NULL) { stExamples -> head = myExample; } else { myLastExample -> next = myExample; } myLastExample = myExample; // Increment the number of examples stExamples -> numExamples++; } // while free (myBuffer); return stExamples; } // Ed_GetExampleDirectories /************************************************************************/ /* Ed_GetLastActiveEditWindow */ /************************************************************************/ HWND Ed_GetLastActiveEditWindow (void) { WindowListPtr myWindowListEntry; HWND myWindow = NULL; int myHighestValue = -1; // Find the file in the list myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { if ((myWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) && (myWindowListEntry -> activeIndex > myHighestValue)) { myWindow = myWindowListEntry -> window; myHighestValue = myWindowListEntry -> activeIndex; } myWindowListEntry = myWindowListEntry -> next; } return myWindow; } // Ed_GetActiveWindow extern void TL_TLI_TLISS ();extern void TL_TLI_TLIPS (); extern MDIOTime_GetTicks (); /************************************************************************/ /* Ed_ProcessWaitingEvents */ /************************************************************************/ void Ed_ProcessWaitingEvents (BOOL pmWaitForEvent) { MSG myMessage; int myResult; static BOOL myStProcessingMessages = FALSE; //static int c = 0; //char myMsg [256]; if (!myStProcessingMessages) { myStProcessingMessages = TRUE; //TL_TLI_TLISS (0, (short) 2); //wsprintf (myMsg, "%d-%d\n", MDIOTime_GetTicks (), c++); //TL_TLI_TLIPS (0, myMsg, (short) 0); if (pmWaitForEvent) { // Process at least one event, even if you have to wait for it myResult = GetMessage (&myMessage, NULL, 0, 0); if (myResult) { MyProcessMessage (&myMessage); } //TL_TLI_TLISS (0, (short) 2); //wsprintf (myMsg, "*%d-%d\n", MDIOTime_GetTicks (), c++); //TL_TLI_TLIPS (0, myMsg, (short) 0); } // Process any waiting messages and return while (PeekMessage (&myMessage, NULL, 0, 0, PM_REMOVE)) { //char myMsg [256]; //wsprintf (myMsg, "%d H:%x M:%d", c, (int) myMessage.hwnd, myMessage.message); //c++; //TL_TLI_TLISS (0, (short) 2); //TL_TLI_TLIPS (0, myMsg, (short) 0); MyProcessMessage (&myMessage); //TL_TLI_TLISS (0, (short) 2); //TL_TLI_TLIPS (0, ".\n", (short) 0); } myStProcessingMessages = FALSE; } else { DebugBreak (); } } // Ed_ProcessWaitingEvents /************************************************************************/ /* Ed_PutWindowAboveAllOtherEdWindows */ /* */ /* This goes through the window list and places all the MIO windows on */ /* the top, preserving the Z order relative to themselves. */ /************************************************************************/ void Ed_PutWindowAboveAllOtherEdWindows (HWND pmWindow) { // Go through the list of windows, putting all the MIO windows // on the top. HWND myLastWindow = NULL; HWND myWindow = GetTopWindow (GetDesktopWindow ()); while (myWindow != NULL) { int myWindowType = GetWindowLong (myWindow, WINDOW_MEM_WINDOW_TYPE); if (myWindowType == WINDOW_TYPE_EDIT) { if (myLastWindow == NULL) { SetForegroundWindow (pmWindow); } else { SetWindowPos (pmWindow, myLastWindow, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); } return; } myLastWindow = myWindow; myWindow = GetNextWindow (myWindow, GW_HWNDNEXT); } // while } // Ed_PutWindowAboveAllOtherEdWindows /************************************************************************/ /* Ed_RedrawWindows */ /************************************************************************/ void Ed_RedrawWindows (void) { WindowListPtr myWindowListEntry; myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { RedrawWindow (myWindowListEntry -> window, NULL, NULL, RDW_FRAME | RDW_INVALIDATE); myWindowListEntry = myWindowListEntry -> next; } } // Ed_RedrawWindows /************************************************************************/ /* Ed_RemoveFromWindowList */ /* */ /* If this is the last window to be closed, ask if the user wants to */ /* quit. If they don't, then return false, otherwise start quitting */ /* the program. */ /************************************************************************/ BOOL Ed_RemoveFromWindowList (HWND pmWindow) { WindowListPtr myWindowListEntry, myPrevWindowListEntry; // The files are stored in the linked list from most recent to least. // Check if the file is already on the list myWindowListEntry = stWindowListHeader; myPrevWindowListEntry = NULL; while (myWindowListEntry != NULL) { if (myWindowListEntry -> window == pmWindow) { break; } myPrevWindowListEntry = myWindowListEntry; myWindowListEntry = myWindowListEntry -> next; } if (myWindowListEntry == NULL) { EdFail_Fatal (IDS_WINDOW_NOT_FOUND, __FILE__, __LINE__, 0); } // The file is in the list. If it is the last editor // window, then ask the user if they want to quit. if (myWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) { WindowListPtr myTempWindowListEntry; int myNumEditWindows = 0; myTempWindowListEntry = stWindowListHeader; while (myTempWindowListEntry != NULL) { if (myTempWindowListEntry -> windowKind == WINDOW_TYPE_EDIT) { myNumEditWindows++; } myTempWindowListEntry = myTempWindowListEntry -> next; } if ((myNumEditWindows == 1) && !stRunningTestSuite && !stAutoRunPrograms) { if (!MyConfirmExit (pmWindow)) { return FALSE; } // Kill any running program if (!EdRun_KillRunningProgramAndQuit (pmWindow)) { // Quit the program PostQuitMessage (0); } } } if (myPrevWindowListEntry == NULL) { stWindowListHeader = myWindowListEntry -> next; } else { myPrevWindowListEntry -> next = myWindowListEntry -> next; } // If there are no non-editor windows to be opened, ask if user if they // want to quit // Free the entry free (myWindowListEntry); return TRUE; } // Ed_RemoveFromWindowList /************************************************************************/ /* Ed_SendMessageEnumerator */ /************************************************************************/ void Ed_SendMessageEnumerator (HWND pmWindow, void *pmMessage) { WindowMessage *myMessage = (WindowMessage *) pmMessage; if (myMessage -> useNotify) { SendNotifyMessage (pmWindow, myMessage -> message, (WPARAM) myMessage -> wParam, (LPARAM) myMessage -> lParam); } else { SendMessage (pmWindow, myMessage -> message, (WPARAM) myMessage -> wParam, (LPARAM) myMessage -> lParam); } } // Ed_SendMessageEnumerator /************************************************************************/ /* Ed_SendMessageToAllWindows */ /************************************************************************/ void Ed_SendMessageToAllWindows (BOOL pmUseNotify, int pmMessage, WPARAM pmWParam, LPARAM pmLParam) { WindowMessage myMessage; myMessage.useNotify = pmUseNotify; myMessage.message = pmMessage; myMessage.wParam = pmWParam; myMessage.lParam = pmLParam; Ed_EnumerateWindows (Ed_SendMessageEnumerator, &myMessage); } // Ed_SendMessageToAllWindows /************************************************************************/ /* Ed_SendStatusMessageEnumerator */ /************************************************************************/ void Ed_SendStatusMessageEnumerator (HWND pmWindow, void *pmMessage) { SendNotifyMessage (pmWindow, WM_SETSTATUSMESSAGE, (WPARAM) EdGlob_MallocString (pmMessage), 0); } // Ed_SendStatusMessageEnumerator /************************************************************************/ /* Ed_SendStatusMessageToAllWindows */ /************************************************************************/ void Ed_SendStatusMessageToAllWindows (char *pmMessage) { Ed_EnumerateWindows (Ed_SendStatusMessageEnumerator, pmMessage); } // Ed_SendStatusMessageToAllWindows /************************************************************************/ /* Ed_SetActiveWindow */ /************************************************************************/ void Ed_SetActiveWindow (HWND pmWindow, int pmWindowKind) { stActiveWindow = pmWindow; stActiveModelessDialog = NULL; if (pmWindow == NULL) { stActiveWindowKind = NO_WINDOW; return; } stActiveWindowKind = pmWindowKind; // If this is an edit window, go through the list and set the active // counter of the window to the current value if (stActiveWindowKind == EDIT_WINDOW) { WindowListPtr myWindowListEntry; // Find the file in the list myWindowListEntry = stWindowListHeader; while (myWindowListEntry != NULL) { if (myWindowListEntry -> window == pmWindow) { break; } myWindowListEntry = myWindowListEntry -> next; } if (myWindowListEntry == NULL) { EdFail_Fatal (IDS_WINDOW_NOT_FOUND, __FILE__, __LINE__, 0); } myWindowListEntry -> activeIndex = stLastActiveCounter; stLastActiveCounter++; } // if (stActiveWindowKind == EDIT_WINDOW) // If this is a modeless dialog, save the current dialog if (stActiveWindowKind == FIND_REPLACE_DIALOG) { stActiveModelessDialog = pmWindow; } } // Ed_SetActiveWindow /************************************************************************/ /* Ed_SetModalDialog */ /************************************************************************/ void Ed_SetModalDialog (HWND pmWindow) { if (pmWindow == NULL) { stModalDialog = NULL; } else if (stModalDialog == NULL) { stModalDialog = pmWindow; } } // Ed_SetModalDialog /************************************************************************/ /* Ed_ToggleBreakpointVisibility */ /************************************************************************/ void Ed_ToggleBreakpointVisibility (void) { EdRun_ToggleBreakpointVisibility (); EdDisp_SetBreakpointVisible (TOGGLE_BREAKPOINTS); Ed_EnumerateFiles (EdDisp_ResizeWindow, NULL); } // Ed_ToggleBreakpointVisibility /************************************************************************/ /* Ed_ToggleDebuggerControlsVisibility */ /************************************************************************/ void Ed_ToggleDebuggerControlsVisibility (void) { EdBBar_SetDebuggerVisible (TOGGLE_DEBUGGER_CONTROLS); Ed_SendMessageToAllWindows (FALSE, WM_CHANGEDEBUGGERCONTROL, 0, 0); } // Ed_ToggleDebuggerControlsVisibility /******************************/ /* Static callback procedures */ /******************************/ /***********************************************************************/ /* MyCheckControlProcedure */ /***********************************************************************/ static BOOL CALLBACK MyCheckControlProcedure (HWND pmDialog, UINT pmMessage, WPARAM pmWParam, LPARAM pmLParam) { switch (pmMessage) { case WM_INITDIALOG: EdGUI_CentreDialogBox (pmDialog); return TRUE; case WM_COMMAND: switch (LOWORD (pmWParam)) { case IDOK: EndDialog (pmDialog, TRUE); return TRUE; case IDCANCEL: EndDialog (pmDialog, FALSE); return TRUE; } // switch } // switch return FALSE; } // MyCheckControlProcedure /*********************/ /* Static procedures */ /*********************/ /************************************************************************/ /* MyInitModules */ /* */ /* Initialize all the modules used by this program. */ /************************************************************************/ static BOOL MyInitModules (void) { // This must be called first, because all other init methods may call // EdFail methods that depends on the initialization. if (!EdFail_Init ()) { return FALSE; } // EdProp_Init will call Ed_PropertiesSet that is needed for most other // modules to initialize properly if (!EdProp_Init (stWantToBecomeAdmin, stLogging)) { return FALSE; } // Logging may now be enabled if (gProperties.logging | gProperties.logWindowMessages) { EdLog_SetWriteToLog (); } // Now initialize this module if (!MyInit ()) { return FALSE; } // Initialize the DDE routines if (!EdDDE_Init ()) { return FALSE; } // Initialize the File routines gProgram.globalWindow = EdFalse_InitWindow (); if (gProgram.globalWindow == NULL) { return FALSE; } // Initialize the File routines if (!EdFile_Init ()) { return FALSE; } // Initialize the GUI routines if (!EdGUI_Init ()) { return FALSE; } // Initialize the logging routines if (!EdLog_Init ()) { return FALSE; } // Initialize the Splash screen routines if (!EdSplash_Init ()) { return FALSE; } // EdWin_Init must be called after EdGUI_Init if (!EdWin_Init ()) { return FALSE; } // EdGlob has no initialization sequence if (!DbgAlloc_Init ()) { return FALSE; } return TRUE; } // MyInitModules /************************************************************************/ /* MyInit */ /* */ /* Load the accelerators */ /************************************************************************/ static BOOL MyInit (void) { // Save the application instance stAccelerator [NO_WINDOW] = NULL; stAccelerator [EDIT_WINDOW] = LoadAccelerators ( gProgram.applicationInstance, MAKEINTRESOURCE (EDIT_WINDOW_ACCELERATOR)); stAccelerator [SPLASH_WINDOW] = NULL; stAccelerator [CONSOLE_WINDOW] = LoadAccelerators ( gProgram.applicationInstance, MAKEINTRESOURCE (CONSOLE_WINDOW_ACCELERATOR)); stAccelerator [TURING_RUN_WINDOW] = LoadAccelerators ( gProgram.applicationInstance, MAKEINTRESOURCE (TURING_RUN_WINDOW_ACCELERATOR)); stAccelerator [FIND_REPLACE_DIALOG] = LoadAccelerators ( gProgram.applicationInstance, MAKEINTRESOURCE (FIND_REPLACE_DIALOG_ACCELERATOR)); if (stAccelerator [EDIT_WINDOW] == NULL) { EdFail_Warn (IDS_LOADACCELERATORSFAIL, __FILE__, __LINE__, GetLastError (), EDIT_WINDOW); return FALSE; } if (stAccelerator [CONSOLE_WINDOW] == NULL) { EdFail_Warn (IDS_LOADACCELERATORSFAIL, __FILE__, __LINE__, GetLastError (), CONSOLE_WINDOW); return FALSE; } if (stAccelerator [TURING_RUN_WINDOW] == NULL) { EdFail_Warn (IDS_LOADACCELERATORSFAIL, __FILE__, __LINE__, GetLastError (), TURING_RUN_WINDOW); return FALSE; } if (stAccelerator [FIND_REPLACE_DIALOG] == NULL) { EdFail_Warn (IDS_LOADACCELERATORSFAIL, __FILE__, __LINE__, GetLastError (), FIND_REPLACE_DIALOG); return FALSE; } // This code handles things like GPFs and so on. if (gProperties.catchExceptions) { SetUnhandledExceptionFilter ( (LPTOP_LEVEL_EXCEPTION_FILTER) EdFail_CrashHandler); } return TRUE; } // MyInit /************************************************************************/ /* MyCheckCommonControlVersion */ /************************************************************************/ static BOOL MyCheckCommonControlVersion (void) { int myVersion; myVersion = EdGUI_GetCommonControlVersionNumber (); if (myVersion == 0) { return DialogBoxParam (gProgram.applicationInstance, MAKEINTRESOURCE (UNKNOWN_COMCTL_VERSION), NULL, MyCheckControlProcedure, 0); } else if (myVersion < 470) { return DialogBoxParam (gProgram.applicationInstance, MAKEINTRESOURCE (BAD_COMCTL_VERSION), NULL, MyCheckControlProcedure, 0); } return TRUE; } // MyCheckCommonControlVersion /************************************************************************/ /* MyConfirmExit */ /************************************************************************/ static BOOL MyConfirmExit (HWND pmWindow) { int myResult; if (stAlreadyExiting || !gProperties.confirmQuit) return TRUE; myResult = EdGUI_Message1 (pmWindow, MB_OKCANCEL | MB_ICONWARNING, IDS_APPLICATION_NAME, IDS_CONFIRM_QUIT_MESSAGE, gProgram.environmentName); if (myResult == IDCANCEL) { return FALSE; } return TRUE; } // MyConfirmExit /************************************************************************/ /* MyFreeCommandLineArguments */ /************************************************************************/ static void MyFreeCommandLineArguments (int pmNumArgs, char *pmArgs[]) { int cnt; for (cnt = 0 ; cnt < pmNumArgs ; cnt++) free (pmArgs [cnt]); if (pmArgs != NULL) free (pmArgs); } // MyFreeCommandLineArguments /************************************************************************/ /* MyGetCommandLineArguments */ /************************************************************************/ static void MyGetCommandLineArguments (char *pmCmdLine, int *pmNumArgs, int *pmNumOptionArgs, char **pmArgs[]) { char *myPtr = pmCmdLine, *myWordPtr; int myNumArgs = 0; int myNumOptionArgs = 0; while (*myPtr != 0) { // Skip whitespace while ((*myPtr == ' ') || (*myPtr == '\t')) myPtr++; if (*myPtr == 0) break; // Add one to the number of arguments myNumArgs++; if (*myPtr == '"') { myPtr++; // Skip non-whitespace if ((*myPtr == '-') || (*myPtr == '/')) myNumOptionArgs++; while ((*myPtr != '"') && (*myPtr != 0)) myPtr++; if (*myPtr == '"') { myPtr++; } } else { // Skip non-whitespace if ((*myPtr == '-') || (*myPtr == '/')) myNumOptionArgs++; while ((*myPtr != ' ') && (*myPtr != '\t') && (*myPtr != 0)) myPtr++; } } if (myNumArgs > 0) { *pmArgs = (char **) malloc (myNumArgs * sizeof (char *)); myPtr = pmCmdLine; myNumArgs = 0; while (*myPtr != 0) { // Skip whitespace while ((*myPtr == ' ') || (*myPtr == '\t')) myPtr++; if (*myPtr == 0) break; // Skip non-whitespace if (*myPtr == '"') { myPtr++; myWordPtr = myPtr; while ((*myWordPtr != '"') && (*myWordPtr != 0)) { myWordPtr++; } } else { myWordPtr = myPtr; while ((*myWordPtr != ' ') && (*myWordPtr != '\t') && (*myWordPtr != 0)) { myWordPtr++; } } // If this is a relative path, add the startup directory if ((*myPtr == '-') || (*myPtr == '/') || (*myPtr == '\\') || (*(myPtr + 1) == ':')) { (*pmArgs) [myNumArgs] = (char *) malloc (myWordPtr - myPtr + 1); // Copy argument and add trailing space strncpy ((*pmArgs) [myNumArgs], myPtr, myWordPtr - myPtr); ((*pmArgs) [myNumArgs]) [myWordPtr - myPtr] = 0; } else { FilePath myCurrentDir; EdFile_GetCurrentDirectory (myCurrentDir); if (myCurrentDir [strlen (myCurrentDir) - 1] != '\\') { strcat (myCurrentDir, "\\"); } (*pmArgs) [myNumArgs] = (char *) malloc (myWordPtr - myPtr + strlen (myCurrentDir) + 1); // Copy argument and add trailing space strcpy ((*pmArgs) [myNumArgs], myCurrentDir); strncat ((*pmArgs) [myNumArgs], myPtr, myWordPtr - myPtr); ((*pmArgs) [myNumArgs]) [strlen (myCurrentDir) + myWordPtr - myPtr] = 0; } // Add one to the number of arguments myNumArgs++; myPtr = myWordPtr; if (*myPtr == '"') { myPtr++; } } } else { *pmArgs = NULL; } *pmNumArgs = myNumArgs; *pmNumOptionArgs = myNumOptionArgs; } // MyGetCommandLineArguments /************************************************************************/ /* MyProcessCommandLineArguments */ /************************************************************************/ static BOOL MyProcessCommandLineArguments (int pmNumArgs, char *pmArgs[], BOOL pmProcessOptions) { char myArgument [1024]; int cnt; for (cnt = 0 ; cnt < pmNumArgs ; cnt++) { strcpy (myArgument, pmArgs [cnt]); // Convert to upper case and set '/' switch to '-' EdGlob_ConvertToLowerCase (myArgument); if (myArgument [0] == '/') { myArgument [0] = '-'; } if (myArgument [0] == '-') { if (strcmp (myArgument, OPTION_ADMIN) == 0) { if (pmProcessOptions) { stWantToBecomeAdmin = TRUE; } pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_COMPILEFILE) == 0) { if (pmProcessOptions) { stCompilePrograms = TRUE; } pmArgs [cnt] [0] = 0; cnt++; if (cnt == pmNumArgs) { EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_ERR_TITLE, IDS_NO_TESTSUITE_FILE); return FALSE; } strcpy (stCompileFile, pmArgs [cnt]); pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_AUTORUN) == 0) { if (pmProcessOptions) { stAutoRunPrograms = TRUE; } pmArgs [cnt] [0] = 0; cnt++; if (cnt == pmNumArgs) { EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_ERR_TITLE, IDS_NO_TESTSUITE_FILE); return FALSE; } strcpy (stAutoRunFile, pmArgs [cnt]); pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_LOG_STR) == 0) { if (pmProcessOptions) { stLogging = TRUE; } pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_WRITE_ALL_PREFS_STR) == 0) { if (pmProcessOptions) { EdProp_SetWriteAllPrefs (); } pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_NO_INITIAL_WINDOW) == 0) { if (pmProcessOptions) { stNoWindow = TRUE; } pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_TESTSUITE) == 0) { if (pmProcessOptions) { stRunningTestSuite = TRUE; } pmArgs [cnt] [0] = 0; cnt++; if (cnt == pmNumArgs) { EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_ERR_TITLE, IDS_NO_TESTSUITE_FILE); return FALSE; } strcpy (stTestSuiteFile, pmArgs [cnt]); pmArgs [cnt] [0] = 0; } else if (strcmp (myArgument, OPTION_DISPLAY_HELP_STR) == 0) { FilePath myApplicationPath; char *myApplicationName; char *myDot; // Get the name of the application. Remove the path and the // extension. GetModuleFileName (NULL, myApplicationPath, PATHNAME_LENGTH); myApplicationName = strrchr (myApplicationPath, '\\'); if (myApplicationName == NULL) { myApplicationName = myApplicationPath; } else { // Skip over the backslash myApplicationName++; } myDot = strrchr (myApplicationName, '.'); if (_stricmp (myDot, ".exe") == 0) { *myDot = 0; } // Display command line options EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_HELP_TITLE, IDS_CMD_LINE_HELP_MESSAGE, myApplicationName, OPTION_LOG_STR, OPTION_WRITE_ALL_PREFS_STR, OPTION_DISPLAY_HELP_STR,OPTION_AUTORUN,OPTION_COMPILEFILE); pmArgs [cnt] [0] = 0; return FALSE; } else { // Unrecognized option EdGUI_Message1 (NULL, 0, IDS_CMD_LINE_ERR_TITLE, IDS_UNKNOWN_CMD_LINE_OPTION, pmArgs [cnt], OPTION_LOG_STR, OPTION_WRITE_ALL_PREFS_STR, OPTION_DISPLAY_HELP_STR, OPTION_AUTORUN,OPTION_COMPILEFILE); pmArgs [cnt] [0] = 0; return FALSE; } } // if option } // for return TRUE; } // MyProcessCommandLineArguments /************************************************************************/ /* MyProcessEvents */ /************************************************************************/ static DWORD MyProcessEvents (void) { MSG myMessage; int myResult; while (TRUE) { myResult = GetMessage (&myMessage, NULL, 0, 0); if (!myResult) break; MyProcessMessage (&myMessage); } return myMessage.wParam; } // MyProcessEvents /************************************************************************/ /* MyProcessMessage */ /************************************************************************/ static void MyProcessMessage (MSG *pmMessagePtr) { /* // Log the windows messages if (TRUE) { EdLog_PrintWindowsMessage ("Processing", pmMessagePtr -> hwnd, pmMessagePtr -> message, pmMessagePtr -> wParam, pmMessagePtr -> lParam); } */ if ((stActiveWindow == NULL) || (!TranslateAccelerator (stActiveWindow, stAccelerator [stActiveWindowKind], pmMessagePtr))) { if ((stActiveModelessDialog == NULL) || (!IsDialogMessage (stActiveModelessDialog, pmMessagePtr))) { TranslateMessage (pmMessagePtr); DispatchMessage (pmMessagePtr); } } } // MyProcessMessage /***********************************************************************/ /* MySetForegroundWindow */ /***********************************************************************/ static BOOL MySetForegroundWindow (HWND pmWindow) { DWORD myThreadID1, myThreadID2; BOOL myResult; if (pmWindow == GetForegroundWindow ()) { return TRUE; } // // First need to get the thread responsible for this window, // and the thread for the foreground window. // myThreadID1 = GetWindowThreadProcessId (GetForegroundWindow (), NULL); myThreadID2 = GetWindowThreadProcessId (pmWindow, NULL); // // By sharing input state, threads share their concept of the active window. // if (myThreadID1 != myThreadID2) { AttachThreadInput (myThreadID1, myThreadID2, TRUE); myResult = SetForegroundWindow (pmWindow); Sleep (100); AttachThreadInput (myThreadID1, myThreadID2, FALSE); } else { myResult = SetForegroundWindow (pmWindow); Sleep (100); } if (IsIconic (pmWindow)) { ShowWindow (pmWindow, SW_RESTORE); } else { ShowWindow (pmWindow, SW_SHOW); } return myResult; } // MySetForegroundWindow
279980.c
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "PeripheralPins.h" /************RTC***************/ const PinMap PinMap_RTC[] = { {NC, OSC32KCLK, 0}, }; /************ADC***************/ const PinMap PinMap_ADC[] = { {PTB0, ADC0_SE8, 0}, {PTB1, ADC0_SE9, 0}, {PTB2, ADC0_SE12, 0}, {PTB3, ADC0_SE13, 0}, {PTC0, ADC0_SE14, 0}, {PTC1, ADC0_SE15, 0}, {PTC2, ADC0_SE4b, 0}, {PTD1, ADC0_SE5b, 0}, {PTD5, ADC0_SE6b, 0}, {PTD6, ADC0_SE7b, 0}, {NC, NC, 0} }; /************DAC***************/ const PinMap PinMap_DAC[] = { {DAC0_OUT, DAC_0, 0}, {NC, NC, 0} }; /************I2C***************/ const PinMap PinMap_I2C_SDA[] = { {PTB1, I2C_0, 2}, {PTB3, I2C_0, 2}, {PTC11, I2C_1, 2}, {PTD3, I2C_0, 7}, {PTD9, I2C_0, 2}, {PTE0, I2C_1, 6}, {NC, NC , 0} }; const PinMap PinMap_I2C_SCL[] = { {PTB0, I2C_0, 2}, {PTB2, I2C_0, 2}, {PTC10, I2C_1, 2}, {PTD2, I2C_0, 7}, {PTD8, I2C_0, 2}, {PTE1, I2C_1, 6}, {NC, NC, 0} }; /************LPUART***************/ const PinMap PinMap_UART_TX[] = { {PTA2, LPUART_0, 2}, {PTA14, LPUART_0, 3}, {PTB17, LPUART_0, 3}, {PTC4, LPUART_1, 3}, {PTD3, LPUART_2, 3}, {PTD7, LPUART_0, 3}, {PTE0, LPUART_1, 3}, {NC, NC, 0} }; const PinMap PinMap_UART_RX[] = { {PTA1, LPUART_0, 2}, {PTA15, LPUART_0, 3}, {PTB16, LPUART_0, 3}, {PTC3, LPUART_1, 3}, {PTD2, LPUART_2, 3}, {PTD6, LPUART_0, 3}, {PTE1, LPUART_1, 3}, {NC, NC, 0} }; /************SPI***************/ const PinMap PinMap_SPI_SCLK[] = { {PTE1, SPI_1, 2}, {PTE2, SPI_1, 7}, {PTA15, SPI_1, 2}, {PTB11, SPI_1, 2}, {PTC5, SPI_0, 2}, {PTD1, SPI_0, 2}, {PTD5, SPI_1, 7}, {NC, NC, 0} }; const PinMap PinMap_SPI_MOSI[] = { {PTE2, SPI_1, 2}, {PTE3, SPI_1, 7}, {PTA16, SPI_1, 2}, {PTB16, SPI_1, 2}, {PTC6, SPI_0, 2}, {PTD2, SPI_0, 2}, {PTD6, SPI_1, 7}, {NC, NC, 0} }; const PinMap PinMap_SPI_MISO[] = { {PTE1, SPI_1, 7}, {PTE4, SPI_1, 2}, {PTA17, SPI_1, 2}, {PTB17, SPI_1, 2}, {PTC7, SPI_0, 2}, {PTD3, SPI_0, 2}, {PTD7, SPI_1, 7}, {NC, NC, 0} }; const PinMap PinMap_SPI_SSEL[] = { {PTE5, SPI_1, 2}, {PTA14, SPI_1, 2}, {PTB10, SPI_1, 2}, {PTC4, SPI_0, 2}, {PTD0, SPI_0, 2}, {PTD4, SPI_1, 7}, {NC, NC, 0} }; /************PWM***************/ const PinMap PinMap_PWM[] = { {PTA0, PWM_6, 3}, // PTA0 , TPM0 CH5 {PTA3, PWM_1, 3}, // PTA3 , TPM0 CH0 {PTA4, PWM_2 , 3}, // PTA4 , TPM0 CH1 {PTA5, PWM_3 , 3}, // PTA5 , TPM0 CH2 {PTA10, PWM_9, 3}, // PTA10, TPM2 CH0 {PTA11, PWM_10, 3}, // PTA11, TPM2 CH1 {PTA12, PWM_7 , 3}, // PTA12, TPM1 CH0 {PTA13, PWM_8 , 3}, // PTA13, TPM1 CH1 {PTB0, PWM_7, 3}, // PTB0 , TPM1 CH0 {PTB1, PWM_8, 3}, // PTB1 , TPM1 CH1 {PTB18, PWM_9, 3}, // PTB18, TPM2 CH0 {PTB19, PWM_10, 3}, // PTB18, TPM2 CH1 {PTC1, PWM_1, 4}, // PTC1 , TPM0 CH0 {PTC2, PWM_2, 4}, // PTC2 , TPM0 CH1 {PTC3, PWM_3, 4}, // PTC3 , TPM0 CH2 {PTC4, PWM_4, 4}, // PTC4 , TPM0 CH3 {PTC5, PWM_3, 7}, // PTC4 , TPM0 CH2 {PTD4, PWM_5 , 4}, // PTD4 , TPM0 CH4 {PTD5, PWM_6 , 4}, // PTD5 , TPM0 CH5 {NC , NC , 0} };
691766.c
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* * Copyright 2017 Broadcom * * 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 (the "GPL"). * * 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 version 2 (GPLv2) for more details. * * You should have received a copy of the GNU General Public License * version 2 (GPLv2) along with this source code. */ /* * Test driver for call-back functions in Linux KNET driver. * * The module can be built from the standard Linux user mode target * directories using the following command (assuming bash), e.g. * * cd $SDK/systems/linux/user/gto-2_6 * BUILD_KNET_CB=1 make -s mod */ #include <gmodule.h> /* Must be included first */ #include <kcom.h> #include <bcm-knet.h> MODULE_AUTHOR("Broadcom Corporation"); MODULE_DESCRIPTION("Broadcom Linux KNET Call-Back Driver"); MODULE_LICENSE("GPL"); /* Module Information */ #define MODULE_MAJOR 121 #define MODULE_NAME "linux-knet-cb" static void show_mac(struct sk_buff *skb) { printk("DMAC=%02X:%02X:%02X:%02X:%02X:%02X\n", skb->data[0], skb->data[1], skb->data[2], skb->data[3], skb->data[4], skb->data[5]); } static struct sk_buff * test_rx_cb(struct sk_buff *skb, int dev_no, void *meta) { printk("rx_cb for dev %d\n", dev_no); printk("netif user data 0x%x\n", KNET_SKB_CB(skb)->netif_user_data); printk("filter user data 0x%x\n", KNET_SKB_CB(skb)->filter_user_data); printk("dcb type 0x%x\n", KNET_SKB_CB(skb)->dcb_type); if (skb->data[5] == 0x03) { dev_kfree_skb(skb); return NULL; } show_mac(skb); return skb; } static struct sk_buff * test_tx_cb(struct sk_buff *skb, int dev_no, void *meta) { printk("tx_cb for dev %d\n", dev_no); show_mac(skb); skb->data[5] += 1; return skb; } static int test_filter_cb(uint8_t *pkt, int size, int dev_no, void *meta, int chan, kcom_filter_t *kf) { printk("filter_cb (%d) for dev %d\n", kf->dest_id, dev_no); if (pkt[12] == 0x81 && pkt[13] == 0x00) { printk(" VTAG %d\n", pkt[15]); kf->dest_type = KCOM_DEST_T_NETIF; kf->dest_id = pkt[15]; return 1; } return 0; } /* * Generic module functions */ static int _pprint(void) { pprintf("Broadcom Linux KNET Call-Back Driver\n"); return 0; } static int _cleanup(void) { bkn_rx_skb_cb_unregister(test_rx_cb); bkn_tx_skb_cb_unregister(test_tx_cb); bkn_filter_cb_unregister(test_filter_cb); return 0; } static int _init(void) { bkn_rx_skb_cb_register(test_rx_cb); bkn_tx_skb_cb_register(test_tx_cb); bkn_filter_cb_register(test_filter_cb); return 0; } static gmodule_t _gmodule = { name: MODULE_NAME, major: MODULE_MAJOR, init: _init, cleanup: _cleanup, pprint: _pprint, ioctl: NULL, open: NULL, close: NULL, }; gmodule_t* gmodule_get(void) { EXPORT_NO_SYMBOLS; return &_gmodule; }
619862.c
/*- * Copyright (c) 2015 David Chisnall * Copyright (c) 2015 SRI International * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * 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 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 AUTHOR 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 <stdarg.h> #include "cheri_c_test.h" static char str[] = "012345678901234567890"; static volatile void *ptrs[] = { &str[0], &str[1], &str[2], &str[3], &str[4], &str[5], &str[6], &str[7], &str[8], &str[9], &str[0], &str[11], &str[12], &str[13], &str[14], &str[15], &str[16], &str[17], &str[18], &str[19] }; static int gint; static void printstuff(int argpairs, ...) { va_list ap; va_start(ap, argpairs); // Check that the length corresponds to the number of arguments, with // appropriate padding. assert_eq(__builtin_cheri_length_get(ap), argpairs * sizeof(void*) * 2); ASSERT_HAS_NOT_PERMISSION(ap, STORE); ASSERT_HAS_NOT_PERMISSION(ap, STORE_CAPABILITY); for (int i=0 ; i<argpairs ; i++) { int x = va_arg(ap, int); char *p = va_arg(ap, void*); assert_eq(x, i); assert(__builtin_cheri_tag_get(p)); assert_eq_cap(p, __DEVOLATILE(const void*, ptrs[i])); assert_eq(*p, str[i]); } va_end(ap); } typedef void (*inc_t)(void); static void inc(void) { gint++; } static void check_fp(int intarg, ...) { inc_t incfp; va_list ap; va_start(ap, intarg); // Check that we've been passed a single function pointer sized argument #ifdef INCLUDE_XFAIL assert_eq(__builtin_cheri_length_get(ap), sizeof(void *)); incfp = va_arg(ap, inc_t); for (int i = 0; i < intarg; i++) incfp(); assert_eq(gint, intarg); #else (void)incfp; #endif va_end(ap); } BEGIN_TEST(clang_purecap_va_args) printstuff(8, 0,ptrs[0],1,ptrs[1],2,ptrs[2],3,ptrs[3],4,ptrs[4],5,ptrs[5],6,ptrs[6],7,ptrs[7]); check_fp(3, &inc); assert_eq(faults, 0); END_TEST
88277.c
/* * Water Gauge * * COPYRIGHT (C) 2014-2015, Shanghai Real-Thread Technology Co., Ltd * http://www.rt-thread.com * * This file is part of RT-Thread (http://www.rt-thread.org) * * All rights reserved. * * 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. * * Change Logs: * Date Author Notes * 2014-04-16 Grissiom first version */ #include <rthw.h> #include <rtthread.h> #include "watermark_queue.h" void rt_wm_que_set_mark(struct rt_watermark_queue *wg, unsigned int low, unsigned int high) { RT_ASSERT(low <= high); wg->high_mark = high; wg->low_mark = low; } void rt_wm_que_init(struct rt_watermark_queue *wg, unsigned int low, unsigned int high) { rt_wm_que_set_mark(wg, low, high); rt_list_init(&wg->suspended_threads); wg->level = 0; } void rt_wm_que_dump(struct rt_watermark_queue *wg) { struct rt_list_node *node; rt_kprintf("wg %p: low: %d, high: %d, cur: %d\n", wg, wg->low_mark, wg->high_mark, wg->level); rt_kprintf("thread suspend:"); for (node = wg->suspended_threads.next; node != &wg->suspended_threads; node = node->next) { rt_thread_t thread; thread = rt_list_entry(wg->suspended_threads.next, struct rt_thread, tlist); rt_kprintf(" %.*s", RT_NAME_MAX, thread->name); } rt_kprintf("\n"); }
798713.c
/** @file misc.c * * Misc functions. * * Copyright 2009 Simon Kallweit * * 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 <lwpb/lwpb.h> /** * Returns a textual description of an lwpb error code. * @param err Error code * @return Returns the textual description. */ const char *lwpb_err_text(lwpb_err_t err) { switch (err) { case LWPB_ERR_OK: return "OK"; case LWPB_ERR_CANCEL: return "Cancelled by user"; case LWPB_ERR_UNKNOWN_FIELD: return "Unknown field"; case LWPB_ERR_INVALID_FIELD: return "Invalid field"; case LWPB_ERR_END_OF_BUF: return "End of buffer"; case LWPB_ERR_MEM: return "Memory allocation failed"; case LWPB_ERR_NET_INIT: return "Network initialization failed"; default: return "Unknown"; } }
236484.c
#include <stdio.h> void swapptr(int **a, int **b){ int *tmp; tmp = *a; *a = *b; *b = tmp; } int main(int argc, char **argv) { int x, y; int *m, *n; x = 5; y = 9; m = &x; n = &y; printf("*m = %d\n", *m); printf("*n = %d\n", *n); printf("n = %x\n", n); printf("m = %x\n", m); printf("Swapping\n"); swapptr(&m, &n); printf("*m = %d\n", *m); printf("*n = %d\n", *n); printf("m = %x\n", m); printf("n = %x\n", n); printf("x = %d\n", x); printf("y = %d\n", y); return 0; }
710817.c
/* * * Copyright 2015, Google Inc. * 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 Google Inc. 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 "test/core/end2end/end2end_tests.h" #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/useful.h> #include "src/core/ext/client_config/client_channel.h" #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" #include "src/core/lib/channel/compress_filter.h" #include "src/core/lib/channel/connected_channel.h" #include "src/core/lib/channel/http_client_filter.h" #include "src/core/lib/channel/http_server_filter.h" #include "src/core/lib/iomgr/endpoint_pair.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/surface/completion_queue.h" #include "src/core/lib/surface/server.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" /* chttp2 transport that is immediately available (used for testing connected_channel without a client_channel */ static void server_setup_transport(void *ts, grpc_transport *transport) { grpc_end2end_test_fixture *f = ts; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_endpoint_pair *sfd = f->fixture_data; grpc_endpoint_add_to_pollset(&exec_ctx, sfd->server, grpc_cq_pollset(f->cq)); grpc_server_setup_transport(&exec_ctx, f->server, transport, NULL, grpc_server_get_channel_args(f->server)); grpc_exec_ctx_finish(&exec_ctx); } typedef struct { grpc_end2end_test_fixture *f; grpc_channel_args *client_args; } sp_client_setup; static void client_setup_transport(grpc_exec_ctx *exec_ctx, void *ts, grpc_transport *transport) { sp_client_setup *cs = ts; cs->f->client = grpc_channel_create(exec_ctx, "socketpair-target", cs->client_args, GRPC_CLIENT_DIRECT_CHANNEL, transport); } static grpc_end2end_test_fixture chttp2_create_fixture_socketpair( grpc_channel_args *client_args, grpc_channel_args *server_args) { grpc_endpoint_pair *sfd = gpr_malloc(sizeof(grpc_endpoint_pair)); grpc_end2end_test_fixture f; memset(&f, 0, sizeof(f)); f.fixture_data = sfd; f.cq = grpc_completion_queue_create(NULL); *sfd = grpc_iomgr_create_endpoint_pair("fixture", 1); return f; } static void chttp2_init_client_socketpair(grpc_end2end_test_fixture *f, grpc_channel_args *client_args) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_endpoint_pair *sfd = f->fixture_data; grpc_transport *transport; sp_client_setup cs; cs.client_args = client_args; cs.f = f; transport = grpc_create_chttp2_transport(&exec_ctx, client_args, sfd->client, 1); client_setup_transport(&exec_ctx, &cs, transport); GPR_ASSERT(f->client); grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL); grpc_exec_ctx_finish(&exec_ctx); } static void chttp2_init_server_socketpair(grpc_end2end_test_fixture *f, grpc_channel_args *server_args) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_endpoint_pair *sfd = f->fixture_data; grpc_transport *transport; GPR_ASSERT(!f->server); f->server = grpc_server_create(server_args, NULL); grpc_server_register_completion_queue(f->server, f->cq, NULL); grpc_server_start(f->server); transport = grpc_create_chttp2_transport(&exec_ctx, server_args, sfd->server, 0); server_setup_transport(f, transport); grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL); grpc_exec_ctx_finish(&exec_ctx); } static void chttp2_tear_down_socketpair(grpc_end2end_test_fixture *f) { gpr_free(f->fixture_data); } /* All test configurations */ static grpc_end2end_test_config configs[] = { {"chttp2/socketpair_one_byte_at_a_time", 0, chttp2_create_fixture_socketpair, chttp2_init_client_socketpair, chttp2_init_server_socketpair, chttp2_tear_down_socketpair}, }; int main(int argc, char **argv) { size_t i; grpc_test_init(argc, argv); grpc_end2end_tests_pre_init(); grpc_init(); for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) { grpc_end2end_tests(argc, argv, configs[i]); } grpc_shutdown(); return 0; }
922890.c
/* Verify a quote issued by an AIK */ /* See aikquote.c for format of quote data file */ /* * Copyright (c) 2009 Hal Finney * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include <memory.h> //#include <trousers/tss.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/sha.h> #ifndef BYTE #define BYTE unsigned char #endif #ifndef UINT16 #define UINT16 unsigned short #endif #ifndef UINT32 #define UINT32 unsigned #endif int main (int ac, char **av) { FILE *f_in; BYTE *chal; UINT32 chalLen; BYTE *quote; UINT32 quoteLen; RSA *aikRsa; UINT32 selectLen; BYTE *select; UINT32 pcrLen; BYTE *pcrs; UINT32 sigLen; BYTE *sig; BYTE chalmd[20]; BYTE md[20]; BYTE qinfo[8+20+20]; char *chalfile = NULL; int pcr; int pcri = 0; int i; if (ac == 5 && 0 == strcmp(av[1], "-c")) { chalfile = av[2]; for (i=3; i<ac; i++) av[i-2] = av[i]; ac -= 2; } if (ac != 3) { fprintf (stderr, "Usage: %s [-c challengefile] aikrsafile quotefile\n", av[0]); exit (1); } /* Read challenge file */ if (chalfile) { if ((f_in = fopen (chalfile, "rb")) == NULL) { fprintf (stderr, "Unable to open file %s\n", chalfile); exit (1); } fseek (f_in, 0, SEEK_END); chalLen = ftell (f_in); fseek (f_in, 0, SEEK_SET); chal = malloc (chalLen); if (fread (chal, 1, chalLen, f_in) != chalLen) { fprintf (stderr, "Unable to read file %s\n", chalfile); exit (1); } fclose (f_in); SHA1 (chal, chalLen, chalmd); free (chal); } else { memset (chalmd, 0, sizeof(chalmd)); } /* Read AIK from OpenSSL file */ if ((f_in = fopen (av[1], "rb")) == NULL) { fprintf (stderr, "Unable to open file %s\n", av[1]); exit (1); } if ((aikRsa = PEM_read_RSA_PUBKEY(f_in, NULL, NULL, NULL)) == NULL) { fprintf (stderr, "Unable to read RSA file %s\n", av[1]); exit (1); } fclose (f_in); /* Read quote file */ if ((f_in = fopen (av[2], "rb")) == NULL) { fprintf (stderr, "Unable to open file %s\n", av[2]); exit (1); } fseek (f_in, 0, SEEK_END); quoteLen = ftell (f_in); fseek (f_in, 0, SEEK_SET); quote = malloc (quoteLen); if (fread (quote, 1, quoteLen, f_in) != quoteLen) { fprintf (stderr, "Unable to read file %s\n", av[2]); exit (1); } fclose (f_in); /* Parse quote file */ if (quoteLen < 2) goto badquote; selectLen = ntohs (*(UINT16*)quote); if (2 + selectLen + 4 > quoteLen) goto badquote; select = quote + 2; pcrLen = ntohl (*(UINT32*)(quote+2+selectLen)); if (2 + selectLen + 4 + pcrLen + 20 > quoteLen) goto badquote; pcrs = select + selectLen + 4; sig = pcrs + pcrLen; sigLen = quote + quoteLen - sig; /* Create TPM_QUOTE_INFO struct */ qinfo[0] = 1; qinfo[1] = 1; qinfo[2] = 0; qinfo[3] = 0; qinfo[4] = 'Q'; qinfo[5] = 'U'; qinfo[6] = 'O'; qinfo[7] = 'T'; SHA1 (quote, 2+selectLen+4+pcrLen, qinfo+8); memcpy (qinfo+8+20, chalmd, 20); /* Verify RSA signature */ SHA1 (qinfo, sizeof(qinfo), md); if (1 != RSA_verify(NID_sha1, md, sizeof(md), sig, sigLen, aikRsa)) { fprintf (stderr, "Error, bad RSA signature in quote\n"); exit (2); } /* Print out PCR values */ for (pcr=0; pcr < 8*selectLen; pcr++) { if (select[pcr/8] & (1 << (pcr%8))) { printf ("%2d ", pcr); for (i=0; i<20; i++) { printf ("%02x", pcrs[20*pcri+i]); } printf ("\n"); pcri++; } } fflush (stdout); fprintf (stderr, "Success!\n"); return 0; badquote: fprintf (stderr, "Input AIK quote file incorrect format\n"); return 1; }
616874.c
/* * Copyright (c) Texas Instruments Incorporated 2018 * * 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 Texas Instruments Incorporated 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. * */ /** * \file ccmr5_test_cfg_rd_op_key.c * * \brief This file contains CCM test code for R5 core. * * \details CCM register read/write and configuration tests **/ /* ========================================================================== */ /* Include Files */ /* ========================================================================== */ #include <ti/csl/test/ccmr5/ccmr5_test_app/ccmr5_test_main.h> #include <ti/csl/test/ccmr5/ccmr5_test_app/ccmr5_test_cfg_rd_op_key.h> /* ========================================================================== */ /* Macros */ /* ========================================================================== */ /* ========================================================================== */ /* Global Variables */ /* ========================================================================== */ /* ========================================================================== */ /* Internal Function Declarations */ /* ========================================================================== */ /* ========================================================================== */ /* Function Definitions */ /* ========================================================================== */ /* CCMR5 OP KEY Read for various module Ids */ int32_t CSL_CCMR5_Reg_Rd_Op_Key_Test(void *expectedVal) { int32_t csl_ret, testResult; uint32_t i; CSL_McuArmssCcmR5ModuleId modId, modIdList[CSL_CCMR5_TOTAL_NUM_MODULE_ID]; CSL_McuArmssCcmR5OpModeKey *pExpVal; uintptr_t ccmR5BaseAddress; CSL_McuArmssCcmR5OpModeKey expVal, opModeKey; int32_t metaInfo; /* Initialize the regiser values to be read to known value */ if (expectedVal != (void *) NULL) { pExpVal = ( CSL_McuArmssCcmR5OpModeKey*) expectedVal; expVal = *pExpVal; testResult = CSL_CCMR5_TEST_PASS; } else { testResult = CSL_CCMR5_TEST_FAIL; } /* test Read the Op Key for all modules */ if (testResult == CSL_CCMR5_TEST_PASS) { ccmR5BaseAddress = CSL_MCU_ARMSS0_COMPARE_CFG_BASE; modIdList[0] = CSL_MCU_ARMSS_CCMR5_CPU_MODULE_ID; modIdList[1] = CSL_MCU_ARMSS_CCMR5_VIM_MODULE_ID; modIdList[2] = CSL_MCU_ARMSS_CCMR5_INACTIVITY_MONITOR_MODULE_ID; for ( i = CSL_MCU_ARMSS_CCMR5_CPU_MODULE_ID; i < CSL_CCMR5_TOTAL_NUM_MODULE_ID; i++) { csl_ret = CSL_armR5CCMGetOperationModeKey(ccmR5BaseAddress, modIdList[i], &opModeKey, &metaInfo); if (csl_ret == CSL_PASS) { if (opModeKey != expVal) { testResult = CSL_CCMR5_TEST_FAIL; } else { testResult = CSL_CCMR5_TEST_PASS; } } else { /* set testResult to fail */ testResult = CSL_CCMR5_TEST_FAIL; } if (testResult == CSL_CCMR5_TEST_FAIL) { break; } } } /* Check for invalid module ID passed to CSL */ if ( testResult == CSL_CCMR5_TEST_PASS) { modId = CSL_MCU_ARMSS_CCMR5_INVALID_MODULE_ID; /* Some invalid module Id */ testResult = CSL_armR5CCMGetOperationModeKey(ccmR5BaseAddress, modId, &opModeKey, &metaInfo); /* Expected failure operation return from CSL and hence Fail is basically test pass */ if (testResult == CSL_CCMR5_TEST_FAIL) { testResult = CSL_CCMR5_TEST_PASS; } } return (testResult); } /* Key Write test */ int32_t CSL_CCMR5_Reg_Cfg_Op_key_Test(void *desiredVal) { int32_t testResult; uint32_t i; CSL_McuArmssCcmR5ModuleId modIdList[CSL_CCMR5_TOTAL_NUM_MODULE_ID]; uintptr_t ccmR5BaseAddress; CSL_McuArmssCcmR5OpModeKey opModeKeySave[CSL_CCMR5_TOTAL_NUM_MODULE_ID]; int32_t metaInfo; testResult = CSL_CCMR5_TEST_PASS; /* Save the original Op key value before the test, excercise GetKey API */ if (testResult == CSL_CCMR5_TEST_PASS) { ccmR5BaseAddress = CSL_MCU_ARMSS0_COMPARE_CFG_BASE; modIdList[0] = CSL_MCU_ARMSS_CCMR5_CPU_MODULE_ID; modIdList[1] = CSL_MCU_ARMSS_CCMR5_VIM_MODULE_ID; modIdList[2] = CSL_MCU_ARMSS_CCMR5_INACTIVITY_MONITOR_MODULE_ID; for ( i = CSL_MCU_ARMSS_CCMR5_CPU_MODULE_ID; i < CSL_CCMR5_TOTAL_NUM_MODULE_ID; i++) { testResult = CSL_armR5CCMGetOperationModeKey(ccmR5BaseAddress, modIdList[i], &opModeKeySave[i], &metaInfo); if (testResult != CSL_PASS) { /* set testResult to fail */ testResult = CSL_CCMR5_TEST_FAIL; break; } } } /* Restore the original Op key value before the test, excercise SetKey API */ if (testResult == CSL_CCMR5_TEST_PASS) { ccmR5BaseAddress = CSL_MCU_ARMSS0_COMPARE_CFG_BASE; for ( i = CSL_MCU_ARMSS_CCMR5_CPU_MODULE_ID; i < CSL_CCMR5_TOTAL_NUM_MODULE_ID; i++) { testResult = CSL_armR5CCMSetOperationModeKey(ccmR5BaseAddress, modIdList[i], opModeKeySave[i], &metaInfo); if (testResult != CSL_PASS) { /* set testResult to fail */ testResult = CSL_CCMR5_TEST_FAIL; break; } else { testResult = CSL_CCMR5_TEST_PASS; } } } return (testResult); } /* Nothing past this point */
797705.c
/* mbed Microcontroller Library * SPDX-License-Identifier: BSD-3-Clause ****************************************************************************** * * Copyright (c) 2016-2021 STMicroelectronics. * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** * * Automatically generated from STM32CubeMX/db/mcu/STM32L443CCTx.xml */ #include "PeripheralPins.h" #include "mbed_toolchain.h" //============================================================================== // Notes // // - The pins mentioned Px_y_ALTz are alternative possibilities which use other // HW peripheral instances. You can use them the same way as any other "normal" // pin (i.e. PwmOut pwm(PA_7_ALT0);). These pins are not displayed on the board // pinout image on mbed.org. // // - The pins which are connected to other components present on the board have // the comment "Connected to xxx". The pin function may not work properly in this // case. These pins may not be displayed on the board pinout image on mbed.org. // Please read the board reference manual and schematic for more information. // // - Warning: pins connected to the default STDIO_UART_TX and STDIO_UART_RX pins are commented // See https://os.mbed.com/teams/ST/wiki/STDIO for more information. // //============================================================================== //*** ADC *** MBED_WEAK const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC1_IN11 {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12 {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16 {NC, NC, 0} }; // !!! SECTION TO BE CHECKED WITH DEVICE REFERENCE MANUAL MBED_WEAK const PinMap PinMap_ADC_Internal[] = { // {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, {NC, NC, 0} }; //*** DAC *** MBED_WEAK const PinMap PinMap_DAC[] = { {PA_4, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC1_OUT1 {PA_5, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC1_OUT2 {NC, NC, 0} }; //*** I2C *** MBED_WEAK const PinMap PinMap_I2C_SDA[] = { {PA_10, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_4, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PB_14, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_I2C_SCL[] = { {PA_7, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PA_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PB_13, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {NC, NC, 0} }; //*** PWM *** // TIM2 cannot be used because already used by the us_ticker // (update us_ticker_data.h file if another timer is chosen) MBED_WEAK const PinMap PinMap_PWM[] = { // {PA_0, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PA_1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N // {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 {PA_2, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 // {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 {PA_3, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 // {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 {PA_6, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 {PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4 // {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 {PB_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N {PB_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N // {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_6, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM16, 1, 1)}, // TIM16_CH1N {PB_8, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 // {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 {PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N {PB_13_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N {PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N {PB_14_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 {PB_15, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N {PB_15_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 {NC, NC, 0} }; //*** SERIAL *** MBED_WEAK const PinMap PinMap_UART_TX[] = { {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_2_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_UART_RX[] = { {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_3_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_USART2)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_UART_RTS[] = { {PA_1, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_15, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PB_1, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PB_1_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PB_3, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_12, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PB_14, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_UART_CTS[] = { {PA_0, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_6, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PA_6_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PA_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_4, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_13, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PB_13_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {NC, NC, 0} }; //*** SPI *** MBED_WEAK const PinMap PinMap_SPI_MOSI[] = { {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PA_12, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_5_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_SPI_MISO[] = { {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PA_11, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_SPI_SCLK[] = { {PA_1, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_3_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_SPI_SSEL[] = { {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PA_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PA_15_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_0, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, {PB_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, {NC, NC, 0} }; //*** CAN *** MBED_WEAK const PinMap PinMap_CAN_RD[] = { {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_CAN_TD[] = { {PA_12, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_9, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; //*** QUADSPI *** MBED_WEAK const PinMap PinMap_QSPI_DATA0[] = { {PB_1, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO0 {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_QSPI_DATA1[] = { {PB_0, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO1 {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_QSPI_DATA2[] = { {PA_7, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO2 {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_QSPI_DATA3[] = { {PA_6, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO3 {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_QSPI_SCLK[] = { {PA_3, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_CLK {PB_10, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_CLK {NC, NC, 0} }; MBED_WEAK const PinMap PinMap_QSPI_SSEL[] = { {PA_2, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_NCS {PB_11, QSPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_NCS {NC, NC, 0} }; //*** USBDEVICE *** MBED_WEAK const PinMap PinMap_USB_FS[] = { {PA_11, USB_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF10_USB_FS)}, // USB_DM {PA_12, USB_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF10_USB_FS)}, // USB_DP // {PA_13, USB_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB_FS)}, // USB_NOE {NC, NC, 0} };
239492.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* elements.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bsouchet <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/23 17:56:13 by bsouchet #+# #+# */ /* Updated: 2017/05/13 10:40:25 by bsouchet ### ########.fr */ /* */ /* ************************************************************************** */ #include "rt.h" void set_default_element(t_rt *rt, t_cl *cl, char type) { char *str; str = ft_strdup((char *)rt->scn->s_elem->n); free(rt->scn->s_elem->n); set_default_parameters(rt->scn->s_elem, type, 0); rt->scn->s_elem->id = rt->ui->id++; if (type == 'C') rt->scn->s_elem->n = (cl_char *)ft_strf("Default"); else if (type == 'L') rt->scn->s_elem->n = (cl_char *)ft_strf("Default Diffuse"); else rt->scn->s_elem->n = (cl_char *)ft_strf("Default Sphere"); rt->scn->s_elem->forme = 0; redraw_current_element(rt, cl, str); } void add_new_camera(t_rt *rt, t_obj *tmp) { tmp = set_default_parameters(rt->prs->obj_tmp, 'C', 0); tmp->n = (cl_char *)ft_strjoin("Camera ", ft_itoa(rt->scn->n_cams), 'R'); tmp->focal = rt->scn->c_cam->focal; tmp->pos.x = rt->scn->c_cam->pos.x; tmp->pos.y = rt->scn->c_cam->pos.y; tmp->pos.z = rt->scn->c_cam->pos.z; tmp->rot.x = rt->scn->c_cam->rot.x; tmp->rot.y = rt->scn->c_cam->rot.y; tmp->rot.z = rt->scn->c_cam->rot.z; rt->scn->o = lst_new_camera(rt, rt->scn->o, 0); rt->ui->area[4].h += (rt->ui->area[4].h <= 379) ? 29 : 0; (rt->scn->n_elms >= 12) ? (rt->ui->nav_state = 1) : 1; (rt->r_view.x != 18) ? draw_outliner(rt, -1, 0) : 1; } void add_new_light(t_rt *rt, t_obj *tmp, short type) { tmp = set_default_parameters(rt->prs->obj_tmp, 'L', 0); if (type == T_DIFFUSE && ++rt->scn->lt[0]) tmp->n = (cl_char *)ft_strjoin("Point ", ft_itoa(rt->scn->lt[0]), 'R'); else if (type == T_DIRECTIONAL && ++rt->scn->lt[1]) tmp->n = (cl_char *)ft_strjoin("Directional ", ft_itoa(rt->scn->lt[1]), 'R'); else if (++rt->scn->lt[2]) tmp->n = (cl_char *)ft_strjoin("Spot ", ft_itoa(rt->scn->lt[2]), 'R'); tmp->forme = type; tmp->clr = (cl_float3){{1.0f, (219. / 255.), (74. / 255.), 1.0f}}; rt->scn->o = lst_new_light(rt, rt->scn->o, 0); rt->ui->area[4].h += (rt->ui->area[4].h <= 379) ? 29 : 0; (rt->scn->n_elms >= 12) ? (rt->ui->nav_state = 1) : 1; (rt->r_view.x != 18) ? draw_outliner(rt, -1, 0) : 1; } void add_new_object(t_rt *rt, t_obj *tmp, short type) { ++rt->scn->ot[type]; tmp = set_default_parameters(rt->prs->obj_tmp, 'O', 0); tmp->n = (cl_char *)ft_strjoin(shape_object(type), ft_itoa(rt->scn->ot[type]), 'R'); tmp->forme = type; rt->scn->o = lst_new_object(rt, rt->scn->o, 0, 0); rt->ui->area[4].h += (rt->ui->area[4].h <= 379) ? 29 : 0; (rt->scn->n_elms >= 12) ? (rt->ui->nav_state = 1) : 1; (rt->r_view.x != 18) ? draw_outliner(rt, -1, 0) : 1; } void add_new_shader(t_obj *obj, short type) { obj->preset = type; if (type == 0) { obj->clr = (cl_float3){{0.51, 0.314, 0.098, 1.0f}}; obj->radius = 40; obj->shader = 22; } else if (type == 1) { obj->clr = (cl_float3){{0.51, 0.51, 0.50, 1.0f}}; obj->radius = 90; obj->shader = 2; } else if (type == 2) { obj->clr = (cl_float3){{0.992, 1.0f, 1.0f, 1.0f}}; obj->radius = 25; obj->shader = 20; } else if (type == 3) { obj->clr = (cl_float3){{0.544, 0.488, 0.5058, 1.0f}}; obj->radius = 75; obj->shader = 12; } }
536399.c
/*************************************************************************** Taito F3 Video emulation - Bryan McPhail, [email protected] **************************************************************************** Brief overview: 4 scrolling layers (512x512 or 1024x512) of 4/5/6 bpp tiles. 1 scrolling text layer (512x512, characters generated in vram), 4bpp chars. 1 scrolling pixel layer (512x256 pixels generated in pivot ram), 4bpp pixels. 2 sprite banks (for double buffering of sprites) Sprites can be 4, 5 or 6 bpp Sprite scaling. Rowscroll on all playfields Line by line zoom on all playfields Column scroll on all playfields Line by line sprite and playfield priority mixing Notes: All special effects are controlled by an area in 'line ram'. Typically there are 256 values, one for each line of the screen (including clipped lines at the top of the screen). For example, at 0x8000 in lineram, there are 4 sets of 256 values (one for each playfield) and each value is the scale control for that line in the destination bitmap (screen). Therefore each line can have a different zoom value for special effects. This also applies to playfield priority, rowscroll, column scroll, sprite priority and VRAM/pivot layers. However - at the start of line ram there are also sets of 256 values controlling each effect - effects can be selectively applied to individual playfields or only certain lines out of the 256 can be active - in which case the last allowed value can be latched (typically used so a game can use one zoom or row value over the whole playfield). The programmers of some of these games made strange use of flipscreen - some games have all their graphics flipped in ROM, and use the flipscreen bit to display them correctly!. Most games display 232 scanlines, but some use lineram effects to clip themselves to 224 or less. **************************************************************************** Line ram memory map: Here 'playfield 1' refers to the first playfield in memory, etc 0x0000: Column line control ram (256 lines) 100x: Where bit 0 of x enables effect on playfield 1 Where bit 1 of x enables effect on playfield 2 Where bit 2 of x enables effect on playfield 3 Where bit 3 of x enables effect on playfield 4 0x0200: Line control ram for 0x5000 section. 0x0400: Line control ram for 0x6000 section. 180x: Where bit 0 of x latches sprite alpha value Where bit 1 of x latches tilemap alpha value 0x0600: Sprite control ram 1c0x: Where x enables sprite control word for that line 0x0800: Zoom line control ram (256 lines) 200x: Where bit 0 of x enables effect on playfield 1 Where bit 1 of x enables effect on playfield 2 Where bit 2 of x enables effect on playfield 3 Where bit 3 of x enables effect on playfield 4 0x0a00: Assumed unused. 0x0c00: Rowscroll line control ram (256 lines) 280x: Where bit 0 of x enables effect on playfield 1 Where bit 1 of x enables effect on playfield 2 Where bit 2 of x enables effect on playfield 3 Where bit 3 of x enables effect on playfield 4 0x0e00: Priority line control ram (256 lines) 2c0x: Where bit 0 of x enables effect on playfield 1 Where bit 1 of x enables effect on playfield 2 Where bit 2 of x enables effect on playfield 3 Where bit 3 of x enables effect on playfield 4 0x4000: Column scroll & clipping info 0x5000: Clip plane 0 (low bits) 0x5200: Clip plane 1 (low bits) 0x5400: Unused? 0x5600: Unused? 0x6000: Sync register 0x6004: Sprite alpha control 0xff00: VRAM/Pixel layer control 0xa000 enables pixel layer for this line (Disables VRAM layer) 0x2000 enables garbage pixels for this line (maybe another pixel bank?) [unemulated] 0x0800 seems to set the vram layer to be opaque [unemulated] Effect of other bits is unknown. 0x00c0: Alpha mode for sprites with pri value 0x00 0x0030: Alpha mode for sprites with pri value 0x00 0x000c: Alpha mode for sprites with pri value 0x00 0x0003: Alpha mode for sprites with pri value 0x00 0x6200: Alpha blending control 0x6400 - controls X zoom of tile - each tile collapses to 16 single colour lines xxx1 - affects bottom playfield xxx2 - xxx4 - xxx8 - affects top playfield xxfx - x zoom - 0 = 1st pixel 16 times 1 = 1st pixel 8, then 2nd 8 8 = 2 per pixel (these effects only known to be used on spcinvdj title screen and riding fight - not emulated) 1xxx = interpret palette ram for this playfield line as 15 bit and bilinear filter framebuffer(??) 3xxx = interpret palette ram for this playfield line as 15 bit 7xxx = interpret palette ram for this playfield line as 24 bit palette 8xxx = interpret palette ram for this playfield line as 21 bit palette (effect not emulated) 0x6600: Background - background palette entry (under all tilemaps) (takes part in alpha blending) (effect not emulated) 0x7000: Pivot/vram layer enable 0x7200: Cram layer priority 0x7400: Sprite clipping 0x7600: Sprite priority values 0xf000: Relative priority for sprites with pri value 0xc0 0x0f00: Relative priority for sprites with pri value 0x80 0x00f0: Relative priority for sprites with pri value 0x40 0x000f: Relative priority for sprites with pri value 0x00 0x8000: Playfield 1 scale (1 word per line, 256 lines, 0x80 = default no scale) 0x8200: Playfield 2/4 scale 0x8400: Playfield 3 scale 0x8600: Playfield 2/4 scale 0x00ff = Y scale (0x80 = no scale, > 0x80 is zoom in, < 0x80 is zoom out [0xc0 is half height of 0x80]) 0xff00 = X scale (0 = no scale, > 0 = zoom in, [0x8000 would be double length]) Playfield 2 & 4 registers seem to be interleaved, playfield 2 Y zoom is stored where you would expect playfield 4 y zoom to be and vice versa. 0x9000: Palette add (can affect opacity) [ not emulated ] 0xa000: Playfield 1 rowscroll (1 word per line, 256 lines) 0xa200: Playfield 2 rowscroll 0xa400: Playfield 3 rowscroll 0xa600: Playfield 4 rowscroll 0xb000: Playfield 1 priority (1 word per line, 256 lines) 0xb200: Playfield 2 priority 0xb400: Playfield 3 priority 0xb600: Playfield 4 priority 0xf000 = Blend mode, 0x3000 = Normal, 0x7000 = Alpha A, 0xb000 = Alpha B, others disable line 0x0800 = Clip line (totally disable line) 0x0400 = Assumed unused 0x0200 = If set enable clip plane 1 0x0100 = If set enable clip plane 0 0x00c0 = Assumed unused 0x0020 = Enable clip inverse mode for plane 1 0x0010 = Enable clip inverse mode for plane 0 0x000f = Layer priority 0xc000 - 0xffff: Unused. When sprite priority==playfield priority sprite takes precedence (Bubble Symph title) **************************************************************************** F3 sprite format: Word 0: 0xffff Tile number (LSB) Word 1: 0xff00 X zoom 0x00ff Y zoom Word 2: 0x03ff X position Word 3: 0x03ff Y position Word 4: 0xf000 Sprite block controls 0x0800 Sprite block start 0x0400 Use same colour on this sprite as block start 0x0200 Y flip 0x0100 X flip 0x00ff Colour Word 5: 0xffff Tile number (MSB), probably only low bits used Word 6: 0x8000 If set, jump to sprite location in low bits 0x03ff Location to jump to. Word 7: 0xffff Unused? Always zero? **************************************************************************** Playfield control information (0x660000-1f): Word 0- 3: X scroll values for the 4 playfields. Word 4- 7: Y scroll values for the 4 playfields. Word 8-11: Unused. Always zero. Word 12: Pixel + VRAM playfields X scroll Word 13: Pixel + VRAM playfields Y scroll Word 14: Unused. Always zero. Word 15: If set to 0x80, then 1024x512 playfields are used, else 512x512 top bits unused - writing to low 4 bits is desync or blank tilemap Playfield tile info: 0xc000 0000 - X/Y Flip 0x3000 ffff - Tile index 0x0dff 0000 - Colour (top 2 bits use not clear, always set) 0x0200 0000 - Alpha blend mode ***************************************************************************/ #include "driver.h" #include "taito_f3.h" #include "ui.h" #define DARIUSG_KLUDGE //#define DEBUG_F3 1 static tilemap *pf1_tilemap,*pf2_tilemap,*pf3_tilemap,*pf4_tilemap; static tilemap *pixel_layer,*vram_layer; static UINT32 *spriteram32_buffered; static int vram_dirty[256]; static int pivot_changed,vram_changed; static UINT32 f3_control_0[8]; static UINT32 f3_control_1[8]; static int flipscreen; static UINT8 *pivot_dirty; static UINT32 *f3_pf_data_1,*f3_pf_data_2,*f3_pf_data_3,*f3_pf_data_4; UINT32 *f3_vram,*f3_line_ram; UINT32 *f3_pf_data,*f3_pivot_ram; static int f3_skip_this_frame; /* Game specific data, some of this can be removed when the software values are figured out */ struct F3config { int name; int extend; int sprite_lag; }; static const struct F3config *f3_game_config; static const struct F3config f3_config_table[] = { /* Name Extend Sprite Lag */ { RINGRAGE, 0, 2 }, { ARABIANM, 0, 2 }, { RIDINGF, 1, 1 }, { GSEEKER, 0, 1 }, { TRSTAR, 1, 0 }, { GUNLOCK, 1, 2 }, { TWINQIX, 1, 1 }, { SCFINALS, 0, 1 }, { LIGHTBR, 1, 2 }, { KAISERKN, 0, 2 }, { DARIUSG, 0, 2 }, { BUBSYMPH, 1, 1 }, { SPCINVDX, 1, 1 }, { QTHEATER, 1, 1 }, { HTHERO95, 0, 1 }, { SPCINV95, 0, 1 }, { EACTION2, 1, 2 }, { QUIZHUHU, 1, 1 }, { PBOBBLE2, 0, 1 }, { GEKIRIDO, 0, 1 }, { KTIGER2, 0, 0 }, { BUBBLEM, 1, 1 }, { CLEOPATR, 0, 1 }, { PBOBBLE3, 0, 1 }, { ARKRETRN, 1, 1 }, { KIRAMEKI, 0, 1 }, { PUCHICAR, 1, 1 }, { PBOBBLE4, 0, 1 }, { POPNPOP, 1, 1 }, { LANDMAKR, 1, 1 }, { RECALH, 1, 1 }, { COMMANDW, 1, 1 }, {0} }; struct tempsprite { int code,color; int flipx,flipy; int x,y; int zoomx,zoomy; int pri; }; static struct tempsprite *spritelist; static const struct tempsprite *sprite_end; static void get_sprite_info(running_machine *machine, const UINT32 *spriteram32_ptr); static int sprite_lag=1; static UINT8 sprite_pri_usage=0; struct f3_playfield_line_inf { int alpha_mode[256]; int pri[256]; /* use for draw_scanlines */ UINT16 *src[256],*src_s[256],*src_e[256]; UINT8 *tsrc[256],*tsrc_s[256]; int x_count[256]; UINT32 x_zoom[256]; UINT32 clip0[256]; UINT32 clip1[256]; }; struct f3_spritealpha_line_inf { UINT16 alpha_level[256]; UINT16 spri[256]; UINT16 sprite_alpha[256]; UINT32 sprite_clip0[256]; UINT32 sprite_clip1[256]; INT16 clip0_l[256]; INT16 clip0_r[256]; INT16 clip1_l[256]; INT16 clip1_r[256]; }; /* alpha_mode ---- --xx 0:disable 1:nomal 2:alpha 7000 3:alpha b000 ---1 ---- alpha level a --1- ---- alpha level b 1-------- opaque line */ static struct f3_playfield_line_inf *pf_line_inf; static struct f3_spritealpha_line_inf *sa_line_inf; static mame_bitmap *pri_alp_bitmap; /* pri_alp_bitmap ---- ---1 sprite priority 0 ---- --1- sprite priority 1 ---- -1-- sprite priority 2 ---- 1--- sprite priority 3 ---1 ---- alpha level a 7000 --1- ---- alpha level b 7000 -1-- ---- alpha level a b000 1--- ---- alpha level b b000 1111 1111 opaque pixel */ static int f3_alpha_level_2as=127; static int f3_alpha_level_2ad=127; static int f3_alpha_level_3as=127; static int f3_alpha_level_3ad=127; static int f3_alpha_level_2bs=127; static int f3_alpha_level_2bd=127; static int f3_alpha_level_3bs=127; static int f3_alpha_level_3bd=127; static void init_alpha_blend_func(void); static int width_mask=0x1ff; static int twidth_mask=0x1f,twidth_mask_bit=5; static UINT8 *tile_opaque_sp; static UINT8 *tile_opaque_pf; /******************************************************************************/ static void print_debug_info(mame_bitmap *bitmap) { int l[16]; char buf[64*16]; char *bufptr = buf; bufptr += sprintf(bufptr,"%04X %04X %04X %04X\n",f3_control_0[0]>>22,(f3_control_0[0]&0xffff)>>6,f3_control_0[1]>>22,(f3_control_0[1]&0xffff)>>6); bufptr += sprintf(bufptr,"%04X %04X %04X %04X\n",f3_control_0[2]>>23,(f3_control_0[2]&0xffff)>>7,f3_control_0[3]>>23,(f3_control_0[3]&0xffff)>>7); bufptr += sprintf(bufptr,"%04X %04X %04X %04X\n",f3_control_1[0]>>16,f3_control_1[0]&0xffff,f3_control_1[1]>>16,f3_control_1[1]&0xffff); bufptr += sprintf(bufptr,"%04X %04X %04X %04X\n",f3_control_1[2]>>16,f3_control_1[2]&0xffff,f3_control_1[3]>>16,f3_control_1[3]&0xffff); bufptr += sprintf(bufptr,"%04X %04X %04X %04X %04X %04X %04X %04X\n",spriteram32_buffered[0]>>16,spriteram32_buffered[0]&0xffff,spriteram32_buffered[1]>>16,spriteram32_buffered[1]&0xffff,spriteram32_buffered[2]>>16,spriteram32_buffered[2]&0xffff,spriteram32_buffered[3]>>16,spriteram32_buffered[3]&0xffff); bufptr += sprintf(bufptr,"%04X %04X %04X %04X %04X %04X %04X %04X\n",spriteram32_buffered[4]>>16,spriteram32_buffered[4]&0xffff,spriteram32_buffered[5]>>16,spriteram32_buffered[5]&0xffff,spriteram32_buffered[6]>>16,spriteram32_buffered[6]&0xffff,spriteram32_buffered[7]>>16,spriteram32_buffered[7]&0xffff); bufptr += sprintf(bufptr,"%04X %04X %04X %04X %04X %04X %04X %04X\n",spriteram32_buffered[8]>>16,spriteram32_buffered[8]&0xffff,spriteram32_buffered[9]>>16,spriteram32_buffered[9]&0xffff,spriteram32_buffered[10]>>16,spriteram32_buffered[10]&0xffff,spriteram32_buffered[11]>>16,spriteram32_buffered[11]&0xffff); l[0]=f3_line_ram[0x0040]&0xffff; l[1]=f3_line_ram[0x00c0]&0xffff; l[2]=f3_line_ram[0x0140]&0xffff; l[3]=f3_line_ram[0x01c0]&0xffff; bufptr += sprintf(bufptr,"Ctr1: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x0240]&0xffff; l[1]=f3_line_ram[0x02c0]&0xffff; l[2]=f3_line_ram[0x0340]&0xffff; l[3]=f3_line_ram[0x03c0]&0xffff; bufptr += sprintf(bufptr,"Ctr2: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x2c60]&0xffff; l[1]=f3_line_ram[0x2ce0]&0xffff; l[2]=f3_line_ram[0x2d60]&0xffff; l[3]=f3_line_ram[0x2de0]&0xffff; bufptr += sprintf(bufptr,"Pri : %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x2060]&0xffff; l[1]=f3_line_ram[0x20e0]&0xffff; l[2]=f3_line_ram[0x2160]&0xffff; l[3]=f3_line_ram[0x21e0]&0xffff; bufptr += sprintf(bufptr,"Zoom: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x2860]&0xffff; l[1]=f3_line_ram[0x28e0]&0xffff; l[2]=f3_line_ram[0x2960]&0xffff; l[3]=f3_line_ram[0x29e0]&0xffff; bufptr += sprintf(bufptr,"Line: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x1c60]&0xffff; l[1]=f3_line_ram[0x1ce0]&0xffff; l[2]=f3_line_ram[0x1d60]&0xffff; l[3]=f3_line_ram[0x1de0]&0xffff; bufptr += sprintf(bufptr,"Sprt: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x1860]&0xffff; l[1]=f3_line_ram[0x18e0]&0xffff; l[2]=f3_line_ram[0x1960]&0xffff; l[3]=f3_line_ram[0x19e0]&0xffff; bufptr += sprintf(bufptr,"Pivt: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x1060]&0xffff; l[1]=f3_line_ram[0x10e0]&0xffff; l[2]=f3_line_ram[0x1160]&0xffff; l[3]=f3_line_ram[0x11e0]&0xffff; bufptr += sprintf(bufptr,"Colm: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); l[0]=f3_line_ram[0x1460]&0xffff; l[1]=f3_line_ram[0x14e0]&0xffff; l[2]=f3_line_ram[0x1560]&0xffff; l[3]=f3_line_ram[0x15e0]&0xffff; bufptr += sprintf(bufptr,"5000: %04x %04x %04x %04x\n",l[0],l[1],l[2],l[3]); ui_draw_text(buf, 60, 40); } /******************************************************************************/ INLINE void get_tile_info(running_machine *machine, tile_data *tileinfo, int tile_index, UINT32 *gfx_base) { UINT32 tile=gfx_base[tile_index]; UINT8 abtype=(tile>>(16+9))&0x1f; SET_TILE_INFO( 1, tile&0xffff, (tile>>16)&0x1ff, TILE_FLIPYX( tile >> 30 )); tileinfo->category = abtype&1; /* alpha blending type */ } static TILE_GET_INFO( get_tile_info1 ) { get_tile_info(machine,tileinfo,tile_index,f3_pf_data_1); } static TILE_GET_INFO( get_tile_info2 ) { get_tile_info(machine,tileinfo,tile_index,f3_pf_data_2); } static TILE_GET_INFO( get_tile_info3 ) { get_tile_info(machine,tileinfo,tile_index,f3_pf_data_3); } static TILE_GET_INFO( get_tile_info4 ) { get_tile_info(machine,tileinfo,tile_index,f3_pf_data_4); } static TILE_GET_INFO( get_tile_info_vram ) { int vram_tile; int flags=0; if (tile_index&1) vram_tile = (videoram32[tile_index>>1]&0xffff); else vram_tile = (videoram32[tile_index>>1]>>16); if (vram_tile&0x0100) flags|=TILE_FLIPX; if (vram_tile&0x8000) flags|=TILE_FLIPY; SET_TILE_INFO( 0, vram_tile&0xff, (vram_tile>>9)&0x3f, flags); } static TILE_GET_INFO( get_tile_info_pixel ) { int vram_tile,col_off; int flags=0; int y_offs=(f3_control_1[2]&0x1ff); if (flipscreen) y_offs+=0x100; /* Colour is shared with VRAM layer */ if ((((tile_index%32)*8 + y_offs)&0x1ff)>0xff) col_off=0x800+((tile_index%32)*0x40)+((tile_index&0xfe0)>>5); else col_off=((tile_index%32)*0x40)+((tile_index&0xfe0)>>5); if (col_off&1) vram_tile = (videoram32[col_off>>1]&0xffff); else vram_tile = (videoram32[col_off>>1]>>16); if (vram_tile&0x0100) flags|=TILE_FLIPX; if (vram_tile&0x8000) flags|=TILE_FLIPY; SET_TILE_INFO( 3, tile_index, (vram_tile>>9)&0x3f, flags); } /******************************************************************************/ VIDEO_EOF( f3 ) { if (sprite_lag==2) { if (video_skip_this_frame() == 0) { get_sprite_info(machine, spriteram32_buffered); } memcpy(spriteram32_buffered,spriteram32,spriteram_size); } else if (sprite_lag==1) { if (video_skip_this_frame() == 0) { get_sprite_info(machine, spriteram32); } } } VIDEO_START( f3 ) { const struct F3config *pCFG=&f3_config_table[0]; int tile; spritelist=0; spriteram32_buffered=0; pivot_dirty=0; pf_line_inf=0; pri_alp_bitmap=0; tile_opaque_sp=0; tile_opaque_pf=0; /* Setup individual game */ do { if (pCFG->name==f3_game) { break; } pCFG++; } while(pCFG->name); f3_game_config=pCFG; if (f3_game_config->extend) { pf1_tilemap = tilemap_create(get_tile_info1,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,64,32); pf2_tilemap = tilemap_create(get_tile_info2,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,64,32); pf3_tilemap = tilemap_create(get_tile_info3,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,64,32); pf4_tilemap = tilemap_create(get_tile_info4,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,64,32); f3_pf_data_1=f3_pf_data+0x0000; f3_pf_data_2=f3_pf_data+0x0800; f3_pf_data_3=f3_pf_data+0x1000; f3_pf_data_4=f3_pf_data+0x1800; width_mask=0x3ff; twidth_mask=0x3f; twidth_mask_bit=6; } else { pf1_tilemap = tilemap_create(get_tile_info1,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,32,32); pf2_tilemap = tilemap_create(get_tile_info2,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,32,32); pf3_tilemap = tilemap_create(get_tile_info3,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,32,32); pf4_tilemap = tilemap_create(get_tile_info4,tilemap_scan_rows,TILEMAP_TYPE_PEN,16,16,32,32); f3_pf_data_1=f3_pf_data+0x0000; f3_pf_data_2=f3_pf_data+0x0400; f3_pf_data_3=f3_pf_data+0x0800; f3_pf_data_4=f3_pf_data+0x0c00; width_mask=0x1ff; twidth_mask=0x1f; twidth_mask_bit=5; } spriteram32_buffered = (UINT32 *)auto_malloc(0x10000); spritelist = auto_malloc(0x400 * sizeof(*spritelist)); sprite_end = spritelist; vram_layer = tilemap_create(get_tile_info_vram,tilemap_scan_rows,TILEMAP_TYPE_PEN,8,8,64,64); pixel_layer = tilemap_create(get_tile_info_pixel,tilemap_scan_cols,TILEMAP_TYPE_PEN,8,8,64,32); pivot_dirty = (UINT8 *)auto_malloc(2048); pf_line_inf = auto_malloc(5 * sizeof(struct f3_playfield_line_inf)); sa_line_inf = auto_malloc(1 * sizeof(struct f3_spritealpha_line_inf)); pri_alp_bitmap = auto_bitmap_alloc( machine->screen[0].width, machine->screen[0].height, BITMAP_FORMAT_INDEXED8 ); tile_opaque_sp = (UINT8 *)auto_malloc(machine->gfx[2]->total_elements); tile_opaque_pf = (UINT8 *)auto_malloc(machine->gfx[1]->total_elements); tilemap_set_transparent_pen(pf1_tilemap,0); tilemap_set_transparent_pen(pf2_tilemap,0); tilemap_set_transparent_pen(pf3_tilemap,0); tilemap_set_transparent_pen(pf4_tilemap,0); tilemap_set_transparent_pen(vram_layer,0); tilemap_set_transparent_pen(pixel_layer,0); /* Palettes have 4 bpp indexes despite up to 6 bpp data */ machine->gfx[1]->color_granularity=16; machine->gfx[2]->color_granularity=16; flipscreen = 0; memset(spriteram32_buffered,0,spriteram_size); memset(spriteram32,0,spriteram_size); state_save_register_global_array(f3_control_0); state_save_register_global_array(f3_control_1); for (tile = 0;tile < 256;tile++) vram_dirty[tile]=1; for (tile = 0;tile < 2048;tile++) pivot_dirty[tile]=1; f3_skip_this_frame=0; sprite_lag=f3_game_config->sprite_lag; init_alpha_blend_func(); { const gfx_element *sprite_gfx = machine->gfx[2]; int c; for (c = 0;c < sprite_gfx->total_elements;c++) { int x,y; int chk_trans_or_opa=0; UINT8 *dp = sprite_gfx->gfxdata + c * sprite_gfx->char_modulo; for (y = 0;y < sprite_gfx->height;y++) { for (x = 0;x < sprite_gfx->width;x++) { if(!dp[x]) chk_trans_or_opa|=2; else chk_trans_or_opa|=1; } dp += sprite_gfx->line_modulo; } if(chk_trans_or_opa==1) tile_opaque_sp[c]=1; else tile_opaque_sp[c]=0; } } { const gfx_element *pf_gfx = machine->gfx[1]; int c; for (c = 0;c < pf_gfx->total_elements;c++) { int x,y; int chk_trans_or_opa=0; UINT8 *dp = pf_gfx->gfxdata + c * pf_gfx->char_modulo; for (y = 0;y < pf_gfx->height;y++) { for (x = 0;x < pf_gfx->width;x++) { if(!dp[x]) chk_trans_or_opa|=2; else chk_trans_or_opa|=1; } dp += pf_gfx->line_modulo; } tile_opaque_pf[c]=chk_trans_or_opa; } } } /******************************************************************************/ WRITE32_HANDLER( f3_pf_data_w ) { COMBINE_DATA(&f3_pf_data[offset]); if (f3_game_config->extend) { if (offset<0x800) tilemap_mark_tile_dirty(pf1_tilemap,offset-0x0000); else if (offset<0x1000) tilemap_mark_tile_dirty(pf2_tilemap,offset-0x0800); else if (offset<0x1800) tilemap_mark_tile_dirty(pf3_tilemap,offset-0x1000); else if (offset<0x2000) tilemap_mark_tile_dirty(pf4_tilemap,offset-0x1800); } else { if (offset<0x400) tilemap_mark_tile_dirty(pf1_tilemap,offset-0x0000); else if (offset<0x800) tilemap_mark_tile_dirty(pf2_tilemap,offset-0x0400); else if (offset<0xc00) tilemap_mark_tile_dirty(pf3_tilemap,offset-0x0800); else if (offset<0x1000) tilemap_mark_tile_dirty(pf4_tilemap,offset-0xc00); } } WRITE32_HANDLER( f3_control_0_w ) { COMBINE_DATA(&f3_control_0[offset]); } WRITE32_HANDLER( f3_control_1_w ) { COMBINE_DATA(&f3_control_1[offset]); } WRITE32_HANDLER( f3_videoram_w ) { int tile,col_off; COMBINE_DATA(&videoram32[offset]); tilemap_mark_tile_dirty(vram_layer,offset<<1); tilemap_mark_tile_dirty(vram_layer,(offset<<1)+1); if (offset>0x3ff) offset-=0x400; tile=offset<<1; col_off=((tile&0x3f)*32)+((tile&0xfc0)>>6); tilemap_mark_tile_dirty(pixel_layer,col_off); tilemap_mark_tile_dirty(pixel_layer,col_off+32); } WRITE32_HANDLER( f3_vram_w ) { COMBINE_DATA(&f3_vram[offset]); vram_dirty[offset/8]=1; vram_changed=1; } WRITE32_HANDLER( f3_pivot_w ) { COMBINE_DATA(&f3_pivot_ram[offset]); pivot_dirty[offset/8]=1; pivot_changed=1; } WRITE32_HANDLER( f3_lineram_w ) { /* DariusGX has an interesting bug at the start of Round D - the clearing of lineram (0xa000->0x0xa7ff) overflows into priority RAM (0xb000) and creates garbage priority values. I'm not sure what the real machine would do with these values, and this emulation certainly doesn't like it, so I've chosen to catch the bug here, and prevent the trashing of priority ram. If anyone has information on what the real machine does, please let me know! */ if (f3_game==DARIUSG) { if (f3_skip_this_frame) return; if (offset==0xb000/4 && data==0x003f0000) { f3_skip_this_frame=1; return; } } COMBINE_DATA(&f3_line_ram[offset]); } WRITE32_HANDLER( f3_palette_24bit_w ) { int r,g,b; COMBINE_DATA(&paletteram32[offset]); /* 12 bit palette games - there has to be a palette select bit somewhere */ if (f3_game==SPCINVDX || f3_game==RIDINGF || f3_game==ARABIANM || f3_game==RINGRAGE) { b = 15 * ((paletteram32[offset] >> 4) & 0xf); g = 15 * ((paletteram32[offset] >> 8) & 0xf); r = 15 * ((paletteram32[offset] >> 12) & 0xf); } /* This is weird - why are only the sprites and VRAM palettes 21 bit? */ else if (f3_game==CLEOPATR) { if (offset<0x100 || offset>0x1000) { r = ((paletteram32[offset] >>16) & 0x7f)<<1; g = ((paletteram32[offset] >> 8) & 0x7f)<<1; b = ((paletteram32[offset] >> 0) & 0x7f)<<1; } else { r = (paletteram32[offset] >>16) & 0xff; g = (paletteram32[offset] >> 8) & 0xff; b = (paletteram32[offset] >> 0) & 0xff; } } /* Another weird couple - perhaps this is alpha blending related? */ else if (f3_game==TWINQIX || f3_game==RECALH) { if (offset>0x1c00) { r = ((paletteram32[offset] >>16) & 0x7f)<<1; g = ((paletteram32[offset] >> 8) & 0x7f)<<1; b = ((paletteram32[offset] >> 0) & 0x7f)<<1; } else { r = (paletteram32[offset] >>16) & 0xff; g = (paletteram32[offset] >> 8) & 0xff; b = (paletteram32[offset] >> 0) & 0xff; } } /* All other games - standard 24 bit palette */ else { r = (paletteram32[offset] >>16) & 0xff; g = (paletteram32[offset] >> 8) & 0xff; b = (paletteram32[offset] >> 0) & 0xff; } palette_set_color(Machine,offset,MAKE_RGB(r,g,b)); } /******************************************************************************/ static UINT8 add_sat[256][256]; static int alpha_s_1_1; static int alpha_s_1_2; static int alpha_s_1_4; static int alpha_s_1_5; static int alpha_s_1_6; static int alpha_s_1_8; static int alpha_s_1_9; static int alpha_s_1_a; static int alpha_s_2a_0; static int alpha_s_2a_4; static int alpha_s_2a_8; static int alpha_s_2b_0; static int alpha_s_2b_4; static int alpha_s_2b_8; static int alpha_s_3a_0; static int alpha_s_3a_1; static int alpha_s_3a_2; static int alpha_s_3b_0; static int alpha_s_3b_1; static int alpha_s_3b_2; static UINT32 dval; static UINT8 pval; static UINT8 tval; static UINT8 pdest_2a = 0x10; static UINT8 pdest_2b = 0x20; static int tr_2a = 0; static int tr_2b = 1; static UINT8 pdest_3a = 0x40; static UINT8 pdest_3b = 0x80; static int tr_3a = 0; static int tr_3b = 1; static int (*dpix_n[8][16])(UINT32 s_pix); static int (**dpix_lp[5])(UINT32 s_pix); static int (**dpix_sp[9])(UINT32 s_pix); /*============================================================================*/ #define SET_ALPHA_LEVEL(d,s) \ { \ int level = s; \ if(level == 0) level = -1; \ d = level+1; \ } INLINE void f3_alpha_set_level(void) { // SET_ALPHA_LEVEL(alpha_s_1_1, f3_alpha_level_2ad) SET_ALPHA_LEVEL(alpha_s_1_1, 255-f3_alpha_level_2as) // SET_ALPHA_LEVEL(alpha_s_1_2, f3_alpha_level_2bd) SET_ALPHA_LEVEL(alpha_s_1_2, 255-f3_alpha_level_2bs) SET_ALPHA_LEVEL(alpha_s_1_4, f3_alpha_level_3ad) // SET_ALPHA_LEVEL(alpha_s_1_5, f3_alpha_level_3ad*f3_alpha_level_2ad/255) SET_ALPHA_LEVEL(alpha_s_1_5, f3_alpha_level_3ad*(255-f3_alpha_level_2as)/255) // SET_ALPHA_LEVEL(alpha_s_1_6, f3_alpha_level_3ad*f3_alpha_level_2bd/255) SET_ALPHA_LEVEL(alpha_s_1_6, f3_alpha_level_3ad*(255-f3_alpha_level_2bs)/255) SET_ALPHA_LEVEL(alpha_s_1_8, f3_alpha_level_3bd) // SET_ALPHA_LEVEL(alpha_s_1_9, f3_alpha_level_3bd*f3_alpha_level_2ad/255) SET_ALPHA_LEVEL(alpha_s_1_9, f3_alpha_level_3bd*(255-f3_alpha_level_2as)/255) // SET_ALPHA_LEVEL(alpha_s_1_a, f3_alpha_level_3bd*f3_alpha_level_2bd/255) SET_ALPHA_LEVEL(alpha_s_1_a, f3_alpha_level_3bd*(255-f3_alpha_level_2bs)/255) SET_ALPHA_LEVEL(alpha_s_2a_0, f3_alpha_level_2as) SET_ALPHA_LEVEL(alpha_s_2a_4, f3_alpha_level_2as*f3_alpha_level_3ad/255) SET_ALPHA_LEVEL(alpha_s_2a_8, f3_alpha_level_2as*f3_alpha_level_3bd/255) SET_ALPHA_LEVEL(alpha_s_2b_0, f3_alpha_level_2bs) SET_ALPHA_LEVEL(alpha_s_2b_4, f3_alpha_level_2bs*f3_alpha_level_3ad/255) SET_ALPHA_LEVEL(alpha_s_2b_8, f3_alpha_level_2bs*f3_alpha_level_3bd/255) SET_ALPHA_LEVEL(alpha_s_3a_0, f3_alpha_level_3as) SET_ALPHA_LEVEL(alpha_s_3a_1, f3_alpha_level_3as*f3_alpha_level_2ad/255) SET_ALPHA_LEVEL(alpha_s_3a_2, f3_alpha_level_3as*f3_alpha_level_2bd/255) SET_ALPHA_LEVEL(alpha_s_3b_0, f3_alpha_level_3bs) SET_ALPHA_LEVEL(alpha_s_3b_1, f3_alpha_level_3bs*f3_alpha_level_2ad/255) SET_ALPHA_LEVEL(alpha_s_3b_2, f3_alpha_level_3bs*f3_alpha_level_2bd/255) } #undef SET_ALPHA_LEVEL /*============================================================================*/ #ifdef LSB_FIRST #define COLOR1 0 #define COLOR2 1 #define COLOR3 2 #else #define COLOR1 3 #define COLOR2 2 #define COLOR3 1 #endif INLINE void f3_alpha_blend32_s( int alphas, UINT32 s ) { UINT8 *sc = (UINT8 *)&s; UINT8 *dc = (UINT8 *)&dval; dc[COLOR1] = (alphas * sc[COLOR1]) >> 8; dc[COLOR2] = (alphas * sc[COLOR2]) >> 8; dc[COLOR3] = (alphas * sc[COLOR3]) >> 8; } INLINE void f3_alpha_blend32_d( int alphas, UINT32 s ) { UINT8 *sc = (UINT8 *)&s; UINT8 *dc = (UINT8 *)&dval; dc[COLOR1] = add_sat[dc[COLOR1]][(alphas * sc[COLOR1]) >> 8]; dc[COLOR2] = add_sat[dc[COLOR2]][(alphas * sc[COLOR2]) >> 8]; dc[COLOR3] = add_sat[dc[COLOR3]][(alphas * sc[COLOR3]) >> 8]; } /*============================================================================*/ INLINE void f3_alpha_blend_1_1( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_1,s);} INLINE void f3_alpha_blend_1_2( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_2,s);} INLINE void f3_alpha_blend_1_4( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_4,s);} INLINE void f3_alpha_blend_1_5( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_5,s);} INLINE void f3_alpha_blend_1_6( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_6,s);} INLINE void f3_alpha_blend_1_8( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_8,s);} INLINE void f3_alpha_blend_1_9( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_9,s);} INLINE void f3_alpha_blend_1_a( UINT32 s ){f3_alpha_blend32_d(alpha_s_1_a,s);} INLINE void f3_alpha_blend_2a_0( UINT32 s ){f3_alpha_blend32_s(alpha_s_2a_0,s);} INLINE void f3_alpha_blend_2a_4( UINT32 s ){f3_alpha_blend32_d(alpha_s_2a_4,s);} INLINE void f3_alpha_blend_2a_8( UINT32 s ){f3_alpha_blend32_d(alpha_s_2a_8,s);} INLINE void f3_alpha_blend_2b_0( UINT32 s ){f3_alpha_blend32_s(alpha_s_2b_0,s);} INLINE void f3_alpha_blend_2b_4( UINT32 s ){f3_alpha_blend32_d(alpha_s_2b_4,s);} INLINE void f3_alpha_blend_2b_8( UINT32 s ){f3_alpha_blend32_d(alpha_s_2b_8,s);} INLINE void f3_alpha_blend_3a_0( UINT32 s ){f3_alpha_blend32_s(alpha_s_3a_0,s);} INLINE void f3_alpha_blend_3a_1( UINT32 s ){f3_alpha_blend32_d(alpha_s_3a_1,s);} INLINE void f3_alpha_blend_3a_2( UINT32 s ){f3_alpha_blend32_d(alpha_s_3a_2,s);} INLINE void f3_alpha_blend_3b_0( UINT32 s ){f3_alpha_blend32_s(alpha_s_3b_0,s);} INLINE void f3_alpha_blend_3b_1( UINT32 s ){f3_alpha_blend32_d(alpha_s_3b_1,s);} INLINE void f3_alpha_blend_3b_2( UINT32 s ){f3_alpha_blend32_d(alpha_s_3b_2,s);} /*============================================================================*/ static int dpix_1_noalpha(UINT32 s_pix) {dval = s_pix; return 1;} static int dpix_ret1(UINT32 s_pix) {return 1;} static int dpix_ret0(UINT32 s_pix) {return 0;} static int dpix_1_1(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_1(s_pix); return 1;} static int dpix_1_2(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_2(s_pix); return 1;} static int dpix_1_4(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_4(s_pix); return 1;} static int dpix_1_5(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_5(s_pix); return 1;} static int dpix_1_6(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_6(s_pix); return 1;} static int dpix_1_8(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_8(s_pix); return 1;} static int dpix_1_9(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_9(s_pix); return 1;} static int dpix_1_a(UINT32 s_pix) {if(s_pix) f3_alpha_blend_1_a(s_pix); return 1;} static int dpix_2a_0(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2a_0(s_pix); else dval = 0; if(pdest_2a) {pval |= pdest_2a;return 0;} return 1; } static int dpix_2a_4(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2a_4(s_pix); if(pdest_2a) {pval |= pdest_2a;return 0;} return 1; } static int dpix_2a_8(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2a_8(s_pix); if(pdest_2a) {pval |= pdest_2a;return 0;} return 1; } static int dpix_3a_0(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3a_0(s_pix); else dval = 0; if(pdest_3a) {pval |= pdest_3a;return 0;} return 1; } static int dpix_3a_1(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3a_1(s_pix); if(pdest_3a) {pval |= pdest_3a;return 0;} return 1; } static int dpix_3a_2(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3a_2(s_pix); if(pdest_3a) {pval |= pdest_3a;return 0;} return 1; } static int dpix_2b_0(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2b_0(s_pix); else dval = 0; if(pdest_2b) {pval |= pdest_2b;return 0;} return 1; } static int dpix_2b_4(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2b_4(s_pix); if(pdest_2b) {pval |= pdest_2b;return 0;} return 1; } static int dpix_2b_8(UINT32 s_pix) { if(s_pix) f3_alpha_blend_2b_8(s_pix); if(pdest_2b) {pval |= pdest_2b;return 0;} return 1; } static int dpix_3b_0(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3b_0(s_pix); else dval = 0; if(pdest_3b) {pval |= pdest_3b;return 0;} return 1; } static int dpix_3b_1(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3b_1(s_pix); if(pdest_3b) {pval |= pdest_3b;return 0;} return 1; } static int dpix_3b_2(UINT32 s_pix) { if(s_pix) f3_alpha_blend_3b_2(s_pix); if(pdest_3b) {pval |= pdest_3b;return 0;} return 1; } static int dpix_2_0(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_2b) {f3_alpha_blend_2b_0(s_pix);if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {f3_alpha_blend_2a_0(s_pix);if(pdest_2a) pval |= pdest_2a;else return 1;} } else { if(tr2==tr_2b) {dval = 0;if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {dval = 0;if(pdest_2a) pval |= pdest_2a;else return 1;} } return 0; } static int dpix_2_4(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_2b) {f3_alpha_blend_2b_4(s_pix);if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {f3_alpha_blend_2a_4(s_pix);if(pdest_2a) pval |= pdest_2a;else return 1;} } else { if(tr2==tr_2b) {if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {if(pdest_2a) pval |= pdest_2a;else return 1;} } return 0; } static int dpix_2_8(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_2b) {f3_alpha_blend_2b_8(s_pix);if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {f3_alpha_blend_2a_8(s_pix);if(pdest_2a) pval |= pdest_2a;else return 1;} } else { if(tr2==tr_2b) {if(pdest_2b) pval |= pdest_2b;else return 1;} else if(tr2==tr_2a) {if(pdest_2a) pval |= pdest_2a;else return 1;} } return 0; } static int dpix_3_0(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_3b) {f3_alpha_blend_3b_0(s_pix);if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {f3_alpha_blend_3a_0(s_pix);if(pdest_3a) pval |= pdest_3a;else return 1;} } else { if(tr2==tr_3b) {dval = 0;if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {dval = 0;if(pdest_3a) pval |= pdest_3a;else return 1;} } return 0; } static int dpix_3_1(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_3b) {f3_alpha_blend_3b_1(s_pix);if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {f3_alpha_blend_3a_1(s_pix);if(pdest_3a) pval |= pdest_3a;else return 1;} } else { if(tr2==tr_3b) {if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {if(pdest_3a) pval |= pdest_3a;else return 1;} } return 0; } static int dpix_3_2(UINT32 s_pix) { UINT8 tr2=tval&1; if(s_pix) { if(tr2==tr_3b) {f3_alpha_blend_3b_2(s_pix);if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {f3_alpha_blend_3a_2(s_pix);if(pdest_3a) pval |= pdest_3a;else return 1;} } else { if(tr2==tr_3b) {if(pdest_3b) pval |= pdest_3b;else return 1;} else if(tr2==tr_3a) {if(pdest_3a) pval |= pdest_3a;else return 1;} } return 0; } INLINE void dpix_1_sprite(UINT32 s_pix) { if(s_pix) { UINT8 p1 = pval&0xf0; if (p1==0x10) f3_alpha_blend_1_1(s_pix); else if(p1==0x20) f3_alpha_blend_1_2(s_pix); else if(p1==0x40) f3_alpha_blend_1_4(s_pix); else if(p1==0x50) f3_alpha_blend_1_5(s_pix); else if(p1==0x60) f3_alpha_blend_1_6(s_pix); else if(p1==0x80) f3_alpha_blend_1_8(s_pix); else if(p1==0x90) f3_alpha_blend_1_9(s_pix); else if(p1==0xa0) f3_alpha_blend_1_a(s_pix); } } INLINE void dpix_bg(UINT32 bgcolor) { UINT8 p1 = pval&0xf0; if(!p1) dval = bgcolor; else if(p1==0x10) f3_alpha_blend_1_1(bgcolor); else if(p1==0x20) f3_alpha_blend_1_2(bgcolor); else if(p1==0x40) f3_alpha_blend_1_4(bgcolor); else if(p1==0x50) f3_alpha_blend_1_5(bgcolor); else if(p1==0x60) f3_alpha_blend_1_6(bgcolor); else if(p1==0x80) f3_alpha_blend_1_8(bgcolor); else if(p1==0x90) f3_alpha_blend_1_9(bgcolor); else if(p1==0xa0) f3_alpha_blend_1_a(bgcolor); } /******************************************************************************/ static void init_alpha_blend_func(void) { int i,j; dpix_n[0][0x0]=dpix_1_noalpha; dpix_n[0][0x1]=dpix_1_noalpha; dpix_n[0][0x2]=dpix_1_noalpha; dpix_n[0][0x3]=dpix_1_noalpha; dpix_n[0][0x4]=dpix_1_noalpha; dpix_n[0][0x5]=dpix_1_noalpha; dpix_n[0][0x6]=dpix_1_noalpha; dpix_n[0][0x7]=dpix_1_noalpha; dpix_n[0][0x8]=dpix_1_noalpha; dpix_n[0][0x9]=dpix_1_noalpha; dpix_n[0][0xa]=dpix_1_noalpha; dpix_n[0][0xb]=dpix_1_noalpha; dpix_n[0][0xc]=dpix_1_noalpha; dpix_n[0][0xd]=dpix_1_noalpha; dpix_n[0][0xe]=dpix_1_noalpha; dpix_n[0][0xf]=dpix_1_noalpha; dpix_n[1][0x0]=dpix_1_noalpha; dpix_n[1][0x1]=dpix_1_1; dpix_n[1][0x2]=dpix_1_2; dpix_n[1][0x3]=dpix_ret1; dpix_n[1][0x4]=dpix_1_4; dpix_n[1][0x5]=dpix_1_5; dpix_n[1][0x6]=dpix_1_6; dpix_n[1][0x7]=dpix_ret1; dpix_n[1][0x8]=dpix_1_8; dpix_n[1][0x9]=dpix_1_9; dpix_n[1][0xa]=dpix_1_a; dpix_n[1][0xb]=dpix_ret1; dpix_n[1][0xc]=dpix_ret1; dpix_n[1][0xd]=dpix_ret1; dpix_n[1][0xe]=dpix_ret1; dpix_n[1][0xf]=dpix_ret1; dpix_n[2][0x0]=dpix_2a_0; dpix_n[2][0x1]=dpix_ret0; dpix_n[2][0x2]=dpix_ret0; dpix_n[2][0x3]=dpix_ret0; dpix_n[2][0x4]=dpix_2a_4; dpix_n[2][0x5]=dpix_ret0; dpix_n[2][0x6]=dpix_ret0; dpix_n[2][0x7]=dpix_ret0; dpix_n[2][0x8]=dpix_2a_8; dpix_n[2][0x9]=dpix_ret0; dpix_n[2][0xa]=dpix_ret0; dpix_n[2][0xb]=dpix_ret0; dpix_n[2][0xc]=dpix_ret0; dpix_n[2][0xd]=dpix_ret0; dpix_n[2][0xe]=dpix_ret0; dpix_n[2][0xf]=dpix_ret0; dpix_n[3][0x0]=dpix_3a_0; dpix_n[3][0x1]=dpix_3a_1; dpix_n[3][0x2]=dpix_3a_2; dpix_n[3][0x3]=dpix_ret0; dpix_n[3][0x4]=dpix_ret0; dpix_n[3][0x5]=dpix_ret0; dpix_n[3][0x6]=dpix_ret0; dpix_n[3][0x7]=dpix_ret0; dpix_n[3][0x8]=dpix_ret0; dpix_n[3][0x9]=dpix_ret0; dpix_n[3][0xa]=dpix_ret0; dpix_n[3][0xb]=dpix_ret0; dpix_n[3][0xc]=dpix_ret0; dpix_n[3][0xd]=dpix_ret0; dpix_n[3][0xe]=dpix_ret0; dpix_n[3][0xf]=dpix_ret0; dpix_n[4][0x0]=dpix_2b_0; dpix_n[4][0x1]=dpix_ret0; dpix_n[4][0x2]=dpix_ret0; dpix_n[4][0x3]=dpix_ret0; dpix_n[4][0x4]=dpix_2b_4; dpix_n[4][0x5]=dpix_ret0; dpix_n[4][0x6]=dpix_ret0; dpix_n[4][0x7]=dpix_ret0; dpix_n[4][0x8]=dpix_2b_8; dpix_n[4][0x9]=dpix_ret0; dpix_n[4][0xa]=dpix_ret0; dpix_n[4][0xb]=dpix_ret0; dpix_n[4][0xc]=dpix_ret0; dpix_n[4][0xd]=dpix_ret0; dpix_n[4][0xe]=dpix_ret0; dpix_n[4][0xf]=dpix_ret0; dpix_n[5][0x0]=dpix_3b_0; dpix_n[5][0x1]=dpix_3b_1; dpix_n[5][0x2]=dpix_3b_2; dpix_n[5][0x3]=dpix_ret0; dpix_n[5][0x4]=dpix_ret0; dpix_n[5][0x5]=dpix_ret0; dpix_n[5][0x6]=dpix_ret0; dpix_n[5][0x7]=dpix_ret0; dpix_n[5][0x8]=dpix_ret0; dpix_n[5][0x9]=dpix_ret0; dpix_n[5][0xa]=dpix_ret0; dpix_n[5][0xb]=dpix_ret0; dpix_n[5][0xc]=dpix_ret0; dpix_n[5][0xd]=dpix_ret0; dpix_n[5][0xe]=dpix_ret0; dpix_n[5][0xf]=dpix_ret0; dpix_n[6][0x0]=dpix_2_0; dpix_n[6][0x1]=dpix_ret0; dpix_n[6][0x2]=dpix_ret0; dpix_n[6][0x3]=dpix_ret0; dpix_n[6][0x4]=dpix_2_4; dpix_n[6][0x5]=dpix_ret0; dpix_n[6][0x6]=dpix_ret0; dpix_n[6][0x7]=dpix_ret0; dpix_n[6][0x8]=dpix_2_8; dpix_n[6][0x9]=dpix_ret0; dpix_n[6][0xa]=dpix_ret0; dpix_n[6][0xb]=dpix_ret0; dpix_n[6][0xc]=dpix_ret0; dpix_n[6][0xd]=dpix_ret0; dpix_n[6][0xe]=dpix_ret0; dpix_n[6][0xf]=dpix_ret0; dpix_n[7][0x0]=dpix_3_0; dpix_n[7][0x1]=dpix_3_1; dpix_n[7][0x2]=dpix_3_2; dpix_n[7][0x3]=dpix_ret0; dpix_n[7][0x4]=dpix_ret0; dpix_n[7][0x5]=dpix_ret0; dpix_n[7][0x6]=dpix_ret0; dpix_n[7][0x7]=dpix_ret0; dpix_n[7][0x8]=dpix_ret0; dpix_n[7][0x9]=dpix_ret0; dpix_n[7][0xa]=dpix_ret0; dpix_n[7][0xb]=dpix_ret0; dpix_n[7][0xc]=dpix_ret0; dpix_n[7][0xd]=dpix_ret0; dpix_n[7][0xe]=dpix_ret0; dpix_n[7][0xf]=dpix_ret0; for(i=0;i<256;i++) for(j=0;j<256;j++) add_sat[i][j] = (i + j < 256) ? i + j : 255; } /******************************************************************************/ #define GET_PIXMAP_POINTER(pf_num) \ { \ const struct f3_playfield_line_inf *line_tmp=line_t[pf_num]; \ src##pf_num=line_tmp->src[y]; \ src_s##pf_num=line_tmp->src_s[y]; \ src_e##pf_num=line_tmp->src_e[y]; \ tsrc##pf_num=line_tmp->tsrc[y]; \ tsrc_s##pf_num=line_tmp->tsrc_s[y]; \ x_count##pf_num=line_tmp->x_count[y]; \ x_zoom##pf_num=line_tmp->x_zoom[y]; \ clip_al##pf_num=line_tmp->clip0[y]&0xffff; \ clip_ar##pf_num=line_tmp->clip0[y]>>16; \ clip_bl##pf_num=line_tmp->clip1[y]&0xffff; \ clip_br##pf_num=line_tmp->clip1[y]>>16; \ } #define CULC_PIXMAP_POINTER(pf_num) \ { \ x_count##pf_num += x_zoom##pf_num; \ if(x_count##pf_num>>16) \ { \ x_count##pf_num &= 0xffff; \ src##pf_num++; \ tsrc##pf_num++; \ if(src##pf_num==src_e##pf_num) {src##pf_num=src_s##pf_num; tsrc##pf_num=tsrc_s##pf_num;} \ } \ } /*============================================================================*/ INLINE void draw_scanlines(running_machine *machine, mame_bitmap *bitmap,int xsize,INT16 *draw_line_num, const struct f3_playfield_line_inf **line_t, const int *sprite, UINT32 orient, int skip_layer_num) { const pen_t *clut = &machine->remapped_colortable[0]; UINT32 bgcolor=clut[0]; int length; const int x=46; UINT32 sprite_noalp_0=sprite[0]&0x100; UINT32 sprite_noalp_1=sprite[1]&0x100; UINT32 sprite_noalp_2=sprite[2]&0x100; UINT32 sprite_noalp_3=sprite[3]&0x100; UINT32 sprite_noalp_4=sprite[4]&0x100; UINT32 sprite_noalp_5=sprite[5]&0x100; static UINT16 *src0=0,*src_s0=0,*src_e0=0,clip_al0=0,clip_ar0=0,clip_bl0=0,clip_br0=0; static UINT8 *tsrc0=0,*tsrc_s0=0; static UINT32 x_count0=0,x_zoom0=0; static UINT16 *src1=0,*src_s1=0,*src_e1=0,clip_al1=0,clip_ar1=0,clip_bl1=0,clip_br1=0; static UINT8 *tsrc1=0,*tsrc_s1=0; static UINT32 x_count1=0,x_zoom1=0; static UINT16 *src2=0,*src_s2=0,*src_e2=0,clip_al2=0,clip_ar2=0,clip_bl2=0,clip_br2=0; static UINT8 *tsrc2=0,*tsrc_s2=0; static UINT32 x_count2=0,x_zoom2=0; static UINT16 *src3=0,*src_s3=0,*src_e3=0,clip_al3=0,clip_ar3=0,clip_bl3=0,clip_br3=0; static UINT8 *tsrc3=0,*tsrc_s3=0; static UINT32 x_count3=0,x_zoom3=0; static UINT16 *src4=0,*src_s4=0,*src_e4=0,clip_al4=0,clip_ar4=0,clip_bl4=0,clip_br4=0; static UINT8 *tsrc4=0,*tsrc_s4=0; static UINT32 x_count4=0,x_zoom4=0; UINT16 clip_als=0, clip_ars=0, clip_bls=0, clip_brs=0; UINT8 *dstp0,*dstp; int yadv = bitmap->rowpixels; int i=0,y=draw_line_num[0]; int ty = y; if (orient & ORIENTATION_FLIP_Y) { ty = bitmap->height - 1 - ty; yadv = -yadv; } dstp0 = BITMAP_ADDR8(pri_alp_bitmap, ty, x); pdest_2a = f3_alpha_level_2ad ? 0x10 : 0; pdest_2b = f3_alpha_level_2bd ? 0x20 : 0; tr_2a =(f3_alpha_level_2as==0 && f3_alpha_level_2ad==255) ? -1 : 0; tr_2b =(f3_alpha_level_2bs==0 && f3_alpha_level_2bd==255) ? -1 : 1; pdest_3a = f3_alpha_level_3ad ? 0x40 : 0; pdest_3b = f3_alpha_level_3bd ? 0x80 : 0; tr_3a =(f3_alpha_level_3as==0 && f3_alpha_level_3ad==255) ? -1 : 0; tr_3b =(f3_alpha_level_3bs==0 && f3_alpha_level_3bd==255) ? -1 : 1; { UINT32 *dsti0,*dsti; dsti0 = BITMAP_ADDR32(bitmap, ty, x); while(1) { int cx=0; clip_als=sa_line_inf->sprite_clip0[y]&0xffff; clip_ars=sa_line_inf->sprite_clip0[y]>>16; clip_bls=sa_line_inf->sprite_clip1[y]&0xffff; clip_brs=sa_line_inf->sprite_clip1[y]>>16; length=xsize; dsti = dsti0; dstp = dstp0; switch(skip_layer_num) { case 0: GET_PIXMAP_POINTER(0) case 1: GET_PIXMAP_POINTER(1) case 2: GET_PIXMAP_POINTER(2) case 3: GET_PIXMAP_POINTER(3) case 4: GET_PIXMAP_POINTER(4) } while (1) { pval=*dstp; if (pval!=0xff) { UINT8 sprite_pri; switch(skip_layer_num) { case 0: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[0]&pval)) { if(sprite_noalp_0) break; if(!dpix_sp[sprite_pri]) break; if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if (cx>=clip_al0 && cx<clip_ar0 && !(cx>=clip_bl0 && cx<clip_br0)) {tval=*tsrc0;if(tval&0xf0) if(dpix_lp[0][pval>>4](clut[*src0])) {*dsti=dval;break;}} case 1: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[1]&pval)) { if(sprite_noalp_1) break; if(!dpix_sp[sprite_pri]) { if(!(pval&0xf0)) break; else {dpix_1_sprite(*dsti);*dsti=dval;break;} } if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if (cx>=clip_al1 && cx<clip_ar1 && !(cx>=clip_bl1 && cx<clip_br1)) {tval=*tsrc1;if(tval&0xf0) if(dpix_lp[1][pval>>4](clut[*src1])) {*dsti=dval;break;}} case 2: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[2]&pval)) { if(sprite_noalp_2) break; if(!dpix_sp[sprite_pri]) { if(!(pval&0xf0)) break; else {dpix_1_sprite(*dsti);*dsti=dval;break;} } if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if (cx>=clip_al2 && cx<clip_ar2 && !(cx>=clip_bl2 && cx<clip_br2)) {tval=*tsrc2;if(tval&0xf0) if(dpix_lp[2][pval>>4](clut[*src2])) {*dsti=dval;break;}} case 3: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[3]&pval)) { if(sprite_noalp_3) break; if(!dpix_sp[sprite_pri]) { if(!(pval&0xf0)) break; else {dpix_1_sprite(*dsti);*dsti=dval;break;} } if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if (cx>=clip_al3 && cx<clip_ar3 && !(cx>=clip_bl3 && cx<clip_br3)) {tval=*tsrc3;if(tval&0xf0) if(dpix_lp[3][pval>>4](clut[*src3])) {*dsti=dval;break;}} case 4: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[4]&pval)) { if(sprite_noalp_4) break; if(!dpix_sp[sprite_pri]) { if(!(pval&0xf0)) break; else {dpix_1_sprite(*dsti);*dsti=dval;break;} } if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if (cx>=clip_al4 && cx<clip_ar4 && !(cx>=clip_bl4 && cx<clip_br4)) { tval=*tsrc4; if(tval&0xf0) { if(dpix_lp[4][pval>>4](clut[*src4])) { *dsti=dval; break; } } } case 5: if(cx>=clip_als && cx<clip_ars && !(cx>=clip_bls && cx<clip_brs) && (sprite_pri=sprite[5]&pval)) { if(sprite_noalp_5) break; if(!dpix_sp[sprite_pri]) { if(!(pval&0xf0)) break; else {dpix_1_sprite(*dsti);*dsti=dval;break;} } if(dpix_sp[sprite_pri][pval>>4](*dsti)) {*dsti=dval;break;} } if(!bgcolor) {if(!(pval&0xf0)) {*dsti=0;break;}} else dpix_bg(bgcolor); *dsti=dval; } } if(!(--length)) break; dsti++; dstp++; cx++; switch(skip_layer_num) { case 0: CULC_PIXMAP_POINTER(0) case 1: CULC_PIXMAP_POINTER(1) case 2: CULC_PIXMAP_POINTER(2) case 3: CULC_PIXMAP_POINTER(3) case 4: CULC_PIXMAP_POINTER(4) } } i++; if(draw_line_num[i]<0) break; if(draw_line_num[i]==y+1) { dsti0 += yadv; dstp0 += yadv; y++; continue; } else { int dy=(draw_line_num[i]-y)*yadv; dsti0 += dy; dstp0 += dy; y=draw_line_num[i]; } } } } #undef GET_PIXMAP_POINTER #undef CULC_PIXMAP_POINTER /******************************************************************************/ static void visible_tile_check(running_machine *machine, struct f3_playfield_line_inf *line_t, int line, UINT32 x_index_fx,UINT32 y_index, UINT32 *f3_pf_data_n) { UINT32 *pf_base; int i,trans_all,tile_index,tile_num; int alpha_type,alpha_mode; int opaque_all; int total_elements; if(!(alpha_mode=line_t->alpha_mode[line])) return; total_elements=machine->gfx[1]->total_elements; tile_index=x_index_fx>>16; tile_num=(((line_t->x_zoom[line]*320+(x_index_fx & 0xffff)+0xffff)>>16)+(tile_index%16)+15)/16; tile_index/=16; if (flipscreen) { pf_base=f3_pf_data_n+((31-(y_index/16))<<twidth_mask_bit); tile_index=(twidth_mask-tile_index)-tile_num+1; } else pf_base=f3_pf_data_n+((y_index/16)<<twidth_mask_bit); trans_all=1; opaque_all=1; alpha_type=0; for(i=0;i<tile_num;i++) { UINT32 tile=pf_base[(tile_index)&twidth_mask]; if(tile&0xffff) { trans_all=0; if(opaque_all) { if(tile_opaque_pf[(tile&0xffff)%total_elements]!=1) opaque_all=0; } if(alpha_mode==1) { if(!opaque_all) return; } else { if(alpha_type!=3) { if((tile>>(16+9))&1) alpha_type|=2; else alpha_type|=1; } else if(!opaque_all) break; } } else if(opaque_all) opaque_all=0; tile_index++; } if(trans_all) {line_t->alpha_mode[line]=0;return;} if(alpha_mode>1) { line_t->alpha_mode[line]|=alpha_type<<4; } if(opaque_all) line_t->alpha_mode[line]|=0x80; } /******************************************************************************/ static void calculate_clip(int y, UINT16 pri, UINT32* clip0, UINT32* clip1, int* line_enable) { const struct f3_spritealpha_line_inf *sa_line_t=&sa_line_inf[0]; switch (pri) { case 0x0100: /* Clip plane 1 enable */ { if (sa_line_t->clip0_l[y] > sa_line_t->clip0_r[y]) *line_enable=0; else *clip0=(sa_line_t->clip0_l[y]) | (sa_line_t->clip0_r[y]<<16); *clip1=0; } break; case 0x0110: /* Clip plane 1 enable, inverted */ { *clip1=(sa_line_t->clip0_l[y]) | (sa_line_t->clip0_r[y]<<16); *clip0=0x7fff0000; } break; case 0x0200: /* Clip plane 2 enable */ { if (sa_line_t->clip1_l[y] > sa_line_t->clip1_r[y]) *line_enable=0; else *clip0=(sa_line_t->clip1_l[y]) | (sa_line_t->clip1_r[y]<<16); *clip1=0; } break; case 0x0220: /* Clip plane 2 enable, inverted */ { *clip1=(sa_line_t->clip1_l[y]) | (sa_line_t->clip1_r[y]<<16); *clip0=0x7fff0000; } break; case 0x0300: /* Clip plane 1 & 2 enable */ { int clipl=0,clipr=0; if (sa_line_t->clip1_l[y] > sa_line_t->clip0_l[y]) clipl=sa_line_t->clip1_l[y]; else clipl=sa_line_t->clip0_l[y]; if (sa_line_t->clip1_r[y] < sa_line_t->clip0_r[y]) clipr=sa_line_t->clip1_r[y]; else clipr=sa_line_t->clip0_r[y]; if (clipl > clipr) *line_enable=0; else *clip0=(clipl) | (clipr<<16); *clip1=0; } break; case 0x0310: /* Clip plane 1 & 2 enable, plane 1 inverted */ { if (sa_line_t->clip1_l[y] > sa_line_t->clip1_r[y]) line_enable=0; else *clip0=(sa_line_t->clip1_l[y]) | (sa_line_t->clip1_r[y]<<16); *clip1=(sa_line_t->clip0_l[y]) | (sa_line_t->clip0_r[y]<<16); } break; case 0x0320: /* Clip plane 1 & 2 enable, plane 2 inverted */ { if (sa_line_t->clip0_l[y] > sa_line_t->clip0_r[y]) line_enable=0; else *clip0=(sa_line_t->clip0_l[y]) | (sa_line_t->clip0_r[y]<<16); *clip1=(sa_line_t->clip1_l[y]) | (sa_line_t->clip1_r[y]<<16); } break; case 0x0330: /* Clip plane 1 & 2 enable, both inverted */ { int clipl=0,clipr=0; if (sa_line_t->clip1_l[y] < sa_line_t->clip0_l[y]) clipl=sa_line_t->clip1_l[y]; else clipl=sa_line_t->clip0_l[y]; if (sa_line_t->clip1_r[y] > sa_line_t->clip0_r[y]) clipr=sa_line_t->clip1_r[y]; else clipr=sa_line_t->clip0_r[y]; if (clipl > clipr) *line_enable=0; else *clip1=(clipl) | (clipr<<16); *clip0=0x7fff0000; } break; default: // popmessage("Illegal clip mode"); break; } } static void get_spritealphaclip_info(void) { struct f3_spritealpha_line_inf *line_t=&sa_line_inf[0]; int y,y_end,y_inc; int spri_base,clip_base_low,clip_base_high,inc; UINT16 spri=0; UINT16 sprite_clip=0; UINT16 clip0_low=0, clip0_high=0, clip1_low=0; int alpha_level=0; UINT16 sprite_alpha=0; if (flipscreen) { spri_base=0x77fe; clip_base_low=0x51fe; clip_base_high=0x45fe; inc=-2; y=255; y_end=-1; y_inc=-1; } else { spri_base=0x7600; clip_base_low=0x5000; clip_base_high=0x4400; inc=2; y=0; y_end=256; y_inc=1; } while(y!=y_end) { /* The zoom, column and row values can latch according to control ram */ if (y&1) { if (f3_line_ram[0x080+(y>>1)]&1) clip0_low=(f3_line_ram[clip_base_low/4]>> 0)&0xffff; if (f3_line_ram[0x000+(y>>1)]&4) clip0_high=(f3_line_ram[clip_base_high/4]>> 0)&0xffff; if (f3_line_ram[0x080+(y>>1)]&2) clip1_low=(f3_line_ram[(clip_base_low+0x200)/4]>> 0)&0xffff; if (f3_line_ram[(0x0600/4)+(y>>1)]&0x8) spri=f3_line_ram[spri_base/4]&0xffff; if (f3_line_ram[(0x0600/4)+(y>>1)]&0x4) sprite_clip=f3_line_ram[(spri_base-0x200)/4]&0xffff; if (f3_line_ram[(0x0400/4)+(y>>1)]&0x1) sprite_alpha=f3_line_ram[(spri_base-0x1600)/4]&0xffff; if (f3_line_ram[(0x0400/4)+(y>>1)]&0x2) alpha_level=f3_line_ram[(spri_base-0x1400)/4]&0xffff; } else { if (f3_line_ram[0x080+(y>>1)]&0x10000) clip0_low=(f3_line_ram[clip_base_low/4]>>16)&0xffff; if (f3_line_ram[0x000+(y>>1)]&0x40000) clip0_high=(f3_line_ram[clip_base_high/4]>>16)&0xffff; if (f3_line_ram[0x080+(y>>1)]&0x20000) clip1_low=(f3_line_ram[(clip_base_low+0x200)/4]>>16)&0xffff; if (f3_line_ram[(0x0600/4)+(y>>1)]&0x80000) spri=f3_line_ram[spri_base/4]>>16; if (f3_line_ram[(0x0600/4)+(y>>1)]&0x40000) sprite_clip=f3_line_ram[(spri_base-0x200)/4]>>16; if (f3_line_ram[(0x0400/4)+(y>>1)]&0x10000) sprite_alpha=f3_line_ram[(spri_base-0x1600)/4]>>16; if (f3_line_ram[(0x0400/4)+(y>>1)]&0x20000) alpha_level=f3_line_ram[(spri_base-0x1400)/4]>>16; } line_t->alpha_level[y]=alpha_level; line_t->spri[y]=spri; line_t->sprite_alpha[y]=sprite_alpha; line_t->clip0_l[y]=((clip0_low&0xff)|((clip0_high&0x1000)>>4)) - 47; line_t->clip0_r[y]=(((clip0_low&0xff00)>>8)|((clip0_high&0x2000)>>5)) - 47; line_t->clip1_l[y]=((clip1_low&0xff)|((clip0_high&0x4000)>>6)) - 47; line_t->clip1_r[y]=(((clip1_low&0xff00)>>8)|((clip0_high&0x8000)>>7)) - 47; if (line_t->clip0_l[y]<0) line_t->clip0_l[y]=0; if (line_t->clip0_r[y]<0) line_t->clip0_r[y]=0; if (line_t->clip1_l[y]<0) line_t->clip1_l[y]=0; if (line_t->clip1_r[y]<0) line_t->clip1_r[y]=0; /* Evaluate sprite clipping */ if (sprite_clip&0x080) { line_t->sprite_clip0[y]=0x7fff7fff; line_t->sprite_clip1[y]=0; } else if (sprite_clip&0x33) { int line_enable=1; calculate_clip(y, ((sprite_clip&0x33)<<4), &line_t->sprite_clip0[y], &line_t->sprite_clip1[y], &line_enable); if (line_enable==0) line_t->sprite_clip0[y]=0x7fff7fff; } else { line_t->sprite_clip0[y]=0x7fff0000; line_t->sprite_clip1[y]=0; } spri_base+=inc; clip_base_low+=inc; clip_base_high+=inc; y +=y_inc; } } /* sx and sy are 16.16 fixed point numbers */ static void get_line_ram_info(running_machine *machine, tilemap *tmap, int sx, int sy, int pos, UINT32 *f3_pf_data_n) { struct f3_playfield_line_inf *line_t=&pf_line_inf[pos]; const mame_bitmap *srcbitmap; const mame_bitmap *flagsbitmap; int y,y_start,y_end,y_inc; int line_base,zoom_base,col_base,pri_base,inc; int line_enable; int colscroll=0,x_offset=0,line_zoom=0; UINT32 _y_zoom[256]; UINT16 pri=0; int bit_select0=0x10000<<pos; int bit_select1=1<<pos; int _colscroll[256]; UINT32 _x_offset[256]; int y_index_fx; sx+=((46<<16)); if (flipscreen) { line_base=0xa1fe + (pos*0x200); zoom_base=0x81fe;// + (pos*0x200); col_base =0x41fe + (pos*0x200); pri_base =0xb1fe + (pos*0x200); inc=-2; y_start=255; y_end=-1; y_inc=-1; if (f3_game_config->extend) sx=-sx+((188-512)<<16); else sx=-sx+(188<<16); /* Adjust for flipped scroll position */ y_index_fx=-sy-(256<<16); /* Adjust for flipped scroll position */ } else { line_base=0xa000 + (pos*0x200); zoom_base=0x8000;// + (pos*0x200); col_base =0x4000 + (pos*0x200); pri_base =0xb000 + (pos*0x200); inc=2; y_start=0; y_end=256; y_inc=1; y_index_fx=sy; } y=y_start; while(y!=y_end) { /* The zoom, column and row values can latch according to control ram */ if (y&1) { if (f3_line_ram[0x300+(y>>1)]&bit_select1) x_offset=(f3_line_ram[line_base/4]&0xffff)<<10; if (f3_line_ram[0x380+(y>>1)]&bit_select1) pri=f3_line_ram[pri_base/4]&0xffff; // Zoom for playfields 1 & 3 is interleaved, as is the latch select switch (pos) { case 0: if (f3_line_ram[0x200+(y>>1)]&bit_select1) line_zoom=f3_line_ram[(zoom_base+0x000)/4]&0xffff; break; case 1: if (f3_line_ram[0x200+(y>>1)]&0x2) line_zoom=((f3_line_ram[(zoom_base+0x200)/4]&0xffff)&0xff00) | (line_zoom&0x00ff); if (f3_line_ram[0x200+(y>>1)]&0x8) line_zoom=((f3_line_ram[(zoom_base+0x600)/4]&0xffff)&0x00ff) | (line_zoom&0xff00); break; case 2: if (f3_line_ram[0x200+(y>>1)]&bit_select1) line_zoom=f3_line_ram[(zoom_base+0x400)/4]&0xffff; break; case 3: if (f3_line_ram[0x200+(y>>1)]&0x8) line_zoom=((f3_line_ram[(zoom_base+0x600)/4]&0xffff)&0xff00) | (line_zoom&0x00ff); if (f3_line_ram[0x200+(y>>1)]&0x2) line_zoom=((f3_line_ram[(zoom_base+0x200)/4]&0xffff)&0x00ff) | (line_zoom&0xff00); break; default: break; } // Column scroll only affects playfields 2 & 3 if (pos>=2 && f3_line_ram[0x000+(y>>1)]&bit_select1) colscroll=(f3_line_ram[col_base/4]>> 0)&0x3ff; } else { if (f3_line_ram[0x300+(y>>1)]&bit_select0) x_offset=(f3_line_ram[line_base/4]&0xffff0000)>>6; if (f3_line_ram[0x380+(y>>1)]&bit_select0) pri=(f3_line_ram[pri_base/4]>>16)&0xffff; // Zoom for playfields 1 & 3 is interleaved, as is the latch select switch (pos) { case 0: if (f3_line_ram[0x200+(y>>1)]&bit_select0) line_zoom=f3_line_ram[(zoom_base+0x000)/4]>>16; break; case 1: if (f3_line_ram[0x200+(y>>1)]&0x20000) line_zoom=((f3_line_ram[(zoom_base+0x200)/4]>>16)&0xff00) | (line_zoom&0x00ff); if (f3_line_ram[0x200+(y>>1)]&0x80000) line_zoom=((f3_line_ram[(zoom_base+0x600)/4]>>16)&0x00ff) | (line_zoom&0xff00); break; case 2: if (f3_line_ram[0x200+(y>>1)]&bit_select0) line_zoom=f3_line_ram[(zoom_base+0x400)/4]>>16; break; case 3: if (f3_line_ram[0x200+(y>>1)]&0x80000) line_zoom=((f3_line_ram[(zoom_base+0x600)/4]>>16)&0xff00) | (line_zoom&0x00ff); if (f3_line_ram[0x200+(y>>1)]&0x20000) line_zoom=((f3_line_ram[(zoom_base+0x200)/4]>>16)&0x00ff) | (line_zoom&0xff00); break; default: break; } // Column scroll only affects playfields 2 & 3 if (pos>=2 && f3_line_ram[0x000+(y>>1)]&bit_select0) colscroll=(f3_line_ram[col_base/4]>>16)&0x3ff; } if (!pri || (!flipscreen && y<24) || (flipscreen && y>231) || (pri&0xc000)==0xc000 || !(pri&0x2000)/**/) line_enable=0; else if(pri&0x4000) //alpha1 line_enable=2; else if(pri&0x8000) //alpha2 line_enable=3; else line_enable=1; _colscroll[y]=colscroll; _x_offset[y]=(x_offset&0xffff0000) - (x_offset&0x0000ffff); _y_zoom[y] = (line_zoom&0xff) << 9; /* The football games use values in the range 0x200-0x3ff where the crowd should be drawn - !? Until this is understood we disable those lines (which would usually wrap and show the grass area. */ if (colscroll&0x200) pri|=0x0800; /* Evaluate clipping */ if (pri&0x0800) line_enable=0; else if (pri&0x0330) { //fast path todo - remove line enable calculate_clip(y, pri&0x0330, &line_t->clip0[y], &line_t->clip1[y], &line_enable); } else { /* No clipping */ line_t->clip0[y]=0x7fff0000; line_t->clip1[y]=0; } line_t->x_zoom[y]=0x10000 - (line_zoom&0xff00); line_t->alpha_mode[y]=line_enable; line_t->pri[y]=pri; zoom_base+=inc; line_base+=inc; col_base +=inc; pri_base +=inc; y +=y_inc; } /* set pixmap pointer */ srcbitmap = tilemap_get_pixmap(tmap); flagsbitmap = tilemap_get_flagsmap(tmap); y=y_start; while(y!=y_end) { UINT32 x_index_fx; UINT32 y_index; if(line_t->alpha_mode[y]!=0) { UINT16 *src_s; UINT8 *tsrc_s; x_index_fx = (sx+_x_offset[y]-(10*0x10000)+(10*line_t->x_zoom[y]))&((width_mask<<16)|0xffff); y_index = ((y_index_fx>>16)+_colscroll[y])&0x1ff; /* check tile status */ visible_tile_check(machine, line_t,y,x_index_fx,y_index,f3_pf_data_n); /* If clipping enabled for this line have to disable 'all opaque' optimisation */ if (line_t->clip0[y]!=0x7fff0000 || line_t->clip1[y]!=0) line_t->alpha_mode[y]&=~0x80; /* set pixmap index */ line_t->x_count[y]=x_index_fx & 0xffff; // Fractional part line_t->src_s[y]=src_s=BITMAP_ADDR16(srcbitmap, y_index, 0); line_t->src_e[y]=&src_s[width_mask+1]; line_t->src[y]=&src_s[x_index_fx>>16]; line_t->tsrc_s[y]=tsrc_s=BITMAP_ADDR8(flagsbitmap, y_index, 0); line_t->tsrc[y]=&tsrc_s[x_index_fx>>16]; } y_index_fx += _y_zoom[y]; y +=y_inc; } } static void get_vram_info(tilemap *vram_tilemap, tilemap *pixel_tilemap, int sx, int sy) { const struct f3_spritealpha_line_inf *sprite_alpha_line_t=&sa_line_inf[0]; struct f3_playfield_line_inf *line_t=&pf_line_inf[4]; const mame_bitmap *srcbitmap_pixel, *srcbitmap_vram; const mame_bitmap *flagsbitmap_pixel, *flagsbitmap_vram; int y,y_start,y_end,y_inc; int pri_base,inc; int line_enable; UINT16 pri=0; const int vram_width_mask=0x1ff; if (flipscreen) { pri_base =0x73fe; inc=-2; y_start=255; y_end=-1; y_inc=-1; } else { pri_base =0x7200; inc=2; y_start=0; y_end=256; y_inc=1; } y=y_start; while(y!=y_end) { /* The zoom, column and row values can latch according to control ram */ if (y&1) { if (f3_line_ram[(0x0600/4)+(y>>1)]&0x2) pri=(f3_line_ram[pri_base/4]&0xffff); } else { if (f3_line_ram[(0x0600/4)+(y>>1)]&0x20000) pri=(f3_line_ram[pri_base/4]&0xffff0000)>>16; } if (!pri || (!flipscreen && y<24) || (flipscreen && y>231) || (pri&0xc000)==0xc000 || !(pri&0x2000)/**/) line_enable=0; else if(pri&0x4000) //alpha1 line_enable=2; else if(pri&0x8000) //alpha2 line_enable=3; else line_enable=1; line_t->pri[y]=pri; /* Evaluate clipping */ if (pri&0x0800) line_enable=0; else if (pri&0x0330) { //fast path todo - remove line enable calculate_clip(y, pri&0x0330, &line_t->clip0[y], &line_t->clip1[y], &line_enable); } else { /* No clipping */ line_t->clip0[y]=0x7fff0000; line_t->clip1[y]=0; } line_t->x_zoom[y]=0x10000; line_t->alpha_mode[y]=line_enable; if (line_t->alpha_mode[y]>1) line_t->alpha_mode[y]|=0x10; pri_base +=inc; y +=y_inc; } sx&=0x1ff; /* set pixmap pointer */ srcbitmap_pixel = tilemap_get_pixmap(pixel_tilemap); flagsbitmap_pixel = tilemap_get_flagsmap(pixel_tilemap); srcbitmap_vram = tilemap_get_pixmap(vram_tilemap); flagsbitmap_vram = tilemap_get_flagsmap(vram_tilemap); y=y_start; while(y!=y_end) { if(line_t->alpha_mode[y]!=0) { UINT16 *src_s; UINT8 *tsrc_s; // These bits in control ram indicate whether the line is taken from // the VRAM tilemap layer or pixel layer. const int usePixelLayer=((sprite_alpha_line_t->sprite_alpha[y]&0xa000)==0xa000); /* set pixmap index */ line_t->x_count[y]=0xffff; if (usePixelLayer) line_t->src_s[y]=src_s=BITMAP_ADDR16(srcbitmap_pixel, sy&0xff, 0); else line_t->src_s[y]=src_s=BITMAP_ADDR16(srcbitmap_vram, sy&0x1ff, 0); line_t->src_e[y]=&src_s[vram_width_mask+1]; line_t->src[y]=&src_s[sx]; if (usePixelLayer) line_t->tsrc_s[y]=tsrc_s=BITMAP_ADDR8(flagsbitmap_pixel, sy&0xff, 0); else line_t->tsrc_s[y]=tsrc_s=BITMAP_ADDR8(flagsbitmap_vram, sy&0x1ff, 0); line_t->tsrc[y]=&tsrc_s[sx]; } sy++; y += y_inc; } } /******************************************************************************/ static void scanline_draw(running_machine *machine, mame_bitmap *bitmap, const rectangle *cliprect) { int i,j,y,ys,ye; int y_start,y_end,y_start_next,y_end_next; UINT8 draw_line[256]; INT16 draw_line_num[256]; UINT32 rot=0; if (flipscreen) { rot=ORIENTATION_FLIP_Y; ys=0; ye=232; } else { ys=24; ye=256; } y_start=ys; y_end=ye; memset(draw_line,0,256); while(1) { static int alpha_level_last=-1; int pos; int pri[5],alpha_mode[5],alpha_mode_flag[5],alpha_level; UINT16 sprite_alpha; UINT8 sprite_alpha_check; UINT8 sprite_alpha_all_2a; int spri; int alpha; int layer_tmp[5]; int count_skip_layer=0; int sprite[6]={0,0,0,0,0,0}; const struct f3_playfield_line_inf *line_t[5]; /* find same status of scanlines */ pri[0]=pf_line_inf[0].pri[y_start]; pri[1]=pf_line_inf[1].pri[y_start]; pri[2]=pf_line_inf[2].pri[y_start]; pri[3]=pf_line_inf[3].pri[y_start]; pri[4]=pf_line_inf[4].pri[y_start]; alpha_mode[0]=pf_line_inf[0].alpha_mode[y_start]; alpha_mode[1]=pf_line_inf[1].alpha_mode[y_start]; alpha_mode[2]=pf_line_inf[2].alpha_mode[y_start]; alpha_mode[3]=pf_line_inf[3].alpha_mode[y_start]; alpha_mode[4]=pf_line_inf[4].alpha_mode[y_start]; alpha_level=sa_line_inf[0].alpha_level[y_start]; spri=sa_line_inf[0].spri[y_start]; sprite_alpha=sa_line_inf[0].sprite_alpha[y_start]; draw_line[y_start]=1; draw_line_num[i=0]=y_start; y_start_next=-1; y_end_next=-1; for(y=y_start+1;y<y_end;y++) { if(!draw_line[y]) { if(pri[0]!=pf_line_inf[0].pri[y]) y_end_next=y+1; else if(pri[1]!=pf_line_inf[1].pri[y]) y_end_next=y+1; else if(pri[2]!=pf_line_inf[2].pri[y]) y_end_next=y+1; else if(pri[3]!=pf_line_inf[3].pri[y]) y_end_next=y+1; else if(pri[4]!=pf_line_inf[4].pri[y]) y_end_next=y+1; else if(alpha_mode[0]!=pf_line_inf[0].alpha_mode[y]) y_end_next=y+1; else if(alpha_mode[1]!=pf_line_inf[1].alpha_mode[y]) y_end_next=y+1; else if(alpha_mode[2]!=pf_line_inf[2].alpha_mode[y]) y_end_next=y+1; else if(alpha_mode[3]!=pf_line_inf[3].alpha_mode[y]) y_end_next=y+1; else if(alpha_mode[4]!=pf_line_inf[4].alpha_mode[y]) y_end_next=y+1; else if(alpha_level!=sa_line_inf[0].alpha_level[y]) y_end_next=y+1; else if(spri!=sa_line_inf[0].spri[y]) y_end_next=y+1; else if(sprite_alpha!=sa_line_inf[0].sprite_alpha[y]) y_end_next=y+1; else { draw_line[y]=1; draw_line_num[++i]=y; continue; } if(y_start_next<0) y_start_next=y; } } y_end=y_end_next; y_start=y_start_next; draw_line_num[++i]=-1; /* alpha blend */ alpha_mode_flag[0]=alpha_mode[0]&~3; alpha_mode_flag[1]=alpha_mode[1]&~3; alpha_mode_flag[2]=alpha_mode[2]&~3; alpha_mode_flag[3]=alpha_mode[3]&~3; alpha_mode_flag[4]=alpha_mode[4]&~3; alpha_mode[0]&=3; alpha_mode[1]&=3; alpha_mode[2]&=3; alpha_mode[3]&=3; alpha_mode[4]&=3; if( alpha_mode[0]>1 || alpha_mode[1]>1 || alpha_mode[2]>1 || alpha_mode[3]>1 || alpha_mode[4]>1 || (sprite_alpha&0xff) != 0xff ) { /* set alpha level */ if(alpha_level!=alpha_level_last) { int al_s,al_d; int a=alpha_level; int b=(a>>8)&0xf; int c=(a>>4)&0xf; int d=(a>>0)&0xf; a>>=12; /* b000 7000 */ al_s = ( (15-d)*256) / 8; al_d = ( (15-b)*256) / 8; if(al_s>255) al_s = 255; if(al_d>255) al_d = 255; f3_alpha_level_3as = al_s; f3_alpha_level_3ad = al_d; f3_alpha_level_2as = al_d; f3_alpha_level_2ad = al_s; al_s = ( (15-c)*256) / 8; al_d = ( (15-a)*256) / 8; if(al_s>255) al_s = 255; if(al_d>255) al_d = 255; f3_alpha_level_3bs = al_s; f3_alpha_level_3bd = al_d; f3_alpha_level_2bs = al_d; f3_alpha_level_2bd = al_s; f3_alpha_set_level(); alpha_level_last=alpha_level; } /* set sprite alpha mode */ sprite_alpha_check=0; sprite_alpha_all_2a=1; dpix_sp[1]=0; dpix_sp[2]=0; dpix_sp[4]=0; dpix_sp[8]=0; for(i=0;i<4;i++) /* i = sprite priority offset */ { UINT8 sprite_alpha_mode=(sprite_alpha>>(i*2))&3; UINT8 sftbit=1<<i; if(sprite_pri_usage&sftbit) { if(sprite_alpha_mode==1) { if(f3_alpha_level_2as==0 && f3_alpha_level_2ad==255) sprite_pri_usage&=~sftbit; // Disable sprite priority block else { dpix_sp[sftbit]=dpix_n[2]; sprite_alpha_check|=sftbit; } } else if(sprite_alpha_mode==2) { if(sprite_alpha&0xff00) { if(f3_alpha_level_3as==0 && f3_alpha_level_3ad==255) sprite_pri_usage&=~sftbit; else { dpix_sp[sftbit]=dpix_n[3]; sprite_alpha_check|=sftbit; sprite_alpha_all_2a=0; } } else { if(f3_alpha_level_3bs==0 && f3_alpha_level_3bd==255) sprite_pri_usage&=~sftbit; else { dpix_sp[sftbit]=dpix_n[5]; sprite_alpha_check|=sftbit; sprite_alpha_all_2a=0; } } } } } /* check alpha level */ for(i=0;i<5;i++) /* i = playfield num (pos) */ { int alpha_type = (alpha_mode_flag[i]>>4)&3; if(alpha_mode[i]==2) { if(alpha_type==1) { if (f3_alpha_level_2as==0 && f3_alpha_level_2ad==255) alpha_mode[i]=0; else if(f3_alpha_level_2as==255 && f3_alpha_level_2ad==0 ) alpha_mode[i]=1; } else if(alpha_type==2) { if (f3_alpha_level_2bs==0 && f3_alpha_level_2bd==255) alpha_mode[i]=0; else if(f3_alpha_level_2as==255 && f3_alpha_level_2ad==0 && f3_alpha_level_2bs==255 && f3_alpha_level_2bd==0 ) alpha_mode[i]=1; } else if(alpha_type==3) { if (f3_alpha_level_2as==0 && f3_alpha_level_2ad==255 && f3_alpha_level_2bs==0 && f3_alpha_level_2bd==255) alpha_mode[i]=0; else if(f3_alpha_level_2as==255 && f3_alpha_level_2ad==0 && f3_alpha_level_2bs==255 && f3_alpha_level_2bd==0 ) alpha_mode[i]=1; } } else if(alpha_mode[i]==3) { if(alpha_type==1) { if (f3_alpha_level_3as==0 && f3_alpha_level_3ad==255) alpha_mode[i]=0; else if(f3_alpha_level_3as==255 && f3_alpha_level_3ad==0 ) alpha_mode[i]=1; } else if(alpha_type==2) { if (f3_alpha_level_3bs==0 && f3_alpha_level_3bd==255) alpha_mode[i]=0; else if(f3_alpha_level_3as==255 && f3_alpha_level_3ad==0 && f3_alpha_level_3bs==255 && f3_alpha_level_3bd==0 ) alpha_mode[i]=1; } else if(alpha_type==3) { if (f3_alpha_level_3as==0 && f3_alpha_level_3ad==255 && f3_alpha_level_3bs==0 && f3_alpha_level_3bd==255) alpha_mode[i]=0; else if(f3_alpha_level_3as==255 && f3_alpha_level_3ad==0 && f3_alpha_level_3bs==255 && f3_alpha_level_3bd==0 ) alpha_mode[i]=1; } } } if ( (alpha_mode[0]==1 || alpha_mode[0]==2 || !alpha_mode[0]) && (alpha_mode[1]==1 || alpha_mode[1]==2 || !alpha_mode[1]) && (alpha_mode[2]==1 || alpha_mode[2]==2 || !alpha_mode[2]) && (alpha_mode[3]==1 || alpha_mode[3]==2 || !alpha_mode[3]) && (alpha_mode[4]==1 || alpha_mode[4]==2 || !alpha_mode[4]) && sprite_alpha_all_2a ) { int alpha_type = (alpha_mode_flag[0] | alpha_mode_flag[1] | alpha_mode_flag[2] | alpha_mode_flag[3])&0x30; if( (alpha_type==0x10 && f3_alpha_level_2as==255) || (alpha_type==0x20 && f3_alpha_level_2as==255 && f3_alpha_level_2bs==255) || (alpha_type==0x30 && f3_alpha_level_2as==255 && f3_alpha_level_2bs==255) ) { if(alpha_mode[0]>1) alpha_mode[0]=1; if(alpha_mode[1]>1) alpha_mode[1]=1; if(alpha_mode[2]>1) alpha_mode[2]=1; if(alpha_mode[3]>1) alpha_mode[3]=1; if(alpha_mode[4]>1) alpha_mode[4]=1; sprite_alpha_check=0; dpix_sp[1]=0; dpix_sp[2]=0; dpix_sp[4]=0; dpix_sp[8]=0; } } } else { sprite_alpha_check=0; dpix_sp[1]=0; dpix_sp[2]=0; dpix_sp[4]=0; dpix_sp[8]=0; } /* set scanline priority */ { int pri_max_opa=-1; for(i=0;i<5;i++) /* i = playfield num (pos) */ { int p0=pri[i]; int pri_sl1=p0&0x0f; layer_tmp[i]=i + (pri_sl1<<3); if(!alpha_mode[i]) { layer_tmp[i]|=0x80; count_skip_layer++; } else if(alpha_mode[i]==1 && (alpha_mode_flag[i]&0x80)) { if(layer_tmp[i]>pri_max_opa) pri_max_opa=layer_tmp[i]; } } if(pri_max_opa!=-1) { if(pri_max_opa>layer_tmp[0]) {layer_tmp[0]|=0x80;count_skip_layer++;} if(pri_max_opa>layer_tmp[1]) {layer_tmp[1]|=0x80;count_skip_layer++;} if(pri_max_opa>layer_tmp[2]) {layer_tmp[2]|=0x80;count_skip_layer++;} if(pri_max_opa>layer_tmp[3]) {layer_tmp[3]|=0x80;count_skip_layer++;} if(pri_max_opa>layer_tmp[4]) {layer_tmp[4]|=0x80;count_skip_layer++;} } } /* sort layer_tmp */ for(i=0;i<4;i++) { for(j=i+1;j<5;j++) { if(layer_tmp[i]<layer_tmp[j]) { int temp = layer_tmp[i]; layer_tmp[i] = layer_tmp[j]; layer_tmp[j] = temp; } } } /* check sprite & layer priority */ { int l0,l1,l2,l3,l4; int pri_sp[5]; l0=layer_tmp[0]>>3; l1=layer_tmp[1]>>3; l2=layer_tmp[2]>>3; l3=layer_tmp[3]>>3; l4=layer_tmp[4]>>3; pri_sp[0]=spri&0xf; pri_sp[1]=(spri>>4)&0xf; pri_sp[2]=(spri>>8)&0xf; pri_sp[3]=spri>>12; for(i=0;i<4;i++) /* i = sprite priority offset */ { int sp,sflg=1<<i; if(!(sprite_pri_usage & sflg)) continue; sp=pri_sp[i]; /* sprite priority==playfield priority BUBSYMPH (title) ---> sprite DARIUSG (ZONE V' BOSS) ---> playfield */ if (f3_game == BUBSYMPH ) sp++; //BUBSYMPH (title) if( sp>l0) sprite[0]|=sflg; else if(sp<=l0 && sp>l1) sprite[1]|=sflg; else if(sp<=l1 && sp>l2) sprite[2]|=sflg; else if(sp<=l2 && sp>l3) sprite[3]|=sflg; else if(sp<=l3 && sp>l4) sprite[4]|=sflg; else if(sp<=l4 ) sprite[5]|=sflg; } } /* draw scanlines */ alpha=0; for(i=count_skip_layer;i<5;i++) { pos=layer_tmp[i]&7; line_t[i]=&pf_line_inf[pos]; if(sprite[i]&sprite_alpha_check) alpha=1; else if(!alpha) sprite[i]|=0x100; if(alpha_mode[pos]>1) { int alpha_type=(((alpha_mode_flag[pos]>>4)&3)-1)*2; dpix_lp[i]=dpix_n[alpha_mode[pos]+alpha_type]; alpha=1; } else { if(alpha) dpix_lp[i]=dpix_n[1]; else dpix_lp[i]=dpix_n[0]; } } if(sprite[5]&sprite_alpha_check) alpha=1; else if(!alpha) sprite[5]|=0x100; draw_scanlines(machine, bitmap,320,draw_line_num,line_t,sprite,rot,count_skip_layer); if(y_start<0) break; } } /******************************************************************************/ #define PSET_T \ c = *source; \ if(c) \ { \ p=*pri; \ if(!p || p==0xff) \ { \ *dest = pal[c]; \ *pri = pri_dst; \ } \ } #define PSET_O \ p=*pri; \ if(!p || p==0xff) \ { \ *dest = pal[*source]; \ *pri = pri_dst; \ } #define NEXT_P \ source += dx; \ dest++; \ pri++; INLINE void f3_drawgfx( mame_bitmap *dest_bmp,const gfx_element *gfx, UINT32 code, UINT32 color, int flipx,int flipy, int sx,int sy, const rectangle *clip, UINT8 pri_dst) { rectangle myclip; pri_dst=1<<pri_dst; /* KW 991012 -- Added code to force clip to bitmap boundary */ if(clip) { myclip.min_x = clip->min_x; myclip.max_x = clip->max_x; myclip.min_y = clip->min_y; myclip.max_y = clip->max_y; if (myclip.min_x < 0) myclip.min_x = 0; if (myclip.max_x >= dest_bmp->width) myclip.max_x = dest_bmp->width-1; if (myclip.min_y < 0) myclip.min_y = 0; if (myclip.max_y >= dest_bmp->height) myclip.max_y = dest_bmp->height-1; clip=&myclip; } if( gfx ) { const pen_t *pal = &Machine->remapped_colortable[gfx->color_base + gfx->color_granularity * (color % gfx->total_colors)]; int source_base = (code % gfx->total_elements) * 16; { /* compute sprite increment per screen pixel */ int dx = 1; int dy = 1; int ex = sx+16; int ey = sy+16; int x_index_base; int y_index; if( flipx ) { x_index_base = 15; dx = -1; } else { x_index_base = 0; } if( flipy ) { y_index = 15; dy = -1; } else { y_index = 0; } if( clip ) { if( sx < clip->min_x) { /* clip left */ int pixels = clip->min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < clip->min_y ) { /* clip top */ int pixels = clip->min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > clip->max_x+1 ) { /* clip right */ int pixels = ex-clip->max_x-1; ex -= pixels; } if( ey > clip->max_y+1 ) { /* clip bottom */ int pixels = ey-clip->max_y-1; ey -= pixels; } } if( ex>sx && ey>sy) { /* skip if inner loop doesn't draw anything */ // if (dest_bmp->bpp == 32) { int y=ey-sy; int x=(ex-sx-1)|(tile_opaque_sp[code % gfx->total_elements]<<4); UINT8 *source0 = gfx->gfxdata + (source_base+y_index) * 16 + x_index_base; UINT32 *dest0 = BITMAP_ADDR32(dest_bmp, sy, sx); UINT8 *pri0 = BITMAP_ADDR8(pri_alp_bitmap, sy, sx); int yadv = dest_bmp->rowpixels; dy=dy*16; while(1) { UINT8 *source = source0; UINT32 *dest = dest0; UINT8 *pri = pri0; switch(x) { int c; UINT8 p; case 31: PSET_O NEXT_P case 30: PSET_O NEXT_P case 29: PSET_O NEXT_P case 28: PSET_O NEXT_P case 27: PSET_O NEXT_P case 26: PSET_O NEXT_P case 25: PSET_O NEXT_P case 24: PSET_O NEXT_P case 23: PSET_O NEXT_P case 22: PSET_O NEXT_P case 21: PSET_O NEXT_P case 20: PSET_O NEXT_P case 19: PSET_O NEXT_P case 18: PSET_O NEXT_P case 17: PSET_O NEXT_P case 16: PSET_O break; case 15: PSET_T NEXT_P case 14: PSET_T NEXT_P case 13: PSET_T NEXT_P case 12: PSET_T NEXT_P case 11: PSET_T NEXT_P case 10: PSET_T NEXT_P case 9: PSET_T NEXT_P case 8: PSET_T NEXT_P case 7: PSET_T NEXT_P case 6: PSET_T NEXT_P case 5: PSET_T NEXT_P case 4: PSET_T NEXT_P case 3: PSET_T NEXT_P case 2: PSET_T NEXT_P case 1: PSET_T NEXT_P case 0: PSET_T } if(!(--y)) break; source0 += dy; dest0+=yadv; pri0+=yadv; } } } } } } #undef PSET_T #undef PSET_O #undef NEXT_P INLINE void f3_drawgfxzoom(mame_bitmap *dest_bmp,const gfx_element *gfx, UINT32 code, UINT32 color, int flipx,int flipy, int sx,int sy, const rectangle *clip, int scalex, int scaley, UINT8 pri_dst) { rectangle myclip; pri_dst=1<<pri_dst; /* KW 991012 -- Added code to force clip to bitmap boundary */ if(clip) { myclip.min_x = clip->min_x; myclip.max_x = clip->max_x; myclip.min_y = clip->min_y; myclip.max_y = clip->max_y; if (myclip.min_x < 0) myclip.min_x = 0; if (myclip.max_x >= dest_bmp->width) myclip.max_x = dest_bmp->width-1; if (myclip.min_y < 0) myclip.min_y = 0; if (myclip.max_y >= dest_bmp->height) myclip.max_y = dest_bmp->height-1; clip=&myclip; } if( gfx ) { const pen_t *pal = &Machine->remapped_colortable[gfx->color_base + gfx->color_granularity * (color % gfx->total_colors)]; int source_base = (code % gfx->total_elements) * 16; { /* compute sprite increment per screen pixel */ int dx = (16<<16)/scalex; int dy = (16<<16)/scaley; int ex = sx+scalex; int ey = sy+scaley; int x_index_base; int y_index; if( flipx ) { x_index_base = (scalex-1)*dx; dx = -dx; } else { x_index_base = 0; } if( flipy ) { y_index = (scaley-1)*dy; dy = -dy; } else { y_index = 0; } if( clip ) { if( sx < clip->min_x) { /* clip left */ int pixels = clip->min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < clip->min_y ) { /* clip top */ int pixels = clip->min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > clip->max_x+1 ) { /* clip right */ int pixels = ex-clip->max_x-1; ex -= pixels; } if( ey > clip->max_y+1 ) { /* clip bottom */ int pixels = ey-clip->max_y-1; ey -= pixels; } } if( ex>sx ) { /* skip if inner loop doesn't draw anything */ // if (dest_bmp->bpp == 32) { int y; for( y=sy; y<ey; y++ ) { UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * 16; UINT32 *dest = BITMAP_ADDR32(dest_bmp, y, 0); UINT8 *pri = BITMAP_ADDR8(pri_alp_bitmap, y, 0); int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { int c = source[x_index>>16]; if(c) { UINT8 p=pri[x]; if (p == 0 || p == 0xff) { dest[x] = pal[c]; pri[x] = pri_dst; } } x_index += dx; } y_index += dy; } } } } } } #define CALC_ZOOM(p) { \ p##_addition = 0x100 - block_zoom_##p + p##_addition_left; \ p##_addition_left = p##_addition & 0xf; \ p##_addition = p##_addition >> 4; \ /*zoom##p = p##_addition << 12;*/ \ } static void get_sprite_info(running_machine *machine, const UINT32 *spriteram32_ptr) { const int min_x=machine->screen[0].visarea.min_x,max_x=machine->screen[0].visarea.max_x; const int min_y=machine->screen[0].visarea.min_y,max_y=machine->screen[0].visarea.max_y; int offs,spritecont,flipx,flipy,old_x,old_y,color,x,y; int sprite,global_x=0,global_y=0,subglobal_x=0,subglobal_y=0; int block_x=0, block_y=0; int last_color=0,last_x=0,last_y=0,block_zoom_x=0,block_zoom_y=0; int this_x,this_y; int y_addition=16, x_addition=16; int multi=0; int sprite_top; int x_addition_left = 8, y_addition_left = 8; struct tempsprite *sprite_ptr = spritelist; int total_sprites=0; color=0; flipx=flipy=0; old_y=old_x=0; y=x=0; sprite_top=0x1000; for (offs = 0; offs < sprite_top && (total_sprites < 0x400); offs += 4) { const int current_offs=offs; /* Offs can change during loop, current_offs cannot */ /* Check if the sprite list jump command bit is set */ if ((spriteram32_ptr[current_offs+3]>>16) & 0x8000) { UINT32 jump = (spriteram32_ptr[current_offs+3]>>16)&0x3ff; UINT32 new_offs=((offs&0x2000)|((jump<<4)/4)); if (new_offs==offs) break; offs=new_offs - 4; } /* Check if special command bit is set */ if (spriteram32_ptr[current_offs+1] & 0x8000) { UINT32 cntrl=(spriteram32_ptr[current_offs+2])&0xffff; flipscreen=cntrl&0x2000; /* cntrl&0x1000 = disabled? (From F2 driver, doesn't seem used anywhere) cntrl&0x0010 = ??? cntrl&0x0020 = ??? */ /* Sprite bank select */ if (cntrl&1) { offs=offs|0x2000; sprite_top=sprite_top|0x2000; } } /* Set global sprite scroll */ if (((spriteram32_ptr[current_offs+1]>>16) & 0xf000) == 0xa000) { global_x = (spriteram32_ptr[current_offs+1]>>16) & 0xfff; if (global_x >= 0x800) global_x -= 0x1000; global_y = spriteram32_ptr[current_offs+1] & 0xfff; if (global_y >= 0x800) global_y -= 0x1000; } /* And sub-global sprite scroll */ if (((spriteram32_ptr[current_offs+1]>>16) & 0xf000) == 0x5000) { subglobal_x = (spriteram32_ptr[current_offs+1]>>16) & 0xfff; if (subglobal_x >= 0x800) subglobal_x -= 0x1000; subglobal_y = spriteram32_ptr[current_offs+1] & 0xfff; if (subglobal_y >= 0x800) subglobal_y -= 0x1000; } if (((spriteram32_ptr[current_offs+1]>>16) & 0xf000) == 0xb000) { subglobal_x = (spriteram32_ptr[current_offs+1]>>16) & 0xfff; if (subglobal_x >= 0x800) subglobal_x -= 0x1000; subglobal_y = spriteram32_ptr[current_offs+1] & 0xfff; if (subglobal_y >= 0x800) subglobal_y -= 0x1000; global_y=subglobal_y; global_x=subglobal_x; } /* A real sprite to process! */ sprite = (spriteram32_ptr[current_offs]>>16) | ((spriteram32_ptr[current_offs+2]&1)<<16); spritecont = spriteram32_ptr[current_offs+2]>>24; /* These games either don't set the XY control bits properly (68020 bug?), or have some different mode from the others */ #ifdef DARIUSG_KLUDGE if (f3_game==DARIUSG || f3_game==GEKIRIDO || f3_game==CLEOPATR || f3_game==RECALH) multi=spritecont&0xf0; #endif /* Check if this sprite is part of a continued block */ if (multi) { /* Bit 0x4 is 'use previous colour' for this block part */ if (spritecont&0x4) color=last_color; else color=(spriteram32_ptr[current_offs+2]>>16)&0xff; #ifdef DARIUSG_KLUDGE if (f3_game==DARIUSG || f3_game==GEKIRIDO || f3_game==CLEOPATR || f3_game==RECALH) { /* Adjust X Position */ if ((spritecont & 0x40) == 0) { if (spritecont & 0x4) { x = block_x; } else { this_x = spriteram32_ptr[current_offs+1]>>16; if (this_x&0x800) this_x= 0 - (0x800 - (this_x&0x7ff)); else this_x&=0x7ff; if ((spriteram32_ptr[current_offs+1]>>16)&0x8000) { this_x+=0; } else if ((spriteram32_ptr[current_offs+1]>>16)&0x4000) { /* Ignore subglobal (but apply global) */ this_x+=global_x; } else { /* Apply both scroll offsets */ this_x+=global_x+subglobal_x; } x = block_x = this_x; } x_addition_left = 8; CALC_ZOOM(x) } else if ((spritecont & 0x80) != 0) { x = last_x+x_addition; CALC_ZOOM(x) } /* Adjust Y Position */ if ((spritecont & 0x10) == 0) { if (spritecont & 0x4) { y = block_y; } else { this_y = spriteram32_ptr[current_offs+1]&0xffff; if (this_y&0x800) this_y= 0 - (0x800 - (this_y&0x7ff)); else this_y&=0x7ff; if ((spriteram32_ptr[current_offs+1]>>16)&0x8000) { this_y+=0; } else if ((spriteram32_ptr[current_offs+1]>>16)&0x4000) { /* Ignore subglobal (but apply global) */ this_y+=global_y; } else { /* Apply both scroll offsets */ this_y+=global_y+subglobal_y; } y = block_y = this_y; } y_addition_left = 8; CALC_ZOOM(y) } else if ((spritecont & 0x20) != 0) { y = last_y+y_addition; CALC_ZOOM(y) } } else #endif { /* Adjust X Position */ if ((spritecont & 0x40) == 0) { x = block_x; x_addition_left = 8; CALC_ZOOM(x) } else if ((spritecont & 0x80) != 0) { x = last_x+x_addition; CALC_ZOOM(x) } /* Adjust Y Position */ if ((spritecont & 0x10) == 0) { y = block_y; y_addition_left = 8; CALC_ZOOM(y) } else if ((spritecont & 0x20) != 0) { y = last_y+y_addition; CALC_ZOOM(y) } /* Both zero = reread block latch? */ } } /* Else this sprite is the possible start of a block */ else { color = (spriteram32_ptr[current_offs+2]>>16)&0xff; last_color=color; /* Sprite positioning */ this_y = spriteram32_ptr[current_offs+1]&0xffff; this_x = spriteram32_ptr[current_offs+1]>>16; if (this_y&0x800) this_y= 0 - (0x800 - (this_y&0x7ff)); else this_y&=0x7ff; if (this_x&0x800) this_x= 0 - (0x800 - (this_x&0x7ff)); else this_x&=0x7ff; /* Ignore both scroll offsets for this block */ if ((spriteram32_ptr[current_offs+1]>>16)&0x8000) { this_x+=0; this_y+=0; } else if ((spriteram32_ptr[current_offs+1]>>16)&0x4000) { /* Ignore subglobal (but apply global) */ this_x+=global_x; this_y+=global_y; } else { /* Apply both scroll offsets */ this_x+=global_x+subglobal_x; this_y+=global_y+subglobal_y; } block_y = y = this_y; block_x = x = this_x; block_zoom_x=spriteram32_ptr[current_offs]; block_zoom_y=(block_zoom_x>>8)&0xff; block_zoom_x&=0xff; x_addition_left = 8; CALC_ZOOM(x) y_addition_left = 8; CALC_ZOOM(y) } /* These features are common to sprite and block parts */ flipx = spritecont&0x1; flipy = spritecont&0x2; multi = spritecont&0x8; last_x=x; last_y=y; if (!sprite) continue; if (!x_addition || !y_addition) continue; if (flipscreen) { int tx,ty; tx = 512-x_addition-x; ty = 256-y_addition-y; if (tx+x_addition<=min_x || tx>max_x || ty+y_addition<=min_y || ty>max_y) continue; sprite_ptr->x = tx; sprite_ptr->y = ty; sprite_ptr->flipx = !flipx; sprite_ptr->flipy = !flipy; } else { if (x+x_addition<=min_x || x>max_x || y+y_addition<=min_y || y>max_y) continue; sprite_ptr->x = x; sprite_ptr->y = y; sprite_ptr->flipx = flipx; sprite_ptr->flipy = flipy; } sprite_ptr->code = sprite; sprite_ptr->color = color; sprite_ptr->zoomx = x_addition; sprite_ptr->zoomy = y_addition; sprite_ptr->pri = (color & 0xc0) >> 6; sprite_ptr++; total_sprites++; } sprite_end = sprite_ptr; } #undef CALC_ZOOM static void draw_sprites(running_machine *machine, mame_bitmap *bitmap, const rectangle *cliprect) { const struct tempsprite *sprite_ptr; const gfx_element *sprite_gfx = machine->gfx[2]; sprite_ptr = sprite_end; sprite_pri_usage=0; while (sprite_ptr != spritelist) { int pri; sprite_ptr--; pri=sprite_ptr->pri; sprite_pri_usage|=1<<pri; if(sprite_ptr->zoomx==16 && sprite_ptr->zoomy==16) f3_drawgfx(bitmap,sprite_gfx, sprite_ptr->code, sprite_ptr->color, sprite_ptr->flipx,sprite_ptr->flipy, sprite_ptr->x,sprite_ptr->y, cliprect, pri); else f3_drawgfxzoom(bitmap,sprite_gfx, sprite_ptr->code, sprite_ptr->color, sprite_ptr->flipx,sprite_ptr->flipy, sprite_ptr->x,sprite_ptr->y, cliprect, sprite_ptr->zoomx,sprite_ptr->zoomy, pri); } } /******************************************************************************/ VIDEO_UPDATE( f3 ) { UINT32 sy_fix[5],sx_fix[5]; int tile; f3_skip_this_frame=0; tilemap_set_flip(ALL_TILEMAPS,flipscreen ? (TILEMAP_FLIPY | TILEMAP_FLIPX) : 0); /* Dynamically decode VRAM chars if dirty */ if (vram_changed) for (tile = 0;tile < 256;tile++) if (vram_dirty[tile]) { decodechar(machine->gfx[0],tile,(UINT8 *)f3_vram,machine->drv->gfxdecodeinfo[0].gfxlayout); tilemap_mark_all_tiles_dirty(vram_layer); // TODO //tilemap_mark_tile_dirty(vram_layer,tile); vram_dirty[tile]=0; } /* Decode chars & mark tilemap dirty */ if (pivot_changed) for (tile = 0;tile < 2048;tile++) if (pivot_dirty[tile]) { decodechar(machine->gfx[3],tile,(UINT8 *)f3_pivot_ram,machine->drv->gfxdecodeinfo[3].gfxlayout); tilemap_mark_tile_dirty(pixel_layer,tile); pivot_dirty[tile]=0; } pivot_changed=vram_changed=0; /* Setup scroll */ sy_fix[0]=((f3_control_0[2]&0xffff0000)>> 7) + (1<<16); sy_fix[1]=((f3_control_0[2]&0x0000ffff)<< 9) + (1<<16); sy_fix[2]=((f3_control_0[3]&0xffff0000)>> 7) + (1<<16); sy_fix[3]=((f3_control_0[3]&0x0000ffff)<< 9) + (1<<16); sx_fix[0]=((f3_control_0[0]&0xffc00000)>> 6) - (6<<16); sx_fix[1]=((f3_control_0[0]&0x0000ffc0)<<10) - (10<<16); sx_fix[2]=((f3_control_0[1]&0xffc00000)>> 6) - (14<<16); sx_fix[3]=((f3_control_0[1]&0x0000ffc0)<<10) - (18<<16); sx_fix[4]=-(f3_control_1[2]>>16)+41; sy_fix[4]=-(f3_control_1[2]&0x1ff); sx_fix[0]-=((f3_control_0[0]&0x003f0000)>> 6)+0x0400-0x10000; sx_fix[1]-=((f3_control_0[0]&0x0000003f)<<10)+0x0400-0x10000; sx_fix[2]-=((f3_control_0[1]&0x003f0000)>> 6)+0x0400-0x10000; sx_fix[3]-=((f3_control_0[1]&0x0000003f)<<10)+0x0400-0x10000; if (flipscreen) { sy_fix[0]= 0x3000000-sy_fix[0]; sy_fix[1]= 0x3000000-sy_fix[1]; sy_fix[2]= 0x3000000-sy_fix[2]; sy_fix[3]= 0x3000000-sy_fix[3]; sx_fix[0]=-0x1a00000-sx_fix[0]; sx_fix[1]=-0x1a00000-sx_fix[1]; sx_fix[2]=-0x1a00000-sx_fix[2]; sx_fix[3]=-0x1a00000-sx_fix[3]; sx_fix[4]=-sx_fix[4] + 75; sy_fix[4]=-sy_fix[4]; } fillbitmap(pri_alp_bitmap,0,cliprect); /* sprites */ if (sprite_lag==0) get_sprite_info(machine, spriteram32); /* Update sprite buffer */ draw_sprites(machine, bitmap,cliprect); /* Parse sprite, alpha & clipping parts of lineram */ get_spritealphaclip_info(); /* Parse playfield effects */ get_line_ram_info(machine, pf1_tilemap,sx_fix[0],sy_fix[0],0,f3_pf_data_1); get_line_ram_info(machine, pf2_tilemap,sx_fix[1],sy_fix[1],1,f3_pf_data_2); get_line_ram_info(machine, pf3_tilemap,sx_fix[2],sy_fix[2],2,f3_pf_data_3); get_line_ram_info(machine, pf4_tilemap,sx_fix[3],sy_fix[3],3,f3_pf_data_4); get_vram_info(vram_layer,pixel_layer,sx_fix[4],sy_fix[4]); /* Draw final framebuffer */ scanline_draw(machine, bitmap,cliprect); // print_debug_info(bitmap); return 0; }
87261.c
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * search.c: code for normal mode searching commands */ #include "vim.h" #ifdef FEAT_EVAL static void set_vv_searchforward(void); static int first_submatch(regmmatch_T *rp); #endif static int check_linecomment(char_u *line); #ifdef FEAT_FIND_ID static void show_pat_in_path(char_u *, int, int, int, FILE *, linenr_T *, long); #endif typedef struct searchstat { int cur; // current position of found words int cnt; // total count of found words int exact_match; // TRUE if matched exactly on specified position int incomplete; // 0: search was fully completed // 1: recomputing was timed out // 2: max count exceeded int last_maxcount; // the max count of the last search } searchstat_T; static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, int show_top_bot_msg, char_u *msgbuf, int recompute, int maxcount, long timeout); static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchstat_T *stat, int recompute, int maxcount, long timeout); #define SEARCH_STAT_DEF_TIMEOUT 40L #define SEARCH_STAT_DEF_MAX_COUNT 99 #define SEARCH_STAT_BUF_LEN 12 /* * This file contains various searching-related routines. These fall into * three groups: * 1. string searches (for /, ?, n, and N) * 2. character searches within a single line (for f, F, t, T, etc) * 3. "other" kinds of searches like the '%' command, and 'word' searches. */ /* * String searches * * The string search functions are divided into two levels: * lowest: searchit(); uses an pos_T for starting position and found match. * Highest: do_search(); uses curwin->w_cursor; calls searchit(). * * The last search pattern is remembered for repeating the same search. * This pattern is shared between the :g, :s, ? and / commands. * This is in search_regcomp(). * * The actual string matching is done using a heavily modified version of * Henry Spencer's regular expression library. See regexp.c. */ /* * Two search patterns are remembered: One for the :substitute command and * one for other searches. last_idx points to the one that was used the last * time. */ static spat_T spats[2] = { {NULL, TRUE, FALSE, {'/', 0, 0, 0L}}, // last used search pat {NULL, TRUE, FALSE, {'/', 0, 0, 0L}} // last used substitute pat }; static int last_idx = 0; // index in spats[] for RE_LAST static char_u lastc[2] = {NUL, NUL}; // last character searched for static int lastcdir = FORWARD; // last direction of character search static int last_t_cmd = TRUE; // last search t_cmd static char_u lastc_bytes[MB_MAXBYTES + 1]; static int lastc_bytelen = 1; // >1 for multi-byte char // copy of spats[], for keeping the search patterns while executing autocmds static spat_T saved_spats[2]; # ifdef FEAT_SEARCH_EXTRA static int saved_spats_last_idx = 0; static int saved_spats_no_hlsearch = 0; # endif static char_u *mr_pattern = NULL; // pattern used by search_regcomp() #ifdef FEAT_RIGHTLEFT static int mr_pattern_alloced = FALSE; // mr_pattern was allocated #endif #ifdef FEAT_FIND_ID /* * Type used by find_pattern_in_path() to remember which included files have * been searched already. */ typedef struct SearchedFile { FILE *fp; // File pointer char_u *name; // Full name of file linenr_T lnum; // Line we were up to in file int matched; // Found a match in this file } SearchedFile; #endif /* * translate search pattern for vim_regcomp() * * pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) * pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) * pat_save == RE_BOTH: save pat in both patterns (:global command) * pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL * pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL * pat_use == RE_LAST: use last used pattern if "pat" is NULL * options & SEARCH_HIS: put search string in history * options & SEARCH_KEEP: keep previous search pattern * * returns FAIL if failed, OK otherwise. */ int search_regcomp( char_u *pat, int pat_save, int pat_use, int options, regmmatch_T *regmatch) // return: pattern and ignore-case flag { int magic; int i; rc_did_emsg = FALSE; magic = p_magic; /* * If no pattern given, use a previously defined pattern. */ if (pat == NULL || *pat == NUL) { if (pat_use == RE_LAST) i = last_idx; else i = pat_use; if (spats[i].pat == NULL) // pattern was never defined { if (pat_use == RE_SUBST) emsg(_(e_nopresub)); else emsg(_(e_noprevre)); rc_did_emsg = TRUE; return FAIL; } pat = spats[i].pat; magic = spats[i].magic; no_smartcase = spats[i].no_scs; } else if (options & SEARCH_HIS) // put new pattern in history add_to_history(HIST_SEARCH, pat, TRUE, NUL); #ifdef FEAT_RIGHTLEFT if (mr_pattern_alloced) { vim_free(mr_pattern); mr_pattern_alloced = FALSE; } if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { char_u *rev_pattern; rev_pattern = reverse_text(pat); if (rev_pattern == NULL) mr_pattern = pat; // out of memory, keep normal pattern. else { mr_pattern = rev_pattern; mr_pattern_alloced = TRUE; } } else #endif mr_pattern = pat; /* * Save the currently used pattern in the appropriate place, * unless the pattern should not be remembered. */ if (!(options & SEARCH_KEEP) && !cmdmod.keeppatterns) { // search or global command if (pat_save == RE_SEARCH || pat_save == RE_BOTH) save_re_pat(RE_SEARCH, pat, magic); // substitute or global command if (pat_save == RE_SUBST || pat_save == RE_BOTH) save_re_pat(RE_SUBST, pat, magic); } regmatch->rmm_ic = ignorecase(pat); regmatch->rmm_maxcol = 0; regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0); if (regmatch->regprog == NULL) return FAIL; return OK; } /* * Get search pattern used by search_regcomp(). */ char_u * get_search_pat(void) { return mr_pattern; } #if defined(FEAT_RIGHTLEFT) || defined(PROTO) /* * Reverse text into allocated memory. * Returns the allocated string, NULL when out of memory. */ char_u * reverse_text(char_u *s) { unsigned len; unsigned s_i, rev_i; char_u *rev; /* * Reverse the pattern. */ len = (unsigned)STRLEN(s); rev = alloc(len + 1); if (rev != NULL) { rev_i = len; for (s_i = 0; s_i < len; ++s_i) { if (has_mbyte) { int mb_len; mb_len = (*mb_ptr2len)(s + s_i); rev_i -= mb_len; mch_memmove(rev + rev_i, s + s_i, mb_len); s_i += mb_len - 1; } else rev[--rev_i] = s[s_i]; } rev[len] = NUL; } return rev; } #endif void save_re_pat(int idx, char_u *pat, int magic) { if (spats[idx].pat != pat) { vim_free(spats[idx].pat); spats[idx].pat = vim_strsave(pat); spats[idx].magic = magic; spats[idx].no_scs = no_smartcase; last_idx = idx; #ifdef FEAT_SEARCH_EXTRA // If 'hlsearch' set and search pat changed: need redraw. if (p_hls) redraw_all_later(SOME_VALID); set_no_hlsearch(FALSE); #endif } } /* * Save the search patterns, so they can be restored later. * Used before/after executing autocommands and user functions. */ static int save_level = 0; void save_search_patterns(void) { if (save_level++ == 0) { saved_spats[0] = spats[0]; if (spats[0].pat != NULL) saved_spats[0].pat = vim_strsave(spats[0].pat); saved_spats[1] = spats[1]; if (spats[1].pat != NULL) saved_spats[1].pat = vim_strsave(spats[1].pat); #ifdef FEAT_SEARCH_EXTRA saved_spats_last_idx = last_idx; saved_spats_no_hlsearch = no_hlsearch; #endif } } void restore_search_patterns(void) { if (--save_level == 0) { vim_free(spats[0].pat); spats[0] = saved_spats[0]; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif vim_free(spats[1].pat); spats[1] = saved_spats[1]; #ifdef FEAT_SEARCH_EXTRA last_idx = saved_spats_last_idx; set_no_hlsearch(saved_spats_no_hlsearch); #endif } } #if defined(EXITFREE) || defined(PROTO) void free_search_patterns(void) { vim_free(spats[0].pat); vim_free(spats[1].pat); # ifdef FEAT_RIGHTLEFT if (mr_pattern_alloced) { vim_free(mr_pattern); mr_pattern_alloced = FALSE; mr_pattern = NULL; } # endif } #endif #ifdef FEAT_SEARCH_EXTRA // copy of spats[RE_SEARCH], for keeping the search patterns while incremental // searching static spat_T saved_last_search_spat; static int did_save_last_search_spat = 0; static int saved_last_idx = 0; static int saved_no_hlsearch = 0; /* * Save and restore the search pattern for incremental highlight search * feature. * * It's similar to but different from save_search_patterns() and * restore_search_patterns(), because the search pattern must be restored when * canceling incremental searching even if it's called inside user functions. */ void save_last_search_pattern(void) { if (++did_save_last_search_spat != 1) // nested call, nothing to do return; saved_last_search_spat = spats[RE_SEARCH]; if (spats[RE_SEARCH].pat != NULL) saved_last_search_spat.pat = vim_strsave(spats[RE_SEARCH].pat); saved_last_idx = last_idx; saved_no_hlsearch = no_hlsearch; } void restore_last_search_pattern(void) { if (--did_save_last_search_spat > 0) // nested call, nothing to do return; if (did_save_last_search_spat != 0) { iemsg("restore_last_search_pattern() called more often than save_last_search_pattern()"); return; } vim_free(spats[RE_SEARCH].pat); spats[RE_SEARCH] = saved_last_search_spat; saved_last_search_spat.pat = NULL; # if defined(FEAT_EVAL) set_vv_searchforward(); # endif last_idx = saved_last_idx; set_no_hlsearch(saved_no_hlsearch); } char_u * last_search_pattern(void) { return spats[RE_SEARCH].pat; } #endif /* * Return TRUE when case should be ignored for search pattern "pat". * Uses the 'ignorecase' and 'smartcase' options. */ int ignorecase(char_u *pat) { return ignorecase_opt(pat, p_ic, p_scs); } /* * As ignorecase() put pass the "ic" and "scs" flags. */ int ignorecase_opt(char_u *pat, int ic_in, int scs) { int ic = ic_in; if (ic && !no_smartcase && scs && !(ctrl_x_mode_not_default() && curbuf->b_p_inf)) ic = !pat_has_uppercase(pat); no_smartcase = FALSE; return ic; } /* * Return TRUE if pattern "pat" has an uppercase character. */ int pat_has_uppercase(char_u *pat) { char_u *p = pat; while (*p != NUL) { int l; if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) { if (enc_utf8 && utf_isupper(utf_ptr2char(p))) return TRUE; p += l; } else if (*p == '\\') { if (p[1] == '_' && p[2] != NUL) // skip "\_X" p += 3; else if (p[1] == '%' && p[2] != NUL) // skip "\%X" p += 3; else if (p[1] != NUL) // skip "\X" p += 2; else p += 1; } else if (MB_ISUPPER(*p)) return TRUE; else ++p; } return FALSE; } #if defined(FEAT_EVAL) || defined(PROTO) char_u * last_csearch(void) { return lastc_bytes; } int last_csearch_forward(void) { return lastcdir == FORWARD; } int last_csearch_until(void) { return last_t_cmd == TRUE; } void set_last_csearch(int c, char_u *s UNUSED, int len UNUSED) { *lastc = c; lastc_bytelen = len; if (len) memcpy(lastc_bytes, s, len); else CLEAR_FIELD(lastc_bytes); } #endif void set_csearch_direction(int cdir) { lastcdir = cdir; } void set_csearch_until(int t_cmd) { last_t_cmd = t_cmd; } char_u * last_search_pat(void) { return spats[last_idx].pat; } /* * Reset search direction to forward. For "gd" and "gD" commands. */ void reset_search_dir(void) { spats[0].off.dir = '/'; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif } #if defined(FEAT_EVAL) || defined(FEAT_VIMINFO) /* * Set the last search pattern. For ":let @/ =" and viminfo. * Also set the saved search pattern, so that this works in an autocommand. */ void set_last_search_pat( char_u *s, int idx, int magic, int setlast) { vim_free(spats[idx].pat); // An empty string means that nothing should be matched. if (*s == NUL) spats[idx].pat = NULL; else spats[idx].pat = vim_strsave(s); spats[idx].magic = magic; spats[idx].no_scs = FALSE; spats[idx].off.dir = '/'; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif spats[idx].off.line = FALSE; spats[idx].off.end = FALSE; spats[idx].off.off = 0; if (setlast) last_idx = idx; if (save_level) { vim_free(saved_spats[idx].pat); saved_spats[idx] = spats[0]; if (spats[idx].pat == NULL) saved_spats[idx].pat = NULL; else saved_spats[idx].pat = vim_strsave(spats[idx].pat); # ifdef FEAT_SEARCH_EXTRA saved_spats_last_idx = last_idx; # endif } # ifdef FEAT_SEARCH_EXTRA // If 'hlsearch' set and search pat changed: need redraw. if (p_hls && idx == last_idx && !no_hlsearch) redraw_all_later(SOME_VALID); # endif } #endif #ifdef FEAT_SEARCH_EXTRA /* * Get a regexp program for the last used search pattern. * This is used for highlighting all matches in a window. * Values returned in regmatch->regprog and regmatch->rmm_ic. */ void last_pat_prog(regmmatch_T *regmatch) { if (spats[last_idx].pat == NULL) { regmatch->regprog = NULL; return; } ++emsg_off; // So it doesn't beep if bad expr (void)search_regcomp((char_u *)"", 0, last_idx, SEARCH_KEEP, regmatch); --emsg_off; } #endif /* * Lowest level search function. * Search for 'count'th occurrence of pattern "pat" in direction "dir". * Start at position "pos" and return the found position in "pos". * * if (options & SEARCH_MSG) == 0 don't give any messages * if (options & SEARCH_MSG) == SEARCH_NFMSG don't give 'notfound' messages * if (options & SEARCH_MSG) == SEARCH_MSG give all messages * if (options & SEARCH_HIS) put search pattern in history * if (options & SEARCH_END) return position at end of match * if (options & SEARCH_START) accept match at pos itself * if (options & SEARCH_KEEP) keep previous search pattern * if (options & SEARCH_FOLD) match only once in a closed fold * if (options & SEARCH_PEEK) check for typed char, cancel search * if (options & SEARCH_COL) start at pos->col instead of zero * * Return FAIL (zero) for failure, non-zero for success. * When FEAT_EVAL is defined, returns the index of the first matching * subpattern plus one; one if there was none. */ int searchit( win_T *win, // window to search in; can be NULL for a // buffer without a window! buf_T *buf, pos_T *pos, pos_T *end_pos, // set to end of the match, unless NULL int dir, char_u *pat, long count, int options, int pat_use, // which pattern to use when "pat" is empty searchit_arg_T *extra_arg) // optional extra arguments, can be NULL { int found; linenr_T lnum; // no init to shut up Apollo cc colnr_T col; regmmatch_T regmatch; char_u *ptr; colnr_T matchcol; lpos_T endpos; lpos_T matchpos; int loop; pos_T start_pos; int at_first_line; int extra_col; int start_char_len; int match_ok; long nmatched; int submatch = 0; int first_match = TRUE; int called_emsg_before = called_emsg; #ifdef FEAT_SEARCH_EXTRA int break_loop = FALSE; #endif linenr_T stop_lnum = 0; // stop after this line number when != 0 #ifdef FEAT_RELTIME proftime_T *tm = NULL; // timeout limit or NULL int *timed_out = NULL; // set when timed out or NULL #endif if (extra_arg != NULL) { stop_lnum = extra_arg->sa_stop_lnum; #ifdef FEAT_RELTIME tm = extra_arg->sa_tm; timed_out = &extra_arg->sa_timed_out; #endif } if (search_regcomp(pat, RE_SEARCH, pat_use, (options & (SEARCH_HIS + SEARCH_KEEP)), &regmatch) == FAIL) { if ((options & SEARCH_MSG) && !rc_did_emsg) semsg(_("E383: Invalid search string: %s"), mr_pattern); return FAIL; } /* * find the string */ do // loop for count { // When not accepting a match at the start position set "extra_col" to // a non-zero value. Don't do that when starting at MAXCOL, since // MAXCOL + 1 is zero. if (pos->col == MAXCOL) start_char_len = 0; // Watch out for the "col" being MAXCOL - 2, used in a closed fold. else if (has_mbyte && pos->lnum >= 1 && pos->lnum <= buf->b_ml.ml_line_count && pos->col < MAXCOL - 2) { ptr = ml_get_buf(buf, pos->lnum, FALSE); if ((int)STRLEN(ptr) <= pos->col) start_char_len = 1; else start_char_len = (*mb_ptr2len)(ptr + pos->col); } else start_char_len = 1; if (dir == FORWARD) { if (options & SEARCH_START) extra_col = 0; else extra_col = start_char_len; } else { if (options & SEARCH_START) extra_col = start_char_len; else extra_col = 0; } start_pos = *pos; // remember start pos for detecting no match found = 0; // default: not found at_first_line = TRUE; // default: start in first line if (pos->lnum == 0) // correct lnum for when starting in line 0 { pos->lnum = 1; pos->col = 0; at_first_line = FALSE; // not in first line now } /* * Start searching in current line, unless searching backwards and * we're in column 0. * If we are searching backwards, in column 0, and not including the * current position, gain some efficiency by skipping back a line. * Otherwise begin the search in the current line. */ if (dir == BACKWARD && start_pos.col == 0 && (options & SEARCH_START) == 0) { lnum = pos->lnum - 1; at_first_line = FALSE; } else lnum = pos->lnum; for (loop = 0; loop <= 1; ++loop) // loop twice if 'wrapscan' set { for ( ; lnum > 0 && lnum <= buf->b_ml.ml_line_count; lnum += dir, at_first_line = FALSE) { // Stop after checking "stop_lnum", if it's set. if (stop_lnum != 0 && (dir == FORWARD ? lnum > stop_lnum : lnum < stop_lnum)) break; #ifdef FEAT_RELTIME // Stop after passing the "tm" time limit. if (tm != NULL && profile_passed_limit(tm)) break; #endif /* * Look for a match somewhere in line "lnum". */ col = at_first_line && (options & SEARCH_COL) ? pos->col : (colnr_T)0; nmatched = vim_regexec_multi(&regmatch, win, buf, lnum, col, #ifdef FEAT_RELTIME tm, timed_out #else NULL, NULL #endif ); // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) break; // Abort searching on an error (e.g., out of stack). if (called_emsg > called_emsg_before #ifdef FEAT_RELTIME || (timed_out != NULL && *timed_out) #endif ) break; if (nmatched > 0) { // match may actually be in another line when using \zs matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; #ifdef FEAT_EVAL submatch = first_submatch(&regmatch); #endif // "lnum" may be past end of buffer for "\n\zs". if (lnum + matchpos.lnum > buf->b_ml.ml_line_count) ptr = (char_u *)""; else ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); /* * Forward search in the first line: match should be after * the start position. If not, continue at the end of the * match (this is vi compatible) or on the next char. */ if (dir == FORWARD && at_first_line) { match_ok = TRUE; /* * When the match starts in a next line it's certainly * past the start position. * When match lands on a NUL the cursor will be put * one back afterwards, compare with that position, * otherwise "/$" will get stuck on end of line. */ while (matchpos.lnum == 0 && ((options & SEARCH_END) && first_match ? (nmatched == 1 && (int)endpos.col - 1 < (int)start_pos.col + extra_col) : ((int)matchpos.col - (ptr[matchpos.col] == NUL) < (int)start_pos.col + extra_col))) { /* * If vi-compatible searching, continue at the end * of the match, otherwise continue one position * forward. */ if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) { if (nmatched > 1) { // end is in next line, thus no match in // this line match_ok = FALSE; break; } matchcol = endpos.col; // for empty match: advance one char if (matchcol == matchpos.col && ptr[matchcol] != NUL) { if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else ++matchcol; } } else { matchcol = matchpos.col; if (ptr[matchcol] != NUL) { if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else ++matchcol; } } if (matchcol == 0 && (options & SEARCH_START)) break; if (ptr[matchcol] == NUL || (nmatched = vim_regexec_multi(&regmatch, win, buf, lnum + matchpos.lnum, matchcol, #ifdef FEAT_RELTIME tm, timed_out #else NULL, NULL #endif )) == 0) { match_ok = FALSE; break; } // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) break; matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; # ifdef FEAT_EVAL submatch = first_submatch(&regmatch); # endif // Need to get the line pointer again, a // multi-line search may have made it invalid. ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); } if (!match_ok) continue; } if (dir == BACKWARD) { /* * Now, if there are multiple matches on this line, * we have to get the last one. Or the last one before * the cursor, if we're on that line. * When putting the new cursor at the end, compare * relative to the end of the match. */ match_ok = FALSE; for (;;) { // Remember a position that is before the start // position, we use it if it's the last match in // the line. Always accept a position after // wrapping around. if (loop || ((options & SEARCH_END) ? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && (int)regmatch.endpos[0].col - 1 < (int)start_pos.col + extra_col)) : (lnum + regmatch.startpos[0].lnum < start_pos.lnum || (lnum + regmatch.startpos[0].lnum == start_pos.lnum && (int)regmatch.startpos[0].col < (int)start_pos.col + extra_col)))) { match_ok = TRUE; matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; # ifdef FEAT_EVAL submatch = first_submatch(&regmatch); # endif } else break; /* * We found a valid match, now check if there is * another one after it. * If vi-compatible searching, continue at the end * of the match, otherwise continue one position * forward. */ if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) { if (nmatched > 1) break; matchcol = endpos.col; // for empty match: advance one char if (matchcol == matchpos.col && ptr[matchcol] != NUL) { if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else ++matchcol; } } else { // Stop when the match is in a next line. if (matchpos.lnum > 0) break; matchcol = matchpos.col; if (ptr[matchcol] != NUL) { if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else ++matchcol; } } if (ptr[matchcol] == NUL || (nmatched = vim_regexec_multi(&regmatch, win, buf, lnum + matchpos.lnum, matchcol, #ifdef FEAT_RELTIME tm, timed_out #else NULL, NULL #endif )) == 0) { #ifdef FEAT_RELTIME // If the search timed out, we did find a match // but it might be the wrong one, so that's not // OK. if (timed_out != NULL && *timed_out) match_ok = FALSE; #endif break; } // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) break; // Need to get the line pointer again, a // multi-line search may have made it invalid. ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); } /* * If there is only a match after the cursor, skip * this match. */ if (!match_ok) continue; } // With the SEARCH_END option move to the last character // of the match. Don't do it for an empty match, end // should be same as start then. if ((options & SEARCH_END) && !(options & SEARCH_NOOF) && !(matchpos.lnum == endpos.lnum && matchpos.col == endpos.col)) { // For a match in the first column, set the position // on the NUL in the previous line. pos->lnum = lnum + endpos.lnum; pos->col = endpos.col; if (endpos.col == 0) { if (pos->lnum > 1) // just in case { --pos->lnum; pos->col = (colnr_T)STRLEN(ml_get_buf(buf, pos->lnum, FALSE)); } } else { --pos->col; if (has_mbyte && pos->lnum <= buf->b_ml.ml_line_count) { ptr = ml_get_buf(buf, pos->lnum, FALSE); pos->col -= (*mb_head_off)(ptr, ptr + pos->col); } } if (end_pos != NULL) { end_pos->lnum = lnum + matchpos.lnum; end_pos->col = matchpos.col; } } else { pos->lnum = lnum + matchpos.lnum; pos->col = matchpos.col; if (end_pos != NULL) { end_pos->lnum = lnum + endpos.lnum; end_pos->col = endpos.col; } } pos->coladd = 0; if (end_pos != NULL) end_pos->coladd = 0; found = 1; first_match = FALSE; // Set variables used for 'incsearch' highlighting. search_match_lines = endpos.lnum - matchpos.lnum; search_match_endcol = endpos.col; break; } line_breakcheck(); // stop if ctrl-C typed if (got_int) break; #ifdef FEAT_SEARCH_EXTRA // Cancel searching if a character was typed. Used for // 'incsearch'. Don't check too often, that would slowdown // searching too much. if ((options & SEARCH_PEEK) && ((lnum - pos->lnum) & 0x3f) == 0 && char_avail()) { break_loop = TRUE; break; } #endif if (loop && lnum == start_pos.lnum) break; // if second loop, stop where started } at_first_line = FALSE; // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) break; /* * Stop the search if wrapscan isn't set, "stop_lnum" is * specified, after an interrupt, after a match and after looping * twice. */ if (!p_ws || stop_lnum != 0 || got_int || called_emsg > called_emsg_before #ifdef FEAT_RELTIME || (timed_out != NULL && *timed_out) #endif #ifdef FEAT_SEARCH_EXTRA || break_loop #endif || found || loop) break; /* * If 'wrapscan' is set we continue at the other end of the file. * If 'shortmess' does not contain 's', we give a message. * This message is also remembered in keep_msg for when the screen * is redrawn. The keep_msg is cleared whenever another message is * written. */ if (dir == BACKWARD) // start second loop at the other end lnum = buf->b_ml.ml_line_count; else lnum = 1; if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG)) give_warning((char_u *)_(dir == BACKWARD ? top_bot_msg : bot_top_msg), TRUE); if (extra_arg != NULL) extra_arg->sa_wrapped = TRUE; } if (got_int || called_emsg > called_emsg_before #ifdef FEAT_RELTIME || (timed_out != NULL && *timed_out) #endif #ifdef FEAT_SEARCH_EXTRA || break_loop #endif ) break; } while (--count > 0 && found); // stop after count matches or no match vim_regfree(regmatch.regprog); if (!found) // did not find it { if (got_int) emsg(_(e_interr)); else if ((options & SEARCH_MSG) == SEARCH_MSG) { if (p_ws) semsg(_(e_patnotf2), mr_pattern); else if (lnum == 0) semsg(_("E384: search hit TOP without match for: %s"), mr_pattern); else semsg(_("E385: search hit BOTTOM without match for: %s"), mr_pattern); } return FAIL; } // A pattern like "\n\zs" may go past the last line. if (pos->lnum > buf->b_ml.ml_line_count) { pos->lnum = buf->b_ml.ml_line_count; pos->col = (int)STRLEN(ml_get_buf(buf, pos->lnum, FALSE)); if (pos->col > 0) --pos->col; } return submatch + 1; } #ifdef FEAT_EVAL void set_search_direction(int cdir) { spats[0].off.dir = cdir; } static void set_vv_searchforward(void) { set_vim_var_nr(VV_SEARCHFORWARD, (long)(spats[0].off.dir == '/')); } /* * Return the number of the first subpat that matched. * Return zero if none of them matched. */ static int first_submatch(regmmatch_T *rp) { int submatch; for (submatch = 1; ; ++submatch) { if (rp->startpos[submatch].lnum >= 0) break; if (submatch == 9) { submatch = 0; break; } } return submatch; } #endif /* * Highest level string search function. * Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' * If 'dirc' is 0: use previous dir. * If 'pat' is NULL or empty : use previous string. * If 'options & SEARCH_REV' : go in reverse of previous dir. * If 'options & SEARCH_ECHO': echo the search command and handle options * If 'options & SEARCH_MSG' : may give error message * If 'options & SEARCH_OPT' : interpret optional flags * If 'options & SEARCH_HIS' : put search pattern in history * If 'options & SEARCH_NOOF': don't add offset to position * If 'options & SEARCH_MARK': set previous context mark * If 'options & SEARCH_KEEP': keep previous search pattern * If 'options & SEARCH_START': accept match at curpos itself * If 'options & SEARCH_PEEK': check for typed char, cancel search * * Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this * makes the movement linewise without moving the match position. * * Return 0 for failure, 1 for found, 2 for found and line offset added. */ int do_search( oparg_T *oap, // can be NULL int dirc, // '/' or '?' int search_delim, // the delimiter for the search, e.g. '%' in s%regex%replacement% char_u *pat, long count, int options, searchit_arg_T *sia) // optional arguments or NULL { pos_T pos; // position of the last match char_u *searchstr; soffset_T old_off; int retval; // Return value char_u *p; long c; char_u *dircp; char_u *strcopy = NULL; char_u *ps; char_u *msgbuf = NULL; size_t len; int has_offset = FALSE; /* * A line offset is not remembered, this is vi compatible. */ if (spats[0].off.line && vim_strchr(p_cpo, CPO_LINEOFF) != NULL) { spats[0].off.line = FALSE; spats[0].off.off = 0; } /* * Save the values for when (options & SEARCH_KEEP) is used. * (there is no "if ()" around this because gcc wants them initialized) */ old_off = spats[0].off; pos = curwin->w_cursor; // start searching at the cursor position /* * Find out the direction of the search. */ if (dirc == 0) dirc = spats[0].off.dir; else { spats[0].off.dir = dirc; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif } if (options & SEARCH_REV) { #ifdef MSWIN // There is a bug in the Visual C++ 2.2 compiler which means that // dirc always ends up being '/' dirc = (dirc == '/') ? '?' : '/'; #else if (dirc == '/') dirc = '?'; else dirc = '/'; #endif } #ifdef FEAT_FOLDING // If the cursor is in a closed fold, don't find another match in the same // fold. if (dirc == '/') { if (hasFolding(pos.lnum, NULL, &pos.lnum)) pos.col = MAXCOL - 2; // avoid overflow when adding 1 } else { if (hasFolding(pos.lnum, &pos.lnum, NULL)) pos.col = 0; } #endif #ifdef FEAT_SEARCH_EXTRA /* * Turn 'hlsearch' highlighting back on. */ if (no_hlsearch && !(options & SEARCH_KEEP)) { redraw_all_later(SOME_VALID); set_no_hlsearch(FALSE); } #endif /* * Repeat the search when pattern followed by ';', e.g. "/foo/;?bar". */ for (;;) { int show_top_bot_msg = FALSE; searchstr = pat; dircp = NULL; // use previous pattern if (pat == NULL || *pat == NUL || *pat == search_delim) { if (spats[RE_SEARCH].pat == NULL) // no previous pattern { searchstr = spats[RE_SUBST].pat; if (searchstr == NULL) { emsg(_(e_noprevre)); retval = 0; goto end_do_search; } } else { // make search_regcomp() use spats[RE_SEARCH].pat searchstr = (char_u *)""; } } if (pat != NULL && *pat != NUL) // look for (new) offset { /* * Find end of regular expression. * If there is a matching '/' or '?', toss it. */ ps = strcopy; p = skip_regexp_ex(pat, search_delim, (int)p_magic, &strcopy, NULL); if (strcopy != ps) { // made a copy of "pat" to change "\?" to "?" searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy)); pat = strcopy; searchstr = strcopy; } if (*p == search_delim) { dircp = p; // remember where we put the NUL *p++ = NUL; } spats[0].off.line = FALSE; spats[0].off.end = FALSE; spats[0].off.off = 0; /* * Check for a line offset or a character offset. * For get_address (echo off) we don't check for a character * offset, because it is meaningless and the 's' could be a * substitute command. */ if (*p == '+' || *p == '-' || VIM_ISDIGIT(*p)) spats[0].off.line = TRUE; else if ((options & SEARCH_OPT) && (*p == 'e' || *p == 's' || *p == 'b')) { if (*p == 'e') // end spats[0].off.end = SEARCH_END; ++p; } if (VIM_ISDIGIT(*p) || *p == '+' || *p == '-') // got an offset { // 'nr' or '+nr' or '-nr' if (VIM_ISDIGIT(*p) || VIM_ISDIGIT(*(p + 1))) spats[0].off.off = atol((char *)p); else if (*p == '-') // single '-' spats[0].off.off = -1; else // single '+' spats[0].off.off = 1; ++p; while (VIM_ISDIGIT(*p)) // skip number ++p; } // compute length of search command for get_address() searchcmdlen += (int)(p - pat); pat = p; // put pat after search command } if ((options & SEARCH_ECHO) && messaging() && !msg_silent && (!cmd_silent || !shortmess(SHM_SEARCHCOUNT))) { char_u *trunc; char_u off_buf[40]; size_t off_len = 0; // Compute msg_row early. msg_start(); // Get the offset, so we know how long it is. if (!cmd_silent && (spats[0].off.line || spats[0].off.end || spats[0].off.off)) { p = off_buf; *p++ = dirc; if (spats[0].off.end) *p++ = 'e'; else if (!spats[0].off.line) *p++ = 's'; if (spats[0].off.off > 0 || spats[0].off.line) *p++ = '+'; *p = NUL; if (spats[0].off.off != 0 || spats[0].off.line) sprintf((char *)p, "%ld", spats[0].off.off); off_len = STRLEN(off_buf); } if (*searchstr == NUL) p = spats[0].pat; else p = searchstr; if (!shortmess(SHM_SEARCHCOUNT) || cmd_silent) { // Reserve enough space for the search pattern + offset + // search stat. Use all the space available, so that the // search state is right aligned. If there is not enough space // msg_strtrunc() will shorten in the middle. if (msg_scrolled != 0 && !cmd_silent) // Use all the columns. len = (int)(Rows - msg_row) * Columns - 1; else // Use up to 'showcmd' column. len = (int)(Rows - msg_row - 1) * Columns + sc_col - 1; if (len < STRLEN(p) + off_len + SEARCH_STAT_BUF_LEN + 3) len = STRLEN(p) + off_len + SEARCH_STAT_BUF_LEN + 3; } else // Reserve enough space for the search pattern + offset. len = STRLEN(p) + off_len + 3; vim_free(msgbuf); msgbuf = alloc(len); if (msgbuf != NULL) { vim_memset(msgbuf, ' ', len); msgbuf[len - 1] = NUL; // do not fill the msgbuf buffer, if cmd_silent is set, leave it // empty for the search_stat feature. if (!cmd_silent) { msgbuf[0] = dirc; if (enc_utf8 && utf_iscomposing(utf_ptr2char(p))) { // Use a space to draw the composing char on. msgbuf[1] = ' '; mch_memmove(msgbuf + 2, p, STRLEN(p)); } else mch_memmove(msgbuf + 1, p, STRLEN(p)); if (off_len > 0) mch_memmove(msgbuf + STRLEN(p) + 1, off_buf, off_len); trunc = msg_strtrunc(msgbuf, TRUE); if (trunc != NULL) { vim_free(msgbuf); msgbuf = trunc; } #ifdef FEAT_RIGHTLEFT // The search pattern could be shown on the right in rightleft // mode, but the 'ruler' and 'showcmd' area use it too, thus // it would be blanked out again very soon. Show it on the // left, but do reverse the text. if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { char_u *r; size_t pat_len; r = reverse_text(msgbuf); if (r != NULL) { vim_free(msgbuf); msgbuf = r; // move reversed text to beginning of buffer while (*r != NUL && *r == ' ') r++; pat_len = msgbuf + STRLEN(msgbuf) - r; mch_memmove(msgbuf, r, pat_len); // overwrite old text if ((size_t)(r - msgbuf) >= pat_len) vim_memset(r, ' ', pat_len); else vim_memset(msgbuf + pat_len, ' ', r - msgbuf); } } #endif msg_outtrans(msgbuf); msg_clr_eos(); msg_check(); gotocmdline(FALSE); out_flush(); msg_nowait = TRUE; // don't wait for this message } } } /* * If there is a character offset, subtract it from the current * position, so we don't get stuck at "?pat?e+2" or "/pat/s-2". * Skip this if pos.col is near MAXCOL (closed fold). * This is not done for a line offset, because then we would not be vi * compatible. */ if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) { if (spats[0].off.off > 0) { for (c = spats[0].off.off; c; --c) if (decl(&pos) == -1) break; if (c) // at start of buffer { pos.lnum = 0; // allow lnum == 0 here pos.col = MAXCOL; } } else { for (c = spats[0].off.off; c; ++c) if (incl(&pos) == -1) break; if (c) // at end of buffer { pos.lnum = curbuf->b_ml.ml_line_count + 1; pos.col = 0; } } } c = searchit(curwin, curbuf, &pos, NULL, dirc == '/' ? FORWARD : BACKWARD, searchstr, count, spats[0].off.end + (options & (SEARCH_KEEP + SEARCH_PEEK + SEARCH_HIS + SEARCH_MSG + SEARCH_START + ((pat != NULL && *pat == ';') ? 0 : SEARCH_NOOF))), RE_LAST, sia); if (dircp != NULL) *dircp = search_delim; // restore second '/' or '?' for normal_cmd() if (!shortmess(SHM_SEARCH) && ((dirc == '/' && LT_POS(pos, curwin->w_cursor)) || (dirc == '?' && LT_POS(curwin->w_cursor, pos)))) show_top_bot_msg = TRUE; if (c == FAIL) { retval = 0; goto end_do_search; } if (spats[0].off.end && oap != NULL) oap->inclusive = TRUE; // 'e' includes last character retval = 1; // pattern found /* * Add character and/or line offset */ if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';')) { pos_T org_pos = pos; if (spats[0].off.line) // Add the offset to the line number. { c = pos.lnum + spats[0].off.off; if (c < 1) pos.lnum = 1; else if (c > curbuf->b_ml.ml_line_count) pos.lnum = curbuf->b_ml.ml_line_count; else pos.lnum = c; pos.col = 0; retval = 2; // pattern found, line offset added } else if (pos.col < MAXCOL - 2) // just in case { // to the right, check for end of file c = spats[0].off.off; if (c > 0) { while (c-- > 0) if (incl(&pos) == -1) break; } // to the left, check for start of file else { while (c++ < 0) if (decl(&pos) == -1) break; } } if (!EQUAL_POS(pos, org_pos)) has_offset = TRUE; } // Show [1/15] if 'S' is not in 'shortmess'. if ((options & SEARCH_ECHO) && messaging() && !msg_silent && c != FAIL && !shortmess(SHM_SEARCHCOUNT) && msgbuf != NULL) cmdline_search_stat(dirc, &pos, &curwin->w_cursor, show_top_bot_msg, msgbuf, (count != 1 || has_offset #ifdef FEAT_FOLDING || (!(fdo_flags & FDO_SEARCH) && hasFolding(curwin->w_cursor.lnum, NULL, NULL)) #endif ), SEARCH_STAT_DEF_MAX_COUNT, SEARCH_STAT_DEF_TIMEOUT); /* * The search command can be followed by a ';' to do another search. * For example: "/pat/;/foo/+3;?bar" * This is like doing another search command, except: * - The remembered direction '/' or '?' is from the first search. * - When an error happens the cursor isn't moved at all. * Don't do this when called by get_address() (it handles ';' itself). */ if (!(options & SEARCH_OPT) || pat == NULL || *pat != ';') break; dirc = *++pat; search_delim = dirc; if (dirc != '?' && dirc != '/') { retval = 0; emsg(_("E386: Expected '?' or '/' after ';'")); goto end_do_search; } ++pat; } if (options & SEARCH_MARK) setpcmark(); curwin->w_cursor = pos; curwin->w_set_curswant = TRUE; end_do_search: if ((options & SEARCH_KEEP) || cmdmod.keeppatterns) spats[0].off = old_off; vim_free(strcopy); vim_free(msgbuf); return retval; } /* * search_for_exact_line(buf, pos, dir, pat) * * Search for a line starting with the given pattern (ignoring leading * white-space), starting from pos and going in direction "dir". "pos" will * contain the position of the match found. Blank lines match only if * ADDING is set. If p_ic is set then the pattern must be in lowercase. * Return OK for success, or FAIL if no line found. */ int search_for_exact_line( buf_T *buf, pos_T *pos, int dir, char_u *pat) { linenr_T start = 0; char_u *ptr; char_u *p; if (buf->b_ml.ml_line_count == 0) return FAIL; for (;;) { pos->lnum += dir; if (pos->lnum < 1) { if (p_ws) { pos->lnum = buf->b_ml.ml_line_count; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(top_bot_msg), TRUE); } else { pos->lnum = 1; break; } } else if (pos->lnum > buf->b_ml.ml_line_count) { if (p_ws) { pos->lnum = 1; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(bot_top_msg), TRUE); } else { pos->lnum = 1; break; } } if (pos->lnum == start) break; if (start == 0) start = pos->lnum; ptr = ml_get_buf(buf, pos->lnum, FALSE); p = skipwhite(ptr); pos->col = (colnr_T) (p - ptr); // when adding lines the matching line may be empty but it is not // ignored because we are interested in the next line -- Acevedo if ((compl_cont_status & CONT_ADDING) && !(compl_cont_status & CONT_SOL)) { if ((p_ic ? MB_STRICMP(p, pat) : STRCMP(p, pat)) == 0) return OK; } else if (*p != NUL) // ignore empty lines { // expanding lines or words if ((p_ic ? MB_STRNICMP(p, pat, compl_length) : STRNCMP(p, pat, compl_length)) == 0) return OK; } } return FAIL; } /* * Character Searches */ /* * Search for a character in a line. If "t_cmd" is FALSE, move to the * position of the character, otherwise move to just before the char. * Do this "cap->count1" times. * Return FAIL or OK. */ int searchc(cmdarg_T *cap, int t_cmd) { int c = cap->nchar; // char to search for int dir = cap->arg; // TRUE for searching forward long count = cap->count1; // repeat count int col; char_u *p; int len; int stop = TRUE; if (c != NUL) // normal search: remember args for repeat { if (!KeyStuffed) // don't remember when redoing { *lastc = c; set_csearch_direction(dir); set_csearch_until(t_cmd); lastc_bytelen = (*mb_char2bytes)(c, lastc_bytes); if (cap->ncharC1 != 0) { lastc_bytelen += (*mb_char2bytes)(cap->ncharC1, lastc_bytes + lastc_bytelen); if (cap->ncharC2 != 0) lastc_bytelen += (*mb_char2bytes)(cap->ncharC2, lastc_bytes + lastc_bytelen); } } } else // repeat previous search { if (*lastc == NUL && lastc_bytelen == 1) return FAIL; if (dir) // repeat in opposite direction dir = -lastcdir; else dir = lastcdir; t_cmd = last_t_cmd; c = *lastc; // For multi-byte re-use last lastc_bytes[] and lastc_bytelen. // Force a move of at least one char, so ";" and "," will move the // cursor, even if the cursor is right in front of char we are looking // at. if (vim_strchr(p_cpo, CPO_SCOLON) == NULL && count == 1 && t_cmd) stop = FALSE; } if (dir == BACKWARD) cap->oap->inclusive = FALSE; else cap->oap->inclusive = TRUE; p = ml_get_curline(); col = curwin->w_cursor.col; len = (int)STRLEN(p); while (count--) { if (has_mbyte) { for (;;) { if (dir > 0) { col += (*mb_ptr2len)(p + col); if (col >= len) return FAIL; } else { if (col == 0) return FAIL; col -= (*mb_head_off)(p, p + col - 1) + 1; } if (lastc_bytelen == 1) { if (p[col] == c && stop) break; } else if (STRNCMP(p + col, lastc_bytes, lastc_bytelen) == 0 && stop) break; stop = TRUE; } } else { for (;;) { if ((col += dir) < 0 || col >= len) return FAIL; if (p[col] == c && stop) break; stop = TRUE; } } } if (t_cmd) { // backup to before the character (possibly double-byte) col -= dir; if (has_mbyte) { if (dir < 0) // Landed on the search char which is lastc_bytelen long col += lastc_bytelen - 1; else // To previous char, which may be multi-byte. col -= (*mb_head_off)(p, p + col); } } curwin->w_cursor.col = col; return OK; } /* * "Other" Searches */ /* * findmatch - find the matching paren or brace * * Improvement over vi: Braces inside quotes are ignored. */ pos_T * findmatch(oparg_T *oap, int initc) { return findmatchlimit(oap, initc, 0, 0); } /* * Return TRUE if the character before "linep[col]" equals "ch". * Return FALSE if "col" is zero. * Update "*prevcol" to the column of the previous character, unless "prevcol" * is NULL. * Handles multibyte string correctly. */ static int check_prevcol( char_u *linep, int col, int ch, int *prevcol) { --col; if (col > 0 && has_mbyte) col -= (*mb_head_off)(linep, linep + col); if (prevcol) *prevcol = col; return (col >= 0 && linep[col] == ch) ? TRUE : FALSE; } /* * Raw string start is found at linep[startpos.col - 1]. * Return TRUE if the matching end can be found between startpos and endpos. */ static int find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos) { char_u *p; char_u *delim_copy; size_t delim_len; linenr_T lnum; int found = FALSE; for (p = linep + startpos->col + 1; *p && *p != '('; ++p) ; delim_len = (p - linep) - startpos->col - 1; delim_copy = vim_strnsave(linep + startpos->col + 1, delim_len); if (delim_copy == NULL) return FALSE; for (lnum = startpos->lnum; lnum <= endpos->lnum; ++lnum) { char_u *line = ml_get(lnum); for (p = line + (lnum == startpos->lnum ? startpos->col + 1 : 0); *p; ++p) { if (lnum == endpos->lnum && (colnr_T)(p - line) >= endpos->col) break; if (*p == ')' && STRNCMP(delim_copy, p + 1, delim_len) == 0 && p[delim_len + 1] == '"') { found = TRUE; break; } } if (found) break; } vim_free(delim_copy); return found; } /* * Check matchpairs option for "*initc". * If there is a match set "*initc" to the matching character and "*findc" to * the opposite character. Set "*backwards" to the direction. * When "switchit" is TRUE swap the direction. */ static void find_mps_values( int *initc, int *findc, int *backwards, int switchit) { char_u *ptr; ptr = curbuf->b_p_mps; while (*ptr != NUL) { if (has_mbyte) { char_u *prev; if (mb_ptr2char(ptr) == *initc) { if (switchit) { *findc = *initc; *initc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1); *backwards = TRUE; } else { *findc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1); *backwards = FALSE; } return; } prev = ptr; ptr += mb_ptr2len(ptr) + 1; if (mb_ptr2char(ptr) == *initc) { if (switchit) { *findc = *initc; *initc = mb_ptr2char(prev); *backwards = FALSE; } else { *findc = mb_ptr2char(prev); *backwards = TRUE; } return; } ptr += mb_ptr2len(ptr); } else { if (*ptr == *initc) { if (switchit) { *backwards = TRUE; *findc = *initc; *initc = ptr[2]; } else { *backwards = FALSE; *findc = ptr[2]; } return; } ptr += 2; if (*ptr == *initc) { if (switchit) { *backwards = FALSE; *findc = *initc; *initc = ptr[-2]; } else { *backwards = TRUE; *findc = ptr[-2]; } return; } ++ptr; } if (*ptr == ',') ++ptr; } } /* * findmatchlimit -- find the matching paren or brace, if it exists within * maxtravel lines of the cursor. A maxtravel of 0 means search until falling * off the edge of the file. * * "initc" is the character to find a match for. NUL means to find the * character at or after the cursor. Special values: * '*' look for C-style comment / * * '/' look for C-style comment / *, ignoring comment-end * '#' look for preprocessor directives * 'R' look for raw string start: R"delim(text)delim" (only backwards) * * flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#') * FM_FORWARD search forwards (when initc is '/', '*' or '#') * FM_BLOCKSTOP stop at start/end of block ({ or } in column 0) * FM_SKIPCOMM skip comments (not implemented yet!) * * "oap" is only used to set oap->motion_type for a linewise motion, it can be * NULL */ pos_T * findmatchlimit( oparg_T *oap, int initc, int flags, int maxtravel) { static pos_T pos; // current search position int findc = 0; // matching brace int c; int count = 0; // cumulative number of braces int backwards = FALSE; // init for gcc int raw_string = FALSE; // search for raw string int inquote = FALSE; // TRUE when inside quotes char_u *linep; // pointer to current line char_u *ptr; int do_quotes; // check for quotes in current line int at_start; // do_quotes value at start position int hash_dir = 0; // Direction searched for # things int comment_dir = 0; // Direction searched for comments pos_T match_pos; // Where last slash-star was found int start_in_quotes; // start position is in quotes int traveled = 0; // how far we've searched so far int ignore_cend = FALSE; // ignore comment end int cpo_match; // vi compatible matching int cpo_bsl; // don't recognize backslashes int match_escaped = 0; // search for escaped match int dir; // Direction to search int comment_col = MAXCOL; // start of / / comment #ifdef FEAT_LISP int lispcomm = FALSE; // inside of Lisp-style comment int lisp = curbuf->b_p_lisp; // engage Lisp-specific hacks ;) #endif pos = curwin->w_cursor; pos.coladd = 0; linep = ml_get(pos.lnum); cpo_match = (vim_strchr(p_cpo, CPO_MATCH) != NULL); cpo_bsl = (vim_strchr(p_cpo, CPO_MATCHBSL) != NULL); // Direction to search when initc is '/', '*' or '#' if (flags & FM_BACKWARD) dir = BACKWARD; else if (flags & FM_FORWARD) dir = FORWARD; else dir = 0; /* * if initc given, look in the table for the matching character * '/' and '*' are special cases: look for start or end of comment. * When '/' is used, we ignore running backwards into an star-slash, for * "[*" command, we just want to find any comment. */ if (initc == '/' || initc == '*' || initc == 'R') { comment_dir = dir; if (initc == '/') ignore_cend = TRUE; backwards = (dir == FORWARD) ? FALSE : TRUE; raw_string = (initc == 'R'); initc = NUL; } else if (initc != '#' && initc != NUL) { find_mps_values(&initc, &findc, &backwards, TRUE); if (findc == NUL) return NULL; } else { /* * Either initc is '#', or no initc was given and we need to look * under the cursor. */ if (initc == '#') { hash_dir = dir; } else { /* * initc was not given, must look for something to match under * or near the cursor. * Only check for special things when 'cpo' doesn't have '%'. */ if (!cpo_match) { // Are we before or at #if, #else etc.? ptr = skipwhite(linep); if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep)) { ptr = skipwhite(ptr + 1); if ( STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "endif", 5) == 0 || STRNCMP(ptr, "el", 2) == 0) hash_dir = 1; } // Are we on a comment? else if (linep[pos.col] == '/') { if (linep[pos.col + 1] == '*') { comment_dir = FORWARD; backwards = FALSE; pos.col++; } else if (pos.col > 0 && linep[pos.col - 1] == '*') { comment_dir = BACKWARD; backwards = TRUE; pos.col--; } } else if (linep[pos.col] == '*') { if (linep[pos.col + 1] == '/') { comment_dir = BACKWARD; backwards = TRUE; } else if (pos.col > 0 && linep[pos.col - 1] == '/') { comment_dir = FORWARD; backwards = FALSE; } } } /* * If we are not on a comment or the # at the start of a line, then * look for brace anywhere on this line after the cursor. */ if (!hash_dir && !comment_dir) { /* * Find the brace under or after the cursor. * If beyond the end of the line, use the last character in * the line. */ if (linep[pos.col] == NUL && pos.col) --pos.col; for (;;) { initc = PTR2CHAR(linep + pos.col); if (initc == NUL) break; find_mps_values(&initc, &findc, &backwards, FALSE); if (findc) break; pos.col += mb_ptr2len(linep + pos.col); } if (!findc) { // no brace in the line, maybe use " #if" then if (!cpo_match && *skipwhite(linep) == '#') hash_dir = 1; else return NULL; } else if (!cpo_bsl) { int col, bslcnt = 0; // Set "match_escaped" if there are an odd number of // backslashes. for (col = pos.col; check_prevcol(linep, col, '\\', &col);) bslcnt++; match_escaped = (bslcnt & 1); } } } if (hash_dir) { /* * Look for matching #if, #else, #elif, or #endif */ if (oap != NULL) oap->motion_type = MLINE; // Linewise for this case only if (initc != '#') { ptr = skipwhite(skipwhite(linep) + 1); if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) hash_dir = 1; else if (STRNCMP(ptr, "endif", 5) == 0) hash_dir = -1; else return NULL; } pos.col = 0; while (!got_int) { if (hash_dir > 0) { if (pos.lnum == curbuf->b_ml.ml_line_count) break; } else if (pos.lnum == 1) break; pos.lnum += hash_dir; linep = ml_get(pos.lnum); line_breakcheck(); // check for CTRL-C typed ptr = skipwhite(linep); if (*ptr != '#') continue; pos.col = (colnr_T) (ptr - linep); ptr = skipwhite(ptr + 1); if (hash_dir > 0) { if (STRNCMP(ptr, "if", 2) == 0) count++; else if (STRNCMP(ptr, "el", 2) == 0) { if (count == 0) return &pos; } else if (STRNCMP(ptr, "endif", 5) == 0) { if (count == 0) return &pos; count--; } } else { if (STRNCMP(ptr, "if", 2) == 0) { if (count == 0) return &pos; count--; } else if (initc == '#' && STRNCMP(ptr, "el", 2) == 0) { if (count == 0) return &pos; } else if (STRNCMP(ptr, "endif", 5) == 0) count++; } } return NULL; } } #ifdef FEAT_RIGHTLEFT // This is just guessing: when 'rightleft' is set, search for a matching // paren/brace in the other direction. if (curwin->w_p_rl && vim_strchr((char_u *)"()[]{}<>", initc) != NULL) backwards = !backwards; #endif do_quotes = -1; start_in_quotes = MAYBE; CLEAR_POS(&match_pos); // backward search: Check if this line contains a single-line comment if ((backwards && comment_dir) #ifdef FEAT_LISP || lisp #endif ) comment_col = check_linecomment(linep); #ifdef FEAT_LISP if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) lispcomm = TRUE; // find match inside this comment #endif while (!got_int) { /* * Go to the next position, forward or backward. We could use * inc() and dec() here, but that is much slower */ if (backwards) { #ifdef FEAT_LISP // char to match is inside of comment, don't search outside if (lispcomm && pos.col < (colnr_T)comment_col) break; #endif if (pos.col == 0) // at start of line, go to prev. one { if (pos.lnum == 1) // start of file break; --pos.lnum; if (maxtravel > 0 && ++traveled > maxtravel) break; linep = ml_get(pos.lnum); pos.col = (colnr_T)STRLEN(linep); // pos.col on trailing NUL do_quotes = -1; line_breakcheck(); // Check if this line contains a single-line comment if (comment_dir #ifdef FEAT_LISP || lisp #endif ) comment_col = check_linecomment(linep); #ifdef FEAT_LISP // skip comment if (lisp && comment_col != MAXCOL) pos.col = comment_col; #endif } else { --pos.col; if (has_mbyte) pos.col -= (*mb_head_off)(linep, linep + pos.col); } } else // forward search { if (linep[pos.col] == NUL // at end of line, go to next one #ifdef FEAT_LISP // don't search for match in comment || (lisp && comment_col != MAXCOL && pos.col == (colnr_T)comment_col) #endif ) { if (pos.lnum == curbuf->b_ml.ml_line_count // end of file #ifdef FEAT_LISP // line is exhausted and comment with it, // don't search for match in code || lispcomm #endif ) break; ++pos.lnum; if (maxtravel && traveled++ > maxtravel) break; linep = ml_get(pos.lnum); pos.col = 0; do_quotes = -1; line_breakcheck(); #ifdef FEAT_LISP if (lisp) // find comment pos in new line comment_col = check_linecomment(linep); #endif } else { if (has_mbyte) pos.col += (*mb_ptr2len)(linep + pos.col); else ++pos.col; } } /* * If FM_BLOCKSTOP given, stop at a '{' or '}' in column 0. */ if (pos.col == 0 && (flags & FM_BLOCKSTOP) && (linep[0] == '{' || linep[0] == '}')) { if (linep[0] == findc && count == 0) // match! return &pos; break; // out of scope } if (comment_dir) { // Note: comments do not nest, and we ignore quotes in them // TODO: ignore comment brackets inside strings if (comment_dir == FORWARD) { if (linep[pos.col] == '*' && linep[pos.col + 1] == '/') { pos.col++; return &pos; } } else // Searching backwards { /* * A comment may contain / * or / /, it may also start or end * with / * /. Ignore a / * after / / and after *. */ if (pos.col == 0) continue; else if (raw_string) { if (linep[pos.col - 1] == 'R' && linep[pos.col] == '"' && vim_strchr(linep + pos.col + 1, '(') != NULL) { // Possible start of raw string. Now that we have the // delimiter we can check if it ends before where we // started searching, or before the previously found // raw string start. if (!find_rawstring_end(linep, &pos, count > 0 ? &match_pos : &curwin->w_cursor)) { count++; match_pos = pos; match_pos.col--; } linep = ml_get(pos.lnum); // may have been released } } else if ( linep[pos.col - 1] == '/' && linep[pos.col] == '*' && (pos.col == 1 || linep[pos.col - 2] != '*') && (int)pos.col < comment_col) { count++; match_pos = pos; match_pos.col--; } else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/') { if (count > 0) pos = match_pos; else if (pos.col > 1 && linep[pos.col - 2] == '/' && (int)pos.col <= comment_col) pos.col -= 2; else if (ignore_cend) continue; else return NULL; return &pos; } } continue; } /* * If smart matching ('cpoptions' does not contain '%'), braces inside * of quotes are ignored, but only if there is an even number of * quotes in the line. */ if (cpo_match) do_quotes = 0; else if (do_quotes == -1) { /* * Count the number of quotes in the line, skipping \" and '"'. * Watch out for "\\". */ at_start = do_quotes; for (ptr = linep; *ptr; ++ptr) { if (ptr == linep + pos.col + backwards) at_start = (do_quotes & 1); if (*ptr == '"' && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) ++do_quotes; if (*ptr == '\\' && ptr[1] != NUL) ++ptr; } do_quotes &= 1; // result is 1 with even number of quotes /* * If we find an uneven count, check current line and previous * one for a '\' at the end. */ if (!do_quotes) { inquote = FALSE; if (ptr[-1] == '\\') { do_quotes = 1; if (start_in_quotes == MAYBE) { // Do we need to use at_start here? inquote = TRUE; start_in_quotes = TRUE; } else if (backwards) inquote = TRUE; } if (pos.lnum > 1) { ptr = ml_get(pos.lnum - 1); if (*ptr && *(ptr + STRLEN(ptr) - 1) == '\\') { do_quotes = 1; if (start_in_quotes == MAYBE) { inquote = at_start; if (inquote) start_in_quotes = TRUE; } else if (!backwards) inquote = TRUE; } // ml_get() only keeps one line, need to get linep again linep = ml_get(pos.lnum); } } } if (start_in_quotes == MAYBE) start_in_quotes = FALSE; /* * If 'smartmatch' is set: * Things inside quotes are ignored by setting 'inquote'. If we * find a quote without a preceding '\' invert 'inquote'. At the * end of a line not ending in '\' we reset 'inquote'. * * In lines with an uneven number of quotes (without preceding '\') * we do not know which part to ignore. Therefore we only set * inquote if the number of quotes in a line is even, unless this * line or the previous one ends in a '\'. Complicated, isn't it? */ c = PTR2CHAR(linep + pos.col); switch (c) { case NUL: // at end of line without trailing backslash, reset inquote if (pos.col == 0 || linep[pos.col - 1] != '\\') { inquote = FALSE; start_in_quotes = FALSE; } break; case '"': // a quote that is preceded with an odd number of backslashes is // ignored if (do_quotes) { int col; for (col = pos.col - 1; col >= 0; --col) if (linep[col] != '\\') break; if ((((int)pos.col - 1 - col) & 1) == 0) { inquote = !inquote; start_in_quotes = FALSE; } } break; /* * If smart matching ('cpoptions' does not contain '%'): * Skip things in single quotes: 'x' or '\x'. Be careful for single * single quotes, eg jon's. Things like '\233' or '\x3f' are not * skipped, there is never a brace in them. * Ignore this when finding matches for `'. */ case '\'': if (!cpo_match && initc != '\'' && findc != '\'') { if (backwards) { if (pos.col > 1) { if (linep[pos.col - 2] == '\'') { pos.col -= 2; break; } else if (linep[pos.col - 2] == '\\' && pos.col > 2 && linep[pos.col - 3] == '\'') { pos.col -= 3; break; } } } else if (linep[pos.col + 1]) // forward search { if (linep[pos.col + 1] == '\\' && linep[pos.col + 2] && linep[pos.col + 3] == '\'') { pos.col += 3; break; } else if (linep[pos.col + 2] == '\'') { pos.col += 2; break; } } } // FALLTHROUGH default: #ifdef FEAT_LISP /* * For Lisp skip over backslashed (), {} and []. * (actually, we skip #\( et al) */ if (curbuf->b_p_lisp && vim_strchr((char_u *)"(){}[]", c) != NULL && pos.col > 1 && check_prevcol(linep, pos.col, '\\', NULL) && check_prevcol(linep, pos.col - 1, '#', NULL)) break; #endif // Check for match outside of quotes, and inside of // quotes when the start is also inside of quotes. if ((!inquote || start_in_quotes == TRUE) && (c == initc || c == findc)) { int col, bslcnt = 0; if (!cpo_bsl) { for (col = pos.col; check_prevcol(linep, col, '\\', &col);) bslcnt++; } // Only accept a match when 'M' is in 'cpo' or when escaping // is what we expect. if (cpo_bsl || (bslcnt & 1) == match_escaped) { if (c == initc) count++; else { if (count == 0) return &pos; count--; } } } } } if (comment_dir == BACKWARD && count > 0) { pos = match_pos; return &pos; } return (pos_T *)NULL; // never found it } /* * Check if line[] contains a / / comment. * Return MAXCOL if not, otherwise return the column. * TODO: skip strings. */ static int check_linecomment(char_u *line) { char_u *p; p = line; #ifdef FEAT_LISP // skip Lispish one-line comments if (curbuf->b_p_lisp) { if (vim_strchr(p, ';') != NULL) // there may be comments { int in_str = FALSE; // inside of string p = line; // scan from start while ((p = vim_strpbrk(p, (char_u *)"\";")) != NULL) { if (*p == '"') { if (in_str) { if (*(p - 1) != '\\') // skip escaped quote in_str = FALSE; } else if (p == line || ((p - line) >= 2 // skip #\" form && *(p - 1) != '\\' && *(p - 2) != '#')) in_str = TRUE; } else if (!in_str && ((p - line) < 2 || (*(p - 1) != '\\' && *(p - 2) != '#'))) break; // found! ++p; } } else p = NULL; } else #endif while ((p = vim_strchr(p, '/')) != NULL) { // accept a double /, unless it's preceded with * and followed by *, // because * / / * is an end and start of a C comment if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) break; ++p; } if (p == NULL) return MAXCOL; return (int)(p - line); } /* * Move cursor briefly to character matching the one under the cursor. * Used for Insert mode and "r" command. * Show the match only if it is visible on the screen. * If there isn't a match, then beep. */ void showmatch( int c) // char to show match for { pos_T *lpos, save_cursor; pos_T mpos; colnr_T vcol; long save_so; long save_siso; #ifdef CURSOR_SHAPE int save_state; #endif colnr_T save_dollar_vcol; char_u *p; long *so = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so; long *siso = curwin->w_p_siso >= 0 ? &curwin->w_p_siso : &p_siso; /* * Only show match for chars in the 'matchpairs' option. */ // 'matchpairs' is "x:y,x:y" for (p = curbuf->b_p_mps; *p != NUL; ++p) { #ifdef FEAT_RIGHTLEFT if (PTR2CHAR(p) == c && (curwin->w_p_rl ^ p_ri)) break; #endif p += mb_ptr2len(p) + 1; if (PTR2CHAR(p) == c #ifdef FEAT_RIGHTLEFT && !(curwin->w_p_rl ^ p_ri) #endif ) break; p += mb_ptr2len(p); if (*p == NUL) return; } if ((lpos = findmatch(NULL, NUL)) == NULL) // no match, so beep vim_beep(BO_MATCH); else if (lpos->lnum >= curwin->w_topline && lpos->lnum < curwin->w_botline) { if (!curwin->w_p_wrap) getvcol(curwin, lpos, NULL, &vcol, NULL); if (curwin->w_p_wrap || (vcol >= curwin->w_leftcol && vcol < curwin->w_leftcol + curwin->w_width)) { mpos = *lpos; // save the pos, update_screen() may change it save_cursor = curwin->w_cursor; save_so = *so; save_siso = *siso; // Handle "$" in 'cpo': If the ')' is typed on top of the "$", // stop displaying the "$". if (dollar_vcol >= 0 && dollar_vcol == curwin->w_virtcol) dollar_vcol = -1; ++curwin->w_virtcol; // do display ')' just before "$" update_screen(VALID); // show the new char first save_dollar_vcol = dollar_vcol; #ifdef CURSOR_SHAPE save_state = State; State = SHOWMATCH; ui_cursor_shape(); // may show different cursor shape #endif curwin->w_cursor = mpos; // move to matching char *so = 0; // don't use 'scrolloff' here *siso = 0; // don't use 'sidescrolloff' here showruler(FALSE); setcursor(); cursor_on(); // make sure that the cursor is shown out_flush_cursor(TRUE, FALSE); // Restore dollar_vcol(), because setcursor() may call curs_rows() // which resets it if the matching position is in a previous line // and has a higher column number. dollar_vcol = save_dollar_vcol; /* * brief pause, unless 'm' is present in 'cpo' and a character is * available. */ if (vim_strchr(p_cpo, CPO_SHOWMATCH) != NULL) ui_delay(p_mat * 100L + 8, TRUE); else if (!char_avail()) ui_delay(p_mat * 100L + 9, FALSE); curwin->w_cursor = save_cursor; // restore cursor position *so = save_so; *siso = save_siso; #ifdef CURSOR_SHAPE State = save_state; ui_cursor_shape(); // may show different cursor shape #endif } } } /* * Check if the pattern is zero-width. * If move is TRUE, check from the beginning of the buffer, else from position * "cur". * "direction" is FORWARD or BACKWARD. * Returns TRUE, FALSE or -1 for failure. */ static int is_zero_width(char_u *pattern, int move, pos_T *cur, int direction) { regmmatch_T regmatch; int nmatched = 0; int result = -1; pos_T pos; int called_emsg_before = called_emsg; int flag = 0; if (pattern == NULL) pattern = spats[last_idx].pat; if (search_regcomp(pattern, RE_SEARCH, RE_SEARCH, SEARCH_KEEP, &regmatch) == FAIL) return -1; // init startcol correctly regmatch.startpos[0].col = -1; // move to match if (move) { CLEAR_POS(&pos); } else { pos = *cur; // accept a match at the cursor position flag = SEARCH_START; } if (searchit(curwin, curbuf, &pos, NULL, direction, pattern, 1, SEARCH_KEEP + flag, RE_SEARCH, NULL) != FAIL) { // Zero-width pattern should match somewhere, then we can check if // start and end are in the same position. do { regmatch.startpos[0].col++; nmatched = vim_regexec_multi(&regmatch, curwin, curbuf, pos.lnum, regmatch.startpos[0].col, NULL, NULL); if (nmatched != 0) break; } while (regmatch.regprog != NULL && direction == FORWARD ? regmatch.startpos[0].col < pos.col : regmatch.startpos[0].col > pos.col); if (called_emsg == called_emsg_before) { result = (nmatched != 0 && regmatch.startpos[0].lnum == regmatch.endpos[0].lnum && regmatch.startpos[0].col == regmatch.endpos[0].col); } } vim_regfree(regmatch.regprog); return result; } /* * Find next search match under cursor, cursor at end. * Used while an operator is pending, and in Visual mode. */ int current_search( long count, int forward) // TRUE for forward, FALSE for backward { pos_T start_pos; // start position of the pattern match pos_T end_pos; // end position of the pattern match pos_T orig_pos; // position of the cursor at beginning pos_T pos; // position after the pattern int i; int dir; int result; // result of various function calls char_u old_p_ws = p_ws; int flags = 0; pos_T save_VIsual = VIsual; int zero_width; int skip_first_backward; // Correct cursor when 'selection' is exclusive if (VIsual_active && *p_sel == 'e' && LT_POS(VIsual, curwin->w_cursor)) dec_cursor(); // When searching forward and the cursor is at the start of the Visual // area, skip the first search backward, otherwise it doesn't move. skip_first_backward = forward && VIsual_active && LT_POS(curwin->w_cursor, VIsual); orig_pos = pos = curwin->w_cursor; if (VIsual_active) { if (forward) incl(&pos); else decl(&pos); } // Is the pattern is zero-width?, this time, don't care about the direction zero_width = is_zero_width(spats[last_idx].pat, TRUE, &curwin->w_cursor, FORWARD); if (zero_width == -1) return FAIL; // pattern not found /* * The trick is to first search backwards and then search forward again, * so that a match at the current cursor position will be correctly * captured. When "forward" is false do it the other way around. */ for (i = 0; i < 2; i++) { if (forward) { if (i == 0 && skip_first_backward) continue; dir = i; } else dir = !i; flags = 0; if (!dir && !zero_width) flags = SEARCH_END; end_pos = pos; // wrapping should not occur in the first round if (i == 0) p_ws = FALSE; result = searchit(curwin, curbuf, &pos, &end_pos, (dir ? FORWARD : BACKWARD), spats[last_idx].pat, (long) (i ? count : 1), SEARCH_KEEP | flags, RE_SEARCH, NULL); p_ws = old_p_ws; // First search may fail, but then start searching from the // beginning of the file (cursor might be on the search match) // except when Visual mode is active, so that extending the visual // selection works. if (i == 1 && !result) // not found, abort { curwin->w_cursor = orig_pos; if (VIsual_active) VIsual = save_VIsual; return FAIL; } else if (i == 0 && !result) { if (forward) { // try again from start of buffer CLEAR_POS(&pos); } else { // try again from end of buffer // searching backwards, so set pos to last line and col pos.lnum = curwin->w_buffer->b_ml.ml_line_count; pos.col = (colnr_T)STRLEN( ml_get(curwin->w_buffer->b_ml.ml_line_count)); } } } start_pos = pos; if (!VIsual_active) VIsual = start_pos; // put the cursor after the match curwin->w_cursor = end_pos; if (LT_POS(VIsual, end_pos) && forward) { if (skip_first_backward) // put the cursor on the start of the match curwin->w_cursor = pos; else // put the cursor on last character of match dec_cursor(); } else if (VIsual_active && LT_POS(curwin->w_cursor, VIsual) && forward) curwin->w_cursor = pos; // put the cursor on the start of the match VIsual_active = TRUE; VIsual_mode = 'v'; if (*p_sel == 'e') { // Correction for exclusive selection depends on the direction. if (forward && LTOREQ_POS(VIsual, curwin->w_cursor)) inc_cursor(); else if (!forward && LTOREQ_POS(curwin->w_cursor, VIsual)) inc(&VIsual); } #ifdef FEAT_FOLDING if (fdo_flags & FDO_SEARCH && KeyTyped) foldOpenCursor(); #endif may_start_select('c'); setmouse(); #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end are still the same, and the selection needs to be owned clip_star.vmode = NUL; #endif redraw_curbuf_later(INVERTED); showmode(); return OK; } #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(FEAT_TEXTOBJ) \ || defined(PROTO) /* * return TRUE if line 'lnum' is empty or has white chars only. */ int linewhite(linenr_T lnum) { char_u *p; p = skipwhite(ml_get(lnum)); return (*p == NUL); } #endif /* * Add the search count "[3/19]" to "msgbuf". * See update_search_stat() for other arguments. */ static void cmdline_search_stat( int dirc, pos_T *pos, pos_T *cursor_pos, int show_top_bot_msg, char_u *msgbuf, int recompute, int maxcount, long timeout) { searchstat_T stat; update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount, timeout); if (stat.cur > 0) { char t[SEARCH_STAT_BUF_LEN]; size_t len; #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { if (stat.incomplete == 1) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); else if (stat.cnt > maxcount && stat.cur > maxcount) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", maxcount, maxcount); else if (stat.cnt > maxcount) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]", maxcount, stat.cur); else vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", stat.cnt, stat.cur); } else #endif { if (stat.incomplete == 1) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); else if (stat.cnt > maxcount && stat.cur > maxcount) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", maxcount, maxcount); else if (stat.cnt > maxcount) vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]", stat.cur, maxcount); else vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", stat.cur, stat.cnt); } len = STRLEN(t); if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) { mch_memmove(t + 2, t, len); t[0] = 'W'; t[1] = ' '; len += 2; } mch_memmove(msgbuf + STRLEN(msgbuf) - len, t, len); if (dirc == '?' && stat.cur == maxcount + 1) stat.cur = -1; // keep the message even after redraw, but don't put in history msg_hist_off = TRUE; give_warning(msgbuf, FALSE); msg_hist_off = FALSE; } } /* * Add the search count information to "stat". * "stat" must not be NULL. * When "recompute" is TRUE always recompute the numbers. * dirc == 0: don't find the next/previous match (only set the result to "stat") * dirc == '/': find the next match * dirc == '?': find the previous match */ static void update_search_stat( int dirc, pos_T *pos, pos_T *cursor_pos, searchstat_T *stat, int recompute, int maxcount, long timeout UNUSED) { int save_ws = p_ws; int wraparound = FALSE; pos_T p = (*pos); static pos_T lastpos = {0, 0, 0}; static int cur = 0; static int cnt = 0; static int exact_match = FALSE; static int incomplete = 0; static int last_maxcount = SEARCH_STAT_DEF_MAX_COUNT; static int chgtick = 0; static char_u *lastpat = NULL; static buf_T *lbuf = NULL; #ifdef FEAT_RELTIME proftime_T start; #endif vim_memset(stat, 0, sizeof(searchstat_T)); if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) { stat->cur = cur; stat->cnt = cnt; stat->exact_match = exact_match; stat->incomplete = incomplete; stat->last_maxcount = last_maxcount; return; } last_maxcount = maxcount; wraparound = ((dirc == '?' && LT_POS(lastpos, p)) || (dirc == '/' && LT_POS(p, lastpos))); // If anything relevant changed the count has to be recomputed. // MB_STRNICMP ignores case, but we should not ignore case. // Unfortunately, there is no MB_STRNICMP function. // XXX: above comment should be "no MB_STRCMP function" ? if (!(chgtick == CHANGEDTICK(curbuf) && MB_STRNICMP(lastpat, spats[last_idx].pat, STRLEN(lastpat)) == 0 && STRLEN(lastpat) == STRLEN(spats[last_idx].pat) && EQUAL_POS(lastpos, *cursor_pos) && lbuf == curbuf) || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount) || recompute) { cur = 0; cnt = 0; exact_match = FALSE; incomplete = 0; CLEAR_POS(&lastpos); lbuf = curbuf; } if (EQUAL_POS(lastpos, *cursor_pos) && !wraparound && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 0)) cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1; else { int done_search = FALSE; pos_T endpos = {0, 0, 0}; p_ws = FALSE; #ifdef FEAT_RELTIME if (timeout > 0) profile_setlimit(timeout, &start); #endif while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos, FORWARD, NULL, 1, SEARCH_KEEP, RE_LAST, NULL) != FAIL) { done_search = TRUE; #ifdef FEAT_RELTIME // Stop after passing the time limit. if (timeout > 0 && profile_passed_limit(&start)) { incomplete = 1; break; } #endif cnt++; if (LTOREQ_POS(lastpos, p)) { cur = cnt; if (LT_POS(p, endpos)) exact_match = TRUE; } fast_breakcheck(); if (maxcount > 0 && cnt > maxcount) { incomplete = 2; // max count exceeded break; } } if (got_int) cur = -1; // abort if (done_search) { vim_free(lastpat); lastpat = vim_strsave(spats[last_idx].pat); chgtick = CHANGEDTICK(curbuf); lbuf = curbuf; lastpos = p; } } stat->cur = cur; stat->cnt = cnt; stat->exact_match = exact_match; stat->incomplete = incomplete; stat->last_maxcount = last_maxcount; p_ws = save_ws; } #if defined(FEAT_FIND_ID) || defined(PROTO) /* * Find identifiers or defines in included files. * If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. */ void find_pattern_in_path( char_u *ptr, // pointer to search pattern int dir UNUSED, // direction of expansion int len, // length of search pattern int whole, // match whole words only int skip_comments, // don't match inside comments int type, // Type of search; are we looking for a type? // a macro? long count, int action, // What to do when we find it linenr_T start_lnum, // first line to start searching linenr_T end_lnum) // last line for searching { SearchedFile *files; // Stack of included files SearchedFile *bigger; // When we need more space int max_path_depth = 50; long match_count = 1; char_u *pat; char_u *new_fname; char_u *curr_fname = curbuf->b_fname; char_u *prev_fname = NULL; linenr_T lnum; int depth; int depth_displayed; // For type==CHECK_PATH int old_files; int already_searched; char_u *file_line; char_u *line; char_u *p; char_u save_char; int define_matched; regmatch_T regmatch; regmatch_T incl_regmatch; regmatch_T def_regmatch; int matched = FALSE; int did_show = FALSE; int found = FALSE; int i; char_u *already = NULL; char_u *startp = NULL; char_u *inc_opt = NULL; #if defined(FEAT_QUICKFIX) win_T *curwin_save = NULL; #endif regmatch.regprog = NULL; incl_regmatch.regprog = NULL; def_regmatch.regprog = NULL; file_line = alloc(LSIZE); if (file_line == NULL) return; if (type != CHECK_PATH && type != FIND_DEFINE // when CONT_SOL is set compare "ptr" with the beginning of the line // is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo && !(compl_cont_status & CONT_SOL)) { pat = alloc(len + 5); if (pat == NULL) goto fpip_end; sprintf((char *)pat, whole ? "\\<%.*s\\>" : "%.*s", len, ptr); // ignore case according to p_ic, p_scs and pat regmatch.rm_ic = ignorecase(pat); regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); vim_free(pat); if (regmatch.regprog == NULL) goto fpip_end; } inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc; if (*inc_opt != NUL) { incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0); if (incl_regmatch.regprog == NULL) goto fpip_end; incl_regmatch.rm_ic = FALSE; // don't ignore case in incl. pat. } if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL)) { def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL ? p_def : curbuf->b_p_def, p_magic ? RE_MAGIC : 0); if (def_regmatch.regprog == NULL) goto fpip_end; def_regmatch.rm_ic = FALSE; // don't ignore case in define pat. } files = lalloc_clear(max_path_depth * sizeof(SearchedFile), TRUE); if (files == NULL) goto fpip_end; old_files = max_path_depth; depth = depth_displayed = -1; lnum = start_lnum; if (end_lnum > curbuf->b_ml.ml_line_count) end_lnum = curbuf->b_ml.ml_line_count; if (lnum > end_lnum) // do at least one line lnum = end_lnum; line = ml_get(lnum); for (;;) { if (incl_regmatch.regprog != NULL && vim_regexec(&incl_regmatch, line, (colnr_T)0)) { char_u *p_fname = (curr_fname == curbuf->b_fname) ? curbuf->b_ffname : curr_fname; if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) // Use text from '\zs' to '\ze' (or end) of 'include'. new_fname = find_file_name_in_path(incl_regmatch.startp[0], (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]), FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname); else // Use text after match with 'include'. new_fname = file_name_in_line(incl_regmatch.endp[0], 0, FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); already_searched = FALSE; if (new_fname != NULL) { // Check whether we have already searched in this file for (i = 0;; i++) { if (i == depth + 1) i = old_files; if (i == max_path_depth) break; if (fullpathcmp(new_fname, files[i].name, TRUE, TRUE) & FPC_SAME) { if (type != CHECK_PATH && action == ACTION_SHOW_ALL && files[i].matched) { msg_putchar('\n'); // cursor below last one if (!got_int) // don't display if 'q' // typed at "--more--" // message { msg_home_replace_hl(new_fname); msg_puts(_(" (includes previously listed match)")); prev_fname = NULL; } } VIM_CLEAR(new_fname); already_searched = TRUE; break; } } } if (type == CHECK_PATH && (action == ACTION_SHOW_ALL || (new_fname == NULL && !already_searched))) { if (did_show) msg_putchar('\n'); // cursor below last one else { gotocmdline(TRUE); // cursor at status line msg_puts_title(_("--- Included files ")); if (action != ACTION_SHOW_ALL) msg_puts_title(_("not found ")); msg_puts_title(_("in path ---\n")); } did_show = TRUE; while (depth_displayed < depth && !got_int) { ++depth_displayed; for (i = 0; i < depth_displayed; i++) msg_puts(" "); msg_home_replace(files[depth_displayed].name); msg_puts(" -->\n"); } if (!got_int) // don't display if 'q' typed // for "--more--" message { for (i = 0; i <= depth_displayed; i++) msg_puts(" "); if (new_fname != NULL) { // using "new_fname" is more reliable, e.g., when // 'includeexpr' is set. msg_outtrans_attr(new_fname, HL_ATTR(HLF_D)); } else { /* * Isolate the file name. * Include the surrounding "" or <> if present. */ if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) { // pattern contains \zs, use the match p = incl_regmatch.startp[0]; i = (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]); } else { // find the file name after the end of the match for (p = incl_regmatch.endp[0]; *p && !vim_isfilec(*p); p++) ; for (i = 0; vim_isfilec(p[i]); i++) ; } if (i == 0) { // Nothing found, use the rest of the line. p = incl_regmatch.endp[0]; i = (int)STRLEN(p); } // Avoid checking before the start of the line, can // happen if \zs appears in the regexp. else if (p > line) { if (p[-1] == '"' || p[-1] == '<') { --p; ++i; } if (p[i] == '"' || p[i] == '>') ++i; } save_char = p[i]; p[i] = NUL; msg_outtrans_attr(p, HL_ATTR(HLF_D)); p[i] = save_char; } if (new_fname == NULL && action == ACTION_SHOW_ALL) { if (already_searched) msg_puts(_(" (Already listed)")); else msg_puts(_(" NOT FOUND")); } } out_flush(); // output each line directly } if (new_fname != NULL) { // Push the new file onto the file stack if (depth + 1 == old_files) { bigger = ALLOC_MULT(SearchedFile, max_path_depth * 2); if (bigger != NULL) { for (i = 0; i <= depth; i++) bigger[i] = files[i]; for (i = depth + 1; i < old_files + max_path_depth; i++) { bigger[i].fp = NULL; bigger[i].name = NULL; bigger[i].lnum = 0; bigger[i].matched = FALSE; } for (i = old_files; i < max_path_depth; i++) bigger[i + max_path_depth] = files[i]; old_files += max_path_depth; max_path_depth *= 2; vim_free(files); files = bigger; } } if ((files[depth + 1].fp = mch_fopen((char *)new_fname, "r")) == NULL) vim_free(new_fname); else { if (++depth == old_files) { /* * lalloc() for 'bigger' must have failed above. We * will forget one of our already visited files now. */ vim_free(files[old_files].name); ++old_files; } files[depth].name = curr_fname = new_fname; files[depth].lnum = 0; files[depth].matched = FALSE; if (action == ACTION_EXPAND) { msg_hist_off = TRUE; // reset in msg_trunc_attr() vim_snprintf((char*)IObuff, IOSIZE, _("Scanning included file: %s"), (char *)new_fname); msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R)); } else if (p_verbose >= 5) { verbose_enter(); smsg(_("Searching included file %s"), (char *)new_fname); verbose_leave(); } } } } else { /* * Check if the line is a define (type == FIND_DEFINE) */ p = line; search_line: define_matched = FALSE; if (def_regmatch.regprog != NULL && vim_regexec(&def_regmatch, line, (colnr_T)0)) { /* * Pattern must be first identifier after 'define', so skip * to that position before checking for match of pattern. Also * don't let it match beyond the end of this identifier. */ p = def_regmatch.endp[0]; while (*p && !vim_iswordc(*p)) p++; define_matched = TRUE; } /* * Look for a match. Don't do this if we are looking for a * define and this line didn't match define_prog above. */ if (def_regmatch.regprog == NULL || define_matched) { if (define_matched || (compl_cont_status & CONT_SOL)) { // compare the first "len" chars from "ptr" startp = skipwhite(p); if (p_ic) matched = !MB_STRNICMP(startp, ptr, len); else matched = !STRNCMP(startp, ptr, len); if (matched && define_matched && whole && vim_iswordc(startp[len])) matched = FALSE; } else if (regmatch.regprog != NULL && vim_regexec(&regmatch, line, (colnr_T)(p - line))) { matched = TRUE; startp = regmatch.startp[0]; /* * Check if the line is not a comment line (unless we are * looking for a define). A line starting with "# define" * is not considered to be a comment line. */ if (!define_matched && skip_comments) { if ((*line != '#' || STRNCMP(skipwhite(line + 1), "define", 6) != 0) && get_leader_len(line, NULL, FALSE, TRUE)) matched = FALSE; /* * Also check for a "/ *" or "/ /" before the match. * Skips lines like "int backwards; / * normal index * * /" when looking for "normal". * Note: Doesn't skip "/ *" in comments. */ p = skipwhite(line); if (matched || (p[0] == '/' && p[1] == '*') || p[0] == '*') for (p = line; *p && p < startp; ++p) { if (matched && p[0] == '/' && (p[1] == '*' || p[1] == '/')) { matched = FALSE; // After "//" all text is comment if (p[1] == '/') break; ++p; } else if (!matched && p[0] == '*' && p[1] == '/') { // Can find match after "* /". matched = TRUE; ++p; } } } } } } if (matched) { if (action == ACTION_EXPAND) { int cont_s_ipos = FALSE; int add_r; char_u *aux; if (depth == -1 && lnum == curwin->w_cursor.lnum) break; found = TRUE; aux = p = startp; if (compl_cont_status & CONT_ADDING) { p += compl_length; if (vim_iswordp(p)) goto exit_matched; p = find_word_start(p); } p = find_word_end(p); i = (int)(p - aux); if ((compl_cont_status & CONT_ADDING) && i == compl_length) { // IOSIZE > compl_length, so the STRNCPY works STRNCPY(IObuff, aux, i); // Get the next line: when "depth" < 0 from the current // buffer, otherwise from the included file. Jump to // exit_matched when past the last line. if (depth < 0) { if (lnum >= end_lnum) goto exit_matched; line = ml_get(++lnum); } else if (vim_fgets(line = file_line, LSIZE, files[depth].fp)) goto exit_matched; // we read a line, set "already" to check this "line" later // if depth >= 0 we'll increase files[depth].lnum far // bellow -- Acevedo already = aux = p = skipwhite(line); p = find_word_start(p); p = find_word_end(p); if (p > aux) { if (*aux != ')' && IObuff[i-1] != TAB) { if (IObuff[i-1] != ' ') IObuff[i++] = ' '; // IObuf =~ "\(\k\|\i\).* ", thus i >= 2 if (p_js && (IObuff[i-2] == '.' || (vim_strchr(p_cpo, CPO_JOINSP) == NULL && (IObuff[i-2] == '?' || IObuff[i-2] == '!')))) IObuff[i++] = ' '; } // copy as much as possible of the new word if (p - aux >= IOSIZE - i) p = aux + IOSIZE - i - 1; STRNCPY(IObuff + i, aux, p - aux); i += (int)(p - aux); cont_s_ipos = TRUE; } IObuff[i] = NUL; aux = IObuff; if (i == compl_length) goto exit_matched; } add_r = ins_compl_add_infercase(aux, i, p_ic, curr_fname == curbuf->b_fname ? NULL : curr_fname, dir, cont_s_ipos); if (add_r == OK) // if dir was BACKWARD then honor it just once dir = FORWARD; else if (add_r == FAIL) break; } else if (action == ACTION_SHOW_ALL) { found = TRUE; if (!did_show) gotocmdline(TRUE); // cursor at status line if (curr_fname != prev_fname) { if (did_show) msg_putchar('\n'); // cursor below last one if (!got_int) // don't display if 'q' typed // at "--more--" message msg_home_replace_hl(curr_fname); prev_fname = curr_fname; } did_show = TRUE; if (!got_int) show_pat_in_path(line, type, TRUE, action, (depth == -1) ? NULL : files[depth].fp, (depth == -1) ? &lnum : &files[depth].lnum, match_count++); // Set matched flag for this file and all the ones that // include it for (i = 0; i <= depth; ++i) files[i].matched = TRUE; } else if (--count <= 0) { found = TRUE; if (depth == -1 && lnum == curwin->w_cursor.lnum #if defined(FEAT_QUICKFIX) && g_do_tagpreview == 0 #endif ) emsg(_("E387: Match is on current line")); else if (action == ACTION_SHOW) { show_pat_in_path(line, type, did_show, action, (depth == -1) ? NULL : files[depth].fp, (depth == -1) ? &lnum : &files[depth].lnum, 1L); did_show = TRUE; } else { #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif #if defined(FEAT_QUICKFIX) // ":psearch" uses the preview window if (g_do_tagpreview != 0) { curwin_save = curwin; prepare_tagpreview(TRUE, TRUE, FALSE); } #endif if (action == ACTION_SPLIT) { if (win_split(0, 0) == FAIL) break; RESET_BINDING(curwin); } if (depth == -1) { // match in current file #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (!GETFILE_SUCCESS(getfile( curwin_save->w_buffer->b_fnum, NULL, NULL, TRUE, lnum, FALSE))) break; // failed to jump to file } else #endif setpcmark(); curwin->w_cursor.lnum = lnum; check_cursor(); } else { if (!GETFILE_SUCCESS(getfile( 0, files[depth].name, NULL, TRUE, files[depth].lnum, FALSE))) break; // failed to jump to file // autocommands may have changed the lnum, we don't // want that here curwin->w_cursor.lnum = files[depth].lnum; } } if (action != ACTION_SHOW) { curwin->w_cursor.col = (colnr_T)(startp - line); curwin->w_set_curswant = TRUE; } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0 && curwin != curwin_save && win_valid(curwin_save)) { // Return cursor to where we were validate_cursor(); redraw_later(VALID); win_enter(curwin_save, TRUE); } # ifdef FEAT_PROP_POPUP else if (WIN_IS_POPUP(curwin)) // can't keep focus in popup window win_enter(firstwin, TRUE); # endif #endif break; } exit_matched: matched = FALSE; // look for other matches in the rest of the line if we // are not at the end of it already if (def_regmatch.regprog == NULL && action == ACTION_EXPAND && !(compl_cont_status & CONT_SOL) && *startp != NUL && *(p = startp + mb_ptr2len(startp)) != NUL) goto search_line; } line_breakcheck(); if (action == ACTION_EXPAND) ins_compl_check_keys(30, FALSE); if (got_int || ins_compl_interrupted()) break; /* * Read the next line. When reading an included file and encountering * end-of-file, close the file and continue in the file that included * it. */ while (depth >= 0 && !already && vim_fgets(line = file_line, LSIZE, files[depth].fp)) { fclose(files[depth].fp); --old_files; files[old_files].name = files[depth].name; files[old_files].matched = files[depth].matched; --depth; curr_fname = (depth == -1) ? curbuf->b_fname : files[depth].name; if (depth < depth_displayed) depth_displayed = depth; } if (depth >= 0) // we could read the line { files[depth].lnum++; // Remove any CR and LF from the line. i = (int)STRLEN(line); if (i > 0 && line[i - 1] == '\n') line[--i] = NUL; if (i > 0 && line[i - 1] == '\r') line[--i] = NUL; } else if (!already) { if (++lnum > end_lnum) break; line = ml_get(lnum); } already = NULL; } // End of big for (;;) loop. // Close any files that are still open. for (i = 0; i <= depth; i++) { fclose(files[i].fp); vim_free(files[i].name); } for (i = old_files; i < max_path_depth; i++) vim_free(files[i].name); vim_free(files); if (type == CHECK_PATH) { if (!did_show) { if (action != ACTION_SHOW_ALL) msg(_("All included files were found")); else msg(_("No included files")); } } else if (!found && action != ACTION_EXPAND) { if (got_int || ins_compl_interrupted()) emsg(_(e_interr)); else if (type == FIND_DEFINE) emsg(_("E388: Couldn't find definition")); else emsg(_("E389: Couldn't find pattern")); } if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) msg_end(); fpip_end: vim_free(file_line); vim_regfree(regmatch.regprog); vim_regfree(incl_regmatch.regprog); vim_regfree(def_regmatch.regprog); } static void show_pat_in_path( char_u *line, int type, int did_show, int action, FILE *fp, linenr_T *lnum, long count) { char_u *p; if (did_show) msg_putchar('\n'); // cursor below last one else if (!msg_silent) gotocmdline(TRUE); // cursor at status line if (got_int) // 'q' typed at "--more--" message return; for (;;) { p = line + STRLEN(line) - 1; if (fp != NULL) { // We used fgets(), so get rid of newline at end if (p >= line && *p == '\n') --p; if (p >= line && *p == '\r') --p; *(p + 1) = NUL; } if (action == ACTION_SHOW_ALL) { sprintf((char *)IObuff, "%3ld: ", count); // show match nr msg_puts((char *)IObuff); sprintf((char *)IObuff, "%4ld", *lnum); // show line nr // Highlight line numbers msg_puts_attr((char *)IObuff, HL_ATTR(HLF_N)); msg_puts(" "); } msg_prt_line(line, FALSE); out_flush(); // show one line at a time // Definition continues until line that doesn't end with '\' if (got_int || type != FIND_DEFINE || p < line || *p != '\\') break; if (fp != NULL) { if (vim_fgets(line, LSIZE, fp)) // end of file break; ++*lnum; } else { if (++*lnum > curbuf->b_ml.ml_line_count) break; line = ml_get(*lnum); } msg_putchar('\n'); } } #endif #ifdef FEAT_VIMINFO /* * Return the last used search pattern at "idx". */ spat_T * get_spat(int idx) { return &spats[idx]; } /* * Return the last used search pattern index. */ int get_spat_last_idx(void) { return last_idx; } #endif #ifdef FEAT_EVAL /* * "searchcount()" function */ void f_searchcount(typval_T *argvars, typval_T *rettv) { pos_T pos = curwin->w_cursor; char_u *pattern = NULL; int maxcount = SEARCH_STAT_DEF_MAX_COUNT; long timeout = SEARCH_STAT_DEF_TIMEOUT; int recompute = TRUE; searchstat_T stat; if (rettv_dict_alloc(rettv) == FAIL) return; if (shortmess(SHM_SEARCHCOUNT)) // 'shortmess' contains 'S' flag recompute = TRUE; if (argvars[0].v_type != VAR_UNKNOWN) { dict_T *dict; dictitem_T *di; listitem_T *li; int error = FALSE; if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { emsg(_(e_dictreq)); return; } dict = argvars[0].vval.v_dict; di = dict_find(dict, (char_u *)"timeout", -1); if (di != NULL) { timeout = (long)tv_get_number_chk(&di->di_tv, &error); if (error) return; } di = dict_find(dict, (char_u *)"maxcount", -1); if (di != NULL) { maxcount = (int)tv_get_number_chk(&di->di_tv, &error); if (error) return; } recompute = dict_get_bool(dict, (char_u *)"recompute", recompute); di = dict_find(dict, (char_u *)"pattern", -1); if (di != NULL) { pattern = tv_get_string_chk(&di->di_tv); if (pattern == NULL) return; } di = dict_find(dict, (char_u *)"pos", -1); if (di != NULL) { if (di->di_tv.v_type != VAR_LIST) { semsg(_(e_invarg2), "pos"); return; } if (list_len(di->di_tv.vval.v_list) != 3) { semsg(_(e_invarg2), "List format should be [lnum, col, off]"); return; } li = list_find(di->di_tv.vval.v_list, 0L); if (li != NULL) { pos.lnum = tv_get_number_chk(&li->li_tv, &error); if (error) return; } li = list_find(di->di_tv.vval.v_list, 1L); if (li != NULL) { pos.col = tv_get_number_chk(&li->li_tv, &error) - 1; if (error) return; } li = list_find(di->di_tv.vval.v_list, 2L); if (li != NULL) { pos.coladd = tv_get_number_chk(&li->li_tv, &error); if (error) return; } } } save_last_search_pattern(); if (pattern != NULL) { if (*pattern == NUL) goto the_end; vim_free(spats[last_idx].pat); spats[last_idx].pat = vim_strsave(pattern); } if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) goto the_end; // the previous pattern was never defined update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout); dict_add_number(rettv->vval.v_dict, "current", stat.cur); dict_add_number(rettv->vval.v_dict, "total", stat.cnt); dict_add_number(rettv->vval.v_dict, "exact_match", stat.exact_match); dict_add_number(rettv->vval.v_dict, "incomplete", stat.incomplete); dict_add_number(rettv->vval.v_dict, "maxcount", stat.last_maxcount); the_end: restore_last_search_pattern(); } /* * Fuzzy string matching * * Ported from the lib_fts library authored by Forrest Smith. * https://github.com/forrestthewoods/lib_fts/tree/master/code * * Blog describing the algorithm: * https://www.forrestthewoods.com/blog/reverse_engineering_sublime_texts_fuzzy_match/ * * Each matching string is assigned a score. The following factors are checked: * Matched letter * Unmatched letter * Consecutively matched letters * Proximity to start * Letter following a separator (space, underscore) * Uppercase letter following lowercase (aka CamelCase) * * Matched letters are good. Unmatched letters are bad. Matching near the start * is good. Matching the first letter in the middle of a phrase is good. * Matching the uppercase letters in camel case entries is good. * * The score assigned for each factor is explained below. * File paths are different from file names. File extensions may be ignorable. * Single words care about consecutive matches but not separators or camel * case. * Score starts at 0 * Matched letter: +0 points * Unmatched letter: -1 point * Consecutive match bonus: +5 points * Separator bonus: +10 points * Camel case bonus: +10 points * Unmatched leading letter: -3 points (max: -9) * * There is some nuance to this. Scores don’t have an intrinsic meaning. The * score range isn’t 0 to 100. It’s roughly [-50, 50]. Longer words have a * lower minimum score due to unmatched letter penalty. Longer search patterns * have a higher maximum score due to match bonuses. * * Separator and camel case bonus is worth a LOT. Consecutive matches are worth * quite a bit. * * There is a penalty if you DON’T match the first three letters. Which * effectively rewards matching near the start. However there’s no difference * in matching between the middle and end. * * There is not an explicit bonus for an exact match. Unmatched letters receive * a penalty. So shorter strings and closer matches are worth more. */ typedef struct { listitem_T *item; int score; list_T *lmatchpos; } fuzzyItem_T; // bonus for adjacent matches #define SEQUENTIAL_BONUS 15 // bonus if match occurs after a separator #define SEPARATOR_BONUS 30 // bonus if match is uppercase and prev is lower #define CAMEL_BONUS 30 // bonus if the first letter is matched #define FIRST_LETTER_BONUS 15 // penalty applied for every letter in str before the first match #define LEADING_LETTER_PENALTY -5 // maximum penalty for leading letters #define MAX_LEADING_LETTER_PENALTY -15 // penalty for every letter that doesn't match #define UNMATCHED_LETTER_PENALTY -1 // Score for a string that doesn't fuzzy match the pattern #define SCORE_NONE -9999 #define FUZZY_MATCH_RECURSION_LIMIT 10 // Maximum number of characters that can be fuzzy matched #define MAXMATCHES 256 typedef int_u matchidx_T; /* * Compute a score for a fuzzy matched string. The matching character locations * are in 'matches'. */ static int fuzzy_match_compute_score( char_u *str, int strSz, matchidx_T *matches, int numMatches) { int score; int penalty; int unmatched; int i; char_u *p = str; matchidx_T sidx = 0; // Initialize score score = 100; // Apply leading letter penalty penalty = LEADING_LETTER_PENALTY * matches[0]; if (penalty < MAX_LEADING_LETTER_PENALTY) penalty = MAX_LEADING_LETTER_PENALTY; score += penalty; // Apply unmatched penalty unmatched = strSz - numMatches; score += UNMATCHED_LETTER_PENALTY * unmatched; // Apply ordering bonuses for (i = 0; i < numMatches; ++i) { matchidx_T currIdx = matches[i]; if (i > 0) { matchidx_T prevIdx = matches[i - 1]; // Sequential if (currIdx == (prevIdx + 1)) score += SEQUENTIAL_BONUS; } // Check for bonuses based on neighbor character value if (currIdx > 0) { // Camel case int neighbor = ' '; int curr; int neighborSeparator; if (has_mbyte) { while (sidx < currIdx) { neighbor = (*mb_ptr2char)(p); (void)mb_ptr2char_adv(&p); sidx++; } curr = (*mb_ptr2char)(p); } else { neighbor = str[currIdx - 1]; curr = str[currIdx]; } if (vim_islower(neighbor) && vim_isupper(curr)) score += CAMEL_BONUS; // Separator neighborSeparator = neighbor == '_' || neighbor == ' '; if (neighborSeparator) score += SEPARATOR_BONUS; } else { // First letter score += FIRST_LETTER_BONUS; } } return score; } static int fuzzy_match_recursive( char_u *fuzpat, char_u *str, matchidx_T strIdx, int *outScore, char_u *strBegin, int strLen, matchidx_T *srcMatches, matchidx_T *matches, int maxMatches, int nextMatch, int *recursionCount) { // Recursion params int recursiveMatch = FALSE; matchidx_T bestRecursiveMatches[MAXMATCHES]; int bestRecursiveScore = 0; int first_match; int matched; // Count recursions ++*recursionCount; if (*recursionCount >= FUZZY_MATCH_RECURSION_LIMIT) return FALSE; // Detect end of strings if (*fuzpat == '\0' || *str == '\0') return FALSE; // Loop through fuzpat and str looking for a match first_match = TRUE; while (*fuzpat != NUL && *str != NUL) { int c1; int c2; c1 = PTR2CHAR(fuzpat); c2 = PTR2CHAR(str); // Found match if (vim_tolower(c1) == vim_tolower(c2)) { matchidx_T recursiveMatches[MAXMATCHES]; int recursiveScore = 0; char_u *next_char; // Supplied matches buffer was too short if (nextMatch >= maxMatches) return FALSE; // "Copy-on-Write" srcMatches into matches if (first_match && srcMatches) { memcpy(matches, srcMatches, nextMatch * sizeof(srcMatches[0])); first_match = FALSE; } // Recursive call that "skips" this match if (has_mbyte) next_char = str + (*mb_ptr2len)(str); else next_char = str + 1; if (fuzzy_match_recursive(fuzpat, next_char, strIdx + 1, &recursiveScore, strBegin, strLen, matches, recursiveMatches, sizeof(recursiveMatches)/sizeof(recursiveMatches[0]), nextMatch, recursionCount)) { // Pick best recursive score if (!recursiveMatch || recursiveScore > bestRecursiveScore) { memcpy(bestRecursiveMatches, recursiveMatches, MAXMATCHES * sizeof(recursiveMatches[0])); bestRecursiveScore = recursiveScore; } recursiveMatch = TRUE; } // Advance matches[nextMatch++] = strIdx; if (has_mbyte) (void)mb_ptr2char_adv(&fuzpat); else ++fuzpat; } if (has_mbyte) (void)mb_ptr2char_adv(&str); else ++str; strIdx++; } // Determine if full fuzpat was matched matched = *fuzpat == NUL ? TRUE : FALSE; // Calculate score if (matched) *outScore = fuzzy_match_compute_score(strBegin, strLen, matches, nextMatch); // Return best result if (recursiveMatch && (!matched || bestRecursiveScore > *outScore)) { // Recursive score is better than "this" memcpy(matches, bestRecursiveMatches, maxMatches * sizeof(matches[0])); *outScore = bestRecursiveScore; return TRUE; } else if (matched) return TRUE; // "this" score is better than recursive return FALSE; // no match } /* * fuzzy_match() * * Performs exhaustive search via recursion to find all possible matches and * match with highest score. * Scores values have no intrinsic meaning. Possible score range is not * normalized and varies with pattern. * Recursion is limited internally (default=10) to prevent degenerate cases * (fuzpat="aaaaaa" str="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"). * Uses char_u for match indices. Therefore patterns are limited to MAXMATCHES * characters. * * Returns TRUE if 'fuzpat' matches 'str'. Also returns the match score in * 'outScore' and the matching character positions in 'matches'. */ static int fuzzy_match( char_u *str, char_u *fuzpat, int *outScore, matchidx_T *matches, int maxMatches) { int recursionCount = 0; int len = MB_CHARLEN(str); *outScore = 0; return fuzzy_match_recursive(fuzpat, str, 0, outScore, str, len, NULL, matches, maxMatches, 0, &recursionCount); } /* * Sort the fuzzy matches in the descending order of the match score. */ static int fuzzy_item_compare(const void *s1, const void *s2) { int v1 = ((fuzzyItem_T *)s1)->score; int v2 = ((fuzzyItem_T *)s2)->score; return v1 == v2 ? 0 : v1 > v2 ? -1 : 1; } /* * Fuzzy search the string 'str' in a list of 'items' and return the matching * strings in 'fmatchlist'. * If 'items' is a list of strings, then search for 'str' in the list. * If 'items' is a list of dicts, then either use 'key' to lookup the string * for each item or use 'item_cb' Funcref function to get the string. * If 'retmatchpos' is TRUE, then return a list of positions where 'str' * matches for each item. */ static void match_fuzzy( list_T *items, char_u *str, char_u *key, callback_T *item_cb, int retmatchpos, list_T *fmatchlist) { long len; fuzzyItem_T *ptrs; listitem_T *li; long i = 0; int found_match = FALSE; matchidx_T matches[MAXMATCHES]; len = list_len(items); if (len == 0) return; ptrs = ALLOC_CLEAR_MULT(fuzzyItem_T, len); if (ptrs == NULL) return; // For all the string items in items, get the fuzzy matching score FOR_ALL_LIST_ITEMS(items, li) { int score; char_u *itemstr; typval_T rettv; ptrs[i].item = li; ptrs[i].score = SCORE_NONE; itemstr = NULL; rettv.v_type = VAR_UNKNOWN; if (li->li_tv.v_type == VAR_STRING) // list of strings itemstr = li->li_tv.vval.v_string; else if (li->li_tv.v_type == VAR_DICT && (key != NULL || item_cb->cb_name != NULL)) { // For a dict, either use the specified key to lookup the string or // use the specified callback function to get the string. if (key != NULL) itemstr = dict_get_string(li->li_tv.vval.v_dict, key, FALSE); else { typval_T argv[2]; // Invoke the supplied callback (if any) to get the dict item li->li_tv.vval.v_dict->dv_refcount++; argv[0].v_type = VAR_DICT; argv[0].vval.v_dict = li->li_tv.vval.v_dict; argv[1].v_type = VAR_UNKNOWN; if (call_callback(item_cb, -1, &rettv, 1, argv) != FAIL) { if (rettv.v_type == VAR_STRING) itemstr = rettv.vval.v_string; } dict_unref(li->li_tv.vval.v_dict); } } if (itemstr != NULL && fuzzy_match(itemstr, str, &score, matches, sizeof(matches) / sizeof(matches[0]))) { // Copy the list of matching positions in itemstr to a list, if // 'retmatchpos' is set. if (retmatchpos) { int j; int strsz; ptrs[i].lmatchpos = list_alloc(); if (ptrs[i].lmatchpos == NULL) goto done; strsz = MB_CHARLEN(str); for (j = 0; j < strsz; j++) { if (list_append_number(ptrs[i].lmatchpos, matches[j]) == FAIL) goto done; } } ptrs[i].score = score; found_match = TRUE; } ++i; clear_tv(&rettv); } if (found_match) { list_T *l; // Sort the list by the descending order of the match score qsort((void *)ptrs, (size_t)len, sizeof(fuzzyItem_T), fuzzy_item_compare); // For matchfuzzy(), return a list of matched strings. // ['str1', 'str2', 'str3'] // For matchfuzzypos(), return a list with two items. // The first item is a list of matched strings. The second item // is a list of lists where each list item is a list of matched // character positions. // [['str1', 'str2', 'str3'], [[1, 3], [1, 3], [1, 3]]] if (retmatchpos) { li = list_find(fmatchlist, 0); if (li == NULL || li->li_tv.vval.v_list == NULL) goto done; l = li->li_tv.vval.v_list; } else l = fmatchlist; // Copy the matching strings with a valid score to the return list for (i = 0; i < len; i++) { if (ptrs[i].score == SCORE_NONE) break; list_append_tv(l, &ptrs[i].item->li_tv); } // next copy the list of matching positions if (retmatchpos) { li = list_find(fmatchlist, -1); if (li == NULL || li->li_tv.vval.v_list == NULL) goto done; l = li->li_tv.vval.v_list; for (i = 0; i < len; i++) { if (ptrs[i].score == SCORE_NONE) break; if (ptrs[i].lmatchpos != NULL && list_append_list(l, ptrs[i].lmatchpos) == FAIL) goto done; } } } done: vim_free(ptrs); } /* * Do fuzzy matching. Returns the list of matched strings in 'rettv'. * If 'retmatchpos' is TRUE, also returns the matching character positions. */ static void do_fuzzymatch(typval_T *argvars, typval_T *rettv, int retmatchpos) { callback_T cb; char_u *key = NULL; int ret; CLEAR_POINTER(&cb); // validate and get the arguments if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) { semsg(_(e_listarg), retmatchpos ? "matchfuzzypos()" : "matchfuzzy()"); return; } if (argvars[1].v_type != VAR_STRING || argvars[1].vval.v_string == NULL) { semsg(_(e_invarg2), tv_get_string(&argvars[1])); return; } if (argvars[2].v_type != VAR_UNKNOWN) { dict_T *d; dictitem_T *di; if (argvars[2].v_type != VAR_DICT || argvars[2].vval.v_dict == NULL) { emsg(_(e_dictreq)); return; } // To search a dict, either a callback function or a key can be // specified. d = argvars[2].vval.v_dict; if ((di = dict_find(d, (char_u *)"key", -1)) != NULL) { if (di->di_tv.v_type != VAR_STRING || di->di_tv.vval.v_string == NULL || *di->di_tv.vval.v_string == NUL) { semsg(_(e_invarg2), tv_get_string(&di->di_tv)); return; } key = tv_get_string(&di->di_tv); } else if ((di = dict_find(d, (char_u *)"text_cb", -1)) != NULL) { cb = get_callback(&di->di_tv); if (cb.cb_name == NULL) { semsg(_(e_invargval), "text_cb"); return; } } } // get the fuzzy matches ret = rettv_list_alloc(rettv); if (ret != OK) goto done; if (retmatchpos) { list_T *l; // For matchfuzzypos(), a list with two items are returned. First item // is a list of matching strings and the second item is a list of // lists with matching positions within each string. l = list_alloc(); if (l == NULL) goto done; if (list_append_list(rettv->vval.v_list, l) == FAIL) goto done; l = list_alloc(); if (l == NULL) goto done; if (list_append_list(rettv->vval.v_list, l) == FAIL) goto done; } match_fuzzy(argvars[0].vval.v_list, tv_get_string(&argvars[1]), key, &cb, retmatchpos, rettv->vval.v_list); done: free_callback(&cb); } /* * "matchfuzzy()" function */ void f_matchfuzzy(typval_T *argvars, typval_T *rettv) { do_fuzzymatch(argvars, rettv, FALSE); } /* * "matchfuzzypos()" function */ void f_matchfuzzypos(typval_T *argvars, typval_T *rettv) { do_fuzzymatch(argvars, rettv, TRUE); } #endif
865669.c
/*- * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting * 2012, Adrian Chadd * 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, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any * redistribution must be conditioned upon including a substantially * similar Disclaimer requirement for further binary redistribution. * * NO WARRANTY * 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 NONINFRINGEMENT, MERCHANTIBILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. * * $FreeBSD: soc2013/dpl/head/tools/tools/ath/athaggrstats/main.c 237399 2012-06-10 06:44:04Z adrian $ */ /* * Simple Atheros-specific tool to inspect and monitor software queue * and aggregate statistics. * * athaggrstats [-i interface] [-bz] [-l] [-o fmtstring] [interval] * * (default interface is ath0). If interval is specified a rolling output * a la netstat -i is displayed every interval seconds. The format of * the rolling display can be controlled a la ps. The -l option will * print a list of all possible statistics for use with the -o option. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <string.h> #include <err.h> #include "athaggrstats.h" static struct { const char *tag; const char *fmt; } tags[] = { { "default", "singlepkt,nonbawpkt,aggrpkt,bawclosedpkt,lhsinglepkt,schednopkt,rtsaggrlimit" }, }; static const char * getfmt(const char *tag) { #define N(a) (sizeof(a)/sizeof(a[0])) int i; for (i = 0; i < N(tags); i++) if (strcasecmp(tags[i].tag, tag) == 0) return tags[i].fmt; return tag; #undef N } static int signalled; static void catchalarm(int signo __unused) { signalled = 1; } int main(int argc, char *argv[]) { struct athaggrstatfoo *wf; const char *ifname; int c, banner = 1; ifname = getenv("ATH"); if (ifname == NULL) ifname = "ath0"; wf = athaggrstats_new(ifname, getfmt("default")); while ((c = getopt(argc, argv, "bi:lo:z")) != -1) { switch (c) { case 'b': banner = 0; break; case 'i': wf->setifname(wf, optarg); break; case 'l': wf->print_fields(wf, stdout); return 0; case 'o': wf->setfmt(wf, getfmt(optarg)); break; case 'z': wf->zerostats(wf); break; default: errx(-1, "usage: %s [-a] [-i ifname] [-l] [-o fmt] [-z] [interval]\n", argv[0]); /*NOTREACHED*/ } } argc -= optind; argv += optind; if (argc > 0) { u_long interval = strtoul(argv[0], NULL, 0); int line, omask; if (interval < 1) interval = 1; signal(SIGALRM, catchalarm); signalled = 0; alarm(interval); banner: if (banner) wf->print_header(wf, stdout); line = 0; loop: if (line != 0) { wf->collect_cur(wf); wf->print_current(wf, stdout); wf->update_tot(wf); } else { wf->collect_tot(wf); wf->print_total(wf, stdout); } fflush(stdout); omask = sigblock(sigmask(SIGALRM)); if (!signalled) sigpause(0); sigsetmask(omask); signalled = 0; alarm(interval); line++; if (line == 21) /* XXX tty line count */ goto banner; else goto loop; /*NOTREACHED*/ } else { wf->collect_tot(wf); wf->print_verbose(wf, stdout); } return 0; }
491826.c
/** * @file * Ethernet Interface Skeleton * */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <[email protected]> * */ /* * This file is a skeleton for developing Ethernet network interface * drivers for lwIP. Add code to the low_level functions and do a * search-and-replace for the word "ethernetif" to replace it with * something that better describes your network interface. */ #include "lwip/opt.h" #if 1 /* ready */ #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/sys.h" #include <lwip/stats.h> #include <lwip/snmp.h> #include "netif/etharp.h" #include "netif/ppp_oe.h" /* Kernel includes. */ #include "BRTOS.h" #include "drivers.h" #include "derivative.h" /* Standard library includes. */ #include <string.h> /* Demo includes. */ #include "eth_phy.h" #include "enet.h" #include "mii.h" #include "ethernetif.h" /* Define those to better describe your network interface. */ #define IFNAME0 'e' #define IFNAME1 'n' /* PHY hardware specifics. */ #define PHY_STATUS ( 0x1F ) #define PHY_DUPLEX_STATUS ( 4<<2 ) #define PHY_SPEED_STATUS ( 1<<2 ) /* Delay to wait for a DMA buffer to become available if one is not already available. */ #define netifBUFFER_WAIT_ATTEMPTS 10 #define netifBUFFER_WAIT_DELAY 10 /* Delay between polling the PHY to see if a link has been established. */ #define netifLINK_DELAY 500 /* Delay between looking for incoming packets. In ideal world this would be infinite. */ #define netifBLOCK_TIME_WAITING_FOR_INPUT netifLINK_DELAY /* Very short delay to use when waiting for the Tx to finish with a buffer if we run out of Rx buffers. */ #define enetMINIMAL_DELAY 2 /*FSL: arrays to be used*/ static unsigned char xENETTxDescriptors_unaligned[ ( configNUM_ENET_TX_BUFFERS * sizeof( NBUF ) ) + 16 ]; static unsigned char xENETRxDescriptors_unaligned[ ( configNUM_ENET_RX_BUFFERS * sizeof( NBUF ) ) + 16 ]; static unsigned char ucENETTxBuffers[ ( configNUM_ENET_TX_BUFFERS * configENET_TX_BUFFER_SIZE ) + 16 ]; static unsigned char ucENETRxBuffers[ ( configNUM_ENET_RX_BUFFERS * configENET_RX_BUFFER_SIZE ) + 16 ]; /* The DMA descriptors. This is a char array to allow us to align it correctly. */ static NBUF *xENETTxDescriptors; static NBUF *xENETRxDescriptors; /* The DMA buffers. These are char arrays to allow them to be alligned correctly. */ static OS_CPU_TYPE uxNextRxBuffer = 0, uxNextTxBuffer = 0; /* Semaphore used by the ENET interrupt handler to wake the handler task. */ static BRTOS_Sem* xENETSemaphore; extern int periph_clk_khz; ContextType* xEthIntTask; /** * Helper struct to hold private data used to operate your ethernet interface. * Keeping the ethernet address of the MAC in this struct is not necessary * as it is already kept in the struct netif. * But this is only an example, anyway... */ struct ethernetif { struct eth_addr *ethaddr; /* Add whatever per-interface state that is needed here. */ }; /* Standard lwIP netif handlers. */ static void prvInitialiseENETBuffers( void ); static void low_level_init( struct netif *netif ); static err_t low_level_output(struct netif *netif, struct pbuf *p); static struct pbuf *low_level_input(struct netif *netif); /* Forward declarations. */ static void ethernetif_input(/*FSL:struct netif *netif*/void *pParams); #if 1 //CW10 uint32_t __REV(uint32_t value) { uint32_t result=0; __asm volatile ("rev %0, %1" : "=r" (result) : "r" (value) ); return(result); } __asm int32_t __REVSH(int16_t value) { revsh r0, r0 bx lr } #endif //CW10 /** * In this function, the hardware should be initialized. * Called from ethernetif_init(). * * @param netif the already initialized lwip network interface structure * for this ethernetif */ static void low_level_init(struct netif *netif) { /*unsigned portLONG*/ int usData; const INT8U ucMACAddress[6] = { configMAC_ADDR0, configMAC_ADDR1,configMAC_ADDR2,configMAC_ADDR3,configMAC_ADDR4,configMAC_ADDR5 }; //FSL:struct ethernetif *ethernetif = netif->state; /* set MAC hardware address length */ netif->hwaddr_len = ETHARP_HWADDR_LEN; /* set MAC hardware address */ netif->hwaddr[0] = configMAC_ADDR0; netif->hwaddr[1] = configMAC_ADDR1; netif->hwaddr[2] = configMAC_ADDR2; netif->hwaddr[3] = configMAC_ADDR3; netif->hwaddr[4] = configMAC_ADDR4; netif->hwaddr[5] = configMAC_ADDR5; /* maximum transfer unit */ netif->mtu = configENET_TX_BUFFER_SIZE; /* device capabilities */ /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP; /* Do whatever else is needed to initialize interface. */ /* Enable the ENET clock. */ SIM_SCGC2 |= SIM_SCGC2_ENET_MASK; /*FSL: allow concurrent access to MPU controller. Example: ENET uDMA to SRAM, otherwise bus error*/ MPU_CESR = 0; prvInitialiseENETBuffers(); OSSemCreate(0,&xENETSemaphore); /* Set the Reset bit and clear the Enable bit */ ENET_ECR = ENET_ECR_RESET_MASK; /* Wait at least 8 clock cycles */ for( usData = 0; usData < 10; usData++ ) { asm( "NOP" ); } /*FSL: start MII interface*/ mii_init(0, PERIPH_CLK_KHZ/1000/*MHz*/); //enet_interrupt_routine //set_irq_priority (76, 6); enable_irq(76);//ENET xmit interrupt //enet_interrupt_routine //set_irq_priority (77, 6); enable_irq(77);//ENET rx interrupt //enet_interrupt_routine //set_irq_priority (78, 6); enable_irq(78);//ENET error and misc interrupts /* * Make sure the external interface signals are enabled */ PORTB_PCR0 = PORT_PCR_MUX(4);//GPIO;//RMII0_MDIO/MII0_MDIO PORTB_PCR1 = PORT_PCR_MUX(4);//GPIO;//RMII0_MDC/MII0_MDC #if configUSE_MII_MODE PORTA_PCR14 = PORT_PCR_MUX(4);//RMII0_CRS_DV/MII0_RXDV #if 0 PORTA_PCR5 = PORT_PCR_MUX(4);//RMII0_RXER/MII0_RXER #else PORTA_PCR5 = (0|PORT_PCR_MUX(1)|PORT_PCR_PE_MASK|!PORT_PCR_PS_MASK);//GPIO pull down #endif PORTA_PCR12 = PORT_PCR_MUX(4);//RMII0_RXD1/MII0_RXD1 PORTA_PCR13 = PORT_PCR_MUX(4);//RMII0_RXD0/MII0_RXD0 PORTA_PCR15 = PORT_PCR_MUX(4);//RMII0_TXEN/MII0_TXEN PORTA_PCR16 = PORT_PCR_MUX(4);//RMII0_TXD0/MII0_TXD0 PORTA_PCR17 = PORT_PCR_MUX(4);//RMII0_TXD1/MII0_TXD1 PORTA_PCR11 = PORT_PCR_MUX(4);//MII0_RXCLK PORTA_PCR25 = PORT_PCR_MUX(4);//MII0_TXCLK PORTA_PCR9 = PORT_PCR_MUX(4);//MII0_RXD3 PORTA_PCR10 = PORT_PCR_MUX(4);//MII0_RXD2 PORTA_PCR28 = PORT_PCR_MUX(4);//MII0_TXER PORTA_PCR24 = PORT_PCR_MUX(4);//MII0_TXD2 PORTA_PCR26 = PORT_PCR_MUX(4);//MII0_TXD3 PORTA_PCR27 = PORT_PCR_MUX(4);//MII0_CRS PORTA_PCR29 = PORT_PCR_MUX(4);//MII0_COL #else PORTA_PCR14 = PORT_PCR_MUX(4);//RMII0_CRS_DV/MII0_RXDV #if 0 PORTA_PCR5 = PORT_PCR_MUX(4);//RMII0_RXER/MII0_RXER #else PORTA_PCR5 = (0|PORT_PCR_MUX(1)|PORT_PCR_PE_MASK|!PORT_PCR_PS_MASK);//GPIO pull down #endif PORTA_PCR12 = PORT_PCR_MUX(4);//RMII0_RXD1/MII0_RXD1 PORTA_PCR13 = PORT_PCR_MUX(4);//RMII0_RXD0/MII0_RXD0 PORTA_PCR15 = PORT_PCR_MUX(4);//RMII0_TXEN/MII0_TXEN PORTA_PCR16 = PORT_PCR_MUX(4);//RMII0_TXD0/MII0_TXD0 PORTA_PCR17 = PORT_PCR_MUX(4);//RMII0_TXD1/MII0_TXD1 #endif /* Can we talk to the PHY? */ do { DelayTask( netifLINK_DELAY ); usData = 0xffff; mii_read( 0, configPHY_ADDRESS, PHY_PHYIDR1, &usData ); } while( usData == 0xffff ); /* Start auto negotiate. */ mii_write( 0, configPHY_ADDRESS, PHY_BMCR, ( PHY_BMCR_AN_RESTART | PHY_BMCR_AN_ENABLE ) ); /* Wait for auto negotiate to complete. */ do { DelayTask( netifLINK_DELAY ); mii_read( 0, configPHY_ADDRESS, PHY_BMSR, &usData ); } while( !( usData & PHY_BMSR_AN_COMPLETE ) ); /* When we get here we have a link - find out what has been negotiated. */ usData = 0; mii_read( 0, configPHY_ADDRESS, PHY_STATUS, &usData ); /* Clear the Individual and Group Address Hash registers */ ENET_IALR = 0; ENET_IAUR = 0; ENET_GALR = 0; ENET_GAUR = 0; /* Set the Physical Address for the selected ENET */ enet_set_address( 0, ucMACAddress ); #if configUSE_MII_MODE /* Various mode/status setup. */ ENET_RCR = ENET_RCR_MAX_FL(configENET_RX_BUFFER_SIZE) | ENET_RCR_MII_MODE_MASK | ENET_RCR_CRCFWD_MASK; #else ENET_RCR = ENET_RCR_MAX_FL(configENET_RX_BUFFER_SIZE) | ENET_RCR_MII_MODE_MASK | ENET_RCR_CRCFWD_MASK | ENET_RCR_RMII_MODE_MASK; #endif /*FSL: clear rx/tx control registers*/ ENET_TCR = 0; /* Setup half or full duplex. */ if( usData & PHY_DUPLEX_STATUS ) { /*Full duplex*/ ENET_RCR &= (unsigned long)~ENET_RCR_DRT_MASK; ENET_TCR |= ENET_TCR_FDEN_MASK; } else { /*half duplex*/ ENET_RCR |= ENET_RCR_DRT_MASK; ENET_TCR &= (unsigned long)~ENET_TCR_FDEN_MASK; } /* Setup speed */ if( usData & PHY_SPEED_STATUS ) { /*10Mbps*/ ENET_RCR |= ENET_RCR_RMII_10T_MASK; } #if( configUSE_PROMISCUOUS_MODE == 1 ) { ENET_RCR |= ENET_RCR_PROM_MASK; } #endif #ifdef ENHANCED_BD ENET_ECR = ENET_ECR_EN1588_MASK; #else ENET_ECR = 0; #endif /* Set Rx Buffer Size */ ENET_MRBR = (INT16U) configENET_RX_BUFFER_SIZE; /* Point to the start of the circular Rx buffer descriptor queue */ ENET_RDSR = (INT32U) &( xENETRxDescriptors[ 0 ] ); /* Point to the start of the circular Tx buffer descriptor queue */ ENET_TDSR = (INT32U) xENETTxDescriptors; /* Clear all ENET interrupt events */ ENET_EIR = (INT32U) -1; /* Enable interrupts. */ ENET_EIMR = ENET_EIR_TXF_MASK | ENET_EIMR_RXF_MASK | ENET_EIMR_RXB_MASK | ENET_EIMR_UN_MASK | ENET_EIMR_RL_MASK | ENET_EIMR_LC_MASK | ENET_EIMR_BABT_MASK | ENET_EIMR_BABR_MASK | ENET_EIMR_EBERR_MASK; /* Create the task that handles the MAC ENET. */ //xTaskCreate( ethernetif_input, ( signed char * ) "ETH_INT", configETHERNET_INPUT_TASK_STACK_SIZE, (void *)netif, configETHERNET_INPUT_TASK_PRIORITY, &xEthIntTask ); (void)InstallTask(&ethernetif_input, "LwIP Eth task", ETHERNET_INPUT_TASK_STACK_SIZE, ETH_THREAD_PRIO, (void *)netif); /* Enable the MAC itself. */ ENET_ECR |= ENET_ECR_ETHEREN_MASK; /* Indicate that there have been empty receive buffers produced */ ENET_RDAR = ENET_RDAR_RDAR_MASK; } /** * This function should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * * @param netif the lwip network interface structure for this ethernetif * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) * @return ERR_OK if the packet could be sent * an err_t value if the packet couldn't be sent * * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to * strange results. You might consider waiting for space in the DMA queue * to become availale since the stack doesn't retry to send a packet * dropped because of memory failure (except for the TCP timers). */ static err_t low_level_output(struct netif *netif, struct pbuf *p) { //FSL: struct ethernetif *ethernetif = netif->state; u16_t l = 0; struct pbuf *q; unsigned char *pcTxData = NULL; OS_CPU_TYPE i; //initiate transfer(); #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif /* Get a DMA buffer into which we can write the data to send. */ for( i = 0; i < netifBUFFER_WAIT_ATTEMPTS; i++ ) { if( xENETTxDescriptors[ uxNextTxBuffer ].status & TX_BD_R ) { /* Wait for the buffer to become available. */ DelayTask( netifBUFFER_WAIT_DELAY ); } else { #ifdef NBUF_LITTLE_ENDIAN pcTxData = (unsigned char *)__REV((uint32_t)xENETTxDescriptors[ uxNextTxBuffer ].data); #else pcTxData = xENETTxDescriptors[ uxNextTxBuffer ].data; #endif break; } } if( pcTxData == NULL ) { /* For break point only. */ asm(NOP); return ERR_BUF; } else { for(q = p; q != NULL; q = q->next) { /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */ memcpy( &pcTxData[l], (u8_t*)q->payload, q->len ); l += q->len; } } //signal that packet should be sent(); /* Setup the buffer descriptor for transmission */ #ifdef NBUF_LITTLE_ENDIAN xENETTxDescriptors[ uxNextTxBuffer ].length = __REVSH(l);//nbuf->length + ETH_HDR_LEN; #else xENETTxDescriptors[ uxNextTxBuffer ].length = l;//nbuf->length + ETH_HDR_LEN; #endif xENETTxDescriptors[ uxNextTxBuffer ].status |= (TX_BD_R | TX_BD_L); #ifdef ENHANCED_BD xENETTxDescriptors[ uxNextTxBuffer ].bdu = 0x00000000; xENETTxDescriptors[ uxNextTxBuffer ].ebd_status = TX_BD_INT | TX_BD_TS;// | TX_BD_IINS | TX_BD_PINS; #endif /* Continue the Tx DMA task (in case it was waiting for a new TxBD) */ ENET_TDAR = ENET_TDAR_TDAR_MASK; uxNextTxBuffer++; if( uxNextTxBuffer >= configNUM_ENET_TX_BUFFERS ) { uxNextTxBuffer = 0; } #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ #endif LINK_STATS_INC(link.xmit); return ERR_OK; } /** * Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * * @param netif the lwip network interface structure for this ethernetif * @return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ static struct pbuf * low_level_input(struct netif *netif) { //FSL: struct ethernetif *ethernetif = netif->state; u32_t l = 0; struct pbuf *p, *q; u16_t len; #ifdef NBUF_LITTLE_ENDIAN u8_t *data_temp; #endif ( void ) netif; l = 0; p = NULL; /* Obtain the size of the packet and put it into the "len" variable. */ #ifdef NBUF_LITTLE_ENDIAN len = __REVSH(xENETRxDescriptors[ uxNextRxBuffer ].length); #else len = xENETRxDescriptors[ uxNextRxBuffer ].length; #endif if( ( len != 0 ) && ( ( xENETRxDescriptors[ uxNextRxBuffer ].status & RX_BD_E ) == 0 ) ) { #if ETH_PAD_SIZE len += ETH_PAD_SIZE; /* allow room for Ethernet padding */ #endif /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); if (p != NULL) { #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif /* We iterate over the pbuf chain until we have read the entire * packet into the pbuf. */ for(q = p; q != NULL; q = q->next) { /* Read enough bytes to fill this pbuf in the chain. The * available data in the pbuf is given by the q->len * variable. * This does not necessarily have to be a memcpy, you can also preallocate * pbufs for a DMA-enabled MAC and after receiving truncate it to the * actually received size. In this case, ensure the tot_len member of the * pbuf is the sum of the chained pbuf len members. */ #ifdef NBUF_LITTLE_ENDIAN data_temp = (u8_t *)__REV((u32_t)xENETRxDescriptors[ uxNextRxBuffer ].data); memcpy((u8_t*)q->payload, &( data_temp[l] ), q->len); #else memcpy((u8_t*)q->payload, &( xENETRxDescriptors[ uxNextRxBuffer ].data[l] ), q->len); #endif l = l + q->len; #ifdef ENHANCED_BD //FSL: not implemented at stack level //rx_packet->ebd_status = RxNBUF[index_rxbd].ebd_status; #ifdef NBUF_LITTLE_ENDIAN //rx_packet->timestamp = __REV(RxNBUF[index_rxbd].timestamp); //rx_packet->length_proto_type = __REVSH(RxNBUF[index_rxbd].length_proto_type); //rx_packet->payload_checksum = __REVSH(RxNBUF[index_rxbd].payload_checksum); #else //rx_packet->timestamp = RxNBUF[index_rxbd].timestamp; //rx_packet->length_proto_type = RxNBUF[index_rxbd].length_proto_type; //rx_packet->payload_checksum = RxNBUF[index_rxbd].payload_checksum; #endif #endif } #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ LINK_STATS_INC(link.recv); #endif } else { //drop packet(); LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); } //acknowledge that packet has been read(); /* Free the descriptor. */ xENETRxDescriptors[ uxNextRxBuffer ].status |= RX_BD_E; ENET_RDAR = ENET_RDAR_RDAR_MASK; uxNextRxBuffer++; if( uxNextRxBuffer >= configNUM_ENET_RX_BUFFERS ) { uxNextRxBuffer = 0; } } return p; } /** * This function should be called when a packet is ready to be read * from the interface. It uses the function low_level_input() that * should handle the actual reception of bytes from the network * interface. Then the type of the received packet is determined and * the appropriate input function is called. * * @param netif the lwip network interface structure for this ethernetif */ static void ethernetif_input(/*FSL:struct netif *netif*/void *pParams) { //FSL: struct ethernetif *ethernetif; struct netif *netif; struct eth_hdr *ethhdr; struct pbuf *p; //FSL: ethernetif = netif->state; netif = (struct netif*) pParams; for( ;; ) { do { /* move received packet into a new pbuf */ p = low_level_input(netif); /* no packet could be read, silently ignore this */ if (p == NULL) { /* No packet could be read. Wait a for an interrupt to tell us there is more data available. */ (void)OSSemPend (xENETSemaphore, netifBLOCK_TIME_WAITING_FOR_INPUT); } }while( p == NULL ); /* points to packet payload, which starts with an Ethernet header */ ethhdr = p->payload; switch (htons(ethhdr->type)) { /* IP or ARP packet? */ case ETHTYPE_IP: case ETHTYPE_ARP: #if PPPOE_SUPPORT /* PPPoE packet? */ case ETHTYPE_PPPOEDISC: case ETHTYPE_PPPOE: #endif /* PPPOE_SUPPORT */ /* full packet send to tcpip_thread to process */ if (netif->input(p, netif)!=ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n")); pbuf_free(p); p = NULL; } break; default: pbuf_free(p); p = NULL; break; } } } /** * Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * * This function should be passed as a parameter to netif_add(). * * @param netif the lwip network interface structure for this ethernetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t ethernetif_init(struct netif *netif) { struct ethernetif *ethernetif; LWIP_ASSERT("netif != NULL", (netif != NULL)); ethernetif = mem_malloc(sizeof(struct ethernetif)); if (ethernetif == NULL) { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out of memory\n")); return ERR_MEM; } #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwip"; #endif /* LWIP_NETIF_HOSTNAME */ /* * Initialize the snmp variables and counters inside the struct netif. * The last argument should be replaced with your link speed, in units * of bits per second. */ NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS); netif->state = ethernetif; netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; /* We directly use etharp_output() here to save a function call. * You can instead declare your own function an call etharp_output() * from it if you have to do some checks before sending (e.g. if link * is available...) */ netif->output = etharp_output; netif->linkoutput = low_level_output; ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]); /* initialize the hardware */ low_level_init(netif); return ERR_OK; } /*-----------------------------------------------------------*/ static void prvInitialiseENETBuffers( void ) { OS_CPU_TYPE ux; unsigned char *pcBufPointer; pcBufPointer = &( xENETTxDescriptors_unaligned[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } xENETTxDescriptors = ( NBUF * ) pcBufPointer; pcBufPointer = &( xENETRxDescriptors_unaligned[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } xENETRxDescriptors = ( NBUF * ) pcBufPointer; /* Setup the buffers and descriptors. */ pcBufPointer = &( ucENETTxBuffers[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } for( ux = 0; ux < configNUM_ENET_TX_BUFFERS; ux++ ) { xENETTxDescriptors[ ux ].status = TX_BD_TC; #ifdef NBUF_LITTLE_ENDIAN xENETTxDescriptors[ ux ].data = (uint8_t *)__REV((uint32_t)pcBufPointer); #else xENETTxDescriptors[ ux ].data = pcBufPointer; #endif pcBufPointer += configENET_TX_BUFFER_SIZE; xENETTxDescriptors[ ux ].length = 0; #ifdef ENHANCED_BD xENETTxDescriptors[ ux ].ebd_status = TX_BD_IINS | TX_BD_PINS; #endif } pcBufPointer = &( ucENETRxBuffers[ 0 ] ); while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 ) { pcBufPointer++; } for( ux = 0; ux < configNUM_ENET_RX_BUFFERS; ux++ ) { xENETRxDescriptors[ ux ].status = RX_BD_E; xENETRxDescriptors[ ux ].length = 0; #ifdef NBUF_LITTLE_ENDIAN xENETRxDescriptors[ ux ].data = (uint8_t *)__REV((uint32_t)pcBufPointer); #else xENETRxDescriptors[ ux ].data = pcBufPointer; #endif pcBufPointer += configENET_RX_BUFFER_SIZE; #ifdef ENHANCED_BD xENETRxDescriptors[ ux ].bdu = 0x00000000; xENETRxDescriptors[ ux ].ebd_status = RX_BD_INT; #endif } /* Set the wrap bit in the last descriptors to form a ring. */ xENETTxDescriptors[ configNUM_ENET_TX_BUFFERS - 1 ].status |= TX_BD_W; xENETRxDescriptors[ configNUM_ENET_RX_BUFFERS - 1 ].status |= RX_BD_W; uxNextRxBuffer = 0; uxNextTxBuffer = 0; } /*-----------------------------------------------------------*/ void ETH_Handler( void ) { unsigned long ulEvent; /* Determine the cause of the interrupt. */ ulEvent = ENET_EIR & ENET_EIMR; ENET_EIR = ulEvent; if( ( ulEvent & ENET_EIR_RXB_MASK ) || ( ulEvent & ENET_EIR_RXF_MASK ) ) { /* A packet has been received. Wake the handler task. */ OSSemPost(xENETSemaphore); } if (ulEvent & ( ENET_EIR_UN_MASK | ENET_EIR_RL_MASK | ENET_EIR_LC_MASK | ENET_EIR_EBERR_MASK | ENET_EIR_BABT_MASK | ENET_EIR_BABR_MASK | ENET_EIR_EBERR_MASK ) ) { /* Sledge hammer error handling. */ prvInitialiseENETBuffers(); ENET_RDAR = ENET_RDAR_RDAR_MASK; } } /************************************************************************ * NAME: ENET_ISR; * * DESCRIPTION: This handler is executed on every FNET interrupt * (from ethernet and timer module). *************************************************************************/ void ENET_ISR(void) { /******************************* * OS-specific Interrupt Enter. *******************************/ OS_SAVE_ISR(); OS_INT_ENTER(); #if (NESTING_INT == 1) OS_ENABLE_NESTING(); #endif /* Call original CPU handler*/ ETH_Handler(); /******************************* * Interrupt Exit. *******************************/ OS_INT_EXIT(); OS_RESTORE_ISR(); } #endif /* 0 */
419722.c
/*++ Copyright (c) 1996, 1997 Microsoft Corporation Module Name: init.c Abstract: This module contains the initialization code for AGP440.SYS. Author: John Vert (jvert) 10/21/1997 Revision History: --*/ #include "agp440.h" ULONG AgpExtensionSize = sizeof(AGP440_EXTENSION); PAGP_FLUSH_PAGES AgpFlushPages = NULL; // not implemented NTSTATUS AgpInitializeTarget( IN PVOID AgpExtension ) /*++ Routine Description: Entrypoint for target initialization. This is called first. Arguments: AgpExtension - Supplies the AGP extension Return Value: NTSTATUS --*/ { PAGP440_EXTENSION Extension = AgpExtension; // // Initialize our chipset-specific extension // Extension->ApertureStart.QuadPart = 0; Extension->ApertureLength = 0; Extension->Gart = NULL; Extension->GartLength = 0; Extension->GlobalEnable = FALSE; Extension->PCIEnable = FALSE; Extension->GartPhysical.QuadPart = 0; Extension->SpecialTarget = 0; return(STATUS_SUCCESS); } NTSTATUS AgpInitializeMaster( IN PVOID AgpExtension, OUT ULONG *AgpCapabilities ) /*++ Routine Description: Entrypoint for master initialization. This is called after target initialization and should be used to initialize the AGP capabilities of both master and target. This is also called when the master transitions into the D0 state. Arguments: AgpExtension - Supplies the AGP extension AgpCapabilities - Returns the capabilities of this AGP device. Return Value: STATUS_SUCCESS --*/ { NTSTATUS Status; PCI_AGP_CAPABILITY MasterCap; PCI_AGP_CAPABILITY TargetCap; PAGP440_EXTENSION Extension = AgpExtension; ULONG SBAEnable; ULONG DataRate; ULONG FastWrite; BOOLEAN ReverseInit; ULONG VendorId = 0; ULONG AgpCtrl = 0; #if DBG PCI_AGP_CAPABILITY CurrentCap; #endif // // Intel says if all BIOS manufacturers perform RMW ops on this // register, then it will always be set, however two video OEMs // have complained of systems where this was not set, and was // causing the system to freeze, so we'll hard code it just in // case (only affects 440LX) // Read440Config(&VendorId, 0, sizeof(VendorId)); if ((VendorId == AGP_440LX_IDENTIFIER) || (VendorId == AGP_440LX2_IDENTIFIER)) { Read440Config(&AgpCtrl, AGPCTRL_OFFSET, sizeof(AgpCtrl)); AgpCtrl |= READ_SYNC_ENABLE; Write440Config(&AgpCtrl, AGPCTRL_OFFSET, sizeof(AgpCtrl)); } // // Indicate that we can map memory through the GART aperture // *AgpCapabilities = AGP_CAPABILITIES_MAP_PHYSICAL; // // Get the master and target AGP capabilities // Status = AgpLibGetMasterCapability(AgpExtension, &MasterCap); if (!NT_SUCCESS(Status)) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibGetMasterCapability failed %08lx\n")); return(Status); } // // Some broken cards (Matrox Millenium II "AGP") report no valid // supported transfer rates. These are not really AGP cards. They // have an AGP Capabilities structure that reports no capabilities. // if (MasterCap.AGPStatus.Rate == 0) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibGetMasterCapability returned no valid transfer rate\n")); return(STATUS_INVALID_DEVICE_REQUEST); } Status = AgpLibGetPciDeviceCapability(0,0,&TargetCap); if (!NT_SUCCESS(Status)) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibGetPciDeviceCapability failed %08lx\n")); return(Status); } // // Determine the greatest common denominator for data rate. // DataRate = TargetCap.AGPStatus.Rate & MasterCap.AGPStatus.Rate; AGP_ASSERT(DataRate != 0); // // Select the highest common rate. // if (DataRate & PCI_AGP_RATE_4X) { DataRate = PCI_AGP_RATE_4X; } else if (DataRate & PCI_AGP_RATE_2X) { DataRate = PCI_AGP_RATE_2X; } else if (DataRate & PCI_AGP_RATE_1X) { DataRate = PCI_AGP_RATE_1X; } // // Previously a call was made to change the rate (successfully), // use this rate again now // if (Extension->SpecialTarget & AGP_FLAG_SPECIAL_RESERVE) { DataRate = (ULONG)((Extension->SpecialTarget & AGP_FLAG_SPECIAL_RESERVE) >> AGP_FLAG_SET_RATE_SHIFT); } // // Enable SBA if both master and target support it. // SBAEnable = (TargetCap.AGPStatus.SideBandAddressing & MasterCap.AGPStatus.SideBandAddressing); // // Enable FastWrite if both master and target support it. // FastWrite = (TargetCap.AGPStatus.FastWrite & MasterCap.AGPStatus.FastWrite); // // Enable the Master first. // ReverseInit = (Extension->SpecialTarget & AGP_FLAG_REVERSE_INITIALIZATION) == AGP_FLAG_REVERSE_INITIALIZATION; if (ReverseInit) { MasterCap.AGPCommand.Rate = DataRate; MasterCap.AGPCommand.AGPEnable = 1; MasterCap.AGPCommand.SBAEnable = SBAEnable; MasterCap.AGPCommand.FastWriteEnable = FastWrite; MasterCap.AGPCommand.FourGBEnable = 0; MasterCap.AGPCommand.RequestQueueDepth = TargetCap.AGPStatus.RequestQueueDepthMaximum; Status = AgpLibSetMasterCapability(AgpExtension, &MasterCap); if (!NT_SUCCESS(Status)) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibSetMasterCapability %08lx failed %08lx\n", &MasterCap, Status)); } } // // Now enable the Target. // TargetCap.AGPCommand.Rate = DataRate; TargetCap.AGPCommand.AGPEnable = 1; TargetCap.AGPCommand.SBAEnable = SBAEnable; TargetCap.AGPCommand.FastWriteEnable = FastWrite; TargetCap.AGPCommand.FourGBEnable = 0; Status = AgpLibSetPciDeviceCapability(0, 0, &TargetCap); if (!NT_SUCCESS(Status)) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibSetPciDeviceCapability %08lx for target failed %08lx\n", &TargetCap, Status)); return(Status); } if (!ReverseInit) { MasterCap.AGPCommand.Rate = DataRate; MasterCap.AGPCommand.AGPEnable = 1; MasterCap.AGPCommand.SBAEnable = SBAEnable; MasterCap.AGPCommand.FastWriteEnable = FastWrite; MasterCap.AGPCommand.FourGBEnable = 0; MasterCap.AGPCommand.RequestQueueDepth = TargetCap.AGPStatus.RequestQueueDepthMaximum; Status = AgpLibSetMasterCapability(AgpExtension, &MasterCap); if (!NT_SUCCESS(Status)) { AGPLOG(AGP_CRITICAL, ("AGP440InitializeDevice - AgpLibSetMasterCapability %08lx failed %08lx\n", &MasterCap, Status)); } } #if DBG // // Read them back, see if it worked // Status = AgpLibGetMasterCapability(AgpExtension, &CurrentCap); AGP_ASSERT(NT_SUCCESS(Status)); // // If the target request queue depth is greater than the master will // allow, it will be trimmed. Loosen the assert to not require an // exact match. // AGP_ASSERT(CurrentCap.AGPCommand.RequestQueueDepth <= MasterCap.AGPCommand.RequestQueueDepth); CurrentCap.AGPCommand.RequestQueueDepth = MasterCap.AGPCommand.RequestQueueDepth; AGP_ASSERT(RtlEqualMemory(&CurrentCap.AGPCommand, &MasterCap.AGPCommand, sizeof(CurrentCap.AGPCommand))); Status = AgpLibGetPciDeviceCapability(0,0,&CurrentCap); AGP_ASSERT(NT_SUCCESS(Status)); AGP_ASSERT(RtlEqualMemory(&CurrentCap.AGPCommand, &TargetCap.AGPCommand, sizeof(CurrentCap.AGPCommand))); #endif return(Status); }
316029.c
#include <bitcoin/feerate.h> #include <bitcoin/script.h> #include <ccan/crypto/shachain/shachain.h> #include <ccan/mem/mem.h> #include <ccan/tal/str/str.h> #include <common/derive_basepoints.h> #include <common/htlc_tx.h> #include <common/initial_commit_tx.h> #include <common/key_derive.h> #include <common/keyset.h> #include <common/peer_billboard.h> #include <common/status.h> #include <common/subdaemon.h> #include <common/type_to_string.h> #include <common/utils.h> #include <common/version.h> #include <errno.h> #include <hsmd/gen_hsm_client_wire.h> #include <inttypes.h> #include <lightningd/channel_state.h> #include <onchaind/gen_onchain_wire.h> #include <onchaind/onchain_types.h> #include <stdio.h> #include <unistd.h> #include <wire/wire_sync.h> #include "gen_onchain_types_names.h" /* stdin == requests */ #define REQ_FD STDIN_FILENO #define HSM_FD 3 /* Required in various places: keys for commitment transaction. */ static const struct keyset *keyset; /* IFF it's their commitment tx: HSM can't derive their per-commitment point! */ static const struct pubkey *remote_per_commitment_point; /* The commitment number we're dealing with (if not mutual close) */ static u64 commit_num; /* The feerate to use when we generate transactions. */ static u32 feerate_per_kw; /* Min and max feerates we ever used */ static u32 min_possible_feerate, max_possible_feerate; /* The dust limit to use when we generate transactions. */ static u64 dust_limit_satoshis; /* The CSV delays for each side. */ static u32 to_self_delay[NUM_SIDES]; /* Where we send money to (our wallet) */ static struct pubkey our_wallet_pubkey; /* Their revocation secret (only if they cheated). */ static const struct secret *remote_per_commitment_secret; /* one value is useful for a few witness scripts */ static const u8 ONE = 0x1; /* When to tell master about HTLCs which are missing/timed out */ static u32 reasonable_depth; /* The messages to send at that depth. */ static u8 **missing_htlc_msgs; /* If we broadcast a tx, or need a delay to resolve the output. */ struct proposed_resolution { /* This can be NULL if our proposal is to simply ignore it after depth */ const struct bitcoin_tx *tx; /* Non-zero if this is CSV-delayed. */ u32 depth_required; enum tx_type tx_type; }; /* How it actually got resolved. */ struct resolution { struct bitcoin_txid txid; unsigned int depth; enum tx_type tx_type; }; struct tracked_output { enum tx_type tx_type; struct bitcoin_txid txid; u32 tx_blockheight; /* FIXME: Convert all depths to blocknums, then just get new blk msgs */ u32 depth; u32 outnum; u64 satoshi; enum output_type output_type; /* If it is an HTLC, these are non-NULL */ const struct htlc_stub *htlc; const u8 *wscript; /* If it's an HTLC off our unilateral, this is their sig for htlc_tx */ const secp256k1_ecdsa_signature *remote_htlc_sig; /* Our proposed solution (if any) */ struct proposed_resolution *proposal; /* If it is resolved. */ struct resolution *resolved; }; /* We vary feerate until signature they offered matches. */ static u64 grind_htlc_tx_fee(struct bitcoin_tx *tx, const secp256k1_ecdsa_signature *remotesig, const u8 *wscript, u64 multiplier) { u64 prev_fee = UINT64_MAX; u64 input_amount = *tx->input[0].amount; for (u64 i = min_possible_feerate; i <= max_possible_feerate; i++) { /* BOLT #3: * * The fee for an HTLC-timeout transaction: * - MUST BE calculated to match: * 1. Multiply `feerate_per_kw` by 663 and divide by 1000 * (rounding down). * * The fee for an HTLC-success transaction: * - MUST BE calculated to match: * 1. Multiply `feerate_per_kw` by 703 and divide by 1000 * (rounding down). */ u64 fee = i * multiplier / 1000; if (fee > input_amount) break; /* Minor optimization: don't check same fee twice */ if (fee == prev_fee) continue; prev_fee = fee; tx->output[0].amount = input_amount - fee; if (!check_tx_sig(tx, 0, NULL, wscript, &keyset->other_htlc_key, remotesig)) continue; return fee; } status_failed(STATUS_FAIL_INTERNAL_ERROR, "grind_fee failed from %u - %u" " for tx %s, inputamount %"PRIu64", signature %s, wscript %s, multiplier %"PRIu64, min_possible_feerate, max_possible_feerate, type_to_string(tmpctx, struct bitcoin_tx, tx), input_amount, type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig), tal_hex(tmpctx, wscript), multiplier); } static void set_htlc_timeout_fee(struct bitcoin_tx *tx, const secp256k1_ecdsa_signature *remotesig, const u8 *wscript) { static u64 fee = UINT64_MAX; /* BOLT #3: * * The fee for an HTLC-timeout transaction: * - MUST BE calculated to match: * 1. Multiply `feerate_per_kw` by 663 and divide by 1000 (rounding * down). */ if (fee == UINT64_MAX) { fee = grind_htlc_tx_fee(tx, remotesig, wscript, 663); return; } tx->output[0].amount = *tx->input[0].amount - fee; if (check_tx_sig(tx, 0, NULL, wscript, &keyset->other_htlc_key, remotesig)) return; status_failed(STATUS_FAIL_INTERNAL_ERROR, "htlc_timeout_fee %"PRIu64" failed sigcheck " " for tx %s, signature %s, wscript %s", fee, type_to_string(tmpctx, struct bitcoin_tx, tx), type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig), tal_hex(tmpctx, wscript)); } static void set_htlc_success_fee(struct bitcoin_tx *tx, const secp256k1_ecdsa_signature *remotesig, const u8 *wscript) { static u64 fee = UINT64_MAX; /* BOLT #3: * * The fee for an HTLC-success transaction: * - MUST BE calculated to match: * 1. Multiply `feerate_per_kw` by 703 and divide by 1000 * (rounding down). */ if (fee == UINT64_MAX) { fee = grind_htlc_tx_fee(tx, remotesig, wscript, 703); return; } tx->output[0].amount = *tx->input[0].amount - fee; if (check_tx_sig(tx, 0, NULL, wscript, &keyset->other_htlc_key, remotesig)) return; status_failed(STATUS_FAIL_INTERNAL_ERROR, "htlc_success_fee %"PRIu64" failed sigcheck " " for tx %s, signature %s, wscript %s", fee, type_to_string(tmpctx, struct bitcoin_tx, tx), type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig), tal_hex(tmpctx, wscript)); } static const char *tx_type_name(enum tx_type tx_type) { size_t i; for (i = 0; enum_tx_type_names[i].name; i++) if (enum_tx_type_names[i].v == tx_type) return enum_tx_type_names[i].name; return "unknown"; } static const char *output_type_name(enum output_type output_type) { size_t i; for (i = 0; enum_output_type_names[i].name; i++) if (enum_output_type_names[i].v == output_type) return enum_output_type_names[i].name; return "unknown"; } static u8 *delayed_payment_to_us(const tal_t *ctx, struct bitcoin_tx *tx, const u8 *wscript) { return towire_hsm_sign_delayed_payment_to_us(ctx, commit_num, tx, wscript, *tx->input[0].amount); } static u8 *remote_htlc_to_us(const tal_t *ctx, struct bitcoin_tx *tx, const u8 *wscript) { return towire_hsm_sign_remote_htlc_to_us(ctx, remote_per_commitment_point, tx, wscript, *tx->input[0].amount); } static u8 *penalty_to_us(const tal_t *ctx, struct bitcoin_tx *tx, const u8 *wscript) { return towire_hsm_sign_penalty_to_us(ctx, remote_per_commitment_secret, tx, wscript, *tx->input[0].amount); } /* * This covers: * 1. to-us output spend (`<local_delayedsig> 0`) * 2. the their-commitment, our HTLC timeout case (`<remotehtlcsig> 0`), * 3. the their-commitment, our HTLC redeem case (`<remotehtlcsig> <payment_preimage>`) * 4. the their-revoked-commitment, to-local (`<revocation_sig> 1`) * 5. the their-revoked-commitment, htlc (`<revocation_sig> <revocationkey>`) * * Overrides *tx_type if it all turns to dust. */ static struct bitcoin_tx *tx_to_us(const tal_t *ctx, u8 *(*hsm_sign_msg)(const tal_t *ctx, struct bitcoin_tx *tx, const u8 *wscript), struct tracked_output *out, u32 to_self_delay, u32 locktime, const void *elem, size_t elemsize, const u8 *wscript, enum tx_type *tx_type) { struct bitcoin_tx *tx; u64 fee; secp256k1_ecdsa_signature sig; u8 *msg; tx = bitcoin_tx(ctx, 1, 1); tx->lock_time = locktime; tx->input[0].sequence_number = to_self_delay; tx->input[0].txid = out->txid; tx->input[0].index = out->outnum; tx->input[0].amount = tal_dup(tx->input, u64, &out->satoshi); tx->output[0].amount = out->satoshi; tx->output[0].script = scriptpubkey_p2wpkh(tx->output, &our_wallet_pubkey); /* Worst-case sig is 73 bytes */ fee = feerate_per_kw * (measure_tx_weight(tx) + 1 + 3 + 73 + 0 + tal_count(wscript)) / 1000; /* Result is trivial? Spend with small feerate, but don't wait * around for it as it might not confirm. */ if (tx->output[0].amount < dust_limit_satoshis + fee) { /* FIXME: We should use SIGHASH_NONE so others can take it */ fee = feerate_floor() * (measure_tx_weight(tx) + 1 + 3 + 73 + 0 + tal_count(wscript)) / 1000; /* This shouldn't happen (we don't set feerate below floor!), * but just in case. */ if (tx->output[0].amount < dust_limit_satoshis + fee) { fee = tx->output[0].amount - dust_limit_satoshis; status_broken("TX %s can't afford minimal feerate" "; setting fee to %"PRIu64, tx_type_name(*tx_type), fee); } else status_unusual("TX %s amount %"PRIu64" too small to" " pay reasonable fee, using minimal fee" " and ignoring", tx_type_name(*tx_type), out->satoshi); *tx_type = IGNORING_TINY_PAYMENT; } tx->output[0].amount -= fee; if (!wire_sync_write(HSM_FD, take(hsm_sign_msg(NULL, tx, wscript)))) status_failed(STATUS_FAIL_HSM_IO, "Writing sign request to hsm"); msg = wire_sync_read(tmpctx, HSM_FD); if (!msg || !fromwire_hsm_sign_tx_reply(msg, &sig)) { status_failed(STATUS_FAIL_HSM_IO, "Reading sign_tx_reply: %s", tal_hex(tmpctx, msg)); } tx->input[0].witness = bitcoin_witness_sig_and_element(tx->input, &sig, elem, elemsize, wscript); return tx; } static void hsm_sign_local_htlc_tx(struct bitcoin_tx *tx, const u8 *wscript, secp256k1_ecdsa_signature *sig) { u8 *msg = towire_hsm_sign_local_htlc_tx(NULL, commit_num, tx, wscript, *tx->input[0].amount); if (!wire_sync_write(HSM_FD, take(msg))) status_failed(STATUS_FAIL_HSM_IO, "Writing sign_local_htlc_tx to hsm"); msg = wire_sync_read(tmpctx, HSM_FD); if (!msg || !fromwire_hsm_sign_tx_reply(msg, sig)) status_failed(STATUS_FAIL_HSM_IO, "Reading sign_local_htlc_tx: %s", tal_hex(tmpctx, msg)); } static void hsm_get_per_commitment_point(struct pubkey *per_commitment_point) { u8 *msg = towire_hsm_get_per_commitment_point(NULL, commit_num); struct secret *unused; if (!wire_sync_write(HSM_FD, take(msg))) status_failed(STATUS_FAIL_HSM_IO, "Writing sign_htlc_tx to hsm"); msg = wire_sync_read(tmpctx, HSM_FD); if (!msg || !fromwire_hsm_get_per_commitment_point_reply(tmpctx, msg, per_commitment_point, &unused)) status_failed(STATUS_FAIL_HSM_IO, "Reading hsm_get_per_commitment_point_reply: %s", tal_hex(tmpctx, msg)); } static struct tracked_output * new_tracked_output(struct tracked_output ***outs, const struct bitcoin_txid *txid, u32 tx_blockheight, enum tx_type tx_type, u32 outnum, u64 satoshi, enum output_type output_type, const struct htlc_stub *htlc, const u8 *wscript, const secp256k1_ecdsa_signature *remote_htlc_sig) { size_t n = tal_count(*outs); struct tracked_output *out = tal(*outs, struct tracked_output); status_trace("Tracking output %u of %s: %s/%s", outnum, type_to_string(tmpctx, struct bitcoin_txid, txid), tx_type_name(tx_type), output_type_name(output_type)); out->tx_type = tx_type; out->txid = *txid; out->tx_blockheight = tx_blockheight; out->depth = 0; out->outnum = outnum; out->satoshi = satoshi; out->output_type = output_type; out->proposal = NULL; out->resolved = NULL; out->htlc = htlc; out->wscript = wscript; out->remote_htlc_sig = remote_htlc_sig; tal_resize(outs, n+1); (*outs)[n] = out; return out; } static void ignore_output(struct tracked_output *out) { status_trace("Ignoring output %u of %s: %s/%s", out->outnum, type_to_string(tmpctx, struct bitcoin_txid, &out->txid), tx_type_name(out->tx_type), output_type_name(out->output_type)); out->resolved = tal(out, struct resolution); out->resolved->txid = out->txid; out->resolved->depth = 0; out->resolved->tx_type = SELF; } static void proposal_meets_depth(struct tracked_output *out) { /* If we simply wanted to ignore it after some depth */ if (!out->proposal->tx) { ignore_output(out); return; } status_trace("Broadcasting %s (%s) to resolve %s/%s", tx_type_name(out->proposal->tx_type), type_to_string(tmpctx, struct bitcoin_tx, out->proposal->tx), tx_type_name(out->tx_type), output_type_name(out->output_type)); wire_sync_write(REQ_FD, take(towire_onchain_broadcast_tx(NULL, out->proposal->tx))); /* Don't wait for this if we're ignoring the tiny payment. */ if (out->proposal->tx_type == IGNORING_TINY_PAYMENT) { ignore_output(out); out->proposal = tal_free(out->proposal); } /* We will get a callback when it's in a block. */ } static void propose_resolution(struct tracked_output *out, const struct bitcoin_tx *tx, unsigned int depth_required, enum tx_type tx_type) { status_trace("Propose handling %s/%s by %s (%s) after %u blocks", tx_type_name(out->tx_type), output_type_name(out->output_type), tx_type_name(tx_type), tx ? type_to_string(tmpctx, struct bitcoin_tx, tx):"IGNORING", depth_required); out->proposal = tal(out, struct proposed_resolution); out->proposal->tx = tal_steal(out->proposal, tx); out->proposal->depth_required = depth_required; out->proposal->tx_type = tx_type; if (depth_required == 0) proposal_meets_depth(out); } static void propose_resolution_at_block(struct tracked_output *out, const struct bitcoin_tx *tx, unsigned int block_required, enum tx_type tx_type) { u32 depth; /* Expiry could be in the past! */ if (block_required < out->tx_blockheight) depth = 0; else /* Note that out->tx_blockheight is already at depth 1 */ depth = block_required - out->tx_blockheight + 1; propose_resolution(out, tx, depth, tx_type); } static bool is_valid_sig(const u8 *e) { secp256k1_ecdsa_signature sig; size_t len = tal_count(e); /* Last byte is sighash flags */ if (len < 1) return false; return signature_from_der(e, len-1, &sig); } /* We ignore things which look like signatures. */ static bool input_similar(const struct bitcoin_tx_input *i1, const struct bitcoin_tx_input *i2) { if (!bitcoin_txid_eq(&i1->txid, &i2->txid)) return false; if (i1->index != i2->index) return false; if (!scripteq(i1->script, i2->script)) return false; if (i1->sequence_number != i2->sequence_number) return false; if (tal_count(i1->witness) != tal_count(i2->witness)) return false; for (size_t i = 0; i < tal_count(i1->witness); i++) { if (scripteq(i1->witness[i], i2->witness[i])) continue; if (is_valid_sig(i1->witness[i]) && is_valid_sig(i2->witness[i])) continue; return false; } return true; } /* This simple case: true if this was resolved by our proposal. */ static bool resolved_by_proposal(struct tracked_output *out, const struct bitcoin_tx *tx) { /* If there's no TX associated, it's not us. */ if (!out->proposal->tx) return false; out->resolved = tal(out, struct resolution); /* Our proposal can change as feerates change. Input * comparison (ignoring signatures) works pretty well. * * FIXME: Better would be to compare outputs, but they weren't * saved to db correctly until now. (COMPAT_V052) */ if (tal_count(tx->input) != tal_count(out->proposal->tx->input)) return false; for (size_t i = 0; i < tal_count(tx->input); i++) { if (!input_similar(tx->input + i, out->proposal->tx->input + i)) return false; } bitcoin_txid(tx, &out->resolved->txid); status_trace("Resolved %s/%s by our proposal %s (%s)", tx_type_name(out->tx_type), output_type_name(out->output_type), tx_type_name(out->proposal->tx_type), type_to_string(tmpctx, struct bitcoin_txid, &out->resolved->txid)); out->resolved->depth = 0; out->resolved->tx_type = out->proposal->tx_type; /* Don't need proposal any more */ out->proposal = tal_free(out->proposal); return true; } /* Otherwise, we figure out what happened and then call this. */ static void resolved_by_other(struct tracked_output *out, const struct bitcoin_txid *txid, enum tx_type tx_type) { out->resolved = tal(out, struct resolution); out->resolved->txid = *txid; out->resolved->depth = 0; out->resolved->tx_type = tx_type; status_trace("Resolved %s/%s by %s (%s)", tx_type_name(out->tx_type), output_type_name(out->output_type), tx_type_name(tx_type), type_to_string(tmpctx, struct bitcoin_txid, txid)); } static void unknown_spend(struct tracked_output *out, const struct bitcoin_tx *tx) { out->resolved = tal(out, struct resolution); bitcoin_txid(tx, &out->resolved->txid); out->resolved->depth = 0; out->resolved->tx_type = UNKNOWN_TXTYPE; /* FIXME: we need a louder warning! */ status_trace("Unknown spend of %s/%s by %s", tx_type_name(out->tx_type), output_type_name(out->output_type), type_to_string(tmpctx, struct bitcoin_tx, tx)); } static u64 unmask_commit_number(const struct bitcoin_tx *tx, enum side funder, const struct pubkey *local_payment_basepoint, const struct pubkey *remote_payment_basepoint) { u64 obscurer; const struct pubkey *keys[NUM_SIDES]; keys[LOCAL] = local_payment_basepoint; keys[REMOTE] = remote_payment_basepoint; /* BOLT #3: * * The 48-bit commitment transaction number is obscured by * `XOR` with the lower 48 bits of... */ obscurer = commit_number_obscurer(keys[funder], keys[!funder]); /* BOLT #3: * * * locktime: upper 8 bits are 0x20, lower 24 bits are the * lower 24 bits of the obscured commitment transaction * number *... * * `txin[0]` sequence: upper 8 bits are 0x80, lower 24 bits * are upper 24 bits of the obscured commitment * transaction number */ return ((tx->lock_time & 0x00FFFFFF) | (tx->input[0].sequence_number & (u64)0x00FFFFFF) << 24) ^ obscurer; } static bool is_mutual_close(const struct bitcoin_tx *tx, const u8 *local_scriptpubkey, const u8 *remote_scriptpubkey) { size_t i; bool local_matched = false, remote_matched = false; for (i = 0; i < tal_count(tx->output); i++) { /* To be paranoid, we only let each one match once. */ if (scripteq(tx->output[i].script, local_scriptpubkey) && !local_matched) local_matched = true; else if (scripteq(tx->output[i].script, remote_scriptpubkey) && !remote_matched) remote_matched = true; else return false; } return true; } /* We only ever send out one, so matching it is easy. */ static bool is_local_commitment(const struct bitcoin_txid *txid, const struct bitcoin_txid *our_broadcast_txid) { return bitcoin_txid_eq(txid, our_broadcast_txid); } /* BOLT #5: * * Outputs that are *resolved* are considered *irrevocably resolved* * once the remote's *resolving* transaction is included in a block at least 100 * deep, on the most-work blockchain. */ static size_t num_not_irrevocably_resolved(struct tracked_output **outs) { size_t i, num = 0; for (i = 0; i < tal_count(outs); i++) { if (!outs[i]->resolved || outs[i]->resolved->depth < 100) num++; } return num; } static u32 prop_blockheight(const struct tracked_output *out) { return out->tx_blockheight + out->proposal->depth_required; } static void billboard_update(struct tracked_output **outs) { const struct tracked_output *best = NULL; /* Highest priority is to report on proposals we have */ for (size_t i = 0; i < tal_count(outs); i++) { if (!outs[i]->proposal) continue; if (!best || prop_blockheight(outs[i]) < prop_blockheight(best)) best = outs[i]; } if (best) { /* If we've broadcast and not seen yet, this happens */ if (best->proposal->depth_required <= best->depth) { peer_billboard(false, "%u outputs unresolved: waiting confirmation that we spent %s (%s:%u) using %s", num_not_irrevocably_resolved(outs), output_type_name(best->output_type), type_to_string(tmpctx, struct bitcoin_txid, &best->txid), best->outnum, tx_type_name(best->proposal->tx_type)); } else { peer_billboard(false, "%u outputs unresolved: in %u blocks will spend %s (%s:%u) using %s", num_not_irrevocably_resolved(outs), best->proposal->depth_required - best->depth, output_type_name(best->output_type), type_to_string(tmpctx, struct bitcoin_txid, &best->txid), best->outnum, tx_type_name(best->proposal->tx_type)); } return; } /* Now, just report on the last thing we're waiting out. */ for (size_t i = 0; i < tal_count(outs); i++) { /* FIXME: Can this happen? No proposal, no resolution? */ if (!outs[i]->resolved) continue; if (!best || outs[i]->resolved->depth < best->resolved->depth) best = outs[i]; } if (best) { peer_billboard(false, "All outputs resolved:" " waiting %u more blocks before forgetting" " channel", best->resolved->depth < 100 ? 100 - best->resolved->depth : 0); return; } /* Not sure this can happen, but take last one (there must be one!) */ best = outs[tal_count(outs)-1]; peer_billboard(false, "%u outputs unresolved: %s is one (depth %u)", num_not_irrevocably_resolved(outs), output_type_name(best->output_type), best->depth); } static void unwatch_tx(const struct bitcoin_tx *tx) { u8 *msg; struct bitcoin_txid txid; bitcoin_txid(tx, &txid); msg = towire_onchain_unwatch_tx(tx, &txid); wire_sync_write(REQ_FD, take(msg)); } static void handle_htlc_onchain_fulfill(struct tracked_output *out, const struct bitcoin_tx *tx) { const u8 *witness_preimage; struct preimage preimage; struct sha256 sha; struct ripemd160 ripemd; /* Our HTLC, they filled (must be an HTLC-success tx). */ if (out->tx_type == THEIR_UNILATERAL) { /* BOLT #3: * * ## HTLC-Timeout and HTLC-Success Transactions * * ... `txin[0]` witness stack: `0 <remotehtlcsig> <localhtlcsig> * <payment_preimage>` for HTLC-success */ if (tal_count(tx->input[0].witness) != 5) /* +1 for wscript */ status_failed(STATUS_FAIL_INTERNAL_ERROR, "%s/%s spent with weird witness %zu", tx_type_name(out->tx_type), output_type_name(out->output_type), tal_count(tx->input[0].witness)); witness_preimage = tx->input[0].witness[3]; } else if (out->tx_type == OUR_UNILATERAL) { /* BOLT #3: * * The remote node can redeem the HTLC with the witness: * * <remotehtlcsig> <payment_preimage> */ if (tal_count(tx->input[0].witness) != 3) /* +1 for wscript */ status_failed(STATUS_FAIL_INTERNAL_ERROR, "%s/%s spent with weird witness %zu", tx_type_name(out->tx_type), output_type_name(out->output_type), tal_count(tx->input[0].witness)); witness_preimage = tx->input[0].witness[1]; } else status_failed(STATUS_FAIL_INTERNAL_ERROR, "onchain_fulfill for %s/%s?", tx_type_name(out->tx_type), output_type_name(out->output_type)); if (tal_count(witness_preimage) != sizeof(preimage)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "%s/%s spent with bad witness length %zu", tx_type_name(out->tx_type), output_type_name(out->output_type), tal_count(witness_preimage)); memcpy(&preimage, witness_preimage, sizeof(preimage)); sha256(&sha, &preimage, sizeof(preimage)); ripemd160(&ripemd, &sha, sizeof(sha)); if (!ripemd160_eq(&ripemd, &out->htlc->ripemd)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "%s/%s spent with bad preimage %s (ripemd not %s)", tx_type_name(out->tx_type), output_type_name(out->output_type), type_to_string(tmpctx, struct preimage, &preimage), type_to_string(tmpctx, struct ripemd160, &out->htlc->ripemd)); /* Tell master we found a preimage. */ status_trace("%s/%s gave us preimage %s", tx_type_name(out->tx_type), output_type_name(out->output_type), type_to_string(tmpctx, struct preimage, &preimage)); wire_sync_write(REQ_FD, take(towire_onchain_extracted_preimage(NULL, &preimage))); } static void resolve_htlc_tx(struct tracked_output ***outs, size_t out_index, const struct bitcoin_tx *htlc_tx, const struct bitcoin_txid *htlc_txid, u32 tx_blockheight) { struct tracked_output *out; struct bitcoin_tx *tx; enum tx_type tx_type = OUR_DELAYED_RETURN_TO_WALLET; u8 *wscript = bitcoin_wscript_htlc_tx(htlc_tx, to_self_delay[LOCAL], &keyset->self_revocation_key, &keyset->self_delayed_payment_key); /* BOLT #5: * * - SHOULD resolve the HTLC-timeout transaction by spending it to * a convenient address... * - MUST wait until the `OP_CHECKSEQUENCEVERIFY` delay has passed * (as specified by the remote node's `open_channel` * `to_self_delay` field) before spending that HTLC-timeout * output. */ out = new_tracked_output(outs, htlc_txid, tx_blockheight, (*outs)[out_index]->resolved->tx_type, 0, htlc_tx->output[0].amount, DELAYED_OUTPUT_TO_US, NULL, NULL, NULL); /* BOLT #3: * * ## HTLC-Timeout and HTLC-Success Transactions * * These HTLC transactions are almost identical, except the * HTLC-timeout transaction is timelocked. * * ... to collect the output, the local node uses an input with * nSequence `to_self_delay` and a witness stack `<local_delayedsig> * 0` */ tx = tx_to_us(*outs, delayed_payment_to_us, out, to_self_delay[LOCAL], 0, NULL, 0, wscript, &tx_type); propose_resolution(out, tx, to_self_delay[LOCAL], tx_type); } /* BOLT #5: * * - MUST *resolve* the _remote node's HTLC-timeout transaction_ by spending it * using the revocation private key. * - MUST *resolve* the _remote node's HTLC-success transaction_ by spending it * using the revocation private key. */ static void steal_htlc_tx(struct tracked_output *out) { struct bitcoin_tx *tx; enum tx_type tx_type = OUR_PENALTY_TX; /* BOLT #3: * * To spend this via penalty, the remote node uses a witness stack * `<revocationsig> 1` */ tx = tx_to_us(out, penalty_to_us, out, 0xFFFFFFFF, 0, &ONE, sizeof(ONE), out->wscript, &tx_type); propose_resolution(out, tx, 0, tx_type); } /* An output has been spent: see if it resolves something we care about. */ static void output_spent(struct tracked_output ***outs, const struct bitcoin_tx *tx, u32 input_num, u32 tx_blockheight) { struct bitcoin_txid txid; bitcoin_txid(tx, &txid); for (size_t i = 0; i < tal_count(*outs); i++) { struct tracked_output *out = (*outs)[i]; if (out->resolved) continue; if (tx->input[input_num].index != out->outnum) continue; if (!bitcoin_txid_eq(&tx->input[input_num].txid, &out->txid)) continue; /* Was this our resolution? */ if (resolved_by_proposal(out, tx)) { /* If it's our htlc tx, we need to resolve that, too. */ if (out->resolved->tx_type == OUR_HTLC_SUCCESS_TX || out->resolved->tx_type == OUR_HTLC_TIMEOUT_TX) resolve_htlc_tx(outs, i, tx, &txid, tx_blockheight); return; } switch (out->output_type) { case OUTPUT_TO_US: case DELAYED_OUTPUT_TO_US: unknown_spend(out, tx); break; case THEIR_HTLC: if (out->tx_type == THEIR_REVOKED_UNILATERAL) { steal_htlc_tx(out); } else { /* We ignore this timeout tx, since we should * resolve by ignoring once we reach depth. */ } break; case OUR_HTLC: /* The only way they can spend this: fulfill; even * if it's revoked: */ /* BOLT #5: * * ## HTLC Output Handling: Local Commitment, Local Offers *... * - MUST extract the payment preimage from the * transaction input witness. *... * ## HTLC Output Handling: Remote Commitment, Local Offers *... * - MUST extract the payment preimage from the * HTLC-success transaction input witness. */ handle_htlc_onchain_fulfill(out, tx); if (out->tx_type == THEIR_REVOKED_UNILATERAL) steal_htlc_tx(out); else { /* BOLT #5: * * ## HTLC Output Handling: Local Commitment, * Local Offers *... * - if the commitment transaction HTLC output * is spent using the payment preimage, the * output is considered *irrevocably resolved* */ ignore_output(out); } break; case FUNDING_OUTPUT: /* Master should be restarting us, as this implies * that our old tx was unspent. */ status_failed(STATUS_FAIL_INTERNAL_ERROR, "Funding output spent again!"); /* Um, we don't track these! */ case OUTPUT_TO_THEM: case DELAYED_OUTPUT_TO_THEM: status_failed(STATUS_FAIL_INTERNAL_ERROR, "Tracked spend of %s/%s?", tx_type_name(out->tx_type), output_type_name(out->output_type)); } return; } /* Not interesting to us, so unwatch the tx and all its outputs */ status_trace("Notified about tx %s output %u spend, but we don't care", type_to_string(tmpctx, struct bitcoin_txid, &tx->input[input_num].txid), tx->input[input_num].index); unwatch_tx(tx); } static void update_resolution_depth(struct tracked_output *out, u32 depth) { bool reached_reasonable_depth; status_trace("%s/%s->%s depth %u", tx_type_name(out->tx_type), output_type_name(out->output_type), tx_type_name(out->resolved->tx_type), depth); /* We only set this once. */ reached_reasonable_depth = (out->resolved->depth < reasonable_depth && depth >= reasonable_depth); /* BOLT #5: * * - if the commitment transaction HTLC output has *timed out* and * hasn't been *resolved*: * - MUST *resolve* the output by spending it using the HTLC-timeout * transaction. * - once the resolving transaction has reached reasonable depth: * - MUST fail the corresponding incoming HTLC (if any). */ if ((out->resolved->tx_type == OUR_HTLC_TIMEOUT_TX || out->resolved->tx_type == OUR_HTLC_TIMEOUT_TO_US) && reached_reasonable_depth) { u8 *msg; status_trace("%s/%s reached reasonable depth %u", tx_type_name(out->tx_type), output_type_name(out->output_type), depth); msg = towire_onchain_htlc_timeout(out, out->htlc); wire_sync_write(REQ_FD, take(msg)); } out->resolved->depth = depth; } static void tx_new_depth(struct tracked_output **outs, const struct bitcoin_txid *txid, u32 depth) { size_t i; /* Special handling for commitment tx reaching depth */ if (bitcoin_txid_eq(&outs[0]->resolved->txid, txid) && depth >= reasonable_depth && missing_htlc_msgs) { status_trace("Sending %zu missing htlc messages", tal_count(missing_htlc_msgs)); for (i = 0; i < tal_count(missing_htlc_msgs); i++) wire_sync_write(REQ_FD, missing_htlc_msgs[i]); /* Don't do it again. */ missing_htlc_msgs = tal_free(missing_htlc_msgs); } for (i = 0; i < tal_count(outs); i++) { /* Update output depth. */ if (bitcoin_txid_eq(&outs[i]->txid, txid)) outs[i]->depth = depth; /* Is this tx resolving an output? */ if (outs[i]->resolved) { if (bitcoin_txid_eq(&outs[i]->resolved->txid, txid)) { update_resolution_depth(outs[i], depth); } continue; } /* Otherwise, is this something we have a pending * resolution for? */ if (outs[i]->proposal && bitcoin_txid_eq(&outs[i]->txid, txid) && depth >= outs[i]->proposal->depth_required) { proposal_meets_depth(outs[i]); } } } /* BOLT #5: * * A local node: * - if it receives (or already possesses) a payment preimage for an unresolved * HTLC output that it has been offered AND for which it has committed to an * outgoing HTLC: * - MUST *resolve* the output by spending it, using the HTLC-success * transaction. * - MUST resolve the output of that HTLC-success transaction. * - otherwise: * - if the *remote node* is NOT irrevocably committed to the HTLC: * - MUST NOT *resolve* the output by spending it. *... * ## HTLC Output Handling: Remote Commitment, Remote Offers *... * A local node: * - if it receives (or already possesses) a payment preimage for an unresolved * HTLC output that it was offered AND for which it has committed to an * outgoing HTLC: * - MUST *resolve* the output by spending it to a convenient address. * - otherwise: * - if the remote node is NOT irrevocably committed to the HTLC: * - MUST NOT *resolve* the output by spending it. */ /* Master makes sure we only get told preimages once other node is committed. */ static void handle_preimage(struct tracked_output **outs, const struct preimage *preimage) { size_t i; struct sha256 sha; struct ripemd160 ripemd; sha256(&sha, preimage, sizeof(*preimage)); ripemd160(&ripemd, &sha, sizeof(sha)); for (i = 0; i < tal_count(outs); i++) { struct bitcoin_tx *tx; secp256k1_ecdsa_signature sig; if (outs[i]->output_type != THEIR_HTLC) continue; if (!ripemd160_eq(&outs[i]->htlc->ripemd, &ripemd)) continue; /* Too late? */ if (outs[i]->resolved) { /* FIXME: We need a better warning method! */ status_trace("WARNING: HTLC already resolved by %s" " when we found preimage", tx_type_name(outs[i]->resolved->tx_type)); return; } /* Discard any previous resolution. Could be a timeout, * could be due to multiple identical rhashes in tx. */ outs[i]->proposal = tal_free(outs[i]->proposal); /* BOLT #5: * * * ## HTLC Output Handling: Local Commitment, Remote Offers *... * A local node: * - if it receives (or already possesses) a payment preimage * for an unresolved HTLC output that it has been offered * AND for which it has committed to an outgoing HTLC: * - MUST *resolve* the output by spending it, using the * HTLC-success transaction. */ if (outs[i]->remote_htlc_sig) { tx = htlc_success_tx(outs[i], &outs[i]->txid, outs[i]->outnum, outs[i]->satoshi * 1000, to_self_delay[LOCAL], 0, keyset); set_htlc_success_fee(tx, outs[i]->remote_htlc_sig, outs[i]->wscript); hsm_sign_local_htlc_tx(tx, outs[i]->wscript, &sig); tx->input[0].witness = bitcoin_witness_htlc_success_tx(tx->input, &sig, outs[i]->remote_htlc_sig, preimage, outs[i]->wscript); propose_resolution(outs[i], tx, 0, OUR_HTLC_SUCCESS_TX); } else { enum tx_type tx_type = THEIR_HTLC_FULFILL_TO_US; /* BOLT #5: * * ## HTLC Output Handling: Remote Commitment, Remote * Offers *... * A local node: * - if it receives (or already possesses) a payment * preimage for an unresolved HTLC output that it was * offered AND for which it has committed to an * outgoing HTLC: * - MUST *resolve* the output by spending it to a * convenient address. */ tx = tx_to_us(outs[i], remote_htlc_to_us, outs[i], 0, 0, preimage, sizeof(*preimage), outs[i]->wscript, &tx_type); propose_resolution(outs[i], tx, 0, tx_type); } } } /* BOLT #5: * * A node: * - once it has broadcast a funding transaction OR sent a commitment signature * for a commitment transaction that contains an HTLC output: * - until all outputs are *irrevocably resolved*: * - MUST monitor the blockchain for transactions that spend any output that * is NOT *irrevocably resolved*. */ static void wait_for_resolved(struct tracked_output **outs) { billboard_update(outs); while (num_not_irrevocably_resolved(outs) != 0) { u8 *msg = wire_sync_read(outs, REQ_FD); struct bitcoin_txid txid; struct bitcoin_tx *tx; u32 input_num, depth, tx_blockheight; struct preimage preimage; status_trace("Got new message %s", onchain_wire_type_name(fromwire_peektype(msg))); if (fromwire_onchain_depth(msg, &txid, &depth)) tx_new_depth(outs, &txid, depth); else if (fromwire_onchain_spent(msg, msg, &tx, &input_num, &tx_blockheight)) output_spent(&outs, tx, input_num, tx_blockheight); else if (fromwire_onchain_known_preimage(msg, &preimage)) handle_preimage(outs, &preimage); else master_badmsg(-1, msg); billboard_update(outs); tal_free(msg); clean_tmpctx(); } wire_sync_write(REQ_FD, take(towire_onchain_all_irrevocably_resolved(outs))); } static void init_reply(const char *what) { /* Send init_reply first, so billboard gets credited to ONCHAIND */ wire_sync_write(REQ_FD, take(towire_onchain_init_reply(NULL))); peer_billboard(true, what); } static void handle_mutual_close(const struct bitcoin_txid *txid, struct tracked_output **outs) { init_reply("Tracking mutual close transaction"); /* BOLT #5: * * A mutual close transaction *resolves* the funding transaction output. * * In the case of a mutual close, a node need not do anything else, as * it has already agreed to the output, which is sent to its specified * `scriptpubkey` */ resolved_by_other(outs[0], txid, MUTUAL_CLOSE); wait_for_resolved(outs); } static u8 **derive_htlc_scripts(const struct htlc_stub *htlcs, enum side side) { size_t i; u8 **htlc_scripts = tal_arr(htlcs, u8 *, tal_count(htlcs)); for (i = 0; i < tal_count(htlcs); i++) { if (htlcs[i].owner == side) htlc_scripts[i] = htlc_offered_wscript(htlc_scripts, &htlcs[i].ripemd, keyset); else { /* FIXME: remove abs_locktime */ struct abs_locktime ltime; if (!blocks_to_abs_locktime(htlcs[i].cltv_expiry, &ltime)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Could not convert cltv_expiry %u to locktime", htlcs[i].cltv_expiry); htlc_scripts[i] = htlc_received_wscript(htlc_scripts, &htlcs[i].ripemd, &ltime, keyset); } } return htlc_scripts; } static void resolve_our_htlc_ourcommit(struct tracked_output *out) { struct bitcoin_tx *tx; secp256k1_ecdsa_signature localsig; /* BOLT #5: * * ## HTLC Output Handling: Local Commitment, Local Offers * ... * - if the commitment transaction HTLC output has *timed out* and * hasn't been *resolved*: * - MUST *resolve* the output by spending it using the HTLC-timeout * transaction. */ tx = htlc_timeout_tx(out, &out->txid, out->outnum, out->satoshi * 1000, out->htlc->cltv_expiry, to_self_delay[LOCAL], 0, keyset); set_htlc_timeout_fee(tx, out->remote_htlc_sig, out->wscript); hsm_sign_local_htlc_tx(tx, out->wscript, &localsig); tx->input[0].witness = bitcoin_witness_htlc_timeout_tx(tx->input, &localsig, out->remote_htlc_sig, out->wscript); propose_resolution_at_block(out, tx, out->htlc->cltv_expiry, OUR_HTLC_TIMEOUT_TX); } static void resolve_our_htlc_theircommit(struct tracked_output *out) { struct bitcoin_tx *tx; enum tx_type tx_type = OUR_HTLC_TIMEOUT_TO_US; /* BOLT #5: * * ## HTLC Output Handling: Remote Commitment, Local Offers * ... * * - if the commitment transaction HTLC output has *timed out* AND NOT * been *resolved*: * - MUST *resolve* the output, by spending it to a convenient * address. */ tx = tx_to_us(out, remote_htlc_to_us, out, 0, out->htlc->cltv_expiry, NULL, 0, out->wscript, &tx_type); propose_resolution_at_block(out, tx, out->htlc->cltv_expiry, tx_type); } static void resolve_their_htlc(struct tracked_output *out) { /* BOLT #5: * * ## HTLC Output Handling: Remote Commitment, Remote Offers *... * ### Requirements *... * If not otherwise resolved, once the HTLC output has expired, it is * considered *irrevocably resolved*. */ /* If we hit timeout depth, resolve by ignoring. */ propose_resolution_at_block(out, NULL, out->htlc->cltv_expiry, THEIR_HTLC_TIMEOUT_TO_THEM); } static int match_htlc_output(const struct bitcoin_tx *tx, unsigned int outnum, u8 **htlc_scripts) { /* Must be a p2wsh output */ if (!is_p2wsh(tx->output[outnum].script, NULL)) return -1; for (size_t i = 0; i < tal_count(htlc_scripts); i++) { struct sha256 sha; if (!htlc_scripts[i]) continue; sha256(&sha, htlc_scripts[i], tal_count(htlc_scripts[i])); if (memeq(tx->output[outnum].script + 2, tal_count(tx->output[outnum].script) - 2, &sha, sizeof(sha))) return i; } return -1; } /* Tell master about any we didn't use, if it wants to know. */ static void note_missing_htlcs(u8 **htlc_scripts, const struct htlc_stub *htlcs, const bool *tell_if_missing, const bool *tell_immediately) { for (size_t i = 0; i < tal_count(htlcs); i++) { u8 *msg; /* Used. */ if (!htlc_scripts[i]) continue; /* Doesn't care. */ if (!tell_if_missing[i]) continue; msg = towire_onchain_missing_htlc_output(missing_htlc_msgs, &htlcs[i]); if (tell_immediately[i]) wire_sync_write(REQ_FD, take(msg)); else { size_t n = tal_count(missing_htlc_msgs); tal_resize(&missing_htlc_msgs, n+1); missing_htlc_msgs[n] = msg; } } } static void handle_our_unilateral(const struct bitcoin_tx *tx, u32 tx_blockheight, const struct bitcoin_txid *txid, const struct basepoints basepoints[NUM_SIDES], const struct htlc_stub *htlcs, const bool *tell_if_missing, const bool *tell_immediately, const secp256k1_ecdsa_signature *remote_htlc_sigs, struct tracked_output **outs) { u8 **htlc_scripts; u8 *local_wscript, *script[NUM_SIDES]; struct pubkey local_per_commitment_point; struct keyset *ks; size_t i; init_reply("Tracking our own unilateral close"); /* BOLT #5: * * In this case, a node discovers its *local commitment transaction*, * which *resolves* the funding transaction output. */ resolved_by_other(outs[0], txid, OUR_UNILATERAL); /* Figure out what delayed to-us output looks like */ hsm_get_per_commitment_point(&local_per_commitment_point); /* keyset is const, we need a non-const ptr to set it up */ keyset = ks = tal(tx, struct keyset); if (!derive_keyset(&local_per_commitment_point, &basepoints[LOCAL], &basepoints[REMOTE], ks)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Deriving keyset for %"PRIu64, commit_num); status_trace("Deconstructing unilateral tx: %"PRIu64 " using keyset: " " self_revocation_key: %s" " self_delayed_payment_key: %s" " self_payment_key: %s" " other_payment_key: %s" " self_htlc_key: %s" " other_htlc_key: %s", commit_num, type_to_string(tmpctx, struct pubkey, &keyset->self_revocation_key), type_to_string(tmpctx, struct pubkey, &keyset->self_delayed_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->other_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_htlc_key), type_to_string(tmpctx, struct pubkey, &keyset->other_htlc_key)); local_wscript = to_self_wscript(tmpctx, to_self_delay[LOCAL], keyset); /* Figure out what to-us output looks like. */ script[LOCAL] = scriptpubkey_p2wsh(tmpctx, local_wscript); /* Figure out what direct to-them output looks like. */ script[REMOTE] = scriptpubkey_p2wpkh(tmpctx, &keyset->other_payment_key); /* Calculate all the HTLC scripts so we can match them */ htlc_scripts = derive_htlc_scripts(htlcs, LOCAL); status_trace("Script to-me: %u: %s (%s)", to_self_delay[LOCAL], tal_hex(tmpctx, script[LOCAL]), tal_hex(tmpctx, local_wscript)); status_trace("Script to-them: %s", tal_hex(tmpctx, script[REMOTE])); for (i = 0; i < tal_count(tx->output); i++) { status_trace("Output %zu: %s", i, tal_hex(tmpctx, tx->output[i].script)); } for (i = 0; i < tal_count(tx->output); i++) { struct tracked_output *out; int j; if (script[LOCAL] && scripteq(tx->output[i].script, script[LOCAL])) { struct bitcoin_tx *to_us; enum tx_type tx_type = OUR_DELAYED_RETURN_TO_WALLET; /* BOLT #5: * * A node: * - upon discovering its *local commitment * transaction*: * - SHOULD spend the `to_local` output to a * convenient address. * - MUST wait until the `OP_CHECKSEQUENCEVERIFY` * delay has passed (as specified by the remote * node's `to_self_delay` field) before spending * the output. */ out = new_tracked_output(&outs, txid, tx_blockheight, OUR_UNILATERAL, i, tx->output[i].amount, DELAYED_OUTPUT_TO_US, NULL, NULL, NULL); /* BOLT #3: * * The output is spent by a transaction with * `nSequence` field set to `to_self_delay` (which can * only be valid after that duration has passed) and * witness: * * <local_delayedsig> 0 */ to_us = tx_to_us(out, delayed_payment_to_us, out, to_self_delay[LOCAL], 0, NULL, 0, local_wscript, &tx_type); /* BOLT #5: * * Note: if the output is spent (as recommended), the * output is *resolved* by the spending transaction */ propose_resolution(out, to_us, to_self_delay[LOCAL], tx_type); script[LOCAL] = NULL; continue; } if (script[REMOTE] && scripteq(tx->output[i].script, script[REMOTE])) { /* BOLT #5: * * - MAY ignore the `to_remote` output. * - Note: No action is required by the local * node, as `to_remote` is considered *resolved* * by the commitment transaction itself. */ out = new_tracked_output(&outs, txid, tx_blockheight, OUR_UNILATERAL, i, tx->output[i].amount, OUTPUT_TO_THEM, NULL, NULL, NULL); ignore_output(out); script[REMOTE] = NULL; continue; } /* FIXME: limp along when this happens! */ j = match_htlc_output(tx, i, htlc_scripts); if (j == -1) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Could not find resolution for output %zu", i); if (htlcs[j].owner == LOCAL) { /* BOLT #5: * * - MUST handle HTLCs offered by itself as specified * in [HTLC Output Handling: Local Commitment, * Local Offers] */ out = new_tracked_output(&outs, txid, tx_blockheight, OUR_UNILATERAL, i, tx->output[i].amount, OUR_HTLC, &htlcs[j], htlc_scripts[j], remote_htlc_sigs); resolve_our_htlc_ourcommit(out); } else { out = new_tracked_output(&outs, txid, tx_blockheight, OUR_UNILATERAL, i, tx->output[i].amount, THEIR_HTLC, &htlcs[j], htlc_scripts[j], remote_htlc_sigs); /* BOLT #5: * * - MUST handle HTLCs offered by the remote node * as specified in [HTLC Output Handling: Local * Commitment, Remote Offers] */ resolve_their_htlc(out); } /* Each of these consumes one HTLC signature */ remote_htlc_sigs++; /* We've matched this HTLC, can't do again. */ htlc_scripts[j] = NULL; } note_missing_htlcs(htlc_scripts, htlcs, tell_if_missing, tell_immediately); wait_for_resolved(outs); } /* We produce individual penalty txs. It's less efficient, but avoids them * using HTLC txs to block our penalties for long enough to pass the CSV * delay */ static void steal_to_them_output(struct tracked_output *out) { u8 *wscript; struct bitcoin_tx *tx; enum tx_type tx_type = OUR_PENALTY_TX; /* BOLT #3: * * If a revoked commitment transaction is published, the other party * can spend this output immediately with the following witness: * * <revocation_sig> 1 */ wscript = bitcoin_wscript_to_local(tmpctx, to_self_delay[REMOTE], &keyset->self_revocation_key, &keyset->self_delayed_payment_key); tx = tx_to_us(tmpctx, penalty_to_us, out, 0xFFFFFFFF, 0, &ONE, sizeof(ONE), wscript, &tx_type); propose_resolution(out, tx, 0, tx_type); } static void steal_htlc(struct tracked_output *out) { struct bitcoin_tx *tx; enum tx_type tx_type = OUR_PENALTY_TX; u8 der[PUBKEY_DER_LEN]; /* BOLT #3: * * If a revoked commitment transaction is published, the remote node can * spend this output immediately with the following witness: * * <revocation_sig> <revocationpubkey> */ pubkey_to_der(der, &keyset->self_revocation_key); tx = tx_to_us(out, penalty_to_us, out, 0xFFFFFFFF, 0, der, sizeof(der), out->wscript, &tx_type); propose_resolution(out, tx, 0, tx_type); } /* BOLT #5: * * If any node tries to cheat by broadcasting an outdated commitment * transaction (any previous commitment transaction besides the most current * one), the other node in the channel can use its revocation private key to * claim all the funds from the channel's original funding transaction. */ static void handle_their_cheat(const struct bitcoin_tx *tx, const struct bitcoin_txid *txid, u32 tx_blockheight, const struct sha256 *revocation_preimage, const struct basepoints basepoints[NUM_SIDES], const struct htlc_stub *htlcs, const bool *tell_if_missing, const bool *tell_immediately, struct tracked_output **outs) { u8 **htlc_scripts; u8 *remote_wscript, *script[NUM_SIDES]; struct keyset *ks; struct pubkey *k; size_t i; init_reply("Tracking their illegal close: taking all funds"); /* BOLT #5: * * Once a node discovers a commitment transaction for which *it* has a * revocation private key, the funding transaction output is *resolved*. */ resolved_by_other(outs[0], txid, THEIR_REVOKED_UNILATERAL); /* FIXME: Types. */ BUILD_ASSERT(sizeof(struct secret) == sizeof(*revocation_preimage)); remote_per_commitment_secret = tal_dup(tx, struct secret, (struct secret *) revocation_preimage); /* Need tmpvar for non-const. */ remote_per_commitment_point = k = tal(tx, struct pubkey); if (!pubkey_from_secret(remote_per_commitment_secret, k)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Failed derive from per_commitment_secret %s", type_to_string(tmpctx, struct secret, remote_per_commitment_secret)); status_trace("Deriving keyset %"PRIu64 ": per_commit_point=%s" " self_payment_basepoint=%s" " other_payment_basepoint=%s" " self_htlc_basepoint=%s" " other_htlc_basepoint=%s" " self_delayed_basepoint=%s" " other_revocation_basepoint=%s", commit_num, type_to_string(tmpctx, struct pubkey, remote_per_commitment_point), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].payment), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].payment), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].htlc), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].htlc), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].delayed_payment), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].revocation)); /* keyset is const, we need a non-const ptr to set it up */ keyset = ks = tal(tx, struct keyset); if (!derive_keyset(remote_per_commitment_point, &basepoints[REMOTE], &basepoints[LOCAL], ks)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Deriving keyset for %"PRIu64, commit_num); status_trace("Deconstructing revoked unilateral tx: %"PRIu64 " using keyset: " " self_revocation_key: %s" " self_delayed_payment_key: %s" " self_payment_key: %s" " other_payment_key: %s" " self_htlc_key: %s" " other_htlc_key: %s", commit_num, type_to_string(tmpctx, struct pubkey, &keyset->self_revocation_key), type_to_string(tmpctx, struct pubkey, &keyset->self_delayed_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->other_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_htlc_key), type_to_string(tmpctx, struct pubkey, &keyset->other_htlc_key)); remote_wscript = to_self_wscript(tmpctx, to_self_delay[REMOTE], keyset); /* Figure out what to-them output looks like. */ script[REMOTE] = scriptpubkey_p2wsh(tmpctx, remote_wscript); /* Figure out what direct to-us output looks like. */ script[LOCAL] = scriptpubkey_p2wpkh(tmpctx, &keyset->other_payment_key); /* Calculate all the HTLC scripts so we can match them */ htlc_scripts = derive_htlc_scripts(htlcs, REMOTE); status_trace("Script to-them: %u: %s (%s)", to_self_delay[REMOTE], tal_hex(tmpctx, script[REMOTE]), tal_hex(tmpctx, remote_wscript)); status_trace("Script to-me: %s", tal_hex(tmpctx, script[LOCAL])); for (i = 0; i < tal_count(tx->output); i++) { status_trace("Output %zu: %s", i, tal_hex(tmpctx, tx->output[i].script)); } for (i = 0; i < tal_count(tx->output); i++) { struct tracked_output *out; int j; if (script[LOCAL] && scripteq(tx->output[i].script, script[LOCAL])) { /* BOLT #5: * * - MAY take no action regarding the _local node's * main output_, as this is a simple P2WPKH output * to itself. * - Note: this output is considered *resolved* by * the commitment transaction itself. */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_REVOKED_UNILATERAL, i, tx->output[i].amount, OUTPUT_TO_US, NULL, NULL, NULL); ignore_output(out); script[LOCAL] = NULL; /* Tell the master that it will want to add * this UTXO to its outputs */ wire_sync_write(REQ_FD, towire_onchain_add_utxo( tmpctx, txid, i, remote_per_commitment_point, tx->output[i].amount, tx_blockheight)); continue; } if (script[REMOTE] && scripteq(tx->output[i].script, script[REMOTE])) { /* BOLT #5: * * - MUST *resolve* the _remote node's main output_ by * spending it using the revocation private key. */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_REVOKED_UNILATERAL, i, tx->output[i].amount, DELAYED_OUTPUT_TO_THEM, NULL, NULL, NULL); steal_to_them_output(out); script[REMOTE] = NULL; continue; } j = match_htlc_output(tx, i, htlc_scripts); if (j == -1) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Could not find resolution for output %zu", i); if (htlcs[j].owner == LOCAL) { /* BOLT #5: * * - MUST *resolve* the _local node's offered HTLCs_ * in one of three ways: * * spend the *commitment tx* using the payment * revocation private key. * * spend the *commitment tx* using the payment * preimage (if known). * * spend the *HTLC-timeout tx*, if the remote node * has published it. */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_REVOKED_UNILATERAL, i, tx->output[i].amount, OUR_HTLC, &htlcs[j], htlc_scripts[j], NULL); steal_htlc(out); } else { out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_REVOKED_UNILATERAL, i, tx->output[i].amount, THEIR_HTLC, &htlcs[j], htlc_scripts[j], NULL); /* BOLT #5: * * - MUST *resolve* the _remote node's offered HTLCs_ * in one of two ways: * * spend the *commitment tx* using the payment * revocation key. * * spend the *commitment tx* once the HTLC timeout * has passed. */ steal_htlc(out); } htlc_scripts[j] = NULL; } note_missing_htlcs(htlc_scripts, htlcs, tell_if_missing, tell_immediately); wait_for_resolved(outs); } static void handle_their_unilateral(const struct bitcoin_tx *tx, u32 tx_blockheight, const struct bitcoin_txid *txid, const struct pubkey *this_remote_per_commitment_point, const struct basepoints basepoints[NUM_SIDES], const struct htlc_stub *htlcs, const bool *tell_if_missing, const bool *tell_immediately, struct tracked_output **outs) { u8 **htlc_scripts; u8 *remote_wscript, *script[NUM_SIDES]; struct keyset *ks; size_t i; init_reply("Tracking their unilateral close"); /* HSM can't derive this. */ remote_per_commitment_point = this_remote_per_commitment_point; /* BOLT #5: * * # Unilateral Close Handling: Remote Commitment Transaction * * The *remote node's* commitment transaction *resolves* the funding * transaction output. * * There are no delays constraining node behavior in this case, so * it's simpler for a node to handle than the case in which it * discovers its local commitment transaction (see [Unilateral Close * Handling: Local Commitment Transaction] */ resolved_by_other(outs[0], txid, THEIR_UNILATERAL); status_trace("Deriving keyset %"PRIu64 ": per_commit_point=%s" " self_payment_basepoint=%s" " other_payment_basepoint=%s" " self_htlc_basepoint=%s" " other_htlc_basepoint=%s" " self_delayed_basepoint=%s" " other_revocation_basepoint=%s", commit_num, type_to_string(tmpctx, struct pubkey, remote_per_commitment_point), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].payment), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].payment), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].htlc), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].htlc), type_to_string(tmpctx, struct pubkey, &basepoints[REMOTE].delayed_payment), type_to_string(tmpctx, struct pubkey, &basepoints[LOCAL].revocation)); /* keyset is const, we need a non-const ptr to set it up */ keyset = ks = tal(tx, struct keyset); if (!derive_keyset(remote_per_commitment_point, &basepoints[REMOTE], &basepoints[LOCAL], ks)) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Deriving keyset for %"PRIu64, commit_num); status_trace("Deconstructing unilateral tx: %"PRIu64 " using keyset: " " self_revocation_key: %s" " self_delayed_payment_key: %s" " self_payment_key: %s" " other_payment_key: %s" " self_htlc_key: %s" " other_htlc_key: %s", commit_num, type_to_string(tmpctx, struct pubkey, &keyset->self_revocation_key), type_to_string(tmpctx, struct pubkey, &keyset->self_delayed_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->other_payment_key), type_to_string(tmpctx, struct pubkey, &keyset->self_htlc_key), type_to_string(tmpctx, struct pubkey, &keyset->other_htlc_key)); remote_wscript = to_self_wscript(tmpctx, to_self_delay[REMOTE], keyset); /* Figure out what to-them output looks like. */ script[REMOTE] = scriptpubkey_p2wsh(tmpctx, remote_wscript); /* Figure out what direct to-us output looks like. */ script[LOCAL] = scriptpubkey_p2wpkh(tmpctx, &keyset->other_payment_key); /* Calculate all the HTLC scripts so we can match them */ htlc_scripts = derive_htlc_scripts(htlcs, REMOTE); status_trace("Script to-them: %u: %s (%s)", to_self_delay[REMOTE], tal_hex(tmpctx, script[REMOTE]), tal_hex(tmpctx, remote_wscript)); status_trace("Script to-me: %s", tal_hex(tmpctx, script[LOCAL])); for (i = 0; i < tal_count(tx->output); i++) { status_trace("Output %zu: %s", i, tal_hex(tmpctx, tx->output[i].script)); } for (i = 0; i < tal_count(tx->output); i++) { struct tracked_output *out; int j; if (script[LOCAL] && scripteq(tx->output[i].script, script[LOCAL])) { /* BOLT #5: * * - MAY take no action in regard to the associated * `to_remote`, which is simply a P2WPKH output to * the *local node*. * - Note: `to_remote` is considered *resolved* by the * commitment transaction itself. */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_UNILATERAL, i, tx->output[i].amount, OUTPUT_TO_US, NULL, NULL, NULL); ignore_output(out); script[LOCAL] = NULL; /* Tell the master that it will want to add * this UTXO to its outputs */ wire_sync_write(REQ_FD, towire_onchain_add_utxo( tmpctx, txid, i, remote_per_commitment_point, tx->output[i].amount, tx_blockheight)); continue; } if (script[REMOTE] && scripteq(tx->output[i].script, script[REMOTE])) { /* BOLT #5: * * - MAY take no action in regard to the associated * `to_local`, which is a payment output to the *remote * node*. * - Note: `to_local` is considered *resolved* by the * commitment transaction itself. */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_UNILATERAL, i, tx->output[i].amount, DELAYED_OUTPUT_TO_THEM, NULL, NULL, NULL); ignore_output(out); continue; } j = match_htlc_output(tx, i, htlc_scripts); if (j == -1) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Could not find resolution for output %zu", i); if (htlcs[j].owner == LOCAL) { /* BOLT #5: * * - MUST handle HTLCs offered by itself as specified in * [HTLC Output Handling: Remote Commitment, * Local Offers] */ out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_UNILATERAL, i, tx->output[i].amount, OUR_HTLC, &htlcs[j], htlc_scripts[j], NULL); resolve_our_htlc_theircommit(out); } else { out = new_tracked_output(&outs, txid, tx_blockheight, THEIR_UNILATERAL, i, tx->output[i].amount, THEIR_HTLC, &htlcs[j], htlc_scripts[j], NULL); /* BOLT #5: * * - MUST handle HTLCs offered by the remote node as * specified in [HTLC Output Handling: Remote * Commitment, Remote Offers] */ resolve_their_htlc(out); } htlc_scripts[j] = NULL; } note_missing_htlcs(htlc_scripts, htlcs, tell_if_missing, tell_immediately); wait_for_resolved(outs); } int main(int argc, char *argv[]) { setup_locale(); const tal_t *ctx = tal(NULL, char); u8 *msg; struct pubkey remote_per_commit_point, old_remote_per_commit_point; enum side funder; struct basepoints basepoints[NUM_SIDES]; struct shachain shachain; struct bitcoin_tx *tx; struct tracked_output **outs; struct bitcoin_txid our_broadcast_txid, txid; secp256k1_ecdsa_signature *remote_htlc_sigs; u64 funding_amount_satoshi, num_htlcs; u8 *scriptpubkey[NUM_SIDES]; struct htlc_stub *htlcs; bool *tell_if_missing, *tell_immediately; u32 tx_blockheight; subdaemon_setup(argc, argv); status_setup_sync(REQ_FD); missing_htlc_msgs = tal_arr(ctx, u8 *, 0); msg = wire_sync_read(tmpctx, REQ_FD); if (!fromwire_onchain_init(ctx, msg, &shachain, &funding_amount_satoshi, &old_remote_per_commit_point, &remote_per_commit_point, &to_self_delay[LOCAL], &to_self_delay[REMOTE], &feerate_per_kw, &dust_limit_satoshis, &our_broadcast_txid, &scriptpubkey[LOCAL], &scriptpubkey[REMOTE], &our_wallet_pubkey, &funder, &basepoints[LOCAL], &basepoints[REMOTE], &tx, &tx_blockheight, &reasonable_depth, &remote_htlc_sigs, &num_htlcs, &min_possible_feerate, &max_possible_feerate)) { master_badmsg(WIRE_ONCHAIN_INIT, msg); } bitcoin_txid(tx, &txid); /* FIXME: Filter as we go, don't load them all into mem! */ htlcs = tal_arr(ctx, struct htlc_stub, num_htlcs); tell_if_missing = tal_arr(ctx, bool, num_htlcs); tell_immediately = tal_arr(ctx, bool, num_htlcs); if (!htlcs || !tell_if_missing || !tell_immediately) status_failed(STATUS_FAIL_INTERNAL_ERROR, "Can't allocate %"PRIu64" htlcs", num_htlcs); for (u64 i = 0; i < num_htlcs; i++) { msg = wire_sync_read(tmpctx, REQ_FD); if (!fromwire_onchain_htlc(msg, &htlcs[i], &tell_if_missing[i], &tell_immediately[i])) master_badmsg(WIRE_ONCHAIN_HTLC, msg); } outs = tal_arr(ctx, struct tracked_output *, 0); new_tracked_output(&outs, &tx->input[0].txid, 0, /* We don't care about funding blockheight */ FUNDING_TRANSACTION, tx->input[0].index, funding_amount_satoshi, FUNDING_OUTPUT, NULL, NULL, NULL); status_trace("Remote per-commit point: %s", type_to_string(tmpctx, struct pubkey, &remote_per_commit_point)); status_trace("Old remote per-commit point: %s", type_to_string(tmpctx, struct pubkey, &old_remote_per_commit_point)); /* BOLT #5: * * There are three ways a channel can end: * * 1. The good way (*mutual close*): at some point the local and * remote nodes agree to close the channel. They generate a *closing * transaction* (which is similar to a commitment transaction, but * without any pending payments) and publish it on the blockchain (see * [BOLT #2: Channel Close](02-peer-protocol.md#channel-close)). */ if (is_mutual_close(tx, scriptpubkey[LOCAL], scriptpubkey[REMOTE])) handle_mutual_close(&txid, outs); else { /* BOLT #5: * * 2. The bad way (*unilateral close*): something goes wrong, * possibly without evil intent on either side. Perhaps one * party crashed, for instance. One side publishes its * *latest commitment transaction*. */ struct sha256 revocation_preimage; commit_num = unmask_commit_number(tx, funder, &basepoints[LOCAL].payment, &basepoints[REMOTE].payment); status_trace("commitnum = %"PRIu64 ", revocations_received = %"PRIu64, commit_num, revocations_received(&shachain)); if (is_local_commitment(&txid, &our_broadcast_txid)) handle_our_unilateral(tx, tx_blockheight, &txid, basepoints, htlcs, tell_if_missing, tell_immediately, remote_htlc_sigs, outs); /* BOLT #5: * * 3. The ugly way (*revoked transaction close*): one of the * parties deliberately tries to cheat, by publishing an * *outdated commitment transaction* (presumably, a prior * version, which is more in its favor). */ else if (shachain_get_hash(&shachain, shachain_index(commit_num), &revocation_preimage)) { handle_their_cheat(tx, &txid, tx_blockheight, &revocation_preimage, basepoints, htlcs, tell_if_missing, tell_immediately, outs); /* BOLT #5: * * There may be more than one valid, *unrevoked* commitment * transaction after a signature has been received via * `commitment_signed` and before the corresponding * `revoke_and_ack`. As such, either commitment may serve as * the *remote node's* commitment transaction; hence, the * local node is required to handle both. */ } else if (commit_num == revocations_received(&shachain)) { status_trace("Their unilateral tx, old commit point"); handle_their_unilateral(tx, tx_blockheight, &txid, &old_remote_per_commit_point, basepoints, htlcs, tell_if_missing, tell_immediately, outs); } else if (commit_num == revocations_received(&shachain) + 1) { status_trace("Their unilateral tx, new commit point"); handle_their_unilateral(tx, tx_blockheight, &txid, &remote_per_commit_point, basepoints, htlcs, tell_if_missing, tell_immediately, outs); } else status_failed(STATUS_FAIL_INTERNAL_ERROR, "Unknown commitment index %"PRIu64 " for tx %s", commit_num, type_to_string(tmpctx, struct bitcoin_tx, tx)); } /* We're done! */ tal_free(ctx); daemon_shutdown(); return 0; }
659570.c
#include <glib.h> #include "test_world.h" #include "sem_world.h" typedef struct { sem_world world; sem_train train; } test_world_context; void test_world_create_blank(test_world_context* test_ctx, const void* data); void test_world_switch_points_to_next_in_array(test_world_context* test_ctx, const void* data); void test_world_needs_points_switch_when_train_on_inactive_track(test_world_context* test_ctx, const void* data); void test_world_not_needs_points_switch_when_train_on_active_track(test_world_context* test_ctx, const void* data); void test_world_train_not_accepted_on_unconnected_points(test_world_context* test_ctx, const void* data); void test_world_track_matching_inactive_points(test_world_context* test_ctx, const void* data); void test_world_track_part_horizontal_first(test_world_context* test_ctx, const void* data); void test_world_track_part_horizontal_second(test_world_context* test_ctx, const void* data); void test_world_track_part_vertical(test_world_context* test_ctx, const void* data); void add_test_world(const char *test_name, void (*test)(test_world_context*, const void* data)); void test_world_setup(test_world_context* test_ctx, const void* data); void test_world_teardown(test_world_context* test_ctx, const void* data); void test_world_setup(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_world* world = &(test_ctx->world); world->max_x = 2; world->max_y = 1; sem_world_init_blank(world); } void test_world_teardown(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_world* world = &(test_ctx->world); sem_world_destroy(world); } void add_tests_world() { add_test_world("/world/create_blank", test_world_create_blank); add_test_world("/world/switch_points_to_next_in_array", test_world_switch_points_to_next_in_array); add_test_world("/world/needs_points_switch_when_train_on_inactive_track", test_world_needs_points_switch_when_train_on_inactive_track); add_test_world("/world/not_needs_points_switch_when_train_on_active_track", test_world_not_needs_points_switch_when_train_on_active_track); add_test_world("/world/train_not_accepted_on_unconnected_points", test_world_train_not_accepted_on_unconnected_points); add_test_world("/world/track_matching_inactive_points", test_world_track_matching_inactive_points); add_test_world("/world/track_part_horizontal_first", test_world_track_part_horizontal_first); add_test_world("/world/track_part_horizontal_second", test_world_track_part_horizontal_second); add_test_world("/world/track_part_vertical", test_world_track_part_vertical); } void add_test_world(const char *test_name, void (*test)(test_world_context*, const void* data)) { g_test_add(test_name, test_world_context, NULL, test_world_setup, test, test_world_teardown); } void test_world_create_blank(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_world* world = &(test_ctx->world); g_assert_true(sem_tile_at(world, 0, 0)->class == BLANK); g_assert_true(sem_tile_at(world, 1, 0)->class == BLANK); } void test_world_switch_points_to_next_in_array(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_world* world = &(test_ctx->world); sem_track trackW_NE; sem_track trackW_SE; sem_track trackW_E; sem_tile* tile = sem_tile_at(world, 0, 0); sem_tile_set_points(tile, &trackW_NE); tile->points[0] = &trackW_SE; tile->points[1] = &trackW_E; tile->points[2] = &trackW_NE; sem_tile_switch_points(tile); g_assert_true(tile->track == &trackW_SE); } void test_world_needs_points_switch_when_train_on_inactive_track(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_train* train = &(test_ctx->train); sem_world* world = &(test_ctx->world); sem_tile_acceptance acceptance; sem_tile_acceptance_init(&acceptance); train->direction = SEM_EAST; sem_track trackNW_E; sem_track_set(&trackNW_E, SEM_NORTH | SEM_WEST, SEM_EAST); sem_track trackW_E; sem_track_set(&trackW_E, SEM_WEST, SEM_EAST); sem_tile* tile = sem_tile_at(world, 1, 0); sem_tile_set_points(tile, &trackNW_E); tile->points[1] = &trackW_E; sem_tile_accept(train, tile, &acceptance); g_assert_true(acceptance.need_points_switch); } void test_world_not_needs_points_switch_when_train_on_active_track(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_train* train = &(test_ctx->train); sem_world* world = &(test_ctx->world); sem_tile_acceptance acceptance; sem_tile_acceptance_init(&acceptance); train->direction = SEM_EAST; sem_track trackNW_E; sem_track_set(&trackNW_E, SEM_NORTH | SEM_WEST, SEM_EAST); sem_track trackW_E; sem_track_set(&trackW_E, SEM_WEST, SEM_EAST); sem_tile* tile = sem_tile_at(world, 1, 0); sem_tile_set_points(tile, &trackW_E); tile->points[0] = &trackNW_E; tile->points[1] = &trackW_E; sem_tile_accept(train, tile, &acceptance); g_assert_false(acceptance.need_points_switch); } void test_world_train_not_accepted_on_unconnected_points(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_train* train = &(test_ctx->train); sem_world* world = &(test_ctx->world); train->direction = SEM_EAST; sem_tile_acceptance acceptance; sem_tile_acceptance_init(&acceptance); sem_track trackN_SE; sem_track_set(&trackN_SE, SEM_NORTH, SEM_SOUTH | SEM_EAST); sem_track trackN_S; sem_track_set(&trackN_S, SEM_NORTH, SEM_SOUTH); sem_tile* tile = sem_tile_at(world, 1, 0); sem_tile_set_points(tile, &trackN_S); tile->points[0] = &trackN_SE; tile->points[1] = &trackN_S; g_assert_true(sem_tile_accept(train, tile, &acceptance) == SEM_ERROR); } void test_world_track_matching_inactive_points(test_world_context* test_ctx, const void* data) { #pragma unused(data) sem_world* world = &(test_ctx->world); sem_tile* tile = sem_tile_at(world, 0, 0); sem_track active_track; sem_track_set(&active_track, SEM_NORTH, SEM_SOUTH); sem_tile_set_points(tile, &active_track); sem_track inactive_track; sem_track_set(&inactive_track, SEM_NORTH, SEM_SOUTH | SEM_WEST); tile->points[1] = &inactive_track; sem_track* matched_track = NULL; sem_tile_track_matching(tile, &inactive_track, &matched_track); g_assert_false(matched_track == NULL); g_assert_true(matched_track == &inactive_track); } void test_world_track_part_horizontal_first(test_world_context* test_ctx, const void* data) { #pragma unused(test_ctx) #pragma unused(data) sem_track trackSW_NE; sem_track_set(&trackSW_NE, SEM_SOUTH | SEM_WEST, SEM_NORTH | SEM_EAST); sem_track trackW_E; sem_track_set(&trackW_E, SEM_WEST, SEM_EAST); trackW_E.next = &trackSW_NE; g_assert_true(sem_track_part_horizontal(&trackW_E) == &trackW_E); } void test_world_track_part_horizontal_second(test_world_context* test_ctx, const void* data) { #pragma unused(test_ctx) #pragma unused(data) sem_track trackSW_NE; sem_track_set(&trackSW_NE, SEM_SOUTH | SEM_WEST, SEM_NORTH | SEM_EAST); sem_track trackW_E; sem_track_set(&trackW_E, SEM_WEST, SEM_EAST); trackSW_NE.next = &trackW_E; g_assert_true(sem_track_part_horizontal(&trackSW_NE) == &trackW_E); } void test_world_track_part_vertical(test_world_context* test_ctx, const void* data) { #pragma unused(test_ctx) #pragma unused(data) sem_track trackS_N; sem_track_set(&trackS_N, SEM_SOUTH, SEM_NORTH); sem_track trackW_E; sem_track_set(&trackW_E, SEM_WEST, SEM_EAST); trackW_E.next = &trackS_N; g_assert_true(sem_track_part_vertical(&trackW_E) == &trackS_N); }
750505.c
/* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "nrf_bootloader_info.h" /** @brief This variable ensures that the linker script will write the bootloader start address * to the UICR register. This value will be written in the HEX file and thus written to * UICR when the bootloader is flashed into the chip. */ #if defined (__CC_ARM ) #pragma push #pragma diag_suppress 1296 uint32_t m_uicr_bootloader_start_address __attribute__((at(NRF_UICR_BOOTLOADER_START_ADDRESS))) = BOOTLOADER_START_ADDR; #pragma pop #elif defined ( __GNUC__ ) volatile uint32_t m_uicr_bootloader_start_address __attribute__ ((section(".uicrBootStartAddress"))) = BOOTLOADER_START_ADDR; #elif defined ( __ICCARM__ ) __root const uint32_t m_uicr_bootloader_start_address @ NRF_UICR_BOOTLOADER_START_ADDRESS = BOOTLOADER_START_ADDR; #endif
276996.c
// // Created by Andrew Wade on 2019-01-22. // #include "_mock_tests.h" int main() { GROUP_RUN_SINGLE(mock_tests); }
777243.c
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic INET6 transport hashtables * * Authors: Lotsa people, from code originally in tcp, generalised here * by Arnaldo Carvalho de Melo <[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 (at your option) any later version. */ #include <linux/module.h> #include <linux/random.h> #include <net/inet_connection_sock.h> #include <net/inet_hashtables.h> #include <net/inet6_hashtables.h> #include <net/ip.h> void __inet6_hash(struct inet_hashinfo *hashinfo, struct sock *sk) { struct hlist_head *list; rwlock_t *lock; BUG_TRAP(sk_unhashed(sk)); if (sk->sk_state == TCP_LISTEN) { list = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)]; lock = &hashinfo->lhash_lock; inet_listen_wlock(hashinfo); } else { unsigned int hash; sk->sk_hash = hash = inet6_sk_ehashfn(sk); hash &= (hashinfo->ehash_size - 1); list = &hashinfo->ehash[hash].chain; lock = &hashinfo->ehash[hash].lock; write_lock(lock); } __sk_add_node(sk, list); sock_prot_inc_use(sk->sk_prot); write_unlock(lock); } EXPORT_SYMBOL(__inet6_hash); /* * Sockets in TCP_CLOSE state are _always_ taken out of the hash, so * we need not check it for TCP lookups anymore, thanks Alexey. -DaveM * * The sockhash lock must be held as a reader here. */ struct sock *__inet6_lookup_established(struct inet_hashinfo *hashinfo, const struct in6_addr *saddr, const __be16 sport, const struct in6_addr *daddr, const u16 hnum, const int dif) { struct sock *sk; const struct hlist_node *node; const __portpair ports = INET_COMBINED_PORTS(sport, hnum); /* Optimize here for direct hit, only listening connections can * have wildcards anyways. */ unsigned int hash = inet6_ehashfn(daddr, hnum, saddr, sport); struct inet_ehash_bucket *head = inet_ehash_bucket(hashinfo, hash); prefetch(head->chain.first); read_lock(&head->lock); sk_for_each(sk, node, &head->chain) { /* For IPV6 do the cheaper port and family tests first. */ if (INET6_MATCH(sk, hash, saddr, daddr, ports, dif)) goto hit; /* You sunk my battleship! */ } /* Must check for a TIME_WAIT'er before going to listener hash. */ sk_for_each(sk, node, &head->twchain) { const struct inet_timewait_sock *tw = inet_twsk(sk); if(*((__portpair *)&(tw->tw_dport)) == ports && sk->sk_family == PF_INET6) { const struct inet6_timewait_sock *tw6 = inet6_twsk(sk); if (ipv6_addr_equal(&tw6->tw_v6_daddr, saddr) && ipv6_addr_equal(&tw6->tw_v6_rcv_saddr, daddr) && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == dif)) goto hit; } } read_unlock(&head->lock); return NULL; hit: sock_hold(sk); read_unlock(&head->lock); return sk; } EXPORT_SYMBOL(__inet6_lookup_established); struct sock *inet6_lookup_listener(struct inet_hashinfo *hashinfo, const struct in6_addr *daddr, const unsigned short hnum, const int dif) { struct sock *sk; const struct hlist_node *node; struct sock *result = NULL; int score, hiscore = 0; read_lock(&hashinfo->lhash_lock); sk_for_each(sk, node, &hashinfo->listening_hash[inet_lhashfn(hnum)]) { if (inet_sk(sk)->num == hnum && sk->sk_family == PF_INET6) { const struct ipv6_pinfo *np = inet6_sk(sk); score = 1; if (!ipv6_addr_any(&np->rcv_saddr)) { if (!ipv6_addr_equal(&np->rcv_saddr, daddr)) continue; score++; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) continue; score++; } if (score == 3) { result = sk; break; } if (score > hiscore) { hiscore = score; result = sk; } } } if (result) sock_hold(result); read_unlock(&hashinfo->lhash_lock); return result; } EXPORT_SYMBOL_GPL(inet6_lookup_listener); struct sock *inet6_lookup(struct inet_hashinfo *hashinfo, const struct in6_addr *saddr, const __be16 sport, const struct in6_addr *daddr, const __be16 dport, const int dif) { struct sock *sk; local_bh_disable(); sk = __inet6_lookup(hashinfo, saddr, sport, daddr, ntohs(dport), dif); local_bh_enable(); return sk; } EXPORT_SYMBOL_GPL(inet6_lookup); static int __inet6_check_established(struct inet_timewait_death_row *death_row, struct sock *sk, const __u16 lport, struct inet_timewait_sock **twp) { struct inet_hashinfo *hinfo = death_row->hashinfo; struct inet_sock *inet = inet_sk(sk); const struct ipv6_pinfo *np = inet6_sk(sk); const struct in6_addr *daddr = &np->rcv_saddr; const struct in6_addr *saddr = &np->daddr; const int dif = sk->sk_bound_dev_if; const __portpair ports = INET_COMBINED_PORTS(inet->dport, lport); const unsigned int hash = inet6_ehashfn(daddr, lport, saddr, inet->dport); struct inet_ehash_bucket *head = inet_ehash_bucket(hinfo, hash); struct sock *sk2; const struct hlist_node *node; struct inet_timewait_sock *tw; prefetch(head->chain.first); write_lock(&head->lock); /* Check TIME-WAIT sockets first. */ sk_for_each(sk2, node, &head->twchain) { const struct inet6_timewait_sock *tw6 = inet6_twsk(sk2); tw = inet_twsk(sk2); if(*((__portpair *)&(tw->tw_dport)) == ports && sk2->sk_family == PF_INET6 && ipv6_addr_equal(&tw6->tw_v6_daddr, saddr) && ipv6_addr_equal(&tw6->tw_v6_rcv_saddr, daddr) && sk2->sk_bound_dev_if == sk->sk_bound_dev_if) { if (twsk_unique(sk, sk2, twp)) goto unique; else goto not_unique; } } tw = NULL; /* And established part... */ sk_for_each(sk2, node, &head->chain) { if (INET6_MATCH(sk2, hash, saddr, daddr, ports, dif)) goto not_unique; } unique: /* Must record num and sport now. Otherwise we will see * in hash table socket with a funny identity. */ inet->num = lport; inet->sport = htons(lport); BUG_TRAP(sk_unhashed(sk)); __sk_add_node(sk, &head->chain); sk->sk_hash = hash; sock_prot_inc_use(sk->sk_prot); write_unlock(&head->lock); if (twp != NULL) { *twp = tw; NET_INC_STATS_BH(LINUX_MIB_TIMEWAITRECYCLED); } else if (tw != NULL) { /* Silly. Should hash-dance instead... */ inet_twsk_deschedule(tw, death_row); NET_INC_STATS_BH(LINUX_MIB_TIMEWAITRECYCLED); inet_twsk_put(tw); } return 0; not_unique: write_unlock(&head->lock); return -EADDRNOTAVAIL; } static inline u32 inet6_sk_port_offset(const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ipv6_pinfo *np = inet6_sk(sk); return secure_ipv6_port_ephemeral(np->rcv_saddr.s6_addr32, np->daddr.s6_addr32, inet->dport); } int inet6_hash_connect(struct inet_timewait_death_row *death_row, struct sock *sk) { return __inet_hash_connect(death_row, sk, inet6_sk_port_offset(sk), __inet6_check_established, __inet6_hash); } EXPORT_SYMBOL_GPL(inet6_hash_connect);
537011.c
/* clktest.c,v 3.1 1993/07/06 01:05:23 jbj Exp * clktest - test the clock line discipline * * usage: clktest -b bps -f -t timeo -s cmd -c char1 -a char2 /dev/whatever */ #include "clktest-opts.h" #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0) #if defined(ULT_2_0_SUCKS) #ifndef sigmask #define sigmask(m) (1<<(m)) #endif #endif #ifndef STREAM # ifndef CLKLDISC CLOCK_LINE_DISCIPLINE_NEEDED_BY_THIS_PROGRAM; # endif #else # ifdef CLKLDISC ONLY_ONE_CLOCK_LINE_DISCIPLINE_FOR_THIS_PROGRAM; # endif #endif /* * Mask for blocking SIGIO and SIGALRM */ #define BLOCKSIGMASK (sigmask(SIGIO)|sigmask(SIGALRM)) #define progname clktestOptions.pzProgName struct timeval timeout = { 0 }; char *cmd = NULL; int cmdlen; #ifdef CLKLDISC u_long magic1 = DEFMAGIC; u_long magic2 = DEFMAGIC; #endif int speed = B9600; int ttflags = RAW|EVENP|ODDP; volatile int wasalarmed; volatile int iosig; struct timeval lasttv; extern u_long ustotslo[]; extern u_long ustotsmid[]; extern u_long ustotshi[]; int alarming(); int ioready(); /* * main - parse arguments and handle options */ int main( int argc, char *argv[] ) { int fd; struct sgttyb ttyb; struct itimerval itimer; #ifdef STREAM magic[0] = 0; #endif { int ct = optionProcess( &clktestOptions, argc, argv ); if (HAVE_OPT(COMMAND) && (strlen(OPT_ARG(COMMAND)) == 0)) { fputs( "The command option string must not be empty\n", stderr ); USAGE( EXIT_FAILURE ); } if ((argc -= ct) != 1) { fputs( "Missing tty device name\n", stderr ); USAGE( EXIT_FAILURE ); } argv += ct; } #ifdef STREAM if (!strlen(magic)) strcpy(magic,DEFMAGIC); #endif fd = open(*argv, HAVE_OPT(TIMEOUT) ? O_RDWR : O_RDONLY, 0777); if (fd == -1) { fprintf(stderr, "%s: open(%s): ", progname, *argv); perror(""); exit(1); } if (ioctl(fd, TIOCEXCL, (char *)0) < 0) { (void) fprintf(stderr, "%s: ioctl(TIOCEXCL): ", progname); perror(""); exit(1); } /* * If we have the clock discipline, set the port to raw. Otherwise * we run cooked. */ ttyb.sg_ispeed = ttyb.sg_ospeed = speed; #ifdef CLKLDISC ttyb.sg_erase = (char)magic1; ttyb.sg_kill = (char)magic2; #endif ttyb.sg_flags = (short)ttflags; if (ioctl(fd, TIOCSETP, (char *)&ttyb) < 0) { (void) fprintf(stderr, "%s: ioctl(TIOCSETP): ", progname); perror(""); exit(1); } if (fcntl(fd, F_SETOWN, getpid()) == -1) { (void) fprintf(stderr, "%s: fcntl(F_SETOWN): ", progname); perror(""); exit(1); } #ifdef CLKLDISC { int ldisc; ldisc = CLKLDISC; if (ioctl(fd, TIOCSETD, (char *)&ldisc) < 0) { (void) fprintf(stderr, "%s: ioctl(TIOCSETD): ", progname); perror(""); exit(1); } } #endif #ifdef STREAM if (ioctl(fd, I_POP, 0) >=0 ) ; if (ioctl(fd, I_PUSH, "clk") < 0) { (void) fprintf(stderr, "%s: ioctl(I_PUSH): ", progname); perror(""); exit(1); } if (ioctl(fd, CLK_SETSTR, magic) < 0) { (void) fprintf(stderr, "%s: ioctl(CLK_SETSTR): ", progname); perror(""); exit(1); } #endif (void) gettimeofday(&lasttv, (struct timezone *)0); if (HAVE_OPT(TIMEOUT)) { /* * set non-blocking, async I/O on the descriptor */ iosig = 0; (void) signal(SIGIO, ioready); if (fcntl(fd, F_SETFL, FNDELAY|FASYNC) < 0) { (void) fprintf(stderr, "%s: fcntl(F_SETFL): ", progname); perror(""); exit(1); } /* * Set up the alarm interrupt. */ wasalarmed = 0; (void) signal(SIGALRM, alarming); timeout.tv_sec = OPT_VALUE_TIMEOUT; itimer.it_interval = itimer.it_value = timeout; setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0); doboth(fd); } doioonly(fd); } /* * doboth - handle both I/O and alarms via SIGIO */ int doboth( int fd ) { int n; int sawalarm; int sawiosig; int omask; fd_set fds; struct timeval tvzero; sawalarm = 0; sawiosig = 0; FD_ZERO(&fds); for (;;) { omask = sigblock(BLOCKSIGMASK); if (wasalarmed) { /* alarmed? */ sawalarm = 1; wasalarmed = 0; } if (iosig) { sawiosig = 1; iosig = 0; } if (!sawalarm && !sawiosig) { /* * Nothing to do. Wait for something. */ sigpause(omask); if (wasalarmed) { /* alarmed? */ sawalarm = 1; wasalarmed = 0; } if (iosig) { sawiosig = 1; iosig = 0; } } (void)sigsetmask(omask); if (sawiosig) { do { tvzero.tv_sec = tvzero.tv_usec = 0; FD_SET(fd, &fds); n = select(fd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero); if (n > 0) doio(fd); } while (n > 0); if (n == -1) { (void) fprintf(stderr, "%s: select: ", progname); perror(""); exit(1); } sawiosig = 0; } if (sawalarm) { doalarm(fd); sawalarm = 0; } } } /* * doioonly - do I/O. This avoids the use of signals */ int doioonly( int fd ) { int n; fd_set fds; FD_ZERO(&fds); for (;;) { FD_SET(fd, &fds); n = select(fd+1, &fds, (fd_set *)0, (fd_set *)0, (struct timeval *)0); if (n > 0) doio(fd); } } /* * doio - read a buffer full of stuff and print it out */ int doio( int fd ) { register char *rp, *rpend; register char *cp; register int i; char raw[512]; struct timeval tv, tvd; int rlen; int ind; char cooked[2049]; static char *digits = "0123456789abcdef"; rlen = read(fd, raw, sizeof(raw)); if (rlen < 0) { (void) fprintf(stderr, "%s: read(): ", progname); perror(""); return; } if (rlen == 0) { (void) printf("Zero length read\n"); return; } cp = cooked; rp = raw; rpend = &raw[rlen]; ind = 0; while (rp < rpend) { ind = 1; if (isprint(*rp)) *cp++ = *rp; else { *cp++ = '<'; *cp++ = digits[((*rp)>>4) & 0xf]; *cp++ = digits[*rp & 0xf]; *cp++ = '>'; } if ( #ifdef CLKLDISC (*rp == (char)magic1 || *rp == (char)magic2) #else ( strchr( magic, *rp) != NULL ) #endif ) { rp++; ind = 0; *cp = '\0'; if ((rpend - rp) < sizeof(struct timeval)) { (void)printf( "Too little data (%d): %s\n", rpend-rp, cooked); return; } tv.tv_sec = 0; for (i = 0; i < 4; i++) { tv.tv_sec <<= 8; tv.tv_sec |= ((long)*rp++) & 0xff; } tv.tv_usec = 0; for (i = 0; i < 4; i++) { tv.tv_usec <<= 8; tv.tv_usec |= ((long)*rp++) & 0xff; } tvd.tv_sec = tv.tv_sec - lasttv.tv_sec; tvd.tv_usec = tv.tv_usec - lasttv.tv_usec; if (tvd.tv_usec < 0) { tvd.tv_usec += 1000000; tvd.tv_sec--; } (void)printf("%lu.%06lu %lu.%06lu %s\n", tv.tv_sec, tv.tv_usec, tvd.tv_sec, tvd.tv_usec, cooked); lasttv = tv; } else { rp++; } } if (ind) { *cp = '\0'; (void)printf("Incomplete data: %s\n", cooked); } } /* * doalarm - send a string out the port, if we have one. */ int doalarm( int fd ) { int n; if (! HAVE_OPT(COMMAND)) return; n = write(fd, cmd, cmdlen); if (n < 0) { (void) fprintf(stderr, "%s: write(): ", progname); perror(""); } else if (n < cmdlen) { (void) printf("Short write (%d bytes, should be %d)\n", n, cmdlen); } } /* * alarming - receive alarm interupt */ void alarming(void) { wasalarmed = 1; } /* * ioready - handle SIGIO interrupt */ void ioready(void) { iosig = 1; }
598853.c
/*================== * 无向网的最小生成树 * * 包含算法: 7.9 ==================*/ #include "MinimumSpanningTree.h" /* * 普里姆算法中用到的辅助数组, * 用来记录从顶点子集U到顶点子集V-U的代价最小的边 */ static struct { VertexType adjvex; // 顶点子集U中的顶点 VRType lowcost; // 顶点子集V-U到当前顶点的边的权值 } closedge[MAX_VERTEX_NUM]; // 辅助数组 /* * ████████ 算法7.9 ████████ * * 普里姆算法 * * 从第u个顶点出发构造无向网G的最小生成树T,输出T的各条边。 * 该算法的耗时部分是对顶点的遍历,与网中的边数无关,因为适用于边比较稠密的网 * * 注:预设图的权值均大于0,允许调整 */ void MinSpanTree_PRIM(MGraph G, VertexType u) { int i, j, k; // 返回顶点u在无向网中的位置 k = LocateVex(G, u); // 辅助数组初始化,将顶点u加入了顶点子集U for(j = 0; j < G.vexnum; j++) { if(j != k) { closedge[j].adjvex = u; closedge[j].lowcost = G.arcs[k][j].adj; } } // 赋值为0意味着顶点k已进入顶点子集U closedge[k].lowcost = 0; // 选择其余G.vexnum-1个顶点 for(i = 1; i < G.vexnum; i++) { // 从顶点子集V-U中选出下一个候选顶点以便后续加入到最小生成树 k = minimum(G); // 打印顶点和边的信息 printf("%c --%d-- %c\n", closedge[k].adjvex, closedge[k].lowcost, G.vexs[k]); // 将顶点k加入到顶点子集U closedge[k].lowcost = 0; // 新顶点进入顶点子集U后,需要更新顶点子集U与顶点子集V-U的边的信息 for(j = 0; j < G.vexnum; j++) { if(G.arcs[k][j].adj < closedge[j].lowcost) { closedge[j].adjvex = G.vexs[k]; closedge[j].lowcost = G.arcs[k][j].adj; } } } } /* * 从顶点子集V-U中选出下一个候选顶点以便后续加入到最小生成树 * * 选择顶点子集U到顶点子集V-U的权值最小的边, * 并返回该边在顶点子集V-U中那头的端点, * 该端点后续会加入到顶点子集U中,成为最小生成树的新结点。 * * 注:形参与教材中给出的模板有所不同 */ static int minimum(MGraph G) { int i, k = -1; int min = INT_MAX; // 从权值不为0的边中选择拥有最小权值的边 for(i = 0; i < G.vexnum; i++) { if(closedge[i].lowcost != 0 && closedge[i].lowcost < min) { min = closedge[i].lowcost; k = i; } } return k; } /* * 克鲁斯卡尔算法 * * 从第u个顶点出发构造无向网G的最小生成树T,输出T的各条边 * 该算法的耗时部分是对边的遍历,与网中的顶点无关,因为适用于边比较稀疏的网 * * 可以改进之处:对已有边排序时可以采用第9章介绍的堆排序 */ void MinSpanTree_KRUSKAL(MGraph G) { int i, j, k; int s1, s2; // 边集 struct Edge { int v1; // 顶点1的下标 int v2; // 顶点2的下标 VRType adj; // 权值 } * edges, tmp; // 记录已经加入到最小生成树的顶点集,这里使用集合的目的是快速判断候选顶点是否会造成环路 MFSet S; Relation relation; // 边集的容量就是边的数量 edges = (struct Edge*)malloc(G.arcnum* sizeof(struct Edge)); // 对边计数 k = 0; // 获取所有的边 for(i = 0; i < G.vexnum; i++) { // 由于网是无向的,所以只遍历一半的边就可以 for(j = 0; j <= i; j++) { // 只对有效的边进行统计 if(G.arcs[i][j].adj != INFINITE) { edges[k].v1 = i; edges[k].v2 = j; edges[k].adj = G.arcs[i][j].adj; k++; } } } // 根据权值从小到大对边进行排序,这里只是简单使用了效率较低的冒泡排序 for(i = 0; i < G.arcnum - 1; i++) { for(j = 0; j < G.arcnum - i - 1; j++) { // 每轮遍历都将权值大的往后挪 if(edges[j].adj > edges[j + 1].adj) { tmp = edges[j]; edges[j] = edges[j + 1]; edges[j + 1] = tmp; } } } // 初始化顶点集合 initial_mfset(&S, G.vexnum); // 从边集中依次选择权值最小,且不构成环路的边加入到最小生成树 for(i = 0; i < G.arcnum; i++) { s1 = find_mfset(S, edges[i].v1); s2 = find_mfset(S, edges[i].v2); // 如果这两个端点位于同一个集合,则跳过该条边 if(s1 == s2) { continue; } // 构造二元关系 relation.n = 1; relation.pairs[0].i = edges[i].v1; relation.pairs[0].j = edges[i].v2; build_mfset(&S, relation); // 打印顶点和边的信息 printf("%c --%d-- %c\n", GetVex(G, edges[i].v1), edges[i].adj, GetVex(G, edges[i].v2)); } }
40061.c
// zhongling.c inherit NPC; void create() { set_name("钟灵", ({ "zhong ling","zhong" }) ); set("gender", "女性" ); set("age", 15); set("str", 16); set("con", 24); set("dex", 11); set("per", 27); set("int", 24); set("chat_chance", 1); set("chat_msg", ({ "钟灵自言自语道:“要是我的闪电貂在这儿就好了。”\n", }) ); set("inquiry", ([ "段誉" : "段哥哥呢?他在哪儿?", "钟灵" : "我就是钟灵啊。", "甘宝宝" : "甘宝宝是我妈。", "钟万仇" : "钟万仇是我爹。", "here" : "这里是万劫谷。", "木婉清" : "木婉清被关在后面的石屋里,快去救她!", ])); set("attitude", "friendly"); set("max_neili", 200); set("neili", 200); set("force_factor", 10); set("combat_exp", 3500); set_skill("finger", 60); set_skill("parry", 40); set_skill("dodge", 50); set_skill("sword", 30); set_skill("force", 50); set_skill("sun-finger",40); map_skill("finger", "sun-finger"); map_skill("parry", "sun-finger"); setup(); carry_object("/d/wanjiegu/npc/obj/moon-dress")->wear(); carry_object("/d/wanjiegu/npc/obj/shoes")->wear(); carry_object("/d/wanjiegu/npc/obj/xiu-scarf")->wear(); } void init() { object ob; ::init(); if( interactive(ob = this_player()) ) { message_vision("钟灵对$N说道:快去救木姐姐,木姐姐被关在后面的石屋里!\n",ob); } } int accept_object(object who, object ob) { object *inv, sh; int i; inv = all_inventory(this_object()); if (ob->name() == "闪电貂") { tell_object(who,"钟灵说道:谢谢你帮我找回了闪电貂!\n"); tell_object(who,"钟灵说道:下次你见到段誉时,告诉他我已经回家了。\n"); if(!sizeof(inv) ) for ( i=0; i< sizeof(inv); i++ ) if ( inv[i]->name() == "绣花鞋" ) { destruct(inv[i]); tell_object("who, 钟灵脱下一双绣花鞋。\n"); sh = new("/t/wanjiegu/npc/obj/shoes2"); tell_object(who, "钟灵说道:这是我的一双绣花鞋,请你带给段誉。\n"); sh->move(who); return 1; } return 1; } return 0; } void die() { object killer; if (objectp(killer = query_last_damage_from())) killer->set_temp("marks/murder_zhongling", 1); ::die(); }
67727.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 L2CAP utility functions * ******************************************************************************/ #include <stdlib.h> #include <string.h> //#include <stdio.h> #include "controller.h" #include "gki.h" #include "bt_types.h" #include "hcimsgs.h" #include "l2cdefs.h" #include "l2c_int.h" #include "hcidefs.h" #include "btu.h" #include "btm_api.h" #include "btm_int.h" #include "hcidefs.h" #include "allocator.h" /******************************************************************************* ** ** Function l2cu_allocate_lcb ** ** Description Look for an unused LCB ** ** Returns LCB address or NULL if none found ** *******************************************************************************/ tL2C_LCB *l2cu_allocate_lcb (BD_ADDR p_bd_addr, BOOLEAN is_bonding, tBT_TRANSPORT transport) { int xx; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if (!p_lcb->in_use) { memset (p_lcb, 0, sizeof (tL2C_LCB)); memcpy (p_lcb->remote_bd_addr, p_bd_addr, BD_ADDR_LEN); p_lcb->in_use = TRUE; p_lcb->link_state = LST_DISCONNECTED; p_lcb->handle = HCI_INVALID_HANDLE; p_lcb->link_flush_tout = 0xFFFF; p_lcb->timer_entry.param = (TIMER_PARAM_TYPE)p_lcb; p_lcb->info_timer_entry.param = (TIMER_PARAM_TYPE)p_lcb; p_lcb->upda_con_timer.param = (TIMER_PARAM_TYPE)p_lcb; p_lcb->idle_timeout = l2cb.idle_timeout; p_lcb->id = 1; /* spec does not allow '0' */ p_lcb->is_bonding = is_bonding; #if (BLE_INCLUDED == TRUE) p_lcb->transport = transport; p_lcb->tx_data_len = controller_get_interface()->get_ble_default_data_packet_length(); if (transport == BT_TRANSPORT_LE) { l2cb.num_ble_links_active++; l2c_ble_link_adjust_allocation(); } else #endif { l2cb.num_links_active++; l2c_link_adjust_allocation(); } p_lcb->link_xmit_data_q = list_new(NULL); return (p_lcb); } } /* If here, no free LCB found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_update_lcb_4_bonding ** ** Description Mark the lcb for bonding. Used when bonding takes place on ** an existing ACL connection. (Pre-Lisbon devices) ** ** Returns Nothing ** *******************************************************************************/ void l2cu_update_lcb_4_bonding (BD_ADDR p_bd_addr, BOOLEAN is_bonding) { tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr (p_bd_addr, BT_TRANSPORT_BR_EDR); if (p_lcb) { p_lcb->is_bonding = is_bonding; } } /******************************************************************************* ** ** Function l2cu_release_lcb ** ** Description Release an LCB. All timers will be stopped, channels ** dropped, buffers returned etc. ** ** Returns void ** *******************************************************************************/ void l2cu_release_lcb (tL2C_LCB *p_lcb) { tL2C_CCB *p_ccb; p_lcb->in_use = FALSE; p_lcb->is_bonding = FALSE; /* Stop timers */ btu_stop_timer (&p_lcb->timer_entry); btu_stop_timer (&p_lcb->info_timer_entry); /* Release any unfinished L2CAP packet on this link */ if (p_lcb->p_hcit_rcv_acl) { GKI_freebuf(p_lcb->p_hcit_rcv_acl); p_lcb->p_hcit_rcv_acl = NULL; } #if BTM_SCO_INCLUDED == TRUE #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_BR_EDR) #endif /* Release all SCO links */ btm_remove_sco_links(p_lcb->remote_bd_addr); #endif if (p_lcb->sent_not_acked > 0) { #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_LE) { l2cb.controller_le_xmit_window += p_lcb->sent_not_acked; if (l2cb.controller_le_xmit_window > l2cb.num_lm_ble_bufs) { l2cb.controller_le_xmit_window = l2cb.num_lm_ble_bufs; } } else #endif { l2cb.controller_xmit_window += p_lcb->sent_not_acked; if (l2cb.controller_xmit_window > l2cb.num_lm_acl_bufs) { l2cb.controller_xmit_window = l2cb.num_lm_acl_bufs; } } } #if (BLE_INCLUDED == TRUE) // Reset BLE connecting flag only if the address matches if (!memcmp(l2cb.ble_connecting_bda, p_lcb->remote_bd_addr, BD_ADDR_LEN)) { l2cb.is_ble_connecting = FALSE; } #endif #if (L2CAP_NUM_FIXED_CHNLS > 0) l2cu_process_fixed_disc_cback(p_lcb); #endif /* Ensure no CCBs left on this LCB */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_lcb->ccb_queue.p_first_ccb) { l2cu_release_ccb (p_ccb); } /* Tell BTM Acl management the link was removed */ if ((p_lcb->link_state == LST_CONNECTED) || (p_lcb->link_state == LST_DISCONNECTING)) #if (BLE_INCLUDED == TRUE) btm_acl_removed (p_lcb->remote_bd_addr, p_lcb->transport); #else btm_acl_removed (p_lcb->remote_bd_addr, BT_TRANSPORT_BR_EDR); #endif /* Release any held buffers */ if (p_lcb->link_xmit_data_q) { while (!list_is_empty(p_lcb->link_xmit_data_q)) { BT_HDR *p_buf = list_front(p_lcb->link_xmit_data_q); list_remove(p_lcb->link_xmit_data_q, p_buf); GKI_freebuf(p_buf); } list_free(p_lcb->link_xmit_data_q); p_lcb->link_xmit_data_q = NULL; } #if (L2CAP_UCD_INCLUDED == TRUE) /* clean up any security pending UCD */ l2c_ucd_delete_sec_pending_q(p_lcb); #endif #if BLE_INCLUDED == TRUE /* Re-adjust flow control windows make sure it does not go negative */ if (p_lcb->transport == BT_TRANSPORT_LE) { if (l2cb.num_ble_links_active >= 1) { l2cb.num_ble_links_active--; } l2c_ble_link_adjust_allocation(); } else #endif { if (l2cb.num_links_active >= 1) { l2cb.num_links_active--; } l2c_link_adjust_allocation(); } /* Check for ping outstanding */ if (p_lcb->p_echo_rsp_cb) { tL2CA_ECHO_RSP_CB *p_cb = p_lcb->p_echo_rsp_cb; /* Zero out the callback in case app immediately calls us again */ p_lcb->p_echo_rsp_cb = NULL; (*p_cb) (L2CAP_PING_RESULT_NO_LINK); } } /******************************************************************************* ** ** Function l2cu_find_lcb_by_bd_addr ** ** Description Look through all active LCBs for a match based on the ** remote BD address. ** ** Returns pointer to matched LCB, or NULL if no match ** *******************************************************************************/ tL2C_LCB *l2cu_find_lcb_by_bd_addr (BD_ADDR p_bd_addr, tBT_TRANSPORT transport) { int xx; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if ((p_lcb->in_use) && #if BLE_INCLUDED == TRUE p_lcb->transport == transport && #endif (!memcmp (p_lcb->remote_bd_addr, p_bd_addr, BD_ADDR_LEN))) { return (p_lcb); } } /* If here, no match found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_get_conn_role ** ** Description Determine the desired role (master or slave) of a link. ** If already got a slave link, this one must be a master. If ** already got at least 1 link where we are the master, make this ** also a master. ** ** Returns HCI_ROLE_MASTER or HCI_ROLE_SLAVE ** *******************************************************************************/ UINT8 l2cu_get_conn_role (tL2C_LCB *p_this_lcb) { return l2cb.desire_role; } /******************************************************************************* ** ** Function l2c_is_cmd_rejected ** ** Description Checks if cmd_code is command or response ** If a command it will be rejected per spec. ** This function is used when a illegal packet length is detected ** ** Returns BOOLEAN - TRUE if cmd_code is a command and it is rejected, ** FALSE if response code. (command not rejected) ** *******************************************************************************/ BOOLEAN l2c_is_cmd_rejected (UINT8 cmd_code, UINT8 id, tL2C_LCB *p_lcb) { switch (cmd_code) { case L2CAP_CMD_CONN_REQ: case L2CAP_CMD_CONFIG_REQ: case L2CAP_CMD_DISC_REQ: case L2CAP_CMD_ECHO_REQ: case L2CAP_CMD_INFO_REQ: case L2CAP_CMD_AMP_CONN_REQ: case L2CAP_CMD_AMP_MOVE_REQ: case L2CAP_CMD_BLE_UPDATE_REQ: l2cu_send_peer_cmd_reject (p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, id, L2CAP_DEFAULT_MTU, 0); L2CAP_TRACE_WARNING ("Dumping first Command (%d)", cmd_code); return TRUE; default: /* Otherwise a response */ return FALSE; } } /******************************************************************************* ** ** Function l2cu_build_header ** ** Description Builds the L2CAP command packet header ** ** Returns Pointer to allocated packet or NULL if no resources ** *******************************************************************************/ BT_HDR *l2cu_build_header (tL2C_LCB *p_lcb, UINT16 len, UINT8 cmd, UINT8 id) { BT_HDR *p_buf = (BT_HDR *)GKI_getpoolbuf (L2CAP_CMD_POOL_ID); UINT8 *p; if (!p_buf) { return (NULL); } p_buf->offset = L2CAP_SEND_CMD_OFFSET; p_buf->len = len + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET; /* Put in HCI header - handle + pkt boundary */ #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_LE) { UINT16_TO_STREAM (p, (p_lcb->handle | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT))); } else #endif { #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) UINT16_TO_STREAM (p, p_lcb->handle | l2cb.non_flushable_pbf); #else UINT16_TO_STREAM (p, (p_lcb->handle | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT))); #endif } UINT16_TO_STREAM (p, len + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD); UINT16_TO_STREAM (p, len + L2CAP_CMD_OVERHEAD); #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_LE) { //counter_add("l2cap.ble.tx.bytes", p_buf->len); //counter_add("l2cap.ble.tx.pkts", 1); UINT16_TO_STREAM (p, L2CAP_BLE_SIGNALLING_CID); } else #endif { //counter_add("l2cap.sig.tx.bytes", p_buf->len); //counter_add("l2cap.sig.tx.pkts", 1); UINT16_TO_STREAM (p, L2CAP_SIGNALLING_CID); } /* Put in L2CAP command header */ UINT8_TO_STREAM (p, cmd); UINT8_TO_STREAM (p, id); UINT16_TO_STREAM (p, len); return (p_buf); } /******************************************************************************* ** ** Function l2cu_adj_id ** ** Description Checks for valid ID based on specified mask ** and adjusts the id if invalid. ** ** Returns void ** *******************************************************************************/ void l2cu_adj_id (tL2C_LCB *p_lcb, UINT8 adj_mask) { if ((adj_mask & L2CAP_ADJ_ZERO_ID) && !p_lcb->id) { p_lcb->id++; } } /******************************************************************************* ** ** Function l2cu_send_peer_cmd_reject ** ** Description Build and send an L2CAP "command reject" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_cmd_reject (tL2C_LCB *p_lcb, UINT16 reason, UINT8 rem_id, UINT16 p1, UINT16 p2) { UINT16 param_len; BT_HDR *p_buf; UINT8 *p; /* Put in L2CAP packet header */ if (reason == L2CAP_CMD_REJ_MTU_EXCEEDED) { param_len = 2; } else if (reason == L2CAP_CMD_REJ_INVALID_CID) { param_len = 4; } else { param_len = 0; } if ((p_buf = l2cu_build_header (p_lcb, (UINT16) (L2CAP_CMD_REJECT_LEN + param_len), L2CAP_CMD_REJECT, rem_id)) == NULL ) { L2CAP_TRACE_WARNING ("L2CAP - no buffer cmd_rej"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, reason); if (param_len >= 2) { UINT16_TO_STREAM (p, p1); } if (param_len >= 4) { UINT16_TO_STREAM (p, p2); } l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_connect_req ** ** Description Build and send an L2CAP "connection request" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_connect_req (tL2C_CCB *p_ccb) { BT_HDR *p_buf; UINT8 *p; /* Create an identifier for this packet */ p_ccb->p_lcb->id++; l2cu_adj_id(p_ccb->p_lcb, L2CAP_ADJ_ID); p_ccb->local_id = p_ccb->p_lcb->id; if ((p_buf = l2cu_build_header (p_ccb->p_lcb, L2CAP_CONN_REQ_LEN, L2CAP_CMD_CONN_REQ, p_ccb->local_id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for conn_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, p_ccb->p_rcb->real_psm); UINT16_TO_STREAM (p, p_ccb->local_cid); l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_connect_rsp ** ** Description Build and send an L2CAP "connection response" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_connect_rsp (tL2C_CCB *p_ccb, UINT16 result, UINT16 status) { BT_HDR *p_buf; UINT8 *p; if (result == L2CAP_CONN_PENDING) { /* if we already sent pending response */ if (p_ccb->flags & CCB_FLAG_SENT_PENDING) { return; } else { p_ccb->flags |= CCB_FLAG_SENT_PENDING; } } if ((p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, p_ccb->remote_id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for conn_rsp"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, p_ccb->local_cid); UINT16_TO_STREAM (p, p_ccb->remote_cid); UINT16_TO_STREAM (p, result); UINT16_TO_STREAM (p, status); l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_reject_connection ** ** Description Build and send an L2CAP "connection response neg" message ** to the peer. This function is called when there is no peer ** CCB (non-existant PSM or no resources). ** ** Returns void ** *******************************************************************************/ void l2cu_reject_connection (tL2C_LCB *p_lcb, UINT16 remote_cid, UINT8 rem_id, UINT16 result) { BT_HDR *p_buf; UINT8 *p; if ((p_buf = l2cu_build_header(p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, rem_id)) == NULL ) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for conn_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, 0); /* Local CID of 0 */ UINT16_TO_STREAM (p, remote_cid); UINT16_TO_STREAM (p, result); UINT16_TO_STREAM (p, 0); /* Status of 0 */ l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_config_req ** ** Description Build and send an L2CAP "configuration request" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_config_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { BT_HDR *p_buf; UINT16 cfg_len = 0; UINT8 *p; /* Create an identifier for this packet */ p_ccb->p_lcb->id++; l2cu_adj_id(p_ccb->p_lcb, L2CAP_ADJ_ID); p_ccb->local_id = p_ccb->p_lcb->id; if (p_cfg->mtu_present) { cfg_len += L2CAP_CFG_MTU_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->flush_to_present) { cfg_len += L2CAP_CFG_FLUSH_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->qos_present) { cfg_len += L2CAP_CFG_QOS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->fcr_present) { cfg_len += L2CAP_CFG_FCR_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->fcs_present) { cfg_len += L2CAP_CFG_FCS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->ext_flow_spec_present) { cfg_len += L2CAP_CFG_EXT_FLOW_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if ((p_buf = l2cu_build_header (p_ccb->p_lcb, (UINT16) (L2CAP_CONFIG_REQ_LEN + cfg_len), L2CAP_CMD_CONFIG_REQ, p_ccb->local_id)) == NULL ) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for conn_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, p_ccb->remote_cid); UINT16_TO_STREAM (p, p_cfg->flags); /* Flags (continuation) */ /* Now, put the options */ if (p_cfg->mtu_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_MTU); UINT8_TO_STREAM (p, L2CAP_CFG_MTU_OPTION_LEN); UINT16_TO_STREAM (p, p_cfg->mtu); } if (p_cfg->flush_to_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_FLUSH_TOUT); UINT8_TO_STREAM (p, L2CAP_CFG_FLUSH_OPTION_LEN); UINT16_TO_STREAM (p, p_cfg->flush_to); } if (p_cfg->qos_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_QOS); UINT8_TO_STREAM (p, L2CAP_CFG_QOS_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->qos.qos_flags); UINT8_TO_STREAM (p, p_cfg->qos.service_type); UINT32_TO_STREAM (p, p_cfg->qos.token_rate); UINT32_TO_STREAM (p, p_cfg->qos.token_bucket_size); UINT32_TO_STREAM (p, p_cfg->qos.peak_bandwidth); UINT32_TO_STREAM (p, p_cfg->qos.latency); UINT32_TO_STREAM (p, p_cfg->qos.delay_variation); } if (p_cfg->fcr_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_FCR); UINT8_TO_STREAM (p, L2CAP_CFG_FCR_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->fcr.mode); UINT8_TO_STREAM (p, p_cfg->fcr.tx_win_sz); UINT8_TO_STREAM (p, p_cfg->fcr.max_transmit); UINT16_TO_STREAM (p, p_cfg->fcr.rtrans_tout); UINT16_TO_STREAM (p, p_cfg->fcr.mon_tout); UINT16_TO_STREAM (p, p_cfg->fcr.mps); } if (p_cfg->fcs_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_FCS); UINT8_TO_STREAM (p, L2CAP_CFG_FCS_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->fcs); } if (p_cfg->ext_flow_spec_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_EXT_FLOW); UINT8_TO_STREAM (p, L2CAP_CFG_EXT_FLOW_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->ext_flow_spec.id); UINT8_TO_STREAM (p, p_cfg->ext_flow_spec.stype); UINT16_TO_STREAM (p, p_cfg->ext_flow_spec.max_sdu_size); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.sdu_inter_time); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.access_latency); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.flush_timeout); } l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_config_rsp ** ** Description Build and send an L2CAP "configuration response" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_config_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { BT_HDR *p_buf; UINT16 cfg_len = 0; UINT8 *p; /* Create an identifier for this packet */ if (p_cfg->mtu_present) { cfg_len += L2CAP_CFG_MTU_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->flush_to_present) { cfg_len += L2CAP_CFG_FLUSH_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->qos_present) { cfg_len += L2CAP_CFG_QOS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->fcr_present) { cfg_len += L2CAP_CFG_FCR_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if (p_cfg->ext_flow_spec_present) { cfg_len += L2CAP_CFG_EXT_FLOW_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; } if ((p_buf = l2cu_build_header (p_ccb->p_lcb, (UINT16)(L2CAP_CONFIG_RSP_LEN + cfg_len), L2CAP_CMD_CONFIG_RSP, p_ccb->remote_id)) == NULL ) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for conn_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, p_ccb->remote_cid); UINT16_TO_STREAM (p, p_cfg->flags); /* Flags (continuation) Must match request */ UINT16_TO_STREAM (p, p_cfg->result); /* Now, put the options */ if (p_cfg->mtu_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_MTU); UINT8_TO_STREAM (p, L2CAP_CFG_MTU_OPTION_LEN); UINT16_TO_STREAM (p, p_cfg->mtu); } if (p_cfg->flush_to_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_FLUSH_TOUT); UINT8_TO_STREAM (p, L2CAP_CFG_FLUSH_OPTION_LEN); UINT16_TO_STREAM (p, p_cfg->flush_to); } if (p_cfg->qos_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_QOS); UINT8_TO_STREAM (p, L2CAP_CFG_QOS_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->qos.qos_flags); UINT8_TO_STREAM (p, p_cfg->qos.service_type); UINT32_TO_STREAM (p, p_cfg->qos.token_rate); UINT32_TO_STREAM (p, p_cfg->qos.token_bucket_size); UINT32_TO_STREAM (p, p_cfg->qos.peak_bandwidth); UINT32_TO_STREAM (p, p_cfg->qos.latency); UINT32_TO_STREAM (p, p_cfg->qos.delay_variation); } if (p_cfg->fcr_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_FCR); UINT8_TO_STREAM (p, L2CAP_CFG_FCR_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->fcr.mode); UINT8_TO_STREAM (p, p_cfg->fcr.tx_win_sz); UINT8_TO_STREAM (p, p_cfg->fcr.max_transmit); UINT16_TO_STREAM (p, p_ccb->our_cfg.fcr.rtrans_tout); UINT16_TO_STREAM (p, p_ccb->our_cfg.fcr.mon_tout); UINT16_TO_STREAM (p, p_cfg->fcr.mps); } if (p_cfg->ext_flow_spec_present) { UINT8_TO_STREAM (p, L2CAP_CFG_TYPE_EXT_FLOW); UINT8_TO_STREAM (p, L2CAP_CFG_EXT_FLOW_OPTION_LEN); UINT8_TO_STREAM (p, p_cfg->ext_flow_spec.id); UINT8_TO_STREAM (p, p_cfg->ext_flow_spec.stype); UINT16_TO_STREAM (p, p_cfg->ext_flow_spec.max_sdu_size); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.sdu_inter_time); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.access_latency); UINT32_TO_STREAM (p, p_cfg->ext_flow_spec.flush_timeout); } l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_config_rej ** ** Description Build and send an L2CAP "configuration reject" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_config_rej (tL2C_CCB *p_ccb, UINT8 *p_data, UINT16 data_len, UINT16 rej_len) { BT_HDR *p_buf; UINT16 len, cfg_len, buf_space, len1; UINT8 *p, *p_hci_len, *p_data_end; UINT8 cfg_code; L2CAP_TRACE_DEBUG("l2cu_send_peer_config_rej: data_len=%d, rej_len=%d", data_len, rej_len); len = BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN; len1 = 0xFFFF - len; if (rej_len > len1) { L2CAP_TRACE_ERROR ("L2CAP - cfg_rej pkt size exceeds buffer design max limit."); return; } p_buf = (BT_HDR *)GKI_getbuf (len + rej_len); if (!p_buf) { L2CAP_TRACE_ERROR ("L2CAP - no buffer for cfg_rej"); return; } p_buf->offset = L2CAP_SEND_CMD_OFFSET; p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET; /* Put in HCI header - handle + pkt boundary */ #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) if (HCI_NON_FLUSHABLE_PB_SUPPORTED(BTM_ReadLocalFeatures ())) { UINT16_TO_STREAM (p, (p_ccb->p_lcb->handle | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT))); } else #endif { UINT16_TO_STREAM (p, (p_ccb->p_lcb->handle | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT))); } /* Remember the HCI header length position, and save space for it */ p_hci_len = p; p += 2; /* Put in L2CAP packet header */ UINT16_TO_STREAM (p, L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN + rej_len); UINT16_TO_STREAM (p, L2CAP_SIGNALLING_CID); /* Put in L2CAP command header */ UINT8_TO_STREAM (p, L2CAP_CMD_CONFIG_RSP); UINT8_TO_STREAM (p, p_ccb->remote_id); UINT16_TO_STREAM (p, L2CAP_CONFIG_RSP_LEN + rej_len); UINT16_TO_STREAM (p, p_ccb->remote_cid); UINT16_TO_STREAM (p, 0); /* Flags = 0 (no continuation) */ UINT16_TO_STREAM (p, L2CAP_CFG_UNKNOWN_OPTIONS); buf_space = rej_len; /* Now, put the rejected options */ p_data_end = p_data + data_len; while (p_data < p_data_end) { cfg_code = *p_data; cfg_len = *(p_data + 1); switch (cfg_code & 0x7F) { /* skip known options */ case L2CAP_CFG_TYPE_MTU: case L2CAP_CFG_TYPE_FLUSH_TOUT: case L2CAP_CFG_TYPE_QOS: p_data += cfg_len + L2CAP_CFG_OPTION_OVERHEAD; break; /* unknown options; copy into rsp if not hints */ default: /* sanity check option length */ if ((cfg_len + L2CAP_CFG_OPTION_OVERHEAD) <= data_len) { if ((cfg_code & 0x80) == 0) { if (buf_space >= (cfg_len + L2CAP_CFG_OPTION_OVERHEAD)) { memcpy(p, p_data, cfg_len + L2CAP_CFG_OPTION_OVERHEAD); p += cfg_len + L2CAP_CFG_OPTION_OVERHEAD; buf_space -= (cfg_len + L2CAP_CFG_OPTION_OVERHEAD); } else { L2CAP_TRACE_WARNING("L2CAP - cfg_rej exceeds allocated buffer"); p_data = p_data_end; /* force loop exit */ break; } } p_data += cfg_len + L2CAP_CFG_OPTION_OVERHEAD; } /* bad length; force loop exit */ else { p_data = p_data_end; } break; } } len = (UINT16) (p - p_hci_len - 2); UINT16_TO_STREAM (p_hci_len, len); p_buf->len = len + 4; L2CAP_TRACE_DEBUG ("L2CAP - cfg_rej pkt hci_len=%d, l2cap_len=%d", len, (L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN + rej_len)); l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_disc_req ** ** Description Build and send an L2CAP "disconnect request" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_disc_req (tL2C_CCB *p_ccb) { BT_HDR *p_buf, *p_buf2; UINT8 *p; /* Create an identifier for this packet */ p_ccb->p_lcb->id++; l2cu_adj_id(p_ccb->p_lcb, L2CAP_ADJ_ID); p_ccb->local_id = p_ccb->p_lcb->id; if ((p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_DISC_REQ_LEN, L2CAP_CMD_DISC_REQ, p_ccb->local_id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for disc_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, p_ccb->remote_cid); UINT16_TO_STREAM (p, p_ccb->local_cid); /* Move all queued data packets to the LCB. In FCR mode, assume the higher layer checks that all buffers are sent before disconnecting. */ if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) { while (GKI_getfirst(&p_ccb->xmit_hold_q)) { p_buf2 = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q); l2cu_set_acl_hci_header (p_buf2, p_ccb); l2c_link_check_send_pkts (p_ccb->p_lcb, p_ccb, p_buf2); } } l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_disc_rsp ** ** Description Build and send an L2CAP "disconnect response" message ** to the peer. ** ** This function is passed the parameters for the disconnect ** response instead of the CCB address, as it may be called ** to send a disconnect response when there is no CCB. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_disc_rsp (tL2C_LCB *p_lcb, UINT8 remote_id, UINT16 local_cid, UINT16 remote_cid) { BT_HDR *p_buf; UINT8 *p; if ((p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_RSP_LEN, L2CAP_CMD_DISC_RSP, remote_id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for disc_rsp"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, local_cid); UINT16_TO_STREAM (p, remote_cid); l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_echo_req ** ** Description Build and send an L2CAP "echo request" message ** to the peer. Note that we do not currently allow ** data in the echo request. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_echo_req (tL2C_LCB *p_lcb, UINT8 *p_data, UINT16 data_len) { BT_HDR *p_buf; UINT8 *p; p_lcb->id++; l2cu_adj_id(p_lcb, L2CAP_ADJ_ZERO_ID); /* check for wrap to '0' */ if ((p_buf = l2cu_build_header(p_lcb, (UINT16) (L2CAP_ECHO_REQ_LEN + data_len), L2CAP_CMD_ECHO_REQ, p_lcb->id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for echo_req"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; if (data_len) { ARRAY_TO_STREAM (p, p_data, data_len); } l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_echo_rsp ** ** Description Build and send an L2CAP "echo response" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_echo_rsp (tL2C_LCB *p_lcb, UINT8 id, UINT8 *p_data, UINT16 data_len) { BT_HDR *p_buf; UINT8 *p; UINT16 maxlen; /* Filter out duplicate IDs or if available buffers are low (intruder checking) */ if (!id || id == p_lcb->cur_echo_id) { /* Dump this request since it is illegal */ L2CAP_TRACE_WARNING ("L2CAP ignoring duplicate echo request (%d)", id); return; } else { p_lcb->cur_echo_id = id; } /* Don't respond if we more than 10% of our buffers are used */ if (GKI_poolutilization (L2CAP_CMD_POOL_ID) > 10) { L2CAP_TRACE_WARNING ("L2CAP gki pool used up to more than 10%%, ignore echo response"); return; } uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_classic(); uint16_t acl_packet_size = controller_get_interface()->get_acl_packet_size_classic(); /* Don't return data if it does not fit in ACL and L2CAP MTU */ maxlen = (GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID) > acl_packet_size) ? acl_data_size : (UINT16)GKI_get_pool_bufsize(L2CAP_CMD_POOL_ID); maxlen -= (UINT16)(BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD + L2CAP_ECHO_RSP_LEN); if (data_len > maxlen) { data_len = 0; } if ((p_buf = l2cu_build_header (p_lcb, (UINT16)(L2CAP_ECHO_RSP_LEN + data_len), L2CAP_CMD_ECHO_RSP, id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for echo_rsp"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; if (data_len) { ARRAY_TO_STREAM (p, p_data, data_len); } l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_info_req ** ** Description Build and send an L2CAP "info request" message ** to the peer. ** Returns void ** *******************************************************************************/ void l2cu_send_peer_info_req (tL2C_LCB *p_lcb, UINT16 info_type) { BT_HDR *p_buf; UINT8 *p; /* check for wrap and/or BRCM ID */ p_lcb->id++; l2cu_adj_id(p_lcb, L2CAP_ADJ_ID); if ((p_buf = l2cu_build_header(p_lcb, 2, L2CAP_CMD_INFO_REQ, p_lcb->id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for info_req"); return; } L2CAP_TRACE_EVENT ("l2cu_send_peer_info_req: type 0x%04x", info_type); p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, info_type); p_lcb->w4_info_rsp = TRUE; btu_start_timer (&p_lcb->info_timer_entry, BTU_TTYPE_L2CAP_INFO, L2CAP_WAIT_INFO_RSP_TOUT); l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_info_rsp ** ** Description Build and send an L2CAP "info response" message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_info_rsp (tL2C_LCB *p_lcb, UINT8 remote_id, UINT16 info_type) { BT_HDR *p_buf; UINT8 *p; UINT16 len = L2CAP_INFO_RSP_LEN; #if (L2CAP_CONFORMANCE_TESTING == TRUE) if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (l2cb.test_info_resp & (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_EXT_FLOW_SPEC | L2CAP_EXTFEA_FIXED_CHNLS | L2CAP_EXTFEA_EXT_WINDOW | L2CAP_EXTFEA_UCD_RECEPTION )) ) #else if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (L2CAP_EXTFEA_SUPPORTED_MASK & (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_FIXED_CHNLS | L2CAP_EXTFEA_UCD_RECEPTION )) ) #endif { len += L2CAP_EXTENDED_FEATURES_ARRAY_SIZE; } else if (info_type == L2CAP_FIXED_CHANNELS_INFO_TYPE) { len += L2CAP_FIXED_CHNL_ARRAY_SIZE; } else if (info_type == L2CAP_CONNLESS_MTU_INFO_TYPE) { len += L2CAP_CONNLESS_MTU_INFO_SIZE; } if ((p_buf = l2cu_build_header(p_lcb, len, L2CAP_CMD_INFO_RSP, remote_id)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no buffer for info_rsp"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, info_type); #if (L2CAP_CONFORMANCE_TESTING == TRUE) if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (l2cb.test_info_resp & ( L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_UCD_RECEPTION )) ) #else if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (L2CAP_EXTFEA_SUPPORTED_MASK & ( L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_UCD_RECEPTION )) ) #endif { UINT16_TO_STREAM (p, L2CAP_INFO_RESP_RESULT_SUCCESS); #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_LE) { /* optional data are not added for now */ UINT32_TO_STREAM (p, L2CAP_BLE_EXTFEA_MASK); } else #endif { #if L2CAP_CONFORMANCE_TESTING == TRUE UINT32_TO_STREAM (p, l2cb.test_info_resp); #else #if (L2CAP_NUM_FIXED_CHNLS > 0) UINT32_TO_STREAM (p, L2CAP_EXTFEA_SUPPORTED_MASK | L2CAP_EXTFEA_FIXED_CHNLS); #else UINT32_TO_STREAM (p, L2CAP_EXTFEA_SUPPORTED_MASK); #endif #endif } } else if (info_type == L2CAP_FIXED_CHANNELS_INFO_TYPE) { UINT16_TO_STREAM (p, L2CAP_INFO_RESP_RESULT_SUCCESS); memset (p, 0, L2CAP_FIXED_CHNL_ARRAY_SIZE); p[0] = L2CAP_FIXED_CHNL_SIG_BIT; if ( L2CAP_EXTFEA_SUPPORTED_MASK & L2CAP_EXTFEA_UCD_RECEPTION ) { p[0] |= L2CAP_FIXED_CHNL_CNCTLESS_BIT; } #if (L2CAP_NUM_FIXED_CHNLS > 0) { int xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) if (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL) { p[(xx + L2CAP_FIRST_FIXED_CHNL) / 8] |= 1 << ((xx + L2CAP_FIRST_FIXED_CHNL) % 8); } } #endif } else if (info_type == L2CAP_CONNLESS_MTU_INFO_TYPE) { UINT16_TO_STREAM (p, L2CAP_INFO_RESP_RESULT_SUCCESS); UINT16_TO_STREAM (p, L2CAP_UCD_MTU); } else { UINT16_TO_STREAM (p, L2CAP_INFO_RESP_RESULT_NOT_SUPPORTED); /* 'not supported' */ } l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /****************************************************************************** ** ** Function l2cu_enqueue_ccb ** ** Description queue CCB by priority. The first CCB is highest priority and ** is served at first. The CCB is queued to an LLCB or an LCB. ** ** Returns None ** *******************************************************************************/ void l2cu_enqueue_ccb (tL2C_CCB *p_ccb) { tL2C_CCB *p_ccb1; tL2C_CCB_Q *p_q = NULL; /* Find out which queue the channel is on */ if (p_ccb->p_lcb != NULL) { p_q = &p_ccb->p_lcb->ccb_queue; } if ( (!p_ccb->in_use) || (p_q == NULL) ) { L2CAP_TRACE_ERROR ("l2cu_enqueue_ccb CID: 0x%04x ERROR in_use: %u p_lcb: %p", p_ccb->local_cid, p_ccb->in_use, p_ccb->p_lcb); return; } L2CAP_TRACE_DEBUG ("l2cu_enqueue_ccb CID: 0x%04x priority: %d", p_ccb->local_cid, p_ccb->ccb_priority); /* If the queue is empty, we go at the front */ if (!p_q->p_first_ccb) { p_q->p_first_ccb = p_q->p_last_ccb = p_ccb; p_ccb->p_next_ccb = p_ccb->p_prev_ccb = NULL; } else { p_ccb1 = p_q->p_first_ccb; while (p_ccb1 != NULL) { /* Insert new ccb at the end of the same priority. Lower number, higher priority */ if (p_ccb->ccb_priority < p_ccb1->ccb_priority) { /* Are we at the head of the queue ? */ if (p_ccb1 == p_q->p_first_ccb) { p_q->p_first_ccb = p_ccb; } else { p_ccb1->p_prev_ccb->p_next_ccb = p_ccb; } p_ccb->p_next_ccb = p_ccb1; p_ccb->p_prev_ccb = p_ccb1->p_prev_ccb; p_ccb1->p_prev_ccb = p_ccb; break; } p_ccb1 = p_ccb1->p_next_ccb; } /* If we are lower then anyone in the list, we go at the end */ if (!p_ccb1) { /* add new ccb at the end of the list */ p_q->p_last_ccb->p_next_ccb = p_ccb; p_ccb->p_next_ccb = NULL; p_ccb->p_prev_ccb = p_q->p_last_ccb; p_q->p_last_ccb = p_ccb; } } #if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) /* Adding CCB into round robin service table of its LCB */ if (p_ccb->p_lcb != NULL) { /* if this is the first channel in this priority group */ if (p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb == 0 ) { /* Set the first channel to this CCB */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = p_ccb; /* Set the next serving channel in this group to this CCB */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = p_ccb; /* Initialize quota of this priority group based on its priority */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].quota = L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); } /* increase number of channels in this group */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb++; } #endif } /****************************************************************************** ** ** Function l2cu_dequeue_ccb ** ** Description dequeue CCB from a queue ** ** Returns - ** *******************************************************************************/ void l2cu_dequeue_ccb (tL2C_CCB *p_ccb) { tL2C_CCB_Q *p_q = NULL; L2CAP_TRACE_DEBUG ("l2cu_dequeue_ccb CID: 0x%04x", p_ccb->local_cid); /* Find out which queue the channel is on */ if (p_ccb->p_lcb != NULL) { p_q = &p_ccb->p_lcb->ccb_queue; } if ( (!p_ccb->in_use) || (p_q == NULL) || (p_q->p_first_ccb == NULL) ) { L2CAP_TRACE_ERROR ("l2cu_dequeue_ccb CID: 0x%04x ERROR in_use: %u p_lcb: %p p_q: %p p_q->p_first_ccb: %p", p_ccb->local_cid, p_ccb->in_use, p_ccb->p_lcb, p_q, p_q ? p_q->p_first_ccb : 0); return; } #if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) /* Removing CCB from round robin service table of its LCB */ if (p_ccb->p_lcb != NULL) { /* decrease number of channels in this priority group */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb--; /* if it was the last channel in the priority group */ if (p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb == 0 ) { p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = NULL; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = NULL; } else { /* if it is the first channel of this group */ if ( p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb == p_ccb ) { p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = p_ccb->p_next_ccb; } /* if it is the next serving channel of this group */ if ( p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb == p_ccb ) { /* simply, start serving from the first channel */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb; } } } #endif if (p_ccb == p_q->p_first_ccb) { /* We are removing the first in a queue */ p_q->p_first_ccb = p_ccb->p_next_ccb; if (p_q->p_first_ccb) { p_q->p_first_ccb->p_prev_ccb = NULL; } else { p_q->p_last_ccb = NULL; } } else if (p_ccb == p_q->p_last_ccb) { /* We are removing the last in a queue */ p_q->p_last_ccb = p_ccb->p_prev_ccb; p_q->p_last_ccb->p_next_ccb = NULL; } else { /* In the middle of a chain. */ p_ccb->p_prev_ccb->p_next_ccb = p_ccb->p_next_ccb; p_ccb->p_next_ccb->p_prev_ccb = p_ccb->p_prev_ccb; } p_ccb->p_next_ccb = p_ccb->p_prev_ccb = NULL; } /****************************************************************************** ** ** Function l2cu_change_pri_ccb ** ** Description ** ** Returns - ** *******************************************************************************/ void l2cu_change_pri_ccb (tL2C_CCB *p_ccb, tL2CAP_CHNL_PRIORITY priority) { if (p_ccb->ccb_priority != priority) { /* If CCB is not the only guy on the queue */ if ( (p_ccb->p_next_ccb != NULL) || (p_ccb->p_prev_ccb != NULL) ) { L2CAP_TRACE_DEBUG ("Update CCB list in logical link"); /* Remove CCB from queue and re-queue it at new priority */ l2cu_dequeue_ccb (p_ccb); p_ccb->ccb_priority = priority; l2cu_enqueue_ccb (p_ccb); } #if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) else { /* If CCB is the only guy on the queue, no need to re-enqueue */ /* update only round robin service data */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb = 0; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = NULL; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = NULL; p_ccb->ccb_priority = priority; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = p_ccb; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = p_ccb; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].quota = L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb = 1; } #endif } } /******************************************************************************* ** ** Function l2cu_allocate_ccb ** ** Description This function allocates a Channel Control Block and ** attaches it to a link control block. The local CID ** is also assigned. ** ** Returns pointer to CCB, or NULL if none ** *******************************************************************************/ tL2C_CCB *l2cu_allocate_ccb (tL2C_LCB *p_lcb, UINT16 cid) { tL2C_CCB *p_ccb; tL2C_CCB *p_prev; L2CAP_TRACE_DEBUG ("l2cu_allocate_ccb: cid 0x%04x", cid); if (!l2cb.p_free_ccb_first) { return (NULL); } /* If a CID was passed in, use that, else take the first free one */ if (cid == 0) { p_ccb = l2cb.p_free_ccb_first; l2cb.p_free_ccb_first = p_ccb->p_next_ccb; } else { p_prev = NULL; p_ccb = &l2cb.ccb_pool[cid - L2CAP_BASE_APPL_CID]; if (p_ccb == l2cb.p_free_ccb_first) { l2cb.p_free_ccb_first = p_ccb->p_next_ccb; } else { for (p_prev = l2cb.p_free_ccb_first; p_prev != NULL; p_prev = p_prev->p_next_ccb) { if (p_prev->p_next_ccb == p_ccb) { p_prev->p_next_ccb = p_ccb->p_next_ccb; if (p_ccb == l2cb.p_free_ccb_last) { l2cb.p_free_ccb_last = p_prev; } break; } } if (p_prev == NULL) { L2CAP_TRACE_ERROR ("l2cu_allocate_ccb: could not find CCB for CID 0x%04x in the free list", cid); return NULL; } } } p_ccb->p_next_ccb = p_ccb->p_prev_ccb = NULL; p_ccb->in_use = TRUE; /* Get a CID for the connection */ p_ccb->local_cid = L2CAP_BASE_APPL_CID + (UINT16)(p_ccb - l2cb.ccb_pool); p_ccb->p_lcb = p_lcb; p_ccb->p_rcb = NULL; p_ccb->should_free_rcb = false; /* Set priority then insert ccb into LCB queue (if we have an LCB) */ p_ccb->ccb_priority = L2CAP_CHNL_PRIORITY_LOW; if (p_lcb) { l2cu_enqueue_ccb (p_ccb); } /* clear what peer wants to configure */ p_ccb->peer_cfg_bits = 0; /* Put in default values for configuration */ memset (&p_ccb->our_cfg, 0, sizeof(tL2CAP_CFG_INFO)); memset (&p_ccb->peer_cfg, 0, sizeof(tL2CAP_CFG_INFO)); /* Put in default values for local/peer configurations */ p_ccb->our_cfg.flush_to = p_ccb->peer_cfg.flush_to = L2CAP_DEFAULT_FLUSH_TO; p_ccb->our_cfg.mtu = p_ccb->peer_cfg.mtu = L2CAP_DEFAULT_MTU; p_ccb->our_cfg.qos.service_type = p_ccb->peer_cfg.qos.service_type = L2CAP_DEFAULT_SERV_TYPE; p_ccb->our_cfg.qos.token_rate = p_ccb->peer_cfg.qos.token_rate = L2CAP_DEFAULT_TOKEN_RATE; p_ccb->our_cfg.qos.token_bucket_size = p_ccb->peer_cfg.qos.token_bucket_size = L2CAP_DEFAULT_BUCKET_SIZE; p_ccb->our_cfg.qos.peak_bandwidth = p_ccb->peer_cfg.qos.peak_bandwidth = L2CAP_DEFAULT_PEAK_BANDWIDTH; p_ccb->our_cfg.qos.latency = p_ccb->peer_cfg.qos.latency = L2CAP_DEFAULT_LATENCY; p_ccb->our_cfg.qos.delay_variation = p_ccb->peer_cfg.qos.delay_variation = L2CAP_DEFAULT_DELAY; p_ccb->bypass_fcs = 0; memset (&p_ccb->ertm_info, 0, sizeof(tL2CAP_ERTM_INFO)); p_ccb->peer_cfg_already_rejected = FALSE; p_ccb->fcr_cfg_tries = L2CAP_MAX_FCR_CFG_TRIES; p_ccb->fcrb.ack_timer.param = (TIMER_PARAM_TYPE)p_ccb; /* if timer is running, remove it from timer list */ if (p_ccb->fcrb.ack_timer.in_use) { btu_stop_quick_timer (&p_ccb->fcrb.ack_timer); } p_ccb->fcrb.mon_retrans_timer.param = (TIMER_PARAM_TYPE)p_ccb; // btla-specific ++ /* CSP408639 Fix: When L2CAP send amp move channel request or receive * L2CEVT_AMP_MOVE_REQ do following sequence. Send channel move * request -> Stop retrans/monitor timer -> Change channel state to CST_AMP_MOVING. */ if (p_ccb->fcrb.mon_retrans_timer.in_use) { btu_stop_quick_timer (&p_ccb->fcrb.mon_retrans_timer); } // btla-specific -- #if (CLASSIC_BT_INCLUDED == TRUE) l2c_fcr_stop_timer (p_ccb); #endif ///CLASSIC_BT_INCLUDED == TRUE p_ccb->ertm_info.preferred_mode = L2CAP_FCR_BASIC_MODE; /* Default mode for channel is basic mode */ p_ccb->ertm_info.allowed_modes = L2CAP_FCR_CHAN_OPT_BASIC; /* Default mode for channel is basic mode */ p_ccb->ertm_info.fcr_rx_pool_id = L2CAP_FCR_RX_POOL_ID; p_ccb->ertm_info.fcr_tx_pool_id = L2CAP_FCR_TX_POOL_ID; p_ccb->ertm_info.user_rx_pool_id = HCI_ACL_POOL_ID; p_ccb->ertm_info.user_tx_pool_id = HCI_ACL_POOL_ID; p_ccb->max_rx_mtu = L2CAP_MTU_SIZE; p_ccb->tx_mps = GKI_get_pool_bufsize(HCI_ACL_POOL_ID) - 32; GKI_init_q (&p_ccb->xmit_hold_q); p_ccb->cong_sent = FALSE; p_ccb->buff_quota = 2; /* This gets set after config */ /* If CCB was reserved Config_Done can already have some value */ if (cid == 0) { p_ccb->config_done = 0; } else { L2CAP_TRACE_DEBUG ("l2cu_allocate_ccb: cid 0x%04x config_done:0x%x", cid, p_ccb->config_done); } p_ccb->chnl_state = CST_CLOSED; p_ccb->flags = 0; p_ccb->tx_data_rate = L2CAP_CHNL_DATA_RATE_LOW; p_ccb->rx_data_rate = L2CAP_CHNL_DATA_RATE_LOW; #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) p_ccb->is_flushable = FALSE; #endif p_ccb->timer_entry.param = (TIMER_PARAM_TYPE)p_ccb; p_ccb->timer_entry.in_use = 0; l2c_link_adjust_chnl_allocation (); return (p_ccb); } /******************************************************************************* ** ** Function l2cu_start_post_bond_timer ** ** Description This function starts the ACL Link inactivity timer after ** dedicated bonding ** This timer can be longer than the normal link inactivity ** timer for some platforms. ** ** Returns BOOLEAN - TRUE if idle timer started or disconnect initiated ** FALSE if there's one or more pending CCB's exist ** *******************************************************************************/ BOOLEAN l2cu_start_post_bond_timer (UINT16 handle) { UINT16 timeout; tL2C_LCB *p_lcb = l2cu_find_lcb_by_handle(handle); if (!p_lcb) { return (TRUE); } p_lcb->is_bonding = FALSE; /* Only start timer if no control blocks allocated */ if (p_lcb->ccb_queue.p_first_ccb != NULL) { return (FALSE); } /* If no channels on the connection, start idle timeout */ if ( (p_lcb->link_state == LST_CONNECTED) || (p_lcb->link_state == LST_CONNECTING) || (p_lcb->link_state == LST_DISCONNECTING) ) { if (p_lcb->idle_timeout == 0) { if (btsnd_hcic_disconnect (p_lcb->handle, HCI_ERR_PEER_USER)) { p_lcb->link_state = LST_DISCONNECTING; timeout = L2CAP_LINK_DISCONNECT_TOUT; } else { timeout = BT_1SEC_TIMEOUT; } } else { timeout = L2CAP_BONDING_TIMEOUT; } if (timeout != 0xFFFF) { btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, timeout); } return (TRUE); } return (FALSE); } /******************************************************************************* ** ** Function l2cu_release_ccb ** ** Description This function releases a Channel Control Block. The timer ** is stopped, any attached buffers freed, and the CCB is removed ** from the link control block. ** ** Returns void ** *******************************************************************************/ void l2cu_release_ccb (tL2C_CCB *p_ccb) { tL2C_LCB *p_lcb = p_ccb->p_lcb; tL2C_RCB *p_rcb = p_ccb->p_rcb; L2CAP_TRACE_DEBUG ("l2cu_release_ccb: cid 0x%04x in_use: %u", p_ccb->local_cid, p_ccb->in_use); /* If already released, could be race condition */ if (!p_ccb->in_use) { return; } #if (SDP_INCLUDED == TRUE) if (p_rcb && (p_rcb->psm != p_rcb->real_psm)) { btm_sec_clr_service_by_psm(p_rcb->psm); } #endif ///SMP_INCLUDED == TRUE if (p_ccb->should_free_rcb) { osi_free(p_rcb); p_ccb->p_rcb = NULL; p_ccb->should_free_rcb = false; } btm_sec_clr_temp_auth_service (p_lcb->remote_bd_addr); /* Stop the timer */ btu_stop_timer (&p_ccb->timer_entry); while (!GKI_queue_is_empty(&p_ccb->xmit_hold_q)) { GKI_freebuf (GKI_dequeue (&p_ccb->xmit_hold_q)); } #if (CLASSIC_BT_INCLUDED == TRUE) l2c_fcr_cleanup (p_ccb); #endif ///CLASSIC_BT_INCLUDED == TRUE /* Channel may not be assigned to any LCB if it was just pre-reserved */ if ( (p_lcb) && ( (p_ccb->local_cid >= L2CAP_BASE_APPL_CID) #if (L2CAP_UCD_INCLUDED == TRUE) || (p_ccb->local_cid == L2CAP_CONNECTIONLESS_CID) #endif ) ) { l2cu_dequeue_ccb (p_ccb); /* Delink the CCB from the LCB */ p_ccb->p_lcb = NULL; } /* Put the CCB back on the free pool */ if (!l2cb.p_free_ccb_first) { l2cb.p_free_ccb_first = p_ccb; l2cb.p_free_ccb_last = p_ccb; p_ccb->p_next_ccb = NULL; p_ccb->p_prev_ccb = NULL; } else { p_ccb->p_next_ccb = NULL; p_ccb->p_prev_ccb = l2cb.p_free_ccb_last; l2cb.p_free_ccb_last->p_next_ccb = p_ccb; l2cb.p_free_ccb_last = p_ccb; } /* Flag as not in use */ p_ccb->in_use = FALSE; /* If no channels on the connection, start idle timeout */ if ((p_lcb) && p_lcb->in_use && (p_lcb->link_state == LST_CONNECTED)) { if (!p_lcb->ccb_queue.p_first_ccb) { l2cu_no_dynamic_ccbs (p_lcb); } else { /* Link is still active, adjust channel quotas. */ l2c_link_adjust_chnl_allocation (); } } } /******************************************************************************* ** ** Function l2cu_find_ccb_by_remote_cid ** ** Description Look through all active CCBs on a link for a match based ** on the remote CID. ** ** Returns pointer to matched CCB, or NULL if no match ** *******************************************************************************/ tL2C_CCB *l2cu_find_ccb_by_remote_cid (tL2C_LCB *p_lcb, UINT16 remote_cid) { tL2C_CCB *p_ccb; /* If LCB is NULL, look through all active links */ if (!p_lcb) { return NULL; } else { for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) if ((p_ccb->in_use) && (p_ccb->remote_cid == remote_cid)) { return (p_ccb); } } /* If here, no match found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_allocate_rcb ** ** Description Look through the Registration Control Blocks for a free ** one. ** ** Returns Pointer to the RCB or NULL if not found ** *******************************************************************************/ tL2C_RCB *l2cu_allocate_rcb (UINT16 psm) { tL2C_RCB *p_rcb = &l2cb.rcb_pool[0]; UINT16 xx; for (xx = 0; xx < MAX_L2CAP_CLIENTS; xx++, p_rcb++) { if (!p_rcb->in_use) { p_rcb->in_use = TRUE; p_rcb->psm = psm; #if (L2CAP_UCD_INCLUDED == TRUE) p_rcb->ucd.state = L2C_UCD_STATE_UNUSED; #endif return (p_rcb); } } /* If here, no free RCB found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_release_rcb ** ** Description Mark an RCB as no longet in use ** ** Returns void ** *******************************************************************************/ void l2cu_release_rcb (tL2C_RCB *p_rcb) { p_rcb->in_use = FALSE; p_rcb->psm = 0; } /******************************************************************************* ** ** Function l2cu_disconnect_chnl ** ** Description Disconnect a channel. Typically, this is due to either ** receiving a bad configuration, bad packet or max_retries expiring. ** *******************************************************************************/ void l2cu_disconnect_chnl (tL2C_CCB *p_ccb) { UINT16 local_cid = p_ccb->local_cid; if (local_cid >= L2CAP_BASE_APPL_CID) { tL2CA_DISCONNECT_IND_CB *p_disc_cb = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; L2CAP_TRACE_WARNING ("L2CAP - disconnect_chnl CID: 0x%04x", local_cid); l2cu_send_peer_disc_req (p_ccb); l2cu_release_ccb (p_ccb); (*p_disc_cb)(local_cid, FALSE); } else { /* failure on the AMP channel, probably need to disconnect ACL */ L2CAP_TRACE_ERROR ("L2CAP - disconnect_chnl CID: 0x%04x Ignored", local_cid); } } /******************************************************************************* ** ** Function l2cu_find_rcb_by_psm ** ** Description Look through the Registration Control Blocks to see if ** anyone registered to handle the PSM in question ** ** Returns Pointer to the RCB or NULL if not found ** *******************************************************************************/ tL2C_RCB *l2cu_find_rcb_by_psm (UINT16 psm) { tL2C_RCB *p_rcb = &l2cb.rcb_pool[0]; UINT16 xx; for (xx = 0; xx < MAX_L2CAP_CLIENTS; xx++, p_rcb++) { if ((p_rcb->in_use) && (p_rcb->psm == psm)) { return (p_rcb); } } /* If here, no match found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_process_peer_cfg_req ** ** Description This function is called when the peer sends us a "config request" ** message. It extracts the configuration of interest and saves ** it in the CCB. ** ** Note: Negotiation of the FCR channel type is handled internally, ** all others are passed to the upper layer. ** ** Returns UINT8 - L2CAP_PEER_CFG_OK if passed to upper layer, ** L2CAP_PEER_CFG_UNACCEPTABLE if automatically responded to ** because parameters are unnacceptable from a specification ** point of view. ** L2CAP_PEER_CFG_DISCONNECT if no compatible channel modes ** between the two devices, and shall be closed. ** *******************************************************************************/ UINT8 l2cu_process_peer_cfg_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { BOOLEAN mtu_ok = TRUE; BOOLEAN qos_type_ok = TRUE; BOOLEAN flush_to_ok = TRUE; BOOLEAN fcr_ok = TRUE; #if (CLASSIC_BT_INCLUDED == TRUE) UINT8 fcr_status; #endif ///CLASSIC_BT_INCLUDED == TRUE /* Ignore FCR parameters for basic mode */ if (!p_cfg->fcr_present) { p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; } /* Save the MTU that our peer can receive */ if (p_cfg->mtu_present) { /* Make sure MTU is at least the minimum */ if (p_cfg->mtu >= L2CAP_MIN_MTU) { /* In basic mode, limit the MTU to our buffer size */ if ( (p_cfg->fcr_present == FALSE) && (p_cfg->mtu > L2CAP_MTU_SIZE) ) { p_cfg->mtu = L2CAP_MTU_SIZE; } /* Save the accepted value in case of renegotiation */ p_ccb->peer_cfg.mtu = p_cfg->mtu; p_ccb->peer_cfg.mtu_present = TRUE; p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_MTU; } else { /* Illegal MTU value */ p_cfg->mtu = L2CAP_MIN_MTU; mtu_ok = FALSE; } } /* Reload mtu from a previously accepted config request */ else if (p_ccb->peer_cfg.mtu_present) { p_cfg->mtu_present = TRUE; p_cfg->mtu = p_ccb->peer_cfg.mtu; } /* Verify that the flush timeout is a valid value (0 is illegal) */ if (p_cfg->flush_to_present) { if (!p_cfg->flush_to) { p_cfg->flush_to = 0xFFFF; /* Infinite retransmissions (spec default) */ flush_to_ok = FALSE; } else { /* Save the accepted value in case of renegotiation */ p_ccb->peer_cfg.flush_to_present = TRUE; p_ccb->peer_cfg.flush_to = p_cfg->flush_to; p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FLUSH_TO; } } /* Reload flush_to from a previously accepted config request */ else if (p_ccb->peer_cfg.flush_to_present) { p_cfg->flush_to_present = TRUE; p_cfg->flush_to = p_ccb->peer_cfg.flush_to; } /* Save the QOS settings the the peer is using */ if (p_cfg->qos_present) { /* Make sure service type is not a reserved value; otherwise let upper layer decide if acceptable */ if (p_cfg->qos.service_type <= GUARANTEED) { p_ccb->peer_cfg.qos = p_cfg->qos; p_ccb->peer_cfg.qos_present = TRUE; p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_QOS; } else { /* Illegal service type value */ p_cfg->qos.service_type = BEST_EFFORT; qos_type_ok = FALSE; } } /* Reload QOS from a previously accepted config request */ else if (p_ccb->peer_cfg.qos_present) { p_cfg->qos_present = TRUE; p_cfg->qos = p_ccb->peer_cfg.qos; } #if (CLASSIC_BT_INCLUDED == TRUE) if ((fcr_status = l2c_fcr_process_peer_cfg_req (p_ccb, p_cfg)) == L2CAP_PEER_CFG_DISCONNECT) { /* Notify caller to disconnect the channel (incompatible modes) */ p_cfg->result = L2CAP_CFG_FAILED_NO_REASON; p_cfg->mtu_present = p_cfg->qos_present = p_cfg->flush_to_present = 0; return (L2CAP_PEER_CFG_DISCONNECT); } fcr_ok = (fcr_status == L2CAP_PEER_CFG_OK); #endif ///CLASSIC_BT_INCLUDED == TRUE /* Return any unacceptable parameters */ if (mtu_ok && flush_to_ok && qos_type_ok && fcr_ok) { l2cu_adjust_out_mps (p_ccb); return (L2CAP_PEER_CFG_OK); } else { p_cfg->result = L2CAP_CFG_UNACCEPTABLE_PARAMS; if (mtu_ok) { p_cfg->mtu_present = FALSE; } if (flush_to_ok) { p_cfg->flush_to_present = FALSE; } if (qos_type_ok) { p_cfg->qos_present = FALSE; } if (fcr_ok) { p_cfg->fcr_present = FALSE; } return (L2CAP_PEER_CFG_UNACCEPTABLE); } } /******************************************************************************* ** ** Function l2cu_process_peer_cfg_rsp ** ** Description This function is called when the peer sends us a "config response" ** message. It extracts the configuration of interest and saves ** it in the CCB. ** ** Returns void ** *******************************************************************************/ void l2cu_process_peer_cfg_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { /* If we wanted QoS and the peer sends us a positive response with QoS, use his values */ if ( (p_cfg->qos_present) && (p_ccb->our_cfg.qos_present) ) { p_ccb->our_cfg.qos = p_cfg->qos; } if (p_cfg->fcr_present) { /* Save the retransmission and monitor timeout values */ if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE) { p_ccb->peer_cfg.fcr.rtrans_tout = p_cfg->fcr.rtrans_tout; p_ccb->peer_cfg.fcr.mon_tout = p_cfg->fcr.mon_tout; } /* Calculate the max number of packets for which we can delay sending an ack */ if (p_cfg->fcr.tx_win_sz < p_ccb->our_cfg.fcr.tx_win_sz) { p_ccb->fcrb.max_held_acks = p_cfg->fcr.tx_win_sz / 3; } else { p_ccb->fcrb.max_held_acks = p_ccb->our_cfg.fcr.tx_win_sz / 3; } L2CAP_TRACE_DEBUG ("l2cu_process_peer_cfg_rsp(): peer tx_win_sz: %d, our tx_win_sz: %d, max_held_acks: %d", p_cfg->fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz, p_ccb->fcrb.max_held_acks); } } /******************************************************************************* ** ** Function l2cu_process_our_cfg_req ** ** Description This function is called when we send a "config request" ** message. It extracts the configuration of interest and saves ** it in the CCB. ** ** Returns void ** *******************************************************************************/ void l2cu_process_our_cfg_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { tL2C_LCB *p_lcb; UINT16 hci_flush_to; /* Save the QOS settings we are using for transmit */ if (p_cfg->qos_present) { p_ccb->our_cfg.qos_present = TRUE; p_ccb->our_cfg.qos = p_cfg->qos; } if (p_cfg->fcr_present) { /* Override FCR options if attempting streaming or basic */ if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) { memset(&p_cfg->fcr, 0, sizeof(tL2CAP_FCR_OPTS)); } else { /* On BR/EDR, timer values are zero in config request */ /* On class 2 AMP, timer value in config request shall be non-0 processing time */ /* timer value in config response shall be greater than received processing time */ p_cfg->fcr.mon_tout = p_cfg->fcr.rtrans_tout = 0; if (p_cfg->fcr.mode == L2CAP_FCR_STREAM_MODE) { p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0; } } /* Set the threshold to send acks (may be updated in the cfg response) */ p_ccb->fcrb.max_held_acks = p_cfg->fcr.tx_win_sz / 3; /* Include FCS option only if peer can handle it */ if (p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_NO_CRC) { /* FCS check can be bypassed if peer also desires to bypass */ if (p_cfg->fcs_present && p_cfg->fcs == L2CAP_CFG_FCS_BYPASS) { p_ccb->bypass_fcs |= L2CAP_CFG_FCS_OUR; } } else { p_cfg->fcs_present = FALSE; } } else { p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; } p_ccb->our_cfg.fcr.mode = p_cfg->fcr.mode; p_ccb->our_cfg.fcr_present = p_cfg->fcr_present; /* Check the flush timeout. If it is lower than the current one used */ /* then we need to adjust the flush timeout sent to the controller */ if (p_cfg->flush_to_present) { if ((p_cfg->flush_to == 0) || (p_cfg->flush_to == L2CAP_NO_AUTOMATIC_FLUSH)) { /* don't send invalid flush timeout */ /* SPEC: The sender of the Request shall specify its flush timeout value */ /* if it differs from the default value of 0xFFFF */ p_cfg->flush_to_present = FALSE; } else { p_ccb->our_cfg.flush_to = p_cfg->flush_to; p_lcb = p_ccb->p_lcb; if (p_cfg->flush_to < p_lcb->link_flush_tout) { p_lcb->link_flush_tout = p_cfg->flush_to; /* If the timeout is within range of HCI, set the flush timeout */ if (p_cfg->flush_to <= ((HCI_MAX_AUTO_FLUSH_TOUT * 5) / 8)) { /* Convert flush timeout to 0.625 ms units, with round */ hci_flush_to = ((p_cfg->flush_to * 8) + 3) / 5; btsnd_hcic_write_auto_flush_tout (p_lcb->handle, hci_flush_to); } } } } } /******************************************************************************* ** ** Function l2cu_process_our_cfg_rsp ** ** Description This function is called when we send the peer a "config response" ** message. It extracts the configuration of interest and saves ** it in the CCB. ** ** Returns void ** *******************************************************************************/ #if (CLASSIC_BT_INCLUDED == TRUE) void l2cu_process_our_cfg_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg) { /* If peer wants QoS, we are allowed to change the values in a positive response */ if ( (p_cfg->qos_present) && (p_ccb->peer_cfg.qos_present) ) { p_ccb->peer_cfg.qos = p_cfg->qos; } else { p_cfg->qos_present = FALSE; } l2c_fcr_adj_our_rsp_options (p_ccb, p_cfg); } #endif ///CLASSIC_BT_INCLUDED == TRUE /******************************************************************************* ** ** Function l2cu_device_reset ** ** Description This function is called when reset of the device is ** completed. For all active connection simulate HCI_DISC ** ** Returns void ** *******************************************************************************/ void l2cu_device_reset (void) { int xx; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->handle != HCI_INVALID_HANDLE)) { l2c_link_hci_disc_comp (p_lcb->handle, (UINT8) - 1); } } #if (BLE_INCLUDED == TRUE) l2cb.is_ble_connecting = FALSE; #endif } /******************************************************************************* ** ** Function l2cu_create_conn ** ** Description This function initiates an acl connection via HCI ** ** Returns TRUE if successful, FALSE if gki get buffer fails. ** *******************************************************************************/ BOOLEAN l2cu_create_conn (tL2C_LCB *p_lcb, tBT_TRANSPORT transport) { int xx; tL2C_LCB *p_lcb_cur = &l2cb.lcb_pool[0]; #if BTM_SCO_INCLUDED == TRUE BOOLEAN is_sco_active; #endif #if (BLE_INCLUDED == TRUE) tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; BTM_ReadDevInfo(p_lcb->remote_bd_addr, &dev_type, &addr_type); if (transport == BT_TRANSPORT_LE) { if (!controller_get_interface()->supports_ble()) { return FALSE; } p_lcb->ble_addr_type = addr_type; p_lcb->transport = BT_TRANSPORT_LE; return (l2cble_create_conn(p_lcb)); } #endif /* If there is a connection where we perform as a slave, try to switch roles for this connection */ for (xx = 0, p_lcb_cur = &l2cb.lcb_pool[0]; xx < MAX_L2CAP_LINKS; xx++, p_lcb_cur++) { if (p_lcb_cur == p_lcb) { continue; } if ((p_lcb_cur->in_use) && (p_lcb_cur->link_role == HCI_ROLE_SLAVE)) { #if BTM_SCO_INCLUDED == TRUE /* The LMP_switch_req shall be sent only if the ACL logical transport is in active mode, when encryption is disabled, and all synchronous logical transports on the same physical link are disabled." */ /* Check if there is any SCO Active on this BD Address */ is_sco_active = btm_is_sco_active_by_bdaddr(p_lcb_cur->remote_bd_addr); L2CAP_TRACE_API ("l2cu_create_conn - btm_is_sco_active_by_bdaddr() is_sco_active = %s", \ (is_sco_active == TRUE) ? "TRUE" : "FALSE"); if (is_sco_active == TRUE) { continue; /* No Master Slave switch not allowed when SCO Active */ } #endif /*4_1_TODO check if btm_cb.devcb.local_features to be used instead */ if (HCI_SWITCH_SUPPORTED(BTM_ReadLocalFeatures())) { /* mark this lcb waiting for switch to be completed and start switch on the other one */ p_lcb->link_state = LST_CONNECTING_WAIT_SWITCH; p_lcb->link_role = HCI_ROLE_MASTER; if (BTM_SwitchRole (p_lcb_cur->remote_bd_addr, HCI_ROLE_MASTER, NULL) == BTM_CMD_STARTED) { btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_ROLE_SWITCH_TOUT); return (TRUE); } } } } p_lcb->link_state = LST_CONNECTING; return (l2cu_create_conn_after_switch (p_lcb)); } /******************************************************************************* ** ** Function l2cu_get_num_hi_priority ** ** Description Gets the number of high priority channels. ** ** Returns ** *******************************************************************************/ UINT8 l2cu_get_num_hi_priority (void) { UINT8 no_hi = 0; int xx; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)) { no_hi++; } } return no_hi; } /******************************************************************************* ** ** Function l2cu_create_conn_after_switch ** ** Description This function initiates an acl connection via HCI ** If switch required to create connection it is already done. ** ** Returns TRUE if successful, FALSE if gki get buffer fails. ** *******************************************************************************/ BOOLEAN l2cu_create_conn_after_switch (tL2C_LCB *p_lcb) { UINT8 allow_switch = HCI_CR_CONN_ALLOW_SWITCH; tBTM_INQ_INFO *p_inq_info; UINT8 page_scan_rep_mode; UINT8 page_scan_mode; UINT16 clock_offset; UINT8 *p_features; UINT16 num_acl = BTM_GetNumAclLinks(); tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (p_lcb->remote_bd_addr); UINT8 no_hi_prio_chs = l2cu_get_num_hi_priority(); p_features = BTM_ReadLocalFeatures(); L2CAP_TRACE_DEBUG ("l2cu_create_conn_after_switch :%d num_acl:%d no_hi: %d is_bonding:%d", l2cb.disallow_switch, num_acl, no_hi_prio_chs, p_lcb->is_bonding); /* FW team says that we can participant in 4 piconets * typically 3 piconet + 1 for scanning. * We can enhance the code to count the number of piconets later. */ if ( ((!l2cb.disallow_switch && (num_acl < 3)) || (p_lcb->is_bonding && (no_hi_prio_chs == 0))) && HCI_SWITCH_SUPPORTED(p_features)) { allow_switch = HCI_CR_CONN_ALLOW_SWITCH; } else { allow_switch = HCI_CR_CONN_NOT_ALLOW_SWITCH; } p_lcb->link_state = LST_CONNECTING; /* Check with the BT manager if details about remote device are known */ if ((p_inq_info = BTM_InqDbRead(p_lcb->remote_bd_addr)) != NULL) { page_scan_rep_mode = p_inq_info->results.page_scan_rep_mode; page_scan_mode = p_inq_info->results.page_scan_mode; clock_offset = (UINT16)(p_inq_info->results.clock_offset); } else { /* No info known. Use default settings */ page_scan_rep_mode = HCI_PAGE_SCAN_REP_MODE_R1; page_scan_mode = HCI_MANDATARY_PAGE_SCAN_MODE; clock_offset = (p_dev_rec) ? p_dev_rec->clock_offset : 0; } if (!btsnd_hcic_create_conn (p_lcb->remote_bd_addr, ( HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM3 | HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM5 | HCI_PKT_TYPES_MASK_DH5 ), page_scan_rep_mode, page_scan_mode, clock_offset, allow_switch)) { L2CAP_TRACE_ERROR ("L2CAP - no buffer for l2cu_create_conn"); l2cu_release_lcb (p_lcb); return (FALSE); } btm_acl_update_busy_level (BTM_BLI_PAGE_EVT); btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_CONNECT_TOUT); return (TRUE); } /******************************************************************************* ** ** Function l2cu_find_lcb_by_state ** ** Description Look through all active LCBs for a match based on the ** LCB state. ** ** Returns pointer to first matched LCB, or NULL if no match ** *******************************************************************************/ tL2C_LCB *l2cu_find_lcb_by_state (tL2C_LINK_STATE state) { UINT16 i; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->link_state == state)) { return (p_lcb); } } /* If here, no match found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_lcb_disconnecting ** ** Description On each active lcb, check if the lcb is in disconnecting ** state, or if there are no ccb's on the lcb (implying idle timeout is running), or if last ccb on the link is in disconnecting state. ** ** Returns TRUE if any of above conditions met, FALSE otherwise ** *******************************************************************************/ BOOLEAN l2cu_lcb_disconnecting (void) { tL2C_LCB *p_lcb; tL2C_CCB *p_ccb; UINT16 i; BOOLEAN status = FALSE; p_lcb = &l2cb.lcb_pool[0]; for (i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { if (p_lcb->in_use) { /* no ccbs on lcb, or lcb is in disconnecting state */ if ((!p_lcb->ccb_queue.p_first_ccb) || (p_lcb->link_state == LST_DISCONNECTING)) { status = TRUE; break; } /* only one ccb left on lcb */ else if (p_lcb->ccb_queue.p_first_ccb == p_lcb->ccb_queue.p_last_ccb) { p_ccb = p_lcb->ccb_queue.p_first_ccb; if ((p_ccb->in_use) && ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) || (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) { status = TRUE; break; } } } } return status; } /******************************************************************************* ** ** Function l2cu_set_acl_priority ** ** Description Sets the transmission priority for a channel. ** (For initial implementation only two values are valid. ** L2CAP_PRIORITY_NORMAL and L2CAP_PRIORITY_HIGH). ** ** Returns TRUE if a valid channel, else FALSE ** *******************************************************************************/ BOOLEAN l2cu_set_acl_priority (BD_ADDR bd_addr, UINT8 priority, BOOLEAN reset_after_rs) { tL2C_LCB *p_lcb; UINT8 *pp; UINT8 command[HCI_BRCM_ACL_PRIORITY_PARAM_SIZE]; UINT8 vs_param; //APPL_TRACE_EVENT("SET ACL PRIORITY %d", priority); /* Find the link control block for the acl channel */ if ((p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR)) == NULL) { L2CAP_TRACE_WARNING ("L2CAP - no LCB for L2CA_SetAclPriority"); return (FALSE); } if (BTM_IS_BRCM_CONTROLLER()) { /* Called from above L2CAP through API; send VSC if changed */ if ((!reset_after_rs && (priority != p_lcb->acl_priority)) || /* Called because of a master/slave role switch; if high resend VSC */ ( reset_after_rs && p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)) { pp = command; vs_param = (priority == L2CAP_PRIORITY_HIGH) ? HCI_BRCM_ACL_PRIORITY_HIGH : HCI_BRCM_ACL_PRIORITY_LOW; UINT16_TO_STREAM (pp, p_lcb->handle); UINT8_TO_STREAM (pp, vs_param); BTM_VendorSpecificCommand (HCI_BRCM_SET_ACL_PRIORITY, HCI_BRCM_ACL_PRIORITY_PARAM_SIZE, command, NULL); /* Adjust lmp buffer allocation for this channel if priority changed */ if (p_lcb->acl_priority != priority) { p_lcb->acl_priority = priority; l2c_link_adjust_allocation(); } } } return (TRUE); } #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) /****************************************************************************** ** ** Function l2cu_set_non_flushable_pbf ** ** Description set L2CAP_PKT_START_NON_FLUSHABLE if controller supoorts ** ** Returns void ** *******************************************************************************/ void l2cu_set_non_flushable_pbf (BOOLEAN is_supported) { if (is_supported) { l2cb.non_flushable_pbf = (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT); } else { l2cb.non_flushable_pbf = (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT); } } #endif /******************************************************************************* ** ** Function l2cu_resubmit_pending_sec_req ** ** Description This function is called when required security procedures ** are completed and any pending requests can be re-submitted. ** ** Returns void ** *******************************************************************************/ #if (CLASSIC_BT_INCLUDED == TRUE) void l2cu_resubmit_pending_sec_req (BD_ADDR p_bda) { tL2C_LCB *p_lcb; tL2C_CCB *p_ccb; tL2C_CCB *p_next_ccb; int xx; L2CAP_TRACE_DEBUG ("l2cu_resubmit_pending_sec_req p_bda: %p", p_bda); /* If we are called with a BDA, only resubmit for that BDA */ if (p_bda) { p_lcb = l2cu_find_lcb_by_bd_addr (p_bda, BT_TRANSPORT_BR_EDR); /* If we don't have one, this is an error */ if (p_lcb) { /* For all channels, send the event through their FSMs */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_next_ccb) { p_next_ccb = p_ccb->p_next_ccb; l2c_csm_execute (p_ccb, L2CEVT_SEC_RE_SEND_CMD, NULL); } } else { L2CAP_TRACE_WARNING ("l2cu_resubmit_pending_sec_req - unknown BD_ADDR"); } } else { /* No BDA pasesed in, so check all links */ for (xx = 0, p_lcb = &l2cb.lcb_pool[0]; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if (p_lcb->in_use) { /* For all channels, send the event through their FSMs */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_next_ccb) { p_next_ccb = p_ccb->p_next_ccb; l2c_csm_execute (p_ccb, L2CEVT_SEC_RE_SEND_CMD, NULL); } } } } } #endif ///CLASSIC_BT_INCLUDED == TRUE #if L2CAP_CONFORMANCE_TESTING == TRUE /******************************************************************************* ** ** Function l2cu_set_info_rsp_mask ** ** Description This function allows the script wrapper to change the ** info resp mask for conformance testing. ** ** Returns pointer to CCB, or NULL if none ** *******************************************************************************/ void l2cu_set_info_rsp_mask (UINT32 mask) { l2cb.test_info_resp = mask; } #endif /* L2CAP_CONFORMANCE_TESTING */ /******************************************************************************* ** ** Function l2cu_adjust_out_mps ** ** Description Sets our MPS based on current controller capabilities ** ** Returns void ** *******************************************************************************/ void l2cu_adjust_out_mps (tL2C_CCB *p_ccb) { UINT16 packet_size; /* on the tx side MTU is selected based on packet size of the controller */ packet_size = btm_get_max_packet_size (p_ccb->p_lcb->remote_bd_addr); if (packet_size <= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN)) { /* something is very wrong */ L2CAP_TRACE_ERROR ("l2cu_adjust_out_mps bad packet size: %u will use MPS: %u", packet_size, p_ccb->peer_cfg.fcr.mps); p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps; } else { packet_size -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN); /* We try to negotiate MTU that each packet can be split into whole number of max packets. For example if link is 1.2 max packet size is 339 bytes. At first calculate how many whole packets it is. MAX L2CAP is 1691 + 4 overhead. 1695, that will be 5 Dh5 packets. Now maximum L2CAP packet is 5 * 339 = 1695. Minus 4 bytes L2CAP header 1691. For EDR 2.0 packet size is 1027. So we better send RFCOMM packet as 1 3DH5 packet 1 * 1027 = 1027. Minus 4 bytes L2CAP header 1023. */ if (p_ccb->peer_cfg.fcr.mps >= packet_size) { p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps / packet_size * packet_size; } else { p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps; } L2CAP_TRACE_DEBUG ("l2cu_adjust_out_mps use %d Based on peer_cfg.fcr.mps: %u packet_size: %u", p_ccb->tx_mps, p_ccb->peer_cfg.fcr.mps, packet_size); } } /******************************************************************************* ** ** Function l2cu_initialize_fixed_ccb ** ** Description Initialize a fixed channel's CCB ** ** Returns TRUE or FALSE ** *******************************************************************************/ BOOLEAN l2cu_initialize_fixed_ccb (tL2C_LCB *p_lcb, UINT16 fixed_cid, tL2CAP_FCR_OPTS *p_fcr) { #if (L2CAP_NUM_FIXED_CHNLS > 0) tL2C_CCB *p_ccb; /* If we already have a CCB, then simply return */ if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL] != NULL) { return (TRUE); } if ((p_ccb = l2cu_allocate_ccb (NULL, 0)) == NULL) { return (FALSE); } btu_stop_timer(&p_lcb->timer_entry); /* Set CID for the connection */ p_ccb->local_cid = fixed_cid; p_ccb->remote_cid = fixed_cid; GKI_init_q (&p_ccb->xmit_hold_q); p_ccb->is_flushable = FALSE; p_ccb->timer_entry.param = (TIMER_PARAM_TYPE)p_ccb; if (p_fcr) { /* Set the FCR parameters. For now, we will use default pools */ p_ccb->our_cfg.fcr = p_ccb->peer_cfg.fcr = *p_fcr; p_ccb->ertm_info.fcr_rx_pool_id = HCI_ACL_POOL_ID; p_ccb->ertm_info.fcr_tx_pool_id = HCI_ACL_POOL_ID; p_ccb->ertm_info.user_rx_pool_id = HCI_ACL_POOL_ID; p_ccb->ertm_info.user_tx_pool_id = HCI_ACL_POOL_ID; p_ccb->fcrb.max_held_acks = p_fcr->tx_win_sz / 3; } /* Link ccb to lcb and lcb to ccb */ p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = p_ccb; p_ccb->p_lcb = p_lcb; /* There is no configuration, so if the link is up, the channel is up */ if (p_lcb->link_state == LST_CONNECTED) { p_ccb->chnl_state = CST_OPEN; } /* Set the default idle timeout value to use */ p_ccb->fixed_chnl_idle_tout = l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].default_idle_tout; #endif return (TRUE); } /******************************************************************************* ** ** Function l2cu_no_dynamic_ccbs ** ** Description Handles the case when there are no more dynamic CCBs. If there ** are any fixed CCBs, start the longest of the fixed CCB timeouts, ** otherwise start the default link idle timeout or disconnect. ** ** Returns void ** *******************************************************************************/ void l2cu_no_dynamic_ccbs (tL2C_LCB *p_lcb) { #if (SMP_INCLUDED == TRUE) tBTM_STATUS rc; #endif ///SMP_INCLUDED == TRUE UINT16 timeout = p_lcb->idle_timeout; #if (L2CAP_NUM_FIXED_CHNLS > 0) int xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if ( (p_lcb->p_fixed_ccbs[xx] != NULL) && (p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout > timeout) ) { timeout = p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout; } } #endif /* If the link is pairing, do not mess with the timeouts */ if (p_lcb->is_bonding) { return; } if (timeout == 0) { L2CAP_TRACE_DEBUG ("l2cu_no_dynamic_ccbs() IDLE timer 0, disconnecting link"); #if (SMP_INCLUDED == TRUE) rc = btm_sec_disconnect (p_lcb->handle, HCI_ERR_PEER_USER); if (rc == BTM_CMD_STARTED) { l2cu_process_fixed_disc_cback(p_lcb); p_lcb->link_state = LST_DISCONNECTING; timeout = L2CAP_LINK_DISCONNECT_TOUT; } else if (rc == BTM_SUCCESS) { l2cu_process_fixed_disc_cback(p_lcb); /* BTM SEC will make sure that link is release (probably after pairing is done) */ p_lcb->link_state = LST_DISCONNECTING; timeout = 0xFFFF; } else if ( (p_lcb->is_bonding) && (btsnd_hcic_disconnect (p_lcb->handle, HCI_ERR_PEER_USER)) ) { l2cu_process_fixed_disc_cback(p_lcb); p_lcb->link_state = LST_DISCONNECTING; timeout = L2CAP_LINK_DISCONNECT_TOUT; } else { /* probably no buffer to send disconnect */ timeout = BT_1SEC_TIMEOUT; } #endif ///SMP_INCLUDED == TRUE } if (timeout != 0xFFFF) { L2CAP_TRACE_DEBUG ("l2cu_no_dynamic_ccbs() starting IDLE timeout: %d", timeout); btu_start_timer (&p_lcb->timer_entry, BTU_TTYPE_L2CAP_LINK, timeout); } else { btu_stop_timer(&p_lcb->timer_entry); } } #if (L2CAP_NUM_FIXED_CHNLS > 0) /******************************************************************************* ** ** Function l2cu_process_fixed_chnl_resp ** ** Description handle a fixed channel response (or lack thereof) ** if the link failed, or a fixed channel response was ** not received, the bitfield is all zeros. ** *******************************************************************************/ void l2cu_process_fixed_chnl_resp (tL2C_LCB *p_lcb) { L2CAP_TRACE_DEBUG("%s",__func__); #if (BLE_INCLUDED == TRUE) if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { /* ignore all not assigned BR/EDR channels */ p_lcb->peer_chnl_mask[0] &= (L2CAP_FIXED_CHNL_SIG_BIT | \ L2CAP_FIXED_CHNL_CNCTLESS_BIT | \ L2CAP_FIXED_CHNL_SMP_BR_BIT); } else { p_lcb->peer_chnl_mask[0] = l2cb.l2c_ble_fixed_chnls_mask; } #endif /* Tell all registered fixed channels about the connection */ for (int xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { #if BLE_INCLUDED == TRUE /* skip sending LE fix channel callbacks on BR/EDR links */ if (p_lcb->transport == BT_TRANSPORT_BR_EDR && xx + L2CAP_FIRST_FIXED_CHNL >= L2CAP_ATT_CID && xx + L2CAP_FIRST_FIXED_CHNL <= L2CAP_SMP_CID) { continue; } #endif if (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL) { if (p_lcb->peer_chnl_mask[(xx + L2CAP_FIRST_FIXED_CHNL) / 8] & (1 << ((xx + L2CAP_FIRST_FIXED_CHNL) % 8))) { if (p_lcb->p_fixed_ccbs[xx]) { p_lcb->p_fixed_ccbs[xx]->chnl_state = CST_OPEN; } #if BLE_INCLUDED == TRUE (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, TRUE, 0, p_lcb->transport); #else (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, TRUE, 0, BT_TRANSPORT_BR_EDR); #endif } else { #if BLE_INCLUDED == TRUE (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, p_lcb->transport); #else (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, BT_TRANSPORT_BR_EDR); #endif if (p_lcb->p_fixed_ccbs[xx]) { l2cu_release_ccb (p_lcb->p_fixed_ccbs[xx]); p_lcb->p_fixed_ccbs[xx] = NULL; } } } } } #endif /******************************************************************************* ** ** Function l2cu_process_fixed_disc_cback ** ** Description send l2cap fixed channel disconnection callback to application ** ** ** Returns void ** *******************************************************************************/ void l2cu_process_fixed_disc_cback (tL2C_LCB *p_lcb) { #if (L2CAP_NUM_FIXED_CHNLS > 0) /* Select peer channels mask to use depending on transport */ UINT8 peer_channel_mask = p_lcb->peer_chnl_mask[0]; // For LE, reset the stored peer channel mask if (p_lcb->transport == BT_TRANSPORT_LE) { p_lcb->peer_chnl_mask[0] = 0; } for (int xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if (p_lcb->p_fixed_ccbs[xx]) { if (p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) { tL2C_CCB *p_l2c_chnl_ctrl_block; p_l2c_chnl_ctrl_block = p_lcb->p_fixed_ccbs[xx]; p_lcb->p_fixed_ccbs[xx] = NULL; l2cu_release_ccb(p_l2c_chnl_ctrl_block); #if BLE_INCLUDED == TRUE (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, p_lcb->transport); #else (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, BT_TRANSPORT_BR_EDR); #endif } } else if ( (peer_channel_mask & (1 << (xx + L2CAP_FIRST_FIXED_CHNL))) && (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL) ) #if BLE_INCLUDED == TRUE (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, p_lcb->transport); #else (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, FALSE, p_lcb->disc_reason, BT_TRANSPORT_BR_EDR); #endif } #endif } #if (BLE_INCLUDED == TRUE) /******************************************************************************* ** ** Function l2cu_send_peer_ble_par_req ** ** Description Build and send a BLE parameter update request message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_ble_par_req (tL2C_LCB *p_lcb, UINT16 min_int, UINT16 max_int, UINT16 latency, UINT16 timeout) { BT_HDR *p_buf; UINT8 *p; /* Create an identifier for this packet */ p_lcb->id++; l2cu_adj_id (p_lcb, L2CAP_ADJ_ID); if ((p_buf = l2cu_build_header (p_lcb, L2CAP_CMD_BLE_UPD_REQ_LEN, L2CAP_CMD_BLE_UPDATE_REQ, p_lcb->id)) == NULL ) { L2CAP_TRACE_WARNING ("l2cu_send_peer_ble_par_req - no buffer"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, min_int); UINT16_TO_STREAM (p, max_int); UINT16_TO_STREAM (p, latency); UINT16_TO_STREAM (p, timeout); l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } /******************************************************************************* ** ** Function l2cu_send_peer_ble_par_rsp ** ** Description Build and send a BLE parameter update response message ** to the peer. ** ** Returns void ** *******************************************************************************/ void l2cu_send_peer_ble_par_rsp (tL2C_LCB *p_lcb, UINT16 reason, UINT8 rem_id) { BT_HDR *p_buf; UINT8 *p; if ((p_buf = l2cu_build_header (p_lcb, L2CAP_CMD_BLE_UPD_RSP_LEN, L2CAP_CMD_BLE_UPDATE_RSP, rem_id)) == NULL ) { L2CAP_TRACE_WARNING ("l2cu_send_peer_ble_par_rsp - no buffer"); return; } p = (UINT8 *)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM (p, reason); l2c_link_check_send_pkts (p_lcb, NULL, p_buf); } #endif /* BLE_INCLUDED == TRUE */ /******************************************************************************* ** Functions used by both Full and Light Stack ********************************************************************************/ /******************************************************************************* ** ** Function l2cu_find_lcb_by_handle ** ** Description Look through all active LCBs for a match based on the ** HCI handle. ** ** Returns pointer to matched LCB, or NULL if no match ** *******************************************************************************/ tL2C_LCB *l2cu_find_lcb_by_handle (UINT16 handle) { int xx; tL2C_LCB *p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->handle == handle)) { return (p_lcb); } } /* If here, no match found */ return (NULL); } /******************************************************************************* ** ** Function l2cu_find_ccb_by_cid ** ** Description Look through all active CCBs on a link for a match based ** on the local CID. If passed the link pointer is NULL, all ** active links are searched. ** ** Returns pointer to matched CCB, or NULL if no match ** *******************************************************************************/ tL2C_CCB *l2cu_find_ccb_by_cid (tL2C_LCB *p_lcb, UINT16 local_cid) { tL2C_CCB *p_ccb = NULL; #if (L2CAP_UCD_INCLUDED == TRUE) UINT8 xx; #endif if (local_cid >= L2CAP_BASE_APPL_CID) { /* find the associated CCB by "index" */ local_cid -= L2CAP_BASE_APPL_CID; if (local_cid >= MAX_L2CAP_CHANNELS) { return NULL; } p_ccb = l2cb.ccb_pool + local_cid; /* make sure the CCB is in use */ if (!p_ccb->in_use) { p_ccb = NULL; } /* make sure it's for the same LCB */ else if (p_lcb && p_lcb != p_ccb->p_lcb) { p_ccb = NULL; } } #if (L2CAP_UCD_INCLUDED == TRUE) else { /* searching fixed channel */ p_ccb = l2cb.ccb_pool; for ( xx = 0; xx < MAX_L2CAP_CHANNELS; xx++ ) { if ((p_ccb->local_cid == local_cid) && (p_ccb->in_use) && (p_lcb == p_ccb->p_lcb)) { break; } else { p_ccb++; } } if ( xx >= MAX_L2CAP_CHANNELS ) { return NULL; } } #endif return (p_ccb); } #if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE && CLASSIC_BT_INCLUDED == TRUE) /****************************************************************************** ** ** Function l2cu_get_next_channel_in_rr ** ** Description get the next channel to send on a link. It also adjusts the ** CCB queue to do a basic priority and round-robin scheduling. ** ** Returns pointer to CCB or NULL ** *******************************************************************************/ static tL2C_CCB *l2cu_get_next_channel_in_rr(tL2C_LCB *p_lcb) { tL2C_CCB *p_serve_ccb = NULL; tL2C_CCB *p_ccb; int i, j; /* scan all of priority until finding a channel to serve */ for ( i = 0; (i < L2CAP_NUM_CHNL_PRIORITY) && (!p_serve_ccb); i++ ) { /* scan all channel within serving priority group until finding a channel to serve */ for ( j = 0; (j < p_lcb->rr_serv[p_lcb->rr_pri].num_ccb) && (!p_serve_ccb); j++) { /* scaning from next serving channel */ p_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb; if (!p_ccb) { L2CAP_TRACE_ERROR("p_serve_ccb is NULL, rr_pri=%d", p_lcb->rr_pri); return NULL; } L2CAP_TRACE_DEBUG("RR scan pri=%d, lcid=0x%04x, q_cout=%d", p_ccb->ccb_priority, p_ccb->local_cid, GKI_queue_length(&p_ccb->xmit_hold_q)); /* store the next serving channel */ /* this channel is the last channel of its priority group */ if (( p_ccb->p_next_ccb == NULL ) || ( p_ccb->p_next_ccb->ccb_priority != p_ccb->ccb_priority )) { /* next serving channel is set to the first channel in the group */ p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_first_ccb; } else { /* next serving channel is set to the next channel in the group */ p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_ccb->p_next_ccb; } if (p_ccb->chnl_state != CST_OPEN) { continue; } /* eL2CAP option in use */ if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) { continue; } if ( GKI_queue_is_empty(&p_ccb->fcrb.retrans_q)) { if ( GKI_queue_is_empty(&p_ccb->xmit_hold_q)) { continue; } /* If using the common pool, should be at least 10% free. */ if ( (p_ccb->ertm_info.fcr_tx_pool_id == HCI_ACL_POOL_ID) && (GKI_poolutilization (HCI_ACL_POOL_ID) > 90) ) { continue; } #if (CLASSIC_BT_INCLUDED == TRUE) /* If in eRTM mode, check for window closure */ if ( (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && (l2c_fcr_is_flow_controlled (p_ccb)) ) { continue; } #endif ///CLASSIC_BT_INCLUDED == TRUE } } else { if (GKI_queue_is_empty(&p_ccb->xmit_hold_q)) { continue; } } /* found a channel to serve */ p_serve_ccb = p_ccb; /* decrease quota of its priority group */ p_lcb->rr_serv[p_lcb->rr_pri].quota--; } /* if there is no more quota of the priority group or no channel to have data to send */ if ((p_lcb->rr_serv[p_lcb->rr_pri].quota == 0) || (!p_serve_ccb)) { /* serve next priority group */ p_lcb->rr_pri = (p_lcb->rr_pri + 1) % L2CAP_NUM_CHNL_PRIORITY; /* initialize its quota */ p_lcb->rr_serv[p_lcb->rr_pri].quota = L2CAP_GET_PRIORITY_QUOTA(p_lcb->rr_pri); } } if (p_serve_ccb) { L2CAP_TRACE_DEBUG("RR service pri=%d, quota=%d, lcid=0x%04x", p_serve_ccb->ccb_priority, p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota, p_serve_ccb->local_cid ); } return p_serve_ccb; } #else /* (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) */ /****************************************************************************** ** ** Function l2cu_get_next_channel ** ** Description get the next channel to send on a link bassed on priority ** scheduling. ** ** Returns pointer to CCB or NULL ** *******************************************************************************/ #if (CLASSIC_BT_INCLUDED == TRUE) static tL2C_CCB *l2cu_get_next_channel(tL2C_LCB *p_lcb) { tL2C_CCB *p_ccb; /* Get the first CCB with data to send. */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { if (p_ccb->chnl_state != CST_OPEN) { continue; } if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) { continue; } if (p_ccb->fcrb.retrans_q.count != 0) { return p_ccb; } if (p_ccb->xmit_hold_q.count == 0) { continue; } /* If using the common pool, should be at least 10% free. */ if ( (p_ccb->ertm_info.fcr_tx_pool_id == HCI_ACL_POOL_ID) && (GKI_poolutilization (HCI_ACL_POOL_ID) > 90) ) { continue; } /* If in eRTM mode, check for window closure */ if ( (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && (l2c_fcr_is_flow_controlled (p_ccb)) ) { continue; } /* If here, we found someone */ return p_ccb; } return NULL; } #endif ///CLASSIC_BT_INCLUDED == TRUE #endif /* (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) */ /****************************************************************************** ** ** Function l2cu_get_next_buffer_to_send ** ** Description get the next buffer to send on a link. It also adjusts the ** CCB queue to do a basic priority and round-robin scheduling. ** ** Returns pointer to buffer or NULL ** *******************************************************************************/ BT_HDR *l2cu_get_next_buffer_to_send (tL2C_LCB *p_lcb) { tL2C_CCB *p_ccb; BT_HDR *p_buf = NULL; /* Highest priority are fixed channels */ #if (L2CAP_NUM_FIXED_CHNLS > 0) int xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if ((p_ccb = p_lcb->p_fixed_ccbs[xx]) == NULL) { continue; } /* eL2CAP option in use */ if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { #if (CLASSIC_BT_INCLUDED == TRUE) if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) { continue; } /* No more checks needed if sending from the reatransmit queue */ if (GKI_queue_is_empty(&p_ccb->fcrb.retrans_q)) { if (GKI_queue_is_empty(&p_ccb->xmit_hold_q)) { continue; } /* If using the common pool, should be at least 10% free. */ if ( (p_ccb->ertm_info.fcr_tx_pool_id == HCI_ACL_POOL_ID) && (GKI_poolutilization (HCI_ACL_POOL_ID) > 90) ) { continue; } /* If in eRTM mode, check for window closure */ if ( (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && (l2c_fcr_is_flow_controlled (p_ccb)) ) { continue; } } if ((p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0)) != NULL) { l2cu_check_channel_congestion (p_ccb); l2cu_set_acl_hci_header (p_buf, p_ccb); return (p_buf); } #else continue; #endif ///CLASSIC_BT_INCLUDED == TRUE } else { if (!GKI_queue_is_empty(&p_ccb->xmit_hold_q)) { p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q); if (NULL == p_buf) { L2CAP_TRACE_ERROR("l2cu_get_buffer_to_send: No data to be sent"); return (NULL); } /* send tx complete */ if (l2cb.fixed_reg[xx].pL2CA_FixedTxComplete_Cb) { (*l2cb.fixed_reg[xx].pL2CA_FixedTxComplete_Cb)(p_ccb->local_cid, 1); } l2cu_check_channel_congestion (p_ccb); l2cu_set_acl_hci_header (p_buf, p_ccb); return (p_buf); } } } #endif #if (CLASSIC_BT_INCLUDED == TRUE) #if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) /* get next serving channel in round-robin */ p_ccb = l2cu_get_next_channel_in_rr( p_lcb ); #else p_ccb = l2cu_get_next_channel( p_lcb ); #endif /* Return if no buffer */ if (p_ccb == NULL) { return (NULL); } if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { if ((p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0)) == NULL) { return (NULL); } } else { p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q); if (NULL == p_buf) { L2CAP_TRACE_ERROR("l2cu_get_buffer_to_send() #2: No data to be sent"); return (NULL); } } if ( p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_TxComplete_Cb && (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE) ) { (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, 1); } l2cu_check_channel_congestion (p_ccb); l2cu_set_acl_hci_header (p_buf, p_ccb); #endif ///CLASSIC_BT_INCLUDED == TRUE return (p_buf); } /****************************************************************************** ** ** Function l2cu_set_acl_hci_header ** ** Description Set HCI handle for ACL packet ** ** Returns None ** *******************************************************************************/ void l2cu_set_acl_hci_header (BT_HDR *p_buf, tL2C_CCB *p_ccb) { UINT8 *p; /* Set the pointer to the beginning of the data minus 4 bytes for the packet header */ p = (UINT8 *)(p_buf + 1) + p_buf->offset - HCI_DATA_PREAMBLE_SIZE; #if (BLE_INCLUDED == TRUE) if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT)); uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_ble(); /* The HCI transport will segment the buffers. */ if (p_buf->len > acl_data_size) { UINT16_TO_STREAM (p, acl_data_size); } else { UINT16_TO_STREAM (p, p_buf->len); } } /* (BLE_INCLUDED == TRUE) */ else #endif { #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) if ( (((p_buf->layer_specific & L2CAP_FLUSHABLE_MASK) == L2CAP_FLUSHABLE_CH_BASED) && (p_ccb->is_flushable)) || ((p_buf->layer_specific & L2CAP_FLUSHABLE_MASK) == L2CAP_FLUSHABLE_PKT) ) { UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT)); } else { UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | l2cb.non_flushable_pbf); } #else UINT16_TO_STREAM (p, p_ccb->p_lcb->handle | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT)); #endif uint16_t acl_data_size = controller_get_interface()->get_acl_data_size_classic(); /* The HCI transport will segment the buffers. */ if (p_buf->len > acl_data_size) { UINT16_TO_STREAM (p, acl_data_size); } else { UINT16_TO_STREAM (p, p_buf->len); } } p_buf->offset -= HCI_DATA_PREAMBLE_SIZE; p_buf->len += HCI_DATA_PREAMBLE_SIZE; } /****************************************************************************** ** ** Function l2cu_check_channel_congestion ** ** Description check if any change in congestion status ** ** Returns None ** *******************************************************************************/ void l2cu_check_channel_congestion (tL2C_CCB *p_ccb) { UINT16 q_count = GKI_queue_length(&p_ccb->xmit_hold_q); #if (L2CAP_UCD_INCLUDED == TRUE) if ( p_ccb->local_cid == L2CAP_CONNECTIONLESS_CID ) { q_count += p_ccb->p_lcb->ucd_out_sec_pending_q.count; } #endif /* If the CCB queue limit is subject to a quota, check for congestion */ /* if this channel has outgoing traffic */ if (p_ccb->buff_quota != 0) { /* If this channel was congested */ if ( p_ccb->cong_sent ) { /* If the channel is not congested now, tell the app */ if (q_count <= (p_ccb->buff_quota / 2)) { p_ccb->cong_sent = FALSE; if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb) { L2CAP_TRACE_DEBUG ("L2CAP - Calling CongestionStatus_Cb (FALSE), CID: 0x%04x xmit_hold_q.count: %u buff_quota: %u", p_ccb->local_cid, q_count, p_ccb->buff_quota); /* Prevent recursive calling */ l2cb.is_cong_cback_context = TRUE; (*p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb)(p_ccb->local_cid, FALSE); l2cb.is_cong_cback_context = FALSE; } #if (L2CAP_UCD_INCLUDED == TRUE) else if ( p_ccb->p_rcb && p_ccb->local_cid == L2CAP_CONNECTIONLESS_CID ) { if ( p_ccb->p_rcb->ucd.cb_info.pL2CA_UCD_Congestion_Status_Cb ) { L2CAP_TRACE_DEBUG ("L2CAP - Calling UCD CongestionStatus_Cb (FALSE), SecPendingQ:%u,XmitQ:%u,Quota:%u", p_ccb->p_lcb->ucd_out_sec_pending_q.count, p_ccb->xmit_hold_q.count, p_ccb->buff_quota); p_ccb->p_rcb->ucd.cb_info.pL2CA_UCD_Congestion_Status_Cb( p_ccb->p_lcb->remote_bd_addr, FALSE ); } } #endif #if (L2CAP_NUM_FIXED_CHNLS > 0) else { UINT8 xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx ++) { if (p_ccb->p_lcb->p_fixed_ccbs[xx] == p_ccb) { if (l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb != NULL) { (* l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb)(p_ccb->p_lcb->remote_bd_addr, FALSE); } break; } } } #endif } } else { /* If this channel was not congested but it is congested now, tell the app */ if (q_count > p_ccb->buff_quota) { p_ccb->cong_sent = TRUE; if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb) { L2CAP_TRACE_DEBUG ("L2CAP - Calling CongestionStatus_Cb (TRUE),CID:0x%04x,XmitQ:%u,Quota:%u", p_ccb->local_cid, q_count, p_ccb->buff_quota); (*p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb)(p_ccb->local_cid, TRUE); } #if (L2CAP_UCD_INCLUDED == TRUE) else if ( p_ccb->p_rcb && p_ccb->local_cid == L2CAP_CONNECTIONLESS_CID ) { if ( p_ccb->p_rcb->ucd.cb_info.pL2CA_UCD_Congestion_Status_Cb ) { L2CAP_TRACE_DEBUG ("L2CAP - Calling UCD CongestionStatus_Cb (TRUE), SecPendingQ:%u,XmitQ:%u,Quota:%u", p_ccb->p_lcb->ucd_out_sec_pending_q.count, p_ccb->xmit_hold_q.count, p_ccb->buff_quota); p_ccb->p_rcb->ucd.cb_info.pL2CA_UCD_Congestion_Status_Cb( p_ccb->p_lcb->remote_bd_addr, TRUE ); } } #endif #if (L2CAP_NUM_FIXED_CHNLS > 0) else { UINT8 xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx ++) { if (p_ccb->p_lcb->p_fixed_ccbs[xx] == p_ccb) { if (l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb != NULL) { (* l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb)(p_ccb->p_lcb->remote_bd_addr, TRUE); } break; } } } #endif } } } }
510757.c
/* * sdbm - ndbm work-alike hashed database library * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978). * author: [email protected] * status: public domain. * * core routines */ #include "INTERN.h" #include "config.h" #ifdef WIN32 #include "io.h" #endif #include "sdbm.h" #include "tune.h" #include "pair.h" #ifdef I_FCNTL # include <fcntl.h> #endif #ifdef I_SYS_FILE # include <sys/file.h> #endif #ifdef I_STRING # ifndef __ultrix__ # include <string.h> # endif #else # include <strings.h> #endif /* * externals */ #include <errno.h> /* See notes in perl.h about avoiding extern int errno; */ extern Malloc_t malloc proto((MEM_SIZE)); extern Free_t free proto((Malloc_t)); /* * forward */ static int getdbit proto((DBM *, long)); static int setdbit proto((DBM *, long)); static int getpage proto((DBM *, long)); static datum getnext proto((DBM *)); static int makroom proto((DBM *, long, int)); /* * useful macros */ #define bad(x) ((x).dptr == NULL || (x).dsize < 0) #define exhash(item) sdbm_hash((item).dptr, (item).dsize) #define ioerr(db) ((db)->flags |= DBM_IOERR) #define OFF_PAG(off) (long) (off) * PBLKSIZ #define OFF_DIR(off) (long) (off) * DBLKSIZ static long masks[] = { 000000000000, 000000000001, 000000000003, 000000000007, 000000000017, 000000000037, 000000000077, 000000000177, 000000000377, 000000000777, 000000001777, 000000003777, 000000007777, 000000017777, 000000037777, 000000077777, 000000177777, 000000377777, 000000777777, 000001777777, 000003777777, 000007777777, 000017777777, 000037777777, 000077777777, 000177777777, 000377777777, 000777777777, 001777777777, 003777777777, 007777777777, 017777777777 }; DBM * sdbm_open(register char *file, register int flags, register int mode) { register DBM *db; register char *dirname; register char *pagname; register int n; if (file == NULL || !*file) return errno = EINVAL, (DBM *) NULL; /* * need space for two seperate filenames */ n = strlen(file) * 2 + strlen(DIRFEXT) + strlen(PAGFEXT) + 2; if ((dirname = (char *) malloc((unsigned) n)) == NULL) return errno = ENOMEM, (DBM *) NULL; /* * build the file names */ dirname = strcat(strcpy(dirname, file), DIRFEXT); pagname = strcpy(dirname + strlen(dirname) + 1, file); pagname = strcat(pagname, PAGFEXT); db = sdbm_prep(dirname, pagname, flags, mode); free((char *) dirname); return db; } DBM * sdbm_prep(char *dirname, char *pagname, int flags, int mode) { register DBM *db; struct stat dstat; if ((db = (DBM *) malloc(sizeof(DBM))) == NULL) return errno = ENOMEM, (DBM *) NULL; db->flags = 0; db->hmask = 0; db->blkptr = 0; db->keyptr = 0; /* * adjust user flags so that WRONLY becomes RDWR, * as required by this package. Also set our internal * flag for RDONLY if needed. */ if (flags & O_WRONLY) flags = (flags & ~O_WRONLY) | O_RDWR; else if ((flags & 03) == O_RDONLY) db->flags = DBM_RDONLY; /* * open the files in sequence, and stat the dirfile. * If we fail anywhere, undo everything, return NULL. */ #if defined(OS2) || defined(MSDOS) || defined(WIN32) || defined(__CYGWIN__) flags |= O_BINARY; # endif if ((db->pagf = open(pagname, flags, mode)) > -1) { if ((db->dirf = open(dirname, flags, mode)) > -1) { /* * need the dirfile size to establish max bit number. */ if (fstat(db->dirf, &dstat) == 0) { /* * zero size: either a fresh database, or one with a single, * unsplit data page: dirpage is all zeros. */ db->dirbno = (!dstat.st_size) ? 0 : -1; db->pagbno = -1; db->maxbno = dstat.st_size * BYTESIZ; (void) memset(db->pagbuf, 0, PBLKSIZ); (void) memset(db->dirbuf, 0, DBLKSIZ); /* * success */ return db; } (void) close(db->dirf); } (void) close(db->pagf); } free((char *) db); return (DBM *) NULL; } void sdbm_close(register DBM *db) { if (db == NULL) errno = EINVAL; else { (void) close(db->dirf); (void) close(db->pagf); free((char *) db); } } datum sdbm_fetch(register DBM *db, datum key) { if (db == NULL || bad(key)) return errno = EINVAL, nullitem; if (getpage(db, exhash(key))) return getpair(db->pagbuf, key); return ioerr(db), nullitem; } int sdbm_exists(register DBM *db, datum key) { if (db == NULL || bad(key)) return errno = EINVAL, -1; if (getpage(db, exhash(key))) return exipair(db->pagbuf, key); return ioerr(db), -1; } int sdbm_delete(register DBM *db, datum key) { if (db == NULL || bad(key)) return errno = EINVAL, -1; if (sdbm_rdonly(db)) return errno = EPERM, -1; if (getpage(db, exhash(key))) { if (!delpair(db->pagbuf, key)) return -1; /* * update the page file */ if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) return ioerr(db), -1; return 0; } return ioerr(db), -1; } int sdbm_store(register DBM *db, datum key, datum val, int flags) { int need; register long hash; if (db == NULL || bad(key)) return errno = EINVAL, -1; if (sdbm_rdonly(db)) return errno = EPERM, -1; need = key.dsize + val.dsize; /* * is the pair too big (or too small) for this database ?? */ if (need < 0 || need > PAIRMAX) return errno = EINVAL, -1; if (getpage(db, (hash = exhash(key)))) { /* * if we need to replace, delete the key/data pair * first. If it is not there, ignore. */ if (flags == DBM_REPLACE) (void) delpair(db->pagbuf, key); #ifdef SEEDUPS else if (duppair(db->pagbuf, key)) return 1; #endif /* * if we do not have enough room, we have to split. */ if (!fitpair(db->pagbuf, need)) if (!makroom(db, hash, need)) return ioerr(db), -1; /* * we have enough room or split is successful. insert the key, * and update the page file. */ (void) putpair(db->pagbuf, key, val); if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) return ioerr(db), -1; /* * success */ return 0; } return ioerr(db), -1; } /* * makroom - make room by splitting the overfull page * this routine will attempt to make room for SPLTMAX times before * giving up. */ static int makroom(register DBM *db, long int hash, int need) { long newp; char twin[PBLKSIZ]; #if defined(DOSISH) || defined(WIN32) char zer[PBLKSIZ]; long oldtail; #endif char *pag = db->pagbuf; char *New = twin; register int smax = SPLTMAX; do { /* * split the current page */ (void) splpage(pag, New, db->hmask + 1); /* * address of the new page */ newp = (hash & db->hmask) | (db->hmask + 1); /* * write delay, read avoidence/cache shuffle: * select the page for incoming pair: if key is to go to the new page, * write out the previous one, and copy the new one over, thus making * it the current page. If not, simply write the new page, and we are * still looking at the page of interest. current page is not updated * here, as sdbm_store will do so, after it inserts the incoming pair. */ #if defined(DOSISH) || defined(WIN32) /* * Fill hole with 0 if made it. * (hole is NOT read as 0) */ oldtail = lseek(db->pagf, 0L, SEEK_END); memset(zer, 0, PBLKSIZ); while (OFF_PAG(newp) > oldtail) { if (lseek(db->pagf, 0L, SEEK_END) < 0 || write(db->pagf, zer, PBLKSIZ) < 0) { return 0; } oldtail += PBLKSIZ; } #endif if (hash & (db->hmask + 1)) { if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) return 0; db->pagbno = newp; (void) memcpy(pag, New, PBLKSIZ); } else if (lseek(db->pagf, OFF_PAG(newp), SEEK_SET) < 0 || write(db->pagf, New, PBLKSIZ) < 0) return 0; if (!setdbit(db, db->curbit)) return 0; /* * see if we have enough room now */ if (fitpair(pag, need)) return 1; /* * try again... update curbit and hmask as getpage would have * done. because of our update of the current page, we do not * need to read in anything. BUT we have to write the current * [deferred] page out, as the window of failure is too great. */ db->curbit = 2 * db->curbit + ((hash & (db->hmask + 1)) ? 2 : 1); db->hmask |= db->hmask + 1; if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0 || write(db->pagf, db->pagbuf, PBLKSIZ) < 0) return 0; } while (--smax); /* * if we are here, this is real bad news. After SPLTMAX splits, * we still cannot fit the key. say goodnight. */ #ifdef BADMESS (void) write(2, "sdbm: cannot insert after SPLTMAX attempts.\n", 44); #endif return 0; } /* * the following two routines will break if * deletions aren't taken into account. (ndbm bug) */ datum sdbm_firstkey(register DBM *db) { if (db == NULL) return errno = EINVAL, nullitem; /* * start at page 0 */ if (lseek(db->pagf, OFF_PAG(0), SEEK_SET) < 0 || read(db->pagf, db->pagbuf, PBLKSIZ) < 0) return ioerr(db), nullitem; db->pagbno = 0; db->blkptr = 0; db->keyptr = 0; return getnext(db); } datum sdbm_nextkey(register DBM *db) { if (db == NULL) return errno = EINVAL, nullitem; return getnext(db); } /* * all important binary trie traversal */ static int getpage(register DBM *db, register long int hash) { register int hbit; register long dbit; register long pagb; dbit = 0; hbit = 0; while (dbit < db->maxbno && getdbit(db, dbit)) dbit = 2 * dbit + ((hash & (1 << hbit++)) ? 2 : 1); debug(("dbit: %d...", dbit)); db->curbit = dbit; db->hmask = masks[hbit]; pagb = hash & db->hmask; /* * see if the block we need is already in memory. * note: this lookaside cache has about 10% hit rate. */ if (pagb != db->pagbno) { /* * note: here, we assume a "hole" is read as 0s. * if not, must zero pagbuf first. */ if (lseek(db->pagf, OFF_PAG(pagb), SEEK_SET) < 0 || read(db->pagf, db->pagbuf, PBLKSIZ) < 0) return 0; if (!chkpage(db->pagbuf)) return 0; db->pagbno = pagb; debug(("pag read: %d\n", pagb)); } return 1; } static int getdbit(register DBM *db, register long int dbit) { register long c; register long dirb; c = dbit / BYTESIZ; dirb = c / DBLKSIZ; if (dirb != db->dirbno) { int got; if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 || (got=read(db->dirf, db->dirbuf, DBLKSIZ)) < 0) return 0; if (got==0) memset(db->dirbuf,0,DBLKSIZ); db->dirbno = dirb; debug(("dir read: %d\n", dirb)); } return db->dirbuf[c % DBLKSIZ] & (1 << dbit % BYTESIZ); } static int setdbit(register DBM *db, register long int dbit) { register long c; register long dirb; c = dbit / BYTESIZ; dirb = c / DBLKSIZ; if (dirb != db->dirbno) { int got; if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 || (got=read(db->dirf, db->dirbuf, DBLKSIZ)) < 0) return 0; if (got==0) memset(db->dirbuf,0,DBLKSIZ); db->dirbno = dirb; debug(("dir read: %d\n", dirb)); } db->dirbuf[c % DBLKSIZ] |= (1 << dbit % BYTESIZ); #if 0 if (dbit >= db->maxbno) db->maxbno += DBLKSIZ * BYTESIZ; #else if (OFF_DIR((dirb+1))*BYTESIZ > db->maxbno) db->maxbno=OFF_DIR((dirb+1))*BYTESIZ; #endif if (lseek(db->dirf, OFF_DIR(dirb), SEEK_SET) < 0 || write(db->dirf, db->dirbuf, DBLKSIZ) < 0) return 0; return 1; } /* * getnext - get the next key in the page, and if done with * the page, try the next page in sequence */ static datum getnext(register DBM *db) { datum key; for (;;) { db->keyptr++; key = getnkey(db->pagbuf, db->keyptr); if (key.dptr != NULL) return key; /* * we either run out, or there is nothing on this page.. * try the next one... If we lost our position on the * file, we will have to seek. */ db->keyptr = 0; if (db->pagbno != db->blkptr++) if (lseek(db->pagf, OFF_PAG(db->blkptr), SEEK_SET) < 0) break; db->pagbno = db->blkptr; if (read(db->pagf, db->pagbuf, PBLKSIZ) <= 0) break; if (!chkpage(db->pagbuf)) break; } return ioerr(db), nullitem; }
954016.c
/****************************************************************************** * Copyright (C) 2003 - 2021 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ /*****************************************************************************/ /** * @file xgpio_sinit.c * @addtogroup gpio_v4_8 * @{ * * The implementation of the XGpio driver's static initialization * functionality. * * @note * * None * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ----------------------------------------------- * 2.01a jvb 10/13/05 First release * 2.11a mta 03/21/07 Updated to new coding style * 4.0 sha 07/15/15 Defined macro XPAR_XGPIO_NUM_INSTANCES if not * defined in xparameters.h * </pre> * *****************************************************************************/ /***************************** Include Files ********************************/ #include "xstatus.h" #ifndef SDT #include "xparameters.h" #endif #include "xgpio_i.h" /************************** Constant Definitions ****************************/ #ifndef XPAR_XGPIO_NUM_INSTANCES #define XPAR_XGPIO_NUM_INSTANCES 0 /**< GPIO instances */ #endif /**************************** Type Definitions ******************************/ /***************** Macros (Inline Functions) Definitions ********************/ /************************** Variable Definitions ****************************/ /************************** Function Prototypes *****************************/ /******************************************************************************/ /** * Lookup the device configuration based on the unique device ID. The table * ConfigTable contains the configuration info for each device in the system. * * @param DeviceId is the device identifier to lookup. * * @return * - A pointer of data type XGpio_Config which points to the * device configuration if DeviceID is found. * - NULL if DeviceID is not found. * * @note None. * ******************************************************************************/ #ifndef SDT XGpio_Config *XGpio_LookupConfig(u16 DeviceId) { XGpio_Config *CfgPtr = NULL; int Index; for (Index = 0; Index < XPAR_XGPIO_NUM_INSTANCES; Index++) { if (XGpio_ConfigTable[Index].DeviceId == DeviceId) { CfgPtr = &XGpio_ConfigTable[Index]; break; } } return CfgPtr; } #else XGpio_Config *XGpio_LookupConfig(UINTPTR BaseAddress) { XGpio_Config *CfgPtr = NULL; int Index; for (Index = 0U; XGpio_ConfigTable[Index].Name != NULL; Index++) { if ((XGpio_ConfigTable[Index].BaseAddress == BaseAddress) || !BaseAddress) { CfgPtr = &XGpio_ConfigTable[Index]; break; } } return CfgPtr; } #endif /****************************************************************************/ /** * Initialize the XGpio instance provided by the caller based on the * given DeviceID. * * Nothing is done except to initialize the InstancePtr. * * @param InstancePtr is a pointer to an XGpio instance. The memory the * pointer references must be pre-allocated by the caller. Further * calls to manipulate the instance/driver through the XGpio API * must be made with this pointer. * @param DeviceId is the unique id of the device controlled by this XGpio * instance. Passing in a device id associates the generic XGpio * instance to a specific device, as chosen by the caller or * application developer. * * @return * - XST_SUCCESS if the initialization was successful. * - XST_DEVICE_NOT_FOUND if the device configuration data was not * found for a device with the supplied device ID. * * @note None. * *****************************************************************************/ #ifndef SDT int XGpio_Initialize(XGpio * InstancePtr, u16 DeviceId) #else int XGpio_Initialize(XGpio * InstancePtr, UINTPTR BaseAddress) #endif { XGpio_Config *ConfigPtr; /* * Assert arguments */ Xil_AssertNonvoid(InstancePtr != NULL); /* * Lookup configuration data in the device configuration table. * Use this configuration info down below when initializing this * driver. */ #ifndef SDT ConfigPtr = XGpio_LookupConfig(DeviceId); #else ConfigPtr = XGpio_LookupConfig(BaseAddress); #endif if (ConfigPtr == (XGpio_Config *) NULL) { InstancePtr->IsReady = 0; return (XST_DEVICE_NOT_FOUND); } return XGpio_CfgInitialize(InstancePtr, ConfigPtr, ConfigPtr->BaseAddress); } /** @} */
973750.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64a.c Label Definition File: CWE78_OS_Command_Injection.no_path.label.xml Template File: sources-sink-64a.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: fromFile Read input from a file * GoodSource: Benign input * Sinks: w32spawnlp * BadSink : execute command with wspawnlp * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 # define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" # define COMMAND_INT L"cmd.exe" # define COMMAND_ARG1 L"/c" # define COMMAND_ARG2 L"dir" # define COMMAND_ARG3 data #else /* NOT _WIN32 */ # define COMMAND_INT_PATH L"/bin/sh" # define COMMAND_INT L"sh" # define COMMAND_ARG1 L"ls" # define COMMAND_ARG2 data # define COMMAND_ARG3 NULL #endif #ifdef _WIN32 # define FOPEN _wfopen #else /* fopen is used on unix-based OSs */ # define FOPEN fopen #endif #include <process.h> #ifndef OMITBAD /* bad function declaration */ void CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64b_bad_sink(void * void_data_ptr); void CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64_bad() { wchar_t * data; wchar_t data_buf[100] = L""; data = data_buf; { /* Read input from a file */ size_t data_len = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if(100-data_len > 1) { pFile = FOPEN(L"C:\\temp\\file.txt", L"r"); if (pFile != NULL) { fgetws(data+data_len, (int)(100-data_len), pFile); fclose(pFile); } } } CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64b_bad_sink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64b_goodG2B_sink(void * void_data_ptr); static void goodG2B() { wchar_t * data; wchar_t data_buf[100] = L""; data = data_buf; /* FIX: Benign input preventing command injection */ wcscat(data, L"*.*"); CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64b_goodG2B_sink(&data); } void CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_fromFile_w32spawnlp_64_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
609938.c
/* MIT License Copyright (c) 2017-2021 Mark E Sowden <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "plm_private.h" /************************************************************/ /* MTL Format */ /* todo */ /************************************************************/ /* Obj Static Model Format */ typedef struct ObjVectorLst { PLVector3 v; struct ObjVectorLst *next; } ObjVectorLst; typedef struct ObjFaceLst { PLGVertex *vertices; unsigned int num_vertices; char mtl_name[ 64 ]; struct ObjFaceLst *next; } ObjFaceLst; typedef struct ObjHandle { ObjVectorLst *vertex_normals; ObjVectorLst *vertex_positions; ObjVectorLst *vertex_tex_coords; ObjFaceLst *faces; char mtllib_path[ PL_SYSTEM_MAX_PATH ]; } ObjHandle; static void FreeObjHandle( ObjHandle *obj ) { PlFree( obj ); } static ObjVectorLst *GetVectorIndex( ObjVectorLst *start, unsigned int idx ) { ObjVectorLst *cur = start; for ( unsigned int i = 0; i < idx - 1; ++i ) { if ( cur->next == NULL ) { ModelLog( "Invalid vector index (%d)!\n", i ); return NULL; } cur = cur->next; } return cur; } PLMModel *PlmLoadObjModel( const char *path ) { PLFile *fp = PlOpenFile( path, false ); if ( fp == NULL ) { return NULL; } ObjHandle *obj = PlMAllocA( sizeof( ObjHandle ) ); ObjVectorLst **cur_v = &( obj->vertex_positions ); ObjVectorLst **cur_vn = &( obj->vertex_normals ); ObjVectorLst **cur_vt = &( obj->vertex_tex_coords ); *cur_v = *cur_vn = *cur_vt = NULL; ObjFaceLst **cur_face = &( obj->faces ); *cur_face = NULL; char tk[ 256 ]; while ( PlReadString( fp, tk, sizeof( tk ) ) != NULL ) { if ( tk[ 0 ] == '\0' || tk[ 0 ] == '#' || tk[ 0 ] == 'o' || tk[ 0 ] == 'g' || tk[ 0 ] == 's' ) { continue; } else if ( tk[ 0 ] == 'v' && tk[ 1 ] == ' ' ) { /* vertex position */ ObjVectorLst *this_v = PlMAllocA( sizeof( ObjVectorLst ) ); unsigned int n = sscanf( &tk[ 2 ], "%f %f %f", &this_v->v.x, &this_v->v.y, &this_v->v.z ); if ( n < 3 ) { ModelLog( "Invalid vertex position, less than 3 coords!\n\"%s\"\n", tk ); } else if ( n > 3 ) { ModelLog( "Ignoring fourth vertex position parameter, unsupported!\n\"%s\"\n", tk ); } *cur_v = this_v; this_v->next = NULL; cur_v = &( this_v->next ); continue; } else if ( tk[ 0 ] == 'v' && tk[ 1 ] == 't' ) { /* vertex texture */ ObjVectorLst *this_vt = PlMAllocA( sizeof( ObjVectorLst ) ); unsigned int n = sscanf( &tk[ 2 ], "%f %f", &this_vt->v.x, &this_vt->v.y ); if ( n < 2 ) { ModelLog( "Invalid vertex uv, less than 2 coords!\n\"%s\"\n", tk ); } else if ( n > 2 ) { ModelLog( "Ignoring third uv parameter, unsupported!\n\"%s\"\n", tk ); } *cur_vt = this_vt; this_vt->next = NULL; cur_vt = &( this_vt->next ); continue; } else if ( tk[ 0 ] == 'v' && tk[ 1 ] == 'n' ) { /* vertex normal */ ObjVectorLst *this_vn = PlMAllocA( sizeof( ObjVectorLst ) ); if ( sscanf( &tk[ 2 ], "%f %f %f", &this_vn->v.x, &this_vn->v.y, &this_vn->v.z ) < 3 ) { ModelLog( "Invalid vertex normal, less than 3 coords!\n\"%s\"\n", tk ); } *cur_vn = this_vn; this_vn->next = NULL; cur_vn = &( this_vn->next ); continue; } else if ( tk[ 0 ] == 'f' && tk[ 1 ] == ' ' ) { /* face */ int idx[ 64 ]; unsigned int num_elements = 1; /* faces are kind of a special case, so we'll need * to parse them manually here */ char *pos = tk; while ( *pos != '\0' && *pos != '\n' && *pos != '\r' ) { if ( *pos == ' ' ) { continue; } pos++; } ObjFaceLst *this_face = PlMAllocA( sizeof( ObjFaceLst ) ); *cur_face = this_face; this_face->next = NULL; cur_face = &( this_face->next ); continue; } ModelLog( "Unknown/unsupported parameter '%s', ignoring!\n", tk[ 0 ] ); } PlCloseFile( fp ); /* right we're finally done, time to see what we hauled... */ return NULL; } bool plWriteObjModel( PLMModel *model, const char *path ) { if ( model == NULL ) { PlReportBasicError( PL_RESULT_INVALID_PARM1 ); return false; } FILE *fp = fopen( path, "w" ); if ( fp == NULL ) { PlReportBasicError( PL_RESULT_FILEWRITE ); return false; } fprintf( fp, "# generated by hei platform lib (https://github.com/TalonBraveInfo/platform)\n" ); if ( model->type == PLM_MODELTYPE_SKELETAL ) { ModelLog( "Model is of type skeletal; Obj only supports static models so skeleton will be discarded...\n" ); } /* for now, use the same name as the model for the material */ const char *filename = PlGetFileName( path ); size_t len = strlen( filename ); char *mtl_name = PlMAllocA( len ); snprintf( mtl_name, len - 4, "%s", PlGetFileName( path ) ); fprintf( fp, "mtllib ./%s.mtl\n", mtl_name ); /* todo: kill duplicated data */ for ( unsigned int i = 0; i < model->numMeshes; ++i ) { PLGMesh *mesh = model->meshes[ i ]; if ( mesh->primitive == PLG_MESH_TRIANGLES ) { fprintf( fp, "o mesh.%0d\n", i ); /* print out vertices */ for ( unsigned int vi = 0; vi < mesh->num_verts; ++i ) { fprintf( fp, "v %s\n", PlPrintVector3( &mesh->vertices[ vi ].position, pl_float_var ) ); } /* print out texture coords */ for ( unsigned int vi = 0; vi < mesh->num_verts; ++i ) { fprintf( fp, "vt %s\n", PlPrintVector2( &mesh->vertices[ vi ].st[ 0 ], pl_float_var ) ); } /* print out vertex normals */ for ( unsigned int vi = 0; vi < mesh->num_verts; ++i ) { fprintf( fp, "vn %s\n", PlPrintVector3( &mesh->vertices[ vi ].normal, pl_float_var ) ); } fprintf( fp, "# %d vertices\n", mesh->num_verts ); if ( mesh->texture != NULL && mesh->texture->name[ 0 ] != '\0' ) { fprintf( fp, "usemtl %s\n", mesh->texture->name ); } for ( unsigned int fi = 0; fi < mesh->num_triangles; ++i ) { fprintf( fp, "f %d/%d/%d\n", mesh->indices[ fi ], mesh->indices[ fi ], mesh->indices[ fi ] ); } } } PlFree( mtl_name ); fclose( fp ); // todo... return true; }
121975.c
//> Scanning on Demand compiler-c #include <stdio.h> //> Compiling Expressions compiler-include-stdlib #include <stdlib.h> //< Compiling Expressions compiler-include-stdlib //> Local Variables compiler-include-string #include <string.h> //< Local Variables compiler-include-string #include "common.h" #include "compiler.h" //> Garbage Collection compiler-include-memory #include "memory.h" //< Garbage Collection compiler-include-memory #include "scanner.h" //> Compiling Expressions include-debug #ifdef DEBUG_PRINT_CODE #include "debug.h" #endif //< Compiling Expressions include-debug //> Compiling Expressions parser typedef struct { Token current; Token previous; //> had-error-field bool hadError; //< had-error-field //> panic-mode-field bool panicMode; //< panic-mode-field } Parser; //> precedence typedef enum { PREC_NONE, PREC_ASSIGNMENT, // = PREC_OR, // or PREC_AND, // and PREC_EQUALITY, // == != PREC_COMPARISON, // < > <= >= PREC_TERM, // + - PREC_FACTOR, // * / PREC_UNARY, // ! - PREC_CALL, // . () PREC_PRIMARY } Precedence; //< precedence //> parse-fn-type //< parse-fn-type /* Compiling Expressions parse-fn-type < Global Variables parse-fn-type typedef void (*ParseFn)(); */ //> Global Variables parse-fn-type typedef void (*ParseFn)(bool canAssign); //< Global Variables parse-fn-type //> parse-rule typedef struct { ParseFn prefix; ParseFn infix; Precedence precedence; } ParseRule; //< parse-rule //> Local Variables local-struct typedef struct { Token name; int depth; //> Closures is-captured-field bool isCaptured; //< Closures is-captured-field } Local; //< Local Variables local-struct //> Closures upvalue-struct typedef struct { uint8_t index; bool isLocal; } Upvalue; //< Closures upvalue-struct //> Calls and Functions function-type-enum typedef enum { TYPE_FUNCTION, //> Methods and Initializers initializer-type-enum TYPE_INITIALIZER, //< Methods and Initializers initializer-type-enum //> Methods and Initializers method-type-enum TYPE_METHOD, //< Methods and Initializers method-type-enum TYPE_SCRIPT } FunctionType; //< Calls and Functions function-type-enum //> Local Variables compiler-struct /* Local Variables compiler-struct < Calls and Functions enclosing-field typedef struct { */ //> Calls and Functions enclosing-field typedef struct Compiler { struct Compiler* enclosing; //< Calls and Functions enclosing-field //> Calls and Functions function-fields ObjFunction* function; FunctionType type; //< Calls and Functions function-fields Local locals[UINT8_COUNT]; int localCount; //> Closures upvalues-array Upvalue upvalues[UINT8_COUNT]; //< Closures upvalues-array int scopeDepth; } Compiler; //< Local Variables compiler-struct //> Methods and Initializers class-compiler-struct typedef struct ClassCompiler { struct ClassCompiler* enclosing; //> Superclasses has-superclass bool hasSuperclass; //< Superclasses has-superclass } ClassCompiler; //< Methods and Initializers class-compiler-struct Parser parser; //< Compiling Expressions parser //> Local Variables current-compiler Compiler* current = NULL; //< Local Variables current-compiler //> Methods and Initializers current-class ClassCompiler* currentClass = NULL; //< Methods and Initializers current-class //> Compiling Expressions compiling-chunk /* Compiling Expressions compiling-chunk < Calls and Functions current-chunk Chunk* compilingChunk; static Chunk* currentChunk() { return compilingChunk; } */ //> Calls and Functions current-chunk static Chunk* currentChunk() { return &current->function->chunk; } //< Calls and Functions current-chunk //< Compiling Expressions compiling-chunk //> Compiling Expressions error-at static void errorAt(Token* token, const char* message) { //> check-panic-mode if (parser.panicMode) return; //< check-panic-mode //> set-panic-mode parser.panicMode = true; //< set-panic-mode fprintf(stderr, "[line %d] Error", token->line); if (token->type == TOKEN_EOF) { fprintf(stderr, " at end"); } else if (token->type == TOKEN_ERROR) { // Nothing. } else { fprintf(stderr, " at '%.*s'", token->length, token->start); } fprintf(stderr, ": %s\n", message); parser.hadError = true; } //< Compiling Expressions error-at //> Compiling Expressions error static void error(const char* message) { errorAt(&parser.previous, message); } //< Compiling Expressions error //> Compiling Expressions error-at-current static void errorAtCurrent(const char* message) { errorAt(&parser.current, message); } //< Compiling Expressions error-at-current //> Compiling Expressions advance static void advance() { parser.previous = parser.current; for (;;) { parser.current = scanToken(); if (parser.current.type != TOKEN_ERROR) break; errorAtCurrent(parser.current.start); } } //< Compiling Expressions advance //> Compiling Expressions consume static void consume(TokenType type, const char* message) { if (parser.current.type == type) { advance(); return; } errorAtCurrent(message); } //< Compiling Expressions consume //> Global Variables check static bool check(TokenType type) { return parser.current.type == type; } //< Global Variables check //> Global Variables match static bool match(TokenType type) { if (!check(type)) return false; advance(); return true; } //< Global Variables match //> Compiling Expressions emit-byte static void emitByte(uint8_t byte) { writeChunk(currentChunk(), byte, parser.previous.line); } //< Compiling Expressions emit-byte //> Compiling Expressions emit-bytes static void emitBytes(uint8_t byte1, uint8_t byte2) { emitByte(byte1); emitByte(byte2); } //< Compiling Expressions emit-bytes //> Jumping Back and Forth emit-loop static void emitLoop(int loopStart) { emitByte(OP_LOOP); int offset = currentChunk()->count - loopStart + 2; if (offset > UINT16_MAX) error("Loop body too large."); emitByte((offset >> 8) & 0xff); emitByte(offset & 0xff); } //< Jumping Back and Forth emit-loop //> Jumping Back and Forth emit-jump static int emitJump(uint8_t instruction) { emitByte(instruction); emitByte(0xff); emitByte(0xff); return currentChunk()->count - 2; } //< Jumping Back and Forth emit-jump //> Compiling Expressions emit-return static void emitReturn() { /* Calls and Functions return-nil < Methods and Initializers return-this emitByte(OP_NIL); */ //> Methods and Initializers return-this if (current->type == TYPE_INITIALIZER) { emitBytes(OP_GET_LOCAL, 0); } else { emitByte(OP_NIL); } //< Methods and Initializers return-this emitByte(OP_RETURN); } //< Compiling Expressions emit-return //> Compiling Expressions make-constant static uint8_t makeConstant(Value value) { int constant = addConstant(currentChunk(), value); if (constant > UINT8_MAX) { error("Too many constants in one chunk."); return 0; } return (uint8_t)constant; } //< Compiling Expressions make-constant //> Compiling Expressions emit-constant static void emitConstant(Value value) { emitBytes(OP_CONSTANT, makeConstant(value)); } //< Compiling Expressions emit-constant //> Jumping Back and Forth patch-jump static void patchJump(int offset) { // -2 to adjust for the bytecode for the jump offset itself. int jump = currentChunk()->count - offset - 2; if (jump > UINT16_MAX) { error("Too much code to jump over."); } currentChunk()->code[offset] = (jump >> 8) & 0xff; currentChunk()->code[offset + 1] = jump & 0xff; } //< Jumping Back and Forth patch-jump //> Local Variables init-compiler /* Local Variables init-compiler < Calls and Functions init-compiler static void initCompiler(Compiler* compiler) { */ //> Calls and Functions init-compiler static void initCompiler(Compiler* compiler, FunctionType type) { //> store-enclosing compiler->enclosing = current; //< store-enclosing compiler->function = NULL; compiler->type = type; //< Calls and Functions init-compiler compiler->localCount = 0; compiler->scopeDepth = 0; //> Calls and Functions init-function compiler->function = newFunction(); //< Calls and Functions init-function current = compiler; //> Calls and Functions init-function-name if (type != TYPE_SCRIPT) { current->function->name = copyString(parser.previous.start, parser.previous.length); } //< Calls and Functions init-function-name //> Calls and Functions init-function-slot Local* local = &current->locals[current->localCount++]; local->depth = 0; //> Closures init-zero-local-is-captured local->isCaptured = false; //< Closures init-zero-local-is-captured /* Calls and Functions init-function-slot < Methods and Initializers slot-zero local->name.start = ""; local->name.length = 0; */ //> Methods and Initializers slot-zero if (type != TYPE_FUNCTION) { local->name.start = "this"; local->name.length = 4; } else { local->name.start = ""; local->name.length = 0; } //< Methods and Initializers slot-zero //< Calls and Functions init-function-slot } //< Local Variables init-compiler //> Compiling Expressions end-compiler /* Compiling Expressions end-compiler < Calls and Functions end-compiler static void endCompiler() { */ //> Calls and Functions end-compiler static ObjFunction* endCompiler() { //< Calls and Functions end-compiler emitReturn(); //> Calls and Functions end-function ObjFunction* function = current->function; //< Calls and Functions end-function //> dump-chunk #ifdef DEBUG_PRINT_CODE if (!parser.hadError) { /* Compiling Expressions dump-chunk < Calls and Functions disassemble-end disassembleChunk(currentChunk(), "code"); */ //> Calls and Functions disassemble-end disassembleChunk(currentChunk(), function->name != NULL ? function->name->chars : "<script>"); //< Calls and Functions disassemble-end } #endif //< dump-chunk //> Calls and Functions return-function //> restore-enclosing current = current->enclosing; //< restore-enclosing return function; //< Calls and Functions return-function } //< Compiling Expressions end-compiler //> Local Variables begin-scope static void beginScope() { current->scopeDepth++; } //< Local Variables begin-scope //> Local Variables end-scope static void endScope() { current->scopeDepth--; //> pop-locals while (current->localCount > 0 && current->locals[current->localCount - 1].depth > current->scopeDepth) { /* Local Variables pop-locals < Closures end-scope emitByte(OP_POP); */ //> Closures end-scope if (current->locals[current->localCount - 1].isCaptured) { emitByte(OP_CLOSE_UPVALUE); } else { emitByte(OP_POP); } //< Closures end-scope current->localCount--; } //< pop-locals } //< Local Variables end-scope //> Compiling Expressions forward-declarations static void expression(); //> Global Variables forward-declarations static void statement(); static void declaration(); //< Global Variables forward-declarations static ParseRule* getRule(TokenType type); static void parsePrecedence(Precedence precedence); //< Compiling Expressions forward-declarations //> Global Variables identifier-constant static uint8_t identifierConstant(Token* name) { return makeConstant(OBJ_VAL(copyString(name->start, name->length))); } //< Global Variables identifier-constant //> Local Variables identifiers-equal static bool identifiersEqual(Token* a, Token* b) { if (a->length != b->length) return false; return memcmp(a->start, b->start, a->length) == 0; } //< Local Variables identifiers-equal //> Local Variables resolve-local static int resolveLocal(Compiler* compiler, Token* name) { for (int i = compiler->localCount - 1; i >= 0; i--) { Local* local = &compiler->locals[i]; if (identifiersEqual(name, &local->name)) { //> own-initializer-error if (local->depth == -1) { error("Can't read local variable in its own initializer."); } //< own-initializer-error return i; } } return -1; } //< Local Variables resolve-local //> Closures add-upvalue static int addUpvalue(Compiler* compiler, uint8_t index, bool isLocal) { int upvalueCount = compiler->function->upvalueCount; //> existing-upvalue for (int i = 0; i < upvalueCount; i++) { Upvalue* upvalue = &compiler->upvalues[i]; if (upvalue->index == index && upvalue->isLocal == isLocal) { return i; } } //< existing-upvalue //> too-many-upvalues if (upvalueCount == UINT8_COUNT) { error("Too many closure variables in function."); return 0; } //< too-many-upvalues compiler->upvalues[upvalueCount].isLocal = isLocal; compiler->upvalues[upvalueCount].index = index; return compiler->function->upvalueCount++; } //< Closures add-upvalue //> Closures resolve-upvalue static int resolveUpvalue(Compiler* compiler, Token* name) { if (compiler->enclosing == NULL) return -1; int local = resolveLocal(compiler->enclosing, name); if (local != -1) { //> mark-local-captured compiler->enclosing->locals[local].isCaptured = true; //< mark-local-captured return addUpvalue(compiler, (uint8_t)local, true); } //> resolve-upvalue-recurse int upvalue = resolveUpvalue(compiler->enclosing, name); if (upvalue != -1) { return addUpvalue(compiler, (uint8_t)upvalue, false); } //< resolve-upvalue-recurse return -1; } //< Closures resolve-upvalue //> Local Variables add-local static void addLocal(Token name) { //> too-many-locals if (current->localCount == UINT8_COUNT) { error("Too many local variables in function."); return; } //< too-many-locals Local* local = &current->locals[current->localCount++]; local->name = name; /* Local Variables add-local < Local Variables declare-undefined local->depth = current->scopeDepth; */ //> declare-undefined local->depth = -1; //< declare-undefined //> Closures init-is-captured local->isCaptured = false; //< Closures init-is-captured } //< Local Variables add-local //> Local Variables declare-variable static void declareVariable() { if (current->scopeDepth == 0) return; Token* name = &parser.previous; //> existing-in-scope for (int i = current->localCount - 1; i >= 0; i--) { Local* local = &current->locals[i]; if (local->depth != -1 && local->depth < current->scopeDepth) { break; // [negative] } if (identifiersEqual(name, &local->name)) { error("Already a variable with this name in this scope."); } } //< existing-in-scope addLocal(*name); } //< Local Variables declare-variable //> Global Variables parse-variable static uint8_t parseVariable(const char* errorMessage) { consume(TOKEN_IDENTIFIER, errorMessage); //> Local Variables parse-local declareVariable(); if (current->scopeDepth > 0) return 0; //< Local Variables parse-local return identifierConstant(&parser.previous); } //< Global Variables parse-variable //> Local Variables mark-initialized static void markInitialized() { //> Calls and Functions check-depth if (current->scopeDepth == 0) return; //< Calls and Functions check-depth current->locals[current->localCount - 1].depth = current->scopeDepth; } //< Local Variables mark-initialized //> Global Variables define-variable static void defineVariable(uint8_t global) { //> Local Variables define-variable if (current->scopeDepth > 0) { //> define-local markInitialized(); //< define-local return; } //< Local Variables define-variable emitBytes(OP_DEFINE_GLOBAL, global); } //< Global Variables define-variable //> Calls and Functions argument-list static uint8_t argumentList() { uint8_t argCount = 0; if (!check(TOKEN_RIGHT_PAREN)) { do { expression(); //> arg-limit if (argCount == 255) { error("Can't have more than 255 arguments."); } //< arg-limit argCount++; } while (match(TOKEN_COMMA)); } consume(TOKEN_RIGHT_PAREN, "Expect ')' after arguments."); return argCount; } //< Calls and Functions argument-list //> Jumping Back and Forth and static void and_(bool canAssign) { int endJump = emitJump(OP_JUMP_IF_FALSE); emitByte(OP_POP); parsePrecedence(PREC_AND); patchJump(endJump); } //< Jumping Back and Forth and //> Compiling Expressions binary /* Compiling Expressions binary < Global Variables binary static void binary() { */ //> Global Variables binary static void binary(bool canAssign) { //< Global Variables binary TokenType operatorType = parser.previous.type; ParseRule* rule = getRule(operatorType); parsePrecedence((Precedence)(rule->precedence + 1)); switch (operatorType) { //> Types of Values comparison-operators case TOKEN_BANG_EQUAL: emitBytes(OP_EQUAL, OP_NOT); break; case TOKEN_EQUAL_EQUAL: emitByte(OP_EQUAL); break; case TOKEN_GREATER: emitByte(OP_GREATER); break; case TOKEN_GREATER_EQUAL: emitBytes(OP_LESS, OP_NOT); break; case TOKEN_LESS: emitByte(OP_LESS); break; case TOKEN_LESS_EQUAL: emitBytes(OP_GREATER, OP_NOT); break; //< Types of Values comparison-operators case TOKEN_PLUS: emitByte(OP_ADD); break; case TOKEN_MINUS: emitByte(OP_SUBTRACT); break; case TOKEN_STAR: emitByte(OP_MULTIPLY); break; case TOKEN_SLASH: emitByte(OP_DIVIDE); break; default: return; // Unreachable. } } //< Compiling Expressions binary //> Calls and Functions compile-call static void call(bool canAssign) { uint8_t argCount = argumentList(); emitBytes(OP_CALL, argCount); } //< Calls and Functions compile-call //> Classes and Instances compile-dot static void dot(bool canAssign) { consume(TOKEN_IDENTIFIER, "Expect property name after '.'."); uint8_t name = identifierConstant(&parser.previous); if (canAssign && match(TOKEN_EQUAL)) { expression(); emitBytes(OP_SET_PROPERTY, name); //> Methods and Initializers parse-call } else if (match(TOKEN_LEFT_PAREN)) { uint8_t argCount = argumentList(); emitBytes(OP_INVOKE, name); emitByte(argCount); //< Methods and Initializers parse-call } else { emitBytes(OP_GET_PROPERTY, name); } } //< Classes and Instances compile-dot //> Types of Values parse-literal /* Types of Values parse-literal < Global Variables parse-literal static void literal() { */ //> Global Variables parse-literal static void literal(bool canAssign) { //< Global Variables parse-literal switch (parser.previous.type) { case TOKEN_FALSE: emitByte(OP_FALSE); break; case TOKEN_NIL: emitByte(OP_NIL); break; case TOKEN_TRUE: emitByte(OP_TRUE); break; default: return; // Unreachable. } } //< Types of Values parse-literal //> Compiling Expressions grouping /* Compiling Expressions grouping < Global Variables grouping static void grouping() { */ //> Global Variables grouping static void grouping(bool canAssign) { //< Global Variables grouping expression(); consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression."); } //< Compiling Expressions grouping /* Compiling Expressions number < Global Variables number static void number() { */ //> Compiling Expressions number //> Global Variables number static void number(bool canAssign) { //< Global Variables number double value = strtod(parser.previous.start, NULL); /* Compiling Expressions number < Types of Values const-number-val emitConstant(value); */ //> Types of Values const-number-val emitConstant(NUMBER_VAL(value)); //< Types of Values const-number-val } //< Compiling Expressions number //> Jumping Back and Forth or static void or_(bool canAssign) { int elseJump = emitJump(OP_JUMP_IF_FALSE); int endJump = emitJump(OP_JUMP); patchJump(elseJump); emitByte(OP_POP); parsePrecedence(PREC_OR); patchJump(endJump); } //< Jumping Back and Forth or /* Strings parse-string < Global Variables string static void string() { */ //> Strings parse-string //> Global Variables string static void string(bool canAssign) { //< Global Variables string emitConstant(OBJ_VAL(copyString(parser.previous.start + 1, parser.previous.length - 2))); } //< Strings parse-string /* Global Variables read-named-variable < Global Variables named-variable-signature static void namedVariable(Token name) { */ //> Global Variables named-variable-signature static void namedVariable(Token name, bool canAssign) { //< Global Variables named-variable-signature /* Global Variables read-named-variable < Local Variables named-local uint8_t arg = identifierConstant(&name); */ //> Global Variables read-named-variable //> Local Variables named-local uint8_t getOp, setOp; int arg = resolveLocal(current, &name); if (arg != -1) { getOp = OP_GET_LOCAL; setOp = OP_SET_LOCAL; //> Closures named-variable-upvalue } else if ((arg = resolveUpvalue(current, &name)) != -1) { getOp = OP_GET_UPVALUE; setOp = OP_SET_UPVALUE; //< Closures named-variable-upvalue } else { arg = identifierConstant(&name); getOp = OP_GET_GLOBAL; setOp = OP_SET_GLOBAL; } //< Local Variables named-local /* Global Variables read-named-variable < Global Variables named-variable emitBytes(OP_GET_GLOBAL, arg); */ //> named-variable /* Global Variables named-variable < Global Variables named-variable-can-assign if (match(TOKEN_EQUAL)) { */ //> named-variable-can-assign if (canAssign && match(TOKEN_EQUAL)) { //< named-variable-can-assign expression(); /* Global Variables named-variable < Local Variables emit-set emitBytes(OP_SET_GLOBAL, arg); */ //> Local Variables emit-set emitBytes(setOp, (uint8_t)arg); //< Local Variables emit-set } else { /* Global Variables named-variable < Local Variables emit-get emitBytes(OP_GET_GLOBAL, arg); */ //> Local Variables emit-get emitBytes(getOp, (uint8_t)arg); //< Local Variables emit-get } //< named-variable } //< Global Variables read-named-variable /* Global Variables variable-without-assign < Global Variables variable static void variable() { namedVariable(parser.previous); } */ //> Global Variables variable static void variable(bool canAssign) { namedVariable(parser.previous, canAssign); } //< Global Variables variable //> Superclasses synthetic-token static Token syntheticToken(const char* text) { Token token; token.start = text; token.length = (int)strlen(text); return token; } //< Superclasses synthetic-token //> Superclasses super static void super_(bool canAssign) { //> super-errors if (currentClass == NULL) { error("Can't use 'super' outside of a class."); } else if (!currentClass->hasSuperclass) { error("Can't use 'super' in a class with no superclass."); } //< super-errors consume(TOKEN_DOT, "Expect '.' after 'super'."); consume(TOKEN_IDENTIFIER, "Expect superclass method name."); uint8_t name = identifierConstant(&parser.previous); //> super-get namedVariable(syntheticToken("this"), false); /* Superclasses super-get < Superclasses super-invoke namedVariable(syntheticToken("super"), false); emitBytes(OP_GET_SUPER, name); */ //< super-get //> super-invoke if (match(TOKEN_LEFT_PAREN)) { uint8_t argCount = argumentList(); namedVariable(syntheticToken("super"), false); emitBytes(OP_SUPER_INVOKE, name); emitByte(argCount); } else { namedVariable(syntheticToken("super"), false); emitBytes(OP_GET_SUPER, name); } //< super-invoke } //< Superclasses super //> Methods and Initializers this static void this_(bool canAssign) { //> this-outside-class if (currentClass == NULL) { error("Can't use 'this' outside of a class."); return; } //< this-outside-class variable(false); } // [this] //< Methods and Initializers this //> Compiling Expressions unary /* Compiling Expressions unary < Global Variables unary static void unary() { */ //> Global Variables unary static void unary(bool canAssign) { //< Global Variables unary TokenType operatorType = parser.previous.type; // Compile the operand. /* Compiling Expressions unary < Compiling Expressions unary-operand expression(); */ //> unary-operand parsePrecedence(PREC_UNARY); //< unary-operand // Emit the operator instruction. switch (operatorType) { //> Types of Values compile-not case TOKEN_BANG: emitByte(OP_NOT); break; //< Types of Values compile-not case TOKEN_MINUS: emitByte(OP_NEGATE); break; default: return; // Unreachable. } } //< Compiling Expressions unary //> Compiling Expressions rules ParseRule rules[] = { /* Compiling Expressions rules < Calls and Functions infix-left-paren [TOKEN_LEFT_PAREN] = {grouping, NULL, PREC_NONE}, */ //> Calls and Functions infix-left-paren [TOKEN_LEFT_PAREN] = {grouping, call, PREC_CALL}, //< Calls and Functions infix-left-paren [TOKEN_RIGHT_PAREN] = {NULL, NULL, PREC_NONE}, [TOKEN_LEFT_BRACE] = {NULL, NULL, PREC_NONE}, // [big] [TOKEN_RIGHT_BRACE] = {NULL, NULL, PREC_NONE}, [TOKEN_COMMA] = {NULL, NULL, PREC_NONE}, /* Compiling Expressions rules < Classes and Instances table-dot [TOKEN_DOT] = {NULL, NULL, PREC_NONE}, */ //> Classes and Instances table-dot [TOKEN_DOT] = {NULL, dot, PREC_CALL}, //< Classes and Instances table-dot [TOKEN_MINUS] = {unary, binary, PREC_TERM}, [TOKEN_PLUS] = {NULL, binary, PREC_TERM}, [TOKEN_SEMICOLON] = {NULL, NULL, PREC_NONE}, [TOKEN_SLASH] = {NULL, binary, PREC_FACTOR}, [TOKEN_STAR] = {NULL, binary, PREC_FACTOR}, /* Compiling Expressions rules < Types of Values table-not [TOKEN_BANG] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-not [TOKEN_BANG] = {unary, NULL, PREC_NONE}, //< Types of Values table-not /* Compiling Expressions rules < Types of Values table-equal [TOKEN_BANG_EQUAL] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-equal [TOKEN_BANG_EQUAL] = {NULL, binary, PREC_EQUALITY}, //< Types of Values table-equal [TOKEN_EQUAL] = {NULL, NULL, PREC_NONE}, /* Compiling Expressions rules < Types of Values table-comparisons [TOKEN_EQUAL_EQUAL] = {NULL, NULL, PREC_NONE}, [TOKEN_GREATER] = {NULL, NULL, PREC_NONE}, [TOKEN_GREATER_EQUAL] = {NULL, NULL, PREC_NONE}, [TOKEN_LESS] = {NULL, NULL, PREC_NONE}, [TOKEN_LESS_EQUAL] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-comparisons [TOKEN_EQUAL_EQUAL] = {NULL, binary, PREC_EQUALITY}, [TOKEN_GREATER] = {NULL, binary, PREC_COMPARISON}, [TOKEN_GREATER_EQUAL] = {NULL, binary, PREC_COMPARISON}, [TOKEN_LESS] = {NULL, binary, PREC_COMPARISON}, [TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON}, //< Types of Values table-comparisons /* Compiling Expressions rules < Global Variables table-identifier [TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE}, */ //> Global Variables table-identifier [TOKEN_IDENTIFIER] = {variable, NULL, PREC_NONE}, //< Global Variables table-identifier /* Compiling Expressions rules < Strings table-string [TOKEN_STRING] = {NULL, NULL, PREC_NONE}, */ //> Strings table-string [TOKEN_STRING] = {string, NULL, PREC_NONE}, //< Strings table-string [TOKEN_NUMBER] = {number, NULL, PREC_NONE}, /* Compiling Expressions rules < Jumping Back and Forth table-and [TOKEN_AND] = {NULL, NULL, PREC_NONE}, */ //> Jumping Back and Forth table-and [TOKEN_AND] = {NULL, and_, PREC_AND}, //< Jumping Back and Forth table-and [TOKEN_CLASS] = {NULL, NULL, PREC_NONE}, [TOKEN_ELSE] = {NULL, NULL, PREC_NONE}, /* Compiling Expressions rules < Types of Values table-false [TOKEN_FALSE] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-false [TOKEN_FALSE] = {literal, NULL, PREC_NONE}, //< Types of Values table-false [TOKEN_FOR] = {NULL, NULL, PREC_NONE}, [TOKEN_FUN] = {NULL, NULL, PREC_NONE}, [TOKEN_IF] = {NULL, NULL, PREC_NONE}, /* Compiling Expressions rules < Types of Values table-nil [TOKEN_NIL] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-nil [TOKEN_NIL] = {literal, NULL, PREC_NONE}, //< Types of Values table-nil /* Compiling Expressions rules < Jumping Back and Forth table-or [TOKEN_OR] = {NULL, NULL, PREC_NONE}, */ //> Jumping Back and Forth table-or [TOKEN_OR] = {NULL, or_, PREC_OR}, //< Jumping Back and Forth table-or [TOKEN_PRINT] = {NULL, NULL, PREC_NONE}, [TOKEN_RETURN] = {NULL, NULL, PREC_NONE}, /* Compiling Expressions rules < Superclasses table-super [TOKEN_SUPER] = {NULL, NULL, PREC_NONE}, */ //> Superclasses table-super [TOKEN_SUPER] = {super_, NULL, PREC_NONE}, //< Superclasses table-super /* Compiling Expressions rules < Methods and Initializers table-this [TOKEN_THIS] = {NULL, NULL, PREC_NONE}, */ //> Methods and Initializers table-this [TOKEN_THIS] = {this_, NULL, PREC_NONE}, //< Methods and Initializers table-this /* Compiling Expressions rules < Types of Values table-true [TOKEN_TRUE] = {NULL, NULL, PREC_NONE}, */ //> Types of Values table-true [TOKEN_TRUE] = {literal, NULL, PREC_NONE}, //< Types of Values table-true [TOKEN_VAR] = {NULL, NULL, PREC_NONE}, [TOKEN_WHILE] = {NULL, NULL, PREC_NONE}, [TOKEN_ERROR] = {NULL, NULL, PREC_NONE}, [TOKEN_EOF] = {NULL, NULL, PREC_NONE}, }; //< Compiling Expressions rules //> Compiling Expressions parse-precedence static void parsePrecedence(Precedence precedence) { /* Compiling Expressions parse-precedence < Compiling Expressions precedence-body // What goes here? */ //> precedence-body advance(); ParseFn prefixRule = getRule(parser.previous.type)->prefix; if (prefixRule == NULL) { error("Expect expression."); return; } /* Compiling Expressions precedence-body < Global Variables prefix-rule prefixRule(); */ //> Global Variables prefix-rule bool canAssign = precedence <= PREC_ASSIGNMENT; prefixRule(canAssign); //< Global Variables prefix-rule //> infix while (precedence <= getRule(parser.current.type)->precedence) { advance(); ParseFn infixRule = getRule(parser.previous.type)->infix; /* Compiling Expressions infix < Global Variables infix-rule infixRule(); */ //> Global Variables infix-rule infixRule(canAssign); //< Global Variables infix-rule } //> Global Variables invalid-assign if (canAssign && match(TOKEN_EQUAL)) { error("Invalid assignment target."); } //< Global Variables invalid-assign //< infix //< precedence-body } //< Compiling Expressions parse-precedence //> Compiling Expressions get-rule static ParseRule* getRule(TokenType type) { return &rules[type]; } //< Compiling Expressions get-rule //> Compiling Expressions expression static void expression() { /* Compiling Expressions expression < Compiling Expressions expression-body // What goes here? */ //> expression-body parsePrecedence(PREC_ASSIGNMENT); //< expression-body } //< Compiling Expressions expression //> Local Variables block static void block() { while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) { declaration(); } consume(TOKEN_RIGHT_BRACE, "Expect '}' after block."); } //< Local Variables block //> Calls and Functions compile-function static void function(FunctionType type) { Compiler compiler; initCompiler(&compiler, type); beginScope(); // [no-end-scope] consume(TOKEN_LEFT_PAREN, "Expect '(' after function name."); //> parameters if (!check(TOKEN_RIGHT_PAREN)) { do { current->function->arity++; if (current->function->arity > 255) { errorAtCurrent("Can't have more than 255 parameters."); } uint8_t constant = parseVariable("Expect parameter name."); defineVariable(constant); } while (match(TOKEN_COMMA)); } //< parameters consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters."); consume(TOKEN_LEFT_BRACE, "Expect '{' before function body."); block(); ObjFunction* function = endCompiler(); /* Calls and Functions compile-function < Closures emit-closure emitBytes(OP_CONSTANT, makeConstant(OBJ_VAL(function))); */ //> Closures emit-closure emitBytes(OP_CLOSURE, makeConstant(OBJ_VAL(function))); //< Closures emit-closure //> Closures capture-upvalues for (int i = 0; i < function->upvalueCount; i++) { emitByte(compiler.upvalues[i].isLocal ? 1 : 0); emitByte(compiler.upvalues[i].index); } //< Closures capture-upvalues } //< Calls and Functions compile-function //> Methods and Initializers method static void method() { consume(TOKEN_IDENTIFIER, "Expect method name."); uint8_t constant = identifierConstant(&parser.previous); //> method-body //< method-body /* Methods and Initializers method-body < Methods and Initializers method-type FunctionType type = TYPE_FUNCTION; */ //> method-type FunctionType type = TYPE_METHOD; //< method-type //> initializer-name if (parser.previous.length == 4 && memcmp(parser.previous.start, "init", 4) == 0) { type = TYPE_INITIALIZER; } //< initializer-name //> method-body function(type); //< method-body emitBytes(OP_METHOD, constant); } //< Methods and Initializers method //> Classes and Instances class-declaration static void classDeclaration() { consume(TOKEN_IDENTIFIER, "Expect class name."); //> Methods and Initializers class-name Token className = parser.previous; //< Methods and Initializers class-name uint8_t nameConstant = identifierConstant(&parser.previous); declareVariable(); emitBytes(OP_CLASS, nameConstant); defineVariable(nameConstant); //> Methods and Initializers create-class-compiler ClassCompiler classCompiler; //> Superclasses init-has-superclass classCompiler.hasSuperclass = false; //< Superclasses init-has-superclass classCompiler.enclosing = currentClass; currentClass = &classCompiler; //< Methods and Initializers create-class-compiler //> Superclasses compile-superclass if (match(TOKEN_LESS)) { consume(TOKEN_IDENTIFIER, "Expect superclass name."); variable(false); //> inherit-self if (identifiersEqual(&className, &parser.previous)) { error("A class can't inherit from itself."); } //< inherit-self //> superclass-variable beginScope(); addLocal(syntheticToken("super")); defineVariable(0); //< superclass-variable namedVariable(className, false); emitByte(OP_INHERIT); //> set-has-superclass classCompiler.hasSuperclass = true; //< set-has-superclass } //< Superclasses compile-superclass //> Methods and Initializers load-class namedVariable(className, false); //< Methods and Initializers load-class consume(TOKEN_LEFT_BRACE, "Expect '{' before class body."); //> Methods and Initializers class-body while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) { method(); } //< Methods and Initializers class-body consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body."); //> Methods and Initializers pop-class emitByte(OP_POP); //< Methods and Initializers pop-class //> Superclasses end-superclass-scope if (classCompiler.hasSuperclass) { endScope(); } //< Superclasses end-superclass-scope //> Methods and Initializers pop-enclosing currentClass = currentClass->enclosing; //< Methods and Initializers pop-enclosing } //< Classes and Instances class-declaration //> Calls and Functions fun-declaration static void funDeclaration() { uint8_t global = parseVariable("Expect function name."); markInitialized(); function(TYPE_FUNCTION); defineVariable(global); } //< Calls and Functions fun-declaration //> Global Variables var-declaration static void varDeclaration() { uint8_t global = parseVariable("Expect variable name."); if (match(TOKEN_EQUAL)) { expression(); } else { emitByte(OP_NIL); } consume(TOKEN_SEMICOLON, "Expect ';' after variable declaration."); defineVariable(global); } //< Global Variables var-declaration //> Global Variables expression-statement static void expressionStatement() { expression(); consume(TOKEN_SEMICOLON, "Expect ';' after expression."); emitByte(OP_POP); } //< Global Variables expression-statement //> Jumping Back and Forth for-statement static void forStatement() { //> for-begin-scope beginScope(); //< for-begin-scope consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'."); /* Jumping Back and Forth for-statement < Jumping Back and Forth for-initializer consume(TOKEN_SEMICOLON, "Expect ';'."); */ //> for-initializer if (match(TOKEN_SEMICOLON)) { // No initializer. } else if (match(TOKEN_VAR)) { varDeclaration(); } else { expressionStatement(); } //< for-initializer int loopStart = currentChunk()->count; /* Jumping Back and Forth for-statement < Jumping Back and Forth for-exit consume(TOKEN_SEMICOLON, "Expect ';'."); */ //> for-exit int exitJump = -1; if (!match(TOKEN_SEMICOLON)) { expression(); consume(TOKEN_SEMICOLON, "Expect ';' after loop condition."); // Jump out of the loop if the condition is false. exitJump = emitJump(OP_JUMP_IF_FALSE); emitByte(OP_POP); // Condition. } //< for-exit /* Jumping Back and Forth for-statement < Jumping Back and Forth for-increment consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses."); */ //> for-increment if (!match(TOKEN_RIGHT_PAREN)) { int bodyJump = emitJump(OP_JUMP); int incrementStart = currentChunk()->count; expression(); emitByte(OP_POP); consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses."); emitLoop(loopStart); loopStart = incrementStart; patchJump(bodyJump); } //< for-increment statement(); emitLoop(loopStart); //> exit-jump if (exitJump != -1) { patchJump(exitJump); emitByte(OP_POP); // Condition. } //< exit-jump //> for-end-scope endScope(); //< for-end-scope } //< Jumping Back and Forth for-statement //> Jumping Back and Forth if-statement static void ifStatement() { consume(TOKEN_LEFT_PAREN, "Expect '(' after 'if'."); expression(); consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition."); // [paren] int thenJump = emitJump(OP_JUMP_IF_FALSE); //> pop-then emitByte(OP_POP); //< pop-then statement(); //> jump-over-else int elseJump = emitJump(OP_JUMP); //< jump-over-else patchJump(thenJump); //> pop-end emitByte(OP_POP); //< pop-end //> compile-else if (match(TOKEN_ELSE)) statement(); //< compile-else //> patch-else patchJump(elseJump); //< patch-else } //< Jumping Back and Forth if-statement //> Global Variables print-statement static void printStatement() { expression(); consume(TOKEN_SEMICOLON, "Expect ';' after value."); emitByte(OP_PRINT); } //< Global Variables print-statement //> Calls and Functions return-statement static void returnStatement() { //> return-from-script if (current->type == TYPE_SCRIPT) { error("Can't return from top-level code."); } //< return-from-script if (match(TOKEN_SEMICOLON)) { emitReturn(); } else { //> Methods and Initializers return-from-init if (current->type == TYPE_INITIALIZER) { error("Can't return a value from an initializer."); } //< Methods and Initializers return-from-init expression(); consume(TOKEN_SEMICOLON, "Expect ';' after return value."); emitByte(OP_RETURN); } } //< Calls and Functions return-statement //> Jumping Back and Forth while-statement static void whileStatement() { //> loop-start int loopStart = currentChunk()->count; //< loop-start consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'."); expression(); consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition."); int exitJump = emitJump(OP_JUMP_IF_FALSE); emitByte(OP_POP); statement(); //> loop emitLoop(loopStart); //< loop patchJump(exitJump); emitByte(OP_POP); } //< Jumping Back and Forth while-statement //> Global Variables synchronize static void synchronize() { parser.panicMode = false; while (parser.current.type != TOKEN_EOF) { if (parser.previous.type == TOKEN_SEMICOLON) return; switch (parser.current.type) { case TOKEN_CLASS: case TOKEN_FUN: case TOKEN_VAR: case TOKEN_FOR: case TOKEN_IF: case TOKEN_WHILE: case TOKEN_PRINT: case TOKEN_RETURN: return; default: ; // Do nothing. } advance(); } } //< Global Variables synchronize //> Global Variables declaration static void declaration() { //> Classes and Instances match-class if (match(TOKEN_CLASS)) { classDeclaration(); /* Calls and Functions match-fun < Classes and Instances match-class if (match(TOKEN_FUN)) { */ } else if (match(TOKEN_FUN)) { //< Classes and Instances match-class //> Calls and Functions match-fun funDeclaration(); /* Global Variables match-var < Calls and Functions match-fun if (match(TOKEN_VAR)) { */ } else if (match(TOKEN_VAR)) { //< Calls and Functions match-fun //> match-var varDeclaration(); } else { statement(); } //< match-var /* Global Variables declaration < Global Variables match-var statement(); */ //> call-synchronize if (parser.panicMode) synchronize(); //< call-synchronize } //< Global Variables declaration //> Global Variables statement static void statement() { if (match(TOKEN_PRINT)) { printStatement(); //> Jumping Back and Forth parse-for } else if (match(TOKEN_FOR)) { forStatement(); //< Jumping Back and Forth parse-for //> Jumping Back and Forth parse-if } else if (match(TOKEN_IF)) { ifStatement(); //< Jumping Back and Forth parse-if //> Calls and Functions match-return } else if (match(TOKEN_RETURN)) { returnStatement(); //< Calls and Functions match-return //> Jumping Back and Forth parse-while } else if (match(TOKEN_WHILE)) { whileStatement(); //< Jumping Back and Forth parse-while //> Local Variables parse-block } else if (match(TOKEN_LEFT_BRACE)) { beginScope(); block(); endScope(); //< Local Variables parse-block //> parse-expressions-statement } else { expressionStatement(); //< parse-expressions-statement } } //< Global Variables statement /* Scanning on Demand compiler-c < Compiling Expressions compile-signature void compile(const char* source) { */ /* Compiling Expressions compile-signature < Calls and Functions compile-signature bool compile(const char* source, Chunk* chunk) { */ //> Calls and Functions compile-signature ObjFunction* compile(const char* source) { //< Calls and Functions compile-signature initScanner(source); /* Scanning on Demand dump-tokens < Compiling Expressions compile-chunk int line = -1; for (;;) { Token token = scanToken(); if (token.line != line) { printf("%4d ", token.line); line = token.line; } else { printf(" | "); } printf("%2d '%.*s'\n", token.type, token.length, token.start); // [format] if (token.type == TOKEN_EOF) break; } */ //> Local Variables compiler Compiler compiler; //< Local Variables compiler /* Local Variables compiler < Calls and Functions call-init-compiler initCompiler(&compiler); */ //> Calls and Functions call-init-compiler initCompiler(&compiler, TYPE_SCRIPT); //< Calls and Functions call-init-compiler /* Compiling Expressions init-compile-chunk < Calls and Functions call-init-compiler compilingChunk = chunk; */ //> Compiling Expressions compile-chunk //> init-parser-error parser.hadError = false; parser.panicMode = false; //< init-parser-error advance(); //< Compiling Expressions compile-chunk /* Compiling Expressions compile-chunk < Global Variables compile expression(); consume(TOKEN_EOF, "Expect end of expression."); */ //> Global Variables compile while (!match(TOKEN_EOF)) { declaration(); } //< Global Variables compile /* Compiling Expressions finish-compile < Calls and Functions call-end-compiler endCompiler(); */ /* Compiling Expressions return-had-error < Calls and Functions call-end-compiler return !parser.hadError; */ //> Calls and Functions call-end-compiler ObjFunction* function = endCompiler(); return parser.hadError ? NULL : function; //< Calls and Functions call-end-compiler } //> Garbage Collection mark-compiler-roots void markCompilerRoots() { Compiler* compiler = current; while (compiler != NULL) { markObject((Obj*)compiler->function); compiler = compiler->enclosing; } } //< Garbage Collection mark-compiler-roots
201298.c
/* * This file is part of the OpenMV project. * Copyright (c) 2013/2014 Ibrahim Abdelkader <[email protected]> * This work is licensed under the MIT license, see the file LICENSE for details. * * Image library. * */ #include <stdlib.h> #include <mp.h> #include "font.h" #include "array.h" #include "vfs_wrapper.h" #include "imlib.h" #include "common.h" #include "omv_boardconfig.h" #include "sipeed_conv.h" #include "picojpeg_util.h" ///////////////// // Point Stuff // ///////////////// void point_init(point_t *ptr, int x, int y) { ptr->x = x; ptr->y = y; } void point_copy(point_t *dst, point_t *src) { memcpy(dst, src, sizeof(point_t)); } bool point_equal_fast(point_t *ptr0, point_t *ptr1) { return !memcmp(ptr0, ptr1, sizeof(point_t)); } int point_quadrance(point_t *ptr0, point_t *ptr1) { int delta_x = ptr0->x - ptr1->x; int delta_y = ptr0->y - ptr1->y; return (delta_x * delta_x) + (delta_y * delta_y); } //////////////// // Line Stuff // //////////////// // http://www.skytopia.com/project/articles/compsci/clipping.html bool lb_clip_line(line_t *l, int x, int y, int w, int h) // line is drawn if this returns true { int xdelta = l->x2 - l->x1, ydelta = l->y2 - l->y1, p[4], q[4]; float umin = 0, umax = 1; p[0] = -(xdelta); p[1] = +(xdelta); p[2] = -(ydelta); p[3] = +(ydelta); q[0] = l->x1 - (x); q[1] = (x + w - 1) - l->x1; q[2] = l->y1 - (y); q[3] = (y + h - 1) - l->y1; for (int i = 0; i < 4; i++) { if (p[i]) { float u = ((float) q[i]) / ((float) p[i]); if (p[i] < 0) { // outside to inside if (u > umax) return false; if (u > umin) umin = u; } if (p[i] > 0) { // inside to outside if (u < umin) return false; if (u < umax) umax = u; } } else if (q[i] < 0) { return false; } } if (umax < umin) return false; int x1_c = l->x1 + (xdelta * umin); int y1_c = l->y1 + (ydelta * umin); int x2_c = l->x1 + (xdelta * umax); int y2_c = l->y1 + (ydelta * umax); l->x1 = x1_c; l->y1 = y1_c; l->x2 = x2_c; l->y2 = y2_c; return true; } ///////////////////// // Rectangle Stuff // ///////////////////// void rectangle_init(rectangle_t *ptr, int x, int y, int w, int h) { ptr->x = x; ptr->y = y; ptr->w = w; ptr->h = h; } void rectangle_copy(rectangle_t *dst, rectangle_t *src) { memcpy(dst, src, sizeof(rectangle_t)); } bool rectangle_equal_fast(rectangle_t *ptr0, rectangle_t *ptr1) { return !memcmp(ptr0, ptr1, sizeof(rectangle_t)); } bool rectangle_overlap(rectangle_t *ptr0, rectangle_t *ptr1) { int x0 = ptr0->x; int y0 = ptr0->y; int w0 = ptr0->w; int h0 = ptr0->h; int x1 = ptr1->x; int y1 = ptr1->y; int w1 = ptr1->w; int h1 = ptr1->h; return (x0 < (x1 + w1)) && (y0 < (y1 + h1)) && (x1 < (x0 + w0)) && (y1 < (y0 + h0)); } void rectangle_intersected(rectangle_t *dst, rectangle_t *src) { int leftX = IM_MAX(dst->x, src->x); int topY = IM_MAX(dst->y, src->y); int rightX = IM_MIN(dst->x + dst->w, src->x + src->w); int bottomY = IM_MIN(dst->y + dst->h, src->y + src->h); dst->x = leftX; dst->y = topY; dst->w = rightX - leftX; dst->h = bottomY - topY; } void rectangle_united(rectangle_t *dst, rectangle_t *src) { int leftX = IM_MIN(dst->x, src->x); int topY = IM_MIN(dst->y, src->y); int rightX = IM_MAX(dst->x + dst->w, src->x + src->w); int bottomY = IM_MAX(dst->y + dst->h, src->y + src->h); dst->x = leftX; dst->y = topY; dst->w = rightX - leftX; dst->h = bottomY - topY; } ///////////////// // Image Stuff // ///////////////// void image_init(image_t *ptr, int w, int h, int bpp, void *data) { ptr->w = w; ptr->h = h; ptr->bpp = bpp; ptr->data = data; } void image_copy(image_t *dst, image_t *src) { memcpy(dst, src, sizeof(image_t)); } size_t image_size(image_t *ptr) { switch (ptr->bpp) { case IMAGE_BPP_BINARY: { return IMAGE_BINARY_LINE_LEN_BYTES(ptr) * ptr->h; } case IMAGE_BPP_GRAYSCALE: { return IMAGE_GRAYSCALE_LINE_LEN_BYTES(ptr) * ptr->h; } case IMAGE_BPP_RGB565: { return IMAGE_RGB565_LINE_LEN_BYTES(ptr) * ptr->h; } case IMAGE_BPP_BAYER: { return ptr->w * ptr->h; } default: { // JPEG return ptr->bpp; } } } bool image_get_mask_pixel(image_t *ptr, int x, int y) { if ((0 <= x) && (x < ptr->w) && (0 <= y) && (y < ptr->h)) { switch (ptr->bpp) { case IMAGE_BPP_BINARY: { return IMAGE_GET_BINARY_PIXEL(ptr, x, y); } case IMAGE_BPP_GRAYSCALE: { return COLOR_GRAYSCALE_TO_BINARY(IMAGE_GET_GRAYSCALE_PIXEL(ptr, x, y)); } case IMAGE_BPP_RGB565: { return COLOR_RGB565_TO_BINARY(IMAGE_GET_RGB565_PIXEL(ptr, x, y)); } default: { return false; } } } return false; } // Gamma uncompress extern const float xyz_table[256]; const int8_t kernel_gauss_3[3*3] = { 1, 2, 1, 2, 4, 2, 1, 2, 1, }; const int8_t kernel_gauss_5[5*5] = { 1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, 36, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1 }; const int kernel_laplacian_3[3*3] = { -1, -1, -1, -1, 8, -1, -1, -1, -1 }; const int kernel_high_pass_3[3*3] = { -1, -1, -1, -1, +8, -1, -1, -1, -1 }; // USE THE LUT FOR RGB->LAB CONVERSION - NOT THIS FUNCTION! void imlib_rgb_to_lab(simple_color_t *rgb, simple_color_t *lab) { // https://en.wikipedia.org/wiki/SRGB -> Specification of the transformation // https://en.wikipedia.org/wiki/Lab_color_space -> CIELAB-CIEXYZ conversions float r_lin = xyz_table[rgb->red]; float g_lin = xyz_table[rgb->green]; float b_lin = xyz_table[rgb->blue]; float x = ((r_lin * 0.4124f) + (g_lin * 0.3576f) + (b_lin * 0.1805f)) / 095.047f; float y = ((r_lin * 0.2126f) + (g_lin * 0.7152f) + (b_lin * 0.0722f)) / 100.000f; float z = ((r_lin * 0.0193f) + (g_lin * 0.1192f) + (b_lin * 0.9505f)) / 108.883f; x = (x>0.008856f) ? fast_cbrtf(x) : ((x * 7.787037f) + 0.137931f); y = (y>0.008856f) ? fast_cbrtf(y) : ((y * 7.787037f) + 0.137931f); z = (z>0.008856f) ? fast_cbrtf(z) : ((z * 7.787037f) + 0.137931f); lab->L = ((int8_t) fast_roundf(116 * y)) - 16; lab->A = ((int8_t) fast_roundf(500 * (x-y))); lab->B = ((int8_t) fast_roundf(200 * (y-z))); } void imlib_lab_to_rgb(simple_color_t *lab, simple_color_t *rgb) { // https://en.wikipedia.org/wiki/Lab_color_space -> CIELAB-CIEXYZ conversions // https://en.wikipedia.org/wiki/SRGB -> Specification of the transformation float x = ((lab->L + 16) * 0.008621f) + (lab->A * 0.002f); float y = ((lab->L + 16) * 0.008621f); float z = ((lab->L + 16) * 0.008621f) - (lab->B * 0.005f); x = ((x>0.206897f) ? (x*x*x) : ((0.128419f * x) - 0.017713f)) * 095.047f; y = ((y>0.206897f) ? (y*y*y) : ((0.128419f * y) - 0.017713f)) * 100.000f; z = ((z>0.206897f) ? (z*z*z) : ((0.128419f * z) - 0.017713f)) * 108.883f; float r_lin = ((x * +3.2406f) + (y * -1.5372f) + (z * -0.4986f)) / 100.0f; float g_lin = ((x * -0.9689f) + (y * +1.8758f) + (z * +0.0415f)) / 100.0f; float b_lin = ((x * +0.0557f) + (y * -0.2040f) + (z * +1.0570f)) / 100.0f; r_lin = (r_lin>0.0031308f) ? ((1.055f*powf(r_lin, 0.416666f))-0.055f) : (r_lin*12.92f); g_lin = (g_lin>0.0031308f) ? ((1.055f*powf(g_lin, 0.416666f))-0.055f) : (g_lin*12.92f); b_lin = (b_lin>0.0031308f) ? ((1.055f*powf(b_lin, 0.416666f))-0.055f) : (b_lin*12.92f); rgb->red = IM_MAX(IM_MIN(fast_roundf(r_lin * 255), 255), 0); rgb->green = IM_MAX(IM_MIN(fast_roundf(g_lin * 255), 255), 0); rgb->blue = IM_MAX(IM_MIN(fast_roundf(b_lin * 255), 255), 0); } void imlib_rgb_to_grayscale(simple_color_t *rgb, simple_color_t *grayscale) { float r_lin = xyz_table[rgb->red]; float g_lin = xyz_table[rgb->green]; float b_lin = xyz_table[rgb->blue]; float y = ((r_lin * 0.2126f) + (g_lin * 0.7152f) + (b_lin * 0.0722f)) / 100.0f; y = (y>0.0031308f) ? ((1.055f*powf(y, 0.416666f))-0.055f) : (y*12.92f); grayscale->G = IM_MAX(IM_MIN(fast_roundf(y * 255), 255), 0); } // Just copy settings back. void imlib_grayscale_to_rgb(simple_color_t *grayscale, simple_color_t *rgb) { rgb->red = grayscale->G; rgb->green = grayscale->G; rgb->blue = grayscale->G; } ALWAYS_INLINE uint16_t imlib_yuv_to_rgb(uint8_t y, int8_t u, int8_t v) { uint32_t r = IM_MAX(IM_MIN(y + ((91881*v)>>16), 255), 0); uint32_t g = IM_MAX(IM_MIN(y - (((22554*u)+(46802*v))>>16), 255), 0); uint32_t b = IM_MAX(IM_MIN(y + ((116130*u)>>16), 255), 0); return IM_RGB565(IM_R825(r), IM_G826(g), IM_B825(b)); } void imlib_bayer_to_rgb565(image_t *img, int w, int h, int xoffs, int yoffs, uint16_t *rgbbuf) { int r, g, b; for (int y=yoffs; y<yoffs+h; y++) { for (int x=xoffs; x<xoffs+w; x++) { if ((y % 2) == 0) { // Even row if ((x % 2) == 0) { // Even col r = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x-1, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x+1, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x-1, y+1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x+1, y+1)) >> 2; g = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y+1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x-1, y) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x+1, y)) >> 2; b = IM_GET_RAW_PIXEL(img, x, y); } else { // Odd col r = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y+1)) >> 1; b = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x-1, y) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x+1, y)) >> 1; g = IM_GET_RAW_PIXEL(img, x, y); } } else { // Odd row if ((x % 2) == 0) { // Even Col r = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x-1, y) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x+1, y)) >> 1; g = IM_GET_RAW_PIXEL(img, x, y); b = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y+1)) >> 1; } else { // Odd col r = IM_GET_RAW_PIXEL(img, x, y); g = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_Y(img, x, y+1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x-1, y) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_X(img, x+1, y)) >> 2; b = (IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x-1, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x+1, y-1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x-1, y+1) + IM_GET_RAW_PIXEL_CHECK_BOUNDS_XY(img, x+1, y+1)) >> 2; } } r = IM_R825(r); g = IM_G826(g); b = IM_B825(b); *rgbbuf++ = IM_RGB565(r, g, b); } } } //////////////////////////////////////////////////////////////////////////////// static save_image_format_t imblib_parse_extension(image_t *img, const char *path) { size_t l = strlen(path); const char *p = path + l; if (l >= 5) { if (((p[-1] == 'g') || (p[-1] == 'G')) && ((p[-2] == 'e') || (p[-2] == 'E')) && ((p[-3] == 'p') || (p[-3] == 'P')) && ((p[-4] == 'j') || (p[-4] == 'J')) && ((p[-5] == '.') || (p[-5] == '.'))) { // Will convert to JPG if not. return FORMAT_JPG; } } if (l >= 4) { if (((p[-1] == 'g') || (p[-1] == 'G')) && ((p[-2] == 'p') || (p[-2] == 'P')) && ((p[-3] == 'j') || (p[-3] == 'J')) && ((p[-4] == '.') || (p[-4] == '.'))) { // Will convert to JPG if not. return FORMAT_JPG; } else if (((p[-1] == 'p') || (p[-1] == 'P')) && ((p[-2] == 'm') || (p[-2] == 'M')) && ((p[-3] == 'b') || (p[-3] == 'B')) && ((p[-4] == '.') || (p[-4] == '.'))) { if (IM_IS_JPEG(img) || IM_IS_BAYER(img)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Image is not BMP!")); } return FORMAT_BMP; } else if (((p[-1] == 'm') || (p[-1] == 'M')) && ((p[-2] == 'p') || (p[-2] == 'P')) && ((p[-3] == 'p') || (p[-3] == 'P')) && ((p[-4] == '.') || (p[-4] == '.'))) { if (!IM_IS_RGB565(img)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Image is not PPM!")); } return FORMAT_PNM; } else if (((p[-1] == 'm') || (p[-1] == 'M')) && ((p[-2] == 'g') || (p[-2] == 'G')) && ((p[-3] == 'p') || (p[-3] == 'P')) && ((p[-4] == '.') || (p[-4] == '.'))) { if (!IM_IS_GS(img)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Image is not PGM!")); } return FORMAT_PNM; } else if (((p[-1] == 'w') || (p[-1] == 'W')) && ((p[-2] == 'a') || (p[-2] == 'A')) && ((p[-3] == 'r') || (p[-3] == 'R')) && ((p[-4] == '.') || (p[-4] == '.'))) { if (!IM_IS_BAYER(img)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Image is not BAYER!")); } return FORMAT_RAW; } } return FORMAT_DONT_CARE; } bool imlib_read_geometry(mp_obj_t fp, image_t *img, const char *path, img_read_settings_t *rs) { file_read_open_raise(fp, path); char magic[2]; read_data(fp, &magic, 2); file_close(fp); bool vflipped = false; if ((magic[0]=='P') && ((magic[1]=='2') || (magic[1]=='3') || (magic[1]=='5') || (magic[1]=='6'))) { // PPM rs->format = FORMAT_PNM; file_read_open_raise(fp, path); file_buffer_on(fp); // REMEMBER TO TURN THIS OFF LATER! ppm_read_geometry(fp, img, path, &rs->ppm_rs); } else if ((magic[0]=='B') && (magic[1]=='M')) { // BMP rs->format = FORMAT_BMP; file_read_open_raise(fp, path); file_buffer_on(fp); // REMEMBER TO TURN THIS OFF LATER! vflipped = bmp_read_geometry(fp, img, &rs->bmp_rs); } else { fs_unsupported_format(NULL); } imblib_parse_extension(img, path); // Enforce extension! return vflipped; } static void imlib_read_pixels(FIL *fp, image_t *img, int line_start, int line_end, img_read_settings_t *rs) { switch (rs->format) { case FORMAT_BMP: bmp_read_pixels(fp, img, line_start, line_end, &rs->bmp_rs); break; case FORMAT_PNM: ppm_read_pixels(fp, img, line_start, line_end, &rs->ppm_rs); break; default: // won't happen break; } } void imlib_image_operation(image_t *img, const char *path, image_t *other, int scalar, line_op_t op, void *data) { if (path) { uint32_t size = fb_avail() / 2; void *alloc = fb_alloc(size); // We have to do this before the read. // This code reads a window of an image in at a time and then executes // the line operation on each line in that window before moving to the // next window. The vflipped part is here because BMP files can be saved // vertically flipped resulting in us reading the image backwards. FIL fp; image_t temp; img_read_settings_t rs; bool vflipped = imlib_read_geometry(&fp, &temp, path, &rs); if (!IM_EQUAL(img, &temp)) { fs_not_equal(&fp); } // When processing vertically flipped images the read function will fill // the window up from the bottom. The read function assumes that the // window is equal to an image in size. However, since this is not the // case we shrink the window size to how many lines we're buffering. temp.pixels = alloc; temp.h = (size / (temp.w * temp.bpp)); // round down // This should never happen unless someone forgot to free. if ((!temp.pixels) || (!temp.h)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError, "Not enough memory available!")); } for (int i=0; i<img->h; i+=temp.h) { // goes past end int can_do = IM_MIN(temp.h, img->h-i); imlib_read_pixels(&fp, &temp, 0, can_do, &rs); for (int j=0; j<can_do; j++) { if (!vflipped) { op(img, i+j, temp.pixels+(temp.w*temp.bpp*j), data, false); } else { op(img, (img->h-i-can_do)+j, temp.pixels+(temp.w*temp.bpp*j), data, true); } } } file_buffer_off(&fp); file_close(&fp); fb_free(); } else if (other) { if (!IM_EQUAL(img, other)) { fs_not_equal(NULL); } switch (img->bpp) { case IMAGE_BPP_BINARY: { for (int i=0, ii=img->h; i<ii; i++) { op(img, i, IMAGE_COMPUTE_BINARY_PIXEL_ROW_PTR(other, i), data, false); } break; } case IMAGE_BPP_GRAYSCALE: { for (int i=0, ii=img->h; i<ii; i++) { op(img, i, IMAGE_COMPUTE_GRAYSCALE_PIXEL_ROW_PTR(other, i), data, false); } break; } case IMAGE_BPP_RGB565: { for (int i=0, ii=img->h; i<ii; i++) { op(img, i, IMAGE_COMPUTE_RGB565_PIXEL_ROW_PTR(other, i), data, false); } break; } default: { break; } } } else { switch(img->bpp) { case IMAGE_BPP_BINARY: { uint32_t *row_ptr = fb_alloc(IMAGE_BINARY_LINE_LEN_BYTES(img)); for (int i=0, ii=img->w; i<ii; i++) { IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr, i, scalar); } for (int i=0, ii=img->h; i<ii; i++) { op(img, i, row_ptr, data, false); } fb_free(); break; } case IMAGE_BPP_GRAYSCALE: { uint8_t *row_ptr = fb_alloc(IMAGE_GRAYSCALE_LINE_LEN_BYTES(img)); for (int i=0, ii=img->w; i<ii; i++) { IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr, i, scalar); } for (int i=0, ii=img->h; i<ii; i++) { op(img, i, row_ptr, data, false); } fb_free(); break; } case IMAGE_BPP_RGB565: { uint16_t *row_ptr = fb_alloc(IMAGE_RGB565_LINE_LEN_BYTES(img)); for (int i=0, ii=img->w; i<ii; i++) { IMAGE_PUT_RGB565_PIXEL_FAST(row_ptr, i, scalar); } for (int i=0, ii=img->h; i<ii; i++) { op(img, i, row_ptr, data, false); } fb_free(); break; } default: { break; } } } } void imlib_load_image(image_t *img, const char *path, mp_obj_t file) { int err = 0; char magic[2]; bool is_file_obj = true; if( !file ) { file = vfs_internal_open(path,"rb", &err); is_file_obj = false; } if(file == MP_OBJ_NULL || err != 0) mp_raise_OSError(err); vfs_internal_read(file, magic, 2, &err); if( err != 0) mp_raise_OSError(err); vfs_internal_seek(file,-2, SEEK_CUR, &err); if( err != 0) { int tmp = err; vfs_internal_close(file, &err); mp_raise_OSError(tmp); } /*if ((magic[0]=='P') && ((magic[1]=='2') || (magic[1]=='3') || (magic[1]=='5') || (magic[1]=='6'))) { // PPM ppm_read(img, path); } else*/ if ((magic[0]=='B') && (magic[1]=='M')) { // BMP bmp_read(img, path); } else if ((magic[0]==0xFF) && (magic[1]==0xD8)) { // JPEG // jpeg_read(img, path); int err = picojpeg_util_read(img, file, NULL, 0); int tmp; if(!is_file_obj) vfs_internal_close(file, &tmp); if( err != 0) { if(is_file_obj) vfs_internal_close(file, &tmp); mp_raise_OSError(err); } } else { mp_raise_ValueError("format not supported"); } if(!is_file_obj) { imblib_parse_extension(img, path); // Enforce extension! } } void imlib_save_image(image_t *img, const char *path, rectangle_t *roi, int quality) { switch (imblib_parse_extension(img, path)) { //TODO: case FORMAT_BMP: bmp_write_subimg(img, path, roi); break; // case FORMAT_PNM: // ppm_write_subimg(img, path, roi); // break; // case FORMAT_RAW: { // FIL fp; // file_write_open_raise(&fp, path); // write_data(&fp, img->pixels, img->w * img->h); // file_close(&fp); // break; // } case FORMAT_JPG: jpeg_write(img, path, quality); break; // case FORMAT_DONT_CARE: // // Path doesn't have an extension. // if (IM_IS_JPEG(img)) { // char *new_path = strcat(strcpy(fb_alloc(strlen(path)+5), path), ".jpg"); // jpeg_write(img, new_path, quality); // fb_free(); // } else if (IM_IS_BAYER(img)) { // FIL fp; // char *new_path = strcat(strcpy(fb_alloc(strlen(path)+5), path), ".raw"); // file_write_open_raise(&fp, new_path); // write_data(&fp, img->pixels, img->w * img->h); // file_close(&fp); // fb_free(); // } else { // RGB or GS, save as BMP. // char *new_path = strcat(strcpy(fb_alloc(strlen(path)+5), path), ".bmp"); // bmp_write_subimg(img, new_path, roi); // fb_free(); // } // break; default: break; } } //////////////////////////////////////////////////////////////////////////////// // A simple algorithm for correcting lens distortion. // See http://www.tannerhelland.com/4743/simple-algorithm-correcting-lens-distortion/ void imlib_lens_corr(image_t *img, float strength, float zoom) { zoom = 1.0f / zoom; int halfWidth = img->w / 2; int halfHeight = img->h / 2; float lens_corr_radius = strength / fast_sqrtf((img->w * img->w) + (img->h * img->h)); switch(img->bpp) { case IMAGE_BPP_BINARY: { // Create a temp copy of the image to pull pixels from. uint32_t *tmp = fb_alloc(((img->w + UINT32_T_MASK) >> UINT32_T_SHIFT) * img->h); memcpy(tmp, img->data, ((img->w + UINT32_T_MASK) >> UINT32_T_SHIFT) * img->h); memset(img->data, 0, ((img->w + UINT32_T_MASK) >> UINT32_T_SHIFT) * img->h); for (int y = 0, yy = img->h; y < yy; y++) { uint32_t *row_ptr = IMAGE_COMPUTE_BINARY_PIXEL_ROW_PTR(img, y); int newY = y - halfHeight; int newY2 = newY * newY; float zoomedY = newY * zoom; for (int x = 0, xx = img->w; x < xx; x++) { int newX = x - halfWidth; int newX2 = newX * newX; float zoomedX = newX * zoom; float r = lens_corr_radius * fast_sqrtf(newX2 + newY2); float theta = (r < 0.0000001f) ? 1.0f : (fast_atanf(r) / r); int sourceX = halfWidth + fast_roundf(theta * zoomedX); int sourceY = halfHeight + fast_roundf(theta * zoomedY); if ((0 <= sourceX) && (sourceX < img->w) && (0 <= sourceY) && (sourceY < img->h)) { uint32_t *ptr = tmp + (((img->w + UINT32_T_MASK) >> UINT32_T_SHIFT) * sourceY); int pixel = IMAGE_GET_BINARY_PIXEL_FAST(ptr, sourceX); IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr, x, pixel); } } } fb_free(); break; } case IMAGE_BPP_GRAYSCALE: { // Create a temp copy of the image to pull pixels from. uint8_t *tmp = fb_alloc(img->w * img->h * sizeof(uint8_t)); memcpy(tmp, img->data, img->w * img->h * sizeof(uint8_t)); memset(img->data, 0, img->w * img->h * sizeof(uint8_t)); for (int y = 0, yy = img->h; y < yy; y++) { uint8_t *row_ptr = IMAGE_COMPUTE_GRAYSCALE_PIXEL_ROW_PTR(img, y); int newY = y - halfHeight; int newY2 = newY * newY; float zoomedY = newY * zoom; for (int x = 0, xx = img->w; x < xx; x++) { int newX = x - halfWidth; int newX2 = newX * newX; float zoomedX = newX * zoom; float r = lens_corr_radius * fast_sqrtf(newX2 + newY2); float theta = (r < 0.0000001f) ? 1.0f : (fast_atanf(r) / r); int sourceX = halfWidth + fast_roundf(theta * zoomedX); int sourceY = halfHeight + fast_roundf(theta * zoomedY); if ((0 <= sourceX) && (sourceX < img->w) && (0 <= sourceY) && (sourceY < img->h)) { uint8_t *ptr = tmp + (img->w * sourceY); int pixel = IMAGE_GET_GRAYSCALE_PIXEL_FAST(ptr, sourceX); IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr, x, pixel); } } } fb_free(); break; } case IMAGE_BPP_RGB565: { // Create a temp copy of the image to pull pixels from. uint16_t *tmp = fb_alloc(img->w * img->h * sizeof(uint16_t)); memcpy(tmp, img->data, img->w * img->h * sizeof(uint16_t)); memset(img->data, 0, img->w * img->h * sizeof(uint16_t)); for (int y = 0, yy = img->h; y < yy; y++) { uint16_t *row_ptr = IMAGE_COMPUTE_RGB565_PIXEL_ROW_PTR(img, y); int newY = y - halfHeight; int newY2 = newY * newY; float zoomedY = newY * zoom; for (int x = 0, xx = img->w; x < xx; x++) { int newX = x - halfWidth; int newX2 = newX * newX; float zoomedX = newX * zoom; float r = lens_corr_radius * fast_sqrtf(newX2 + newY2); float theta = (r < 0.0000001f) ? 1.0f : (fast_atanf(r) / r); int sourceX = halfWidth + fast_roundf(theta * zoomedX); int sourceY = halfHeight + fast_roundf(theta * zoomedY); if ((0 <= sourceX) && (sourceX < img->w) && (0 <= sourceY) && (sourceY < img->h)) { uint16_t *ptr = tmp + (img->w * sourceY); int pixel = IMAGE_GET_RGB565_PIXEL_FAST(ptr, sourceX); IMAGE_PUT_RGB565_PIXEL_FAST(row_ptr, x, pixel); } } } fb_free(); break; } default: { break; } } } //////////////////////////////////////////////////////////////////////////////// int imlib_image_mean(image_t *src, int *r_mean, int *g_mean, int *b_mean) { int r_s = 0; int g_s = 0; int b_s = 0; int n = src->w * src->h; switch(src->bpp) { case IMAGE_BPP_BINARY: { // Can't run this on a binary image. break; } case IMAGE_BPP_GRAYSCALE: { for (int i=0; i<n; i++) { r_s += src->pixels[i]; } *r_mean = r_s/n; *g_mean = r_s/n; *b_mean = r_s/n; break; } case IMAGE_BPP_RGB565: { for (int i=0; i<n; i++) { uint16_t p = ((uint16_t*)src->pixels)[i]; r_s += COLOR_RGB565_TO_R8(p); g_s += COLOR_RGB565_TO_G8(p); b_s += COLOR_RGB565_TO_B8(p); } *r_mean = r_s/n; *g_mean = g_s/n; *b_mean = b_s/n; break; } default: { break; } } return 0; } // One pass standard deviation. int imlib_image_std(image_t *src) { int w=src->w; int h=src->h; int n=w*h; uint8_t *data=src->pixels; uint32_t s=0, sq=0; for (int i=0; i<n; i+=2) { s += data[i+0]+data[i+1]; sq += data[i+0]*data[i+0] + data[i+1]*data[i+1]; //TODO } if (n%2) { s += data[n-1]; sq += data[n-1]*data[n-1]; } /* mean */ int m = s/n; /* variance */ uint32_t v = sq/n-(m*m); /* std */ return fast_sqrtf(v); } static volatile uint8_t _ai_done_flag; static int kpu_done(void *ctx) { _ai_done_flag = 1; return 0; } void imlib_sepconv3(image_t *img, const int8_t *krn, const float m, const int b) { float krn_f[9]; kpu_task_t task; _ai_done_flag = 0; krn_f[0]=(float)(krn[0]);krn_f[1]=(float)(krn[1]);krn_f[2]=(float)(krn[2]); krn_f[3]=(float)(krn[3]);krn_f[4]=(float)(krn[4]);krn_f[5]=(float)(krn[5]); krn_f[6]=(float)(krn[6]);krn_f[7]=(float)(krn[7]);krn_f[8]=(float)(krn[8]); sipeed_conv_init(&task, img->w, img->h, 1, 1, krn_f); sipeed_conv_run(&task, img->pixels, img->pixels, kpu_done); while(!_ai_done_flag); _ai_done_flag=0; return; }
788649.c
#include <std.h> inherit "/std/armour"; int isSetup, isLight, isBroke; void create() { ::create(); } string my_long() { string tmp; if(isLight) { if(isBroke) { tmp = "%^BOLD%^%^WHITE%^The band of this simple ring is made from a "+ "pure white material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band that is cracked into multiple pieces. %^RESET%^"; } else if(!query_worn()) { tmp = "%^BOLD%^%^WHITE%^The band of this simple ring is made from a "+ "pure white material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band. The gem seems to give off a faint light that sometimes "+ "flickers.%^RESET%^"; } else { tmp = "%^BOLD%^%^WHITE%^The band of this simple ring is made from a "+ "pure white material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band. The gem is currently illuminated, giving off a "+ "soft light.%^RESET%^"; } } else if(!isLight) { if(isBroke) { tmp = "%^BOLD%^%^BLACK%^The band of this simple ring is made from a "+ "pure black. material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band that is cracked into multiple pieces.%^RESET%^"; } else if(!query_worn()) { tmp = "%^BOLD%^%^BLACK%^The band of this simple ring is made from a "+ "pure black. material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band. The gem seems to give off a faint darkness that sometimes "+ "shimmers.%^RESET%^"; } else { tmp = "%^BOLD%^%^BLACK%^The band of this simple ring is made from a "+ "pure black. material. The material is impossible to identify but you believe "+ "that it is some type of mineral. There is a very tiny and almost indistinguishable "+ "gem set into the top of the band. The gem is currently radiating darkness.%^RESET%^"; } } return tmp; } string my_short() { string tmp; if(isLight) tmp = "%^BOLD%^%^WHITE%^A lesser ring of light%^RESET%^"; else tmp = "%^BOLD%^%^BLACK%^A lesser ring of darkness%^RESET%^"; if(query_worn() && !isBroke) { if(isLight) tmp += " %^BOLD%^%^WHITE%^(%^BOLD%^%^CYAN%^ softly illuminated%^BOLD%^%^WHITE%^ )%^RESET%^"; else tmp += "%^BOLD%^%^WHITE%^ ( %^BOLD%^%^BLACK%^radiating darkness %^BOLD%^%^WHITE%^)%^RESET%^"; } return tmp; } string my_obvious_short() { string tmp; if(isLight) tmp = "%^BOLD%^%^WHITE%^A pure white ring%^RESET%^"; else tmp = "%^BOLD%^%^BLACK%^A pure black ring%^RESET%^"; if(query_worn() && !isBroke) { if(isLight) tmp += " %^BOLD%^%^WHITE%^(%^BOLD%^%^CYAN%^ softly illuminated%^BOLD%^%^WHITE%^ )%^RESET%^"; else tmp += "%^BOLD%^%^WHITE%^ ( %^BOLD%^%^BLACK%^radiating darkness %^BOLD%^%^WHITE%^)%^RESET%^"; } return tmp; } void set_for(object myPlayer) { if(!objectp(myPlayer)) return; isSetup = 1; if(member_array((string)myPlayer->query_race(), ({"bugbear", "hobgoblin", "goblin", "gnoll", "orc", "half-drow", "minotaur", "ogre", "ogre-mage", "half-ogre", "kobold", "drow", "troll"})) == -1) { set_name("lesser ring of light"); set_id(({"ring","ring of light", "lesser ring", "lesser ring of light"})); isLight = 1; } else { set_name("lesser ring of darkness"); set_id(({"ring","ring of darkness", "lesser ring", "lesser ring of darkness"})); isLight = 0; } set_item_bonus("sight bonus", 2); set_long((:TO, "my_long":)); set_obvious_short((:TO, "my_obvious_short":)); set_short((:TO, "my_short":)); set_type("ring"); set_ac(0); set_weight(3); set_value(0); set_limbs(({"right hand","left hand"})); set_wear((:TO,"wearme":)); set_remove((:TO,"removeme":)); } int wearme() { if(!objectp(TO)) return 0; if(!objectp(ETO)) return 0; if(isBroke) return 1; if(isLight) { tell_object(ETO, "%^BOLD%^%^WHITE%^The gem on your ring begins illuminating softly.%^RESET%^"); if(objectp(EETO)) { tell_room(EETO, "%^BOLD%^%^WHITE%^The gem on "+ETOQCN+"%^BOLD%^%^WHITE%^"+ "'s begins illuminating softly.%^RESET%^", ETO); } } else if(!isLight) { tell_object(ETO, "%^BOLD%^%^BLACK%^The gem on your ring begins radiating darkness.%^RESET%^"); if(objectp(EETO)) { tell_room(EETO, "%^BOLD%^%^BLACK%^The gem on "+ETOQCN+"%^BOLD%^%^WHITE%^"+ "'s ring begins radiating darkness.%^RESET%^", ETO); } } return 1; } int removeme() { if(!objectp(TO)) return 0; if(!objectp(ETO)) return 0; if(isBroke) return 1; if(isLight) { tell_object(ETO, "%^BOLD%^%^WHITE%^The gem on your ring dims.%^RESET%^"); if(objectp(EETO)) { tell_room(EETO, "%^BOLD%^%^WHITE%^The gem on "+ETOQCN+"%^BOLD%^%^WHITE%^"+ "'s ring suddenly dims.%^RESET%^", ETO); } } else if(!isLight) { tell_object(ETO, "%^BOLD%^%^BLACK%^The gem on your ring flickers before becoming mundane once again.%^RESET%^"); if(objectp(EETO)) { tell_room(EETO, "%^BOLD%^%^BLACK%^The gem on "+ETOQCN+"%^BOLD%^%^WHITE%^"+ "'s ring flickers before becoming mundane once again.%^RESET%^", ETO); } } if(!newbiep(ETO) && !isBroke) { if(!random(8)) { tell_object(ETO, "%^BOLD%^%^RED%^The gem in your ring suddenly cracks!%^RESET%^"); remove_property("sight bonus"); isBroke = 1; } } return 1; } void init() { ::init(); if(isSetup) return; if(!objectp(TO)) return; if(!objectp(ETO)) return; if(!userp(ETO)) return; if(userp(ETO)) { set_for(ETO); return; } }
769087.c
/* Copyright (C) 1991-2019 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <libio/iolibio.h> #include <stdio.h> #define fread(p, m, n, s) _IO_fread(p, m, n, s) /* Read a word (int) from STREAM. */ int getw(FILE* stream) { int w; /* Is there a better way? */ if (fread((void*)&w, sizeof(w), 1, stream) != 1) return EOF; return w; }
421128.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67a.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_dest.label.xml Template File: sources-sink-67a.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sinks: memmove * BadSink : Copy int array to data using memmove * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" typedef struct _CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type { int * a; } CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type; #ifndef OMITBAD /* bad function declaration */ void CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67b_bad_sink(CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type my_struct); void CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_bad() { int * data; CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type my_struct; data = NULL; /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (int *)malloc(50*sizeof(int)); my_struct.a = data; CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67b_bad_sink(my_struct); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67b_goodG2B_sink(CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type my_struct); static void goodG2B() { int * data; CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_struct_type my_struct; data = NULL; /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (int *)malloc(100*sizeof(int)); my_struct.a = data; CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67b_goodG2B_sink(my_struct); } void CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_dest_int_memmove_67_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
993216.c
/**************************************************************************** * drivers/mtd/smart.c * * Sector Mapped Allocation for Really Tiny (SMART) Flash block driver. * * Copyright (C) 2013 Ken Pettit. All rights reserved. * Author: Ken Pettit <[email protected]> * * 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 name NuttX 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <sys/ioctl.h> #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <debug.h> #include <errno.h> #include <nuttx/kmalloc.h> #include <nuttx/fs/fs.h> #include <nuttx/fs/ioctl.h> #include <nuttx/mtd.h> #include <nuttx/smart.h> /**************************************************************************** * Private Definitions ****************************************************************************/ #define SMART_STATUS_COMMITTED 0x80 #define SMART_STATUS_RELEASED 0x40 #define SMART_STATUS_SIZEBITS 0x1C #define SMART_STATUS_VERBITS 0x03 #define SMART_STATUS_VERSION 0x01 #define SMART_SECTSIZE_256 0x00 #define SMART_SECTSIZE_512 0x04 #define SMART_SECTSIZE_1024 0x08 #define SMART_SECTSIZE_2048 0x0C #define SMART_SECTSIZE_4096 0x10 #define SMART_SECTSIZE_8192 0x14 #define SMART_SECTSIZE_16384 0x18 #define SMART_FMT_STAT_UNKNOWN 0 #define SMART_FMT_STAT_FORMATTED 1 #define SMART_FMT_STAT_NOFMT 2 #define SMART_FMT_POS1 sizeof(struct smart_sect_header_s) #define SMART_FMT_POS2 (SMART_FMT_POS1 + 1) #define SMART_FMT_POS3 (SMART_FMT_POS1 + 2) #define SMART_FMT_POS4 (SMART_FMT_POS1 + 3) #define SMART_FMT_SIG1 'S' #define SMART_FMT_SIG2 'M' #define SMART_FMT_SIG3 'R' #define SMART_FMT_SIG4 'T' #define SMART_FMT_VERSION_POS (SMART_FMT_POS1 + 4) #define SMART_FMT_NAMESIZE_POS (SMART_FMT_POS1 + 5) #define SMART_FMT_ROOTDIRS_POS (SMART_FMT_POS1 + 6) #define SMARTFS_FMT_AGING_POS 32 #define SMART_FMT_VERSION 1 #define SMART_FIRST_ALLOC_SECTOR 12 /* First logical sector number we will * use for assignment of requested Alloc * sectors. All enries below this are * reserved (some for root dir entries, * other for our use, such as format * sector, etc. */ #if defined(CONFIG_FS_READAHEAD) || (defined(CONFIG_FS_WRITABLE) && defined(CONFIG_FS_WRITEBUFFER)) # define CONFIG_SMART_RWBUFFER 1 #endif #ifndef CONFIG_MTD_SMART_SECTOR_SIZE # define CONFIG_MTD_SMART_SECTOR_SIZE 1024 #endif #ifndef offsetof #define offsetof(type, member) ( (size_t) &( ( (type *) 0)->member)) #endif /**************************************************************************** * Private Types ****************************************************************************/ struct smart_struct_s { FAR struct mtd_dev_s *mtd; /* Contained MTD interface */ struct mtd_geometry_s geo; /* Device geometry */ uint16_t neraseblocks; /* Number of erase blocks or sub-sectors */ uint16_t freesectors; /* Total number of free sectors */ uint16_t mtdBlksPerSector; /* Number of MTD blocks per SMART Sector */ uint16_t sectorsPerBlk; /* Number of sectors per erase block */ uint16_t sectorsize; /* Sector size on device */ uint16_t totalsectors; /* Total number of sectors on device */ FAR uint16_t *sMap; /* Virtual to physical sector map */ FAR uint8_t *releasecount; /* Count of released sectors per erase block */ FAR uint8_t *freecount; /* Count of free sectors per erase block */ FAR char *rwbuffer; /* Our sector read/write buffer */ const FAR char *partname; /* Optional partition name */ uint8_t formatversion; /* Format version on the device */ uint8_t formatstatus; /* Indicates the status of the device format */ uint8_t namesize; /* Length of filenames on this device */ #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS uint8_t rootdirentries; /* Number of root directory entries */ uint8_t minor; /* Minor number of the block entry */ #endif }; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS struct smart_multiroot_device_s { FAR struct smart_struct_s* dev; uint8_t rootdirnum; }; #endif struct smart_sect_header_s { uint8_t logicalsector[2]; /* The logical sector number */ uint8_t seq[2]; /* Incrementing sequence number */ uint8_t status; /* Status of this sector: * Bit 7: 1 = Not commited * 0 = commited * Bit 6: 1 = Not released * 0 = released * Bit 5: Reserved - 1 * Bit 4: Reserved - 1 * Bit 3: Reserved - 1 * Bit 2: Reserved - 1 * Bit 1-0: Format version */ }; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static int smart_open(FAR struct inode *inode); static int smart_close(FAR struct inode *inode); static ssize_t smart_reload(struct smart_struct_s *dev, FAR uint8_t *buffer, off_t startblock, size_t nblocks); static ssize_t smart_read(FAR struct inode *inode, unsigned char *buffer, size_t start_sector, unsigned int nsectors); #ifdef CONFIG_FS_WRITABLE static ssize_t smart_write(FAR struct inode *inode, const unsigned char *buffer, size_t start_sector, unsigned int nsectors); #endif static int smart_geometry(FAR struct inode *inode, struct geometry *geometry); static int smart_ioctl(FAR struct inode *inode, int cmd, unsigned long arg); /**************************************************************************** * Private Data ****************************************************************************/ static const struct block_operations g_bops = { smart_open, /* open */ smart_close, /* close */ smart_read, /* read */ #ifdef CONFIG_FS_WRITABLE smart_write, /* write */ #else NULL, /* write */ #endif smart_geometry, /* geometry */ smart_ioctl /* ioctl */ }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: smart_open * * Description: Open the block device * ****************************************************************************/ static int smart_open(FAR struct inode *inode) { fvdbg("Entry\n"); return OK; } /**************************************************************************** * Name: smart_close * * Description: close the block device * ****************************************************************************/ static int smart_close(FAR struct inode *inode) { fvdbg("Entry\n"); return OK; } /**************************************************************************** * Name: smart_reload * * Description: Read the specified numer of sectors * ****************************************************************************/ static ssize_t smart_reload(struct smart_struct_s *dev, FAR uint8_t *buffer, off_t startblock, size_t nblocks) { ssize_t nread; ssize_t mtdBlocks, mtdStartBlock; /* Calculate the number of MTD blocks to read */ mtdBlocks = nblocks * dev->mtdBlksPerSector; /* Calculate the first MTD block number */ mtdStartBlock = startblock * dev->mtdBlksPerSector; /* Read the full erase block into the buffer */ fdbg("Read %d blocks starting at block %d\n", mtdBlocks, mtdStartBlock); nread = MTD_BREAD(dev->mtd, mtdStartBlock, mtdBlocks, buffer); if (nread != mtdBlocks) { fdbg("Read %d blocks starting at block %d failed: %d\n", nblocks, startblock, nread); } return nread; } /**************************************************************************** * Name: smart_read * * Description: Read the specified numer of sectors * ****************************************************************************/ static ssize_t smart_read(FAR struct inode *inode, unsigned char *buffer, size_t start_sector, unsigned int nsectors) { struct smart_struct_s *dev; fvdbg("SMART: sector: %d nsectors: %d\n", start_sector, nsectors); DEBUGASSERT(inode && inode->i_private); #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev = ((struct smart_multiroot_device_s*) inode->i_private)->dev; #else dev = (struct smart_struct_s *)inode->i_private; #endif return smart_reload(dev, buffer, start_sector, nsectors); } /**************************************************************************** * Name: smart_write * * Description: Write (or buffer) the specified number of sectors * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static ssize_t smart_write(FAR struct inode *inode, const unsigned char *buffer, size_t start_sector, unsigned int nsectors) { struct smart_struct_s *dev; off_t alignedblock; off_t mask; off_t blkstowrite; off_t offset; off_t nextblock; off_t mtdBlksPerErase; off_t eraseblock; size_t remaining; size_t nxfrd; int ret; off_t mtdstartblock, mtdblockcount; fvdbg("sector: %d nsectors: %d\n", start_sector, nsectors); DEBUGASSERT(inode && inode->i_private); #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev = ((struct smart_multiroot_device_s*) inode->i_private)->dev; #else dev = (struct smart_struct_s *)inode->i_private; #endif /* I think maybe we need to lock on a mutex here */ /* Get the aligned block. Here is is assumed: (1) The number of R/W blocks * per erase block is a power of 2, and (2) the erase begins with that same * alignment. */ mask = dev->sectorsPerBlk - 1; alignedblock = ((start_sector + mask) & ~mask) * dev->mtdBlksPerSector; /* Convert SMART blocks into MTD blocks */ mtdstartblock = start_sector * dev->mtdBlksPerSector; mtdblockcount = nsectors * dev->mtdBlksPerSector; mtdBlksPerErase = dev->mtdBlksPerSector * dev->sectorsPerBlk; fvdbg("mtdsector: %d mtdnsectors: %d\n", mtdstartblock, mtdblockcount); /* Start at first block to be written */ remaining = mtdblockcount; nextblock = mtdstartblock; offset = 0; /* Loop for all blocks to be written */ while (remaining > 0) { /* If this is an aligned block, then erase the block */ if (alignedblock == nextblock) { /* Erase the erase block */ eraseblock = alignedblock / mtdBlksPerErase; ret = MTD_ERASE(dev->mtd, eraseblock, 1); if (ret < 0) { fdbg("Erase block=%d failed: %d\n", eraseblock, ret); /* Unlock the mutex if we add one */ return ret; } } /* Calculate the number of blocks to write. */ blkstowrite = mtdBlksPerErase; if (nextblock != alignedblock) { blkstowrite = alignedblock - nextblock; } if (blkstowrite > remaining) { blkstowrite = remaining; } /* Try to write to the sector. */ fdbg("Write MTD block %d from offset %d\n", nextblock, offset); nxfrd = MTD_BWRITE(dev->mtd, nextblock, blkstowrite, &buffer[offset]); if (nxfrd != blkstowrite) { /* The block is not empty!! What to do? */ fdbg("Write block %d failed: %d.\n", nextblock, nxfrd); /* Unlock the mutex if we add one */ return -EIO; } /* Then update for amount written */ nextblock += blkstowrite; remaining -= blkstowrite; offset += blkstowrite * dev->geo.blocksize; alignedblock += mtdBlksPerErase; } return nsectors; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_geometry * * Description: Return device geometry * ****************************************************************************/ static int smart_geometry(FAR struct inode *inode, struct geometry *geometry) { struct smart_struct_s *dev; uint32_t erasesize; fvdbg("Entry\n"); DEBUGASSERT(inode); if (geometry) { #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev = ((struct smart_multiroot_device_s*) inode->i_private)->dev; #else dev = (struct smart_struct_s *)inode->i_private; #endif geometry->geo_available = true; geometry->geo_mediachanged = false; #ifdef CONFIG_FS_WRITABLE geometry->geo_writeenabled = true; #else geometry->geo_writeenabled = false; #endif erasesize = dev->geo.erasesize; if (erasesize == 0) { erasesize = 65536; } geometry->geo_nsectors = dev->geo.neraseblocks * erasesize / dev->sectorsize; geometry->geo_sectorsize = dev->sectorsize; fvdbg("available: true mediachanged: false writeenabled: %s\n", geometry->geo_writeenabled ? "true" : "false"); fvdbg("nsectors: %d sectorsize: %d\n", geometry->geo_nsectors, geometry->geo_sectorsize); return OK; } return -EINVAL; } /**************************************************************************** * Name: smart_setsectorsize * * Description: Sets the device's sector size and recalculates sector size * dependant variables. * ****************************************************************************/ static int smart_setsectorsize(struct smart_struct_s *dev, uint16_t size) { uint32_t erasesize; uint32_t totalsectors; /* Validate the size isn't zero so we don't divide by zero below */ if (size == 0) { size = CONFIG_MTD_SMART_SECTOR_SIZE; } erasesize = dev->geo.erasesize; dev->neraseblocks = dev->geo.neraseblocks; /* Most FLASH devices have erase size of 64K, but geo.erasesize is only * 16 bits, so it will be zero */ if (erasesize == 0) { erasesize = 65536; } dev->sectorsize = size; dev->mtdBlksPerSector = dev->sectorsize / dev->geo.blocksize; dev->sectorsPerBlk = erasesize / dev->sectorsize; /* Release any existing rwbuffer and sMap */ if (dev->sMap != NULL) { kfree(dev->sMap); } if (dev->rwbuffer != NULL) { kfree(dev->rwbuffer); } /* Allocate a virtual to physical sector map buffer. Also allocate * the storage space for releasecount and freecounts. */ totalsectors = dev->neraseblocks * dev->sectorsPerBlk; dev->totalsectors = (uint16_t) totalsectors; dev->sMap = (uint16_t *) kmalloc(totalsectors * sizeof(uint16_t) + (dev->neraseblocks << 1)); if (!dev->sMap) { fdbg("Error allocating SMART virtual map buffer\n"); kfree(dev); return -EINVAL; } dev->releasecount = (uint8_t *) dev->sMap + (totalsectors * sizeof(uint16_t)); dev->freecount = dev->releasecount + dev->neraseblocks; /* Allocate a read/write buffer */ dev->rwbuffer = (char *) kmalloc(size); if (!dev->rwbuffer) { fdbg("Error allocating SMART read/write buffer\n"); kfree(dev->sMap); kfree(dev); return -EINVAL; } return OK; } /**************************************************************************** * Name: smart_bytewrite * * Description: Writes a non-page size count of bytes to the underlying * MTD device. If the MTD driver supports a direct impl of * write, then it uses it, otherwise it does a read-modify-write * and depends on the architecture of the flash to only program * bits that acutally changed. * ****************************************************************************/ static ssize_t smart_bytewrite(struct smart_struct_s *dev, size_t offset, int nbytes, const uint8_t *buffer) { ssize_t ret; #ifdef CONFIG_MTD_BYTE_WRITE /* Check if the underlying MTD device supports write */ if (dev->mtd->write != NULL) { /* Use the MTD's write method to write individual bytes */ ret = dev->mtd->write(dev->mtd, offset, nbytes, buffer); } else #endif { /* Perform block-based read-modify-write */ uint16_t startblock; uint16_t nblocks; /* First calculate the start block and number of blocks affected */ startblock = offset / dev->geo.blocksize; nblocks = (nbytes + dev->geo.blocksize-1) / dev->geo.blocksize; DEBUGASSERT(nblocks <= dev->mtdBlksPerSector); /* Do a block read */ ret = MTD_BREAD(dev->mtd, startblock, nblocks, (uint8_t *) dev->rwbuffer); if (ret < 0) { fdbg("Error %d reading from device\n", -ret); goto errout; } /* Modify the data */ memcpy(&dev->rwbuffer[offset - startblock * dev->geo.blocksize], buffer, nbytes); /* Write the data back to the device */ ret = MTD_BWRITE(dev->mtd, startblock, nblocks, (uint8_t *) dev->rwbuffer); if (ret < 0) { fdbg("Error %d writing to device\n", -ret); goto errout; } } ret = nbytes; errout: return ret; } /**************************************************************************** * Name: smart_scan * * Description: Performs a scan of the MTD device searching for format * information and fills in logical sector mapping, freesector * count, etc. * ****************************************************************************/ static int smart_scan(struct smart_struct_s *dev) { int sector; int ret; int offset; uint16_t totalsectors; uint16_t sectorsize; uint16_t logicalsector; uint16_t seq1; uint16_t seq2; size_t readaddress; struct smart_sect_header_s header; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS int x; char devname[22]; struct smart_multiroot_device_s *rootdirdev; #endif fvdbg("Entry\n"); /* Read the 1st header from the device. We always keep the * 1st sector's header's sectorsize field accurate, even * after we erase an MTD block/sector */ ret = MTD_READ(dev->mtd, 0, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { goto err_out; } /* Now set the sectorsize and other sectorsize derived variables */ if (header.status == CONFIG_SMARTFS_ERASEDSTATE) { sectorsize = CONFIG_MTD_SMART_SECTOR_SIZE; } else { sectorsize = (header.status & SMART_STATUS_SIZEBITS) << 7; } ret = smart_setsectorsize(dev, sectorsize); if (ret != OK) { goto err_out; } /* Initialize the device variables */ totalsectors = dev->neraseblocks * dev->sectorsPerBlk; dev->formatstatus = SMART_FMT_STAT_NOFMT; dev->freesectors = totalsectors; /* Initialize the freecount and releasecount arrays */ for (sector = 0; sector < dev->neraseblocks; sector++) { dev->freecount[sector] = dev->sectorsPerBlk; dev->releasecount[sector] = 0; } /* Initialize the sector map */ for (sector = 0; sector < totalsectors; sector++) { dev->sMap[sector] = -1; } /* Now scan the MTD device */ for (sector = 0; sector < totalsectors; sector++) { fvdbg("Scan sector %d\n", sector); /* Calculate the read address for this sector */ readaddress = sector * dev->mtdBlksPerSector * dev->geo.blocksize; /* Read the header for this sector */ ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { goto err_out; } /* Get the logical sector number for this physical sector */ logicalsector = *((uint16_t *) header.logicalsector); #if CONFIG_SMARTFS_ERASEDSTATE == 0x00 if (logicalsector == 0) { logicalsector = -1; } #endif /* Test if this sector has been committed */ if ((header.status & SMART_STATUS_COMMITTED) == (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)) { continue; } /* This block is commited, therefore not free. Update the * erase block's freecount. */ dev->freecount[sector / dev->sectorsPerBlk]--; dev->freesectors--; /* Test if this sector has been release and if it has, * update the erase block's releasecount. */ if ((header.status & SMART_STATUS_RELEASED) != (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED)) { dev->releasecount[sector / dev->sectorsPerBlk]++; continue; } if ((header.status & SMART_STATUS_VERBITS) != SMART_STATUS_VERSION) { continue; } /* Validate the logical sector number is in bounds */ if (logicalsector >= totalsectors) { /* Error in logical sector read from the MTD device */ fdbg("Invalid logical sector %d at physical %d.\n", logicalsector, sector); continue; } /* If this is logical sector zero, then read in the signature * information to validate the format signature. */ if (logicalsector == 0) { /* Read the sector data */ ret = MTD_READ(dev->mtd, readaddress, 32, (uint8_t*) dev->rwbuffer); if (ret != 32) { fdbg("Error reading physical sector %d.\n", sector); goto err_out; } /* Validate the format signature */ if (dev->rwbuffer[SMART_FMT_POS1] != SMART_FMT_SIG1 || dev->rwbuffer[SMART_FMT_POS2] != SMART_FMT_SIG2 || dev->rwbuffer[SMART_FMT_POS3] != SMART_FMT_SIG3 || dev->rwbuffer[SMART_FMT_POS4] != SMART_FMT_SIG4) { /* Invalid signature on a sector claiming to be sector 0! * What should we do? Release it?*/ continue; } /* TODO: May want to validate / save the erase block aging info */ /* Mark the volume as formatted and set the sector size */ dev->formatstatus = SMART_FMT_STAT_FORMATTED; dev->namesize = dev->rwbuffer[SMART_FMT_NAMESIZE_POS]; dev->formatversion = dev->rwbuffer[SMART_FMT_VERSION_POS]; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev->rootdirentries = dev->rwbuffer[SMART_FMT_ROOTDIRS_POS]; /* If rootdirentries is greater than 1, then we need to register * additional block devices. */ for (x = 1; x < dev->rootdirentries; x++) { if (dev->partname != NULL) { snprintf(dev->rwbuffer, sizeof(devname), "/dev/smart%d%s%d", dev->minor, dev->partname, x+1); } else { snprintf(devname, sizeof(devname), "/dev/smart%dd%d", dev->minor, x + 1); } /* Inode private data is a reference to a struct containing * the SMART device structure and the root directory number. */ rootdirdev = (struct smart_multiroot_device_s*) kmalloc(sizeof(*rootdirdev)); if (rootdirdev == NULL) { fdbg("Memory alloc failed\n"); ret = -ENOMEM; goto err_out; } /* Populate the rootdirdev */ rootdirdev->dev = dev; rootdirdev->rootdirnum = x; ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, rootdirdev); /* Inode private data is a reference to the SMART device structure */ ret = register_blockdriver(devname, &g_bops, 0, rootdirdev); } #endif } /* Test for duplicate logical sectors on the device */ if (dev->sMap[logicalsector] != 0xFFFF) { /* Uh-oh, we found more than 1 physical sector claiming to be * the * same logical sector. Use the sequence number information * to resolve who wins. */ uint16_t loser; seq2 = *((uint16_t *) header.seq); /* We must re-read the 1st physical sector to get it's seq number */ readaddress = dev->sMap[logicalsector] * dev->mtdBlksPerSector * dev->geo.blocksize; ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { goto err_out; } seq1 = *((uint16_t *) header.seq); /* Now determine who wins */ if (seq1 > 0xFFF0 && seq2 < 10) { /* Seq 2 is the winner ... we assume it wrapped */ loser = dev->sMap[logicalsector]; dev->sMap[logicalsector] = sector; } else if (seq2 > seq1) { /* Seq 2 is bigger, so it's the winner */ loser = dev->sMap[logicalsector]; dev->sMap[logicalsector] = sector; } else { /* We keep the original mapping and seq2 is the loser */ loser = sector; } /* Now release the loser sector */ readaddress = loser * dev->mtdBlksPerSector * dev->geo.blocksize; ret = MTD_READ(dev->mtd, readaddress, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { goto err_out; } #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF header.status &= ~SMART_STATUS_RELEASED; #else header.status |= SMART_STATUS_RELEASED; #endif offset = readaddress + offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &header.status); if (ret < 0) { fdbg("Error %d releasing duplicate sector\n", -ret); goto err_out; } } /* Update the logical to physical sector map */ dev->sMap[logicalsector] = sector; } fdbg("SMART Scan\n"); fdbg(" Erase size: %10d\n", dev->sectorsPerBlk * dev->sectorsize); fdbg(" Erase count: %10d\n", dev->neraseblocks); fdbg(" Sect/block: %10d\n", dev->sectorsPerBlk); fdbg(" MTD Blk/Sect: %10d\n", dev->mtdBlksPerSector); ret = OK; err_out: return ret; } /**************************************************************************** * Name: smart_getformat * * Description: Populates the SMART format structure based on the format * information for the inode. * ****************************************************************************/ #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS static inline int smart_getformat(struct smart_struct_s *dev, struct smart_format_s *fmt, uint8_t rootdirnum) #else static inline int smart_getformat(struct smart_struct_s *dev, struct smart_format_s *fmt) #endif { int ret; int x; fvdbg("Entry\n"); DEBUGASSERT(fmt); /* Test if we know the format status or not. If we don't know the * status, then we must perform a scan of the device to search * for the format marker */ if (dev->formatstatus != SMART_FMT_STAT_FORMATTED) { /* Perform the scan */ ret = smart_scan(dev); if (ret != OK) { goto err_out; } } /* Now fill in the structure */ if (dev->formatstatus == SMART_FMT_STAT_FORMATTED) { fmt->flags = SMART_FMT_ISFORMATTED; } else { fmt->flags = 0; } fmt->sectorsize = dev->sectorsize; fmt->availbytes = dev->sectorsize - sizeof(struct smart_sect_header_s); fmt->nsectors = dev->neraseblocks * dev->sectorsPerBlk; fmt->nfreesectors = dev->freesectors; fmt->namesize = dev->namesize; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS fmt->nrootdirentries = dev->rootdirentries; fmt->rootdirnum = rootdirnum; #endif /* Add the released sectors to the reported free sector count */ for (x = 0; x < dev->neraseblocks; x++) { fmt->nfreesectors += dev->releasecount[x]; } /* Subtract the reserved sector count */ fmt->nfreesectors -= dev->sectorsPerBlk + 4; ret = OK; err_out: return ret; } /**************************************************************************** * Name: smart_llformat * * Description: Performs a low-level format of the flash device. This * involves erasing the device and writing a valid sector * zero (logical) with proper format signature. * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static inline int smart_llformat(struct smart_struct_s *dev, unsigned long arg) { struct smart_sect_header_s *sectorheader; size_t wrcount; size_t totalsectors; int x; int ret; uint8_t sectsize; fvdbg("Entry\n"); /* Erase the MTD device */ ret = MTD_IOCTL(dev->mtd, MTDIOC_BULKERASE, 0); if (ret < 0) { return ret; } /* Now construct a logical sector zero header to write to the device. * We fill it with zero so when we add sector aging, all the sector * ages will already be initialized to zero without needing special * logic to deal with a 0xFF erased-state value. */ sectorheader = (struct smart_sect_header_s *) dev->rwbuffer; memset(dev->rwbuffer, 0, dev->sectorsize); memset(dev->rwbuffer, CONFIG_SMARTFS_ERASEDSTATE, SMARTFS_FMT_AGING_POS); *((uint16_t *) sectorheader->seq) = 0; sectsize = (CONFIG_MTD_SMART_SECTOR_SIZE >> 9) << 2; #if ( CONFIG_SMARTFS_ERASEDSTATE == 0xFF ) *((uint16_t *) sectorheader->logicalsector) = 0; sectorheader->status = (uint8_t) ~(SMART_STATUS_COMMITTED | SMART_STATUS_VERBITS | SMART_STATUS_SIZEBITS) | SMART_STATUS_VERSION | sectsize; #else *((uint16_t *) sectorheader->logicalsector) = 0xFFFF; sectorheader->status = (uint8_t) (SMART_STATUS_COMMITTED | SMART_STATUS_VERSION | sectsize); #endif /* Now add the format signature to the sector */ dev->rwbuffer[SMART_FMT_POS1] = SMART_FMT_SIG1; dev->rwbuffer[SMART_FMT_POS2] = SMART_FMT_SIG2; dev->rwbuffer[SMART_FMT_POS3] = SMART_FMT_SIG3; dev->rwbuffer[SMART_FMT_POS4] = SMART_FMT_SIG4; dev->rwbuffer[SMART_FMT_VERSION_POS] = SMART_FMT_VERSION; dev->rwbuffer[SMART_FMT_NAMESIZE_POS] = CONFIG_SMARTFS_MAXNAMLEN; /* Record the number of root directory entries we have */ dev->rwbuffer[SMART_FMT_ROOTDIRS_POS] = (uint8_t) arg; /* Write the sector to the flash */ wrcount = MTD_BWRITE(dev->mtd, 0, dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer); if (wrcount != dev->mtdBlksPerSector) { /* The block is not empty!! What to do? */ fdbg("Write block 0 failed: %d.\n", wrcount); /* Unlock the mutex if we add one */ return -EIO; } /* Now initialize our internal control variables */ ret = smart_setsectorsize(dev, CONFIG_MTD_SMART_SECTOR_SIZE); if (ret != OK) { return ret; } dev->formatstatus = SMART_FMT_STAT_UNKNOWN; dev->freesectors = dev->neraseblocks * dev->sectorsPerBlk - 1; for (x = 0; x < dev->neraseblocks; x++) { /* Initialize the released and free counts */ dev->releasecount[x] = 0; dev->freecount[x] = dev->sectorsPerBlk; } /* Account for the format sector */ dev->freecount[0]--; /* Now initialize the logical to physical sector map */ dev->sMap[0] = 0; /* Logical sector zero = physical sector 0 */ totalsectors = dev->neraseblocks * dev->sectorsPerBlk; for (x = 1; x < totalsectors; x++) { /* Mark all other logical sectors as non-existant */ dev->sMap[x] = -1; } #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS /* Un-register any extra directory device entries */ for (x = 2; x < 8; x++) { snprintf(dev->rwbuffer, 18, "/dev/smart%dd%d", dev->minor, x); unregister_blockdriver(dev->rwbuffer); } #endif return OK; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_findfreephyssector * * Description: Finds a free physical sector based on free and released * count logic, taking into account reserved sectors. * ****************************************************************************/ static int smart_findfreephyssector(struct smart_struct_s *dev) { uint16_t allocfreecount; uint16_t allocblock; uint16_t physicalsector; uint16_t x; uint32_t readaddr; struct smart_sect_header_s header; int ret; /* Determine which erase block we should allocate the new * sector from. This is based on the number of free sectors * available in each erase block. */ allocfreecount = 0; allocblock = 0xFFFF; physicalsector = 0xFFFF; for (x = 0; x < dev->neraseblocks; x++) { /* Test if this block has more free blocks than the * currently selected block */ if (dev->freecount[x] > allocfreecount) { /* Assign this block to alloc from */ allocblock = x; allocfreecount = dev->freecount[x]; } } /* Check if we found an allocblock. */ if (allocblock == 0xFFFF) { /* No free sectors found! Bug? */ return -EIO; } /* Now find a free physical sector within this selected * erase block to allocate. */ for (x = allocblock * dev->sectorsPerBlk; x < (allocblock+1) * dev->sectorsPerBlk; x++) { /* Check if this physical sector is available */ readaddr = x * dev->mtdBlksPerSector * dev->geo.blocksize; ret = MTD_READ(dev->mtd, readaddr, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { fvdbg("Error reading phys sector %d\n", physicalsector); return -EIO; } if ((*((uint16_t *) header.logicalsector) == 0xFFFF) && (*((uint16_t *) header.seq) == 0xFFFF) && ((header.status & SMART_STATUS_COMMITTED) == (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED))) { physicalsector = x; break; } } return physicalsector; } /**************************************************************************** * Name: smart_garbagecollect * * Description: Performs garbage collection if needed. This is determined * by the count of released sectors relative to free and * total sectors. * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static int smart_garbagecollect(struct smart_struct_s *dev) { uint16_t releasedsectors; uint16_t collectblock; uint16_t releasemax; uint16_t newsector; bool collect = TRUE; int x; int ret; size_t offset; struct smart_sect_header_s *header; uint8_t newstatus; while (collect) { collect = FALSE; /* Calculate the number of released sectors on the device */ releasedsectors = 0; collectblock = 0xFFFF; releasemax = 0; for (x = 0; x < dev->neraseblocks; x++) { releasedsectors += dev->releasecount[x]; if (dev->releasecount[x] > releasemax) { releasemax = dev->releasecount[x]; collectblock = x; } } /* Test if the released sectors count is greater than the * free sectors. If it is, then we will do garbage collection. */ if (releasedsectors > dev->freesectors) collect = TRUE; /* Test if we have more reached our reserved free sector limit */ if (dev->freesectors <= (dev->sectorsPerBlk << 0) + 4) collect = TRUE; /* Test if we need to garbage collect */ if (collect) { if (collectblock == 0xFFFF) { /* Need to collect, but no sectors with released blocks! */ ret = -ENOSPC; goto errout; } fdbg("Collecting block %d, free=%d released=%d\n", collectblock, dev->freecount[collectblock], dev->releasecount[collectblock]); if (dev->freecount[collectblock] == 6) { fdbg("here!\n"); } /* Perform collection on block with the most released sectors. * First mark the block as having no free sectors so we don't * try to move sectors into the block we are trying to erase. */ dev->freecount[collectblock] = 0; /* Next move all live data in the block to a new home. */ for (x = collectblock * dev->sectorsPerBlk; x < (collectblock + 1) * dev->sectorsPerBlk; x++) { /* Read the next sector from this erase block */ ret = MTD_BREAD(dev->mtd, x * dev->mtdBlksPerSector, dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer); if (ret != dev->mtdBlksPerSector) { fdbg("Error reading sector %d\n", x); ret = -EIO; goto errout; } /* Test if if the block is in use */ header = (struct smart_sect_header_s *) dev->rwbuffer; if (((header->status & SMART_STATUS_COMMITTED) == (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED)) || ((header->status & SMART_STATUS_RELEASED) != (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_RELEASED))) { /* This sector doesn't have live data (free or released). * just continue to the next sector and don't move it. */ continue; } /* Find a new sector where it can live, NOT in this erase block */ newsector = smart_findfreephyssector(dev); if (newsector == 0xFFFF) { /* Unable to find a free sector!!! */ fdbg("Can't find a free sector for relocation\n"); ret = -EIO; goto errout; } /* Increment the sequence number and clear the "commit" flag */ (*((uint16_t *) header->seq))++; if (*((uint16_t *) header->seq) == 0xFFFF) { *((uint16_t *) header->seq) = 1; } #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF header->status |= SMART_STATUS_COMMITTED; #else header->status &= ~SMART_STATUS_COMMITTED; #endif /* Write the data to the new physical sector location */ ret = MTD_BWRITE(dev->mtd, newsector * dev->mtdBlksPerSector, dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer); /* Commit the sector */ offset = newsector * dev->mtdBlksPerSector * dev->geo.blocksize + offsetof(struct smart_sect_header_s, status); #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF newstatus = header->status & ~SMART_STATUS_COMMITTED; #else newstatus = header->status | SMART_STATUS_COMMITTED; #endif ret = smart_bytewrite(dev, offset, 1, &newstatus); if (ret < 0) { fdbg("Error %d committing new sector %d\n" -ret, newsector); goto errout; } /* Release the old physical sector */ #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF newstatus = header->status & ~SMART_STATUS_RELEASED; #else newstatus = header->status | SMART_STATUS_RELEASED; #endif offset = x * dev->mtdBlksPerSector * dev->geo.blocksize + offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &newstatus); if (ret < 0) { fdbg("Error %d releasing old sector %d\n" -ret, x); goto errout; } /* Update the variables */ dev->sMap[*((uint16_t *) header->logicalsector)] = newsector; dev->freecount[newsector / dev->sectorsPerBlk]--; } /* Now erase the erase block */ MTD_ERASE(dev->mtd, collectblock, 1); dev->freesectors += dev->releasecount[collectblock]; dev->freecount[collectblock] = dev->sectorsPerBlk; dev->releasecount[collectblock] = 0; /* If this is block zero, then be sure to write the sector size */ if (collectblock == 0) { /* Set the sector size in the 1st header */ uint8_t sectsize = dev->sectorsize >> 7; #if ( CONFIG_SMARTFS_ERASEDSTATE == 0xFF ) newstatus = (uint8_t) ~SMART_STATUS_SIZEBITS | sectsize; #else newstatus = (uint8_t) sectsize; #endif /* Write the sector size to the device */ offset = offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &newstatus); if (ret < 0) { fdbg("Error %d setting sector 0 size\n", -ret); } } /* Update the block aging information in the format signature sector */ } else { /* Test for aging sectors and push them to a new location * so we wear evenly. */ } } return OK; errout: return ret; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_writesector * * Description: Writes data to the specified logical sector. The sector * should have already been allocated prior to the write. If * the logical sector already has data on the device, it will * be released and a new physical sector will be created and * mapped to the logical sector. * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static inline int smart_writesector(struct smart_struct_s *dev, unsigned long arg) { int ret; uint16_t x; bool needsrelocate = FALSE; uint16_t mtdblock; uint16_t physsector; struct smart_read_write_s *req; struct smart_sect_header_s *header; size_t offset; uint8_t byte; fvdbg("Entry\n"); req = (struct smart_read_write_s *) arg; DEBUGASSERT(req->offset <= dev->sectorsize); DEBUGASSERT(req->offset+req->count <= dev->sectorsize); /* Ensure the logical sector has been allocated */ if (req->logsector >= dev->totalsectors) { fdbg("Logical sector %d too large\n", req->logsector); ret = -EINVAL; goto errout; } physsector = dev->sMap[req->logsector]; if (physsector == 0xFFFF) { fdbg("Logical sector %d not allocated\n", req->logsector); ret = -EINVAL; goto errout; } /* Read the sector data into our buffer */ mtdblock = physsector * dev->mtdBlksPerSector; ret = MTD_BREAD(dev->mtd, mtdblock, dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer); if (ret != dev->mtdBlksPerSector) { fdbg("Error reading phys sector %d\n", physsector); ret = -EIO; goto errout; } /* Test if we need to relocate the sector to perform the write */ for (x = 0; x < req->count; x++) { /* Test if the next byte can be written to the flash */ byte = dev->rwbuffer[sizeof(struct smart_sect_header_s) + req->offset + x]; #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF if (((byte ^ req->buffer[x]) | byte) != byte) { needsrelocate = TRUE; break; } #else if (((byte ^ req->buffer[x]) | req->buffer[x]) != req->buffer[x]) { needsrelocate = TRUE; break; } #endif } if (needsrelocate) { /* Find a new physical sector to save data to */ physsector = smart_findfreephyssector(dev); if (physsector == 0xFFFF) { fdbg("Error relocating sector %d\n", req->logsector); ret = -EIO; goto errout; } /* Update the sequence number to indicate the sector was moved */ header = (struct smart_sect_header_s *) dev->rwbuffer; (*((uint16_t *) header->seq))++; #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF header->status |= SMART_STATUS_COMMITTED; #else header->status &= SMART_STATUS_COMMITTED; #endif } /* Now copy the data to the sector buffer. */ memcpy(&dev->rwbuffer[sizeof(struct smart_sect_header_s) + req->offset], req->buffer, req->count); /* Now write the sector buffer to the device. */ if (needsrelocate) { /* Write the entire sector to the new physical location, uncommitted. */ ret = MTD_BWRITE(dev->mtd, physsector * dev->mtdBlksPerSector, dev->mtdBlksPerSector, (uint8_t *) dev->rwbuffer); if (ret != dev->mtdBlksPerSector) { fdbg("Error writing to physical sector %d\n", physsector); ret = -EIO; goto errout; } /* Commit the new physical sector */ #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF byte = header->status & ~SMART_STATUS_COMMITTED; #else byte = header->status | SMART_STATUS_COMMITTED; #endif offset = physsector * dev->mtdBlksPerSector * dev->geo.blocksize + offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &byte); if (ret != 1) { fvdbg("Error committing physical sector %d\n", physsector); ret = -EIO; goto errout; } /* Release the old physical sector */ #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF byte = header->status & ~SMART_STATUS_RELEASED; #else byte = header->status | SMART_STATUS_RELEASED; #endif offset = mtdblock * dev->geo.blocksize + offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &byte); /* Update releasecount for released sector and freecount for the * newly allocated physical sector. */ dev->releasecount[dev->sMap[req->logsector] / dev->sectorsPerBlk]++; dev->freecount[physsector / dev->sectorsPerBlk]--; dev->freesectors--; /* Update the sector map */ dev->sMap[req->logsector] = physsector; /* Since we performed a relocation, do garbage collection to * ensure we don't fill up our flash with released blocks. */ smart_garbagecollect(dev); } else { /* Not relocated. Just write the portion of the sector that needs * to be written. */ offset = mtdblock * dev->geo.blocksize + sizeof(struct smart_sect_header_s) + req->offset; ret = smart_bytewrite(dev, offset, req->count, req->buffer); } ret = OK; errout: return ret; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_readsector * * Description: Reads data from the specified logical sector. The sector * should have already been allocated prior to the read. * ****************************************************************************/ static inline int smart_readsector(struct smart_struct_s *dev, unsigned long arg) { int ret; uint32_t readaddr; uint16_t physsector; struct smart_read_write_s *req; struct smart_sect_header_s header; fvdbg("Entry\n"); req = (struct smart_read_write_s *) arg; DEBUGASSERT(req->offset < dev->sectorsize); DEBUGASSERT(req->offset+req->count < dev->sectorsize); /* Ensure the logical sector has been allocated */ if (req->logsector >= dev->totalsectors) { fdbg("Logical sector %d too large\n", req->logsector); ret = -EINVAL; goto errout; } physsector = dev->sMap[req->logsector]; if (physsector == 0xFFFF) { fdbg("Logical sector %d not allocated\n", req->logsector); ret = -EINVAL; goto errout; } /* Read the sector header data to validate as a sanity check */ ret = MTD_READ(dev->mtd, physsector * dev->mtdBlksPerSector * dev->geo.blocksize, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { fvdbg("Error reading sector %d header\n", physsector); ret = -EIO; goto errout; } /* Do a sanity check on the header data */ if (((*(uint16_t *) header.logicalsector) != req->logsector) || ((header.status & SMART_STATUS_COMMITTED) == (CONFIG_SMARTFS_ERASEDSTATE & SMART_STATUS_COMMITTED))) { /* Error in sector header! How do we handle this? */ fdbg("Error in logical sector %d header, phys=%d\n", req->logsector, physsector); ret = -EIO; goto errout; } /* Read the sector data into the buffer */ readaddr = (uint32_t) physsector * dev->mtdBlksPerSector * dev->geo.blocksize + req->offset + sizeof(struct smart_sect_header_s);; ret = MTD_READ(dev->mtd, readaddr, req->count, (uint8_t *) req->buffer); if (ret != req->count) { fdbg("Error reading phys sector %d\n", physsector); ret = -EIO; goto errout; } errout: return ret; } /**************************************************************************** * Name: smart_allocsector * * Description: Allocates a new logical sector. If an argument is given, * then it tries to allocate the specified sector number. * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static inline int smart_allocsector(struct smart_struct_s *dev, unsigned long requested) { int x; int ret; uint16_t logsector = 0xFFFF; /* Logical sector number selected */ uint16_t physicalsector; /* The selected physical sector */ uint16_t releasecount; struct smart_sect_header_s *header; uint8_t sectsize; /* Validate that we have enough sectors available to perform an * allocation. We have to ensure we keep enough reserved sectors * on hand to do released sector garbage collection. */ releasecount = 0; for (x = 0; x < dev->neraseblocks; x++) { releasecount += dev->releasecount[x]; } if (dev->freesectors <= (dev->sectorsPerBlk << 0) + 4) { /* We are at our free sector limit. Test if we have * sectors we can release */ if (releasecount == 0) { /* No space left!! */ return -ENOSPC; } } /* Check if a specific sector is being requested and allocate that * sector if it isn't already in use */ if ((requested > 2) && (requested < dev->totalsectors)) { /* Validate the sector is not already allocated */ if (dev->sMap[requested] == (uint16_t) -1) { logsector = requested; } } /* Check if we need to scan for an available logical sector */ if (logsector == 0xFFFF) { /* Loop through all sectors and find one to allocate */ for (x = SMART_FIRST_ALLOC_SECTOR; x < dev->totalsectors; x++) { if (dev->sMap[x] == (uint16_t) -1) { /* Unused logical sector found. Use this one */ logsector = x; break; } } } /* Test for an error allocating a sector */ if (logsector == 0xFFFF) { /* Hmmm. We think we had enough logical sectors, but * something happened and we didn't find any free * logical sectors. What do do? Report an error? * rescan and try again to "self heal" in case of a * bug in our code? */ fdbg("No free logical sector numbers! Free sectors = %d\n", dev->freesectors); return -EIO; } /* Check if we need to do garbage collection. We have to * ensure we keep enough reserved free sectors to per garbage * collection as it involves moving sectors from blocks with * released sectors into blocks with free sectors, then * erasing the vacated block. */ smart_garbagecollect(dev); /* Find a free physical sector */ physicalsector = smart_findfreephyssector(dev); fvdbg("Alloc: log=%d, phys=%d, erase block=%d, free=%d, released=%d\n", logsector, physicalsector, physicalsector / dev->sectorsPerBlk, dev->freesectors, releasecount); /* Create a header to assign the logical sector */ memset(dev->rwbuffer, CONFIG_SMARTFS_ERASEDSTATE, dev->sectorsize); header = (struct smart_sect_header_s *) dev->rwbuffer; *((uint16_t *) header->logicalsector) = logsector; *((uint16_t *) header->seq) = 0; sectsize = dev->sectorsize >> 7; #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF header->status = ~(SMART_STATUS_COMMITTED | SMART_STATUS_SIZEBITS | SMART_STATUS_VERBITS) | SMART_STATUS_VERSION | sectsize; #else header->status = SMART_STATUS_COMMITTED | SMART_STATUS_VERSION | sectsize; #endif /* Write the header to the physical sector location */ x = physicalsector * dev->mtdBlksPerSector; fvdbg("Write MTD block %d\n", x); ret = MTD_BWRITE(dev->mtd, x, 1, (uint8_t *) dev->rwbuffer); if (ret != 1) { /* The block is not empty!! What to do? */ fdbg("Write block %d failed: %d.\n", x, ret); /* Unlock the mutex if we add one */ return -EIO; } /* Map the sector and update the free sector counts */ dev->sMap[logsector] = physicalsector; dev->freecount[physicalsector / dev->sectorsPerBlk]--; dev->freesectors--; /* Return the logical sector number */ return logsector; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_freesector * * Description: Frees a logical sector from the device. Freeing (also * called releasing) is performed by programming the released * bit in the sector header's status byte. * ****************************************************************************/ #ifdef CONFIG_FS_WRITABLE static inline int smart_freesector(struct smart_struct_s *dev, unsigned long logicalsector) { int ret; int readaddr; uint16_t physsector; uint16_t block; struct smart_sect_header_s header; size_t offset; /* Check if the logical sector is within bounds */ if ((logicalsector > 2) && (logicalsector < dev->totalsectors)) { /* Validate the sector is actually allocated */ if (dev->sMap[logicalsector] == (uint16_t) -1) { fdbg("Invalid release - sector %d not allocated\n", logicalsector); ret = -EINVAL; goto errout; } } /* Okay to release the sector. Read the sector header info */ physsector = dev->sMap[logicalsector]; readaddr = physsector * dev->mtdBlksPerSector * dev->geo.blocksize; ret = MTD_READ(dev->mtd, readaddr, sizeof(struct smart_sect_header_s), (uint8_t *) &header); if (ret != sizeof(struct smart_sect_header_s)) { goto errout; } /* Do a sanity check on the logical sector number */ if (*((uint16_t *) header.logicalsector) != (uint16_t) logicalsector) { /* Hmmm... something is wrong. This should always match! Bug in our code? */ fdbg("Sector %d logical sector in header doesn't match\n", logicalsector); ret = -EINVAL; goto errout; } /* Mark the sector as released */ #if CONFIG_SMARTFS_ERASEDSTATE == 0xFF header.status &= ~SMART_STATUS_RELEASED; #else header.status |= SMART_STATUS_RELEASED; #endif /* Write the status back to the device */ offset = readaddr + offsetof(struct smart_sect_header_s, status); ret = smart_bytewrite(dev, offset, 1, &header.status); if (ret != 1) { fdbg("Error updating physicl sector %d status\n", physsector); goto errout; } /* Update the erase block's release count */ block = physsector / dev->sectorsPerBlk; dev->releasecount[block]++; /* Unmap this logical sector */ dev->sMap[logicalsector] = (uint16_t) -1; /* If this block has only released blocks, then erase it */ if (dev->releasecount[block] + dev->freecount[block] == dev->sectorsPerBlk) { /* Erase the block */ MTD_ERASE(dev->mtd, block, 1); dev->freesectors += dev->releasecount[block]; dev->releasecount[block] = 0; dev->freecount[block] = dev->sectorsPerBlk; } ret = OK; errout: return ret; } #endif /* CONFIG_FS_WRITABLE */ /**************************************************************************** * Name: smart_ioctl * * Description: Return device geometry * ****************************************************************************/ static int smart_ioctl(FAR struct inode *inode, int cmd, unsigned long arg) { struct smart_struct_s *dev ; int ret; fvdbg("Entry\n"); DEBUGASSERT(inode && inode->i_private); #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev = ((struct smart_multiroot_device_s*) inode->i_private)->dev; #else dev = (struct smart_struct_s *)inode->i_private; #endif /* Process the ioctl's we care about first, pass any we don't respond * to directly to the underlying MTD device. */ switch (cmd) { case BIOC_XIPBASE: /* The argument accompanying the BIOC_XIPBASE should be non-NULL. If * DEBUG is enabled, we will catch it here instead of in the MTD * driver. */ #ifdef CONFIG_DEBUG if (arg == 0) { fdbg("ERROR: BIOC_XIPBASE argument is NULL\n"); return -EINVAL; } #endif /* Just change the BIOC_XIPBASE command to the MTDIOC_XIPBASE command. */ cmd = MTDIOC_XIPBASE; break; case BIOC_GETFORMAT: /* Return the format information for the device */ #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS ret = smart_getformat(dev, (struct smart_format_s *) arg, ((struct smart_multiroot_device_s*) inode->i_private)->rootdirnum); #else ret = smart_getformat(dev, (struct smart_format_s *) arg); #endif goto ok_out; case BIOC_READSECT: /* Do a logical sector read and return the data */ ret = smart_readsector(dev, arg); goto ok_out; #ifdef CONFIG_FS_WRITABLE case BIOC_LLFORMAT: /* Perform a low-level format on the flash */ ret = smart_llformat(dev, arg); goto ok_out; case BIOC_ALLOCSECT: /* Allocate a logical sector for the upper layer file system */ ret = smart_allocsector(dev, arg); goto ok_out; case BIOC_FREESECT: /* Free the specified logical sector */ ret = smart_freesector(dev, arg); goto ok_out; case BIOC_WRITESECT: /* Write to the sector */ ret = smart_writesector(dev, arg); goto ok_out; #endif /* CONFIG_FS_WRITABLE */ } /* No other block driver ioctl commmands are not recognized by this * driver. Other possible MTD driver ioctl commands are passed through * to the MTD driver (unchanged). */ ret = MTD_IOCTL(dev->mtd, cmd, arg); if (ret < 0) { fdbg("ERROR: MTD ioctl(%04x) failed: %d\n", cmd, ret); } ok_out: return ret; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: smart_initialize * * Description: * Initialize to provide a block driver wrapper around an MTD interface * * Input Parameters: * minor - The minor device number. The MTD block device will be * registered as as /dev/smartN where N is the minor number. * mtd - The MTD device that supports the FLASH interface. * ****************************************************************************/ int smart_initialize(int minor, FAR struct mtd_dev_s *mtd, const char *partname) { struct smart_struct_s *dev; int ret = -ENOMEM; uint32_t totalsectors; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS struct smart_multiroot_device_s *rootdirdev; #endif /* Sanity check */ #ifdef CONFIG_DEBUG if (minor < 0 || minor > 255 || !mtd) { return -EINVAL; } #endif /* Allocate a SMART device structure */ dev = (struct smart_struct_s *)kmalloc(sizeof(struct smart_struct_s)); if (dev) { /* Initialize the SMART device structure */ dev->mtd = mtd; /* Get the device geometry. (casting to uintptr_t first eliminates * complaints on some architectures where the sizeof long is different * from the size of a pointer). */ /* Set these to zero in case the device doesn't support them */ ret = MTD_IOCTL(mtd, MTDIOC_GEOMETRY, (unsigned long)((uintptr_t)&dev->geo)); if (ret < 0) { fdbg("MTD ioctl(MTDIOC_GEOMETRY) failed: %d\n", ret); kfree(dev); goto errout; } /* Set the sector size to the default for now */ dev->sMap = NULL; dev->rwbuffer = NULL; ret = smart_setsectorsize(dev, CONFIG_MTD_SMART_SECTOR_SIZE); if (ret != OK) { kfree(dev); goto errout; } /* Calculate the totalsectors on this device and validate */ totalsectors = dev->neraseblocks * dev->sectorsPerBlk; if (totalsectors > 65534) { fdbg("SMART Sector size too small for device\n"); kfree(dev); ret = -EINVAL; goto errout; } dev->freesectors = (uint16_t) totalsectors; /* Mark the device format status an unknown */ dev->formatstatus = SMART_FMT_STAT_UNKNOWN; dev->namesize = CONFIG_SMARTFS_MAXNAMLEN; dev->partname = partname; #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS dev->minor = minor; #endif /* Create a MTD block device name */ #ifdef CONFIG_SMARTFS_MULTI_ROOT_DIRS if (partname != NULL) snprintf(dev->rwbuffer, 18, "/dev/smart%d%sd1", minor, partname); else snprintf(dev->rwbuffer, 18, "/dev/smart%dd1", minor); /* Inode private data is a reference to a struct containing * the SMART device structure and the root directory number. */ rootdirdev = (struct smart_multiroot_device_s*) kmalloc(sizeof(*rootdirdev)); if (rootdirdev == NULL) { fdbg("register_blockdriver failed: %d\n", -ret); kfree(dev->sMap); kfree(dev->rwbuffer); kfree(dev); ret = -ENOMEM; goto errout; } /* Populate the rootdirdev */ rootdirdev->dev = dev; rootdirdev->rootdirnum = 0; ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, rootdirdev); #else if (partname != NULL) snprintf(dev->rwbuffer, 18, "/dev/smart%d%s", minor, partname); else snprintf(dev->rwbuffer, 18, "/dev/smart%d", minor); /* Inode private data is a reference to the SMART device structure */ ret = register_blockdriver(dev->rwbuffer, &g_bops, 0, dev); #endif if (ret < 0) { fdbg("register_blockdriver failed: %d\n", -ret); kfree(dev->sMap); kfree(dev->rwbuffer); kfree(dev); goto errout; } /* Do a scan of the device */ smart_scan(dev); } errout: return ret; }
309165.c
/* OpenCL runtime library: clCreateBuffer() Copyright (c) 2011-2013 Universidad Rey Juan Carlos Pekka Jääskeläinen / Tampere University of Technology Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "pocl_cl.h" #include "devices.h" #include "common.h" #include "pocl_util.h" CL_API_ENTRY cl_mem CL_API_CALL POname(clCreateBuffer)(cl_context context, cl_mem_flags flags, size_t size, void *host_ptr, cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_0 { cl_mem mem = NULL; cl_device_id device; int errcode; unsigned i, j; POCL_GOTO_ERROR_COND((size == 0), CL_INVALID_BUFFER_SIZE); POCL_GOTO_ERROR_COND((context == NULL), CL_INVALID_CONTEXT); mem = (cl_mem) malloc(sizeof(struct _cl_mem)); if (mem == NULL) { errcode = CL_OUT_OF_HOST_MEMORY; goto ERROR; } mem->device_ptrs = NULL; if (flags == 0) flags = CL_MEM_READ_WRITE; /* validate flags */ POCL_GOTO_ERROR_ON((flags > (1<<10)-1), CL_INVALID_VALUE, "Flags must " "be < 1024 (there are only 10 flags)\n"); POCL_GOTO_ERROR_ON(((flags & CL_MEM_READ_WRITE) && (flags & CL_MEM_WRITE_ONLY || flags & CL_MEM_READ_ONLY)), CL_INVALID_VALUE, "Invalid flags: CL_MEM_READ_WRITE cannot be used " "together with CL_MEM_WRITE_ONLY or CL_MEM_READ_ONLY\n"); POCL_GOTO_ERROR_ON(((flags & CL_MEM_READ_ONLY) && (flags & CL_MEM_WRITE_ONLY)), CL_INVALID_VALUE, "Invalid flags: " "can't have both CL_MEM_WRITE_ONLY and CL_MEM_READ_ONLY\n"); POCL_GOTO_ERROR_ON(((flags & CL_MEM_USE_HOST_PTR) && (flags & CL_MEM_ALLOC_HOST_PTR || flags & CL_MEM_COPY_HOST_PTR)), CL_INVALID_VALUE, "Invalid flags: CL_MEM_USE_HOST_PTR cannot be used " "together with CL_MEM_ALLOC_HOST_PTR or CL_MEM_COPY_HOST_PTR\n"); POCL_GOTO_ERROR_ON(((flags & CL_MEM_HOST_WRITE_ONLY) && (flags & CL_MEM_HOST_READ_ONLY)), CL_INVALID_VALUE, "Invalid flags: " "can't have both CL_MEM_HOST_READ_ONLY and CL_MEM_HOST_WRITE_ONLY\n"); POCL_GOTO_ERROR_ON(((flags & CL_MEM_HOST_NO_ACCESS) && ((flags & CL_MEM_HOST_READ_ONLY) || (flags & CL_MEM_HOST_WRITE_ONLY))), CL_INVALID_VALUE, "Invalid flags: CL_MEM_HOST_NO_ACCESS cannot be used " "together with CL_MEM_HOST_READ_ONLY or CL_MEM_HOST_WRITE_ONLY\n"); if (host_ptr == NULL) { POCL_GOTO_ERROR_ON(((flags & CL_MEM_USE_HOST_PTR) || (flags & CL_MEM_COPY_HOST_PTR)), CL_INVALID_HOST_PTR, "host_ptr is NULL, but flags specify {COPY|USE}_HOST_PTR\n"); } else { POCL_GOTO_ERROR_ON(((~flags & CL_MEM_USE_HOST_PTR) && (~flags & CL_MEM_COPY_HOST_PTR)), CL_INVALID_HOST_PTR, "host_ptr is not NULL, but flags don't specify {COPY|USE}_HOST_PTR\n"); } for (i = 0; i < context->num_devices; ++i) { cl_ulong max_alloc; POname(clGetDeviceInfo) (context->devices[i], CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_alloc, NULL); POCL_GOTO_ERROR_ON((size > max_alloc), CL_INVALID_BUFFER_SIZE, "Size (%lu) is bigger than CL_DEVICE_MAX_MEM_ALLOC_SIZE(%lu) of device %s\n", (unsigned long)size, (unsigned long)max_alloc, context->devices[i]->long_name); } POCL_INIT_OBJECT(mem); mem->parent = NULL; mem->map_count = 0; mem->mappings = NULL; mem->buffer = NULL; mem->destructor_callbacks = NULL; mem->type = CL_MEM_OBJECT_BUFFER; mem->flags = flags; mem->is_image = CL_FALSE; mem->owning_device = NULL; mem->is_pipe = 0; mem->pipe_packet_size = 0; mem->pipe_max_packets = 0; /* Store the per device buffer pointers always to a known location in the buffer (dev_id), even though the context might not contain all the devices. */ mem->device_ptrs = (pocl_mem_identifier*) calloc(pocl_num_devices, sizeof(pocl_mem_identifier)); POCL_GOTO_ERROR_COND((mem->device_ptrs == NULL), CL_OUT_OF_HOST_MEMORY); /* init dev pointer structure to ease inter device pointer sharing in ops->alloc_mem_obj */ for (i = 0; i < context->num_devices; ++i) { int dev_id = context->devices[i]->dev_id; mem->device_ptrs[dev_id].global_mem_id = context->devices[i]->global_mem_id; mem->device_ptrs[i].available = 1; } mem->size = size; mem->origin = 0; mem->context = context; mem->mem_host_ptr = host_ptr; mem->shared_mem_allocation_owner = NULL; /* if there is a "special needs" device (hsa) operating in the host memory let it alloc memory first for shared memory use */ if (context->svm_allocdev) { if (context->svm_allocdev->ops->alloc_mem_obj (context->svm_allocdev, mem, host_ptr) != CL_SUCCESS) { errcode = CL_MEM_OBJECT_ALLOCATION_FAILURE; goto ERROR_CLEAN_MEM_AND_DEVICE; } } for (i = 0; i < context->num_devices; ++i) { /* this is already handled iff available */ if (context->svm_allocdev == context->devices[i]) continue; device = context->devices[i]; assert (device->ops->alloc_mem_obj != NULL); if (device->ops->alloc_mem_obj (device, mem, host_ptr) != CL_SUCCESS) { errcode = CL_MEM_OBJECT_ALLOCATION_FAILURE; goto ERROR_CLEAN_MEM_AND_DEVICE; } } /* Some device driver may already have allocated host accessible memory */ if ((flags & CL_MEM_ALLOC_HOST_PTR) && (mem->mem_host_ptr == NULL)) { assert(mem->shared_mem_allocation_owner == NULL); mem->mem_host_ptr = pocl_aligned_malloc (MAX_EXTENDED_ALIGNMENT, size); if (mem->mem_host_ptr == NULL) { errcode = CL_OUT_OF_HOST_MEMORY; goto ERROR_CLEAN_MEM_AND_DEVICE; } } POCL_RETAIN_OBJECT(context); POCL_MSG_PRINT_MEMORY ( "Created Buffer %p, HOST_PTR: %p, DEVICE_PTR[0]: %p SIZE %zu \n", mem, mem->mem_host_ptr, mem->device_ptrs[0].mem_ptr, size); if (errcode_ret != NULL) *errcode_ret = CL_SUCCESS; return mem; ERROR_CLEAN_MEM_AND_DEVICE: for (j = 0; j < i; ++j) { device = context->devices[j]; device->ops->free(device, mem); } ERROR: if (mem) POCL_MEM_FREE (mem->device_ptrs); POCL_MEM_FREE(mem); if(errcode_ret) { *errcode_ret = errcode; } return NULL; } POsym(clCreateBuffer)
149337.c
/********************************************************************** * Copyright (c) 2013, 2014, 2015 Thomas Daede, Cory Fields * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ // Autotools creates libsecp256k1-config.h, of which ECMULT_GEN_PREC_BITS is needed. // ifndef guard so downstream users can define their own if they do not use autotools. #if !defined(ECMULT_GEN_PREC_BITS) #include "libsecp256k1-config.h" #endif #define USE_BASIC_CONFIG 1 #include "basic-config.h" #include "include/secp256k1.h" #include "util.h" #include "field_impl.h" #include "scalar_impl.h" #include "group_impl.h" #include "ecmult_gen_impl.h" static void default_error_callback_fn(const char* str, void* data) { (void)data; fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); abort(); } static const secp256k1_callback default_error_callback = { default_error_callback_fn, NULL }; int main(int argc, char **argv) { secp256k1_ecmult_gen_context ctx; void *prealloc, *base; int inner; int outer; FILE* fp; (void)argc; (void)argv; fp = fopen("ecmult_static_context.h","w"); if (fp == NULL) { fprintf(stderr, "Could not open src/ecmult_static_context.h for writing!\n"); return -1; } fprintf(fp, "#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); fprintf(fp, "#define _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); fprintf(fp, "#include \"src/group.h\"\n"); fprintf(fp, "#define SC SECP256K1_GE_STORAGE_CONST\n"); fprintf(fp, "#if ECMULT_GEN_PREC_N != %d || ECMULT_GEN_PREC_G != %d\n", ECMULT_GEN_PREC_N, ECMULT_GEN_PREC_G); fprintf(fp, " #error configuration mismatch, invalid ECMULT_GEN_PREC_N, ECMULT_GEN_PREC_G. Try deleting ecmult_static_context.h before the build.\n"); fprintf(fp, "#endif\n"); fprintf(fp, "static const secp256k1_ge_storage secp256k1_ecmult_static_context[ECMULT_GEN_PREC_N][ECMULT_GEN_PREC_G] = {\n"); base = checked_malloc(&default_error_callback, SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE); prealloc = base; secp256k1_ecmult_gen_context_init(&ctx); secp256k1_ecmult_gen_context_build(&ctx, &prealloc); for(outer = 0; outer != ECMULT_GEN_PREC_N; outer++) { fprintf(fp,"{\n"); for(inner = 0; inner != ECMULT_GEN_PREC_G; inner++) { fprintf(fp," SC(%uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu)", SECP256K1_GE_STORAGE_CONST_GET((*ctx.prec)[outer][inner])); if (inner != ECMULT_GEN_PREC_G - 1) { fprintf(fp,",\n"); } else { fprintf(fp,"\n"); } } if (outer != ECMULT_GEN_PREC_N - 1) { fprintf(fp,"},\n"); } else { fprintf(fp,"}\n"); } } fprintf(fp,"};\n"); secp256k1_ecmult_gen_context_clear(&ctx); free(base); fprintf(fp, "#undef SC\n"); fprintf(fp, "#endif\n"); fclose(fp); return 0; }
541897.c
/*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved. * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved. * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * a) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * b) 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. * * c) Neither the name of Cisco Systems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(__FreeBSD__) && !defined(__Userspace__) #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #endif #include <netinet/sctp_os.h> #if defined(__FreeBSD__) && !defined(__Userspace__) #include <sys/proc.h> #endif #include <netinet/sctp_var.h> #include <netinet/sctp_sysctl.h> #include <netinet/sctp_pcb.h> #include <netinet/sctputil.h> #include <netinet/sctp.h> #include <netinet/sctp_header.h> #include <netinet/sctp_asconf.h> #include <netinet/sctp_output.h> #include <netinet/sctp_timer.h> #include <netinet/sctp_bsd_addr.h> #if defined(INET) || defined(INET6) #if !defined(_WIN32) #include <netinet/udp.h> #endif #endif #ifdef INET6 #if defined(__Userspace__) #include "user_ip6_var.h" #else #include <netinet6/ip6_var.h> #endif #endif #if defined(__FreeBSD__) && !defined(__Userspace__) #include <sys/sched.h> #include <sys/smp.h> #include <sys/unistd.h> #endif #if defined(__Userspace__) #include <user_socketvar.h> #include <user_atomic.h> #if !defined(_WIN32) #include <netdb.h> #endif #endif #if !defined(__FreeBSD__) || defined(__Userspace__) struct sctp_base_info system_base_info; #endif /* FIX: we don't handle multiple link local scopes */ /* "scopeless" replacement IN6_ARE_ADDR_EQUAL */ #ifdef INET6 int SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b) { #ifdef SCTP_EMBEDDED_V6_SCOPE #if defined(__APPLE__) && !defined(__Userspace__) struct in6_addr tmp_a, tmp_b; tmp_a = a->sin6_addr; #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) if (in6_embedscope(&tmp_a, a, NULL, NULL) != 0) { #else if (in6_embedscope(&tmp_a, a, NULL, NULL, NULL) != 0) { #endif return (0); } tmp_b = b->sin6_addr; #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) if (in6_embedscope(&tmp_b, b, NULL, NULL) != 0) { #else if (in6_embedscope(&tmp_b, b, NULL, NULL, NULL) != 0) { #endif return (0); } return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b)); #elif defined(SCTP_KAME) struct sockaddr_in6 tmp_a, tmp_b; memcpy(&tmp_a, a, sizeof(struct sockaddr_in6)); if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) { return (0); } memcpy(&tmp_b, b, sizeof(struct sockaddr_in6)); if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) { return (0); } return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr)); #else struct in6_addr tmp_a, tmp_b; tmp_a = a->sin6_addr; if (in6_embedscope(&tmp_a, a) != 0) { return (0); } tmp_b = b->sin6_addr; if (in6_embedscope(&tmp_b, b) != 0) { return (0); } return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b)); #endif #else return (IN6_ARE_ADDR_EQUAL(&(a->sin6_addr), &(b->sin6_addr))); #endif /* SCTP_EMBEDDED_V6_SCOPE */ } #endif void sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb) { /* * We really don't need to lock this, but I will just because it * does not hurt. */ SCTP_INP_INFO_RLOCK(); spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep); spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc); spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr); spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr); spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk); spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq); spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq); spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks); SCTP_INP_INFO_RUNLOCK(); } /*- * Addresses are added to VRF's (Virtual Router's). For BSD we * have only the default VRF 0. We maintain a hash list of * VRF's. Each VRF has its own list of sctp_ifn's. Each of * these has a list of addresses. When we add a new address * to a VRF we lookup the ifn/ifn_index, if the ifn does * not exist we create it and add it to the list of IFN's * within the VRF. Once we have the sctp_ifn, we add the * address to the list. So we look something like: * * hash-vrf-table * vrf-> ifn-> ifn -> ifn * vrf | * ... +--ifa-> ifa -> ifa * vrf * * We keep these separate lists since the SCTP subsystem will * point to these from its source address selection nets structure. * When an address is deleted it does not happen right away on * the SCTP side, it gets scheduled. What we do when a * delete happens is immediately remove the address from * the master list and decrement the refcount. As our * addip iterator works through and frees the src address * selection pointing to the sctp_ifa, eventually the refcount * will reach 0 and we will delete it. Note that it is assumed * that any locking on system level ifn/ifa is done at the * caller of these functions and these routines will only * lock the SCTP structures as they add or delete things. * * Other notes on VRF concepts. * - An endpoint can be in multiple VRF's * - An association lives within a VRF and only one VRF. * - Any incoming packet we can deduce the VRF for by * looking at the mbuf/pak inbound (for BSD its VRF=0 :D) * - Any downward send call or connect call must supply the * VRF via ancillary data or via some sort of set default * VRF socket option call (again for BSD no brainer since * the VRF is always 0). * - An endpoint may add multiple VRF's to it. * - Listening sockets can accept associations in any * of the VRF's they are in but the assoc will end up * in only one VRF (gotten from the packet or connect/send). * */ struct sctp_vrf * sctp_allocate_vrf(int vrf_id) { struct sctp_vrf *vrf = NULL; struct sctp_vrflist *bucket; /* First allocate the VRF structure */ vrf = sctp_find_vrf(vrf_id); if (vrf) { /* Already allocated */ return (vrf); } SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf), SCTP_M_VRF); if (vrf == NULL) { /* No memory */ #ifdef INVARIANTS panic("No memory for VRF:%d", vrf_id); #endif return (NULL); } /* setup the VRF */ memset(vrf, 0, sizeof(struct sctp_vrf)); vrf->vrf_id = vrf_id; LIST_INIT(&vrf->ifnlist); vrf->total_ifa_count = 0; vrf->refcount = 0; /* now also setup table ids */ SCTP_INIT_VRF_TABLEID(vrf); /* Init the HASH of addresses */ vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE, &vrf->vrf_addr_hashmark); if (vrf->vrf_addr_hash == NULL) { /* No memory */ #ifdef INVARIANTS panic("No memory for VRF:%d", vrf_id); #endif SCTP_FREE(vrf, SCTP_M_VRF); return (NULL); } /* Add it to the hash table */ bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))]; LIST_INSERT_HEAD(bucket, vrf, next_vrf); atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1); return (vrf); } struct sctp_ifn * sctp_find_ifn(void *ifn, uint32_t ifn_index) { struct sctp_ifn *sctp_ifnp; struct sctp_ifnlist *hash_ifn_head; /* We assume the lock is held for the addresses * if that's wrong problems could occur :-) */ SCTP_IPI_ADDR_LOCK_ASSERT(); hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))]; LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) { if (sctp_ifnp->ifn_index == ifn_index) { return (sctp_ifnp); } if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) { return (sctp_ifnp); } } return (NULL); } struct sctp_vrf * sctp_find_vrf(uint32_t vrf_id) { struct sctp_vrflist *bucket; struct sctp_vrf *liste; bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))]; LIST_FOREACH(liste, bucket, next_vrf) { if (vrf_id == liste->vrf_id) { return (liste); } } return (NULL); } void sctp_free_vrf(struct sctp_vrf *vrf) { if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) { if (vrf->vrf_addr_hash) { SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark); vrf->vrf_addr_hash = NULL; } /* We zero'd the count */ LIST_REMOVE(vrf, next_vrf); SCTP_FREE(vrf, SCTP_M_VRF); atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1); } } void sctp_free_ifn(struct sctp_ifn *sctp_ifnp) { if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) { /* We zero'd the count */ if (sctp_ifnp->vrf) { sctp_free_vrf(sctp_ifnp->vrf); } SCTP_FREE(sctp_ifnp, SCTP_M_IFN); atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1); } } void sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu) { struct sctp_ifn *sctp_ifnp; sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index); if (sctp_ifnp != NULL) { sctp_ifnp->ifn_mtu = mtu; } } void sctp_free_ifa(struct sctp_ifa *sctp_ifap) { if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) { /* We zero'd the count */ if (sctp_ifap->ifn_p) { sctp_free_ifn(sctp_ifap->ifn_p); } SCTP_FREE(sctp_ifap, SCTP_M_IFA); atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1); } } static void sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock) { struct sctp_ifn *found; found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index); if (found == NULL) { /* Not in the list.. sorry */ return; } if (hold_addr_lock == 0) { SCTP_IPI_ADDR_WLOCK(); } else { SCTP_IPI_ADDR_WLOCK_ASSERT(); } LIST_REMOVE(sctp_ifnp, next_bucket); LIST_REMOVE(sctp_ifnp, next_ifn); if (hold_addr_lock == 0) { SCTP_IPI_ADDR_WUNLOCK(); } /* Take away the reference, and possibly free it */ sctp_free_ifn(sctp_ifnp); } void sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr, const char *if_name, uint32_t ifn_index) { struct sctp_vrf *vrf; struct sctp_ifa *sctp_ifap; SCTP_IPI_ADDR_RLOCK(); vrf = sctp_find_vrf(vrf_id); if (vrf == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id); goto out; } sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED); if (sctp_ifap == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n"); goto out; } if (sctp_ifap->ifn_p == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n"); goto out; } if (if_name) { if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) { SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n", sctp_ifap->ifn_p->ifn_name, if_name); goto out; } } else { if (sctp_ifap->ifn_p->ifn_index != ifn_index) { SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n", sctp_ifap->ifn_p->ifn_index, ifn_index); goto out; } } sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID); sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE; out: SCTP_IPI_ADDR_RUNLOCK(); } void sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr, const char *if_name, uint32_t ifn_index) { struct sctp_vrf *vrf; struct sctp_ifa *sctp_ifap; SCTP_IPI_ADDR_RLOCK(); vrf = sctp_find_vrf(vrf_id); if (vrf == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id); goto out; } sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED); if (sctp_ifap == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n"); goto out; } if (sctp_ifap->ifn_p == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n"); goto out; } if (if_name) { if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) { SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n", sctp_ifap->ifn_p->ifn_name, if_name); goto out; } } else { if (sctp_ifap->ifn_p->ifn_index != ifn_index) { SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n", sctp_ifap->ifn_p->ifn_index, ifn_index); goto out; } } sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE); sctp_ifap->localifa_flags |= SCTP_ADDR_VALID; out: SCTP_IPI_ADDR_RUNLOCK(); } /*- * Add an ifa to an ifn. * Register the interface as necessary. * NOTE: ADDR write lock MUST be held. */ static void sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap) { int ifa_af; LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa); sctp_ifap->ifn_p = sctp_ifnp; atomic_add_int(&sctp_ifap->ifn_p->refcount, 1); /* update address counts */ sctp_ifnp->ifa_count++; ifa_af = sctp_ifap->address.sa.sa_family; switch (ifa_af) { #ifdef INET case AF_INET: sctp_ifnp->num_v4++; break; #endif #ifdef INET6 case AF_INET6: sctp_ifnp->num_v6++; break; #endif default: break; } if (sctp_ifnp->ifa_count == 1) { /* register the new interface */ sctp_ifnp->registered_af = ifa_af; } } /*- * Remove an ifa from its ifn. * If no more addresses exist, remove the ifn too. Otherwise, re-register * the interface based on the remaining address families left. * NOTE: ADDR write lock MUST be held. */ static void sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap) { LIST_REMOVE(sctp_ifap, next_ifa); if (sctp_ifap->ifn_p) { /* update address counts */ sctp_ifap->ifn_p->ifa_count--; switch (sctp_ifap->address.sa.sa_family) { #ifdef INET case AF_INET: sctp_ifap->ifn_p->num_v4--; break; #endif #ifdef INET6 case AF_INET6: sctp_ifap->ifn_p->num_v6--; break; #endif default: break; } if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) { /* remove the ifn, possibly freeing it */ sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED); } else { /* re-register address family type, if needed */ if ((sctp_ifap->ifn_p->num_v6 == 0) && (sctp_ifap->ifn_p->registered_af == AF_INET6)) { sctp_ifap->ifn_p->registered_af = AF_INET; } else if ((sctp_ifap->ifn_p->num_v4 == 0) && (sctp_ifap->ifn_p->registered_af == AF_INET)) { sctp_ifap->ifn_p->registered_af = AF_INET6; } /* free the ifn refcount */ sctp_free_ifn(sctp_ifap->ifn_p); } sctp_ifap->ifn_p = NULL; } } struct sctp_ifa * sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index, uint32_t ifn_type, const char *if_name, void *ifa, struct sockaddr *addr, uint32_t ifa_flags, int dynamic_add) { struct sctp_vrf *vrf; struct sctp_ifn *sctp_ifnp, *new_sctp_ifnp; struct sctp_ifa *sctp_ifap, *new_sctp_ifap; struct sctp_ifalist *hash_addr_head; struct sctp_ifnlist *hash_ifn_head; uint32_t hash_of_addr; int new_ifn_af = 0; #ifdef SCTP_DEBUG SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id); SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr); #endif SCTP_MALLOC(new_sctp_ifnp, struct sctp_ifn *, sizeof(struct sctp_ifn), SCTP_M_IFN); if (new_sctp_ifnp == NULL) { #ifdef INVARIANTS panic("No memory for IFN"); #endif return (NULL); } SCTP_MALLOC(new_sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA); if (new_sctp_ifap == NULL) { #ifdef INVARIANTS panic("No memory for IFA"); #endif SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN); return (NULL); } SCTP_IPI_ADDR_WLOCK(); sctp_ifnp = sctp_find_ifn(ifn, ifn_index); if (sctp_ifnp) { vrf = sctp_ifnp->vrf; } else { vrf = sctp_find_vrf(vrf_id); if (vrf == NULL) { vrf = sctp_allocate_vrf(vrf_id); if (vrf == NULL) { SCTP_IPI_ADDR_WUNLOCK(); SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN); SCTP_FREE(new_sctp_ifap, SCTP_M_IFA); return (NULL); } } } if (sctp_ifnp == NULL) { /* build one and add it, can't hold lock * until after malloc done though. */ sctp_ifnp = new_sctp_ifnp; new_sctp_ifnp = NULL; memset(sctp_ifnp, 0, sizeof(struct sctp_ifn)); sctp_ifnp->ifn_index = ifn_index; sctp_ifnp->ifn_p = ifn; sctp_ifnp->ifn_type = ifn_type; sctp_ifnp->refcount = 0; sctp_ifnp->vrf = vrf; atomic_add_int(&vrf->refcount, 1); sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index, addr->sa_family); if (if_name != NULL) { SCTP_SNPRINTF(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name); } else { SCTP_SNPRINTF(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown"); } hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))]; LIST_INIT(&sctp_ifnp->ifalist); LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket); LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn); atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1); new_ifn_af = 1; } sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED); if (sctp_ifap) { /* Hmm, it already exists? */ if ((sctp_ifap->ifn_p) && (sctp_ifap->ifn_p->ifn_index == ifn_index)) { SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n", sctp_ifap->ifn_p->ifn_name, ifn_index, (void *)sctp_ifap); if (new_ifn_af) { /* Remove the created one that we don't want */ sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED); } if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) { /* easy to solve, just switch back to active */ SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n"); sctp_ifap->localifa_flags = SCTP_ADDR_VALID; sctp_ifap->ifn_p = sctp_ifnp; atomic_add_int(&sctp_ifap->ifn_p->refcount, 1); } exit_stage_left: SCTP_IPI_ADDR_WUNLOCK(); if (new_sctp_ifnp != NULL) { SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN); } SCTP_FREE(new_sctp_ifap, SCTP_M_IFA); return (sctp_ifap); } else { if (sctp_ifap->ifn_p) { /* * The last IFN gets the address, remove the * old one */ SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n", (void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name, sctp_ifap->ifn_p->ifn_index, if_name, ifn_index); /* remove the address from the old ifn */ sctp_remove_ifa_from_ifn(sctp_ifap); /* move the address over to the new ifn */ sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap); goto exit_stage_left; } else { /* repair ifnp which was NULL ? */ sctp_ifap->localifa_flags = SCTP_ADDR_VALID; SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n", (void *)sctp_ifnp, (void *)sctp_ifap); sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap); } goto exit_stage_left; } } sctp_ifap = new_sctp_ifap; memset(sctp_ifap, 0, sizeof(struct sctp_ifa)); sctp_ifap->ifn_p = sctp_ifnp; atomic_add_int(&sctp_ifnp->refcount, 1); sctp_ifap->vrf_id = vrf_id; sctp_ifap->ifa = ifa; #ifdef HAVE_SA_LEN memcpy(&sctp_ifap->address, addr, addr->sa_len); #else switch (addr->sa_family) { #ifdef INET case AF_INET: memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in)); break; #endif #ifdef INET6 case AF_INET6: memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in6)); break; #endif #if defined(__Userspace__) case AF_CONN: memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_conn)); break; #endif default: /* TSNH */ break; } #endif sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE; sctp_ifap->flags = ifa_flags; /* Set scope */ switch (sctp_ifap->address.sa.sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin; sin = &sctp_ifap->address.sin; if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) || (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) { sctp_ifap->src_is_loop = 1; } if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) { sctp_ifap->src_is_priv = 1; } sctp_ifnp->num_v4++; if (new_ifn_af) new_ifn_af = AF_INET; break; } #endif #ifdef INET6 case AF_INET6: { /* ok to use deprecated addresses? */ struct sockaddr_in6 *sin6; sin6 = &sctp_ifap->address.sin6; if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) || (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) { sctp_ifap->src_is_loop = 1; } if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) { sctp_ifap->src_is_priv = 1; } sctp_ifnp->num_v6++; if (new_ifn_af) new_ifn_af = AF_INET6; break; } #endif #if defined(__Userspace__) case AF_CONN: if (new_ifn_af) new_ifn_af = AF_CONN; break; #endif default: new_ifn_af = 0; break; } hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa); if ((sctp_ifap->src_is_priv == 0) && (sctp_ifap->src_is_loop == 0)) { sctp_ifap->src_is_glob = 1; } hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)]; LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket); sctp_ifap->refcount = 1; LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa); sctp_ifnp->ifa_count++; vrf->total_ifa_count++; atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1); if (new_ifn_af) { sctp_ifnp->registered_af = new_ifn_af; } SCTP_IPI_ADDR_WUNLOCK(); if (new_sctp_ifnp != NULL) { SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN); } if (dynamic_add) { /* Bump up the refcount so that when the timer * completes it will drop back down. */ struct sctp_laddr *wi; atomic_add_int(&sctp_ifap->refcount, 1); wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr); if (wi == NULL) { /* * Gak, what can we do? We have lost an address * change can you say HOSED? */ SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n"); /* Opps, must decrement the count */ sctp_del_addr_from_vrf(vrf_id, addr, ifn_index, if_name); return (NULL); } SCTP_INCR_LADDR_COUNT(); memset(wi, 0, sizeof(*wi)); (void)SCTP_GETTIME_TIMEVAL(&wi->start_time); wi->ifa = sctp_ifap; wi->action = SCTP_ADD_IP_ADDRESS; SCTP_WQ_ADDR_LOCK(); LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr); sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ, (struct sctp_inpcb *)NULL, (struct sctp_tcb *)NULL, (struct sctp_nets *)NULL); SCTP_WQ_ADDR_UNLOCK(); } else { /* it's ready for use */ sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE; } return (sctp_ifap); } void sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr, uint32_t ifn_index, const char *if_name) { struct sctp_vrf *vrf; struct sctp_ifa *sctp_ifap = NULL; SCTP_IPI_ADDR_WLOCK(); vrf = sctp_find_vrf(vrf_id); if (vrf == NULL) { SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id); goto out_now; } #ifdef SCTP_DEBUG SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id); SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr); #endif sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED); if (sctp_ifap) { /* Validate the delete */ if (sctp_ifap->ifn_p) { int valid = 0; /*- * The name has priority over the ifn_index * if its given. */ if (if_name) { if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) { /* They match its a correct delete */ valid = 1; } } if (!valid) { /* last ditch check ifn_index */ if (ifn_index == sctp_ifap->ifn_p->ifn_index) { valid = 1; } } if (!valid) { SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n", ifn_index, ((if_name == NULL) ? "NULL" : if_name)); SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n", sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name); SCTP_IPI_ADDR_WUNLOCK(); return; } } SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap); sctp_ifap->localifa_flags &= SCTP_ADDR_VALID; /* * We don't set the flag. This means that the structure will * hang around in EP's that have bound specific to it until * they close. This gives us TCP like behavior if someone * removes an address (or for that matter adds it right back). */ /* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */ vrf->total_ifa_count--; LIST_REMOVE(sctp_ifap, next_bucket); sctp_remove_ifa_from_ifn(sctp_ifap); } #ifdef SCTP_DEBUG else { SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:", ifn_index); SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr); } #endif out_now: SCTP_IPI_ADDR_WUNLOCK(); if (sctp_ifap) { struct sctp_laddr *wi; wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr); if (wi == NULL) { /* * Gak, what can we do? We have lost an address * change can you say HOSED? */ SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n"); /* Oops, must decrement the count */ sctp_free_ifa(sctp_ifap); return; } SCTP_INCR_LADDR_COUNT(); memset(wi, 0, sizeof(*wi)); (void)SCTP_GETTIME_TIMEVAL(&wi->start_time); wi->ifa = sctp_ifap; wi->action = SCTP_DEL_IP_ADDRESS; SCTP_WQ_ADDR_LOCK(); /* * Should this really be a tailq? As it is we will process the * newest first :-0 */ LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr); sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ, (struct sctp_inpcb *)NULL, (struct sctp_tcb *)NULL, (struct sctp_nets *)NULL); SCTP_WQ_ADDR_UNLOCK(); } return; } static int sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to) { int loopback_scope; #if defined(INET) int ipv4_local_scope, ipv4_addr_legal; #endif #if defined(INET6) int local_scope, site_scope, ipv6_addr_legal; #endif #if defined(__Userspace__) int conn_addr_legal; #endif struct sctp_vrf *vrf; struct sctp_ifn *sctp_ifn; struct sctp_ifa *sctp_ifa; loopback_scope = stcb->asoc.scope.loopback_scope; #if defined(INET) ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope; ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal; #endif #if defined(INET6) local_scope = stcb->asoc.scope.local_scope; site_scope = stcb->asoc.scope.site_scope; ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal; #endif #if defined(__Userspace__) conn_addr_legal = stcb->asoc.scope.conn_addr_legal; #endif SCTP_IPI_ADDR_RLOCK(); vrf = sctp_find_vrf(stcb->asoc.vrf_id); if (vrf == NULL) { /* no vrf, no addresses */ SCTP_IPI_ADDR_RUNLOCK(); return (0); } if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) { LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) { if ((loopback_scope == 0) && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) { continue; } LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) { if (sctp_is_addr_restricted(stcb, sctp_ifa) && (!sctp_is_addr_pending(stcb, sctp_ifa))) { /* We allow pending addresses, where we * have sent an asconf-add to be considered * valid. */ continue; } if (sctp_ifa->address.sa.sa_family != to->sa_family) { continue; } switch (sctp_ifa->address.sa.sa_family) { #ifdef INET case AF_INET: if (ipv4_addr_legal) { struct sockaddr_in *sin, *rsin; sin = &sctp_ifa->address.sin; rsin = (struct sockaddr_in *)to; if ((ipv4_local_scope == 0) && IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) { continue; } #if defined(__FreeBSD__) && !defined(__Userspace__) if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred, &sin->sin_addr) != 0) { continue; } #endif if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } } break; #endif #ifdef INET6 case AF_INET6: if (ipv6_addr_legal) { struct sockaddr_in6 *sin6, *rsin6; #if defined(SCTP_EMBEDDED_V6_SCOPE) && !defined(SCTP_KAME) struct sockaddr_in6 lsa6; #endif sin6 = &sctp_ifa->address.sin6; rsin6 = (struct sockaddr_in6 *)to; #if defined(__FreeBSD__) && !defined(__Userspace__) if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred, &sin6->sin6_addr) != 0) { continue; } #endif if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) { if (local_scope == 0) continue; #if defined(SCTP_EMBEDDED_V6_SCOPE) if (sin6->sin6_scope_id == 0) { #ifdef SCTP_KAME if (sa6_recoverscope(sin6) != 0) continue; #else lsa6 = *sin6; if (in6_recoverscope(&lsa6, &lsa6.sin6_addr, NULL)) continue; sin6 = &lsa6; #endif /* SCTP_KAME */ } #endif /* SCTP_EMBEDDED_V6_SCOPE */ } if ((site_scope == 0) && (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) { continue; } if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } } break; #endif #if defined(__Userspace__) case AF_CONN: if (conn_addr_legal) { struct sockaddr_conn *sconn, *rsconn; sconn = &sctp_ifa->address.sconn; rsconn = (struct sockaddr_conn *)to; if (sconn->sconn_addr == rsconn->sconn_addr) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } } break; #endif default: /* TSNH */ break; } } } } else { struct sctp_laddr *laddr; LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) { SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n"); continue; } if (sctp_is_addr_restricted(stcb, laddr->ifa) && (!sctp_is_addr_pending(stcb, laddr->ifa))) { /* We allow pending addresses, where we * have sent an asconf-add to be considered * valid. */ continue; } if (laddr->ifa->address.sa.sa_family != to->sa_family) { continue; } switch (to->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin, *rsin; sin = &laddr->ifa->address.sin; rsin = (struct sockaddr_in *)to; if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6, *rsin6; sin6 = &laddr->ifa->address.sin6; rsin6 = (struct sockaddr_in6 *)to; if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn, *rsconn; sconn = &laddr->ifa->address.sconn; rsconn = (struct sockaddr_conn *)to; if (sconn->sconn_addr == rsconn->sconn_addr) { SCTP_IPI_ADDR_RUNLOCK(); return (1); } break; } #endif default: /* TSNH */ break; } } } SCTP_IPI_ADDR_RUNLOCK(); return (0); } static struct sctp_tcb * sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from, struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id) { /**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */ /* * If we support the TCP model, then we must now dig through to see * if we can find our endpoint in the list of tcp ep's. */ uint16_t lport, rport; struct sctppcbhead *ephead; struct sctp_inpcb *inp; struct sctp_laddr *laddr; struct sctp_tcb *stcb; struct sctp_nets *net; #ifdef SCTP_MVRF int fnd, i; #endif if ((to == NULL) || (from == NULL)) { return (NULL); } switch (to->sa_family) { #ifdef INET case AF_INET: if (from->sa_family == AF_INET) { lport = ((struct sockaddr_in *)to)->sin_port; rport = ((struct sockaddr_in *)from)->sin_port; } else { return (NULL); } break; #endif #ifdef INET6 case AF_INET6: if (from->sa_family == AF_INET6) { lport = ((struct sockaddr_in6 *)to)->sin6_port; rport = ((struct sockaddr_in6 *)from)->sin6_port; } else { return (NULL); } break; #endif #if defined(__Userspace__) case AF_CONN: if (from->sa_family == AF_CONN) { lport = ((struct sockaddr_conn *)to)->sconn_port; rport = ((struct sockaddr_conn *)from)->sconn_port; } else { return (NULL); } break; #endif default: return (NULL); } ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))]; /* * Ok now for each of the guys in this bucket we must look and see: * - Does the remote port match. - Does there single association's * addresses match this address (to). If so we update p_ep to point * to this ep and return the tcb from it. */ LIST_FOREACH(inp, ephead, sctp_hash) { SCTP_INP_RLOCK(inp); if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { SCTP_INP_RUNLOCK(inp); continue; } if (lport != inp->sctp_lport) { SCTP_INP_RUNLOCK(inp); continue; } #if defined(__FreeBSD__) && !defined(__Userspace__) switch (to->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin; sin = (struct sockaddr_in *)to; if (prison_check_ip4(inp->ip_inp.inp.inp_cred, &sin->sin_addr) != 0) { SCTP_INP_RUNLOCK(inp); continue; } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)to; if (prison_check_ip6(inp->ip_inp.inp.inp_cred, &sin6->sin6_addr) != 0) { SCTP_INP_RUNLOCK(inp); continue; } break; } #endif default: SCTP_INP_RUNLOCK(inp); continue; } #endif #ifdef SCTP_MVRF fnd = 0; for (i = 0; i < inp->num_vrfs; i++) { if (inp->m_vrf_ids[i] == vrf_id) { fnd = 1; break; } } if (fnd == 0) { SCTP_INP_RUNLOCK(inp); continue; } #else if (inp->def_vrf_id != vrf_id) { SCTP_INP_RUNLOCK(inp); continue; } #endif /* check to see if the ep has one of the addresses */ if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) { /* We are NOT bound all, so look further */ int match = 0; LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa == NULL) { SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__); continue; } if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) { SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n"); continue; } if (laddr->ifa->address.sa.sa_family == to->sa_family) { /* see if it matches */ #ifdef INET if (from->sa_family == AF_INET) { struct sockaddr_in *intf_addr, *sin; intf_addr = &laddr->ifa->address.sin; sin = (struct sockaddr_in *)to; if (sin->sin_addr.s_addr == intf_addr->sin_addr.s_addr) { match = 1; break; } } #endif #ifdef INET6 if (from->sa_family == AF_INET6) { struct sockaddr_in6 *intf_addr6; struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *) to; intf_addr6 = &laddr->ifa->address.sin6; if (SCTP6_ARE_ADDR_EQUAL(sin6, intf_addr6)) { match = 1; break; } } #endif #if defined(__Userspace__) if (from->sa_family == AF_CONN) { struct sockaddr_conn *intf_addr, *sconn; intf_addr = &laddr->ifa->address.sconn; sconn = (struct sockaddr_conn *)to; if (sconn->sconn_addr == intf_addr->sconn_addr) { match = 1; break; } } #endif } } if (match == 0) { /* This endpoint does not have this address */ SCTP_INP_RUNLOCK(inp); continue; } } /* * Ok if we hit here the ep has the address, does it hold * the tcb? */ /* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */ stcb = LIST_FIRST(&inp->sctp_asoc_list); if (stcb == NULL) { SCTP_INP_RUNLOCK(inp); continue; } SCTP_TCB_LOCK(stcb); if (!sctp_does_stcb_own_this_addr(stcb, to)) { SCTP_TCB_UNLOCK(stcb); SCTP_INP_RUNLOCK(inp); continue; } if (stcb->rport != rport) { /* remote port does not match. */ SCTP_TCB_UNLOCK(stcb); SCTP_INP_RUNLOCK(inp); continue; } if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { SCTP_TCB_UNLOCK(stcb); SCTP_INP_RUNLOCK(inp); continue; } if (!sctp_does_stcb_own_this_addr(stcb, to)) { SCTP_TCB_UNLOCK(stcb); SCTP_INP_RUNLOCK(inp); continue; } /* Does this TCB have a matching address? */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { if (net->ro._l_addr.sa.sa_family != from->sa_family) { /* not the same family, can't be a match */ continue; } switch (from->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin, *rsin; sin = (struct sockaddr_in *)&net->ro._l_addr; rsin = (struct sockaddr_in *)from; if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) { /* found it */ if (netp != NULL) { *netp = net; } /* Update the endpoint pointer */ *inp_p = inp; SCTP_INP_RUNLOCK(inp); return (stcb); } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6, *rsin6; sin6 = (struct sockaddr_in6 *)&net->ro._l_addr; rsin6 = (struct sockaddr_in6 *)from; if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) { /* found it */ if (netp != NULL) { *netp = net; } /* Update the endpoint pointer */ *inp_p = inp; SCTP_INP_RUNLOCK(inp); return (stcb); } break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn, *rsconn; sconn = (struct sockaddr_conn *)&net->ro._l_addr; rsconn = (struct sockaddr_conn *)from; if (sconn->sconn_addr == rsconn->sconn_addr) { /* found it */ if (netp != NULL) { *netp = net; } /* Update the endpoint pointer */ *inp_p = inp; SCTP_INP_RUNLOCK(inp); return (stcb); } break; } #endif default: /* TSNH */ break; } } SCTP_TCB_UNLOCK(stcb); SCTP_INP_RUNLOCK(inp); } return (NULL); } /* * rules for use * * 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an * stcb, both will be locked (locked_tcb and stcb) but decrement will be done * (if locked == NULL). 3) Decrement happens on return ONLY if locked == * NULL. */ struct sctp_tcb * sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote, struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb) { struct sctpasochead *head; struct sctp_inpcb *inp; struct sctp_tcb *stcb = NULL; struct sctp_nets *net; uint16_t rport; inp = *inp_p; switch (remote->sa_family) { #ifdef INET case AF_INET: rport = (((struct sockaddr_in *)remote)->sin_port); break; #endif #ifdef INET6 case AF_INET6: rport = (((struct sockaddr_in6 *)remote)->sin6_port); break; #endif #if defined(__Userspace__) case AF_CONN: rport = (((struct sockaddr_conn *)remote)->sconn_port); break; #endif default: return (NULL); } if (locked_tcb) { /* * UN-lock so we can do proper locking here this occurs when * called from load_addresses_from_init. */ atomic_add_int(&locked_tcb->asoc.refcnt, 1); SCTP_TCB_UNLOCK(locked_tcb); } SCTP_INP_INFO_RLOCK(); if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) || (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) { /*- * Now either this guy is our listener or it's the * connector. If it is the one that issued the connect, then * it's only chance is to be the first TCB in the list. If * it is the acceptor, then do the special_lookup to hash * and find the real inp. */ if ((inp->sctp_socket) && SCTP_IS_LISTENING(inp)) { /* to is peer addr, from is my addr */ #ifndef SCTP_MVRF stcb = sctp_tcb_special_locate(inp_p, remote, local, netp, inp->def_vrf_id); if ((stcb != NULL) && (locked_tcb == NULL)) { /* we have a locked tcb, lower refcount */ SCTP_INP_DECR_REF(inp); } if ((locked_tcb != NULL) && (locked_tcb != stcb)) { SCTP_INP_RLOCK(locked_tcb->sctp_ep); SCTP_TCB_LOCK(locked_tcb); atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); SCTP_INP_RUNLOCK(locked_tcb->sctp_ep); } #else /*- * MVRF is tricky, we must look in every VRF * the endpoint has. */ int i; for (i = 0; i < inp->num_vrfs; i++) { stcb = sctp_tcb_special_locate(inp_p, remote, local, netp, inp->m_vrf_ids[i]); if ((stcb != NULL) && (locked_tcb == NULL)) { /* we have a locked tcb, lower refcount */ SCTP_INP_DECR_REF(inp); break; } if ((locked_tcb != NULL) && (locked_tcb != stcb)) { SCTP_INP_RLOCK(locked_tcb->sctp_ep); SCTP_TCB_LOCK(locked_tcb); atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); SCTP_INP_RUNLOCK(locked_tcb->sctp_ep); break; } } #endif SCTP_INP_INFO_RUNLOCK(); return (stcb); } else { SCTP_INP_WLOCK(inp); if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { goto null_return; } stcb = LIST_FIRST(&inp->sctp_asoc_list); if (stcb == NULL) { goto null_return; } SCTP_TCB_LOCK(stcb); if (stcb->rport != rport) { /* remote port does not match. */ SCTP_TCB_UNLOCK(stcb); goto null_return; } if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { SCTP_TCB_UNLOCK(stcb); goto null_return; } if (local && !sctp_does_stcb_own_this_addr(stcb, local)) { SCTP_TCB_UNLOCK(stcb); goto null_return; } /* now look at the list of remote addresses */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { #ifdef INVARIANTS if (net == (TAILQ_NEXT(net, sctp_next))) { panic("Corrupt net list"); } #endif if (net->ro._l_addr.sa.sa_family != remote->sa_family) { /* not the same family */ continue; } switch (remote->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin, *rsin; sin = (struct sockaddr_in *) &net->ro._l_addr; rsin = (struct sockaddr_in *)remote; if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6, *rsin6; sin6 = (struct sockaddr_in6 *)&net->ro._l_addr; rsin6 = (struct sockaddr_in6 *)remote; if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn, *rsconn; sconn = (struct sockaddr_conn *)&net->ro._l_addr; rsconn = (struct sockaddr_conn *)remote; if (sconn->sconn_addr == rsconn->sconn_addr) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif default: /* TSNH */ break; } } SCTP_TCB_UNLOCK(stcb); } } else { SCTP_INP_WLOCK(inp); if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { goto null_return; } head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport, inp->sctp_hashmark)]; LIST_FOREACH(stcb, head, sctp_tcbhash) { if (stcb->rport != rport) { /* remote port does not match */ continue; } SCTP_TCB_LOCK(stcb); if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { SCTP_TCB_UNLOCK(stcb); continue; } if (local && !sctp_does_stcb_own_this_addr(stcb, local)) { SCTP_TCB_UNLOCK(stcb); continue; } /* now look at the list of remote addresses */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { #ifdef INVARIANTS if (net == (TAILQ_NEXT(net, sctp_next))) { panic("Corrupt net list"); } #endif if (net->ro._l_addr.sa.sa_family != remote->sa_family) { /* not the same family */ continue; } switch (remote->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin, *rsin; sin = (struct sockaddr_in *) &net->ro._l_addr; rsin = (struct sockaddr_in *)remote; if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6, *rsin6; sin6 = (struct sockaddr_in6 *) &net->ro._l_addr; rsin6 = (struct sockaddr_in6 *)remote; if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn, *rsconn; sconn = (struct sockaddr_conn *)&net->ro._l_addr; rsconn = (struct sockaddr_conn *)remote; if (sconn->sconn_addr == rsconn->sconn_addr) { /* found it */ if (netp != NULL) { *netp = net; } if (locked_tcb == NULL) { SCTP_INP_DECR_REF(inp); } else if (locked_tcb != stcb) { SCTP_TCB_LOCK(locked_tcb); } if (locked_tcb) { atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); return (stcb); } break; } #endif default: /* TSNH */ break; } } SCTP_TCB_UNLOCK(stcb); } } null_return: /* clean up for returning null */ if (locked_tcb) { SCTP_TCB_LOCK(locked_tcb); atomic_subtract_int(&locked_tcb->asoc.refcnt, 1); } SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_RUNLOCK(); /* not found */ return (NULL); } /* * Find an association for a specific endpoint using the association id given * out in the COMM_UP notification */ struct sctp_tcb * sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock) { /* * Use my the assoc_id to find a endpoint */ struct sctpasochead *head; struct sctp_tcb *stcb; uint32_t id; if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { SCTP_PRINTF("TSNH ep_associd0\n"); return (NULL); } id = (uint32_t)asoc_id; head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)]; if (head == NULL) { /* invalid id TSNH */ SCTP_PRINTF("TSNH ep_associd1\n"); return (NULL); } LIST_FOREACH(stcb, head, sctp_tcbasocidhash) { if (stcb->asoc.assoc_id == id) { if (inp != stcb->sctp_ep) { /* * some other guy has the same id active (id * collision ??). */ SCTP_PRINTF("TSNH ep_associd2\n"); continue; } if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { continue; } if (want_lock) { SCTP_TCB_LOCK(stcb); } return (stcb); } } return (NULL); } struct sctp_tcb * sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock) { struct sctp_tcb *stcb; SCTP_INP_RLOCK(inp); stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock); SCTP_INP_RUNLOCK(inp); return (stcb); } /* * Endpoint probe expects that the INP_INFO is locked. */ static struct sctp_inpcb * sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head, uint16_t lport, uint32_t vrf_id) { struct sctp_inpcb *inp; struct sctp_laddr *laddr; #ifdef INET struct sockaddr_in *sin; #endif #ifdef INET6 struct sockaddr_in6 *sin6; struct sockaddr_in6 *intf_addr6; #endif #if defined(__Userspace__) struct sockaddr_conn *sconn; #endif #ifdef SCTP_MVRF int i; #endif int fnd; #ifdef INET sin = NULL; #endif #ifdef INET6 sin6 = NULL; #endif #if defined(__Userspace__) sconn = NULL; #endif switch (nam->sa_family) { #ifdef INET case AF_INET: sin = (struct sockaddr_in *)nam; break; #endif #ifdef INET6 case AF_INET6: sin6 = (struct sockaddr_in6 *)nam; break; #endif #if defined(__Userspace__) case AF_CONN: sconn = (struct sockaddr_conn *)nam; break; #endif default: /* unsupported family */ return (NULL); } if (head == NULL) return (NULL); LIST_FOREACH(inp, head, sctp_hash) { SCTP_INP_RLOCK(inp); if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { SCTP_INP_RUNLOCK(inp); continue; } if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) && (inp->sctp_lport == lport)) { /* got it */ switch (nam->sa_family) { #ifdef INET case AF_INET: if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) && SCTP_IPV6_V6ONLY(inp)) { /* IPv4 on a IPv6 socket with ONLY IPv6 set */ SCTP_INP_RUNLOCK(inp); continue; } #if defined(__FreeBSD__) && !defined(__Userspace__) if (prison_check_ip4(inp->ip_inp.inp.inp_cred, &sin->sin_addr) != 0) { SCTP_INP_RUNLOCK(inp); continue; } #endif break; #endif #ifdef INET6 case AF_INET6: /* A V6 address and the endpoint is NOT bound V6 */ if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) { SCTP_INP_RUNLOCK(inp); continue; } #if defined(__FreeBSD__) && !defined(__Userspace__) if (prison_check_ip6(inp->ip_inp.inp.inp_cred, &sin6->sin6_addr) != 0) { SCTP_INP_RUNLOCK(inp); continue; } #endif break; #endif default: break; } /* does a VRF id match? */ fnd = 0; #ifdef SCTP_MVRF for (i = 0; i < inp->num_vrfs; i++) { if (inp->m_vrf_ids[i] == vrf_id) { fnd = 1; break; } } #else if (inp->def_vrf_id == vrf_id) fnd = 1; #endif SCTP_INP_RUNLOCK(inp); if (!fnd) continue; return (inp); } SCTP_INP_RUNLOCK(inp); } switch (nam->sa_family) { #ifdef INET case AF_INET: if (sin->sin_addr.s_addr == INADDR_ANY) { /* Can't hunt for one that has no address specified */ return (NULL); } break; #endif #ifdef INET6 case AF_INET6: if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) { /* Can't hunt for one that has no address specified */ return (NULL); } break; #endif #if defined(__Userspace__) case AF_CONN: if (sconn->sconn_addr == NULL) { return (NULL); } break; #endif default: break; } /* * ok, not bound to all so see if we can find a EP bound to this * address. */ LIST_FOREACH(inp, head, sctp_hash) { SCTP_INP_RLOCK(inp); if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { SCTP_INP_RUNLOCK(inp); continue; } if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) { SCTP_INP_RUNLOCK(inp); continue; } /* * Ok this could be a likely candidate, look at all of its * addresses */ if (inp->sctp_lport != lport) { SCTP_INP_RUNLOCK(inp); continue; } /* does a VRF id match? */ fnd = 0; #ifdef SCTP_MVRF for (i = 0; i < inp->num_vrfs; i++) { if (inp->m_vrf_ids[i] == vrf_id) { fnd = 1; break; } } #else if (inp->def_vrf_id == vrf_id) fnd = 1; #endif if (!fnd) { SCTP_INP_RUNLOCK(inp); continue; } LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa == NULL) { SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__); continue; } SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ", (void *)laddr->ifa); if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) { SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n"); continue; } if (laddr->ifa->address.sa.sa_family == nam->sa_family) { /* possible, see if it matches */ switch (nam->sa_family) { #ifdef INET case AF_INET: #if defined(__APPLE__) && !defined(__Userspace__) if (sin == NULL) { /* TSNH */ break; } #endif if (sin->sin_addr.s_addr == laddr->ifa->address.sin.sin_addr.s_addr) { SCTP_INP_RUNLOCK(inp); return (inp); } break; #endif #ifdef INET6 case AF_INET6: intf_addr6 = &laddr->ifa->address.sin6; if (SCTP6_ARE_ADDR_EQUAL(sin6, intf_addr6)) { SCTP_INP_RUNLOCK(inp); return (inp); } break; #endif #if defined(__Userspace__) case AF_CONN: if (sconn->sconn_addr == laddr->ifa->address.sconn.sconn_addr) { SCTP_INP_RUNLOCK(inp); return (inp); } break; #endif } } } SCTP_INP_RUNLOCK(inp); } return (NULL); } static struct sctp_inpcb * sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id) { struct sctppcbhead *head; struct sctp_inpcb *t_inp; #ifdef SCTP_MVRF int i; #endif int fnd; head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))]; LIST_FOREACH(t_inp, head, sctp_hash) { if (t_inp->sctp_lport != lport) { continue; } /* is it in the VRF in question */ fnd = 0; #ifdef SCTP_MVRF for (i = 0; i < inp->num_vrfs; i++) { if (t_inp->m_vrf_ids[i] == vrf_id) { fnd = 1; break; } } #else if (t_inp->def_vrf_id == vrf_id) fnd = 1; #endif if (!fnd) continue; /* This one is in use. */ /* check the v6/v4 binding issue */ if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) && SCTP_IPV6_V6ONLY(t_inp)) { if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) { /* collision in V6 space */ return (t_inp); } else { /* inp is BOUND_V4 no conflict */ continue; } } else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) { /* t_inp is bound v4 and v6, conflict always */ return (t_inp); } else { /* t_inp is bound only V4 */ if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) && SCTP_IPV6_V6ONLY(inp)) { /* no conflict */ continue; } /* else fall through to conflict */ } return (t_inp); } return (NULL); } int sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp) { /* For 1-2-1 with port reuse */ struct sctppcbhead *head; struct sctp_inpcb *tinp, *ninp; SCTP_INP_INFO_WLOCK_ASSERT(); SCTP_INP_WLOCK_ASSERT(inp); if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) { /* only works with port reuse on */ return (-1); } if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) { return (0); } SCTP_INP_WUNLOCK(inp); head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))]; /* Kick out all non-listeners to the TCP hash */ LIST_FOREACH_SAFE(tinp, head, sctp_hash, ninp) { if (tinp->sctp_lport != inp->sctp_lport) { continue; } if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { continue; } if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) { continue; } if (SCTP_IS_LISTENING(tinp)) { continue; } SCTP_INP_WLOCK(tinp); LIST_REMOVE(tinp, sctp_hash); head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))]; tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL; LIST_INSERT_HEAD(head, tinp, sctp_hash); SCTP_INP_WUNLOCK(tinp); } SCTP_INP_WLOCK(inp); /* Pull from where he was */ LIST_REMOVE(inp, sctp_hash); inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL; head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))]; LIST_INSERT_HEAD(head, inp, sctp_hash); return (0); } struct sctp_inpcb * sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock, uint32_t vrf_id) { /* * First we check the hash table to see if someone has this port * bound with just the port. */ struct sctp_inpcb *inp; struct sctppcbhead *head; int lport; unsigned int i; #ifdef INET struct sockaddr_in *sin; #endif #ifdef INET6 struct sockaddr_in6 *sin6; #endif #if defined(__Userspace__) struct sockaddr_conn *sconn; #endif switch (nam->sa_family) { #ifdef INET case AF_INET: sin = (struct sockaddr_in *)nam; lport = sin->sin_port; break; #endif #ifdef INET6 case AF_INET6: sin6 = (struct sockaddr_in6 *)nam; lport = sin6->sin6_port; break; #endif #if defined(__Userspace__) case AF_CONN: sconn = (struct sockaddr_conn *)nam; lport = sconn->sconn_port; break; #endif default: return (NULL); } /* * I could cheat here and just cast to one of the types but we will * do it right. It also provides the check against an Unsupported * type too. */ /* Find the head of the ALLADDR chain */ if (have_lock == 0) { SCTP_INP_INFO_RLOCK(); } head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))]; inp = sctp_endpoint_probe(nam, head, lport, vrf_id); /* * If the TCP model exists it could be that the main listening * endpoint is gone but there still exists a connected socket for this * guy. If so we can return the first one that we find. This may NOT * be the correct one so the caller should be wary on the returned INP. * Currently the only caller that sets find_tcp_pool is in bindx where * we are verifying that a user CAN bind the address. He either * has bound it already, or someone else has, or its open to bind, * so this is good enough. */ if (inp == NULL && find_tcp_pool) { for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) { head = &SCTP_BASE_INFO(sctp_tcpephash)[i]; inp = sctp_endpoint_probe(nam, head, lport, vrf_id); if (inp) { break; } } } if (inp) { SCTP_INP_INCR_REF(inp); } if (have_lock == 0) { SCTP_INP_INFO_RUNLOCK(); } return (inp); } /* * Find an association for an endpoint with the pointer to whom you want to * send to and the endpoint pointer. The address can be IPv4 or IPv6. We may * need to change the *to to some other struct like a mbuf... */ struct sctp_tcb * sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to, struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool, uint32_t vrf_id) { struct sctp_inpcb *inp = NULL; struct sctp_tcb *stcb; SCTP_INP_INFO_RLOCK(); if (find_tcp_pool) { if (inp_p != NULL) { stcb = sctp_tcb_special_locate(inp_p, from, to, netp, vrf_id); } else { stcb = sctp_tcb_special_locate(&inp, from, to, netp, vrf_id); } if (stcb != NULL) { SCTP_INP_INFO_RUNLOCK(); return (stcb); } } inp = sctp_pcb_findep(to, 0, 1, vrf_id); if (inp_p != NULL) { *inp_p = inp; } SCTP_INP_INFO_RUNLOCK(); if (inp == NULL) { return (NULL); } /* * ok, we have an endpoint, now lets find the assoc for it (if any) * we now place the source address or from in the to of the find * endpoint call. Since in reality this chain is used from the * inbound packet side. */ if (inp_p != NULL) { stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to, NULL); } else { stcb = sctp_findassociation_ep_addr(&inp, from, netp, to, NULL); } return (stcb); } /* * This routine will grub through the mbuf that is a INIT or INIT-ACK and * find all addresses that the sender has specified in any address list. Each * address will be used to lookup the TCB and see if one exits. */ static struct sctp_tcb * sctp_findassociation_special_addr(struct mbuf *m, int offset, struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp, struct sockaddr *dst) { struct sctp_paramhdr *phdr, param_buf; #if defined(INET) || defined(INET6) struct sctp_tcb *stcb; uint16_t ptype; #endif uint16_t plen; #ifdef INET struct sockaddr_in sin4; #endif #ifdef INET6 struct sockaddr_in6 sin6; #endif #ifdef INET memset(&sin4, 0, sizeof(sin4)); #ifdef HAVE_SIN_LEN sin4.sin_len = sizeof(sin4); #endif sin4.sin_family = AF_INET; sin4.sin_port = sh->src_port; #endif #ifdef INET6 memset(&sin6, 0, sizeof(sin6)); #ifdef HAVE_SIN6_LEN sin6.sin6_len = sizeof(sin6); #endif sin6.sin6_family = AF_INET6; sin6.sin6_port = sh->src_port; #endif offset += sizeof(struct sctp_init_chunk); phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf)); while (phdr != NULL) { /* now we must see if we want the parameter */ #if defined(INET) || defined(INET6) ptype = ntohs(phdr->param_type); #endif plen = ntohs(phdr->param_length); if (plen == 0) { break; } #ifdef INET if (ptype == SCTP_IPV4_ADDRESS && plen == sizeof(struct sctp_ipv4addr_param)) { /* Get the rest of the address */ struct sctp_ipv4addr_param ip4_param, *p4; phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&ip4_param, sizeof(ip4_param)); if (phdr == NULL) { return (NULL); } p4 = (struct sctp_ipv4addr_param *)phdr; memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr)); /* look it up */ stcb = sctp_findassociation_ep_addr(inp_p, (struct sockaddr *)&sin4, netp, dst, NULL); if (stcb != NULL) { return (stcb); } } #endif #ifdef INET6 if (ptype == SCTP_IPV6_ADDRESS && plen == sizeof(struct sctp_ipv6addr_param)) { /* Get the rest of the address */ struct sctp_ipv6addr_param ip6_param, *p6; phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&ip6_param, sizeof(ip6_param)); if (phdr == NULL) { return (NULL); } p6 = (struct sctp_ipv6addr_param *)phdr; memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr)); /* look it up */ stcb = sctp_findassociation_ep_addr(inp_p, (struct sockaddr *)&sin6, netp, dst, NULL); if (stcb != NULL) { return (stcb); } } #endif offset += SCTP_SIZE32(plen); phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf)); } return (NULL); } static struct sctp_tcb * sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag, struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport, uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag) { /* * Use my vtag to hash. If we find it we then verify the source addr * is in the assoc. If all goes well we save a bit on rec of a * packet. */ struct sctpasochead *head; struct sctp_nets *net; struct sctp_tcb *stcb; #ifdef SCTP_MVRF unsigned int i; #endif SCTP_INP_INFO_RLOCK(); head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag, SCTP_BASE_INFO(hashasocmark))]; LIST_FOREACH(stcb, head, sctp_asocs) { SCTP_INP_RLOCK(stcb->sctp_ep); if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { SCTP_INP_RUNLOCK(stcb->sctp_ep); continue; } #ifdef SCTP_MVRF for (i = 0; i < stcb->sctp_ep->num_vrfs; i++) { if (stcb->sctp_ep->m_vrf_ids[i] == vrf_id) { break; } } if (i == stcb->sctp_ep->num_vrfs) { SCTP_INP_RUNLOCK(inp); continue; } #else if (stcb->sctp_ep->def_vrf_id != vrf_id) { SCTP_INP_RUNLOCK(stcb->sctp_ep); continue; } #endif SCTP_TCB_LOCK(stcb); SCTP_INP_RUNLOCK(stcb->sctp_ep); if (stcb->asoc.my_vtag == vtag) { /* candidate */ if (stcb->rport != rport) { SCTP_TCB_UNLOCK(stcb); continue; } if (stcb->sctp_ep->sctp_lport != lport) { SCTP_TCB_UNLOCK(stcb); continue; } if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { SCTP_TCB_UNLOCK(stcb); continue; } /* RRS:Need toaddr check here */ if (sctp_does_stcb_own_this_addr(stcb, to) == 0) { /* Endpoint does not own this address */ SCTP_TCB_UNLOCK(stcb); continue; } if (remote_tag) { /* If we have both vtags that's all we match on */ if (stcb->asoc.peer_vtag == remote_tag) { /* If both tags match we consider it conclusive * and check NO source/destination addresses */ goto conclusive; } } if (skip_src_check) { conclusive: if (from) { *netp = sctp_findnet(stcb, from); } else { *netp = NULL; /* unknown */ } if (inp_p) *inp_p = stcb->sctp_ep; SCTP_INP_INFO_RUNLOCK(); return (stcb); } net = sctp_findnet(stcb, from); if (net) { /* yep its him. */ *netp = net; SCTP_STAT_INCR(sctps_vtagexpress); *inp_p = stcb->sctp_ep; SCTP_INP_INFO_RUNLOCK(); return (stcb); } else { /* * not him, this should only happen in rare * cases so I peg it. */ SCTP_STAT_INCR(sctps_vtagbogus); } } SCTP_TCB_UNLOCK(stcb); } SCTP_INP_INFO_RUNLOCK(); return (NULL); } /* * Find an association with the pointer to the inbound IP packet. This can be * a IPv4 or IPv6 packet. */ struct sctp_tcb * sctp_findassociation_addr(struct mbuf *m, int offset, struct sockaddr *src, struct sockaddr *dst, struct sctphdr *sh, struct sctp_chunkhdr *ch, struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id) { struct sctp_tcb *stcb; struct sctp_inpcb *inp; if (sh->v_tag) { /* we only go down this path if vtag is non-zero */ stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag), inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0); if (stcb) { return (stcb); } } if (inp_p) { stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp, 1, vrf_id); inp = *inp_p; } else { stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp, 1, vrf_id); } SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp); if (stcb == NULL && inp) { /* Found a EP but not this address */ if ((ch->chunk_type == SCTP_INITIATION) || (ch->chunk_type == SCTP_INITIATION_ACK)) { /*- * special hook, we do NOT return linp or an * association that is linked to an existing * association that is under the TCP pool (i.e. no * listener exists). The endpoint finding routine * will always find a listener before examining the * TCP pool. */ if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) { if (inp_p) { *inp_p = NULL; } return (NULL); } stcb = sctp_findassociation_special_addr(m, offset, sh, &inp, netp, dst); if (inp_p != NULL) { *inp_p = inp; } } } SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb); return (stcb); } /* * lookup an association by an ASCONF lookup address. * if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup */ struct sctp_tcb * sctp_findassociation_ep_asconf(struct mbuf *m, int offset, struct sockaddr *dst, struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id) { struct sctp_tcb *stcb; union sctp_sockstore remote_store; struct sctp_paramhdr param_buf, *phdr; int ptype; int zero_address = 0; #ifdef INET struct sockaddr_in *sin; #endif #ifdef INET6 struct sockaddr_in6 *sin6; #endif memset(&remote_store, 0, sizeof(remote_store)); phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk), &param_buf, sizeof(struct sctp_paramhdr)); if (phdr == NULL) { SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n", __func__); return NULL; } ptype = (int)((uint32_t) ntohs(phdr->param_type)); /* get the correlation address */ switch (ptype) { #ifdef INET6 case SCTP_IPV6_ADDRESS: { /* ipv6 address param */ struct sctp_ipv6addr_param *p6, p6_buf; if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) { return NULL; } p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk), &p6_buf.ph, sizeof(p6_buf)); if (p6 == NULL) { SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n", __func__); return (NULL); } sin6 = &remote_store.sin6; sin6->sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN sin6->sin6_len = sizeof(*sin6); #endif sin6->sin6_port = sh->src_port; memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr)); if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) zero_address = 1; break; } #endif #ifdef INET case SCTP_IPV4_ADDRESS: { /* ipv4 address param */ struct sctp_ipv4addr_param *p4, p4_buf; if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) { return NULL; } p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk), &p4_buf.ph, sizeof(p4_buf)); if (p4 == NULL) { SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n", __func__); return (NULL); } sin = &remote_store.sin; sin->sin_family = AF_INET; #ifdef HAVE_SIN_LEN sin->sin_len = sizeof(*sin); #endif sin->sin_port = sh->src_port; memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr)); if (sin->sin_addr.s_addr == INADDR_ANY) zero_address = 1; break; } #endif default: /* invalid address param type */ return NULL; } if (zero_address) { stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p, netp, sh->src_port, sh->dest_port, 1, vrf_id, 0); if (stcb != NULL) { SCTP_INP_DECR_REF(*inp_p); } } else { stcb = sctp_findassociation_ep_addr(inp_p, &remote_store.sa, netp, dst, NULL); } return (stcb); } /* * allocate a sctp_inpcb and setup a temporary binding to a port/all * addresses. This way if we don't get a bind we by default pick a ephemeral * port with all addresses bound. */ int sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id) { /* * we get called when a new endpoint starts up. We need to allocate * the sctp_inpcb structure from the zone and init it. Mark it as * unbound and find a port that we can use as an ephemeral with * INADDR_ANY. If the user binds later no problem we can then add in * the specific addresses. And setup the default parameters for the * EP. */ int i, error; struct sctp_inpcb *inp; struct sctp_pcb *m; struct timeval time; sctp_sharedkey_t *null_key; error = 0; SCTP_INP_INFO_WLOCK(); inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb); if (inp == NULL) { SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n"); SCTP_INP_INFO_WUNLOCK(); SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS); return (ENOBUFS); } /* zap it */ memset(inp, 0, sizeof(*inp)); /* bump generations */ #if defined(__APPLE__) && !defined(__Userspace__) inp->ip_inp.inp.inp_state = INPCB_STATE_INUSE; #endif /* setup socket pointers */ inp->sctp_socket = so; inp->ip_inp.inp.inp_socket = so; #if defined(__FreeBSD__) && !defined(__Userspace__) inp->ip_inp.inp.inp_cred = crhold(so->so_cred); #endif #ifdef INET6 #if !defined(__Userspace__) && !defined(_WIN32) if (INP_SOCKAF(so) == AF_INET6) { if (MODULE_GLOBAL(ip6_auto_flowlabel)) { inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL; } if (MODULE_GLOBAL(ip6_v6only)) { inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY; } } #endif #endif inp->sctp_associd_counter = 1; inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT; inp->sctp_frag_point = 0; inp->max_cwnd = 0; inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off); inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable); inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable); inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable); inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable); inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable); inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable); inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable); inp->idata_supported = 0; #if defined(__FreeBSD__) && !defined(__Userspace__) inp->fibnum = so->so_fibnum; #else inp->fibnum = 0; #endif #if defined(__Userspace__) inp->ulp_info = NULL; inp->recv_callback = NULL; inp->send_callback = NULL; inp->send_sb_threshold = 0; #endif /* init the small hash table we use to track asocid <-> tcb */ inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark); if (inp->sctp_asocidhash == NULL) { #if defined(__FreeBSD__) && !defined(__Userspace__) crfree(inp->ip_inp.inp.inp_cred); #endif SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); SCTP_INP_INFO_WUNLOCK(); return (ENOBUFS); } SCTP_INCR_EP_COUNT(); inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl); SCTP_INP_INFO_WUNLOCK(); so->so_pcb = (caddr_t)inp; if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) { /* UDP style socket */ inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE | SCTP_PCB_FLAGS_UNBOUND); /* Be sure it is NON-BLOCKING IO for UDP */ /* SCTP_SET_SO_NBIO(so); */ } else if (SCTP_SO_TYPE(so) == SOCK_STREAM) { /* TCP style socket */ inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE | SCTP_PCB_FLAGS_UNBOUND); /* Be sure we have blocking IO by default */ SOCK_LOCK(so); SCTP_CLEAR_SO_NBIO(so); SOCK_UNLOCK(so); } else { /* * unsupported socket type (RAW, etc)- in case we missed it * in protosw */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP); so->so_pcb = NULL; #if defined(__FreeBSD__) && !defined(__Userspace__) crfree(inp->ip_inp.inp.inp_cred); #endif SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); return (EOPNOTSUPP); } if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) { sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE); sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS); } else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) { sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE); sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS); } else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) { sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE); sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS); } inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize), &inp->sctp_hashmark); if (inp->sctp_tcbhash == NULL) { SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n"); SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS); so->so_pcb = NULL; #if defined(__FreeBSD__) && !defined(__Userspace__) crfree(inp->ip_inp.inp.inp_cred); #endif SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); return (ENOBUFS); } #ifdef SCTP_MVRF inp->vrf_size = SCTP_DEFAULT_VRF_SIZE; SCTP_MALLOC(inp->m_vrf_ids, uint32_t *, (sizeof(uint32_t) * inp->vrf_size), SCTP_M_MVRF); if (inp->m_vrf_ids == NULL) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS); so->so_pcb = NULL; SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark); #if defined(__FreeBSD__) && !defined(__Userspace__) crfree(inp->ip_inp.inp.inp_cred); #endif SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); return (ENOBUFS); } inp->m_vrf_ids[0] = vrf_id; inp->num_vrfs = 1; #endif inp->def_vrf_id = vrf_id; #if defined(__APPLE__) && !defined(__Userspace__) #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) inp->ip_inp.inp.inpcb_mtx = lck_mtx_alloc_init(SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr); if (inp->ip_inp.inp.inpcb_mtx == NULL) { SCTP_PRINTF("in_pcballoc: can't alloc mutex! so=%p\n", (void *)so); #ifdef SCTP_MVRF SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF); #endif SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark); so->so_pcb = NULL; SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); SCTP_UNLOCK_EXC(SCTP_BASE_INFO(sctbinfo).ipi_lock); SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM); return (ENOMEM); } #elif defined(APPLE_LION) || defined(APPLE_MOUNTAINLION) lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr); #else lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).ipi_lock_grp, SCTP_BASE_INFO(sctbinfo).ipi_lock_attr); #endif #endif SCTP_INP_INFO_WLOCK(); SCTP_INP_LOCK_INIT(inp); #if defined(__FreeBSD__) && !defined(__Userspace__) INP_LOCK_INIT(&inp->ip_inp.inp, "inp", "sctpinp"); #endif SCTP_INP_READ_INIT(inp); SCTP_ASOC_CREATE_LOCK_INIT(inp); /* lock the new ep */ SCTP_INP_WLOCK(inp); /* add it to the info area */ LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list); #if defined(__APPLE__) && !defined(__Userspace__) inp->ip_inp.inp.inp_pcbinfo = &SCTP_BASE_INFO(sctbinfo); #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION) LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).listhead, &inp->ip_inp.inp, inp_list); #else LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).ipi_listhead, &inp->ip_inp.inp, inp_list); #endif #endif SCTP_INP_INFO_WUNLOCK(); TAILQ_INIT(&inp->read_queue); LIST_INIT(&inp->sctp_addr_list); LIST_INIT(&inp->sctp_asoc_list); #ifdef SCTP_TRACK_FREED_ASOCS /* TEMP CODE */ LIST_INIT(&inp->sctp_asoc_free_list); #endif /* Init the timer structure for signature change */ SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer); inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE; /* now init the actual endpoint default data */ m = &inp->sctp_ep; /* setup the base timeout information */ m->sctp_timeoutticks[SCTP_TIMER_SEND] = sctp_secs_to_ticks(SCTP_SEND_SEC); /* needed ? */ m->sctp_timeoutticks[SCTP_TIMER_INIT] = sctp_secs_to_ticks(SCTP_INIT_SEC); /* needed ? */ m->sctp_timeoutticks[SCTP_TIMER_RECV] = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default)); m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default)); m->sctp_timeoutticks[SCTP_TIMER_PMTU] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default)); m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default)); m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default)); /* all max/min max are in ms */ m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default); m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default); m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default); m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default); m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default); m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default); m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default); m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default); m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold); m->sctp_sws_sender = SCTP_SWS_SENDER_DEF; m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF; m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default); m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default); m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module); m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module); m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default); /* number of streams to pre-open on a association */ m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default); m->default_mtu = 0; /* Add adaptation cookie */ m->adaptation_layer_indicator = 0; m->adaptation_layer_indicator_provided = 0; /* seed random number generator */ m->random_counter = 1; m->store_at = SCTP_SIGNATURE_SIZE; SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers)); sctp_fill_random_store(m); /* Minimum cookie size */ m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) + sizeof(struct sctp_state_cookie); m->size_of_a_cookie += SCTP_SIGNATURE_SIZE; /* Setup the initial secret */ (void)SCTP_GETTIME_TIMEVAL(&time); m->time_of_secret_change = (unsigned int)time.tv_sec; for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) { m->secret_key[0][i] = sctp_select_initial_TSN(m); } sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL); /* How long is a cookie good for ? */ m->def_cookie_life = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default)); /* * Initialize authentication parameters */ m->local_hmacs = sctp_default_supported_hmaclist(); m->local_auth_chunks = sctp_alloc_chunklist(); if (inp->asconf_supported) { sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks); sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks); } m->default_dscp = 0; #ifdef INET6 m->default_flowlabel = 0; #endif m->port = 0; /* encapsulation disabled by default */ LIST_INIT(&m->shared_keys); /* add default NULL key as key id 0 */ null_key = sctp_alloc_sharedkey(); sctp_insert_sharedkey(&m->shared_keys, null_key); SCTP_INP_WUNLOCK(inp); #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 12); #endif return (error); } void sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp, struct sctp_tcb *stcb) { struct sctp_nets *net; uint16_t lport, rport; struct sctppcbhead *head; struct sctp_laddr *laddr, *oladdr; atomic_add_int(&stcb->asoc.refcnt, 1); SCTP_TCB_UNLOCK(stcb); SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(old_inp); SCTP_INP_WLOCK(new_inp); SCTP_TCB_LOCK(stcb); atomic_subtract_int(&stcb->asoc.refcnt, 1); #if defined(__FreeBSD__) && !defined(__Userspace__) #ifdef INET6 if (old_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) { new_inp->ip_inp.inp.inp_flags |= old_inp->ip_inp.inp.inp_flags & INP_CONTROLOPTS; if (old_inp->ip_inp.inp.in6p_outputopts) { new_inp->ip_inp.inp.in6p_outputopts = ip6_copypktopts(old_inp->ip_inp.inp.in6p_outputopts, M_NOWAIT); } } #endif #if defined(INET) && defined(INET6) else #endif #ifdef INET { new_inp->ip_inp.inp.inp_ip_tos = old_inp->ip_inp.inp.inp_ip_tos; new_inp->ip_inp.inp.inp_ip_ttl = old_inp->ip_inp.inp.inp_ip_ttl; } #endif #endif new_inp->sctp_ep.time_of_secret_change = old_inp->sctp_ep.time_of_secret_change; memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key, sizeof(old_inp->sctp_ep.secret_key)); new_inp->sctp_ep.current_secret_number = old_inp->sctp_ep.current_secret_number; new_inp->sctp_ep.last_secret_number = old_inp->sctp_ep.last_secret_number; new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie; /* make it so new data pours into the new socket */ stcb->sctp_socket = new_inp->sctp_socket; stcb->sctp_ep = new_inp; /* Copy the port across */ lport = new_inp->sctp_lport = old_inp->sctp_lport; rport = stcb->rport; /* Pull the tcb from the old association */ LIST_REMOVE(stcb, sctp_tcbhash); LIST_REMOVE(stcb, sctp_tcblist); if (stcb->asoc.in_asocid_hash) { LIST_REMOVE(stcb, sctp_tcbasocidhash); } /* Now insert the new_inp into the TCP connected hash */ head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))]; LIST_INSERT_HEAD(head, new_inp, sctp_hash); /* Its safe to access */ new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND; /* Now move the tcb into the endpoint list */ LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist); /* * Question, do we even need to worry about the ep-hash since we * only have one connection? Probably not :> so lets get rid of it * and not suck up any kernel memory in that. */ if (stcb->asoc.in_asocid_hash) { struct sctpasochead *lhd; lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id, new_inp->hashasocidmark)]; LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash); } /* Ok. Let's restart timer. */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp, stcb, net); } SCTP_INP_INFO_WUNLOCK(); if (new_inp->sctp_tcbhash != NULL) { SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark); new_inp->sctp_tcbhash = NULL; } if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) { /* Subset bound, so copy in the laddr list from the old_inp */ LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) { laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr); if (laddr == NULL) { /* * Gak, what can we do? This assoc is really * HOSED. We probably should send an abort * here. */ SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n"); continue; } SCTP_INCR_LADDR_COUNT(); memset(laddr, 0, sizeof(*laddr)); (void)SCTP_GETTIME_TIMEVAL(&laddr->start_time); laddr->ifa = oladdr->ifa; atomic_add_int(&laddr->ifa->refcount, 1); LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr, sctp_nxt_addr); new_inp->laddr_count++; if (oladdr == stcb->asoc.last_used_address) { stcb->asoc.last_used_address = laddr; } } } /* Now any running timers need to be adjusted. */ if (stcb->asoc.dack_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.dack_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (stcb->asoc.asconf_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.asconf_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (stcb->asoc.strreset_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.strreset_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (stcb->asoc.shut_guard_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.shut_guard_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (stcb->asoc.autoclose_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.autoclose_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (stcb->asoc.delete_prim_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); stcb->asoc.delete_prim_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } /* now what about the nets? */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { if (net->pmtu_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); net->pmtu_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (net->hb_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); net->hb_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } if (net->rxt_timer.ep == old_inp) { SCTP_INP_DECR_REF(old_inp); net->rxt_timer.ep = new_inp; SCTP_INP_INCR_REF(new_inp); } } SCTP_INP_WUNLOCK(new_inp); SCTP_INP_WUNLOCK(old_inp); } /* * insert an laddr entry with the given ifa for the desired list */ static int sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act) { struct sctp_laddr *laddr; laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr); if (laddr == NULL) { /* out of memory? */ SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); return (EINVAL); } SCTP_INCR_LADDR_COUNT(); memset(laddr, 0, sizeof(*laddr)); (void)SCTP_GETTIME_TIMEVAL(&laddr->start_time); laddr->ifa = ifa; laddr->action = act; atomic_add_int(&ifa->refcount, 1); /* insert it */ LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr); return (0); } /* * Remove an laddr entry from the local address list (on an assoc) */ static void sctp_remove_laddr(struct sctp_laddr *laddr) { /* remove from the list */ LIST_REMOVE(laddr, sctp_nxt_addr); sctp_free_ifa(laddr->ifa); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr); SCTP_DECR_LADDR_COUNT(); } #if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Userspace__)) /* * Don't know why, but without this there is an unknown reference when * compiling NetBSD... hmm */ extern void in6_sin6_2_sin(struct sockaddr_in *, struct sockaddr_in6 *sin6); #endif /* * Bind the socket, with the PCB and global info locks held. Note, if a * socket address is specified, the PCB lock may be dropped and re-acquired. * * sctp_ifap is used to bypass normal local address validation checks. */ int #if defined(__FreeBSD__) && !defined(__Userspace__) sctp_inpcb_bind_locked(struct sctp_inpcb *inp, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, struct thread *td) #elif defined(_WIN32) && !defined(__Userspace__) sctp_inpcb_bind_locked(struct sctp_inpcb *inp, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, PKTHREAD p) #else sctp_inpcb_bind_locked(struct sctp_inpcb *inp, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, struct proc *p) #endif { /* bind a ep to a socket address */ struct sctppcbhead *head; struct sctp_inpcb *inp_tmp; #if (defined(__FreeBSD__) || defined(__APPLE__)) && !defined(__Userspace__) struct inpcb *ip_inp; #endif int port_reuse_active = 0; int bindall; #ifdef SCTP_MVRF int i; #endif uint16_t lport; int error; uint32_t vrf_id; #if defined(__FreeBSD__) && !defined(__Userspace__) KASSERT(td != NULL, ("%s: null thread", __func__)); #endif error = 0; lport = 0; bindall = 1; #if (defined(__FreeBSD__) || defined(__APPLE__)) && !defined(__Userspace__) ip_inp = &inp->ip_inp.inp; #endif SCTP_INP_INFO_WLOCK_ASSERT(); SCTP_INP_WLOCK_ASSERT(inp); #ifdef SCTP_DEBUG if (addr) { SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n", ntohs(((struct sockaddr_in *)addr)->sin_port)); SCTPDBG(SCTP_DEBUG_PCB1, "Addr: "); SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr); } #endif if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) { error = EINVAL; /* already did a bind, subsequent binds NOT allowed ! */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } if (addr != NULL) { switch (addr->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin; /* IPV6_V6ONLY socket? */ if (SCTP_IPV6_V6ONLY(inp)) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #ifdef HAVE_SA_LEN if (addr->sa_len != sizeof(*sin)) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif sin = (struct sockaddr_in *)addr; lport = sin->sin_port; #if defined(__FreeBSD__) && !defined(__Userspace__) /* * For LOOPBACK the prison_local_ip4() call will transmute the ip address * to the proper value. */ if ((error = prison_local_ip4(td->td_ucred, &sin->sin_addr)) != 0) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif if (sin->sin_addr.s_addr != INADDR_ANY) { bindall = 0; } break; } #endif #ifdef INET6 case AF_INET6: { /* Only for pure IPv6 Address. (No IPv4 Mapped!) */ struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)addr; #ifdef HAVE_SA_LEN if (addr->sa_len != sizeof(*sin6)) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif lport = sin6->sin6_port; #if defined(__FreeBSD__) && !defined(__Userspace__) /* * For LOOPBACK the prison_local_ip6() call will transmute the ipv6 address * to the proper value. */ if ((error = prison_local_ip6(td->td_ucred, &sin6->sin6_addr, (SCTP_IPV6_V6ONLY(inp) != 0))) != 0) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) { bindall = 0; #ifdef SCTP_EMBEDDED_V6_SCOPE /* KAME hack: embed scopeid */ #if defined(SCTP_KAME) if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #elif defined(__APPLE__) && !defined(__Userspace__) #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL) != 0) { #else if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL, NULL) != 0) { #endif error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #elif defined(__FreeBSD__) && !defined(__Userspace__) error = scope6_check_id(sin6, MODULE_GLOBAL(ip6_use_defzone)); if (error != 0) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #else if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif #endif /* SCTP_EMBEDDED_V6_SCOPE */ } #ifndef SCOPEDROUTING /* this must be cleared for ifa_ifwithaddr() */ sin6->sin6_scope_id = 0; #endif /* SCOPEDROUTING */ break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn; #ifdef HAVE_SA_LEN if (addr->sa_len != sizeof(struct sockaddr_conn)) { error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #endif sconn = (struct sockaddr_conn *)addr; lport = sconn->sconn_port; if (sconn->sconn_addr != NULL) { bindall = 0; } break; } #endif default: error = EAFNOSUPPORT; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } } /* Setup a vrf_id to be the default for the non-bind-all case. */ vrf_id = inp->def_vrf_id; if (lport) { /* * Did the caller specify a port? if so we must see if an ep * already has this one bound. */ /* got to be root to get at low ports */ #if !(defined(_WIN32) && !defined(__Userspace__)) if (ntohs(lport) < IPPORT_RESERVED && #if defined(__FreeBSD__) && !defined(__Userspace__) (error = priv_check(td, PRIV_NETINET_RESERVEDPORT)) != 0) { #elif defined(__APPLE__) && !defined(__Userspace__) (error = suser(p->p_ucred, &p->p_acflag)) != 0) { #elif defined(__Userspace__) /* TODO ensure uid is 0, etc... */ 0) { #else (error = suser(p, 0)) != 0) { #endif goto out; } #endif SCTP_INP_INCR_REF(inp); SCTP_INP_WUNLOCK(inp); if (bindall) { #ifdef SCTP_MVRF for (i = 0; i < inp->num_vrfs; i++) { vrf_id = inp->m_vrf_ids[i]; #else vrf_id = inp->def_vrf_id; #endif inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id); if (inp_tmp != NULL) { /* * lock guy returned and lower count * note that we are not bound so * inp_tmp should NEVER be inp. And * it is this inp (inp_tmp) that gets * the reference bump, so we must * lower it. */ SCTP_INP_DECR_REF(inp_tmp); /* unlock info */ if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) && (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) { /* Ok, must be one-2-one and allowing port re-use */ port_reuse_active = 1; goto continue_anyway; } SCTP_INP_WLOCK(inp); SCTP_INP_DECR_REF(inp); error = EADDRINUSE; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #ifdef SCTP_MVRF } #endif } else { inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id); if (inp_tmp != NULL) { /* * lock guy returned and lower count note * that we are not bound so inp_tmp should * NEVER be inp. And it is this inp (inp_tmp) * that gets the reference bump, so we must * lower it. */ SCTP_INP_DECR_REF(inp_tmp); /* unlock info */ if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) && (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) { /* Ok, must be one-2-one and allowing port re-use */ port_reuse_active = 1; goto continue_anyway; } SCTP_INP_WLOCK(inp); SCTP_INP_DECR_REF(inp); error = EADDRINUSE; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } } continue_anyway: SCTP_INP_WLOCK(inp); SCTP_INP_DECR_REF(inp); if (bindall) { /* verify that no lport is not used by a singleton */ if ((port_reuse_active == 0) && (inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) { /* Sorry someone already has this one bound */ if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) && (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) { port_reuse_active = 1; } else { error = EADDRINUSE; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } } } } else { uint16_t first, last, candidate; uint16_t count; #if defined(__Userspace__) first = MODULE_GLOBAL(ipport_firstauto); last = MODULE_GLOBAL(ipport_lastauto); #elif defined(_WIN32) first = 1; last = 0xffff; #elif defined(__FreeBSD__) || defined(__APPLE__) if (ip_inp->inp_flags & INP_HIGHPORT) { first = MODULE_GLOBAL(ipport_hifirstauto); last = MODULE_GLOBAL(ipport_hilastauto); } else if (ip_inp->inp_flags & INP_LOWPORT) { #if defined(__FreeBSD__) if ((error = priv_check(td, PRIV_NETINET_RESERVEDPORT)) != 0) { #else if ((error = suser(p->p_ucred, &p->p_acflag)) != 0) { #endif SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } first = MODULE_GLOBAL(ipport_lowfirstauto); last = MODULE_GLOBAL(ipport_lowlastauto); } else { first = MODULE_GLOBAL(ipport_firstauto); last = MODULE_GLOBAL(ipport_lastauto); } #endif if (first > last) { uint16_t temp; temp = first; first = last; last = temp; } count = last - first + 1; /* number of candidates */ candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count); for (;;) { #ifdef SCTP_MVRF for (i = 0; i < inp->num_vrfs; i++) { if (sctp_isport_inuse(inp, htons(candidate), inp->m_vrf_ids[i]) != NULL) { break; } } if (i == inp->num_vrfs) { lport = htons(candidate); break; } #else if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) { lport = htons(candidate); break; } #endif if (--count == 0) { error = EADDRINUSE; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } if (candidate == last) candidate = first; else candidate = candidate + 1; } } if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) { /* * this really should not happen. The guy did a non-blocking * bind and then did a close at the same time. */ error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } /* ok we look clear to give out this port, so lets setup the binding */ if (bindall) { /* binding to all addresses, so just set in the proper flags */ inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL; /* set the automatic addr changes from kernel flag */ if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) { sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF); sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF); } else { sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF); sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF); } if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) { sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS); } else { sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS); } /* set the automatic mobility_base from kernel flag (by micchie) */ if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) { sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE); sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED); } else { sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE); sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED); } /* set the automatic mobility_fasthandoff from kernel flag (by micchie) */ if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) { sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF); sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED); } else { sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF); sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED); } } else { /* * bind specific, make sure flags is off and add a new * address structure to the sctp_addr_list inside the ep * structure. * * We will need to allocate one and insert it at the head. The * socketopt call can just insert new addresses in there as * well. It will also have to do the embed scope kame hack * too (before adding). */ struct sctp_ifa *ifa; union sctp_sockstore store; memset(&store, 0, sizeof(store)); switch (addr->sa_family) { #ifdef INET case AF_INET: memcpy(&store.sin, addr, sizeof(struct sockaddr_in)); store.sin.sin_port = 0; break; #endif #ifdef INET6 case AF_INET6: memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6)); store.sin6.sin6_port = 0; break; #endif #if defined(__Userspace__) case AF_CONN: memcpy(&store.sconn, addr, sizeof(struct sockaddr_conn)); store.sconn.sconn_port = 0; break; #endif default: break; } /* * first find the interface with the bound address need to * zero out the port to find the address! yuck! can't do * this earlier since need port for sctp_pcb_findep() */ if (sctp_ifap != NULL) { ifa = sctp_ifap; } else { /* Note for BSD we hit here always other * O/S's will pass things in via the * sctp_ifap argument. */ ifa = sctp_find_ifa_by_addr(&store.sa, vrf_id, SCTP_ADDR_NOT_LOCKED); } if (ifa == NULL) { error = EADDRNOTAVAIL; /* Can't find an interface with that address */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } #ifdef INET6 if (addr->sa_family == AF_INET6) { /* GAK, more FIXME IFA lock? */ if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) { /* Can't bind a non-existent addr. */ error = EINVAL; SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error); goto out; } } #endif /* we're not bound all */ inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL; /* allow bindx() to send ASCONF's for binding changes */ sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF); /* clear automatic addr changes from kernel flag */ sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF); /* add this address to the endpoint list */ error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0); if (error != 0) goto out; inp->laddr_count++; } /* find the bucket */ if (port_reuse_active) { /* Put it into tcp 1-2-1 hash */ head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))]; inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL; } else { head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))]; } /* put it in the bucket */ LIST_INSERT_HEAD(head, inp, sctp_hash); SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n", (void *)head, ntohs(lport), port_reuse_active); /* set in the port */ inp->sctp_lport = lport; /* turn off just the unbound flag */ KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) != 0, ("%s: inp %p is already bound", __func__, inp)); inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND; out: return (error); } int #if defined(__FreeBSD__) && !defined(__Userspace__) sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, struct thread *td) #elif defined(_WIN32) && !defined(__Userspace__) sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, PKTHREAD p) #else sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct sctp_ifa *sctp_ifap, struct proc *p) #endif { struct sctp_inpcb *inp; int error; inp = so->so_pcb; SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(inp); #if defined(__FreeBSD__) && !defined(__Userspace__) error = sctp_inpcb_bind_locked(inp, addr, sctp_ifap, td); #else error = sctp_inpcb_bind_locked(inp, addr, sctp_ifap, p); #endif SCTP_INP_WUNLOCK(inp); SCTP_INP_INFO_WUNLOCK(); return (error); } static void sctp_iterator_inp_being_freed(struct sctp_inpcb *inp) { struct sctp_iterator *it, *nit; /* * We enter with the only the ITERATOR_LOCK in place and a write * lock on the inp_info stuff. */ it = sctp_it_ctl.cur_it; #if defined(__FreeBSD__) && !defined(__Userspace__) if (it && (it->vn != curvnet)) { /* Its not looking at our VNET */ return; } #endif if (it && (it->inp == inp)) { /* * This is tricky and we hold the iterator lock, * but when it returns and gets the lock (when we * release it) the iterator will try to operate on * inp. We need to stop that from happening. But * of course the iterator has a reference on the * stcb and inp. We can mark it and it will stop. * * If its a single iterator situation, we * set the end iterator flag. Otherwise * we set the iterator to go to the next inp. * */ if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) { sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT; } else { sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP; } } /* Now go through and remove any single reference to * our inp that may be still pending on the list */ SCTP_IPI_ITERATOR_WQ_LOCK(); TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) { #if defined(__FreeBSD__) && !defined(__Userspace__) if (it->vn != curvnet) { continue; } #endif if (it->inp == inp) { /* This one points to me is it inp specific? */ if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) { /* Remove and free this one */ TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr); if (it->function_atend != NULL) { (*it->function_atend) (it->pointer, it->val); } SCTP_FREE(it, SCTP_M_ITER); } else { it->inp = LIST_NEXT(it->inp, sctp_list); if (it->inp) { SCTP_INP_INCR_REF(it->inp); } } /* When its put in the refcnt is incremented so decr it */ SCTP_INP_DECR_REF(inp); } } SCTP_IPI_ITERATOR_WQ_UNLOCK(); } /* release sctp_inpcb unbind the port */ void sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from) { /* * Here we free a endpoint. We must find it (if it is in the Hash * table) and remove it from there. Then we must also find it in the * overall list and remove it from there. After all removals are * complete then any timer has to be stopped. Then start the actual * freeing. a) Any local lists. b) Any associations. c) The hash of * all associations. d) finally the ep itself. */ struct sctp_tcb *asoc, *nasoc; struct sctp_laddr *laddr, *nladdr; struct inpcb *ip_pcb; struct socket *so; int being_refed = 0; struct sctp_queued_to_read *sq, *nsq; #if !defined(__Userspace__) #if !defined(__FreeBSD__) sctp_rtentry_t *rt; #endif #endif int cnt; sctp_sharedkey_t *shared_key, *nshared_key; #if defined(__APPLE__) && !defined(__Userspace__) sctp_lock_assert(SCTP_INP_SO(inp)); #endif #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 0); #endif SCTP_ITERATOR_LOCK(); /* mark any iterators on the list or being processed */ sctp_iterator_inp_being_freed(inp); SCTP_ITERATOR_UNLOCK(); SCTP_ASOC_CREATE_LOCK(inp); SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(inp); so = inp->sctp_socket; KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) != 0, ("%s: inp %p still has socket", __func__, inp)); KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) == 0, ("%s: double free of inp %p", __func__, inp)); if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) { inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP; /* socket is gone, so no more wakeups allowed */ inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE; inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT; inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT; } /* First time through we have the socket lock, after that no more. */ sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL, SCTP_FROM_SCTP_PCB + SCTP_LOC_1); if (inp->control) { sctp_m_freem(inp->control); inp->control = NULL; } if (inp->pkt) { sctp_m_freem(inp->pkt); inp->pkt = NULL; } ip_pcb = &inp->ip_inp.inp; /* we could just cast the main pointer * here but I will be nice :> (i.e. * ip_pcb = ep;) */ if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) { int cnt_in_sd; cnt_in_sd = 0; LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) { SCTP_TCB_LOCK(asoc); if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { asoc->sctp_socket = NULL; /* Skip guys being freed */ cnt_in_sd++; if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) { /* * Special case - we did not start a kill * timer on the asoc due to it was not * closed. So go ahead and start it now. */ SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE); sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL); } SCTP_TCB_UNLOCK(asoc); continue; } if (((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) || (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) && (asoc->asoc.total_output_queue_size == 0)) { /* If we have data in queue, we don't want to just * free since the app may have done, send()/close * or connect/send/close. And it wants the data * to get across first. */ /* Just abandon things in the front states */ if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_2) == 0) { cnt_in_sd++; } continue; } /* Disconnect the socket please */ asoc->sctp_socket = NULL; SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_CLOSED_SOCKET); if ((asoc->asoc.size_on_reasm_queue > 0) || (asoc->asoc.control_pdapi) || (asoc->asoc.size_on_all_streams > 0) || (so && (so->so_rcv.sb_cc > 0))) { /* Left with Data unread */ struct mbuf *op_err; op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, ""); asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_3; sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED); SCTP_STAT_INCR_COUNTER32(sctps_aborted); if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) || (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) { SCTP_STAT_DECR_GAUGE32(sctps_currestab); } if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_4) == 0) { cnt_in_sd++; } continue; } else if (TAILQ_EMPTY(&asoc->asoc.send_queue) && TAILQ_EMPTY(&asoc->asoc.sent_queue) && (asoc->asoc.stream_queue_cnt == 0)) { if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) { goto abort_anyway; } if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) && (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) { struct sctp_nets *netp; /* * there is nothing queued to send, * so I send shutdown */ if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) || (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) { SCTP_STAT_DECR_GAUGE32(sctps_currestab); } SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT); sctp_stop_timers_for_shutdown(asoc); if (asoc->asoc.alternate) { netp = asoc->asoc.alternate; } else { netp = asoc->asoc.primary_destination; } sctp_send_shutdown(asoc, netp); sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc, netp); sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc, NULL); sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED); } } else { /* mark into shutdown pending */ SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING); sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc, NULL); if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) { SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_PARTIAL_MSG_LEFT); } if (TAILQ_EMPTY(&asoc->asoc.send_queue) && TAILQ_EMPTY(&asoc->asoc.sent_queue) && (asoc->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) { struct mbuf *op_err; abort_anyway: op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, ""); asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_5; sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED); SCTP_STAT_INCR_COUNTER32(sctps_aborted); if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) || (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) { SCTP_STAT_DECR_GAUGE32(sctps_currestab); } if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_6) == 0) { cnt_in_sd++; } continue; } else { sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED); } } cnt_in_sd++; SCTP_TCB_UNLOCK(asoc); } /* now is there some left in our SHUTDOWN state? */ if (cnt_in_sd) { #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 2); #endif inp->sctp_socket = NULL; SCTP_INP_WUNLOCK(inp); SCTP_ASOC_CREATE_UNLOCK(inp); SCTP_INP_INFO_WUNLOCK(); return; } } inp->sctp_socket = NULL; if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) != SCTP_PCB_FLAGS_UNBOUND) { /* * ok, this guy has been bound. It's port is * somewhere in the SCTP_BASE_INFO(hash table). Remove * it! */ LIST_REMOVE(inp, sctp_hash); inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND; } /* If there is a timer running to kill us, * forget it, since it may have a contest * on the INP lock.. which would cause us * to die ... */ cnt = 0; LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) { SCTP_TCB_LOCK(asoc); if (immediate != SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) { /* Disconnect the socket please */ asoc->sctp_socket = NULL; SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_CLOSED_SOCKET); } if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) { SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE); sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL); } cnt++; SCTP_TCB_UNLOCK(asoc); continue; } /* Free associations that are NOT killing us */ if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) && ((asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) { struct mbuf *op_err; op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, ""); asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_7; sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED); SCTP_STAT_INCR_COUNTER32(sctps_aborted); } else if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) { cnt++; SCTP_TCB_UNLOCK(asoc); continue; } if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) || (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) { SCTP_STAT_DECR_GAUGE32(sctps_currestab); } if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_FORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_8) == 0) { cnt++; } } if (cnt) { /* Ok we have someone out there that will kill us */ #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 3); #endif SCTP_INP_WUNLOCK(inp); SCTP_ASOC_CREATE_UNLOCK(inp); SCTP_INP_INFO_WUNLOCK(); return; } if (SCTP_INP_LOCK_CONTENDED(inp)) being_refed++; if (SCTP_INP_READ_CONTENDED(inp)) being_refed++; if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp)) being_refed++; /* NOTE: 0 refcount also means no timers are referencing us. */ if ((inp->refcount) || (being_refed) || (inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) { #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 4); #endif sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL); SCTP_INP_WUNLOCK(inp); SCTP_ASOC_CREATE_UNLOCK(inp); SCTP_INP_INFO_WUNLOCK(); return; } inp->sctp_ep.signature_change.type = 0; inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE; /* Remove it from the list .. last thing we need a * lock for. */ LIST_REMOVE(inp, sctp_list); SCTP_INP_WUNLOCK(inp); SCTP_ASOC_CREATE_UNLOCK(inp); SCTP_INP_INFO_WUNLOCK(); #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 5); #endif #if !(defined(_WIN32) || defined(__Userspace__)) #if !(defined(__FreeBSD__) && !defined(__Userspace__)) rt = ip_pcb->inp_route.ro_rt; #endif #endif if ((inp->sctp_asocidhash) != NULL) { SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark); inp->sctp_asocidhash = NULL; } /*sa_ignore FREED_MEMORY*/ TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) { /* Its only abandoned if it had data left */ if (sq->length) SCTP_STAT_INCR(sctps_left_abandon); TAILQ_REMOVE(&inp->read_queue, sq, next); sctp_free_remote_addr(sq->whoFrom); if (so) so->so_rcv.sb_cc -= sq->length; if (sq->data) { sctp_m_freem(sq->data); sq->data = NULL; } /* * no need to free the net count, since at this point all * assoc's are gone. */ sctp_free_a_readq(NULL, sq); } /* Now the sctp_pcb things */ /* * free each asoc if it is not already closed/free. we can't use the * macro here since le_next will get freed as part of the * sctp_free_assoc() call. */ if (ip_pcb->inp_options) { (void)sctp_m_free(ip_pcb->inp_options); ip_pcb->inp_options = 0; } #if !(defined(_WIN32) || defined(__Userspace__)) #if !defined(__FreeBSD__) if (rt) { RTFREE(rt); ip_pcb->inp_route.ro_rt = 0; } #endif #endif #ifdef INET6 #if !(defined(_WIN32) || defined(__Userspace__)) #if (defined(__FreeBSD__) || defined(__APPLE__) && !defined(__Userspace__)) if (ip_pcb->inp_vflag & INP_IPV6) { #else if (inp->inp_vflag & INP_IPV6) { #endif ip6_freepcbopts(ip_pcb->in6p_outputopts); } #endif #endif /* INET6 */ ip_pcb->inp_vflag = 0; /* free up authentication fields */ if (inp->sctp_ep.local_auth_chunks != NULL) sctp_free_chunklist(inp->sctp_ep.local_auth_chunks); if (inp->sctp_ep.local_hmacs != NULL) sctp_free_hmaclist(inp->sctp_ep.local_hmacs); LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) { LIST_REMOVE(shared_key, next); sctp_free_sharedkey(shared_key); /*sa_ignore FREED_MEMORY*/ } #if defined(__APPLE__) && !defined(__Userspace__) inp->ip_inp.inp.inp_state = INPCB_STATE_DEAD; if (in_pcb_checkstate(&inp->ip_inp.inp, WNT_STOPUSING, 1) != WNT_STOPUSING) { #ifdef INVARIANTS panic("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp); #else SCTP_PRINTF("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp); #endif } inp->ip_inp.inp.inp_socket->so_flags |= SOF_PCBCLEARING; #endif /* * if we have an address list the following will free the list of * ifaddr's that are set into this ep. Again macro limitations here, * since the LIST_FOREACH could be a bad idea. */ LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) { sctp_remove_laddr(laddr); } #ifdef SCTP_TRACK_FREED_ASOCS /* TEMP CODE */ LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_free_list, sctp_tcblist, nasoc) { LIST_REMOVE(asoc, sctp_tcblist); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), asoc); SCTP_DECR_ASOC_COUNT(); } /* *** END TEMP CODE ****/ #endif #ifdef SCTP_MVRF SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF); #endif /* Now lets see about freeing the EP hash table. */ if (inp->sctp_tcbhash != NULL) { SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark); inp->sctp_tcbhash = NULL; } /* Now we must put the ep memory back into the zone pool */ #if defined(__FreeBSD__) && !defined(__Userspace__) crfree(inp->ip_inp.inp.inp_cred); INP_LOCK_DESTROY(&inp->ip_inp.inp); #endif SCTP_INP_LOCK_DESTROY(inp); SCTP_INP_READ_DESTROY(inp); SCTP_ASOC_CREATE_LOCK_DESTROY(inp); #if !(defined(__APPLE__) && !defined(__Userspace__)) SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp); SCTP_DECR_EP_COUNT(); #else /* For Tiger, we will do this later... */ #endif } struct sctp_nets * sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr) { struct sctp_nets *net; /* locate the address */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr)) return (net); } return (NULL); } int sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id) { struct sctp_ifa *sctp_ifa; sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED); if (sctp_ifa) { return (1); } else { return (0); } } /* * add's a remote endpoint address, done with the INIT/INIT-ACK as well as * when a ASCONF arrives that adds it. It will also initialize all the cwnd * stats of stuff. */ int sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr, struct sctp_nets **netp, uint16_t port, int set_scope, int from) { /* * The following is redundant to the same lines in the * sctp_aloc_assoc() but is needed since others call the add * address function */ struct sctp_nets *net, *netfirst; int addr_inscope; SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ", from); SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr); netfirst = sctp_findnet(stcb, newaddr); if (netfirst) { /* * Lie and return ok, we don't want to make the association * go away for this behavior. It will happen in the TCP * model in a connected socket. It does not reach the hash * table until after the association is built so it can't be * found. Mark as reachable, since the initial creation will * have been cleared and the NOT_IN_ASSOC flag will have * been added... and we don't want to end up removing it * back out. */ if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) { netfirst->dest_state = (SCTP_ADDR_REACHABLE | SCTP_ADDR_UNCONFIRMED); } else { netfirst->dest_state = SCTP_ADDR_REACHABLE; } return (0); } addr_inscope = 1; switch (newaddr->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin; sin = (struct sockaddr_in *)newaddr; if (sin->sin_addr.s_addr == 0) { /* Invalid address */ return (-1); } /* zero out the zero area */ memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); /* assure len is set */ #ifdef HAVE_SIN_LEN sin->sin_len = sizeof(struct sockaddr_in); #endif if (set_scope) { if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) { stcb->asoc.scope.ipv4_local_scope = 1; } } else { /* Validate the address is in scope */ if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) && (stcb->asoc.scope.ipv4_local_scope == 0)) { addr_inscope = 0; } } break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)newaddr; if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) { /* Invalid address */ return (-1); } /* assure len is set */ #ifdef HAVE_SIN6_LEN sin6->sin6_len = sizeof(struct sockaddr_in6); #endif if (set_scope) { if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) { stcb->asoc.scope.loopback_scope = 1; stcb->asoc.scope.local_scope = 0; stcb->asoc.scope.ipv4_local_scope = 1; stcb->asoc.scope.site_scope = 1; } else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) { /* * If the new destination is a LINK_LOCAL we * must have common site scope. Don't set * the local scope since we may not share * all links, only loopback can do this. * Links on the local network would also be * on our private network for v4 too. */ stcb->asoc.scope.ipv4_local_scope = 1; stcb->asoc.scope.site_scope = 1; } else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) { /* * If the new destination is SITE_LOCAL then * we must have site scope in common. */ stcb->asoc.scope.site_scope = 1; } } else { /* Validate the address is in scope */ if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) && (stcb->asoc.scope.loopback_scope == 0)) { addr_inscope = 0; } else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) && (stcb->asoc.scope.local_scope == 0)) { addr_inscope = 0; } else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) && (stcb->asoc.scope.site_scope == 0)) { addr_inscope = 0; } } break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn; sconn = (struct sockaddr_conn *)newaddr; if (sconn->sconn_addr == NULL) { /* Invalid address */ return (-1); } #ifdef HAVE_SCONN_LEN sconn->sconn_len = sizeof(struct sockaddr_conn); #endif break; } #endif default: /* not supported family type */ return (-1); } net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets); if (net == NULL) { return (-1); } SCTP_INCR_RADDR_COUNT(); memset(net, 0, sizeof(struct sctp_nets)); (void)SCTP_GETTIME_TIMEVAL(&net->start_time); #ifdef HAVE_SA_LEN memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len); #endif switch (newaddr->sa_family) { #ifdef INET case AF_INET: #ifndef HAVE_SA_LEN memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in)); #endif ((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport; break; #endif #ifdef INET6 case AF_INET6: #ifndef HAVE_SA_LEN memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in6)); #endif ((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport; break; #endif #if defined(__Userspace__) case AF_CONN: #ifndef HAVE_SA_LEN memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_conn)); #endif ((struct sockaddr_conn *)&net->ro._l_addr)->sconn_port = stcb->rport; break; #endif default: break; } net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id); if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) { stcb->asoc.scope.loopback_scope = 1; stcb->asoc.scope.ipv4_local_scope = 1; stcb->asoc.scope.local_scope = 0; stcb->asoc.scope.site_scope = 1; addr_inscope = 1; } net->failure_threshold = stcb->asoc.def_net_failure; net->pf_threshold = stcb->asoc.def_net_pf_threshold; if (addr_inscope == 0) { net->dest_state = (SCTP_ADDR_REACHABLE | SCTP_ADDR_OUT_OF_SCOPE); } else { if (from == SCTP_ADDR_IS_CONFIRMED) /* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */ net->dest_state = SCTP_ADDR_REACHABLE; else net->dest_state = SCTP_ADDR_REACHABLE | SCTP_ADDR_UNCONFIRMED; } /* We set this to 0, the timer code knows that * this means its an initial value */ net->rto_needed = 1; net->RTO = 0; net->RTO_measured = 0; stcb->asoc.numnets++; net->ref_count = 1; net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1; net->port = port; net->dscp = stcb->asoc.default_dscp; #ifdef INET6 net->flowlabel = stcb->asoc.default_flowlabel; #endif if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) { net->dest_state |= SCTP_ADDR_NOHB; } else { net->dest_state &= ~SCTP_ADDR_NOHB; } if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) { net->dest_state |= SCTP_ADDR_NO_PMTUD; } else { net->dest_state &= ~SCTP_ADDR_NO_PMTUD; } net->heart_beat_delay = stcb->asoc.heart_beat_delay; /* Init the timer structure */ SCTP_OS_TIMER_INIT(&net->rxt_timer.timer); SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer); SCTP_OS_TIMER_INIT(&net->hb_timer.timer); /* Now generate a route for this guy */ #ifdef INET6 #ifdef SCTP_EMBEDDED_V6_SCOPE /* KAME hack: embed scopeid */ if (newaddr->sa_family == AF_INET6) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)&net->ro._l_addr; #if defined(__APPLE__) && !defined(__Userspace__) #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) (void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL); #else (void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL, NULL); #endif #elif defined(SCTP_KAME) (void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)); #else (void)in6_embedscope(&sin6->sin6_addr, sin6); #endif #ifndef SCOPEDROUTING sin6->sin6_scope_id = 0; #endif } #endif /* SCTP_EMBEDDED_V6_SCOPE */ #endif SCTP_RTALLOC((sctp_route_t *)&net->ro, stcb->asoc.vrf_id, stcb->sctp_ep->fibnum); net->src_addr_selected = 0; #if !defined(__Userspace__) if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) { /* Get source address */ net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep, stcb, (sctp_route_t *)&net->ro, net, 0, stcb->asoc.vrf_id); if (stcb->asoc.default_mtu > 0) { net->mtu = stcb->asoc.default_mtu; switch (net->ro._l_addr.sa.sa_family) { #ifdef INET case AF_INET: net->mtu += SCTP_MIN_V4_OVERHEAD; break; #endif #ifdef INET6 case AF_INET6: net->mtu += SCTP_MIN_OVERHEAD; break; #endif #if defined(__Userspace__) case AF_CONN: net->mtu += sizeof(struct sctphdr); break; #endif default: break; } #if defined(INET) || defined(INET6) if (net->port) { net->mtu += (uint32_t)sizeof(struct udphdr); } #endif } else if (net->ro._s_addr != NULL) { uint32_t imtu, rmtu, hcmtu; net->src_addr_selected = 1; /* Now get the interface MTU */ if (net->ro._s_addr->ifn_p != NULL) { imtu = SCTP_GATHER_MTU_FROM_INTFC(net->ro._s_addr->ifn_p); } else { imtu = 0; } #if defined(__FreeBSD__) && !defined(__Userspace__) rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_nh); hcmtu = sctp_hc_get_mtu(&net->ro._l_addr, stcb->sctp_ep->fibnum); #else rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt); hcmtu = 0; #endif net->mtu = sctp_min_mtu(hcmtu, rmtu, imtu); #if defined(__FreeBSD__) && !defined(__Userspace__) #else if (rmtu == 0) { /* Start things off to match mtu of interface please. */ SCTP_SET_MTU_OF_ROUTE(&net->ro._l_addr.sa, net->ro.ro_rt, net->mtu); } #endif } } #endif if (net->mtu == 0) { if (stcb->asoc.default_mtu > 0) { net->mtu = stcb->asoc.default_mtu; switch (net->ro._l_addr.sa.sa_family) { #ifdef INET case AF_INET: net->mtu += SCTP_MIN_V4_OVERHEAD; break; #endif #ifdef INET6 case AF_INET6: net->mtu += SCTP_MIN_OVERHEAD; break; #endif #if defined(__Userspace__) case AF_CONN: net->mtu += sizeof(struct sctphdr); break; #endif default: break; } #if defined(INET) || defined(INET6) if (net->port) { net->mtu += (uint32_t)sizeof(struct udphdr); } #endif } else { switch (newaddr->sa_family) { #ifdef INET case AF_INET: net->mtu = SCTP_DEFAULT_MTU; break; #endif #ifdef INET6 case AF_INET6: net->mtu = 1280; break; #endif #if defined(__Userspace__) case AF_CONN: net->mtu = 1280; break; #endif default: break; } } } #if defined(INET) || defined(INET6) if (net->port) { net->mtu -= (uint32_t)sizeof(struct udphdr); } #endif if (from == SCTP_ALLOC_ASOC) { stcb->asoc.smallest_mtu = net->mtu; } if (stcb->asoc.smallest_mtu > net->mtu) { sctp_pathmtu_adjustment(stcb, net->mtu); } #ifdef INET6 #ifdef SCTP_EMBEDDED_V6_SCOPE if (newaddr->sa_family == AF_INET6) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)&net->ro._l_addr; #ifdef SCTP_KAME (void)sa6_recoverscope(sin6); #else (void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL); #endif /* SCTP_KAME */ } #endif /* SCTP_EMBEDDED_V6_SCOPE */ #endif /* JRS - Use the congestion control given in the CC module */ if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL) (*stcb->asoc.cc_functions.sctp_set_initial_cc_param)(stcb, net); /* * CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning * of assoc (2005/06/27, [email protected]) */ net->find_pseudo_cumack = 1; net->find_rtx_pseudo_cumack = 1; #if defined(__FreeBSD__) && !defined(__Userspace__) /* Choose an initial flowid. */ net->flowid = stcb->asoc.my_vtag ^ ntohs(stcb->rport) ^ ntohs(stcb->sctp_ep->sctp_lport); net->flowtype = M_HASHTYPE_OPAQUE_HASH; #endif if (netp) { *netp = net; } netfirst = TAILQ_FIRST(&stcb->asoc.nets); #if defined(__FreeBSD__) && !defined(__Userspace__) if (net->ro.ro_nh == NULL) { #else if (net->ro.ro_rt == NULL) { #endif /* Since we have no route put it at the back */ TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next); } else if (netfirst == NULL) { /* We are the first one in the pool. */ TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next); #if defined(__FreeBSD__) && !defined(__Userspace__) } else if (netfirst->ro.ro_nh == NULL) { #else } else if (netfirst->ro.ro_rt == NULL) { #endif /* * First one has NO route. Place this one ahead of the first * one. */ TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next); #if defined(__FreeBSD__) && !defined(__Userspace__) } else if (net->ro.ro_nh->nh_ifp != netfirst->ro.ro_nh->nh_ifp) { #else } else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) { #endif /* * This one has a different interface than the one at the * top of the list. Place it ahead. */ TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next); } else { /* * Ok we have the same interface as the first one. Move * forward until we find either a) one with a NULL route... * insert ahead of that b) one with a different ifp.. insert * after that. c) end of the list.. insert at the tail. */ struct sctp_nets *netlook; do { netlook = TAILQ_NEXT(netfirst, sctp_next); if (netlook == NULL) { /* End of the list */ TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next); break; #if defined(__FreeBSD__) && !defined(__Userspace__) } else if (netlook->ro.ro_nh == NULL) { #else } else if (netlook->ro.ro_rt == NULL) { #endif /* next one has NO route */ TAILQ_INSERT_BEFORE(netfirst, net, sctp_next); break; #if defined(__FreeBSD__) && !defined(__Userspace__) } else if (netlook->ro.ro_nh->nh_ifp != net->ro.ro_nh->nh_ifp) { #else } else if (netlook->ro.ro_rt->rt_ifp != net->ro.ro_rt->rt_ifp) { #endif TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook, net, sctp_next); break; } /* Shift forward */ netfirst = netlook; } while (netlook != NULL); } /* got to have a primary set */ if (stcb->asoc.primary_destination == 0) { stcb->asoc.primary_destination = net; #if defined(__FreeBSD__) && !defined(__Userspace__) } else if ((stcb->asoc.primary_destination->ro.ro_nh == NULL) && (net->ro.ro_nh) && #else } else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) && (net->ro.ro_rt) && #endif ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) { /* No route to current primary adopt new primary */ stcb->asoc.primary_destination = net; } /* Validate primary is first */ net = TAILQ_FIRST(&stcb->asoc.nets); if ((net != stcb->asoc.primary_destination) && (stcb->asoc.primary_destination)) { /* first one on the list is NOT the primary * sctp_cmpaddr() is much more efficient if * the primary is the first on the list, make it * so. */ TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next); TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next); } return (0); } static uint32_t sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb) { uint32_t id; struct sctpasochead *head; struct sctp_tcb *lstcb; try_again: if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { /* TSNH */ return (0); } /* * We don't allow assoc id to be one of SCTP_FUTURE_ASSOC, * SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC. */ if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) { inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1; } id = inp->sctp_associd_counter; inp->sctp_associd_counter++; lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0); if (lstcb) { goto try_again; } head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)]; LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash); stcb->asoc.in_asocid_hash = 1; return (id); } /* * allocate an association and add it to the endpoint. The caller must be * careful to add all additional addresses once they are know right away or * else the assoc will be may experience a blackout scenario. */ static struct sctp_tcb * sctp_aloc_assoc_locked(struct sctp_inpcb *inp, struct sockaddr *firstaddr, int *error, uint32_t override_tag, uint32_t initial_tsn, uint32_t vrf_id, uint16_t o_streams, uint16_t port, #if defined(__FreeBSD__) && !defined(__Userspace__) struct thread *p, #elif defined(_WIN32) && !defined(__Userspace__) PKTHREAD p, #else #if defined(__Userspace__) /* __Userspace__ NULL proc is going to be passed here. See sctp_lower_sosend */ #endif struct proc *p, #endif int initialize_auth_params) { /* note the p argument is only valid in unbound sockets */ struct sctp_tcb *stcb; struct sctp_association *asoc; struct sctpasochead *head; uint16_t rport; int err; SCTP_INP_INFO_WLOCK_ASSERT(); SCTP_INP_WLOCK_ASSERT(inp); /* * Assumption made here: Caller has done a * sctp_findassociation_ep_addr(ep, addr's); to make sure the * address does not exist already. */ if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) { /* Hit max assoc, sorry no more */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS); *error = ENOBUFS; return (NULL); } if (firstaddr == NULL) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) && ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) || (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) { /* * If its in the TCP pool, its NOT allowed to create an * association. The parent listener needs to call * sctp_aloc_assoc.. or the one-2-many socket. If a peeled * off, or connected one does this.. its an error. */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) || (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) { if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) || (inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } } SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:"); #ifdef SCTP_DEBUG if (firstaddr) { SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr); switch (firstaddr->sa_family) { #ifdef INET case AF_INET: SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n", ntohs(((struct sockaddr_in *)firstaddr)->sin_port)); break; #endif #ifdef INET6 case AF_INET6: SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n", ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port)); break; #endif #if defined(__Userspace__) case AF_CONN: SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n", ntohs(((struct sockaddr_conn *)firstaddr)->sconn_port)); break; #endif default: break; } } else { SCTPDBG(SCTP_DEBUG_PCB3,"None\n"); } #endif /* SCTP_DEBUG */ switch (firstaddr->sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin; sin = (struct sockaddr_in *)firstaddr; if ((ntohs(sin->sin_port) == 0) || (sin->sin_addr.s_addr == INADDR_ANY) || (sin->sin_addr.s_addr == INADDR_BROADCAST) || IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) || #if defined(__Userspace__) (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_CONN) != 0) || (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) != 0) && (SCTP_IPV6_V6ONLY(inp) != 0)))) { #else (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) != 0) && (SCTP_IPV6_V6ONLY(inp) != 0))) { #endif /* Invalid address */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } rport = sin->sin_port; break; } #endif #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)firstaddr; if ((ntohs(sin6->sin6_port) == 0) || IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) || IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) || ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0)) { /* Invalid address */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } rport = sin6->sin6_port; break; } #endif #if defined(__Userspace__) case AF_CONN: { struct sockaddr_conn *sconn; sconn = (struct sockaddr_conn *)firstaddr; if ((ntohs(sconn->sconn_port) == 0) || (sconn->sconn_addr == NULL) || ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_CONN) == 0)) { /* Invalid address */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } rport = sconn->sconn_port; break; } #endif default: /* not supported family type */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL); *error = EINVAL; return (NULL); } if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) { /* * If you have not performed a bind, then we need to do the * ephemeral bind for you. */ if ((err = sctp_inpcb_bind_locked(inp, NULL, NULL, p))) { /* bind error, probably perm */ *error = err; return (NULL); } } stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb); if (stcb == NULL) { /* out of memory? */ SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM); *error = ENOMEM; return (NULL); } SCTP_INCR_ASOC_COUNT(); memset(stcb, 0, sizeof(*stcb)); asoc = &stcb->asoc; SCTP_TCB_LOCK_INIT(stcb); SCTP_TCB_SEND_LOCK_INIT(stcb); stcb->rport = rport; /* setup back pointer's */ stcb->sctp_ep = inp; stcb->sctp_socket = inp->sctp_socket; if ((err = sctp_init_asoc(inp, stcb, override_tag, initial_tsn, vrf_id, o_streams))) { /* failed */ SCTP_TCB_LOCK_DESTROY(stcb); SCTP_TCB_SEND_LOCK_DESTROY(stcb); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb); SCTP_DECR_ASOC_COUNT(); *error = err; return (NULL); } SCTP_TCB_LOCK(stcb); asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb); /* now that my_vtag is set, add it to the hash */ head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))]; /* put it in the bucket in the vtag hash of assoc's for the system */ LIST_INSERT_HEAD(head, stcb, sctp_asocs); if (sctp_add_remote_addr(stcb, firstaddr, NULL, port, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC)) { /* failure.. memory error? */ if (asoc->strmout) { SCTP_FREE(asoc->strmout, SCTP_M_STRMO); asoc->strmout = NULL; } if (asoc->mapping_array) { SCTP_FREE(asoc->mapping_array, SCTP_M_MAP); asoc->mapping_array = NULL; } if (asoc->nr_mapping_array) { SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP); asoc->nr_mapping_array = NULL; } SCTP_DECR_ASOC_COUNT(); SCTP_TCB_UNLOCK(stcb); SCTP_TCB_LOCK_DESTROY(stcb); SCTP_TCB_SEND_LOCK_DESTROY(stcb); LIST_REMOVE(stcb, sctp_asocs); LIST_REMOVE(stcb, sctp_tcbasocidhash); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb); SCTP_INP_WUNLOCK(inp); SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS); *error = ENOBUFS; return (NULL); } /* Init all the timers */ SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer); SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer); SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer); SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer); SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer); SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer); LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist); /* now file the port under the hash as well */ if (inp->sctp_tcbhash != NULL) { head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport, inp->sctp_hashmark)]; LIST_INSERT_HEAD(head, stcb, sctp_tcbhash); } if (initialize_auth_params == SCTP_INITIALIZE_AUTH_PARAMS) { sctp_initialize_auth_params(inp, stcb); } SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb); return (stcb); } struct sctp_tcb * sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr, int *error, uint32_t override_tag, uint32_t initial_tsn, uint32_t vrf_id, uint16_t o_streams, uint16_t port, #if defined(__FreeBSD__) && !defined(__Userspace__) struct thread *p, #elif defined(_WIN32) && !defined(__Userspace__) PKTHREAD p, #else struct proc *p, #endif int initialize_auth_params) { struct sctp_tcb *stcb; SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(inp); stcb = sctp_aloc_assoc_locked(inp, firstaddr, error, override_tag, initial_tsn, vrf_id, o_streams, port, p, initialize_auth_params); SCTP_INP_INFO_WUNLOCK(); SCTP_INP_WUNLOCK(inp); return (stcb); } struct sctp_tcb * sctp_aloc_assoc_connected(struct sctp_inpcb *inp, struct sockaddr *firstaddr, int *error, uint32_t override_tag, uint32_t initial_tsn, uint32_t vrf_id, uint16_t o_streams, uint16_t port, #if defined(__FreeBSD__) && !defined(__Userspace__) struct thread *p, #elif defined(_WIN32) && !defined(__Userspace__) PKTHREAD p, #else struct proc *p, #endif int initialize_auth_params) { struct sctp_tcb *stcb; SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(inp); if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) && SCTP_IS_LISTENING(inp)) { SCTP_INP_INFO_WUNLOCK(); SCTP_INP_WUNLOCK(inp); *error = EINVAL; return (NULL); } stcb = sctp_aloc_assoc_locked(inp, firstaddr, error, override_tag, initial_tsn, vrf_id, o_streams, port, p, initialize_auth_params); SCTP_INP_INFO_WUNLOCK(); if (stcb != NULL && (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) { inp->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED; soisconnecting(inp->sctp_socket); } SCTP_INP_WUNLOCK(inp); return (stcb); } void sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net) { struct sctp_inpcb *inp; struct sctp_association *asoc; inp = stcb->sctp_ep; asoc = &stcb->asoc; asoc->numnets--; TAILQ_REMOVE(&asoc->nets, net, sctp_next); if (net == asoc->primary_destination) { /* Reset primary */ struct sctp_nets *lnet; lnet = TAILQ_FIRST(&asoc->nets); /* Mobility adaptation Ideally, if deleted destination is the primary, it becomes a fast retransmission trigger by the subsequent SET PRIMARY. (by micchie) */ if (sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE) || sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_FASTHANDOFF)) { SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n"); if (asoc->deleted_primary != NULL) { SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n"); goto out; } asoc->deleted_primary = net; atomic_add_int(&net->ref_count, 1); memset(&net->lastsa, 0, sizeof(net->lastsa)); memset(&net->lastsv, 0, sizeof(net->lastsv)); sctp_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_PRIM_DELETED); sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED, stcb->sctp_ep, stcb, NULL); } out: /* Try to find a confirmed primary */ asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0); } if (net == asoc->last_data_chunk_from) { /* Reset primary */ asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets); } if (net == asoc->last_control_chunk_from) { /* Clear net */ asoc->last_control_chunk_from = NULL; } if (net == asoc->last_net_cmt_send_started) { /* Clear net */ asoc->last_net_cmt_send_started = NULL; } if (net == stcb->asoc.alternate) { sctp_free_remote_addr(stcb->asoc.alternate); stcb->asoc.alternate = NULL; } sctp_timer_stop(SCTP_TIMER_TYPE_PATHMTURAISE, inp, stcb, net, SCTP_FROM_SCTP_PCB + SCTP_LOC_9); sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net, SCTP_FROM_SCTP_PCB + SCTP_LOC_10); net->dest_state |= SCTP_ADDR_BEING_DELETED; sctp_free_remote_addr(net); } /* * remove a remote endpoint address from an association, it will fail if the * address does not exist. */ int sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr) { /* * Here we need to remove a remote address. This is quite simple, we * first find it in the list of address for the association * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE * on that item. Note we do not allow it to be removed if there are * no other addresses. */ struct sctp_association *asoc; struct sctp_nets *net, *nnet; asoc = &stcb->asoc; /* locate the address */ TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) { if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) { continue; } if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr, remaddr)) { /* we found the guy */ if (asoc->numnets < 2) { /* Must have at LEAST two remote addresses */ return (-1); } else { sctp_remove_net(stcb, net); return (0); } } } /* not found. */ return (-2); } static bool sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport, uint32_t now) { struct sctpvtaghead *chain; struct sctp_tagblock *twait_block; int i; SCTP_INP_INFO_LOCK_ASSERT(); chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)]; LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) { for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) { if ((twait_block->vtag_block[i].tv_sec_at_expire >= now) && (twait_block->vtag_block[i].v_tag == tag) && (twait_block->vtag_block[i].lport == lport) && (twait_block->vtag_block[i].rport == rport)) { return (true); } } } return (false); } static void sctp_set_vtag_block(struct sctp_timewait *vtag_block, uint32_t time, uint32_t tag, uint16_t lport, uint16_t rport) { vtag_block->tv_sec_at_expire = time; vtag_block->v_tag = tag; vtag_block->lport = lport; vtag_block->rport = rport; } static void sctp_add_vtag_to_timewait(uint32_t tag, uint16_t lport, uint16_t rport) { struct sctpvtaghead *chain; struct sctp_tagblock *twait_block; struct timeval now; uint32_t time; int i; bool set; SCTP_INP_INFO_WLOCK_ASSERT(); (void)SCTP_GETTIME_TIMEVAL(&now); time = (uint32_t)now.tv_sec + SCTP_BASE_SYSCTL(sctp_vtag_time_wait); chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)]; set = false; LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) { /* Block(s) present, lets find space, and expire on the fly */ for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) { if ((twait_block->vtag_block[i].v_tag == 0) && !set) { sctp_set_vtag_block(twait_block->vtag_block + i, time, tag, lport, rport); set = true; continue; } if ((twait_block->vtag_block[i].v_tag != 0) && (twait_block->vtag_block[i].tv_sec_at_expire < (uint32_t)now.tv_sec)) { if (set) { /* Audit expires this guy */ sctp_set_vtag_block(twait_block->vtag_block + i, 0, 0, 0, 0); } else { /* Reuse it for the new tag */ sctp_set_vtag_block(twait_block->vtag_block + i, time, tag, lport, rport); set = true; } } } if (set) { /* * We only do up to the block where we can * place our tag for audits */ break; } } /* Need to add a new block to chain */ if (!set) { SCTP_MALLOC(twait_block, struct sctp_tagblock *, sizeof(struct sctp_tagblock), SCTP_M_TIMW); if (twait_block == NULL) { return; } memset(twait_block, 0, sizeof(struct sctp_tagblock)); LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock); sctp_set_vtag_block(twait_block->vtag_block, time, tag, lport, rport); } } void sctp_clean_up_stream(struct sctp_tcb *stcb, struct sctp_readhead *rh) { struct sctp_tmit_chunk *chk, *nchk; struct sctp_queued_to_read *control, *ncontrol; TAILQ_FOREACH_SAFE(control, rh, next_instrm, ncontrol) { TAILQ_REMOVE(rh, control, next_instrm); control->on_strm_q = 0; if (control->on_read_q == 0) { sctp_free_remote_addr(control->whoFrom); if (control->data) { sctp_m_freem(control->data); control->data = NULL; } } /* Reassembly free? */ TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) { TAILQ_REMOVE(&control->reasm, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); sctp_free_remote_addr(chk->whoTo); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); /*sa_ignore FREED_MEMORY*/ } /* * We don't free the address here * since all the net's were freed * above. */ if (control->on_read_q == 0) { sctp_free_a_readq(stcb, control); } } } /*- * Free the association after un-hashing the remote port. This * function ALWAYS returns holding NO LOCK on the stcb. It DOES * expect that the input to this function IS a locked TCB. * It will return 0, if it did NOT destroy the association (instead * it unlocks it. It will return NON-zero if it either destroyed the * association OR the association is already destroyed. */ int sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location) { int i; struct sctp_association *asoc; struct sctp_nets *net, *nnet; struct sctp_laddr *laddr, *naddr; struct sctp_tmit_chunk *chk, *nchk; struct sctp_asconf_addr *aparam, *naparam; struct sctp_asconf_ack *aack, *naack; struct sctp_stream_reset_list *strrst, *nstrrst; struct sctp_queued_to_read *sq, *nsq; struct sctp_stream_queue_pending *sp, *nsp; sctp_sharedkey_t *shared_key, *nshared_key; struct socket *so; /* first, lets purge the entry from the hash table. */ #if defined(__APPLE__) && !defined(__Userspace__) sctp_lock_assert(SCTP_INP_SO(inp)); #endif #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, stcb, 6); #endif if (stcb->asoc.state == 0) { #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 7); #endif /* there is no asoc, really TSNH :-0 */ return (1); } SCTP_TCB_SEND_LOCK(stcb); if (stcb->asoc.alternate) { sctp_free_remote_addr(stcb->asoc.alternate); stcb->asoc.alternate = NULL; } #if !(defined(__APPLE__) && !defined(__Userspace__)) /* TEMP CODE */ if (stcb->freed_from_where == 0) { /* Only record the first place free happened from */ stcb->freed_from_where = from_location; } /* TEMP CODE */ #endif asoc = &stcb->asoc; if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) || (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) /* nothing around */ so = NULL; else so = inp->sctp_socket; /* * We used timer based freeing if a reader or writer is in the way. * So we first check if we are actually being called from a timer, * if so we abort early if a reader or writer is still in the way. */ if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) && (from_inpcbfree == SCTP_NORMAL_PROC)) { /* * is it the timer driving us? if so are the reader/writers * gone? */ if (stcb->asoc.refcnt) { /* nope, reader or writer in the way */ sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL); /* no asoc destroyed */ SCTP_TCB_SEND_UNLOCK(stcb); SCTP_TCB_UNLOCK(stcb); #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, stcb, 8); #endif return (0); } } /* Now clean up any other timers */ sctp_stop_association_timers(stcb, false); /* Now the read queue needs to be cleaned up (only once) */ if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) { SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_ABOUT_TO_BE_FREED); SCTP_INP_READ_LOCK(inp); TAILQ_FOREACH(sq, &inp->read_queue, next) { if (sq->stcb == stcb) { sq->do_not_ref_stcb = 1; sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn; /* If there is no end, there never * will be now. */ if (sq->end_added == 0) { /* Held for PD-API clear that. */ sq->pdapi_aborted = 1; sq->held_length = 0; if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) { /* * Need to add a PD-API aborted indication. * Setting the control_pdapi assures that it will * be added right after this msg. */ uint32_t strseq; stcb->asoc.control_pdapi = sq; strseq = (sq->sinfo_stream << 16) | (sq->mid & 0x0000ffff); sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION, stcb, SCTP_PARTIAL_DELIVERY_ABORTED, (void *)&strseq, SCTP_SO_LOCKED); stcb->asoc.control_pdapi = NULL; } } /* Add an end to wake them */ sq->end_added = 1; } } SCTP_INP_READ_UNLOCK(inp); if (stcb->block_entry) { SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET); stcb->block_entry->error = ECONNRESET; stcb->block_entry = NULL; } } if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) { /* Someone holds a reference OR the socket is unaccepted yet. */ if ((stcb->asoc.refcnt) || (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) || (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) { SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE); sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL); } if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) || (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) /* nothing around */ so = NULL; if (so) { /* Wake any reader/writers */ sctp_sorwakeup(inp, so); sctp_sowwakeup(inp, so); } SCTP_TCB_SEND_UNLOCK(stcb); SCTP_TCB_UNLOCK(stcb); #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, stcb, 9); #endif /* no asoc destroyed */ return (0); } #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, stcb, 10); #endif /* When I reach here, no others want * to kill the assoc yet.. and I own * the lock. Now its possible an abort * comes in when I do the lock exchange * below to grab all the locks to do * the final take out. to prevent this * we increment the count, which will * start a timer and blow out above thus * assuring us that we hold exclusive * killing of the asoc. Note that * after getting back the TCB lock * we will go ahead and increment the * counter back up and stop any timer * a passing stranger may have started :-S */ if (from_inpcbfree == SCTP_NORMAL_PROC) { atomic_add_int(&stcb->asoc.refcnt, 1); SCTP_TCB_SEND_UNLOCK(stcb); SCTP_TCB_UNLOCK(stcb); SCTP_INP_INFO_WLOCK(); SCTP_INP_WLOCK(inp); SCTP_TCB_LOCK(stcb); SCTP_TCB_SEND_LOCK(stcb); } /* Double check the GONE flag */ if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) || (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) /* nothing around */ so = NULL; if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) || (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) { /* * For TCP type we need special handling when we are * connected. We also include the peel'ed off ones to. */ if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) { inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED; inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED; if (so) { SOCKBUF_LOCK(&so->so_rcv); so->so_state &= ~(SS_ISCONNECTING | SS_ISDISCONNECTING | SS_ISCONFIRMING | SS_ISCONNECTED); so->so_state |= SS_ISDISCONNECTED; #if defined(__APPLE__) && !defined(__Userspace__) socantrcvmore(so); #else socantrcvmore_locked(so); #endif socantsendmore(so); sctp_sowwakeup(inp, so); sctp_sorwakeup(inp, so); SCTP_SOWAKEUP(so); } } } /* Make it invalid too, that way if its * about to run it will abort and return. */ /* re-increment the lock */ if (from_inpcbfree == SCTP_NORMAL_PROC) { atomic_subtract_int(&stcb->asoc.refcnt, 1); } if (stcb->asoc.refcnt) { SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE); sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL); if (from_inpcbfree == SCTP_NORMAL_PROC) { SCTP_INP_INFO_WUNLOCK(); SCTP_INP_WUNLOCK(inp); } SCTP_TCB_SEND_UNLOCK(stcb); SCTP_TCB_UNLOCK(stcb); return (0); } asoc->state = 0; if (inp->sctp_tcbhash) { LIST_REMOVE(stcb, sctp_tcbhash); } if (stcb->asoc.in_asocid_hash) { LIST_REMOVE(stcb, sctp_tcbasocidhash); } if (inp->sctp_socket == NULL) { stcb->sctp_socket = NULL; } /* Now lets remove it from the list of ALL associations in the EP */ LIST_REMOVE(stcb, sctp_tcblist); if (from_inpcbfree == SCTP_NORMAL_PROC) { SCTP_INP_INCR_REF(inp); SCTP_INP_WUNLOCK(inp); } /* pull from vtag hash */ LIST_REMOVE(stcb, sctp_asocs); sctp_add_vtag_to_timewait(asoc->my_vtag, inp->sctp_lport, stcb->rport); /* Now restop the timers to be sure * this is paranoia at is finest! */ sctp_stop_association_timers(stcb, true); /* * The chunk lists and such SHOULD be empty but we check them just * in case. */ /* anything on the wheel needs to be removed */ for (i = 0; i < asoc->streamoutcnt; i++) { struct sctp_stream_out *outs; outs = &asoc->strmout[i]; /* now clean up any chunks here */ TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) { atomic_subtract_int(&asoc->stream_queue_cnt, 1); TAILQ_REMOVE(&outs->outqueue, sp, next); stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, outs, sp); sctp_free_spbufspace(stcb, asoc, sp); if (sp->data) { if (so) { /* Still an open socket - report */ sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb, 0, (void *)sp, SCTP_SO_LOCKED); } if (sp->data) { sctp_m_freem(sp->data); sp->data = NULL; sp->tail_mbuf = NULL; sp->length = 0; } } if (sp->net) { sctp_free_remote_addr(sp->net); sp->net = NULL; } sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED); } } /*sa_ignore FREED_MEMORY*/ TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) { TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp); SCTP_FREE(strrst, SCTP_M_STRESET); } TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) { TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next); if (sq->data) { sctp_m_freem(sq->data); sq->data = NULL; } sctp_free_remote_addr(sq->whoFrom); sq->whoFrom = NULL; sq->stcb = NULL; /* Free the ctl entry */ sctp_free_a_readq(stcb, sq); /*sa_ignore FREED_MEMORY*/ } TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) { TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1); asoc->free_chunk_cnt--; /*sa_ignore FREED_MEMORY*/ } /* pending send queue SHOULD be empty */ TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) { if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) { asoc->strmout[chk->rec.data.sid].chunks_on_queues--; #ifdef INVARIANTS } else { panic("No chunks on the queues for sid %u.", chk->rec.data.sid); #endif } TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next); if (chk->data) { if (so) { /* Still a socket? */ sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb, 0, chk, SCTP_SO_LOCKED); } if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); if (chk->whoTo) { sctp_free_remote_addr(chk->whoTo); chk->whoTo = NULL; } SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); /*sa_ignore FREED_MEMORY*/ } /* sent queue SHOULD be empty */ TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) { if (chk->sent != SCTP_DATAGRAM_NR_ACKED) { if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) { asoc->strmout[chk->rec.data.sid].chunks_on_queues--; #ifdef INVARIANTS } else { panic("No chunks on the queues for sid %u.", chk->rec.data.sid); #endif } } TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next); if (chk->data) { if (so) { /* Still a socket? */ sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb, 0, chk, SCTP_SO_LOCKED); } if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); sctp_free_remote_addr(chk->whoTo); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); /*sa_ignore FREED_MEMORY*/ } #ifdef INVARIANTS for (i = 0; i < stcb->asoc.streamoutcnt; i++) { if (stcb->asoc.strmout[i].chunks_on_queues > 0) { panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i); } } #endif /* control queue MAY not be empty */ TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) { TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); sctp_free_remote_addr(chk->whoTo); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); /*sa_ignore FREED_MEMORY*/ } /* ASCONF queue MAY not be empty */ TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) { TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } if (chk->holds_key_ref) sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED); sctp_free_remote_addr(chk->whoTo); SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk); SCTP_DECR_CHK_COUNT(); /*sa_ignore FREED_MEMORY*/ } if (asoc->mapping_array) { SCTP_FREE(asoc->mapping_array, SCTP_M_MAP); asoc->mapping_array = NULL; } if (asoc->nr_mapping_array) { SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP); asoc->nr_mapping_array = NULL; } /* the stream outs */ if (asoc->strmout) { SCTP_FREE(asoc->strmout, SCTP_M_STRMO); asoc->strmout = NULL; } asoc->strm_realoutsize = asoc->streamoutcnt = 0; if (asoc->strmin) { for (i = 0; i < asoc->streamincnt; i++) { sctp_clean_up_stream(stcb, &asoc->strmin[i].inqueue); sctp_clean_up_stream(stcb, &asoc->strmin[i].uno_inqueue); } SCTP_FREE(asoc->strmin, SCTP_M_STRMI); asoc->strmin = NULL; } asoc->streamincnt = 0; TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) { #ifdef INVARIANTS if (SCTP_BASE_INFO(ipi_count_raddr) == 0) { panic("no net's left alloc'ed, or list points to itself"); } #endif TAILQ_REMOVE(&asoc->nets, net, sctp_next); sctp_free_remote_addr(net); } LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) { /*sa_ignore FREED_MEMORY*/ sctp_remove_laddr(laddr); } /* pending asconf (address) parameters */ TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) { /*sa_ignore FREED_MEMORY*/ TAILQ_REMOVE(&asoc->asconf_queue, aparam, next); SCTP_FREE(aparam,SCTP_M_ASC_ADDR); } TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) { /*sa_ignore FREED_MEMORY*/ TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next); if (aack->data != NULL) { sctp_m_freem(aack->data); } SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack); } /* clean up auth stuff */ if (asoc->local_hmacs) sctp_free_hmaclist(asoc->local_hmacs); if (asoc->peer_hmacs) sctp_free_hmaclist(asoc->peer_hmacs); if (asoc->local_auth_chunks) sctp_free_chunklist(asoc->local_auth_chunks); if (asoc->peer_auth_chunks) sctp_free_chunklist(asoc->peer_auth_chunks); sctp_free_authinfo(&asoc->authinfo); LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) { LIST_REMOVE(shared_key, next); sctp_free_sharedkey(shared_key); /*sa_ignore FREED_MEMORY*/ } /* Insert new items here :> */ /* Get rid of LOCK */ SCTP_TCB_SEND_UNLOCK(stcb); SCTP_TCB_UNLOCK(stcb); SCTP_TCB_LOCK_DESTROY(stcb); SCTP_TCB_SEND_LOCK_DESTROY(stcb); if (from_inpcbfree == SCTP_NORMAL_PROC) { SCTP_INP_INFO_WUNLOCK(); SCTP_INP_RLOCK(inp); } #if defined(__APPLE__) && !defined(__Userspace__) /* TEMP CODE */ stcb->freed_from_where = from_location; #endif #ifdef SCTP_TRACK_FREED_ASOCS if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) { /* now clean up the tasoc itself */ SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb); SCTP_DECR_ASOC_COUNT(); } else { LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist); } #else SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb); SCTP_DECR_ASOC_COUNT(); #endif if (from_inpcbfree == SCTP_NORMAL_PROC) { if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) { /* If its NOT the inp_free calling us AND * sctp_close as been called, we * call back... */ SCTP_INP_RUNLOCK(inp); /* This will start the kill timer (if we are * the last one) since we hold an increment yet. But * this is the only safe way to do this * since otherwise if the socket closes * at the same time we are here we might * collide in the cleanup. */ sctp_inpcb_free(inp, SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE, SCTP_CALLED_DIRECTLY_NOCMPSET); SCTP_INP_DECR_REF(inp); } else { /* The socket is still open. */ SCTP_INP_DECR_REF(inp); SCTP_INP_RUNLOCK(inp); } } /* destroyed the asoc */ #ifdef SCTP_LOG_CLOSING sctp_log_closing(inp, NULL, 11); #endif return (1); } /* * determine if a destination is "reachable" based upon the addresses bound * to the current endpoint (e.g. only v4 or v6 currently bound) */ /* * FIX: if we allow assoc-level bindx(), then this needs to be fixed to use * assoc level v4/v6 flags, as the assoc *may* not have the same address * types bound as its endpoint */ int sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr) { struct sctp_inpcb *inp; int answer; /* * No locks here, the TCB, in all cases is already locked and an * assoc is up. There is either a INP lock by the caller applied (in * asconf case when deleting an address) or NOT in the HB case, * however if HB then the INP increment is up and the INP will not * be removed (on top of the fact that we have a TCB lock). So we * only want to read the sctp_flags, which is either bound-all or * not.. no protection needed since once an assoc is up you can't be * changing your binding. */ inp = stcb->sctp_ep; if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) { /* if bound all, destination is not restricted */ /* * RRS: Question during lock work: Is this correct? If you * are bound-all you still might need to obey the V4--V6 * flags??? IMO this bound-all stuff needs to be removed! */ return (1); } /* NOTE: all "scope" checks are done when local addresses are added */ switch (destaddr->sa_family) { #ifdef INET6 case AF_INET6: answer = inp->ip_inp.inp.inp_vflag & INP_IPV6; break; #endif #ifdef INET case AF_INET: answer = inp->ip_inp.inp.inp_vflag & INP_IPV4; break; #endif #if defined(__Userspace__) case AF_CONN: answer = inp->ip_inp.inp.inp_vflag & INP_CONN; break; #endif default: /* invalid family, so it's unreachable */ answer = 0; break; } return (answer); } /* * update the inp_vflags on an endpoint */ static void sctp_update_ep_vflag(struct sctp_inpcb *inp) { struct sctp_laddr *laddr; /* first clear the flag */ inp->ip_inp.inp.inp_vflag = 0; /* set the flag based on addresses on the ep list */ LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa == NULL) { SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__); continue; } if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) { continue; } switch (laddr->ifa->address.sa.sa_family) { #ifdef INET6 case AF_INET6: inp->ip_inp.inp.inp_vflag |= INP_IPV6; break; #endif #ifdef INET case AF_INET: inp->ip_inp.inp.inp_vflag |= INP_IPV4; break; #endif #if defined(__Userspace__) case AF_CONN: inp->ip_inp.inp.inp_vflag |= INP_CONN; break; #endif default: break; } } } /* * Add the address to the endpoint local address list There is nothing to be * done if we are bound to all addresses */ void sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action) { struct sctp_laddr *laddr; struct sctp_tcb *stcb; int fnd, error = 0; fnd = 0; if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) { /* You are already bound to all. You have it already */ return; } #ifdef INET6 if (ifa->address.sa.sa_family == AF_INET6) { if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) { /* Can't bind a non-useable addr. */ return; } } #endif /* first, is it already present? */ LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa == ifa) { fnd = 1; break; } } if (fnd == 0) { /* Not in the ep list */ error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action); if (error != 0) return; inp->laddr_count++; /* update inp_vflag flags */ switch (ifa->address.sa.sa_family) { #ifdef INET6 case AF_INET6: inp->ip_inp.inp.inp_vflag |= INP_IPV6; break; #endif #ifdef INET case AF_INET: inp->ip_inp.inp.inp_vflag |= INP_IPV4; break; #endif #if defined(__Userspace__) case AF_CONN: inp->ip_inp.inp.inp_vflag |= INP_CONN; break; #endif default: break; } LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) { sctp_add_local_addr_restricted(stcb, ifa); } } return; } /* * select a new (hopefully reachable) destination net (should only be used * when we deleted an ep addr that is the only usable source address to reach * the destination net) */ static void sctp_select_primary_destination(struct sctp_tcb *stcb) { struct sctp_nets *net; TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { /* for now, we'll just pick the first reachable one we find */ if (net->dest_state & SCTP_ADDR_UNCONFIRMED) continue; if (sctp_destination_is_reachable(stcb, (struct sockaddr *)&net->ro._l_addr)) { /* found a reachable destination */ stcb->asoc.primary_destination = net; } } /* I can't there from here! ...we're gonna die shortly... */ } /* * Delete the address from the endpoint local address list. There is nothing * to be done if we are bound to all addresses */ void sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa) { struct sctp_laddr *laddr; int fnd; fnd = 0; if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) { /* You are already bound to all. You have it already */ return; } LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) { if (laddr->ifa == ifa) { fnd = 1; break; } } if (fnd && (inp->laddr_count < 2)) { /* can't delete unless there are at LEAST 2 addresses */ return; } if (fnd) { /* * clean up any use of this address go through our * associations and clear any last_used_address that match * this one for each assoc, see if a new primary_destination * is needed */ struct sctp_tcb *stcb; /* clean up "next_addr_touse" */ if (inp->next_addr_touse == laddr) /* delete this address */ inp->next_addr_touse = NULL; /* clean up "last_used_address" */ LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) { struct sctp_nets *net; SCTP_TCB_LOCK(stcb); if (stcb->asoc.last_used_address == laddr) /* delete this address */ stcb->asoc.last_used_address = NULL; /* Now spin through all the nets and purge any ref to laddr */ TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { if (net->ro._s_addr == laddr->ifa) { /* Yep, purge src address selected */ #if defined(__FreeBSD__) && !defined(__Userspace__) RO_NHFREE(&net->ro); #else sctp_rtentry_t *rt; /* delete this address if cached */ rt = net->ro.ro_rt; if (rt != NULL) { RTFREE(rt); net->ro.ro_rt = NULL; } #endif sctp_free_ifa(net->ro._s_addr); net->ro._s_addr = NULL; net->src_addr_selected = 0; } } SCTP_TCB_UNLOCK(stcb); } /* for each tcb */ /* remove it from the ep list */ sctp_remove_laddr(laddr); inp->laddr_count--; /* update inp_vflag flags */ sctp_update_ep_vflag(inp); } return; } /* * Add the address to the TCB local address restricted list. * This is a "pending" address list (eg. addresses waiting for an * ASCONF-ACK response) and cannot be used as a valid source address. */ void sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa) { struct sctp_laddr *laddr; struct sctpladdr *list; /* * Assumes TCB is locked.. and possibly the INP. May need to * confirm/fix that if we need it and is not the case. */ list = &stcb->asoc.sctp_restricted_addrs; #ifdef INET6 if (ifa->address.sa.sa_family == AF_INET6) { if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) { /* Can't bind a non-existent addr. */ return; } } #endif /* does the address already exist? */ LIST_FOREACH(laddr, list, sctp_nxt_addr) { if (laddr->ifa == ifa) { return; } } /* add to the list */ (void)sctp_insert_laddr(list, ifa, 0); return; } /* * Remove a local address from the TCB local address restricted list */ void sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa) { struct sctp_inpcb *inp; struct sctp_laddr *laddr; /* * This is called by asconf work. It is assumed that a) The TCB is * locked and b) The INP is locked. This is true in as much as I can * trace through the entry asconf code where I did these locks. * Again, the ASCONF code is a bit different in that it does lock * the INP during its work often times. This must be since we don't * want other proc's looking up things while what they are looking * up is changing :-D */ inp = stcb->sctp_ep; /* if subset bound and don't allow ASCONF's, can't delete last */ if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) && sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) { if (stcb->sctp_ep->laddr_count < 2) { /* can't delete last address */ return; } } LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) { /* remove the address if it exists */ if (laddr->ifa == NULL) continue; if (laddr->ifa == ifa) { sctp_remove_laddr(laddr); return; } } /* address not found! */ return; } #if defined(__FreeBSD__) && !defined(__Userspace__) /* sysctl */ static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC; static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR; #endif #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SCTP_MCORE_INPUT) && defined(SMP) struct sctp_mcore_ctrl *sctp_mcore_workers = NULL; int *sctp_cpuarry = NULL; void sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use) { /* Queue a packet to a processor for the specified core */ struct sctp_mcore_queue *qent; struct sctp_mcore_ctrl *wkq; int need_wake = 0; if (sctp_mcore_workers == NULL) { /* Something went way bad during setup */ sctp_input_with_port(m, off, 0); return; } SCTP_MALLOC(qent, struct sctp_mcore_queue *, (sizeof(struct sctp_mcore_queue)), SCTP_M_MCORE); if (qent == NULL) { /* This is trouble */ sctp_input_with_port(m, off, 0); return; } qent->vn = curvnet; qent->m = m; qent->off = off; qent->v6 = 0; wkq = &sctp_mcore_workers[cpu_to_use]; SCTP_MCORE_QLOCK(wkq); TAILQ_INSERT_TAIL(&wkq->que, qent, next); if (wkq->running == 0) { need_wake = 1; } SCTP_MCORE_QUNLOCK(wkq); if (need_wake) { wakeup(&wkq->running); } } static void sctp_mcore_thread(void *arg) { struct sctp_mcore_ctrl *wkq; struct sctp_mcore_queue *qent; wkq = (struct sctp_mcore_ctrl *)arg; struct mbuf *m; int off, v6; /* Wait for first tickle */ SCTP_MCORE_LOCK(wkq); wkq->running = 0; msleep(&wkq->running, &wkq->core_mtx, 0, "wait for pkt", 0); SCTP_MCORE_UNLOCK(wkq); /* Bind to our cpu */ thread_lock(curthread); sched_bind(curthread, wkq->cpuid); thread_unlock(curthread); /* Now lets start working */ SCTP_MCORE_LOCK(wkq); /* Now grab lock and go */ for (;;) { SCTP_MCORE_QLOCK(wkq); skip_sleep: wkq->running = 1; qent = TAILQ_FIRST(&wkq->que); if (qent) { TAILQ_REMOVE(&wkq->que, qent, next); SCTP_MCORE_QUNLOCK(wkq); CURVNET_SET(qent->vn); m = qent->m; off = qent->off; v6 = qent->v6; SCTP_FREE(qent, SCTP_M_MCORE); if (v6 == 0) { sctp_input_with_port(m, off, 0); } else { SCTP_PRINTF("V6 not yet supported\n"); sctp_m_freem(m); } CURVNET_RESTORE(); SCTP_MCORE_QLOCK(wkq); } wkq->running = 0; if (!TAILQ_EMPTY(&wkq->que)) { goto skip_sleep; } SCTP_MCORE_QUNLOCK(wkq); msleep(&wkq->running, &wkq->core_mtx, 0, "wait for pkt", 0); } } static void sctp_startup_mcore_threads(void) { int i, cpu; if (mp_ncpus == 1) return; if (sctp_mcore_workers != NULL) { /* Already been here in some previous * vnet? */ return; } SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *, ((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl)), SCTP_M_MCORE); if (sctp_mcore_workers == NULL) { /* TSNH I hope */ return; } memset(sctp_mcore_workers, 0 , ((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl))); /* Init the structures */ for (i = 0; i<=mp_maxid; i++) { TAILQ_INIT(&sctp_mcore_workers[i].que); SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]); SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]); sctp_mcore_workers[i].cpuid = i; } if (sctp_cpuarry == NULL) { SCTP_MALLOC(sctp_cpuarry, int *, (mp_ncpus * sizeof(int)), SCTP_M_MCORE); i = 0; CPU_FOREACH(cpu) { sctp_cpuarry[i] = cpu; i++; } } /* Now start them all */ CPU_FOREACH(cpu) { (void)kproc_create(sctp_mcore_thread, (void *)&sctp_mcore_workers[cpu], &sctp_mcore_workers[cpu].thread_proc, 0, SCTP_KTHREAD_PAGES, SCTP_MCORE_NAME); } } #endif #endif #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SCTP_NOT_YET) static struct mbuf * sctp_netisr_hdlr(struct mbuf *m, uintptr_t source) { struct ip *ip; struct sctphdr *sh; int offset; uint32_t flowid, tag; /* * No flow id built by lower layers fix it so we * create one. */ ip = mtod(m, struct ip *); offset = (ip->ip_hl << 2) + sizeof(struct sctphdr); if (SCTP_BUF_LEN(m) < offset) { if ((m = m_pullup(m, offset)) == NULL) { SCTP_STAT_INCR(sctps_hdrops); return (NULL); } ip = mtod(m, struct ip *); } sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2)); tag = htonl(sh->v_tag); flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port); m->m_pkthdr.flowid = flowid; /* FIX ME */ m->m_flags |= M_FLOWID; return (m); } #endif #endif void #if defined(__Userspace__) sctp_pcb_init(int start_threads) #else sctp_pcb_init(void) #endif { /* * SCTP initialization for the PCB structures should be called by * the sctp_init() function. */ int i; struct timeval tv; if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) { /* error I was called twice */ return; } SCTP_BASE_VAR(sctp_pcb_initialized) = 1; #if defined(SCTP_PROCESS_LEVEL_LOCKS) #if !defined(_WIN32) pthread_mutexattr_init(&SCTP_BASE_VAR(mtx_attr)); pthread_rwlockattr_init(&SCTP_BASE_VAR(rwlock_attr)); #ifdef INVARIANTS pthread_mutexattr_settype(&SCTP_BASE_VAR(mtx_attr), PTHREAD_MUTEX_ERRORCHECK); #endif #endif #endif #if defined(SCTP_LOCAL_TRACE_BUF) #if defined(_WIN32) && !defined(__Userspace__) if (SCTP_BASE_SYSCTL(sctp_log) != NULL) { memset(SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log)); } #else memset(&SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log)); #endif #endif #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT) SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *, ((mp_maxid+1) * sizeof(struct sctpstat)), SCTP_M_MCORE); #endif #endif (void)SCTP_GETTIME_TIMEVAL(&tv); #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT) memset(SCTP_BASE_STATS, 0, sizeof(struct sctpstat) * (mp_maxid+1)); SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec; SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec; #else memset(&SCTP_BASE_STATS, 0, sizeof(struct sctpstat)); SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec; SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec; #endif #else memset(&SCTP_BASE_STATS, 0, sizeof(struct sctpstat)); SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec; SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec; #endif /* init the empty list of (All) Endpoints */ LIST_INIT(&SCTP_BASE_INFO(listhead)); #if defined(__APPLE__) && !defined(__Userspace__) LIST_INIT(&SCTP_BASE_INFO(inplisthead)); #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION) SCTP_BASE_INFO(sctbinfo).listhead = &SCTP_BASE_INFO(inplisthead); SCTP_BASE_INFO(sctbinfo).mtx_grp_attr = lck_grp_attr_alloc_init(); lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr); SCTP_BASE_INFO(sctbinfo).mtx_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).mtx_grp_attr); SCTP_BASE_INFO(sctbinfo).mtx_attr = lck_attr_alloc_init(); lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_attr); #else SCTP_BASE_INFO(sctbinfo).ipi_listhead = &SCTP_BASE_INFO(inplisthead); SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr = lck_grp_attr_alloc_init(); lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr); SCTP_BASE_INFO(sctbinfo).ipi_lock_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr); SCTP_BASE_INFO(sctbinfo).ipi_lock_attr = lck_attr_alloc_init(); lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr); #endif #if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION) SCTP_BASE_INFO(sctbinfo).ipi_gc = sctp_gc; in_pcbinfo_attach(&SCTP_BASE_INFO(sctbinfo)); #endif #endif /* init the hash table of endpoints */ #if defined(__FreeBSD__) && !defined(__Userspace__) TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize)); TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize)); TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale)); #endif SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31), &SCTP_BASE_INFO(hashasocmark)); SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize), &SCTP_BASE_INFO(hashmark)); SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize), &SCTP_BASE_INFO(hashtcpmark)); SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize); SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH, &SCTP_BASE_INFO(hashvrfmark)); SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE, &SCTP_BASE_INFO(vrf_ifn_hashmark)); /* init the zones */ /* * FIX ME: Should check for NULL returns, but if it does fail we are * doomed to panic anyways... add later maybe. */ SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep", sizeof(struct sctp_inpcb), maxsockets); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc", sizeof(struct sctp_tcb), sctp_max_number_of_assoc); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr", sizeof(struct sctp_laddr), (sctp_max_number_of_assoc * sctp_scale_up_for_address)); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr", sizeof(struct sctp_nets), (sctp_max_number_of_assoc * sctp_scale_up_for_address)); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk", sizeof(struct sctp_tmit_chunk), (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale))); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq", sizeof(struct sctp_queued_to_read), (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale))); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out", sizeof(struct sctp_stream_queue_pending), (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale))); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf", sizeof(struct sctp_asconf), (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale))); SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack", sizeof(struct sctp_asconf_ack), (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale))); /* Master Lock INIT for info structure */ SCTP_INP_INFO_LOCK_INIT(); SCTP_STATLOG_INIT_LOCK(); SCTP_IPI_COUNT_INIT(); SCTP_IPI_ADDR_INIT(); #ifdef SCTP_PACKET_LOGGING SCTP_IP_PKTLOG_INIT(); #endif LIST_INIT(&SCTP_BASE_INFO(addr_wq)); SCTP_WQ_ADDR_INIT(); /* not sure if we need all the counts */ SCTP_BASE_INFO(ipi_count_ep) = 0; /* assoc/tcb zone info */ SCTP_BASE_INFO(ipi_count_asoc) = 0; /* local addrlist zone info */ SCTP_BASE_INFO(ipi_count_laddr) = 0; /* remote addrlist zone info */ SCTP_BASE_INFO(ipi_count_raddr) = 0; /* chunk info */ SCTP_BASE_INFO(ipi_count_chunk) = 0; /* socket queue zone info */ SCTP_BASE_INFO(ipi_count_readq) = 0; /* stream out queue cont */ SCTP_BASE_INFO(ipi_count_strmoq) = 0; SCTP_BASE_INFO(ipi_free_strmoq) = 0; SCTP_BASE_INFO(ipi_free_chunks) = 0; SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer)); /* Init the TIMEWAIT list */ for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) { LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]); } #if defined(SCTP_PROCESS_LEVEL_LOCKS) #if defined(_WIN32) InitializeConditionVariable(&sctp_it_ctl.iterator_wakeup); #else (void)pthread_cond_init(&sctp_it_ctl.iterator_wakeup, NULL); #endif #endif sctp_startup_iterator(); #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SCTP_MCORE_INPUT) && defined(SMP) sctp_startup_mcore_threads(); #endif #endif /* * INIT the default VRF which for BSD is the only one, other O/S's * may have more. But initially they must start with one and then * add the VRF's as addresses are added. */ sctp_init_vrf_list(SCTP_DEFAULT_VRF); #if defined(__FreeBSD__) && !defined(__Userspace__) && defined(SCTP_NOT_YET) if (ip_register_flow_handler(sctp_netisr_hdlr, IPPROTO_SCTP)) { SCTP_PRINTF("***SCTP- Error can't register netisr handler***\n"); } #endif #if defined(_SCTP_NEEDS_CALLOUT_) || defined(_USER_SCTP_NEEDS_CALLOUT_) /* allocate the lock for the callout/timer queue */ SCTP_TIMERQ_LOCK_INIT(); TAILQ_INIT(&SCTP_BASE_INFO(callqueue)); #endif #if defined(__Userspace__) mbuf_initialize(NULL); atomic_init(); #if defined(INET) || defined(INET6) if (start_threads) recv_thread_init(); #endif #endif } /* * Assumes that the SCTP_BASE_INFO() lock is NOT held. */ void sctp_pcb_finish(void) { struct sctp_vrflist *vrf_bucket; struct sctp_vrf *vrf, *nvrf; struct sctp_ifn *ifn, *nifn; struct sctp_ifa *ifa, *nifa; struct sctpvtaghead *chain; struct sctp_tagblock *twait_block, *prev_twait_block; struct sctp_laddr *wi, *nwi; int i; struct sctp_iterator *it, *nit; if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) { SCTP_PRINTF("%s: race condition on teardown.\n", __func__); return; } SCTP_BASE_VAR(sctp_pcb_initialized) = 0; #if !(defined(__FreeBSD__) && !defined(__Userspace__)) /* Notify the iterator to exit. */ SCTP_IPI_ITERATOR_WQ_LOCK(); sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_MUST_EXIT; sctp_wakeup_iterator(); SCTP_IPI_ITERATOR_WQ_UNLOCK(); #endif #if defined(__APPLE__) && !defined(__Userspace__) #if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION) in_pcbinfo_detach(&SCTP_BASE_INFO(sctbinfo)); #endif SCTP_IPI_ITERATOR_WQ_LOCK(); do { msleep(&sctp_it_ctl.iterator_flags, sctp_it_ctl.ipi_iterator_wq_mtx, 0, "waiting_for_work", 0); } while ((sctp_it_ctl.iterator_flags & SCTP_ITERATOR_EXITED) == 0); thread_deallocate(sctp_it_ctl.thread_proc); SCTP_IPI_ITERATOR_WQ_UNLOCK(); #endif #if defined(_WIN32) && !defined(__Userspace__) if (sctp_it_ctl.iterator_thread_obj != NULL) { NTSTATUS status = STATUS_SUCCESS; KeSetEvent(&sctp_it_ctl.iterator_wakeup[1], IO_NO_INCREMENT, FALSE); status = KeWaitForSingleObject(sctp_it_ctl.iterator_thread_obj, Executive, KernelMode, FALSE, NULL); ObDereferenceObject(sctp_it_ctl.iterator_thread_obj); } #endif #if defined(__Userspace__) if (SCTP_BASE_VAR(iterator_thread_started)) { #if defined(_WIN32) WaitForSingleObject(sctp_it_ctl.thread_proc, INFINITE); CloseHandle(sctp_it_ctl.thread_proc); sctp_it_ctl.thread_proc = NULL; #else pthread_join(sctp_it_ctl.thread_proc, NULL); sctp_it_ctl.thread_proc = 0; #endif } #endif #if defined(SCTP_PROCESS_LEVEL_LOCKS) #if defined(_WIN32) DeleteConditionVariable(&sctp_it_ctl.iterator_wakeup); #else pthread_cond_destroy(&sctp_it_ctl.iterator_wakeup); pthread_mutexattr_destroy(&SCTP_BASE_VAR(mtx_attr)); pthread_rwlockattr_destroy(&SCTP_BASE_VAR(rwlock_attr)); #endif #endif /* In FreeBSD the iterator thread never exits * but we do clean up. * The only way FreeBSD reaches here is if we have VRF's * but we still add the ifdef to make it compile on old versions. */ #if defined(__FreeBSD__) && !defined(__Userspace__) retry: #endif SCTP_IPI_ITERATOR_WQ_LOCK(); #if defined(__FreeBSD__) && !defined(__Userspace__) /* * sctp_iterator_worker() might be working on an it entry without * holding the lock. We won't find it on the list either and * continue and free/destroy it. While holding the lock, spin, to * avoid the race condition as sctp_iterator_worker() will have to * wait to re-acquire the lock. */ if (sctp_it_ctl.iterator_running != 0 || sctp_it_ctl.cur_it != NULL) { SCTP_IPI_ITERATOR_WQ_UNLOCK(); SCTP_PRINTF("%s: Iterator running while we held the lock. Retry. " "cur_it=%p\n", __func__, sctp_it_ctl.cur_it); DELAY(10); goto retry; } #endif TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) { #if defined(__FreeBSD__) && !defined(__Userspace__) if (it->vn != curvnet) { continue; } #endif TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr); if (it->function_atend != NULL) { (*it->function_atend) (it->pointer, it->val); } SCTP_FREE(it,SCTP_M_ITER); } SCTP_IPI_ITERATOR_WQ_UNLOCK(); #if defined(__FreeBSD__) && !defined(__Userspace__) SCTP_ITERATOR_LOCK(); if ((sctp_it_ctl.cur_it) && (sctp_it_ctl.cur_it->vn == curvnet)) { sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT; } SCTP_ITERATOR_UNLOCK(); #endif #if !(defined(__FreeBSD__) && !defined(__Userspace__)) SCTP_IPI_ITERATOR_WQ_DESTROY(); SCTP_ITERATOR_LOCK_DESTROY(); #endif SCTP_OS_TIMER_STOP_DRAIN(&SCTP_BASE_INFO(addr_wq_timer.timer)); SCTP_WQ_ADDR_LOCK(); LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) { LIST_REMOVE(wi, sctp_nxt_addr); SCTP_DECR_LADDR_COUNT(); if (wi->action == SCTP_DEL_IP_ADDRESS) { SCTP_FREE(wi->ifa, SCTP_M_IFA); } SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi); } SCTP_WQ_ADDR_UNLOCK(); /* * free the vrf/ifn/ifa lists and hashes (be sure address monitor * is destroyed first). */ SCTP_IPI_ADDR_WLOCK(); vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))]; LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) { LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) { LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) { /* free the ifa */ LIST_REMOVE(ifa, next_bucket); LIST_REMOVE(ifa, next_ifa); SCTP_FREE(ifa, SCTP_M_IFA); } /* free the ifn */ LIST_REMOVE(ifn, next_bucket); LIST_REMOVE(ifn, next_ifn); SCTP_FREE(ifn, SCTP_M_IFN); } SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark); /* free the vrf */ LIST_REMOVE(vrf, next_vrf); SCTP_FREE(vrf, SCTP_M_VRF); } SCTP_IPI_ADDR_WUNLOCK(); /* free the vrf hashes */ SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark)); SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark)); /* free the TIMEWAIT list elements malloc'd in the function * sctp_add_vtag_to_timewait()... */ for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) { chain = &SCTP_BASE_INFO(vtag_timewait)[i]; if (!LIST_EMPTY(chain)) { prev_twait_block = NULL; LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) { if (prev_twait_block) { SCTP_FREE(prev_twait_block, SCTP_M_TIMW); } prev_twait_block = twait_block; } SCTP_FREE(prev_twait_block, SCTP_M_TIMW); } } /* free the locks and mutexes */ #if defined(__APPLE__) && !defined(__Userspace__) SCTP_TIMERQ_LOCK_DESTROY(); #endif #ifdef SCTP_PACKET_LOGGING SCTP_IP_PKTLOG_DESTROY(); #endif SCTP_IPI_ADDR_DESTROY(); #if defined(__APPLE__) && !defined(__Userspace__) SCTP_IPI_COUNT_DESTROY(); #endif SCTP_STATLOG_DESTROY(); SCTP_INP_INFO_LOCK_DESTROY(); SCTP_WQ_ADDR_DESTROY(); #if defined(__APPLE__) && !defined(__Userspace__) #if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION) lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr); lck_grp_free(SCTP_BASE_INFO(sctbinfo).mtx_grp); lck_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_attr); #else lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr); lck_grp_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp); lck_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr); #endif #endif #if defined(__Userspace__) SCTP_TIMERQ_LOCK_DESTROY(); SCTP_ZONE_DESTROY(zone_mbuf); SCTP_ZONE_DESTROY(zone_clust); SCTP_ZONE_DESTROY(zone_ext_refcnt); #endif /* Get rid of other stuff too. */ if (SCTP_BASE_INFO(sctp_asochash) != NULL) SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark)); if (SCTP_BASE_INFO(sctp_ephash) != NULL) SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark)); if (SCTP_BASE_INFO(sctp_tcpephash) != NULL) SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark)); #if defined(_WIN32) || defined(__FreeBSD__) || defined(__Userspace__) SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf)); SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack)); #endif #if defined(__FreeBSD__) && !defined(__Userspace__) #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT) SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE); #endif #endif } int sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m, int offset, int limit, struct sockaddr *src, struct sockaddr *dst, struct sockaddr *altsa, uint16_t port) { /* * grub through the INIT pulling addresses and loading them to the * nets structure in the asoc. The from address in the mbuf should * also be loaded (if it is not already). This routine can be called * with either INIT or INIT-ACK's as long as the m points to the IP * packet and the offset points to the beginning of the parameters. */ struct sctp_inpcb *inp; struct sctp_nets *net, *nnet, *net_tmp; struct sctp_paramhdr *phdr, param_buf; struct sctp_tcb *stcb_tmp; uint16_t ptype, plen; struct sockaddr *sa; uint8_t random_store[SCTP_PARAM_BUFFER_SIZE]; struct sctp_auth_random *p_random = NULL; uint16_t random_len = 0; uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE]; struct sctp_auth_hmac_algo *hmacs = NULL; uint16_t hmacs_len = 0; uint8_t saw_asconf = 0; uint8_t saw_asconf_ack = 0; uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE]; struct sctp_auth_chunk_list *chunks = NULL; uint16_t num_chunks = 0; sctp_key_t *new_key; uint32_t keylen; int got_random = 0, got_hmacs = 0, got_chklist = 0; uint8_t peer_supports_ecn; uint8_t peer_supports_prsctp; uint8_t peer_supports_auth; uint8_t peer_supports_asconf; uint8_t peer_supports_asconf_ack; uint8_t peer_supports_reconfig; uint8_t peer_supports_nrsack; uint8_t peer_supports_pktdrop; uint8_t peer_supports_idata; #ifdef INET struct sockaddr_in sin; #endif #ifdef INET6 struct sockaddr_in6 sin6; #endif /* First get the destination address setup too. */ #ifdef INET memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; #ifdef HAVE_SIN_LEN sin.sin_len = sizeof(sin); #endif sin.sin_port = stcb->rport; #endif #ifdef INET6 memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; #ifdef HAVE_SIN6_LEN sin6.sin6_len = sizeof(struct sockaddr_in6); #endif sin6.sin6_port = stcb->rport; #endif if (altsa) { sa = altsa; } else { sa = src; } peer_supports_idata = 0; peer_supports_ecn = 0; peer_supports_prsctp = 0; peer_supports_auth = 0; peer_supports_asconf = 0; peer_supports_asconf_ack = 0; peer_supports_reconfig = 0; peer_supports_nrsack = 0; peer_supports_pktdrop = 0; TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) { /* mark all addresses that we have currently on the list */ net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC; } /* does the source address already exist? if so skip it */ inp = stcb->sctp_ep; atomic_add_int(&stcb->asoc.refcnt, 1); stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb); atomic_subtract_int(&stcb->asoc.refcnt, 1); if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) { /* we must add the source address */ /* no scope set here since we have a tcb already. */ switch (sa->sa_family) { #ifdef INET case AF_INET: if (stcb->asoc.scope.ipv4_addr_legal) { if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) { return (-1); } } break; #endif #ifdef INET6 case AF_INET6: if (stcb->asoc.scope.ipv6_addr_legal) { if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) { return (-2); } } break; #endif #if defined(__Userspace__) case AF_CONN: if (stcb->asoc.scope.conn_addr_legal) { if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) { return (-2); } } break; #endif default: break; } } else { if (net_tmp != NULL && stcb_tmp == stcb) { net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC; } else if (stcb_tmp != stcb) { /* It belongs to another association? */ if (stcb_tmp) SCTP_TCB_UNLOCK(stcb_tmp); return (-3); } } if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-4); } /* now we must go through each of the params. */ phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf)); while (phdr) { ptype = ntohs(phdr->param_type); plen = ntohs(phdr->param_length); /* * SCTP_PRINTF("ptype => %0x, plen => %d\n", (uint32_t)ptype, * (int)plen); */ if (offset + plen > limit) { break; } if (plen < sizeof(struct sctp_paramhdr)) { break; } #ifdef INET if (ptype == SCTP_IPV4_ADDRESS) { if (stcb->asoc.scope.ipv4_addr_legal) { struct sctp_ipv4addr_param *p4, p4_buf; /* ok get the v4 address and check/add */ phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf)); if (plen != sizeof(struct sctp_ipv4addr_param) || phdr == NULL) { return (-5); } p4 = (struct sctp_ipv4addr_param *)phdr; sin.sin_addr.s_addr = p4->addr; if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) { /* Skip multi-cast addresses */ goto next_param; } if ((sin.sin_addr.s_addr == INADDR_BROADCAST) || (sin.sin_addr.s_addr == INADDR_ANY)) { goto next_param; } sa = (struct sockaddr *)&sin; inp = stcb->sctp_ep; atomic_add_int(&stcb->asoc.refcnt, 1); stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net, dst, stcb); atomic_subtract_int(&stcb->asoc.refcnt, 1); if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) { /* we must add the source address */ /* * no scope set since we have a tcb * already */ /* * we must validate the state again * here */ add_it_now: if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-7); } if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) { return (-8); } } else if (stcb_tmp == stcb) { if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-10); } if (net != NULL) { /* clear flag */ net->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC; } } else { /* * strange, address is in another * assoc? straighten out locks. */ if (stcb_tmp) { if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) { struct mbuf *op_err; char msg[SCTP_DIAG_INFO_LEN]; /* in setup state we abort this guy */ SCTP_SNPRINTF(msg, sizeof(msg), "%s:%d at %s", __FILE__, __LINE__, __func__); op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code), msg); sctp_abort_an_association(stcb_tmp->sctp_ep, stcb_tmp, op_err, false, SCTP_SO_NOT_LOCKED); goto add_it_now; } SCTP_TCB_UNLOCK(stcb_tmp); } if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-12); } return (-13); } } } else #endif #ifdef INET6 if (ptype == SCTP_IPV6_ADDRESS) { if (stcb->asoc.scope.ipv6_addr_legal) { /* ok get the v6 address and check/add */ struct sctp_ipv6addr_param *p6, p6_buf; phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf)); if (plen != sizeof(struct sctp_ipv6addr_param) || phdr == NULL) { return (-14); } p6 = (struct sctp_ipv6addr_param *)phdr; memcpy((caddr_t)&sin6.sin6_addr, p6->addr, sizeof(p6->addr)); if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) { /* Skip multi-cast addresses */ goto next_param; } if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) { /* Link local make no sense without scope */ goto next_param; } sa = (struct sockaddr *)&sin6; inp = stcb->sctp_ep; atomic_add_int(&stcb->asoc.refcnt, 1); stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net, dst, stcb); atomic_subtract_int(&stcb->asoc.refcnt, 1); if (stcb_tmp == NULL && (inp == stcb->sctp_ep || inp == NULL)) { /* * we must validate the state again * here */ add_it_now6: if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-16); } /* * we must add the address, no scope * set */ if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) { return (-17); } } else if (stcb_tmp == stcb) { /* * we must validate the state again * here */ if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-19); } if (net != NULL) { /* clear flag */ net->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC; } } else { /* * strange, address is in another * assoc? straighten out locks. */ if (stcb_tmp) { if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) { struct mbuf *op_err; char msg[SCTP_DIAG_INFO_LEN]; /* in setup state we abort this guy */ SCTP_SNPRINTF(msg, sizeof(msg), "%s:%d at %s", __FILE__, __LINE__, __func__); op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code), msg); sctp_abort_an_association(stcb_tmp->sctp_ep, stcb_tmp, op_err, false, SCTP_SO_NOT_LOCKED); goto add_it_now6; } SCTP_TCB_UNLOCK(stcb_tmp); } if (stcb->asoc.state == 0) { /* the assoc was freed? */ return (-21); } return (-22); } } } else #endif if (ptype == SCTP_ECN_CAPABLE) { peer_supports_ecn = 1; } else if (ptype == SCTP_ULP_ADAPTATION) { if (stcb->asoc.state != SCTP_STATE_OPEN) { struct sctp_adaptation_layer_indication ai, *aip; phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&ai, sizeof(ai)); aip = (struct sctp_adaptation_layer_indication *)phdr; if (aip) { stcb->asoc.peers_adaptation = ntohl(aip->indication); stcb->asoc.adaptation_needed = 1; } } } else if (ptype == SCTP_SET_PRIM_ADDR) { struct sctp_asconf_addr_param lstore, *fee; int lptype; struct sockaddr *lsa = NULL; #ifdef INET struct sctp_asconf_addrv4_param *fii; #endif if (stcb->asoc.asconf_supported == 0) { return (-100); } if (plen > sizeof(lstore)) { return (-23); } if (plen < sizeof(struct sctp_asconf_addrv4_param)) { return (-101); } phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&lstore, plen); if (phdr == NULL) { return (-24); } fee = (struct sctp_asconf_addr_param *)phdr; lptype = ntohs(fee->addrp.ph.param_type); switch (lptype) { #ifdef INET case SCTP_IPV4_ADDRESS: if (plen != sizeof(struct sctp_asconf_addrv4_param)) { SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n", (int)sizeof(struct sctp_asconf_addrv4_param), plen); } else { fii = (struct sctp_asconf_addrv4_param *)fee; sin.sin_addr.s_addr = fii->addrp.addr; lsa = (struct sockaddr *)&sin; } break; #endif #ifdef INET6 case SCTP_IPV6_ADDRESS: if (plen != sizeof(struct sctp_asconf_addr_param)) { SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n", (int)sizeof(struct sctp_asconf_addr_param), plen); } else { memcpy(sin6.sin6_addr.s6_addr, fee->addrp.addr, sizeof(fee->addrp.addr)); lsa = (struct sockaddr *)&sin6; } break; #endif default: break; } if (lsa) { (void)sctp_set_primary_addr(stcb, sa, NULL); } } else if (ptype == SCTP_HAS_NAT_SUPPORT) { stcb->asoc.peer_supports_nat = 1; } else if (ptype == SCTP_PRSCTP_SUPPORTED) { /* Peer supports pr-sctp */ peer_supports_prsctp = 1; } else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) { /* A supported extension chunk */ struct sctp_supported_chunk_types_param *pr_supported; uint8_t local_store[SCTP_PARAM_BUFFER_SIZE]; int num_ent, i; if (plen > sizeof(local_store)) { return (-35); } phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)&local_store, plen); if (phdr == NULL) { return (-25); } pr_supported = (struct sctp_supported_chunk_types_param *)phdr; num_ent = plen - sizeof(struct sctp_paramhdr); for (i = 0; i < num_ent; i++) { switch (pr_supported->chunk_types[i]) { case SCTP_ASCONF: peer_supports_asconf = 1; break; case SCTP_ASCONF_ACK: peer_supports_asconf_ack = 1; break; case SCTP_FORWARD_CUM_TSN: peer_supports_prsctp = 1; break; case SCTP_PACKET_DROPPED: peer_supports_pktdrop = 1; break; case SCTP_NR_SELECTIVE_ACK: peer_supports_nrsack = 1; break; case SCTP_STREAM_RESET: peer_supports_reconfig = 1; break; case SCTP_AUTHENTICATION: peer_supports_auth = 1; break; case SCTP_IDATA: peer_supports_idata = 1; break; default: /* one I have not learned yet */ break; } } } else if (ptype == SCTP_RANDOM) { if (plen > sizeof(random_store)) break; if (got_random) { /* already processed a RANDOM */ goto next_param; } phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)random_store, plen); if (phdr == NULL) return (-26); p_random = (struct sctp_auth_random *)phdr; random_len = plen - sizeof(*p_random); /* enforce the random length */ if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) { SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n"); return (-27); } got_random = 1; } else if (ptype == SCTP_HMAC_LIST) { uint16_t num_hmacs; uint16_t i; if (plen > sizeof(hmacs_store)) break; if (got_hmacs) { /* already processed a HMAC list */ goto next_param; } phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)hmacs_store, plen); if (phdr == NULL) return (-28); hmacs = (struct sctp_auth_hmac_algo *)phdr; hmacs_len = plen - sizeof(*hmacs); num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]); /* validate the hmac list */ if (sctp_verify_hmac_param(hmacs, num_hmacs)) { return (-29); } if (stcb->asoc.peer_hmacs != NULL) sctp_free_hmaclist(stcb->asoc.peer_hmacs); stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs); if (stcb->asoc.peer_hmacs != NULL) { for (i = 0; i < num_hmacs; i++) { (void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs, ntohs(hmacs->hmac_ids[i])); } } got_hmacs = 1; } else if (ptype == SCTP_CHUNK_LIST) { int i; if (plen > sizeof(chunks_store)) break; if (got_chklist) { /* already processed a Chunks list */ goto next_param; } phdr = sctp_get_next_param(m, offset, (struct sctp_paramhdr *)chunks_store, plen); if (phdr == NULL) return (-30); chunks = (struct sctp_auth_chunk_list *)phdr; num_chunks = plen - sizeof(*chunks); if (stcb->asoc.peer_auth_chunks != NULL) sctp_clear_chunklist(stcb->asoc.peer_auth_chunks); else stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist(); for (i = 0; i < num_chunks; i++) { (void)sctp_auth_add_chunk(chunks->chunk_types[i], stcb->asoc.peer_auth_chunks); /* record asconf/asconf-ack if listed */ if (chunks->chunk_types[i] == SCTP_ASCONF) saw_asconf = 1; if (chunks->chunk_types[i] == SCTP_ASCONF_ACK) saw_asconf_ack = 1; } got_chklist = 1; } else if ((ptype == SCTP_HEARTBEAT_INFO) || (ptype == SCTP_STATE_COOKIE) || (ptype == SCTP_UNRECOG_PARAM) || (ptype == SCTP_COOKIE_PRESERVE) || (ptype == SCTP_SUPPORTED_ADDRTYPE) || (ptype == SCTP_ADD_IP_ADDRESS) || (ptype == SCTP_DEL_IP_ADDRESS) || (ptype == SCTP_ERROR_CAUSE_IND) || (ptype == SCTP_SUCCESS_REPORT)) { /* don't care */ } else { if ((ptype & 0x8000) == 0x0000) { /* * must stop processing the rest of the * param's. Any report bits were handled * with the call to * sctp_arethere_unrecognized_parameters() * when the INIT or INIT-ACK was first seen. */ break; } } next_param: offset += SCTP_SIZE32(plen); if (offset >= limit) { break; } phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf)); } /* Now check to see if we need to purge any addresses */ TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) { if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) == SCTP_ADDR_NOT_IN_ASSOC) { /* This address has been removed from the asoc */ /* remove and free it */ stcb->asoc.numnets--; TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next); if (net == stcb->asoc.alternate) { sctp_free_remote_addr(stcb->asoc.alternate); stcb->asoc.alternate = NULL; } if (net == stcb->asoc.primary_destination) { stcb->asoc.primary_destination = NULL; sctp_select_primary_destination(stcb); } sctp_free_remote_addr(net); } } if ((stcb->asoc.ecn_supported == 1) && (peer_supports_ecn == 0)) { stcb->asoc.ecn_supported = 0; } if ((stcb->asoc.prsctp_supported == 1) && (peer_supports_prsctp == 0)) { stcb->asoc.prsctp_supported = 0; } if ((stcb->asoc.auth_supported == 1) && ((peer_supports_auth == 0) || (got_random == 0) || (got_hmacs == 0))) { stcb->asoc.auth_supported = 0; } if ((stcb->asoc.asconf_supported == 1) && ((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) || (stcb->asoc.auth_supported == 0) || (saw_asconf == 0) || (saw_asconf_ack == 0))) { stcb->asoc.asconf_supported = 0; } if ((stcb->asoc.reconfig_supported == 1) && (peer_supports_reconfig == 0)) { stcb->asoc.reconfig_supported = 0; } if ((stcb->asoc.idata_supported == 1) && (peer_supports_idata == 0)) { stcb->asoc.idata_supported = 0; } if ((stcb->asoc.nrsack_supported == 1) && (peer_supports_nrsack == 0)) { stcb->asoc.nrsack_supported = 0; } if ((stcb->asoc.pktdrop_supported == 1) && (peer_supports_pktdrop == 0)){ stcb->asoc.pktdrop_supported = 0; } /* validate authentication required parameters */ if ((peer_supports_auth == 0) && (got_chklist == 1)) { /* peer does not support auth but sent a chunks list? */ return (-31); } if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) { /* peer supports asconf but not auth? */ return (-32); } else if ((peer_supports_asconf == 1) && (peer_supports_auth == 1) && ((saw_asconf == 0) || (saw_asconf_ack == 0))) { return (-33); } /* concatenate the full random key */ keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len; if (chunks != NULL) { keylen += sizeof(*chunks) + num_chunks; } new_key = sctp_alloc_key(keylen); if (new_key != NULL) { /* copy in the RANDOM */ if (p_random != NULL) { keylen = sizeof(*p_random) + random_len; memcpy(new_key->key, p_random, keylen); } else { keylen = 0; } /* append in the AUTH chunks */ if (chunks != NULL) { memcpy(new_key->key + keylen, chunks, sizeof(*chunks) + num_chunks); keylen += sizeof(*chunks) + num_chunks; } /* append in the HMACs */ if (hmacs != NULL) { memcpy(new_key->key + keylen, hmacs, sizeof(*hmacs) + hmacs_len); } } else { /* failed to get memory for the key */ return (-34); } if (stcb->asoc.authinfo.peer_random != NULL) sctp_free_key(stcb->asoc.authinfo.peer_random); stcb->asoc.authinfo.peer_random = new_key; sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid); sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid); return (0); } int sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa, struct sctp_nets *net) { /* make sure the requested primary address exists in the assoc */ if (net == NULL && sa) net = sctp_findnet(stcb, sa); if (net == NULL) { /* didn't find the requested primary address! */ return (-1); } else { /* set the primary address */ if (net->dest_state & SCTP_ADDR_UNCONFIRMED) { /* Must be confirmed, so queue to set */ net->dest_state |= SCTP_ADDR_REQ_PRIMARY; return (0); } stcb->asoc.primary_destination = net; if (!(net->dest_state & SCTP_ADDR_PF) && (stcb->asoc.alternate)) { sctp_free_remote_addr(stcb->asoc.alternate); stcb->asoc.alternate = NULL; } net = TAILQ_FIRST(&stcb->asoc.nets); if (net != stcb->asoc.primary_destination) { /* first one on the list is NOT the primary * sctp_cmpaddr() is much more efficient if * the primary is the first on the list, make it * so. */ TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next); TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next); } return (0); } } bool sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now) { struct sctpasochead *head; struct sctp_tcb *stcb; SCTP_INP_INFO_LOCK_ASSERT(); head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag, SCTP_BASE_INFO(hashasocmark))]; LIST_FOREACH(stcb, head, sctp_asocs) { /* We choose not to lock anything here. TCB's can't be * removed since we have the read lock, so they can't * be freed on us, same thing for the INP. I may * be wrong with this assumption, but we will go * with it for now :-) */ if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) { continue; } if (stcb->asoc.my_vtag == tag) { /* candidate */ if (stcb->rport != rport) { continue; } if (stcb->sctp_ep->sctp_lport != lport) { continue; } /* The tag is currently used, so don't use it. */ return (false); } } return (!sctp_is_in_timewait(tag, lport, rport, (uint32_t)now->tv_sec)); } static void sctp_drain_mbufs(struct sctp_tcb *stcb) { /* * We must hunt this association for MBUF's past the cumack (i.e. * out of order data that we can renege on). */ struct sctp_association *asoc; struct sctp_tmit_chunk *chk, *nchk; uint32_t cumulative_tsn_p1; struct sctp_queued_to_read *control, *ncontrol; int cnt, strmat; uint32_t gap, i; int fnd = 0; /* We look for anything larger than the cum-ack + 1 */ asoc = &stcb->asoc; if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) { /* none we can reneg on. */ return; } SCTP_STAT_INCR(sctps_protocol_drains_done); cumulative_tsn_p1 = asoc->cumulative_tsn + 1; cnt = 0; /* Ok that was fun, now we will drain all the inbound streams? */ for (strmat = 0; strmat < asoc->streamincnt; strmat++) { TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].inqueue, next_instrm, ncontrol) { #ifdef INVARIANTS if (control->on_strm_q != SCTP_ON_ORDERED) { panic("Huh control: %p on_q: %d -- not ordered?", control, control->on_strm_q); } #endif if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) { /* Yep it is above cum-ack */ cnt++; SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn); KASSERT(control->length > 0, ("control has zero length")); if (asoc->size_on_all_streams >= control->length) { asoc->size_on_all_streams -= control->length; } else { #ifdef INVARIANTS panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length); #else asoc->size_on_all_streams = 0; #endif } sctp_ucount_decr(asoc->cnt_on_all_streams); SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap); if (control->on_read_q) { TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next); control->on_read_q = 0; } TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, control, next_instrm); control->on_strm_q = 0; if (control->data) { sctp_m_freem(control->data); control->data = NULL; } sctp_free_remote_addr(control->whoFrom); /* Now its reasm? */ TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) { cnt++; SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn); KASSERT(chk->send_size > 0, ("chunk has zero length")); if (asoc->size_on_reasm_queue >= chk->send_size) { asoc->size_on_reasm_queue -= chk->send_size; } else { #ifdef INVARIANTS panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size); #else asoc->size_on_reasm_queue = 0; #endif } sctp_ucount_decr(asoc->cnt_on_reasm_queue); SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap); TAILQ_REMOVE(&control->reasm, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED); } sctp_free_a_readq(stcb, control); } } TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].uno_inqueue, next_instrm, ncontrol) { #ifdef INVARIANTS if (control->on_strm_q != SCTP_ON_UNORDERED) { panic("Huh control: %p on_q: %d -- not unordered?", control, control->on_strm_q); } #endif if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) { /* Yep it is above cum-ack */ cnt++; SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn); KASSERT(control->length > 0, ("control has zero length")); if (asoc->size_on_all_streams >= control->length) { asoc->size_on_all_streams -= control->length; } else { #ifdef INVARIANTS panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length); #else asoc->size_on_all_streams = 0; #endif } sctp_ucount_decr(asoc->cnt_on_all_streams); SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap); if (control->on_read_q) { TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next); control->on_read_q = 0; } TAILQ_REMOVE(&asoc->strmin[strmat].uno_inqueue, control, next_instrm); control->on_strm_q = 0; if (control->data) { sctp_m_freem(control->data); control->data = NULL; } sctp_free_remote_addr(control->whoFrom); /* Now its reasm? */ TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) { cnt++; SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn); KASSERT(chk->send_size > 0, ("chunk has zero length")); if (asoc->size_on_reasm_queue >= chk->send_size) { asoc->size_on_reasm_queue -= chk->send_size; } else { #ifdef INVARIANTS panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size); #else asoc->size_on_reasm_queue = 0; #endif } sctp_ucount_decr(asoc->cnt_on_reasm_queue); SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap); TAILQ_REMOVE(&control->reasm, chk, sctp_next); if (chk->data) { sctp_m_freem(chk->data); chk->data = NULL; } sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED); } sctp_free_a_readq(stcb, control); } } } if (cnt) { /* We must back down to see what the new highest is */ for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) { SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn); if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) { asoc->highest_tsn_inside_map = i; fnd = 1; break; } } if (!fnd) { asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1; } /* * Question, should we go through the delivery queue? The only * reason things are on here is the app not reading OR a p-d-api up. * An attacker COULD send enough in to initiate the PD-API and then * send a bunch of stuff to other streams... these would wind up on * the delivery queue.. and then we would not get to them. But in * order to do this I then have to back-track and un-deliver * sequence numbers in streams.. el-yucko. I think for now we will * NOT look at the delivery queue and leave it to be something to * consider later. An alternative would be to abort the P-D-API with * a notification and then deliver the data.... Or another method * might be to keep track of how many times the situation occurs and * if we see a possible attack underway just abort the association. */ #ifdef SCTP_DEBUG SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt); #endif /* * Now do we need to find a new * asoc->highest_tsn_inside_map? */ asoc->last_revoke_count = cnt; sctp_timer_stop(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_PCB + SCTP_LOC_11); /*sa_ignore NO_NULL_CHK*/ sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED); sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED); } /* * Another issue, in un-setting the TSN's in the mapping array we * DID NOT adjust the highest_tsn marker. This will cause one of two * things to occur. It may cause us to do extra work in checking for * our mapping array movement. More importantly it may cause us to * SACK every datagram. This may not be a bad thing though since we * will recover once we get our cum-ack above and all this stuff we * dumped recovered. */ } void sctp_drain() { /* * We must walk the PCB lists for ALL associations here. The system * is LOW on MBUF's and needs help. This is where reneging will * occur. We really hope this does NOT happen! */ #if defined(__FreeBSD__) && !defined(__Userspace__) VNET_ITERATOR_DECL(vnet_iter); #else struct sctp_inpcb *inp; struct sctp_tcb *stcb; SCTP_STAT_INCR(sctps_protocol_drain_calls); if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) { return; } #endif #if defined(__FreeBSD__) && !defined(__Userspace__) VNET_LIST_RLOCK_NOSLEEP(); VNET_FOREACH(vnet_iter) { CURVNET_SET(vnet_iter); struct sctp_inpcb *inp; struct sctp_tcb *stcb; #endif #if defined(__FreeBSD__) && !defined(__Userspace__) SCTP_STAT_INCR(sctps_protocol_drain_calls); if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) { #ifdef VIMAGE continue; #else return; #endif } #endif SCTP_INP_INFO_RLOCK(); LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) { /* For each endpoint */ SCTP_INP_RLOCK(inp); LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) { /* For each association */ SCTP_TCB_LOCK(stcb); sctp_drain_mbufs(stcb); SCTP_TCB_UNLOCK(stcb); } SCTP_INP_RUNLOCK(inp); } SCTP_INP_INFO_RUNLOCK(); #if defined(__FreeBSD__) && !defined(__Userspace__) CURVNET_RESTORE(); } VNET_LIST_RUNLOCK_NOSLEEP(); #endif } /* * start a new iterator * iterates through all endpoints and associations based on the pcb_state * flags and asoc_state. "af" (mandatory) is executed for all matching * assocs and "ef" (optional) is executed when the iterator completes. * "inpf" (optional) is executed for each new endpoint as it is being * iterated through. inpe (optional) is called when the inp completes * its way through all the stcbs. */ int sctp_initiate_iterator(inp_func inpf, asoc_func af, inp_func inpe, uint32_t pcb_state, uint32_t pcb_features, uint32_t asoc_state, void *argp, uint32_t argi, end_func ef, struct sctp_inpcb *s_inp, uint8_t chunk_output_off) { struct sctp_iterator *it = NULL; if (af == NULL) { return (-1); } if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) { SCTP_PRINTF("%s: abort on initialize being %d\n", __func__, SCTP_BASE_VAR(sctp_pcb_initialized)); return (-1); } SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator), SCTP_M_ITER); if (it == NULL) { SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM); return (-1); } memset(it, 0, sizeof(*it)); it->function_assoc = af; it->function_inp = inpf; if (inpf) it->done_current_ep = 0; else it->done_current_ep = 1; it->function_atend = ef; it->pointer = argp; it->val = argi; it->pcb_flags = pcb_state; it->pcb_features = pcb_features; it->asoc_state = asoc_state; it->function_inp_end = inpe; it->no_chunk_output = chunk_output_off; #if defined(__FreeBSD__) && !defined(__Userspace__) it->vn = curvnet; #endif if (s_inp) { /* Assume lock is held here */ it->inp = s_inp; SCTP_INP_INCR_REF(it->inp); it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP; } else { SCTP_INP_INFO_RLOCK(); it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead)); if (it->inp) { SCTP_INP_INCR_REF(it->inp); } SCTP_INP_INFO_RUNLOCK(); it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP; } SCTP_IPI_ITERATOR_WQ_LOCK(); if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) { SCTP_IPI_ITERATOR_WQ_UNLOCK(); SCTP_PRINTF("%s: rollback on initialize being %d it=%p\n", __func__, SCTP_BASE_VAR(sctp_pcb_initialized), it); SCTP_FREE(it, SCTP_M_ITER); return (-1); } TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr); if (sctp_it_ctl.iterator_running == 0) { sctp_wakeup_iterator(); } SCTP_IPI_ITERATOR_WQ_UNLOCK(); /* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */ return (0); }
7777.c
/******************************************************************************* * Copyright @ Huawei Technologies Co., Ltd. 1998-2014. All rights reserved. * File name: sprintf.c * History: * 1. Date: * Author: * Modification: ******************************************************************************** */ #include "securectype.h" #include "securecutil.h" #include "securec.h" #include <stdarg.h> /******************************************************************************* * <NAME> * snprintf_s * * <SYNOPSIS> * int snprintf_s(char* strDest, size_t destMax, size_t count, const char* format, ...); * * <FUNCTION DESCRIPTION> * The snprintf_s function formats and stores count or fewer characters in * strDest and appends a terminating null. Each argument (if any) is converted * and output according to the corresponding format specification in format. * The formatting is consistent with the printf family of functions; If copying * occurs between strings that overlap, the behavior is undefined. * * <INPUT PARAMETERS> * strDest Storage location for the output. * destMax The size of the storage location for output. Size * in bytes for snprintf_s or size in words for snwprintf_s. * count Maximum number of character to store. * format Format-control string. * * <OUTPUT PARAMETERS> * strDest is updated * * <RETURN VALUE> * snprintf_s returns the number of characters stored in strDest, not counting * the terminating null character. * If the storage required to store the data and a terminating null exceeds * destMax, the function set strDest to an empty string, and return -1. * If strDest or format is a NULL pointer, or if count is less than or equal * to zero, the function return -1. ******************************************************************************* */ int snprintf_s (char* strDest, size_t destMax, size_t count, const char* format, ...) { int ret = 0; va_list arglist; va_start(arglist, format); ret = vsnprintf_s(strDest, destMax, count, format, arglist); va_end(arglist); return ret; }
227656.c
//------------------------------------------------------------------------------ // GB_AxB: hard-coded functions for semiring: C<M>=A*B or A'*B //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_bracket.h" #include "GB_iterator.h" #include "GB_sort.h" #include "GB_atomics.h" #include "GB_AxB_saxpy3.h" #include "GB_AxB__include.h" // The C=A*B semiring is defined by the following types and operators: // A'*B function (dot2): GB_Adot2B__lxor_ge_uint8 // A'*B function (dot3): GB_Adot3B__lxor_ge_uint8 // C+=A'*B function (dot4): GB_Adot4B__lxor_ge_uint8 // A*B function (saxpy3): GB_Asaxpy3B__lxor_ge_uint8 // C type: bool // A type: uint8_t // B type: uint8_t // Multiply: z = (aik >= bkj) // Add: cij ^= z // 'any' monoid? 0 // atomic? 1 // OpenMP atomic? 1 // MultAdd: cij ^= (aik >= bkj) // Identity: false // Terminal: ; #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ bool // aik = Ax [pA] #define GB_GETA(aik,Ax,pA) \ uint8_t aik = Ax [pA] // bkj = Bx [pB] #define GB_GETB(bkj,Bx,pB) \ uint8_t bkj = Bx [pB] #define GB_CX(p) Cx [p] // multiply operator #define GB_MULT(z, x, y) \ z = (x >= y) // multiply-add #define GB_MULTADD(z, x, y) \ z ^= (x >= y) // monoid identity value #define GB_IDENTITY \ false // break if cij reaches the terminal value (dot product only) #define GB_DOT_TERMINAL(cij) \ ; // simd pragma for dot-product loop vectorization #define GB_PRAGMA_VECTORIZE_DOT \ GB_PRAGMA_SIMD // simd pragma for other loop vectorization #define GB_PRAGMA_VECTORIZE GB_PRAGMA_SIMD // declare the cij scalar #define GB_CIJ_DECLARE(cij) \ bool cij // save the value of C(i,j) #define GB_CIJ_SAVE(cij,p) Cx [p] = cij // cij = Cx [pC] #define GB_GETC(cij,pC) \ cij = Cx [pC] // Cx [pC] = cij #define GB_PUTC(cij,pC) \ Cx [pC] = cij // Cx [p] = t #define GB_CIJ_WRITE(p,t) Cx [p] = t // C(i,j) += t #define GB_CIJ_UPDATE(p,t) \ Cx [p] ^= t // x + y #define GB_ADD_FUNCTION(x,y) \ x ^ y // type with size of GB_CTYPE, and can be used in compare-and-swap #define GB_CTYPE_PUN \ bool // bit pattern for bool, 8-bit, 16-bit, and 32-bit integers #define GB_CTYPE_BITS \ 0x1L // 1 if monoid update can skipped entirely (the ANY monoid) #define GB_IS_ANY_MONOID \ 0 // 1 if monoid update is EQ #define GB_IS_EQ_MONOID \ 0 // 1 if monoid update can be done atomically, 0 otherwise #define GB_HAS_ATOMIC \ 1 // 1 if monoid update can be done with an OpenMP atomic update, 0 otherwise #if GB_MICROSOFT #define GB_HAS_OMP_ATOMIC \ 0 #else #define GB_HAS_OMP_ATOMIC \ 1 #endif // 1 for the ANY_PAIR semirings #define GB_IS_ANY_PAIR_SEMIRING \ 0 // 1 if PAIR is the multiply operator #define GB_IS_PAIR_MULTIPLIER \ 0 // atomic compare-exchange #define GB_ATOMIC_COMPARE_EXCHANGE(target, expected, desired) \ GB_ATOMIC_COMPARE_EXCHANGE_8 (target, expected, desired) #if GB_IS_ANY_PAIR_SEMIRING // result is purely symbolic; no numeric work to do. Hx is not used. #define GB_HX_WRITE(i,t) #define GB_CIJ_GATHER(p,i) #define GB_HX_UPDATE(i,t) #define GB_CIJ_MEMCPY(p,i,len) #else // Hx [i] = t #define GB_HX_WRITE(i,t) Hx [i] = t // Cx [p] = Hx [i] #define GB_CIJ_GATHER(p,i) Cx [p] = Hx [i] // Hx [i] += t #define GB_HX_UPDATE(i,t) \ Hx [i] ^= t // memcpy (&(Cx [p]), &(Hx [i]), len) #define GB_CIJ_MEMCPY(p,i,len) \ memcpy (Cx +(p), Hx +(i), (len) * sizeof(bool)) #endif // disable this semiring and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_GE || GxB_NO_UINT8 || GxB_NO_LXOR_BOOL || GxB_NO_GE_UINT8 || GxB_NO_LXOR_GE_UINT8) //------------------------------------------------------------------------------ // C=A'*B or C<!M>=A'*B: dot product (phase 2) //------------------------------------------------------------------------------ GrB_Info GB_Adot2B__lxor_ge_uint8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix *Aslice, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, int64_t *GB_RESTRICT B_slice, int64_t *GB_RESTRICT *C_counts, int nthreads, int naslice, int nbslice ) { // C<M>=A'*B now uses dot3 #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_AxB_dot2_meta.c" #undef GB_PHASE_2_OF_2 return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C<M>=A'*B: masked dot product method (phase 2) //------------------------------------------------------------------------------ GrB_Info GB_Adot3B__lxor_ge_uint8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot3_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C+=A'*B: dense dot product //------------------------------------------------------------------------------ GrB_Info GB_Adot4B__lxor_ge_uint8 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, int64_t *GB_RESTRICT A_slice, int naslice, const GrB_Matrix B, bool B_is_pattern, int64_t *GB_RESTRICT B_slice, int nbslice, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot4_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C=A*B, C<M>=A*B, C<!M>=A*B: saxpy3 method (Gustavson + Hash) //------------------------------------------------------------------------------ #include "GB_AxB_saxpy3_template.h" GrB_Info GB_Asaxpy3B__lxor_ge_uint8 ( GrB_Matrix C, const GrB_Matrix M, bool Mask_comp, const bool Mask_struct, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, GB_saxpy3task_struct *GB_RESTRICT TaskList, const int ntasks, const int nfine, const int nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_saxpy3_template.c" return (GrB_SUCCESS) ; #endif } #endif
200110.c
#include <stdio.h> #include<string.h> static int permutation(char *s, int a, int n); int main() { char str[100]; int n; printf("Enter the string: "); scanf("%s",str); n=strlen(str); permutation(str,0,n-1); //function call return 0; } static int swap(char *c1, char *c2); int permutation(char *s, int a, int n) //function for generating permutations //int a = initial index i.e., 0 //int n = index of last variable i.e., 2 { int j; if (a==n) printf("%s\n",s); else { for(j=a; j<=n; j++) { swap((s+a),(s+j)); permutation(s,a+1,n); swap((s+a),(s+j)); //back-tracking } } return 0; } int swap(char *c1, char *c2) //function for swapping 2 integers (at a time) // Let initially c1=x and c2=y { char temp; temp=*c1; //temp=x *c1=*c2; //c1=y *c2=temp; //c2=x return 0; }
725358.c
/* Copyright (c) 2011-2016 mingw-w64 project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <windows.h> #include <stdio.h> #include "pthread.h" #include "thread.h" #include "misc.h" int sched_get_priority_min(int pol) { if (pol < SCHED_MIN || pol > SCHED_MAX) { errno = EINVAL; return -1; } return THREAD_PRIORITY_IDLE; } int sched_get_priority_max(int pol) { if (pol < SCHED_MIN || pol > SCHED_MAX) { errno = EINVAL; return -1; } return THREAD_PRIORITY_TIME_CRITICAL; } int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *p) { int r = 0; if (attr == NULL || p == NULL) { return EINVAL; } memcpy(&attr->param, p, sizeof (*p)); return r; } int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *p) { int r = 0; if (attr == NULL || p == NULL) { return EINVAL; } memcpy(p, &attr->param, sizeof (*p)); return r; } int pthread_attr_setschedpolicy (pthread_attr_t *attr, int pol) { if (!attr || pol < SCHED_MIN || pol > SCHED_MAX) return EINVAL; if (pol != SCHED_OTHER) return ENOTSUP; return 0; } int pthread_attr_getschedpolicy (const pthread_attr_t *attr, int *pol) { if (!attr || !pol) return EINVAL; *pol = SCHED_OTHER; return 0; } static int pthread_check(pthread_t t) { struct _pthread_v *pv; if (!t) return ESRCH; pv = __pth_gpointer_locked (t); if (pv->ended == 0) return 0; CHECK_OBJECT(pv, ESRCH); return 0; } int pthread_getschedparam(pthread_t t, int *pol, struct sched_param *p) { int r; //if (!t) // t = pthread_self(); if ((r = pthread_check(t)) != 0) { return r; } if (!p || !pol) { return EINVAL; } *pol = __pth_gpointer_locked (t)->sched_pol; p->sched_priority = __pth_gpointer_locked (t)->sched.sched_priority; return 0; } int pthread_setschedparam(pthread_t t, int pol, const struct sched_param *p) { struct _pthread_v *pv; int r, pr = 0; //if (!t.p) t = pthread_self(); if ((r = pthread_check(t)) != 0) return r; if (pol < SCHED_MIN || pol > SCHED_MAX || p == NULL) return EINVAL; if (pol != SCHED_OTHER) return ENOTSUP; pr = p->sched_priority; if (pr < sched_get_priority_min(pol) || pr > sched_get_priority_max(pol)) return EINVAL; /* See msdn: there are actually 7 priorities: THREAD_PRIORITY_IDLE - -15 THREAD_PRIORITY_LOWEST -2 THREAD_PRIORITY_BELOW_NORMAL -1 THREAD_PRIORITY_NORMAL 0 THREAD_PRIORITY_ABOVE_NORMAL 1 THREAD_PRIORITY_HIGHEST 2 THREAD_PRIORITY_TIME_CRITICAL 15 */ if (pr <= THREAD_PRIORITY_IDLE) { pr = THREAD_PRIORITY_IDLE; } else if (pr <= THREAD_PRIORITY_LOWEST) { pr = THREAD_PRIORITY_LOWEST; } else if (pr >= THREAD_PRIORITY_TIME_CRITICAL) { pr = THREAD_PRIORITY_TIME_CRITICAL; } else if (pr >= THREAD_PRIORITY_HIGHEST) { pr = THREAD_PRIORITY_HIGHEST; } pv = __pth_gpointer_locked (t); if (SetThreadPriority(pv->h, pr)) { pv->sched_pol = pol; pv->sched.sched_priority = p->sched_priority; } else r = EINVAL; return r; } int sched_getscheduler(pid_t pid) { if (pid != 0) { HANDLE h = NULL; int selfPid = (int) GetCurrentProcessId (); if (pid != (pid_t) selfPid && (h = OpenProcess (PROCESS_QUERY_INFORMATION, 0, (DWORD) pid)) == NULL) { errno = (GetLastError () == (0xFF & ERROR_ACCESS_DENIED)) ? EPERM : ESRCH; return -1; } if (h) CloseHandle (h); } return SCHED_OTHER; } int sched_setscheduler(pid_t pid, int pol, const struct sched_param *param) { if (!param) { errno = EINVAL; return -1; } if (pid != 0) { HANDLE h = NULL; int selfPid = (int) GetCurrentProcessId (); if (pid != (pid_t) selfPid && (h = OpenProcess (PROCESS_SET_INFORMATION, 0, (DWORD) pid)) == NULL) { errno = (GetLastError () == (0xFF & ERROR_ACCESS_DENIED)) ? EPERM : ESRCH; return -1; } if (h) CloseHandle (h); } if (pol != SCHED_OTHER) { errno = ENOSYS; return -1; } return SCHED_OTHER; } int sched_yield(void) { Sleep(0); return 0; }
104360.c
#include "wbhal.h" #include "wb35reg_f.h" #include "core.h" /* * ==================================================== * Original Phy.h * ==================================================== */ /* * ==================================================== * For MAXIM2825/6/7 Ver. 331 or more * * 0x00 0x000a2 * 0x01 0x21cc0 * 0x02 0x13802 * 0x02 0x1383a * * channe1 01 ; 0x03 0x30142 ; 0x04 0x0b333; * channe1 02 ; 0x03 0x32141 ; 0x04 0x08444; * channe1 03 ; 0x03 0x32143 ; 0x04 0x0aeee; * channe1 04 ; 0x03 0x32142 ; 0x04 0x0b333; * channe1 05 ; 0x03 0x31141 ; 0x04 0x08444; * channe1 06 ; 0x03 0x31143 ; 0x04 0x0aeee; * channe1 07 ; 0x03 0x31142 ; 0x04 0x0b333; * channe1 08 ; 0x03 0x33141 ; 0x04 0x08444; * channe1 09 ; 0x03 0x33143 ; 0x04 0x0aeee; * channe1 10 ; 0x03 0x33142 ; 0x04 0x0b333; * channe1 11 ; 0x03 0x30941 ; 0x04 0x08444; * channe1 12 ; 0x03 0x30943 ; 0x04 0x0aeee; * channe1 13 ; 0x03 0x30942 ; 0x04 0x0b333; * * 0x05 0x28986 * 0x06 0x18008 * 0x07 0x38400 * 0x08 0x05100; 100 Hz DC * 0x08 0x05900; 30 KHz DC * 0x09 0x24f08 * 0x0a 0x17e00, 0x17ea0 * 0x0b 0x37d80 * 0x0c 0x0c900 -- 0x0ca00 (lager power 9db than 0x0c000), 0x0c000 */ /* MAX2825 (pure b/g) */ u32 max2825_rf_data[] = { (0x00<<18) | 0x000a2, (0x01<<18) | 0x21cc0, (0x02<<18) | 0x13806, (0x03<<18) | 0x30142, (0x04<<18) | 0x0b333, (0x05<<18) | 0x289A6, (0x06<<18) | 0x18008, (0x07<<18) | 0x38000, (0x08<<18) | 0x05100, (0x09<<18) | 0x24f08, (0x0A<<18) | 0x14000, (0x0B<<18) | 0x37d80, (0x0C<<18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */ }; u32 max2825_channel_data_24[][3] = { {(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 01 */ {(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 02 */ {(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 03 */ {(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 04 */ {(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 05 */ {(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 06 */ {(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 07 */ {(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 08 */ {(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 09 */ {(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 10 */ {(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 11 */ {(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 12 */ {(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 13 */ {(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */ }; u32 max2825_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100}; /* ========================================== */ /* MAX2827 (a/b/g) */ u32 max2827_rf_data[] = { (0x00 << 18) | 0x000a2, (0x01 << 18) | 0x21cc0, (0x02 << 18) | 0x13806, (0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6, (0x06 << 18) | 0x18008, (0x07 << 18) | 0x38000, (0x08 << 18) | 0x05100, (0x09 << 18) | 0x24f08, (0x0A << 18) | 0x14000, (0x0B << 18) | 0x37d80, (0x0C << 18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */ }; u32 max2827_channel_data_24[][3] = { {(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 01 */ {(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 02 */ {(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 03 */ {(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 04 */ {(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 05 */ {(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 06 */ {(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 07 */ {(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 08 */ {(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 09 */ {(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 10 */ {(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 11 */ {(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 12 */ {(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 13 */ {(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */ }; u32 max2827_channel_data_50[][3] = { {(0x03 << 18) | 0x33cc3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x2A9A6}, /* channel 36 */ {(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2A9A6}, /* channel 40 */ {(0x03 << 18) | 0x302c2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2A9A6}, /* channel 44 */ {(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x2A9A6}, /* channel 48 */ {(0x03 << 18) | 0x312c1, (0x04 << 18) | 0x0a666, (0x05 << 18) | 0x2A9A6}, /* channel 52 */ {(0x03 << 18) | 0x332c3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x2A9A6}, /* channel 56 */ {(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2A9A6}, /* channel 60 */ {(0x03 << 18) | 0x30ac2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2A9A6} /* channel 64 */ }; u32 max2827_power_data_24[] = {(0x0C << 18) | 0x0C000, (0x0C << 18) | 0x0D600, (0x0C << 18) | 0x0C100}; u32 max2827_power_data_50[] = {(0x0C << 18) | 0x0C400, (0x0C << 18) | 0x0D500, (0x0C << 18) | 0x0C300}; /* ======================================================= */ /* MAX2828 (a/b/g) */ u32 max2828_rf_data[] = { (0x00 << 18) | 0x000a2, (0x01 << 18) | 0x21cc0, (0x02 << 18) | 0x13806, (0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6, (0x06 << 18) | 0x18008, (0x07 << 18) | 0x38000, (0x08 << 18) | 0x05100, (0x09 << 18) | 0x24f08, (0x0A << 18) | 0x14000, (0x0B << 18) | 0x37d80, (0x0C << 18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */ }; u32 max2828_channel_data_24[][3] = { {(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 01 */ {(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 02 */ {(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 03 */ {(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 04 */ {(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 05 */ {(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 06 */ {(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 07 */ {(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 08 */ {(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 09 */ {(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 10 */ {(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 11 */ {(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 12 */ {(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 13 */ {(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */ }; u32 max2828_channel_data_50[][3] = { {(0x03 << 18) | 0x33cc3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x289A6}, /* channel 36 */ {(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x289A6}, /* channel 40 */ {(0x03 << 18) | 0x302c2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 44 */ {(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6}, /* channel 48 */ {(0x03 << 18) | 0x312c1, (0x04 << 18) | 0x0a666, (0x05 << 18) | 0x289A6}, /* channel 52 */ {(0x03 << 18) | 0x332c3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x289A6}, /* channel 56 */ {(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x289A6}, /* channel 60 */ {(0x03 << 18) | 0x30ac2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6} /* channel 64 */ }; u32 max2828_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100}; u32 max2828_power_data_50[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100}; /* ========================================================== */ /* MAX2829 (a/b/g) */ u32 max2829_rf_data[] = { (0x00 << 18) | 0x000a2, (0x01 << 18) | 0x23520, (0x02 << 18) | 0x13802, (0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x28906, (0x06 << 18) | 0x18008, (0x07 << 18) | 0x3B500, (0x08 << 18) | 0x05100, (0x09 << 18) | 0x24f08, (0x0A << 18) | 0x14000, (0x0B << 18) | 0x37d80, (0x0C << 18) | 0x0F300 /* TXVGA=51, (MAX-6 dB) */ }; u32 max2829_channel_data_24[][3] = { {(3 << 18) | 0x30142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 01 (2412MHz) */ {(3 << 18) | 0x32141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 02 (2417MHz) */ {(3 << 18) | 0x32143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 03 (2422MHz) */ {(3 << 18) | 0x32142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 04 (2427MHz) */ {(3 << 18) | 0x31141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 05 (2432MHz) */ {(3 << 18) | 0x31143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 06 (2437MHz) */ {(3 << 18) | 0x31142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 07 (2442MHz) */ {(3 << 18) | 0x33141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 08 (2447MHz) */ {(3 << 18) | 0x33143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 09 (2452MHz) */ {(3 << 18) | 0x33142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 10 (2457MHz) */ {(3 << 18) | 0x30941, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 11 (2462MHz) */ {(3 << 18) | 0x30943, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 12 (2467MHz) */ {(3 << 18) | 0x30942, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 13 (2472MHz) */ {(3 << 18) | 0x32941, (4 << 18) | 0x09999, (5 << 18) | 0x289C6}, /* 14 (2484MHz) */ }; u32 max2829_channel_data_50[][4] = { {36, (3 << 18) | 0x33cc3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 36 (5.180GHz) */ {40, (3 << 18) | 0x302c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A946}, /* 40 (5.200GHz) */ {44, (3 << 18) | 0x302c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 44 (5.220GHz) */ {48, (3 << 18) | 0x322c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 48 (5.240GHz) */ {52, (3 << 18) | 0x312c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 52 (5.260GHz) */ {56, (3 << 18) | 0x332c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 56 (5.280GHz) */ {60, (3 << 18) | 0x30ac0, (4 << 18) | 0x08000, (5 << 18) | 0x2A946}, /* 60 (5.300GHz) */ {64, (3 << 18) | 0x30ac2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 64 (5.320GHz) */ {100, (3 << 18) | 0x30ec0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 100 (5.500GHz) */ {104, (3 << 18) | 0x30ec2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 104 (5.520GHz) */ {108, (3 << 18) | 0x32ec1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 108 (5.540GHz) */ {112, (3 << 18) | 0x31ec1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 112 (5.560GHz) */ {116, (3 << 18) | 0x33ec3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 116 (5.580GHz) */ {120, (3 << 18) | 0x301c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 120 (5.600GHz) */ {124, (3 << 18) | 0x301c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 124 (5.620GHz) */ {128, (3 << 18) | 0x321c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 128 (5.640GHz) */ {132, (3 << 18) | 0x311c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 132 (5.660GHz) */ {136, (3 << 18) | 0x331c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 136 (5.680GHz) */ {140, (3 << 18) | 0x309c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 140 (5.700GHz) */ {149, (3 << 18) | 0x329c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 149 (5.745GHz) */ {153, (3 << 18) | 0x319c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 153 (5.765GHz) */ {157, (3 << 18) | 0x339c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 157 (5.785GHz) */ {161, (3 << 18) | 0x305c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 161 (5.805GHz) */ /* Japan */ { 184, (3 << 18) | 0x308c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 184 (4.920GHz) */ { 188, (3 << 18) | 0x328c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 188 (4.940GHz) */ { 192, (3 << 18) | 0x318c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 192 (4.960GHz) */ { 196, (3 << 18) | 0x338c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 196 (4.980GHz) */ { 8, (3 << 18) | 0x324c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 8 (5.040GHz) */ { 12, (3 << 18) | 0x314c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 12 (5.060GHz) */ { 16, (3 << 18) | 0x334c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 16 (5.080GHz) */ { 34, (3 << 18) | 0x31cc2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 34 (5.170GHz) */ { 38, (3 << 18) | 0x33cc1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 38 (5.190GHz) */ { 42, (3 << 18) | 0x302c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 42 (5.210GHz) */ { 46, (3 << 18) | 0x322c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 46 (5.230GHz) */ }; /* * ==================================================================== * For MAXIM2825/6/7 Ver. 317 or less * * 0x00 0x00080 * 0x01 0x214c0 * 0x02 0x13802 * * 2.4GHz Channels * channe1 01 (2.412GHz); 0x03 0x30143 ;0x04 0x0accc * channe1 02 (2.417GHz); 0x03 0x32140 ;0x04 0x09111 * channe1 03 (2.422GHz); 0x03 0x32142 ;0x04 0x0bbbb * channe1 04 (2.427GHz); 0x03 0x32143 ;0x04 0x0accc * channe1 05 (2.432GHz); 0x03 0x31140 ;0x04 0x09111 * channe1 06 (2.437GHz); 0x03 0x31142 ;0x04 0x0bbbb * channe1 07 (2.442GHz); 0x03 0x31143 ;0x04 0x0accc * channe1 08 (2.447GHz); 0x03 0x33140 ;0x04 0x09111 * channe1 09 (2.452GHz); 0x03 0x33142 ;0x04 0x0bbbb * channe1 10 (2.457GHz); 0x03 0x33143 ;0x04 0x0accc * channe1 11 (2.462GHz); 0x03 0x30940 ;0x04 0x09111 * channe1 12 (2.467GHz); 0x03 0x30942 ;0x04 0x0bbbb * channe1 13 (2.472GHz); 0x03 0x30943 ;0x04 0x0accc * * 5.0Ghz Channels * channel 36 (5.180GHz); 0x03 0x33cc0 ;0x04 0x0b333 * channel 40 (5.200GHz); 0x03 0x302c0 ;0x04 0x08000 * channel 44 (5.220GHz); 0x03 0x302c2 ;0x04 0x0b333 * channel 48 (5.240GHz); 0x03 0x322c1 ;0x04 0x09999 * channel 52 (5.260GHz); 0x03 0x312c1 ;0x04 0x0a666 * channel 56 (5.280GHz); 0x03 0x332c3 ;0x04 0x08ccc * channel 60 (5.300GHz); 0x03 0x30ac0 ;0x04 0x08000 * channel 64 (5.320GHz); 0x03 0x30ac2 ;0x04 0x08333 * * 2.4GHz band ; 0x05 0x28986; * 5.0GHz band ; 0x05 0x2a986 * 0x06 0x18008 * 0x07 0x38400 * 0x08 0x05108 * 0x09 0x27ff8 * 0x0a 0x14000 * 0x0b 0x37f99 * 0x0c 0x0c000 * ==================================================================== */ u32 maxim_317_rf_data[] = { (0x00 << 18) | 0x000a2, (0x01 << 18) | 0x214c0, (0x02 << 18) | 0x13802, (0x03 << 18) | 0x30143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986, (0x06 << 18) | 0x18008, (0x07 << 18) | 0x38400, (0x08 << 18) | 0x05108, (0x09 << 18) | 0x27ff8, (0x0A << 18) | 0x14000, (0x0B << 18) | 0x37f99, (0x0C << 18) | 0x0c000 }; u32 maxim_317_channel_data_24[][3] = { {(0x03 << 18) | 0x30143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 01 */ {(0x03 << 18) | 0x32140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 02 */ {(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 03 */ {(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 04 */ {(0x03 << 18) | 0x31140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 05 */ {(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 06 */ {(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 07 */ {(0x03 << 18) | 0x33140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 08 */ {(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 09 */ {(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 10 */ {(0x03 << 18) | 0x30940, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 11 */ {(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 12 */ {(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986} /* channe1 13 */ }; u32 maxim_317_channel_data_50[][3] = { {(0x03 << 18) | 0x33cc0, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2a986}, /* channel 36 */ {(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2a986}, /* channel 40 */ {(0x03 << 18) | 0x302c3, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x2a986}, /* channel 44 */ {(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09666, (0x05 << 18) | 0x2a986}, /* channel 48 */ {(0x03 << 18) | 0x312c2, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x2a986}, /* channel 52 */ {(0x03 << 18) | 0x332c0, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2a99e}, /* channel 56 */ {(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2a99e}, /* channel 60 */ {(0x03 << 18) | 0x30ac3, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x2a99e} /* channel 64 */ }; u32 maxim_317_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100}; u32 maxim_317_power_data_50[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100}; /* * =================================================================== * AL2230 MP (Mass Production Version) * RF Registers Setting for Airoha AL2230 silicon after June 1st, 2004 * 20-bit length and LSB first * * Ch01 (2412MHz) ;0x00 0x09EFC ;0x01 0x8CCCC; * Ch02 (2417MHz) ;0x00 0x09EFC ;0x01 0x8CCCD; * Ch03 (2422MHz) ;0x00 0x09E7C ;0x01 0x8CCCC; * Ch04 (2427MHz) ;0x00 0x09E7C ;0x01 0x8CCCD; * Ch05 (2432MHz) ;0x00 0x05EFC ;0x01 0x8CCCC; * Ch06 (2437MHz) ;0x00 0x05EFC ;0x01 0x8CCCD; * Ch07 (2442MHz) ;0x00 0x05E7C ;0x01 0x8CCCC; * Ch08 (2447MHz) ;0x00 0x05E7C ;0x01 0x8CCCD; * Ch09 (2452MHz) ;0x00 0x0DEFC ;0x01 0x8CCCC; * Ch10 (2457MHz) ;0x00 0x0DEFC ;0x01 0x8CCCD; * Ch11 (2462MHz) ;0x00 0x0DE7C ;0x01 0x8CCCC; * Ch12 (2467MHz) ;0x00 0x0DE7C ;0x01 0x8CCCD; * Ch13 (2472MHz) ;0x00 0x03EFC ;0x01 0x8CCCC; * Ch14 (2484Mhz) ;0x00 0x03E7C ;0x01 0x86666; * * 0x02 0x401D8; RXDCOC BW 100Hz for RXHP low * 0x02 0x481DC; RXDCOC BW 30Khz for RXHP low * * 0x03 0xCFFF0 * 0x04 0x23800 * 0x05 0xA3B72 * 0x06 0x6DA01 * 0x07 0xE1688 * 0x08 0x11600 * 0x09 0x99E02 * 0x0A 0x5DDB0 * 0x0B 0xD9900 * 0x0C 0x3FFBD * 0x0D 0xB0000 * 0x0F 0xF00A0 * * RF Calibration for Airoha AL2230 * * 0x0f 0xf00a0 ; Initial Setting * 0x0f 0xf00b0 ; Activate TX DCC * 0x0f 0xf02a0 ; Activate Phase Calibration * 0x0f 0xf00e0 ; Activate Filter RC Calibration * 0x0f 0xf00a0 ; Restore Initial Setting * ================================================================== */ u32 al2230_rf_data[] = { (0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCC, (0x02 << 20) | 0x40058, (0x03 << 20) | 0xCFFF0, (0x04 << 20) | 0x24100, (0x05 << 20) | 0xA3B2F, (0x06 << 20) | 0x6DA01, (0x07 << 20) | 0xE3628, (0x08 << 20) | 0x11600, (0x09 << 20) | 0x9DC02, (0x0A << 20) | 0x5ddb0, (0x0B << 20) | 0xD9900, (0x0C << 20) | 0x3FFBD, (0x0D << 20) | 0xB0000, (0x0F << 20) | 0xF01A0 }; u32 al2230s_rf_data[] = { (0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCC, (0x02 << 20) | 0x40058, (0x03 << 20) | 0xCFFF0, (0x04 << 20) | 0x24100, (0x05 << 20) | 0xA3B2F, (0x06 << 20) | 0x6DA01, (0x07 << 20) | 0xE3628, (0x08 << 20) | 0x11600, (0x09 << 20) | 0x9DC02, (0x0A << 20) | 0x5DDB0, (0x0B << 20) | 0xD9900, (0x0C << 20) | 0x3FFBD, (0x0D << 20) | 0xB0000, (0x0F << 20) | 0xF01A0 }; u32 al2230_channel_data_24[][2] = { {(0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 01 */ {(0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCD}, /* channe1 02 */ {(0x00 << 20) | 0x09E7C, (0x01 << 20) | 0x8CCCC}, /* channe1 03 */ {(0x00 << 20) | 0x09E7C, (0x01 << 20) | 0x8CCCD}, /* channe1 04 */ {(0x00 << 20) | 0x05EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 05 */ {(0x00 << 20) | 0x05EFC, (0x01 << 20) | 0x8CCCD}, /* channe1 06 */ {(0x00 << 20) | 0x05E7C, (0x01 << 20) | 0x8CCCC}, /* channe1 07 */ {(0x00 << 20) | 0x05E7C, (0x01 << 20) | 0x8CCCD}, /* channe1 08 */ {(0x00 << 20) | 0x0DEFC, (0x01 << 20) | 0x8CCCC}, /* channe1 09 */ {(0x00 << 20) | 0x0DEFC, (0x01 << 20) | 0x8CCCD}, /* channe1 10 */ {(0x00 << 20) | 0x0DE7C, (0x01 << 20) | 0x8CCCC}, /* channe1 11 */ {(0x00 << 20) | 0x0DE7C, (0x01 << 20) | 0x8CCCD}, /* channe1 12 */ {(0x00 << 20) | 0x03EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 13 */ {(0x00 << 20) | 0x03E7C, (0x01 << 20) | 0x86666} /* channe1 14 */ }; /* Current setting. u32 airoha_power_data_24[] = {(0x09 << 20) | 0x90202, (0x09 << 20) | 0x96602, (0x09 << 20) | 0x97602}; */ #define AIROHA_TXVGA_LOW_INDEX 31 /* Index for 0x90202 */ #define AIROHA_TXVGA_MIDDLE_INDEX 12 /* Index for 0x96602 */ #define AIROHA_TXVGA_HIGH_INDEX 8 /* Index for 0x97602 1.0.24.0 1.0.28.0 */ u32 al2230_txvga_data[][2] = { /* value , index */ {0x090202, 0}, {0x094202, 2}, {0x092202, 4}, {0x096202, 6}, {0x091202, 8}, {0x095202, 10}, {0x093202, 12}, {0x097202, 14}, {0x090A02, 16}, {0x094A02, 18}, {0x092A02, 20}, {0x096A02, 22}, {0x091A02, 24}, {0x095A02, 26}, {0x093A02, 28}, {0x097A02, 30}, {0x090602, 32}, {0x094602, 34}, {0x092602, 36}, {0x096602, 38}, {0x091602, 40}, {0x095602, 42}, {0x093602, 44}, {0x097602, 46}, {0x090E02, 48}, {0x098E02, 49}, {0x094E02, 50}, {0x09CE02, 51}, {0x092E02, 52}, {0x09AE02, 53}, {0x096E02, 54}, {0x09EE02, 55}, {0x091E02, 56}, {0x099E02, 57}, {0x095E02, 58}, {0x09DE02, 59}, {0x093E02, 60}, {0x09BE02, 61}, {0x097E02, 62}, {0x09FE02, 63} }; /* * ========================================== * For Airoha AL7230, 2.4Ghz band * 24bit, MSB first */ /* channel independent registers: */ u32 al7230_rf_data_24[] = { (0x00 << 24) | 0x003790, (0x01 << 24) | 0x133331, (0x02 << 24) | 0x841FF2, (0x03 << 24) | 0x3FDFA3, (0x04 << 24) | 0x7FD784, (0x05 << 24) | 0x802B55, (0x06 << 24) | 0x56AF36, (0x07 << 24) | 0xCE0207, (0x08 << 24) | 0x6EBC08, (0x09 << 24) | 0x221BB9, (0x0A << 24) | 0xE0000A, (0x0B << 24) | 0x08071B, (0x0C << 24) | 0x000A3C, (0x0D << 24) | 0xFFFFFD, (0x0E << 24) | 0x00000E, (0x0F << 24) | 0x1ABA8F }; u32 al7230_channel_data_24[][2] = { {(0x00 << 24) | 0x003790, (0x01 << 24) | 0x133331}, /* channe1 01 */ {(0x00 << 24) | 0x003790, (0x01 << 24) | 0x1B3331}, /* channe1 02 */ {(0x00 << 24) | 0x003790, (0x01 << 24) | 0x033331}, /* channe1 03 */ {(0x00 << 24) | 0x003790, (0x01 << 24) | 0x0B3331}, /* channe1 04 */ {(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x133331}, /* channe1 05 */ {(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x1B3331}, /* channe1 06 */ {(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x033331}, /* channe1 07 */ {(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x0B3331}, /* channe1 08 */ {(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x133331}, /* channe1 09 */ {(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x1B3331}, /* channe1 10 */ {(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x033331}, /* channe1 11 */ {(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x0B3331}, /* channe1 12 */ {(0x00 << 24) | 0x0037C0, (0x01 << 24) | 0x133331}, /* channe1 13 */ {(0x00 << 24) | 0x0037C0, (0x01 << 24) | 0x066661} /* channel 14 */ }; /* channel independent registers: */ u32 al7230_rf_data_50[] = { (0x00 << 24) | 0x0FF520, (0x01 << 24) | 0x000001, (0x02 << 24) | 0x451FE2, (0x03 << 24) | 0x5FDFA3, (0x04 << 24) | 0x6FD784, (0x05 << 24) | 0x853F55, (0x06 << 24) | 0x56AF36, (0x07 << 24) | 0xCE0207, (0x08 << 24) | 0x6EBC08, (0x09 << 24) | 0x221BB9, (0x0A << 24) | 0xE0600A, (0x0B << 24) | 0x08044B, (0x0C << 24) | 0x00143C, (0x0D << 24) | 0xFFFFFD, (0x0E << 24) | 0x00000E, (0x0F << 24) | 0x12BACF /* 5Ghz default state */ }; u32 al7230_channel_data_5[][4] = { /* channel dependent registers: 0x00, 0x01 and 0x04 */ /* 11J =========== */ {184, (0x00 << 24) | 0x0FF520, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 184 */ {188, (0x00 << 24) | 0x0FF520, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 188 */ {192, (0x00 << 24) | 0x0FF530, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 192 */ {196, (0x00 << 24) | 0x0FF530, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 196 */ {8, (0x00 << 24) | 0x0FF540, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 008 */ {12, (0x00 << 24) | 0x0FF540, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 012 */ {16, (0x00 << 24) | 0x0FF550, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 016 */ {34, (0x00 << 24) | 0x0FF560, (0x01 << 24) | 0x055551, (0x04 << 24) | 0x77F784}, /* channel 034 */ {38, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x100001, (0x04 << 24) | 0x77F784}, /* channel 038 */ {42, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x1AAAA1, (0x04 << 24) | 0x77F784}, /* channel 042 */ {46, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x055551, (0x04 << 24) | 0x77F784}, /* channel 046 */ /* 11 A/H ========= */ {36, (0x00 << 24) | 0x0FF560, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 036 */ {40, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 040 */ {44, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 044 */ {48, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 048 */ {52, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 052 */ {56, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 056 */ {60, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 060 */ {64, (0x00 << 24) | 0x0FF590, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 064 */ {100, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 100 */ {104, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 104 */ {108, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 108 */ {112, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 112 */ {116, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 116 */ {120, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 120 */ {124, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 124 */ {128, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 128 */ {132, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 132 */ {136, (0x00 << 24) | 0x0FF5F0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 136 */ {140, (0x00 << 24) | 0x0FF5F0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 140 */ {149, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x180001, (0x04 << 24) | 0x77F784}, /* channel 149 */ {153, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x02AAA1, (0x04 << 24) | 0x77F784}, /* channel 153 */ {157, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x0D5551, (0x04 << 24) | 0x77F784}, /* channel 157 */ {161, (0x00 << 24) | 0x0FF610, (0x01 << 24) | 0x180001, (0x04 << 24) | 0x77F784}, /* channel 161 */ {165, (0x00 << 24) | 0x0FF610, (0x01 << 24) | 0x02AAA1, (0x04 << 24) | 0x77F784} /* channel 165 */ }; /* * RF Calibration <=== Register 0x0F * 0x0F 0x1ABA8F; start from 2.4Ghz default state * 0x0F 0x9ABA8F; TXDC compensation * 0x0F 0x3ABA8F; RXFIL adjustment * 0x0F 0x1ABA8F; restore 2.4Ghz default state */ /* TXVGA Mapping Table <=== Register 0x0B */ u32 al7230_txvga_data[][2] = { {0x08040B, 0}, /* TXVGA = 0; */ {0x08041B, 1}, /* TXVGA = 1; */ {0x08042B, 2}, /* TXVGA = 2; */ {0x08043B, 3}, /* TXVGA = 3; */ {0x08044B, 4}, /* TXVGA = 4; */ {0x08045B, 5}, /* TXVGA = 5; */ {0x08046B, 6}, /* TXVGA = 6; */ {0x08047B, 7}, /* TXVGA = 7; */ {0x08048B, 8}, /* TXVGA = 8; */ {0x08049B, 9}, /* TXVGA = 9; */ {0x0804AB, 10}, /* TXVGA = 10; */ {0x0804BB, 11}, /* TXVGA = 11; */ {0x0804CB, 12}, /* TXVGA = 12; */ {0x0804DB, 13}, /* TXVGA = 13; */ {0x0804EB, 14}, /* TXVGA = 14; */ {0x0804FB, 15}, /* TXVGA = 15; */ {0x08050B, 16}, /* TXVGA = 16; */ {0x08051B, 17}, /* TXVGA = 17; */ {0x08052B, 18}, /* TXVGA = 18; */ {0x08053B, 19}, /* TXVGA = 19; */ {0x08054B, 20}, /* TXVGA = 20; */ {0x08055B, 21}, /* TXVGA = 21; */ {0x08056B, 22}, /* TXVGA = 22; */ {0x08057B, 23}, /* TXVGA = 23; */ {0x08058B, 24}, /* TXVGA = 24; */ {0x08059B, 25}, /* TXVGA = 25; */ {0x0805AB, 26}, /* TXVGA = 26; */ {0x0805BB, 27}, /* TXVGA = 27; */ {0x0805CB, 28}, /* TXVGA = 28; */ {0x0805DB, 29}, /* TXVGA = 29; */ {0x0805EB, 30}, /* TXVGA = 30; */ {0x0805FB, 31}, /* TXVGA = 31; */ {0x08060B, 32}, /* TXVGA = 32; */ {0x08061B, 33}, /* TXVGA = 33; */ {0x08062B, 34}, /* TXVGA = 34; */ {0x08063B, 35}, /* TXVGA = 35; */ {0x08064B, 36}, /* TXVGA = 36; */ {0x08065B, 37}, /* TXVGA = 37; */ {0x08066B, 38}, /* TXVGA = 38; */ {0x08067B, 39}, /* TXVGA = 39; */ {0x08068B, 40}, /* TXVGA = 40; */ {0x08069B, 41}, /* TXVGA = 41; */ {0x0806AB, 42}, /* TXVGA = 42; */ {0x0806BB, 43}, /* TXVGA = 43; */ {0x0806CB, 44}, /* TXVGA = 44; */ {0x0806DB, 45}, /* TXVGA = 45; */ {0x0806EB, 46}, /* TXVGA = 46; */ {0x0806FB, 47}, /* TXVGA = 47; */ {0x08070B, 48}, /* TXVGA = 48; */ {0x08071B, 49}, /* TXVGA = 49; */ {0x08072B, 50}, /* TXVGA = 50; */ {0x08073B, 51}, /* TXVGA = 51; */ {0x08074B, 52}, /* TXVGA = 52; */ {0x08075B, 53}, /* TXVGA = 53; */ {0x08076B, 54}, /* TXVGA = 54; */ {0x08077B, 55}, /* TXVGA = 55; */ {0x08078B, 56}, /* TXVGA = 56; */ {0x08079B, 57}, /* TXVGA = 57; */ {0x0807AB, 58}, /* TXVGA = 58; */ {0x0807BB, 59}, /* TXVGA = 59; */ {0x0807CB, 60}, /* TXVGA = 60; */ {0x0807DB, 61}, /* TXVGA = 61; */ {0x0807EB, 62}, /* TXVGA = 62; */ {0x0807FB, 63}, /* TXVGA = 63; */ }; /* ============================================= */ /* * W89RF242 RFIC SPI programming initial data * Winbond WLAN 11g RFIC BB-SPI register -- version FA5976A rev 1.3b */ u32 w89rf242_rf_data[] = { (0x00 << 24) | 0xF86100, /* 3E184; MODA (0x00) -- Normal mode ; calibration off */ (0x01 << 24) | 0xEFFFC2, /* 3BFFF; MODB (0x01) -- turn off RSSI, and other circuits are turned on */ (0x02 << 24) | 0x102504, /* 04094; FSET (0x02) -- default 20MHz crystal ; Icmp=1.5mA */ (0x03 << 24) | 0x026286, /* 0098A; FCHN (0x03) -- default CH7, 2442MHz */ (0x04 << 24) | 0x000208, /* 02008; FCAL (0x04) -- XTAL Freq Trim=001000 (socket board#1); FA5976AYG_v1.3C */ (0x05 << 24) | 0x24C60A, /* 09316; GANA (0x05) -- TX VGA default (TXVGA=0x18(12)) & TXGPK=110 ; FA5976A_1.3D */ (0x06 << 24) | 0x3432CC, /* 0D0CB; GANB (0x06) -- RXDC(DC offset) on; LNA=11; RXVGA=001011(11) ; RXFLSW=11(010001); RXGPK=00; RXGCF=00; -50dBm input */ (0x07 << 24) | 0x0C68CE, /* 031A3; FILT (0x07) -- TX/RX filter with auto-tuning; TFLBW=011; RFLBW=100 */ (0x08 << 24) | 0x100010, /* 04000; TCAL (0x08) -- for LO */ (0x09 << 24) | 0x004012, /* 1B900; RCALA (0x09) -- FASTS=11; HPDE=01 (100nsec); SEHP=1 (select B0 pin=RXHP); RXHP=1 (Turn on RXHP function)(FA5976A_1.3C) */ (0x0A << 24) | 0x704014, /* 1C100; RCALB (0x0A) */ (0x0B << 24) | 0x18BDD6, /* 062F7; IQCAL (0x0B) -- Turn on LO phase tuner=0111 & RX-LO phase = 0111; FA5976A_1.3B */ (0x0C << 24) | 0x575558, /* 15D55 ; IBSA (0x0C) -- IFPre =11 ; TC5376A_v1.3A for corner */ (0x0D << 24) | 0x55545A, /* 15555 ; IBSB (0x0D) */ (0x0E << 24) | 0x5557DC, /* 1555F ; IBSC (0x0E) -- IRLNA & IRLNB (PTAT & Const current)=01/01; FA5976B_1.3F */ (0x10 << 24) | 0x000C20, /* 00030 ; TMODA (0x10) -- LNA_gain_step=0011 ; LNA=15/16dB */ (0x11 << 24) | 0x0C0022, /* 03000 ; TMODB (0x11) -- Turn ON RX-Q path Test Switch; To improve IQ path group delay (FA5976A_1.3C) */ (0x12 << 24) | 0x000024 /* TMODC (0x12) -- Turn OFF Tempearure sensor */ }; u32 w89rf242_channel_data_24[][2] = { {(0x03 << 24) | 0x025B06, (0x04 << 24) | 0x080408}, /* channe1 01 */ {(0x03 << 24) | 0x025C46, (0x04 << 24) | 0x080408}, /* channe1 02 */ {(0x03 << 24) | 0x025D86, (0x04 << 24) | 0x080408}, /* channe1 03 */ {(0x03 << 24) | 0x025EC6, (0x04 << 24) | 0x080408}, /* channe1 04 */ {(0x03 << 24) | 0x026006, (0x04 << 24) | 0x080408}, /* channe1 05 */ {(0x03 << 24) | 0x026146, (0x04 << 24) | 0x080408}, /* channe1 06 */ {(0x03 << 24) | 0x026286, (0x04 << 24) | 0x080408}, /* channe1 07 */ {(0x03 << 24) | 0x0263C6, (0x04 << 24) | 0x080408}, /* channe1 08 */ {(0x03 << 24) | 0x026506, (0x04 << 24) | 0x080408}, /* channe1 09 */ {(0x03 << 24) | 0x026646, (0x04 << 24) | 0x080408}, /* channe1 10 */ {(0x03 << 24) | 0x026786, (0x04 << 24) | 0x080408}, /* channe1 11 */ {(0x03 << 24) | 0x0268C6, (0x04 << 24) | 0x080408}, /* channe1 12 */ {(0x03 << 24) | 0x026A06, (0x04 << 24) | 0x080408}, /* channe1 13 */ {(0x03 << 24) | 0x026D06, (0x04 << 24) | 0x080408} /* channe1 14 */ }; u32 w89rf242_power_data_24[] = {(0x05 << 24) | 0x24C48A, (0x05 << 24) | 0x24C48A, (0x05 << 24) | 0x24C48A}; u32 w89rf242_txvga_old_mapping[][2] = { {0, 0} , /* New <-> Old */ {1, 1} , {2, 2} , {3, 3} , {4, 4} , {6, 5} , {8, 6}, {10, 7}, {12, 8}, {14, 9}, {16, 10}, {18, 11}, {20, 12}, {22, 13}, {24, 14}, {26, 15}, {28, 16}, {30, 17}, {32, 18}, {34, 19}, }; u32 w89rf242_txvga_data[][5] = { /* low gain mode */ {(0x05 << 24) | 0x24C00A, 0, 0x00292315, 0x0800FEFF, 0x52523131}, /* min gain */ {(0x05 << 24) | 0x24C80A, 1, 0x00292315, 0x0800FEFF, 0x52523131}, {(0x05 << 24) | 0x24C04A, 2, 0x00292315, 0x0800FEFF, 0x52523131}, /* (default) +14dBm (ANT) */ {(0x05 << 24) | 0x24C84A, 3, 0x00292315, 0x0800FEFF, 0x52523131}, /* TXVGA=0x10 */ {(0x05 << 24) | 0x24C40A, 4, 0x00292315, 0x0800FEFF, 0x60603838}, {(0x05 << 24) | 0x24C40A, 5, 0x00262114, 0x0700FEFF, 0x65653B3B}, /* TXVGA=0x11 */ { (0x05 << 24) | 0x24C44A, 6, 0x00241F13, 0x0700FFFF, 0x58583333}, { (0x05 << 24) | 0x24C44A, 7, 0x00292315, 0x0800FEFF, 0x5E5E3737}, /* TXVGA=0x12 */ {(0x05 << 24) | 0x24C48A, 8, 0x00262114, 0x0700FEFF, 0x53533030}, {(0x05 << 24) | 0x24C48A, 9, 0x00241F13, 0x0700FFFF, 0x59593434}, /* TXVGA=0x13 */ {(0x05 << 24) | 0x24C4CA, 10, 0x00292315, 0x0800FEFF, 0x52523030}, {(0x05 << 24) | 0x24C4CA, 11, 0x00262114, 0x0700FEFF, 0x56563232}, /* TXVGA=0x14 */ {(0x05 << 24) | 0x24C50A, 12, 0x00292315, 0x0800FEFF, 0x54543131}, {(0x05 << 24) | 0x24C50A, 13, 0x00262114, 0x0700FEFF, 0x58583434}, /* TXVGA=0x15 */ {(0x05 << 24) | 0x24C54A, 14, 0x00292315, 0x0800FEFF, 0x54543131}, {(0x05 << 24) | 0x24C54A, 15, 0x00262114, 0x0700FEFF, 0x59593434}, /* TXVGA=0x16 */ {(0x05 << 24) | 0x24C58A, 16, 0x00292315, 0x0800FEFF, 0x55553131}, {(0x05 << 24) | 0x24C58A, 17, 0x00292315, 0x0800FEFF, 0x5B5B3535}, /* TXVGA=0x17 */ {(0x05 << 24) | 0x24C5CA, 18, 0x00262114, 0x0700FEFF, 0x51512F2F}, {(0x05 << 24) | 0x24C5CA, 19, 0x00241F13, 0x0700FFFF, 0x55553131}, /* TXVGA=0x18 */ {(0x05 << 24) | 0x24C60A, 20, 0x00292315, 0x0800FEFF, 0x4F4F2E2E}, {(0x05 << 24) | 0x24C60A, 21, 0x00262114, 0x0700FEFF, 0x53533030}, /* TXVGA=0x19 */ {(0x05 << 24) | 0x24C64A, 22, 0x00292315, 0x0800FEFF, 0x4E4E2D2D}, {(0x05 << 24) | 0x24C64A, 23, 0x00262114, 0x0700FEFF, 0x53533030}, /* TXVGA=0x1A */ {(0x05 << 24) | 0x24C68A, 24, 0x00292315, 0x0800FEFF, 0x50502E2E}, {(0x05 << 24) | 0x24C68A, 25, 0x00262114, 0x0700FEFF, 0x55553131}, /* TXVGA=0x1B */ {(0x05 << 24) | 0x24C6CA, 26, 0x00262114, 0x0700FEFF, 0x53533030}, {(0x05 << 24) | 0x24C6CA, 27, 0x00292315, 0x0800FEFF, 0x5A5A3434}, /* TXVGA=0x1C */ {(0x05 << 24) | 0x24C70A, 28, 0x00292315, 0x0800FEFF, 0x55553131}, {(0x05 << 24) | 0x24C70A, 29, 0x00292315, 0x0800FEFF, 0x5D5D3636}, /* TXVGA=0x1D */ {(0x05 << 24) | 0x24C74A, 30, 0x00292315, 0x0800FEFF, 0x5F5F3737}, {(0x05 << 24) | 0x24C74A, 31, 0x00262114, 0x0700FEFF, 0x65653B3B}, /* TXVGA=0x1E */ {(0x05 << 24) | 0x24C78A, 32, 0x00292315, 0x0800FEFF, 0x66663B3B}, {(0x05 << 24) | 0x24C78A, 33, 0x00262114, 0x0700FEFF, 0x70704141}, /* TXVGA=0x1F */ {(0x05 << 24) | 0x24C7CA, 34, 0x00292315, 0x0800FEFF, 0x72724242} }; /* ================================================================================================== */ /* * ============================================================================================================= * Uxx_ReadEthernetAddress -- * * Routine Description: * Reads in the Ethernet address from the IC. * * Arguments: * pHwData - The pHwData structure * * Return Value: * * The address is stored in EthernetIDAddr. * ============================================================================================================= */ void Uxx_ReadEthernetAddress(struct hw_data *pHwData) { u32 ltmp; /* * Reading Ethernet address from EEPROM and set into hardware due to MAC address maybe change. * Only unplug and plug again can make hardware read EEPROM again. */ Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08000000); /* Start EEPROM access + Read + address(0x0d) */ Wb35Reg_ReadSync(pHwData, 0x03b4, &ltmp); *(u16 *)pHwData->PermanentMacAddress = cpu_to_le16((u16) ltmp); Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08010000); /* Start EEPROM access + Read + address(0x0d) */ Wb35Reg_ReadSync(pHwData, 0x03b4, &ltmp); *(u16 *)(pHwData->PermanentMacAddress + 2) = cpu_to_le16((u16) ltmp); Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08020000); /* Start EEPROM access + Read + address(0x0d) */ Wb35Reg_ReadSync(pHwData, 0x03b4, &ltmp); *(u16 *)(pHwData->PermanentMacAddress + 4) = cpu_to_le16((u16) ltmp); *(u16 *)(pHwData->PermanentMacAddress + 6) = 0; Wb35Reg_WriteSync(pHwData, 0x03e8, cpu_to_le32(*(u32 *)pHwData->PermanentMacAddress)); Wb35Reg_WriteSync(pHwData, 0x03ec, cpu_to_le32(*(u32 *)(pHwData->PermanentMacAddress + 4))); } /* * =============================================================================================================== * CardGetMulticastBit -- * Description: * For a given multicast address, returns the byte and bit in the card multicast registers that it hashes to. * Calls CardComputeCrc() to determine the CRC value. * Arguments: * Address - the address * Byte - the byte that it hashes to * Value - will have a 1 in the relevant bit * Return Value: * None. * ============================================================================================================== */ void CardGetMulticastBit(u8 Address[ETH_ALEN], u8 *Byte, u8 *Value) { u32 Crc; u32 BitNumber; /* First compute the CRC. */ Crc = CardComputeCrc(Address, ETH_ALEN); /* The computed CRC is bit0~31 from left to right */ /* At first we should do right shift 25bits, and read 7bits by using '&', 2^7=128 */ BitNumber = (u32) ((Crc >> 26) & 0x3f); *Byte = (u8) (BitNumber >> 3); /* 900514 original (BitNumber / 8) */ *Value = (u8) ((u8) 1 << (BitNumber % 8)); } void Uxx_power_on_procedure(struct hw_data *pHwData) { u32 ltmp, loop; if (pHwData->phy_type <= RF_MAXIM_V1) Wb35Reg_WriteSync(pHwData, 0x03d4, 0xffffff38); else { Wb35Reg_WriteSync(pHwData, 0x03f4, 0xFF5807FF); Wb35Reg_WriteSync(pHwData, 0x03d4, 0x80); /* regulator on only */ msleep(10); Wb35Reg_WriteSync(pHwData, 0x03d4, 0xb8); /* REG_ON RF_RSTN on, and */ msleep(10); ltmp = 0x4968; if ((pHwData->phy_type == RF_WB_242) || (RF_WB_242_1 == pHwData->phy_type)) ltmp = 0x4468; Wb35Reg_WriteSync(pHwData, 0x03d0, ltmp); Wb35Reg_WriteSync(pHwData, 0x03d4, 0xa0); /* PLL_PD REF_PD set to 0 */ msleep(20); Wb35Reg_ReadSync(pHwData, 0x03d0, &ltmp); loop = 500; /* Wait for 5 second */ while (!(ltmp & 0x20) && loop--) { msleep(10); if (!Wb35Reg_ReadSync(pHwData, 0x03d0, &ltmp)) break; } Wb35Reg_WriteSync(pHwData, 0x03d4, 0xe0); /* MLK_EN */ } Wb35Reg_WriteSync(pHwData, 0x03b0, 1); /* Reset hardware first */ msleep(10); /* Set burst write delay */ Wb35Reg_WriteSync(pHwData, 0x03f8, 0x7ff); } void Set_ChanIndep_RfData_al7230_24(struct hw_data *pHwData, u32 *pltmp , char number) { u8 i; for (i = 0; i < number; i++) { pHwData->phy_para[i] = al7230_rf_data_24[i]; pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_rf_data_24[i] & 0xffffff); } } void Set_ChanIndep_RfData_al7230_50(struct hw_data *pHwData, u32 *pltmp, char number) { u8 i; for (i = 0; i < number; i++) { pHwData->phy_para[i] = al7230_rf_data_50[i]; pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_rf_data_50[i] & 0xffffff); } } /* * ============================================================================================================= * RFSynthesizer_initial -- * ============================================================================================================= */ void RFSynthesizer_initial(struct hw_data *pHwData) { u32 altmp[32]; u32 *pltmp = altmp; u32 ltmp; u8 number = 0x00; /* The number of register vale */ u8 i; /* * bit[31] SPI Enable. * 1=perform synthesizer program operation. This bit will * cleared automatically after the operation is completed. * bit[30] SPI R/W Control * 0=write, 1=read * bit[29:24] SPI Data Format Length * bit[17:4 ] RF Data bits. * bit[3 :0 ] RF address. */ switch (pHwData->phy_type) { case RF_MAXIM_2825: case RF_MAXIM_V1: /* 11g Winbond 2nd BB(with Phy board (v1) + Maxim 331) */ number = ARRAY_SIZE(max2825_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = max2825_rf_data[i]; /* Backup Rf parameter */ pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_rf_data[i], 18); } break; case RF_MAXIM_2827: number = ARRAY_SIZE(max2827_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = max2827_rf_data[i]; pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_rf_data[i], 18); } break; case RF_MAXIM_2828: number = ARRAY_SIZE(max2828_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = max2828_rf_data[i]; pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_rf_data[i], 18); } break; case RF_MAXIM_2829: number = ARRAY_SIZE(max2829_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = max2829_rf_data[i]; pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_rf_data[i], 18); } break; case RF_AIROHA_2230: number = ARRAY_SIZE(al2230_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = al2230_rf_data[i]; pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_rf_data[i], 20); } break; case RF_AIROHA_2230S: number = ARRAY_SIZE(al2230s_rf_data); for (i = 0; i < number; i++) { pHwData->phy_para[i] = al2230s_rf_data[i]; pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230s_rf_data[i], 20); } break; case RF_AIROHA_7230: /* Start to fill RF parameters, PLL_ON should be pulled low. */ Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000000); pr_debug("* PLL_ON low\n"); number = ARRAY_SIZE(al7230_rf_data_24); Set_ChanIndep_RfData_al7230_24(pHwData, pltmp, number); break; case RF_WB_242: case RF_WB_242_1: number = ARRAY_SIZE(w89rf242_rf_data); for (i = 0; i < number; i++) { ltmp = w89rf242_rf_data[i]; if (i == 4) { /* Update the VCO trim from EEPROM */ ltmp &= ~0xff0; /* Mask bit4 ~bit11 */ ltmp |= pHwData->VCO_trim << 4; } pHwData->phy_para[i] = ltmp; pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(ltmp, 24); } break; } pHwData->phy_number = number; /* The 16 is the maximum capability of hardware. Here use 12 */ if (number > 12) { for (i = 0; i < 12; i++) /* For Al2230 */ Wb35Reg_WriteSync(pHwData, 0x0864, pltmp[i]); pltmp += 12; number -= 12; } /* Write to register. number must less and equal than 16 */ for (i = 0; i < number; i++) Wb35Reg_WriteSync(pHwData, 0x864, pltmp[i]); /* Calibration only 1 time */ if (pHwData->CalOneTime) return; pHwData->CalOneTime = 1; switch (pHwData->phy_type) { case RF_AIROHA_2230: ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x07 << 20) | 0xE168E, 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(10); ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_rf_data[7], 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(10); case RF_AIROHA_2230S: Wb35Reg_WriteSync(pHwData, 0x03d4, 0x80); /* regulator on only */ msleep(10); Wb35Reg_WriteSync(pHwData, 0x03d4, 0xa0); /* PLL_PD REF_PD set to 0 */ msleep(10); Wb35Reg_WriteSync(pHwData, 0x03d4, 0xe0); /* MLK_EN */ Wb35Reg_WriteSync(pHwData, 0x03b0, 1); /* Reset hardware first */ msleep(10); /* ========================================================= */ /* The follow code doesn't use the burst-write mode */ ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F<<20) | 0xF01A0, 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); ltmp = pHwData->reg.BB5C & 0xfffff000; Wb35Reg_WriteSync(pHwData, 0x105c, ltmp); pHwData->reg.BB50 |= 0x13; /* (MASK_IQCAL_MODE|MASK_CALIB_START) */ Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50); msleep(5); ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01B0, 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01E0, 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01A0, 20); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp) ; Wb35Reg_WriteSync(pHwData, 0x105c, pHwData->reg.BB5C); pHwData->reg.BB50 &= ~0x13; /* (MASK_IQCAL_MODE|MASK_CALIB_START); */ Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50); break; case RF_AIROHA_7230: /* RF parameters have filled completely, PLL_ON should be pulled high */ Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000080); pr_debug("* PLL_ON high\n"); /* 2.4GHz */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x9ABA8F; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x3ABA8F; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x1ABA8F; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); /* 5GHz */ Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000000); pr_debug("* PLL_ON low\n"); number = ARRAY_SIZE(al7230_rf_data_50); Set_ChanIndep_RfData_al7230_50(pHwData, pltmp, number); /* Write to register. number must less and equal than 16 */ for (i = 0; i < number; i++) Wb35Reg_WriteSync(pHwData, 0x0864, pltmp[i]); msleep(5); Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000080); pr_debug("* PLL_ON high\n"); ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x9ABA8F; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x3ABA8F; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x12BACF; Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); break; case RF_WB_242: case RF_WB_242_1: /* for FA5976A */ ltmp = pHwData->reg.BB5C & 0xfffff000; Wb35Reg_WriteSync(pHwData, 0x105c, ltmp); Wb35Reg_WriteSync(pHwData, 0x1058, 0); pHwData->reg.BB50 |= 0x3; /* (MASK_IQCAL_MODE|MASK_CALIB_START); */ Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50); /* ----- Calibration (1). VCO frequency calibration */ /* Calibration (1a.0). Synthesizer reset */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00101E, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); /* Calibration (1a). VCO frequency calibration mode ; waiting 2msec VCO calibration time */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFE69c0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(2); /* ----- Calibration (2). TX baseband Gm-C filter auto-tuning */ /* Calibration (2a). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF8EBC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (2b.0). TX filter auto-tuning BW: TFLBW=101 (TC5376A default) */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x07<<24) | 0x0C68CE, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (2b). send TX reset signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00201E, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (2c). turn-on TX Gm-C filter auto-tuning */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFCEBC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); udelay(150); /* Sleep 150 us */ /* turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF8EBC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* ----- Calibration (3). RX baseband Gm-C filter auto-tuning */ /* Calibration (3a). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (3b.0). RX filter auto-tuning BW: RFLBW=100 (TC5376A+corner default;) */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x07<<24) | 0x0C68CE, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (3b). send RX reset signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00401E, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (3c). turn-on RX Gm-C filter auto-tuning */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFEEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); udelay(150); /* Sleep 150 us */ /* Calibration (3e). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* ----- Calibration (4). TX LO leakage calibration */ /* Calibration (4a). TX LO leakage calibration */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFD6BC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); udelay(150); /* Sleep 150 us */ /* ----- Calibration (5). RX DC offset calibration */ /* Calibration (5a). turn off ENCAL signal and set to RX SW DC calibration mode */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5b). turn off AGC servo-loop & RSSI */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x01<<24) | 0xEBFFC2, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* for LNA=11 -------- */ /* Calibration (5c-h). RX DC offset current bias ON; & LNA=11; RXVGA=111111 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x343FCC, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(2); /* Calibration (5f). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* for LNA=10 -------- */ /* Calibration (5c-m). RX DC offset current bias ON; & LNA=10; RXVGA=111111 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x342FCC, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(2); /* Calibration (5f). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* for LNA=01 -------- */ /* Calibration (5c-m). RX DC offset current bias ON; & LNA=01; RXVGA=111111 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x341FCC, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(2); /* Calibration (5f). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* for LNA=00 -------- */ /* Calibration (5c-l). RX DC offset current bias ON; & LNA=00; RXVGA=111111 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x340FCC, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(2); /* Calibration (5f). turn off ENCAL signal */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* Calibration (5g). turn on AGC servo-loop */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x01<<24) | 0xEFFFC2, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); /* ----- Calibration (7). Switch RF chip to normal mode */ /* 0x00 0xF86100 ; 3E184 ; Switch RF chip to normal mode */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF86100, 24); Wb35Reg_WriteSync(pHwData, 0x0864, ltmp); msleep(5); break; } } void BBProcessor_AL7230_2400(struct hw_data *pHwData) { struct wb35_reg *reg = &pHwData->reg; u32 pltmp[12]; pltmp[0] = 0x16A8337A; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9AFF9AA6; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xFFF72031; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xFFF72031; pltmp[4] = 0x0FacDCC5; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00CAA333; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0xF2211111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x06443440; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0xA8002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0x40000528; pltmp[11] = 0x232D7F30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232D7F30; Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002c54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002c54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = 0x00332C1B; /* 0x1048 11b TX RC filter */ pltmp[7] = 0x0A00FEFF; /* 0x104c 11b TX RC filter */ pltmp[8] = 0x2B106208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x2B106208; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x52524242; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); } void BBProcessor_AL7230_5000(struct hw_data *pHwData) { struct wb35_reg *reg = &pHwData->reg; u32 pltmp[12]; pltmp[0] = 0x16AA6678; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9AFFA0B2; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xEFFF233E; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xEFFF233E; pltmp[4] = 0x0FacDCC5; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00CAA333; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0xF2432111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x05C43440; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0x40000528; pltmp[11] = 0x232FDF30;/* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232FDF30; Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x80002C7C; /* 0x1030 B_ACQ_Ctrl */ pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = 0x00332C1B; /* 0x1048 11b TX RC filter */ pltmp[7] = 0x0A00FEFF; /* 0x104c 11b TX RC filter */ pltmp[8] = 0x2B107208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x2B107208; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x52524242; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); } /* * =========================================================================== * BBProcessorPowerupInit -- * * Description: * Initialize the Baseband processor. * * Arguments: * pHwData - Handle of the USB Device. * * Return values: * None. *============================================================================ */ void BBProcessor_initial(struct hw_data *pHwData) { struct wb35_reg *reg = &pHwData->reg; u32 i, pltmp[12]; switch (pHwData->phy_type) { case RF_MAXIM_V1: /* Initializng the Winbond 2nd BB(with Phy board (v1) + Maxim 331) */ pltmp[0] = 0x16F47E77; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9AFFAEA4; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xEFFF1A34; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xEFFF1A34; pltmp[4] = 0x0FABE0B7; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00CAA332; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0xF6632111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = (pHwData->phy_type == 3) ? 0x40000a28 : 0x40000228; /* 0x1028 MAXIM_331(b31=0) + WBRF_V1(b11=1) : MAXIM_331(b31=0) + WBRF_V2(b11=0) */ pltmp[11] = 0x232FDF30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232FDF30; /* Modify for 33's 1.0.95.xxx version, antenna 1 */ Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B6C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = 0x00453B24; /* 0x1048 11b TX RC filter */ pltmp[7] = 0x0E00FEFF; /* 0x104c 11b TX RC filter */ pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106208; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x64646464; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x64646464; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_MAXIM_2825: case RF_MAXIM_2827: case RF_MAXIM_2828: pltmp[0] = 0x16b47e77; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9affaea4; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xefff1a34; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xefff1a34; pltmp[4] = 0x0fabe0b7; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0xf6632111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0x40000528; pltmp[11] = 0x232fdf30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232fdf30; /* antenna 1 */ Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B6C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = 0x00453B24; /* 0x1048 11b TX RC filter */ pltmp[7] = 0x0D00FDFF; /* 0x104c 11b TX RC filter */ pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106208; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x64646464; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x64646464; pltmp[11] = 0xAA28C000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_MAXIM_2829: pltmp[0] = 0x16b47e77; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9affaea4; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xf4ff1632; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xf4ff1632; pltmp[4] = 0x0fabe0b7; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0xf8632112; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0x40000528; pltmp[11] = 0x232fdf30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232fdf30; /* antenna 1 */ Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5b2c8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = 0x002c2617; /* 0x1048 11b TX RC filter */ pltmp[7] = 0x0800feff; /* 0x104c 11b TX RC filter */ pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106208; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x64644a4a; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x64646464; pltmp[11] = 0xAA28C000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_AIROHA_2230: pltmp[0] = 0X16764A77; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9affafb2; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xFFFd203c; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xFFFd203c; pltmp[4] = 0X0FBFDCc5; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0XF6632111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04C43640; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0X40000528; pltmp[11] = 0x232dfF30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232dfF30; /* antenna 1 */ Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = BB48_DEFAULT_AL2230_11G; /* 0x1048 11b TX RC filter */ reg->BB48 = BB48_DEFAULT_AL2230_11G; /* 20051221 ch14 */ pltmp[7] = BB4C_DEFAULT_AL2230_11G; /* 0x104c 11b TX RC filter */ reg->BB4C = BB4C_DEFAULT_AL2230_11G; pltmp[8] = 0x27106200; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106200; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x52524242; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_AIROHA_2230S: pltmp[0] = 0X16764A77; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9affafb2; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xFFFd203c; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xFFFd203c; pltmp[4] = 0X0FBFDCc5; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0XF6632111; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04C43640; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0X40000528; pltmp[11] = 0x232dfF30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x232dfF30; /* antenna 1 */ Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */ reg->BB3C = 0x00000000; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = BB48_DEFAULT_AL2230_11G; /* 0x1048 11b TX RC filter */ reg->BB48 = BB48_DEFAULT_AL2230_11G; /* ch14 */ pltmp[7] = BB4C_DEFAULT_AL2230_11G; /* 0x104c 11b TX RC filter */ reg->BB4C = BB4C_DEFAULT_AL2230_11G; pltmp[8] = 0x27106200; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106200; pltmp[9] = 0; /* 0x1054 */ reg->BB54 = 0x00000000; pltmp[10] = 0x52523232; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x52523232; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_AIROHA_7230: BBProcessor_AL7230_2400(pHwData); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; case RF_WB_242: case RF_WB_242_1: pltmp[0] = 0x16A8525D; /* 0x1000 AGC_Ctrl1 */ pltmp[1] = 0x9AFF9ABA; /* 0x1004 AGC_Ctrl2 */ pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */ pltmp[3] = 0xEEE91C32; /* 0x100c AGC_Ctrl4 */ reg->BB0C = 0xEEE91C32; pltmp[4] = 0x0FACDCC5; /* 0x1010 AGC_Ctrl5 */ pltmp[5] = 0x000AA344; /* 0x1014 AGC_Ctrl6 */ pltmp[6] = 0x22222221; /* 0x1018 AGC_Ctrl7 */ pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */ pltmp[8] = 0x04CC3440; /* 0x1020 AGC_Ctrl9 */ pltmp[9] = 0xA9002A79; /* 0x1024 AGC_Ctrl10 */ pltmp[10] = 0x40000528; /* 0x1028 */ pltmp[11] = 0x23457F30; /* 0x102c A_ACQ_Ctrl */ reg->BB2C = 0x23457F30; Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT); pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */ reg->BB30 = 0x00002C54; pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */ pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */ pltmp[3] = pHwData->BB3c_cal; /* 0x103c 11a TX LS filter */ reg->BB3C = pHwData->BB3c_cal; pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */ pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */ pltmp[6] = BB48_DEFAULT_WB242_11G; /* 0x1048 11b TX RC filter */ reg->BB48 = BB48_DEFAULT_WB242_11G; pltmp[7] = BB4C_DEFAULT_WB242_11G; /* 0x104c 11b TX RC filter */ reg->BB4C = BB4C_DEFAULT_WB242_11G; pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */ reg->BB50 = 0x27106208; pltmp[9] = pHwData->BB54_cal; /* 0x1054 */ reg->BB54 = pHwData->BB54_cal; pltmp[10] = 0x52523131; /* 0x1058 IQ_Alpha */ reg->BB58 = 0x52523131; pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */ Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT); Wb35Reg_Write(pHwData, 0x1070, 0x00000045); break; } /* Fill the LNA table */ reg->LNAValue[0] = (u8) (reg->BB0C & 0xff); reg->LNAValue[1] = 0; reg->LNAValue[2] = (u8) ((reg->BB0C & 0xff00) >> 8); reg->LNAValue[3] = 0; /* Fill SQ3 table */ for (i = 0; i < MAX_SQ3_FILTER_SIZE; i++) reg->SQ3_filter[i] = 0x2f; /* half of Bit 0 ~ 6 */ } void set_tx_power_per_channel_max2829(struct hw_data *pHwData, struct chan_info Channel) { RFSynthesizer_SetPowerIndex(pHwData, 100); } void set_tx_power_per_channel_al2230(struct hw_data *pHwData, struct chan_info Channel) { u8 index = 100; if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff) index = pHwData->TxVgaFor24[Channel.ChanNo - 1]; RFSynthesizer_SetPowerIndex(pHwData, index); } void set_tx_power_per_channel_al7230(struct hw_data *pHwData, struct chan_info Channel) { u8 i, index = 100; switch (Channel.band) { case BAND_TYPE_DSSS: case BAND_TYPE_OFDM_24: if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff) index = pHwData->TxVgaFor24[Channel.ChanNo - 1]; break; case BAND_TYPE_OFDM_5: for (i = 0; i < 35; i++) { if (Channel.ChanNo == pHwData->TxVgaFor50[i].ChanNo) { if (pHwData->TxVgaFor50[i].TxVgaValue != 0xff) index = pHwData->TxVgaFor50[i].TxVgaValue; break; } } break; } RFSynthesizer_SetPowerIndex(pHwData, index); } void set_tx_power_per_channel_wb242(struct hw_data *pHwData, struct chan_info Channel) { u8 index = 100; switch (Channel.band) { case BAND_TYPE_DSSS: case BAND_TYPE_OFDM_24: if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff) index = pHwData->TxVgaFor24[Channel.ChanNo - 1]; break; case BAND_TYPE_OFDM_5: break; } RFSynthesizer_SetPowerIndex(pHwData, index); } /* * ========================================================================== * RFSynthesizer_SwitchingChannel -- * * Description: * Swithch the RF channel. * * Arguments: * pHwData - Handle of the USB Device. * Channel - The channel no. * * Return values: * None. * =========================================================================== */ void RFSynthesizer_SwitchingChannel(struct hw_data *pHwData, struct chan_info Channel) { struct wb35_reg *reg = &pHwData->reg; u32 pltmp[16]; /* The 16 is the maximum capability of hardware */ u32 count, ltmp; u8 i, j, number; u8 ChnlTmp; switch (pHwData->phy_type) { case RF_MAXIM_2825: case RF_MAXIM_V1: /* 11g Winbond 2nd BB(with Phy board (v1) + Maxim 331) */ if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */ for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_channel_data_24[Channel.ChanNo-1][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } RFSynthesizer_SetPowerIndex(pHwData, 100); break; case RF_MAXIM_2827: if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */ for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_channel_data_24[Channel.ChanNo-1][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } else if (Channel.band == BAND_TYPE_OFDM_5) { /* channel 36 ~ 64 */ ChnlTmp = (Channel.ChanNo - 36) / 4; for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_channel_data_50[ChnlTmp][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } RFSynthesizer_SetPowerIndex(pHwData, 100); break; case RF_MAXIM_2828: if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */ for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_channel_data_24[Channel.ChanNo-1][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } else if (Channel.band == BAND_TYPE_OFDM_5) { /* channel 36 ~ 64 */ ChnlTmp = (Channel.ChanNo - 36) / 4; for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_channel_data_50[ChnlTmp][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } RFSynthesizer_SetPowerIndex(pHwData, 100); break; case RF_MAXIM_2829: if (Channel.band <= BAND_TYPE_OFDM_24) { for (i = 0; i < 3; i++) pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_channel_data_24[Channel.ChanNo-1][i], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } else if (Channel.band == BAND_TYPE_OFDM_5) { count = ARRAY_SIZE(max2829_channel_data_50); for (i = 0; i < count; i++) { if (max2829_channel_data_50[i][0] == Channel.ChanNo) { for (j = 0; j < 3; j++) pltmp[j] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_channel_data_50[i][j+1], 18); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); if ((max2829_channel_data_50[i][3] & 0x3FFFF) == 0x2A946) { ltmp = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse((5 << 18) | 0x2A906, 18); Wb35Reg_Write(pHwData, 0x0864, ltmp); } else { /* 0x2A9C6 */ ltmp = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse((5 << 18) | 0x2A986, 18); Wb35Reg_Write(pHwData, 0x0864, ltmp); } } } } set_tx_power_per_channel_max2829(pHwData, Channel); break; case RF_AIROHA_2230: case RF_AIROHA_2230S: if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */ for (i = 0; i < 2; i++) pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_channel_data_24[Channel.ChanNo-1][i], 20); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 2, NO_INCREMENT); } set_tx_power_per_channel_al2230(pHwData, Channel); break; case RF_AIROHA_7230: /* Channel independent registers */ if (Channel.band != pHwData->band) { if (Channel.band <= BAND_TYPE_OFDM_24) { /* Update BB register */ BBProcessor_AL7230_2400(pHwData); number = ARRAY_SIZE(al7230_rf_data_24); Set_ChanIndep_RfData_al7230_24(pHwData, pltmp, number); } else { /* Update BB register */ BBProcessor_AL7230_5000(pHwData); number = ARRAY_SIZE(al7230_rf_data_50); Set_ChanIndep_RfData_al7230_50(pHwData, pltmp, number); } /* Write to register. number must less and equal than 16 */ Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, number, NO_INCREMENT); pr_debug("Band changed\n"); } if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */ for (i = 0; i < 2; i++) pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_channel_data_24[Channel.ChanNo-1][i]&0xffffff); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 2, NO_INCREMENT); } else if (Channel.band == BAND_TYPE_OFDM_5) { /* Update Reg12 */ if ((Channel.ChanNo > 64) && (Channel.ChanNo <= 165)) { ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x00143c; Wb35Reg_Write(pHwData, 0x0864, ltmp); } else { /* reg12 = 0x00147c at Channel 4920 ~ 5320 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x00147c; Wb35Reg_Write(pHwData, 0x0864, ltmp); } count = ARRAY_SIZE(al7230_channel_data_5); for (i = 0; i < count; i++) { if (al7230_channel_data_5[i][0] == Channel.ChanNo) { for (j = 0; j < 3; j++) pltmp[j] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_channel_data_5[i][j+1] & 0xffffff); Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT); } } } set_tx_power_per_channel_al7230(pHwData, Channel); break; case RF_WB_242: case RF_WB_242_1: if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */ ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(w89rf242_channel_data_24[Channel.ChanNo-1][0], 24); Wb35Reg_Write(pHwData, 0x864, ltmp); } set_tx_power_per_channel_wb242(pHwData, Channel); break; } if (Channel.band <= BAND_TYPE_OFDM_24) { /* BB: select 2.4 GHz, bit[12-11]=00 */ reg->BB50 &= ~(BIT(11) | BIT(12)); Wb35Reg_Write(pHwData, 0x1050, reg->BB50); /* MODE_Ctrl */ /* MAC: select 2.4 GHz, bit[5]=0 */ reg->M78_ERPInformation &= ~BIT(5); Wb35Reg_Write(pHwData, 0x0878, reg->M78_ERPInformation); /* enable 11b Baseband */ reg->BB30 &= ~BIT(31); Wb35Reg_Write(pHwData, 0x1030, reg->BB30); } else if (Channel.band == BAND_TYPE_OFDM_5) { /* BB: select 5 GHz */ reg->BB50 &= ~(BIT(11) | BIT(12)); if (Channel.ChanNo <= 64) reg->BB50 |= BIT(12); /* 10-5.25GHz */ else if ((Channel.ChanNo >= 100) && (Channel.ChanNo <= 124)) reg->BB50 |= BIT(11); /* 01-5.48GHz */ else if ((Channel.ChanNo >= 128) && (Channel.ChanNo <= 161)) reg->BB50 |= (BIT(12) | BIT(11)); /* 11-5.775GHz */ else /* Chan 184 ~ 196 will use bit[12-11] = 10 in version sh-src-1.2.25 */ reg->BB50 |= BIT(12); Wb35Reg_Write(pHwData, 0x1050, reg->BB50); /* MODE_Ctrl */ /* (1) M78 should alway use 2.4G setting when using RF_AIROHA_7230 */ /* (2) BB30 has been updated previously. */ if (pHwData->phy_type != RF_AIROHA_7230) { /* MAC: select 5 GHz, bit[5]=1 */ reg->M78_ERPInformation |= BIT(5); Wb35Reg_Write(pHwData, 0x0878, reg->M78_ERPInformation); /* disable 11b Baseband */ reg->BB30 |= BIT(31); Wb35Reg_Write(pHwData, 0x1030, reg->BB30); } } } /* * Set the tx power directly from DUT GUI, not from the EEPROM. * Return the current setting */ u8 RFSynthesizer_SetPowerIndex(struct hw_data *pHwData, u8 PowerIndex) { u32 Band = pHwData->band; u8 index = 0; if (pHwData->power_index == PowerIndex) return PowerIndex; if (RF_MAXIM_2825 == pHwData->phy_type) { /* Channel 1 - 13 */ index = RFSynthesizer_SetMaxim2825Power(pHwData, PowerIndex); } else if (RF_MAXIM_2827 == pHwData->phy_type) { if (Band <= BAND_TYPE_OFDM_24) /* Channel 1 - 13 */ index = RFSynthesizer_SetMaxim2827_24Power(pHwData, PowerIndex); else /* Channel 36 - 64 */ index = RFSynthesizer_SetMaxim2827_50Power(pHwData, PowerIndex); } else if (RF_MAXIM_2828 == pHwData->phy_type) { if (Band <= BAND_TYPE_OFDM_24) /* Channel 1 - 13 */ index = RFSynthesizer_SetMaxim2828_24Power(pHwData, PowerIndex); else /* Channel 36 - 64 */ index = RFSynthesizer_SetMaxim2828_50Power(pHwData, PowerIndex); } else if (RF_AIROHA_2230 == pHwData->phy_type) { /* Power index: 0 ~ 63 --- Channel 1 - 14 */ index = RFSynthesizer_SetAiroha2230Power(pHwData, PowerIndex); index = (u8) al2230_txvga_data[index][1]; } else if (RF_AIROHA_2230S == pHwData->phy_type) { /* Power index: 0 ~ 63 --- Channel 1 - 14 */ index = RFSynthesizer_SetAiroha2230Power(pHwData, PowerIndex); index = (u8) al2230_txvga_data[index][1]; } else if (RF_AIROHA_7230 == pHwData->phy_type) { /* Power index: 0 ~ 63 */ index = RFSynthesizer_SetAiroha7230Power(pHwData, PowerIndex); index = (u8)al7230_txvga_data[index][1]; } else if ((RF_WB_242 == pHwData->phy_type) || (RF_WB_242_1 == pHwData->phy_type)) { /* Power index: 0 ~ 19 for original. New range is 0 ~ 33 */ index = RFSynthesizer_SetWinbond242Power(pHwData, PowerIndex); index = (u8)w89rf242_txvga_data[index][1]; } pHwData->power_index = index; /* Backup current */ return index; } /* -- Sub function */ u8 RFSynthesizer_SetMaxim2828_24Power(struct hw_data *pHwData, u8 index) { u32 PowerData; if (index > 1) index = 1; PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_power_data_24[index], 18); Wb35Reg_Write(pHwData, 0x0864, PowerData); return index; } u8 RFSynthesizer_SetMaxim2828_50Power(struct hw_data *pHwData, u8 index) { u32 PowerData; if (index > 1) index = 1; PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_power_data_50[index], 18); Wb35Reg_Write(pHwData, 0x0864, PowerData); return index; } u8 RFSynthesizer_SetMaxim2827_24Power(struct hw_data *pHwData, u8 index) { u32 PowerData; if (index > 1) index = 1; PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_power_data_24[index], 18); Wb35Reg_Write(pHwData, 0x0864, PowerData); return index; } u8 RFSynthesizer_SetMaxim2827_50Power(struct hw_data *pHwData, u8 index) { u32 PowerData; if (index > 1) index = 1; PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_power_data_50[index], 18); Wb35Reg_Write(pHwData, 0x0864, PowerData); return index; } u8 RFSynthesizer_SetMaxim2825Power(struct hw_data *pHwData, u8 index) { u32 PowerData; if (index > 1) index = 1; PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_power_data_24[index], 18); Wb35Reg_Write(pHwData, 0x0864, PowerData); return index; } u8 RFSynthesizer_SetAiroha2230Power(struct hw_data *pHwData, u8 index) { u32 PowerData; u8 i, count; count = ARRAY_SIZE(al2230_txvga_data); for (i = 0; i < count; i++) { if (al2230_txvga_data[i][1] >= index) break; } if (i == count) i--; PowerData = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_txvga_data[i][0], 20); Wb35Reg_Write(pHwData, 0x0864, PowerData); return i; } u8 RFSynthesizer_SetAiroha7230Power(struct hw_data *pHwData, u8 index) { u32 PowerData; u8 i, count; count = ARRAY_SIZE(al7230_txvga_data); for (i = 0; i < count; i++) { if (al7230_txvga_data[i][1] >= index) break; } if (i == count) i--; PowerData = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_txvga_data[i][0] & 0xffffff); Wb35Reg_Write(pHwData, 0x0864, PowerData); return i; } u8 RFSynthesizer_SetWinbond242Power(struct hw_data *pHwData, u8 index) { u32 PowerData; u8 i, count; count = ARRAY_SIZE(w89rf242_txvga_data); for (i = 0; i < count; i++) { if (w89rf242_txvga_data[i][1] >= index) break; } if (i == count) i--; /* Set TxVga into RF */ PowerData = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(w89rf242_txvga_data[i][0], 24); Wb35Reg_Write(pHwData, 0x0864, PowerData); /* Update BB48 BB4C BB58 for high precision txvga */ Wb35Reg_Write(pHwData, 0x1048, w89rf242_txvga_data[i][2]); Wb35Reg_Write(pHwData, 0x104c, w89rf242_txvga_data[i][3]); Wb35Reg_Write(pHwData, 0x1058, w89rf242_txvga_data[i][4]); return i; } /* * =========================================================================== * Dxx_initial -- * Mxx_initial -- * * Routine Description: * Initial the hardware setting and module variable * =========================================================================== */ void Dxx_initial(struct hw_data *pHwData) { struct wb35_reg *reg = &pHwData->reg; /* * Old IC: Single mode only. * New IC: operation decide by Software set bit[4]. 1:multiple 0: single */ reg->D00_DmaControl = 0xc0000004; /* Txon, Rxon, multiple Rx for new 4k DMA */ /* Txon, Rxon, single Rx for old 8k ASIC */ if (!HAL_USB_MODE_BURST(pHwData)) reg->D00_DmaControl = 0xc0000000; /* Txon, Rxon, single Rx for new 4k DMA */ Wb35Reg_WriteSync(pHwData, 0x0400, reg->D00_DmaControl); } void Mxx_initial(struct hw_data *pHwData) { struct wb35_reg *reg = &pHwData->reg; u32 tmp; u32 pltmp[11]; u16 i; /* * ====================================================== * Initial Mxx register * ====================================================== */ /* M00 bit set */ reg->M00_MacControl = 0x80000000; /* Solve beacon sequence number stop by hardware */ /* M24 disable enter power save, BB RxOn and enable NAV attack */ reg->M24_MacControl = 0x08040042; pltmp[0] = reg->M24_MacControl; pltmp[1] = 0; /* Skip M28, because no initialize value is required. */ /* M2C CWmin and CWmax setting */ pHwData->cwmin = DEFAULT_CWMIN; pHwData->cwmax = DEFAULT_CWMAX; reg->M2C_MacControl = DEFAULT_CWMIN << 10; reg->M2C_MacControl |= DEFAULT_CWMAX; pltmp[2] = reg->M2C_MacControl; /* M30 BSSID */ pltmp[3] = *(u32 *)pHwData->bssid; /* M34 */ pHwData->AID = DEFAULT_AID; tmp = *(u16 *) (pHwData->bssid + 4); tmp |= DEFAULT_AID << 16; pltmp[4] = tmp; /* M38 */ reg->M38_MacControl = (DEFAULT_RATE_RETRY_LIMIT << 8) | (DEFAULT_LONG_RETRY_LIMIT << 4) | DEFAULT_SHORT_RETRY_LIMIT; pltmp[5] = reg->M38_MacControl; /* M3C */ tmp = (DEFAULT_PIFST << 26) | (DEFAULT_EIFST << 16) | (DEFAULT_DIFST << 8) | (DEFAULT_SIFST << 4) | DEFAULT_OSIFST ; reg->M3C_MacControl = tmp; pltmp[6] = tmp; /* M40 */ pHwData->slot_time_select = DEFAULT_SLOT_TIME; tmp = (DEFAULT_ATIMWD << 16) | DEFAULT_SLOT_TIME; reg->M40_MacControl = tmp; pltmp[7] = tmp; /* M44 */ tmp = DEFAULT_MAX_TX_MSDU_LIFE_TIME << 10; /* *1024 */ reg->M44_MacControl = tmp; pltmp[8] = tmp; /* M48 */ pHwData->BeaconPeriod = DEFAULT_BEACON_INTERVAL; pHwData->ProbeDelay = DEFAULT_PROBE_DELAY_TIME; tmp = (DEFAULT_BEACON_INTERVAL << 16) | DEFAULT_PROBE_DELAY_TIME; reg->M48_MacControl = tmp; pltmp[9] = tmp; /* M4C */ reg->M4C_MacStatus = (DEFAULT_PROTOCOL_VERSION << 30) | (DEFAULT_MAC_POWER_STATE << 28) | (DEFAULT_DTIM_ALERT_TIME << 24); pltmp[10] = reg->M4C_MacStatus; for (i = 0; i < 11; i++) Wb35Reg_WriteSync(pHwData, 0x0824 + i * 4, pltmp[i]); /* M60 */ Wb35Reg_WriteSync(pHwData, 0x0860, 0x12481248); reg->M60_MacControl = 0x12481248; /* M68 */ Wb35Reg_WriteSync(pHwData, 0x0868, 0x00050900); reg->M68_MacControl = 0x00050900; /* M98 */ Wb35Reg_WriteSync(pHwData, 0x0898, 0xffff8888); reg->M98_MacControl = 0xffff8888; } void Uxx_power_off_procedure(struct hw_data *pHwData) { /* SW, PMU reset and turn off clock */ Wb35Reg_WriteSync(pHwData, 0x03b0, 3); Wb35Reg_WriteSync(pHwData, 0x03f0, 0xf9); } /*Decide the TxVga of every channel */ void GetTxVgaFromEEPROM(struct hw_data *pHwData) { u32 i, j, ltmp; u16 Value[MAX_TXVGA_EEPROM]; u8 *pctmp; u8 ctmp = 0; /* Get the entire TxVga setting in EEPROM */ for (i = 0; i < MAX_TXVGA_EEPROM; i++) { Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08100000 + 0x00010000 * i); Wb35Reg_ReadSync(pHwData, 0x03b4, &ltmp); Value[i] = (u16) (ltmp & 0xffff); /* Get 16 bit available */ Value[i] = cpu_to_le16(Value[i]); /* [7:0]2412 [7:0]2417 .... */ } /* Adjust the filed which fills with reserved value. */ pctmp = (u8 *) Value; for (i = 0; i < (MAX_TXVGA_EEPROM * 2); i++) { if (pctmp[i] != 0xff) ctmp = pctmp[i]; else pctmp[i] = ctmp; } /* Adjust WB_242 to WB_242_1 TxVga scale */ if (pHwData->phy_type == RF_WB_242) { for (i = 0; i < 4; i++) { /* Only 2412 2437 2462 2484 case must be modified */ for (j = 0; j < ARRAY_SIZE(w89rf242_txvga_old_mapping); j++) { if (pctmp[i] < (u8) w89rf242_txvga_old_mapping[j][1]) { pctmp[i] = (u8) w89rf242_txvga_old_mapping[j][0]; break; } } if (j == ARRAY_SIZE(w89rf242_txvga_old_mapping)) pctmp[i] = (u8)w89rf242_txvga_old_mapping[j-1][0]; } } memcpy(pHwData->TxVgaSettingInEEPROM, pctmp, MAX_TXVGA_EEPROM * 2); /* MAX_TXVGA_EEPROM is u16 count */ EEPROMTxVgaAdjust(pHwData); } /* * This function will affect the TxVga parameter in HAL. If hal_set_current_channel * or RFSynthesizer_SetPowerIndex be called, new TxVga will take effect. * TxVgaSettingInEEPROM of sHwData is an u8 array point to EEPROM contain for IS89C35 * This function will use default TxVgaSettingInEEPROM data to calculate new TxVga. */ void EEPROMTxVgaAdjust(struct hw_data *pHwData) { u8 *pTxVga = pHwData->TxVgaSettingInEEPROM; s16 i, stmp; /* -- 2.4G -- */ /* channel 1 ~ 5 */ stmp = pTxVga[1] - pTxVga[0]; for (i = 0; i < 5; i++) pHwData->TxVgaFor24[i] = pTxVga[0] + stmp * i / 4; /* channel 6 ~ 10 */ stmp = pTxVga[2] - pTxVga[1]; for (i = 5; i < 10; i++) pHwData->TxVgaFor24[i] = pTxVga[1] + stmp * (i - 5) / 4; /* channel 11 ~ 13 */ stmp = pTxVga[3] - pTxVga[2]; for (i = 10; i < 13; i++) pHwData->TxVgaFor24[i] = pTxVga[2] + stmp * (i - 10) / 2; /* channel 14 */ pHwData->TxVgaFor24[13] = pTxVga[3]; /* -- 5G -- */ if (pHwData->phy_type == RF_AIROHA_7230) { /* channel 184 */ pHwData->TxVgaFor50[0].ChanNo = 184; pHwData->TxVgaFor50[0].TxVgaValue = pTxVga[4]; /* channel 196 */ pHwData->TxVgaFor50[3].ChanNo = 196; pHwData->TxVgaFor50[3].TxVgaValue = pTxVga[5]; /* interpolate */ pHwData->TxVgaFor50[1].ChanNo = 188; pHwData->TxVgaFor50[2].ChanNo = 192; stmp = pTxVga[5] - pTxVga[4]; pHwData->TxVgaFor50[2].TxVgaValue = pTxVga[5] - stmp / 3; pHwData->TxVgaFor50[1].TxVgaValue = pTxVga[5] - stmp * 2 / 3; /* channel 16 */ pHwData->TxVgaFor50[6].ChanNo = 16; pHwData->TxVgaFor50[6].TxVgaValue = pTxVga[6]; pHwData->TxVgaFor50[4].ChanNo = 8; pHwData->TxVgaFor50[4].TxVgaValue = pTxVga[6]; pHwData->TxVgaFor50[5].ChanNo = 12; pHwData->TxVgaFor50[5].TxVgaValue = pTxVga[6]; /* channel 36 */ pHwData->TxVgaFor50[8].ChanNo = 36; pHwData->TxVgaFor50[8].TxVgaValue = pTxVga[7]; pHwData->TxVgaFor50[7].ChanNo = 34; pHwData->TxVgaFor50[7].TxVgaValue = pTxVga[7]; pHwData->TxVgaFor50[9].ChanNo = 38; pHwData->TxVgaFor50[9].TxVgaValue = pTxVga[7]; /* channel 40 */ pHwData->TxVgaFor50[10].ChanNo = 40; pHwData->TxVgaFor50[10].TxVgaValue = pTxVga[8]; /* channel 48 */ pHwData->TxVgaFor50[14].ChanNo = 48; pHwData->TxVgaFor50[14].TxVgaValue = pTxVga[9]; /* interpolate */ pHwData->TxVgaFor50[11].ChanNo = 42; pHwData->TxVgaFor50[12].ChanNo = 44; pHwData->TxVgaFor50[13].ChanNo = 46; stmp = pTxVga[9] - pTxVga[8]; pHwData->TxVgaFor50[13].TxVgaValue = pTxVga[9] - stmp / 4; pHwData->TxVgaFor50[12].TxVgaValue = pTxVga[9] - stmp * 2 / 4; pHwData->TxVgaFor50[11].TxVgaValue = pTxVga[9] - stmp * 3 / 4; /* channel 52 */ pHwData->TxVgaFor50[15].ChanNo = 52; pHwData->TxVgaFor50[15].TxVgaValue = pTxVga[10]; /* channel 64 */ pHwData->TxVgaFor50[18].ChanNo = 64; pHwData->TxVgaFor50[18].TxVgaValue = pTxVga[11]; /* interpolate */ pHwData->TxVgaFor50[16].ChanNo = 56; pHwData->TxVgaFor50[17].ChanNo = 60; stmp = pTxVga[11] - pTxVga[10]; pHwData->TxVgaFor50[17].TxVgaValue = pTxVga[11] - stmp / 3; pHwData->TxVgaFor50[16].TxVgaValue = pTxVga[11] - stmp * 2 / 3; /* channel 100 */ pHwData->TxVgaFor50[19].ChanNo = 100; pHwData->TxVgaFor50[19].TxVgaValue = pTxVga[12]; /* channel 112 */ pHwData->TxVgaFor50[22].ChanNo = 112; pHwData->TxVgaFor50[22].TxVgaValue = pTxVga[13]; /* interpolate */ pHwData->TxVgaFor50[20].ChanNo = 104; pHwData->TxVgaFor50[21].ChanNo = 108; stmp = pTxVga[13] - pTxVga[12]; pHwData->TxVgaFor50[21].TxVgaValue = pTxVga[13] - stmp / 3; pHwData->TxVgaFor50[20].TxVgaValue = pTxVga[13] - stmp * 2 / 3; /* channel 128 */ pHwData->TxVgaFor50[26].ChanNo = 128; pHwData->TxVgaFor50[26].TxVgaValue = pTxVga[14]; /* interpolate */ pHwData->TxVgaFor50[23].ChanNo = 116; pHwData->TxVgaFor50[24].ChanNo = 120; pHwData->TxVgaFor50[25].ChanNo = 124; stmp = pTxVga[14] - pTxVga[13]; pHwData->TxVgaFor50[25].TxVgaValue = pTxVga[14] - stmp / 4; pHwData->TxVgaFor50[24].TxVgaValue = pTxVga[14] - stmp * 2 / 4; pHwData->TxVgaFor50[23].TxVgaValue = pTxVga[14] - stmp * 3 / 4; /* channel 140 */ pHwData->TxVgaFor50[29].ChanNo = 140; pHwData->TxVgaFor50[29].TxVgaValue = pTxVga[15]; /* interpolate */ pHwData->TxVgaFor50[27].ChanNo = 132; pHwData->TxVgaFor50[28].ChanNo = 136; stmp = pTxVga[15] - pTxVga[14]; pHwData->TxVgaFor50[28].TxVgaValue = pTxVga[15] - stmp / 3; pHwData->TxVgaFor50[27].TxVgaValue = pTxVga[15] - stmp * 2 / 3; /* channel 149 */ pHwData->TxVgaFor50[30].ChanNo = 149; pHwData->TxVgaFor50[30].TxVgaValue = pTxVga[16]; /* channel 165 */ pHwData->TxVgaFor50[34].ChanNo = 165; pHwData->TxVgaFor50[34].TxVgaValue = pTxVga[17]; /* interpolate */ pHwData->TxVgaFor50[31].ChanNo = 153; pHwData->TxVgaFor50[32].ChanNo = 157; pHwData->TxVgaFor50[33].ChanNo = 161; stmp = pTxVga[17] - pTxVga[16]; pHwData->TxVgaFor50[33].TxVgaValue = pTxVga[17] - stmp / 4; pHwData->TxVgaFor50[32].TxVgaValue = pTxVga[17] - stmp * 2 / 4; pHwData->TxVgaFor50[31].TxVgaValue = pTxVga[17] - stmp * 3 / 4; } } void BBProcessor_RateChanging(struct hw_data *pHwData, u8 rate) { struct wb35_reg *reg = &pHwData->reg; unsigned char Is11bRate; Is11bRate = (rate % 6) ? 1 : 0; switch (pHwData->phy_type) { case RF_AIROHA_2230: case RF_AIROHA_2230S: if (Is11bRate) { if ((reg->BB48 != BB48_DEFAULT_AL2230_11B) && (reg->BB4C != BB4C_DEFAULT_AL2230_11B)) { Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_AL2230_11B); Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_AL2230_11B); } } else { if ((reg->BB48 != BB48_DEFAULT_AL2230_11G) && (reg->BB4C != BB4C_DEFAULT_AL2230_11G)) { Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_AL2230_11G); Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_AL2230_11G); } } break; case RF_WB_242: if (Is11bRate) { if ((reg->BB48 != BB48_DEFAULT_WB242_11B) && (reg->BB4C != BB4C_DEFAULT_WB242_11B)) { reg->BB48 = BB48_DEFAULT_WB242_11B; reg->BB4C = BB4C_DEFAULT_WB242_11B; Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_WB242_11B); Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_WB242_11B); } } else { if ((reg->BB48 != BB48_DEFAULT_WB242_11G) && (reg->BB4C != BB4C_DEFAULT_WB242_11G)) { reg->BB48 = BB48_DEFAULT_WB242_11G; reg->BB4C = BB4C_DEFAULT_WB242_11G; Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_WB242_11G); Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_WB242_11G); } } break; } }
123426.c
/* Tomato Firmware Copyright (C) 2006-2009 Jonathan Zarate */ #include "rc.h" void create_passwd(void) { char s[512]; char *p; char salt[32]; FILE *f; mode_t m; #ifdef TCONFIG_SAMBASRV //!!TB char *smbd_user; #endif strcpy(salt, "$1$"); f_read("/dev/urandom", s, 6); base64_encode(s, salt + 3, 6); salt[3 + 8] = 0; p = salt; while (*p) { if (*p == '+') *p = '.'; ++p; } if (((p = nvram_get("http_passwd")) == NULL) || (*p == 0)) p = "admin"; #ifdef TCONFIG_SAMBASRV //!!TB if (((smbd_user = nvram_get("smbd_user")) == NULL) || (*smbd_user == 0) || !strcmp(smbd_user, "root")) smbd_user = "nas"; #endif m = umask(0777); if ((f = fopen("/etc/shadow", "w")) != NULL) { p = crypt(p, salt); fprintf(f, "root:%s:0:0:99999:7:0:0:\n" "nobody:*:0:0:99999:7:0:0:\n", p); #if TOMATO_SL // todo zzz fprintf(f, "admin:*:0:0:99999:7:0:0:\n"); #endif #ifdef TCONFIG_SAMBASRV //!!TB fprintf(f, "%s:*:0:0:99999:7:0:0:\n", smbd_user); #endif fappend(f, "/etc/shadow.custom"); fclose(f); } umask(m); chmod("/etc/shadow", 0600); #ifdef TCONFIG_SAMBASRV //!!TB sprintf(s, "root:x:0:0:root:/root:/bin/sh\n" "%s:x:100:100:nas:/dev/null:/dev/null\n" "nobody:x:65534:65534:nobody:/dev/null:/dev/null\n", smbd_user); f_write_string("/etc/passwd", s, 0, 0644); #else //!!TB f_write_string("/etc/passwd", "root:x:0:0:root:/root:/bin/sh\n" #if TOMATO_SL // todo zzz "admin:x:100:100:nas:/dev/null:/dev/null\n" #endif "nobody:x:65534:65534:nobody:/dev/null:/dev/null\n", 0, 0644); #endif //!!TB fappend_file("/etc/passwd", "/etc/passwd.custom"); f_write_string("/etc/gshadow", "root:*:0:\n" //#if TOMATO_SL #ifdef TCONFIG_SAMBASRV //!!TB "nas:*:100:\n" #endif "nobody:*:65534:\n", 0, 0600); fappend_file("/etc/gshadow", "/etc/gshadow.custom"); f_write_string("/etc/group", "root:x:0:\n" //#if TOMATO_SL #ifdef TCONFIG_SAMBASRV //!!TB "nas:x:100:\n" #endif "nobody:x:65534:\n", 0, 0644); fappend_file("/etc/group", "/etc/group.custom"); } static inline int check_host_key(const char *ktype, const char *nvname, const char *hkfn) { unlink(hkfn); if (!nvram_get_file(nvname, hkfn, 2048)) { eval("dropbearkey", "-t", (char *)ktype, "-f", (char *)hkfn); if (nvram_set_file(nvname, hkfn, 2048)) { return 1; } } return 0; } void start_sshd(void) { int dirty = 0; mkdir("/etc/dropbear", 0700); mkdir("/root/.ssh", 0700); f_write_string("/root/.ssh/authorized_keys", nvram_safe_get("sshd_authkeys"), 0, 0600); dirty |= check_host_key("rsa", "sshd_hostkey", "/etc/dropbear/dropbear_rsa_host_key"); dirty |= check_host_key("dss", "sshd_dsskey", "/etc/dropbear/dropbear_dss_host_key"); if (dirty) nvram_commit_x(); /* xstart("dropbear", "-a", "-p", nvram_safe_get("sshd_port"), nvram_get_int("sshd_pass") ? "" : "-s"); */ char *argv[11]; int argc; char *p; argv[0] = "dropbear"; argv[1] = "-p"; argv[2] = nvram_safe_get("sshd_port"); argc = 3; if (nvram_get_int("sshd_remote") && nvram_invmatch("sshd_rport", nvram_safe_get("sshd_port"))) { argv[argc++] = "-p"; argv[argc++] = nvram_safe_get("sshd_rport"); } if (!nvram_get_int("sshd_pass")) argv[argc++] = "-s"; if (nvram_get_int("sshd_forwarding")) argv[argc++] = "-a"; if (((p = nvram_get("sshd_rwb")) != NULL) && (*p)) { argv[argc++] = "-W"; argv[argc++] = p; } argv[argc] = NULL; _eval(argv, NULL, 0, NULL); } void stop_sshd(void) { killall("dropbear", SIGTERM); } void start_telnetd(void) { xstart("telnetd", "-p", nvram_safe_get("telnetd_port")); } void stop_telnetd(void) { killall("telnetd", SIGTERM); }
363674.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_farm.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ffloris <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/26 16:50:19 by ffloris #+# #+# */ /* Updated: 2018/04/27 18:20:01 by ffloris ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" static void setup_farm(t_farm *farm) { farm->ants = NULL; farm->start = NULL; farm->end = NULL; farm->rooms = NULL; farm->turns = NULL; farm->links = NULL; } int parse_farm(t_list **input, t_farm *farm) { t_list *in; setup_farm(farm); if (!parse_input(input)) return (0); in = *input; if (!parse_ants(&in, farm)) return (0); if (!parse_rooms(&in, farm)) return (0); if (!parse_links(&in, farm)) return (0); return (1); }
344132.c
#include <std.h> #include <move.h> #include "../../tecqumin.h" inherit J_ROOM; void create() { ::create(); set_exits( ([ "south" : TABAXROOM + "jungle45", "east" : TABAXROOM + "jungle43" ]) ); } void init(){ ::init(); set_had_players(3); }
810034.c
//Chapter 3 Programming Project #5 from king's Modern C //Write a program that aks the user to enter the numbers from //1-16(in any order) and then displays the numbers //in a 4 by 4 arrangement, followed by the sums //of the rows, columns, and diagnols //I know this is an awful way of doing it, but this is early in the book before we learn things like loops or decision statements. #include <stdio.h> int main(void) { int num,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12,num13,num14,num15,num16; printf("Enter the numbers from 1 to 16 in any order: "); scanf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",&num,&num2,&num3,&num4,&num5,&num6,&num7,&num8,&num9,&num10,&num11,&num12,&num13,&num14,&num15,&num16); printf(" %2d %2d %2d %2d \n %2d %2d %2d %2d \n %2d %2d %2d %2d \n %2d %2d %2d %2d\n",num,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12,num13,num14,num15,num16); printf("Row sums: %d %d %d %d\n",num+num2+num3+num4,num5+num6+num7+num8,num9+num10+num11+num12,num13+num14+num15+num16); printf("Column sums: %d %d %d %d\n",num+num5+num9+num13,num2+num6+num10+num14,num3+num7+num11+num15,num4+num8+num12+num16); printf("Diagonal sums: %d %d",num+num6+num11+num16,num4+num7+num10+num13); return 0; }
703796.c
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2020 INRIA. * * 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 lcp_avi_caoferris.c \brief Solve an LCP by reformulating it as an AVI and the solver by Cao and Ferris solves the subsequent AVI. */ #include <assert.h> // for assert #include <stdlib.h> // for calloc, malloc, rand, NULL #include "AVI_Solvers.h" // for avi_caoferris #include "AffineVariationalInequalities.h" // for AffineVariationalInequali... #include "NumericsFwd.h" // for RelayProblem, AffineVaria... #include "NumericsMatrix.h" // for NM_create_from_data, NM_D... #include "RelayProblem.h" // for RelayProblem #include "Relay_Solvers.h" // for relay_avi_caoferris_test #include "SiconosSets.h" // for polyhedron, free_polyhedron #include "debug.h" // for DEBUG_EXPR_WE, DEBUG_PRINT void relay_avi_caoferris_test(RelayProblem* problem, double *z, double *w, int *info, SolverOptions* options) { unsigned int n = problem->size; assert(n > 0); assert(problem->M); unsigned int s = 2*n; /* Copy the data from Relay problem to an AVI struct */ AffineVariationalInequalities avi_pb; avi_pb.size = n; avi_pb.M = problem->M; avi_pb.q = problem->q; polyhedron poly; avi_pb.poly.split = &poly; poly.id = SICONOS_SET_POLYHEDRON; poly.size_ineq = s; poly.size_eq = 0; poly.H = NM_create_from_data(NM_DENSE, s, n, calloc(s*n, sizeof(double))); double* H = poly.H->matrix0; poly.K = (double *)malloc(s*sizeof(double)); poly.Heq = NULL; poly.Keq = NULL; DEBUG_PRINT_VEC(problem->lb, n); DEBUG_PRINT_VEC(problem->ub, n); int starting_constraint = rand() % s; for(unsigned i = 0, j = starting_constraint; i < s; ++i, j = (j+1) % s) { if(j >= n) { H[i + s*(j-n)] = 1.0; poly.K[i] = problem->lb[j-n]; } else { H[i + s*j] = -1.0; poly.K[i] = -problem->ub[j]; } } DEBUG_PRINT("H matrix\n"); DEBUG_EXPR_WE(for(unsigned i = 0; i < s; ++i) { for(unsigned j = 0 ; j < n; ++j) { DEBUG_PRINTF("% 2.2e ", H[i + j*s]) } DEBUG_PRINT("\n") }); DEBUG_PRINT("K vector\n"); DEBUG_EXPR_WE(for(unsigned i = 0; i < s; ++i) { DEBUG_PRINTF("% 2.2e ", poly.K[i]) DEBUG_PRINT("\n") }); /* Call directly the 3rd stage * Here w is used as u and z as s in the AVI */ *info = avi_caoferris(&avi_pb, z, w, options); free_polyhedron(&poly); }
837772.c
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_bzero.c :+: :+: */ /* +:+ */ /* By: hyilmaz <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/10/29 22:53:23 by hyilmaz #+# #+# */ /* Updated: 2021/03/09 11:44:50 by hyilmaz ######## odam.nl */ /* */ /* ************************************************************************** */ #include "../libft.h" void ft_bzero(void *s, size_t n) { size_t i; unsigned char *ptr_s; i = 0; ptr_s = s; while (i < n) { *(ptr_s + i) = '\0'; i++; } }
564282.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. * * The Original Code is Copyright (C) 2008 Blender Foundation. * All rights reserved. */ /** \file * \ingroup spseq */ #include <stdio.h> #include <string.h> #include "DNA_gpencil_types.h" #include "DNA_mask_types.h" #include "DNA_scene_types.h" #include "MEM_guardedalloc.h" #include "BLI_blenlib.h" #include "BLI_utildefines.h" #include "BKE_context.h" #include "BKE_global.h" #include "BKE_lib_id.h" #include "BKE_screen.h" #include "BKE_sequencer.h" #include "BKE_sequencer_offscreen.h" #include "ED_screen.h" #include "ED_space_api.h" #include "ED_view3d.h" #include "ED_view3d_offscreen.h" /* Only for sequencer view3d drawing callback. */ #include "WM_api.h" #include "WM_message.h" #include "WM_types.h" #include "RNA_access.h" #include "UI_interface.h" #include "UI_resources.h" #include "UI_view2d.h" #include "IMB_imbuf.h" /* Own include. */ #include "sequencer_intern.h" /**************************** common state *****************************/ static void sequencer_scopes_tag_refresh(ScrArea *area) { SpaceSeq *sseq = (SpaceSeq *)area->spacedata.first; sseq->scopes.reference_ibuf = NULL; } /* ******************** manage regions ********************* */ static ARegion *sequencer_find_region(ScrArea *area, short type) { ARegion *region = NULL; for (region = area->regionbase.first; region; region = region->next) { if (region->regiontype == type) { return region; } } return region; } /* ******************** default callbacks for sequencer space ***************** */ static SpaceLink *sequencer_new(const ScrArea *UNUSED(area), const Scene *scene) { ARegion *region; SpaceSeq *sseq; sseq = MEM_callocN(sizeof(SpaceSeq), "initsequencer"); sseq->spacetype = SPACE_SEQ; sseq->chanshown = 0; sseq->view = SEQ_VIEW_SEQUENCE; sseq->mainb = SEQ_DRAW_IMG_IMBUF; sseq->flag = SEQ_SHOW_GPENCIL | SEQ_USE_ALPHA | SEQ_SHOW_MARKERS | SEQ_SHOW_FCURVES; /* Tool header. */ region = MEM_callocN(sizeof(ARegion), "tool header for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_TOOL_HEADER; region->alignment = (U.uiflag & USER_HEADER_BOTTOM) ? RGN_ALIGN_BOTTOM : RGN_ALIGN_TOP; region->flag = RGN_FLAG_HIDDEN | RGN_FLAG_HIDDEN_BY_USER; /* Header. */ region = MEM_callocN(sizeof(ARegion), "header for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_HEADER; region->alignment = (U.uiflag & USER_HEADER_BOTTOM) ? RGN_ALIGN_BOTTOM : RGN_ALIGN_TOP; /* Buttons/list view. */ region = MEM_callocN(sizeof(ARegion), "buttons for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_UI; region->alignment = RGN_ALIGN_RIGHT; region->flag = RGN_FLAG_HIDDEN; /* Toolbar. */ region = MEM_callocN(sizeof(ARegion), "tools for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_TOOLS; region->alignment = RGN_ALIGN_LEFT; region->flag = RGN_FLAG_HIDDEN; /* Preview region. */ /* NOTE: if you change values here, also change them in sequencer_init_preview_region. */ region = MEM_callocN(sizeof(ARegion), "preview region for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_PREVIEW; region->alignment = RGN_ALIGN_TOP; region->flag |= RGN_FLAG_HIDDEN; /* For now, aspect ratio should be maintained, and zoom is clamped within sane default limits. */ region->v2d.keepzoom = V2D_KEEPASPECT | V2D_KEEPZOOM | V2D_LIMITZOOM; region->v2d.minzoom = 0.001f; region->v2d.maxzoom = 1000.0f; region->v2d.tot.xmin = -960.0f; /* 1920 width centered. */ region->v2d.tot.ymin = -540.0f; /* 1080 height centered. */ region->v2d.tot.xmax = 960.0f; region->v2d.tot.ymax = 540.0f; region->v2d.min[0] = 0.0f; region->v2d.min[1] = 0.0f; region->v2d.max[0] = 12000.0f; region->v2d.max[1] = 12000.0f; region->v2d.cur = region->v2d.tot; region->v2d.align = V2D_ALIGN_FREE; region->v2d.keeptot = V2D_KEEPTOT_FREE; /* Main region. */ region = MEM_callocN(sizeof(ARegion), "main region for sequencer"); BLI_addtail(&sseq->regionbase, region); region->regiontype = RGN_TYPE_WINDOW; /* Seq space goes from (0,8) to (0, efra). */ region->v2d.tot.xmin = 0.0f; region->v2d.tot.ymin = 0.0f; region->v2d.tot.xmax = scene->r.efra; region->v2d.tot.ymax = 8.0f; region->v2d.cur = region->v2d.tot; region->v2d.min[0] = 10.0f; region->v2d.min[1] = 0.5f; region->v2d.max[0] = MAXFRAMEF; region->v2d.max[1] = MAXSEQ; region->v2d.minzoom = 0.01f; region->v2d.maxzoom = 100.0f; region->v2d.scroll |= (V2D_SCROLL_BOTTOM | V2D_SCROLL_HORIZONTAL_HANDLES); region->v2d.scroll |= (V2D_SCROLL_RIGHT | V2D_SCROLL_VERTICAL_HANDLES); region->v2d.keepzoom = 0; region->v2d.keeptot = 0; region->v2d.align = V2D_ALIGN_NO_NEG_Y; return (SpaceLink *)sseq; } /* Not spacelink itself. */ static void sequencer_free(SpaceLink *sl) { SpaceSeq *sseq = (SpaceSeq *)sl; SequencerScopes *scopes = &sseq->scopes; /* XXX if (sseq->gpd) BKE_gpencil_free(sseq->gpd); */ if (scopes->zebra_ibuf) { IMB_freeImBuf(scopes->zebra_ibuf); } if (scopes->waveform_ibuf) { IMB_freeImBuf(scopes->waveform_ibuf); } if (scopes->sep_waveform_ibuf) { IMB_freeImBuf(scopes->sep_waveform_ibuf); } if (scopes->vector_ibuf) { IMB_freeImBuf(scopes->vector_ibuf); } if (scopes->histogram_ibuf) { IMB_freeImBuf(scopes->histogram_ibuf); } } /* Spacetype init callback. */ static void sequencer_init(struct wmWindowManager *UNUSED(wm), ScrArea *UNUSED(area)) { } static void sequencer_refresh(const bContext *C, ScrArea *area) { wmWindowManager *wm = CTX_wm_manager(C); wmWindow *window = CTX_wm_window(C); SpaceSeq *sseq = (SpaceSeq *)area->spacedata.first; ARegion *region_main = sequencer_find_region(area, RGN_TYPE_WINDOW); ARegion *region_preview = sequencer_find_region(area, RGN_TYPE_PREVIEW); bool view_changed = false; switch (sseq->view) { case SEQ_VIEW_SEQUENCE: if (region_main && (region_main->flag & RGN_FLAG_HIDDEN)) { region_main->flag &= ~RGN_FLAG_HIDDEN; region_main->v2d.flag &= ~V2D_IS_INITIALISED; view_changed = true; } if (region_preview && !(region_preview->flag & RGN_FLAG_HIDDEN)) { region_preview->flag |= RGN_FLAG_HIDDEN; region_preview->v2d.flag &= ~V2D_IS_INITIALISED; WM_event_remove_handlers((bContext *)C, &region_preview->handlers); view_changed = true; } if (region_main && region_main->alignment != RGN_ALIGN_NONE) { region_main->alignment = RGN_ALIGN_NONE; view_changed = true; } if (region_preview && region_preview->alignment != RGN_ALIGN_NONE) { region_preview->alignment = RGN_ALIGN_NONE; view_changed = true; } break; case SEQ_VIEW_PREVIEW: if (region_main && !(region_main->flag & RGN_FLAG_HIDDEN)) { region_main->flag |= RGN_FLAG_HIDDEN; region_main->v2d.flag &= ~V2D_IS_INITIALISED; WM_event_remove_handlers((bContext *)C, &region_main->handlers); view_changed = true; } if (region_preview && (region_preview->flag & RGN_FLAG_HIDDEN)) { region_preview->flag &= ~RGN_FLAG_HIDDEN; region_preview->v2d.flag &= ~V2D_IS_INITIALISED; region_preview->v2d.cur = region_preview->v2d.tot; view_changed = true; } if (region_main && region_main->alignment != RGN_ALIGN_NONE) { region_main->alignment = RGN_ALIGN_NONE; view_changed = true; } if (region_preview && region_preview->alignment != RGN_ALIGN_NONE) { region_preview->alignment = RGN_ALIGN_NONE; view_changed = true; } break; case SEQ_VIEW_SEQUENCE_PREVIEW: if (region_main && region_preview) { /* Get available height (without DPI correction). */ const float height = (area->winy - ED_area_headersize()) / UI_DPI_FAC; /* We reuse hidden region's size, allows to find same layout as before if we just switch * between one 'full window' view and the combined one. This gets lost if we switch to both * 'full window' views before, though... Better than nothing. */ if (region_main->flag & RGN_FLAG_HIDDEN) { region_main->flag &= ~RGN_FLAG_HIDDEN; region_main->v2d.flag &= ~V2D_IS_INITIALISED; region_preview->sizey = (int)(height - region_main->sizey); view_changed = true; } if (region_preview->flag & RGN_FLAG_HIDDEN) { region_preview->flag &= ~RGN_FLAG_HIDDEN; region_preview->v2d.flag &= ~V2D_IS_INITIALISED; region_preview->v2d.cur = region_preview->v2d.tot; region_main->sizey = (int)(height - region_preview->sizey); view_changed = true; } if (region_main->alignment != RGN_ALIGN_NONE) { region_main->alignment = RGN_ALIGN_NONE; view_changed = true; } if (region_preview->alignment != RGN_ALIGN_TOP) { region_preview->alignment = RGN_ALIGN_TOP; view_changed = true; } /* Final check that both preview and main height are reasonable. */ if (region_preview->sizey < 10 || region_main->sizey < 10 || region_preview->sizey + region_main->sizey > height) { region_preview->sizey = (int)(height * 0.4f + 0.5f); region_main->sizey = (int)(height - region_preview->sizey); view_changed = true; } } break; } if (view_changed) { ED_area_initialize(wm, window, area); ED_area_tag_redraw(area); } } static SpaceLink *sequencer_duplicate(SpaceLink *sl) { SpaceSeq *sseqn = MEM_dupallocN(sl); /* Clear or remove stuff from old. */ /* XXX sseq->gpd = gpencil_data_duplicate(sseq->gpd, false); */ memset(&sseqn->scopes, 0, sizeof(sseqn->scopes)); return (SpaceLink *)sseqn; } static void sequencer_listener(wmWindow *UNUSED(win), ScrArea *area, wmNotifier *wmn, Scene *UNUSED(scene)) { /* Context changes. */ switch (wmn->category) { case NC_SCENE: switch (wmn->data) { case ND_FRAME: case ND_SEQUENCER: sequencer_scopes_tag_refresh(area); break; } break; case NC_WINDOW: case NC_SPACE: if (wmn->data == ND_SPACE_SEQUENCER) { sequencer_scopes_tag_refresh(area); } break; case NC_GPENCIL: if (wmn->data & ND_GPENCIL_EDITMODE) { ED_area_tag_redraw(area); } break; } } /* ************* dropboxes ************* */ static bool image_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event, const char **UNUSED(r_tooltip)) { ARegion *region = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); int hand; if (drag->type == WM_DRAG_PATH) { if (ELEM(drag->icon, ICON_FILE_IMAGE, ICON_FILE_BLANK)) { /* Rule might not work? */ if (find_nearest_seq(scene, &region->v2d, &hand, event->mval) == NULL) { return 1; } } } return 0; } static bool movie_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event, const char **UNUSED(r_tooltip)) { ARegion *region = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); int hand; if (drag->type == WM_DRAG_PATH) { if (ELEM(drag->icon, 0, ICON_FILE_MOVIE, ICON_FILE_BLANK)) { /* Rule might not work? */ if (find_nearest_seq(scene, &region->v2d, &hand, event->mval) == NULL) { return 1; } } } return 0; } static bool sound_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event, const char **UNUSED(r_tooltip)) { ARegion *region = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); int hand; if (drag->type == WM_DRAG_PATH) { if (ELEM(drag->icon, ICON_FILE_SOUND, ICON_FILE_BLANK)) { /* Rule might not work? */ if (find_nearest_seq(scene, &region->v2d, &hand, event->mval) == NULL) { return 1; } } } return 0; } static void sequencer_drop_copy(wmDrag *drag, wmDropBox *drop) { /* Copy drag path to properties. */ if (RNA_struct_find_property(drop->ptr, "filepath")) { RNA_string_set(drop->ptr, "filepath", drag->path); } if (RNA_struct_find_property(drop->ptr, "directory")) { PointerRNA itemptr; char dir[FILE_MAX], file[FILE_MAX]; BLI_split_dirfile(drag->path, dir, file, sizeof(dir), sizeof(file)); RNA_string_set(drop->ptr, "directory", dir); RNA_collection_clear(drop->ptr, "files"); RNA_collection_add(drop->ptr, "files", &itemptr); RNA_string_set(&itemptr, "name", file); } } /* This region dropbox definition. */ static void sequencer_dropboxes(void) { ListBase *lb = WM_dropboxmap_find("Sequencer", SPACE_SEQ, RGN_TYPE_WINDOW); WM_dropbox_add(lb, "SEQUENCER_OT_image_strip_add", image_drop_poll, sequencer_drop_copy); WM_dropbox_add(lb, "SEQUENCER_OT_movie_strip_add", movie_drop_poll, sequencer_drop_copy); WM_dropbox_add(lb, "SEQUENCER_OT_sound_strip_add", sound_drop_poll, sequencer_drop_copy); } /* ************* end drop *********** */ /* DO NOT make this static, this hides the symbol and breaks API generation script. */ extern const char *sequencer_context_dir[]; /* Quiet warning. */ const char *sequencer_context_dir[] = {"edit_mask", NULL}; static int sequencer_context(const bContext *C, const char *member, bContextDataResult *result) { Scene *scene = CTX_data_scene(C); if (CTX_data_dir(member)) { CTX_data_dir_set(result, sequencer_context_dir); return true; } else if (CTX_data_equals(member, "edit_mask")) { Mask *mask = BKE_sequencer_mask_get(scene); if (mask) { CTX_data_id_pointer_set(result, &mask->id); } return true; } return false; } static void SEQUENCER_GGT_navigate(wmGizmoGroupType *gzgt) { VIEW2D_GGT_navigate_impl(gzgt, "SEQUENCER_GGT_navigate"); } static void sequencer_gizmos(void) { wmGizmoMapType *gzmap_type = WM_gizmomaptype_ensure( &(const struct wmGizmoMapType_Params){SPACE_SEQ, RGN_TYPE_PREVIEW}); WM_gizmogrouptype_append_and_link(gzmap_type, SEQUENCER_GGT_navigate); } /* *********************** sequencer (main) region ************************ */ /* Add handlers, stuff you only do once or on area/region changes. */ static void sequencer_main_region_init(wmWindowManager *wm, ARegion *region) { wmKeyMap *keymap; ListBase *lb; UI_view2d_region_reinit(&region->v2d, V2D_COMMONVIEW_CUSTOM, region->winx, region->winy); #if 0 keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); #endif keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); /* Own keymap. */ keymap = WM_keymap_ensure(wm->defaultconf, "Sequencer", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); /* Add drop boxes. */ lb = WM_dropboxmap_find("Sequencer", SPACE_SEQ, RGN_TYPE_WINDOW); WM_event_add_dropbox_handler(&region->handlers, lb); } /* Strip editing timeline. */ static void sequencer_main_region_draw(const bContext *C, ARegion *region) { draw_timeline_seq(C, region); } static void sequencer_main_region_listener(wmWindow *UNUSED(win), ScrArea *UNUSED(area), ARegion *region, wmNotifier *wmn, const Scene *UNUSED(scene)) { /* Context changes. */ switch (wmn->category) { case NC_SCENE: switch (wmn->data) { case ND_FRAME: case ND_FRAME_RANGE: case ND_MARKERS: case ND_RENDER_OPTIONS: /* For FPS and FPS Base. */ case ND_SEQUENCER: case ND_RENDER_RESULT: ED_region_tag_redraw(region); break; } break; case NC_ANIMATION: switch (wmn->data) { case ND_KEYFRAME: ED_region_tag_redraw(region); break; } break; case NC_SPACE: if (wmn->data == ND_SPACE_SEQUENCER) { ED_region_tag_redraw(region); } break; case NC_ID: if (wmn->action == NA_RENAME) { ED_region_tag_redraw(region); } break; case NC_SCREEN: if (ELEM(wmn->data, ND_ANIMPLAY)) { ED_region_tag_redraw(region); } break; } } static void sequencer_main_region_message_subscribe(const struct bContext *UNUSED(C), struct WorkSpace *UNUSED(workspace), struct Scene *scene, struct bScreen *UNUSED(screen), struct ScrArea *UNUSED(area), struct ARegion *region, struct wmMsgBus *mbus) { wmMsgSubscribeValue msg_sub_value_region_tag_redraw = { .owner = region, .user_data = region, .notify = ED_region_do_msg_notify_tag_redraw, }; /* Timeline depends on scene properties. */ { bool use_preview = (scene->r.flag & SCER_PRV_RANGE); extern PropertyRNA rna_Scene_frame_start; extern PropertyRNA rna_Scene_frame_end; extern PropertyRNA rna_Scene_frame_preview_start; extern PropertyRNA rna_Scene_frame_preview_end; extern PropertyRNA rna_Scene_use_preview_range; extern PropertyRNA rna_Scene_frame_current; const PropertyRNA *props[] = { use_preview ? &rna_Scene_frame_preview_start : &rna_Scene_frame_start, use_preview ? &rna_Scene_frame_preview_end : &rna_Scene_frame_end, &rna_Scene_use_preview_range, &rna_Scene_frame_current, }; PointerRNA idptr; RNA_id_pointer_create(&scene->id, &idptr); for (int i = 0; i < ARRAY_SIZE(props); i++) { WM_msg_subscribe_rna(mbus, &idptr, props[i], &msg_sub_value_region_tag_redraw, __func__); } } { StructRNA *type_array[] = { &RNA_SequenceEditor, &RNA_Sequence, /* Members of 'Sequence'. */ &RNA_SequenceCrop, &RNA_SequenceTransform, &RNA_SequenceModifier, &RNA_SequenceColorBalanceData, }; wmMsgParams_RNA msg_key_params = {{0}}; for (int i = 0; i < ARRAY_SIZE(type_array); i++) { msg_key_params.ptr.type = type_array[i]; WM_msg_subscribe_rna_params( mbus, &msg_key_params, &msg_sub_value_region_tag_redraw, __func__); } } } /* *********************** header region ************************ */ /* Add handlers, stuff you only do once or on area/region changes. */ static void sequencer_header_region_init(wmWindowManager *UNUSED(wm), ARegion *region) { ED_region_header_init(region); } static void sequencer_header_region_draw(const bContext *C, ARegion *region) { ED_region_header(C, region); } /* *********************** toolbar region ************************ */ /* Add handlers, stuff you only do once or on area/region changes. */ static void sequencer_tools_region_init(wmWindowManager *wm, ARegion *region) { wmKeyMap *keymap; region->v2d.scroll = V2D_SCROLL_RIGHT | V2D_SCROLL_VERTICAL_HIDE; ED_region_panels_init(wm, region); keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); } static void sequencer_tools_region_draw(const bContext *C, ARegion *region) { ED_region_panels(C, region); } /* *********************** preview region ************************ */ static void sequencer_preview_region_init(wmWindowManager *wm, ARegion *region) { wmKeyMap *keymap; UI_view2d_region_reinit(&region->v2d, V2D_COMMONVIEW_CUSTOM, region->winx, region->winy); #if 0 keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); #endif keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); /* Own keymap. */ keymap = WM_keymap_ensure(wm->defaultconf, "SequencerPreview", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); } static void sequencer_preview_region_draw(const bContext *C, ARegion *region) { ScrArea *area = CTX_wm_area(C); SpaceSeq *sseq = area->spacedata.first; Scene *scene = CTX_data_scene(C); wmWindowManager *wm = CTX_wm_manager(C); const bool draw_overlay = (scene->ed && (scene->ed->over_flag & SEQ_EDIT_OVERLAY_SHOW)); /* XXX temp fix for wrong setting in sseq->mainb */ if (sseq->mainb == SEQ_DRAW_SEQUENCE) { sseq->mainb = SEQ_DRAW_IMG_IMBUF; } if (!draw_overlay || sseq->overlay_type != SEQ_DRAW_OVERLAY_REFERENCE) { sequencer_draw_preview(C, scene, region, sseq, scene->r.cfra, 0, false, false); } if (draw_overlay && sseq->overlay_type != SEQ_DRAW_OVERLAY_CURRENT) { int over_cfra; if (scene->ed->over_flag & SEQ_EDIT_OVERLAY_ABS) { over_cfra = scene->ed->over_cfra; } else { over_cfra = scene->r.cfra + scene->ed->over_ofs; } if (over_cfra != scene->r.cfra || sseq->overlay_type != SEQ_DRAW_OVERLAY_RECT) { sequencer_draw_preview( C, scene, region, sseq, scene->r.cfra, over_cfra - scene->r.cfra, true, false); } } WM_gizmomap_draw(region->gizmo_map, C, WM_GIZMOMAP_DRAWSTEP_2D); if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) { const rcti *rect = ED_region_visible_rect(region); int xoffset = rect->xmin + U.widget_unit; int yoffset = rect->ymax; ED_scene_draw_fps(scene, xoffset, &yoffset); } } static void sequencer_preview_region_listener(wmWindow *UNUSED(win), ScrArea *UNUSED(area), ARegion *region, wmNotifier *wmn, const Scene *UNUSED(scene)) { /* Context changes. */ switch (wmn->category) { case NC_GPENCIL: if (ELEM(wmn->action, NA_EDITED, NA_SELECTED)) { ED_region_tag_redraw(region); } break; case NC_SCENE: switch (wmn->data) { case ND_FRAME: case ND_MARKERS: case ND_SEQUENCER: case ND_RENDER_OPTIONS: case ND_DRAW_RENDER_VIEWPORT: ED_region_tag_redraw(region); break; } break; case NC_ANIMATION: switch (wmn->data) { case ND_KEYFRAME: ED_region_tag_redraw(region); break; } break; case NC_SPACE: if (wmn->data == ND_SPACE_SEQUENCER) { ED_region_tag_redraw(region); } break; case NC_ID: switch (wmn->data) { case NA_RENAME: ED_region_tag_redraw(region); break; } break; case NC_MASK: if (wmn->action == NA_EDITED) { ED_region_tag_redraw(region); } break; } } /* *********************** buttons region ************************ */ /* Add handlers, stuff you only do once or on area/region changes. */ static void sequencer_buttons_region_init(wmWindowManager *wm, ARegion *region) { wmKeyMap *keymap; keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_v2d_mask(&region->handlers, keymap); UI_panel_category_active_set_default(region, "Strip"); ED_region_panels_init(wm, region); } static void sequencer_buttons_region_draw(const bContext *C, ARegion *region) { ED_region_panels(C, region); } static void sequencer_buttons_region_listener(wmWindow *UNUSED(win), ScrArea *UNUSED(area), ARegion *region, wmNotifier *wmn, const Scene *UNUSED(scene)) { /* Context changes. */ switch (wmn->category) { case NC_GPENCIL: if (ELEM(wmn->action, NA_EDITED, NA_SELECTED)) { ED_region_tag_redraw(region); } break; case NC_SCENE: switch (wmn->data) { case ND_FRAME: case ND_SEQUENCER: ED_region_tag_redraw(region); break; } break; case NC_SPACE: if (wmn->data == ND_SPACE_SEQUENCER) { ED_region_tag_redraw(region); } break; case NC_ID: if (wmn->action == NA_RENAME) { ED_region_tag_redraw(region); } break; } } static void sequencer_id_remap(ScrArea *UNUSED(area), SpaceLink *slink, ID *old_id, ID *new_id) { SpaceSeq *sseq = (SpaceSeq *)slink; if (!ELEM(GS(old_id->name), ID_GD)) { return; } if ((ID *)sseq->gpd == old_id) { sseq->gpd = (bGPdata *)new_id; id_us_min(old_id); id_us_plus(new_id); } } /* ************************************* */ /* Only called once, from space/spacetypes.c. */ void ED_spacetype_sequencer(void) { SpaceType *st = MEM_callocN(sizeof(SpaceType), "spacetype sequencer"); ARegionType *art; st->spaceid = SPACE_SEQ; strncpy(st->name, "Sequencer", BKE_ST_MAXNAME); st->new = sequencer_new; st->free = sequencer_free; st->init = sequencer_init; st->duplicate = sequencer_duplicate; st->operatortypes = sequencer_operatortypes; st->keymap = sequencer_keymap; st->context = sequencer_context; st->gizmos = sequencer_gizmos; st->dropboxes = sequencer_dropboxes; st->refresh = sequencer_refresh; st->listener = sequencer_listener; st->id_remap = sequencer_id_remap; /* Create regions: */ /* Main window. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer region"); art->regionid = RGN_TYPE_WINDOW; art->init = sequencer_main_region_init; art->draw = sequencer_main_region_draw; art->listener = sequencer_main_region_listener; art->message_subscribe = sequencer_main_region_message_subscribe; art->keymapflag = ED_KEYMAP_TOOL | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_ANIMATION; BLI_addhead(&st->regiontypes, art); /* Preview. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer region"); art->regionid = RGN_TYPE_PREVIEW; art->init = sequencer_preview_region_init; art->draw = sequencer_preview_region_draw; art->listener = sequencer_preview_region_listener; art->keymapflag = ED_KEYMAP_TOOL | ED_KEYMAP_GIZMO | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_GPENCIL; BLI_addhead(&st->regiontypes, art); /* Listview/buttons. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer region"); art->regionid = RGN_TYPE_UI; art->prefsizex = UI_SIDEBAR_PANEL_WIDTH * 1.3f; art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES; art->message_subscribe = ED_area_do_mgs_subscribe_for_tool_ui; art->listener = sequencer_buttons_region_listener; art->init = sequencer_buttons_region_init; art->draw = sequencer_buttons_region_draw; BLI_addhead(&st->regiontypes, art); sequencer_buttons_register(art); /* Toolbar. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer tools region"); art->regionid = RGN_TYPE_TOOLS; art->prefsizex = 58; /* XXX */ art->prefsizey = 50; /* XXX */ art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES; art->message_subscribe = ED_region_generic_tools_region_message_subscribe; art->snap_size = ED_region_generic_tools_region_snap_size; art->init = sequencer_tools_region_init; art->draw = sequencer_tools_region_draw; BLI_addhead(&st->regiontypes, art); /* Tool header. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer tool header region"); art->regionid = RGN_TYPE_TOOL_HEADER; art->prefsizey = HEADERY; art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_HEADER; art->listener = sequencer_main_region_listener; art->init = sequencer_header_region_init; art->draw = sequencer_header_region_draw; art->message_subscribe = ED_area_do_mgs_subscribe_for_tool_header; BLI_addhead(&st->regiontypes, art); /* Header. */ art = MEM_callocN(sizeof(ARegionType), "spacetype sequencer region"); art->regionid = RGN_TYPE_HEADER; art->prefsizey = HEADERY; art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_HEADER; art->init = sequencer_header_region_init; art->draw = sequencer_header_region_draw; art->listener = sequencer_main_region_listener; BLI_addhead(&st->regiontypes, art); /* Hud. */ art = ED_area_type_hud(st->spaceid); BLI_addhead(&st->regiontypes, art); BKE_spacetype_register(st); /* Set the sequencer callback when not in background mode. */ if (G.background == 0) { sequencer_view3d_fn = ED_view3d_draw_offscreen_imbuf_simple; } }
919041.c
/** @file oyCMMapi6_s_.c [Template file inheritance graph] +-> oyCMMapi6_s_.template.c | +-> oyCMMapiFilter_s_.template.c | +-> oyCMMapi_s_.template.c | +-- Base_s_.c * Oyranos is an open source Color Management System * * @par Copyright: * 2004-2019 (C) Kai-Uwe Behrmann * * @author Kai-Uwe Behrmann <[email protected]> * @par License: * new BSD - see: http://www.opensource.org/licenses/BSD-3-Clause */ #include "oyCMMapi6_s.h" #include "oyCMMapi6_s_.h" #include "oyCMMapi_s_.h" #include "oyCMMapiFilter_s_.h" #include "oyObject_s.h" #include "oyranos_object_internal.h" #include "oyranos_module_internal.h" #include "oyCMMapiFilter_s_.h" #ifdef HAVE_BACKTRACE #include <execinfo.h> #define BT_BUF_SIZE 100 #endif static int oy_cmmapi6_init_ = 0; static const char * oyCMMapi6_StaticMessageFunc_ ( oyPointer obj, oyNAME_e type, int flags ) { oyCMMapi6_s_ * s = (oyCMMapi6_s_*) obj; static char * text = 0; static int text_n = 0; oyAlloc_f alloc = oyAllocateFunc_; /* silently fail */ if(!s) return ""; if(s->oy_ && s->oy_->allocateFunc_) alloc = s->oy_->allocateFunc_; if( text == NULL || text_n == 0 ) { text_n = 512; text = (char*) alloc( text_n ); if(text) memset( text, 0, text_n ); } if( text == NULL || text_n == 0 ) return "Memory problem"; text[0] = '\000'; if(!(flags & 0x01)) sprintf(text, "%s%s", oyStructTypeToText( s->type_ ), type != oyNAME_NICK?" ":""); return text; } /* Include "CMMapi6.private_custom_definitions.c" { */ /** Function oyCMMapi6_Release__Members * @memberof oyCMMapi6_s * @brief Custom CMMapi6 destructor * @internal * * This function will free up all memmory allocated by the * input object. First all object members witch have their * own release method are deallocated. Then the deallocateFunc_ * of the oy_ object is used to release the rest of the members * that were allocated with oy_->allocateFunc_. * * @param[in] cmmapi6 the CMMapi6 object * * @version Oyranos: x.x.x * @since YYYY/MM/DD (Oyranos: x.x.x) * @date YYYY/MM/DD */ void oyCMMapi6_Release__Members( oyCMMapi6_s_ * cmmapi6 ) { /* Deallocate members here * E.g: oyXXX_Release( &cmmapi6->member ); */ if(cmmapi6->oy_->deallocateFunc_) { #if 0 oyDeAlloc_f deallocateFunc = cmmapi6->oy_->deallocateFunc_; #endif /* Deallocate members of basic type here * E.g.: deallocateFunc( cmmapi6->member ); */ } } /** Function oyCMMapi6_Init__Members * @memberof oyCMMapi6_s * @brief Custom CMMapi6 constructor * @internal * * This function will allocate all memmory for the input object. * For the basic member types this is done using the allocateFunc_ * of the attatced (oyObject_s)oy_ object. * * @param[in] cmmapi6 the CMMapi6 object * * @version Oyranos: x.x.x * @since YYYY/MM/DD (Oyranos: x.x.x) * @date YYYY/MM/DD */ int oyCMMapi6_Init__Members( oyCMMapi6_s_ * cmmapi6 OY_UNUSED ) { return 0; } /** Function oyCMMapi6_Copy__Members * @memberof oyCMMapi6_s * @brief Custom CMMapi6 copy constructor * @internal * * This function makes a copy of all values from the input * to the output object. The destination object and all of its * members should already be allocated. * * @param[in] src the oyCMMapi6_s_ input object * @param[out] dst the output oyCMMapi6_s_ object * * @version Oyranos: x.x.x * @since YYYY/MM/DD (Oyranos: x.x.x) * @date YYYY/MM/DD */ int oyCMMapi6_Copy__Members( oyCMMapi6_s_ * dst, oyCMMapi6_s_ * src) { #if 0 oyAlloc_f allocateFunc_ = 0; oyDeAlloc_f deallocateFunc_ = 0; #endif if(!dst || !src) return 1; #if 0 allocateFunc_ = dst->oy_->allocateFunc_; deallocateFunc_ = dst->oy_->deallocateFunc_; #endif /* Copy each value of src to dst here */ return 0; } /* } Include "CMMapi6.private_custom_definitions.c" */ /** @internal * Function oyCMMapi6_New_ * @memberof oyCMMapi6_s_ * @brief allocate a new oyCMMapi6_s_ object * * @version Oyranos: * @since 2010/04/26 (Oyranos: 0.1.10) * @date 2010/04/26 */ oyCMMapi6_s_ * oyCMMapi6_New_ ( oyObject_s object ) { /* ---- start of common object constructor ----- */ oyOBJECT_e type = oyOBJECT_CMM_API6_S; int error = 0; oyObject_s s_obj = oyObject_NewFrom( object ); oyCMMapi6_s_ * s = 0; if(s_obj) s = (oyCMMapi6_s_*)s_obj->allocateFunc_(sizeof(oyCMMapi6_s_)); else { WARNc_S(_("MEM Error.")); return NULL; } if(!s) { if(s_obj) oyObject_Release( &s_obj ); WARNc_S(_("MEM Error.")); return NULL; } error = !memset( s, 0, sizeof(oyCMMapi6_s_) ); if(error) WARNc_S( "memset failed" ); memcpy( s, &type, sizeof(oyOBJECT_e) ); s->copy = (oyStruct_Copy_f) oyCMMapi6_Copy; s->release = (oyStruct_Release_f) oyCMMapi6_Release; s->oy_ = s_obj; /* ---- start of custom CMMapi constructor ----- */ error += !oyObject_SetParent( s_obj, oyOBJECT_CMM_API_S, (oyPointer)s ); /* ---- end of custom CMMapi constructor ------- */ /* ---- start of custom CMMapiFilter constructor ----- */ error += !oyObject_SetParent( s_obj, oyOBJECT_CMM_API_FILTER_S, (oyPointer)s ); /* ---- end of custom CMMapiFilter constructor ------- */ /* ---- start of custom CMMapi6 constructor ----- */ error += !oyObject_SetParent( s_obj, oyOBJECT_CMM_API6_S, (oyPointer)s ); /* ---- end of custom CMMapi6 constructor ------- */ /* ---- end of common object constructor ------- */ if(error) WARNc_S( "oyObject_SetParent failed" ); /* ---- start of custom CMMapi constructor ----- */ error += oyCMMapi_Init__Members( (oyCMMapi_s_*)s ); /* ---- end of custom CMMapi constructor ------- */ /* ---- start of custom CMMapiFilter constructor ----- */ error += oyCMMapiFilter_Init__Members( (oyCMMapiFilter_s_*)s ); /* ---- end of custom CMMapiFilter constructor ------- */ /* ---- start of custom CMMapi6 constructor ----- */ error += oyCMMapi6_Init__Members( s ); /* ---- end of custom CMMapi6 constructor ------- */ if(!oy_cmmapi6_init_) { oy_cmmapi6_init_ = 1; oyStruct_RegisterStaticMessageFunc( type, oyCMMapi6_StaticMessageFunc_ ); } if(error) WARNc1_S("%d", error); if(oy_debug_objects >= 0) oyObject_GetId( s->oy_ ); return s; } /** @internal * Function oyCMMapi6_Copy__ * @memberof oyCMMapi6_s_ * @brief real copy a CMMapi6 object * * @param[in] cmmapi6 CMMapi6 struct object * @param object the optional object * * @version Oyranos: * @since 2010/04/26 (Oyranos: 0.1.10) * @date 2010/04/26 */ oyCMMapi6_s_ * oyCMMapi6_Copy__ ( oyCMMapi6_s_ *cmmapi6, oyObject_s object ) { oyCMMapi6_s_ *s = 0; int error = 0; if(!cmmapi6 || !object) return s; s = (oyCMMapi6_s_*) oyCMMapi6_New( object ); error = !s; if(!error) { /* ---- start of custom CMMapi copy constructor ----- */ error = oyCMMapi_Copy__Members( (oyCMMapi_s_*)s, (oyCMMapi_s_*)cmmapi6 ); /* ---- end of custom CMMapi copy constructor ------- */ /* ---- start of custom CMMapiFilter copy constructor ----- */ error = oyCMMapiFilter_Copy__Members( (oyCMMapiFilter_s_*)s, (oyCMMapiFilter_s_*)cmmapi6 ); /* ---- end of custom CMMapiFilter copy constructor ------- */ /* ---- start of custom CMMapi6 copy constructor ----- */ error = oyCMMapi6_Copy__Members( s, cmmapi6 ); /* ---- end of custom CMMapi6 copy constructor ------- */ } if(error) oyCMMapi6_Release_( &s ); return s; } /** @internal * Function oyCMMapi6_Copy_ * @memberof oyCMMapi6_s_ * @brief copy or reference a CMMapi6 object * * @param[in] cmmapi6 CMMapi6 struct object * @param object the optional object * * @version Oyranos: * @since 2010/04/26 (Oyranos: 0.1.10) * @date 2010/04/26 */ oyCMMapi6_s_ * oyCMMapi6_Copy_ ( oyCMMapi6_s_ *cmmapi6, oyObject_s object ) { oyCMMapi6_s_ *s = cmmapi6; if(!cmmapi6) return 0; if(cmmapi6 && !object) { s = cmmapi6; if(oy_debug_objects >= 0 && s->oy_) { const char * t = getenv(OY_DEBUG_OBJECTS); int id_ = -1; if(t) id_ = atoi(t); else id_ = oy_debug_objects; if((id_ >= 0 && s->oy_->id_ == id_) || (t && s && (strstr(oyStructTypeToText(s->type_), t) != 0)) || id_ == 1) { oyStruct_s ** parents = NULL; int n = oyStruct_GetParents( (oyStruct_s*)s, &parents ); if(n != s->oy_->ref_) { int i; const char * track_name = oyStructTypeToText(s->type_); #ifdef HAVE_BACKTRACE int j, nptrs; void *buffer[BT_BUF_SIZE]; char **strings; nptrs = backtrace(buffer, BT_BUF_SIZE); /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) would produce similar output to the following: */ strings = backtrace_symbols(buffer, nptrs); if( strings == NULL ) { perror("backtrace_symbols"); } else { int start = nptrs-1; do { --start; } while( start >= 0 && (strstr(strings[start], "(main+") == NULL) ); fprintf(stderr, "\n"); for(j = start; j >= 0; j--) { if(oy_debug) fprintf(stderr, "%s\n", strings[j]); else { char * t = NULL, * txt = NULL; const char * line = strings[j], * tmp = strchr( line, '(' ); if(tmp) t = oyStringCopy( &tmp[1], NULL ); else t = oyStringCopy( line, NULL ); txt = strchr( t, '+' ); if(txt) txt[0] = '\000'; if(j > 0 && (strstr(strings[j-1], t) != NULL) ) oyFree_m_(t); if(t) { if(j==0) fprintf(stderr, "%s() ", t); else fprintf(stderr, "%s()->", t); oyFree_m_(t); } } } free(strings); } #endif fprintf( stderr, "%s[%d] tracking refs: %d parents: %d\n", track_name, s->oy_->id_, s->oy_->ref_, n ); for(i = 0; i < n; ++i) { track_name = oyStructTypeToText(parents[i]->type_); fprintf( stderr, "parent[%d]: %s[%d]\n", i, track_name, parents[i]->oy_->id_ ); } } } } oyObject_Copy( s->oy_ ); return s; } s = oyCMMapi6_Copy__( cmmapi6, object ); return s; } /** @internal * Function oyCMMapi6_Release_ * @memberof oyCMMapi6_s_ * @brief release and possibly deallocate a CMMapi6 object * * @param[in,out] cmmapi6 CMMapi6 struct object * * @version Oyranos: 0.9.7 * @date 2018/10/03 * @since 2010/04/26 (Oyranos: 0.1.10) */ int oyCMMapi6_Release_( oyCMMapi6_s_ **cmmapi6 ) { const char * track_name = NULL; int observer_refs = 0, i; /* ---- start of common object destructor ----- */ oyCMMapi6_s_ *s = 0; if(!cmmapi6 || !*cmmapi6) return 0; s = *cmmapi6; /* static object */ if(!s->oy_) return 0; *cmmapi6 = 0; observer_refs = oyStruct_ObservationCount( (oyStruct_s*)s, 0 ); if(oy_debug_objects >= 0) { const char * t = getenv(OY_DEBUG_OBJECTS); int id_ = -1; if(t) id_ = atoi(t); else id_ = oy_debug_objects; if((id_ >= 0 && s->oy_->id_ == id_) || (t && (strstr(oyStructTypeToText(s->type_), t) != 0)) || id_ == 1) { oyStruct_s ** parents = NULL; int n = oyStruct_GetParents( (oyStruct_s*)s, &parents ); if(n != s->oy_->ref_) { int i; #ifdef HAVE_BACKTRACE int j, nptrs; void *buffer[BT_BUF_SIZE]; char **strings; nptrs = backtrace(buffer, BT_BUF_SIZE); /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) would produce similar output to the following: */ strings = backtrace_symbols(buffer, nptrs); if( strings == NULL ) { perror("backtrace_symbols"); } else { int start = nptrs-1; do { --start; } while( start >= 0 && (strstr(strings[start], "(main+") == NULL) ); fprintf(stderr, "\n"); for(j = start; j >= 0; j--) { if(oy_debug) fprintf(stderr, "%s\n", strings[j]); else { char * t = NULL, * txt = NULL; const char * line = strings[j], * tmp = strchr( line, '(' ); if(tmp) t = oyStringCopy( &tmp[1], NULL ); else t = oyStringCopy( line, NULL ); txt = strchr( t, '+' ); if(txt) txt[0] = '\000'; if(j > 0 && (strstr(strings[j-1], t) != NULL) ) oyFree_m_(t); if(t) { if(j==0) fprintf(stderr, "%s() ", t); else fprintf(stderr, "%s()->", t); oyFree_m_(t); } } } free(strings); } #endif track_name = oyStructTypeToText(s->type_); fprintf( stderr, "%s[%d] unref with refs: %d observers: %d parents: %d\n", track_name, s->oy_->id_, s->oy_->ref_, observer_refs, n ); for(i = 0; i < n; ++i) { track_name = oyStructTypeToText(parents[i]->type_); fprintf( stderr, "parent[%d]: %s[%d]\n", i, track_name, parents[i]->oy_->id_ ); } } } } if((oyObject_UnRef(s->oy_) - observer_refs) > 0) return 0; /* ---- end of common object destructor ------- */ if(oy_debug_objects >= 0) { const char * t = getenv(OY_DEBUG_OBJECTS); int id_ = -1; if(t) id_ = atoi(t); else id_ = oy_debug_objects; if((id_ >= 0 && s->oy_->id_ == id_) || (t && s && (strstr(oyStructTypeToText(s->type_), t) != 0)) || id_ == 1) { track_name = oyStructTypeToText(s->type_); fprintf( stderr, "%s[%d] destruct\n", track_name, s->oy_->id_); } } /* ---- start of custom CMMapi destructor ----- */ oyCMMapi_Release__Members( (oyCMMapi_s_*)s ); /* ---- end of custom CMMapi destructor ------- */ /* ---- start of custom CMMapiFilter destructor ----- */ oyCMMapiFilter_Release__Members( (oyCMMapiFilter_s_*)s ); /* ---- end of custom CMMapiFilter destructor ------- */ /* ---- start of custom CMMapi6 destructor ----- */ oyCMMapi6_Release__Members( s ); /* ---- end of custom CMMapi6 destructor ------- */ /* model and observer reference each other. So release the object two times. * The models and and observers are released later inside the * oyObject_s::handles. */ for(i = 0; i < observer_refs; ++i) { oyObject_UnRef(s->oy_); oyObject_UnRef(s->oy_); } if(s->oy_->deallocateFunc_) { oyDeAlloc_f deallocateFunc = s->oy_->deallocateFunc_; int id = s->oy_->id_; int refs = s->oy_->ref_; if(refs > 1) fprintf( stderr, "!!!ERROR: node[%d]->object can not be untracked with refs: %d\n", id, refs); oyObject_Release( &s->oy_ ); if(track_name) fprintf( stderr, "%s[%d] destructed\n", track_name, id ); deallocateFunc( s ); } return 0; } /* Include "CMMapi6.private_methods_definitions.c" { */ /* } Include "CMMapi6.private_methods_definitions.c" */
383332.c
/*====================================================================* * * crlf.c - insert or remove <cr> and/or <lf> from file; * *. Motley Tools by Charles Maier; *: Copyright (c) 2001-2006 by Charles Maier Associates Limited; *; Licensed under the Internet Software Consortium License; * *--------------------------------------------------------------------*/ #define _GETOPT_H /*====================================================================* * system header files; *--------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> /*====================================================================* * custom header files; *--------------------------------------------------------------------*/ #include "../tools/cmassoc.h" #include "../files/files.h" /*====================================================================* * custom source files; *--------------------------------------------------------------------*/ #ifndef MAKEFILE #include "../tools/console.c" #endif #ifndef MAKEFILE #include "../files/vfopen.c" #include "../files/makepath.c" #include "../files/splitpath.c" #include "../files/mergepath.c" #endif /*====================================================================* * custom source files; *--------------------------------------------------------------------*/ #define CRLF_B_CR 0x0001 #define CRLF_B_LF 0x0002 /*====================================================================* * * void function (flag_t flags) * * read from stdin and write to stdout; convert carriage return * and line feed characters to UNIX, MAC or WINDOWS conventions; * * UNIX uses a line feed, MAC uses a carriage return and WINDOWS * uses both to terminate text lines in a file; * * this function treats one cr or lf and cr/lf or lf/cr pairs as * the line end; all occurances of any combination are replaced * *. Motley Tools by Charles Maier; *: Copyright (c) 2001-2006 by Charles Maier Associates Limited; *; Licensed under the Internet Software Consortium License; * *--------------------------------------------------------------------*/ static void function (flag_t flags) { int c; while ((c = getc (stdin)) != EOF) { if (c == '\r') { if ((c = getc (stdin)) != '\n') { ungetc (c, stdin); } if (_anyset (flags, CRLF_B_CR)) { putc ('\r', stdout); } if (_anyset (flags, CRLF_B_LF)) { putc ('\n', stdout); } continue; } if (c == '\n') { if ((c = getc (stdin)) != '\r') { ungetc (c, stdin); } if (_anyset (flags, CRLF_B_CR)) { putc ('\r', stdout); } if (_anyset (flags, CRLF_B_LF)) { putc ('\n', stdout); } continue; } putc (c, stdout); } return; } /*====================================================================* * * int main (int argc, char const * argv []); * * *. Motley Tools by Charles Maier; *: Copyright (c) 2001-2006 by Charles Maier Associates Limited; *; Licensed under the Internet Software Consortium License; * *--------------------------------------------------------------------*/ int main (int argc, char const * argv []) { static char const * optv [] = { "change text line termination", PUTOPTV_S_FILTER, "asuw", "a\tto Apple computer format [" "'\\r'" "]", "s\tto stream format (no line breaks)", "u\tto standard Unix format [" "'\\n'" "]", "w\tto Microsoft Windows format [" "\"\\r\\n\"" "]", (char const *) (0) }; flag_t flags = CRLF_B_LF; signed c; while (~ (c = getoptv (argc, argv, optv))) { switch (c) { case 's': _clrbits (flags, CRLF_B_CR); _clrbits (flags, CRLF_B_LF); break; case 'u': _clrbits (flags, CRLF_B_CR); _setbits (flags, CRLF_B_LF); break; case 'a': _setbits (flags, CRLF_B_CR); _clrbits (flags, CRLF_B_LF); break; case 'w': _setbits (flags, CRLF_B_CR); _setbits (flags, CRLF_B_LF); break; default: break; } } argc -= optind; argv += optind; if (! argc) { function (flags); } while ((argc) && (* argv)) { if (vfopen (* argv)) { function (flags); } argc--; argv++; } exit (0); }
294183.c
/* * * Copyright 2015 gRPC 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 <ruby/ruby.h> #include <ruby/thread.h> #include "rb_byte_buffer.h" #include "rb_channel.h" #include "rb_grpc_imports.generated.h" #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "rb_call.h" #include "rb_channel_args.h" #include "rb_channel_credentials.h" #include "rb_completion_queue.h" #include "rb_grpc.h" #include "rb_server.h" /* id_channel is the name of the hidden ivar that preserves a reference to the * channel on a call, so that calls are not GCed before their channel. */ static ID id_channel; /* id_target is the name of the hidden ivar that preserves a reference to the * target string used to create the call, preserved so that it does not get * GCed before the channel */ static ID id_target; /* id_insecure_channel is used to indicate that a channel is insecure */ static VALUE id_insecure_channel; /* grpc_rb_cChannel is the ruby class that proxies grpc_channel. */ static VALUE grpc_rb_cChannel = Qnil; /* Used during the conversion of a hash to channel args during channel setup */ static VALUE grpc_rb_cChannelArgs; typedef struct bg_watched_channel { grpc_channel* channel; // these fields must only be accessed under global_connection_polling_mu struct bg_watched_channel* next; int channel_destroyed; int refcount; } bg_watched_channel; /* grpc_rb_channel wraps a grpc_channel. */ typedef struct grpc_rb_channel { VALUE credentials; /* The actual channel (protected in a wrapper to tell when it's safe to * destroy) */ bg_watched_channel* bg_wrapped; } grpc_rb_channel; typedef enum { CONTINUOUS_WATCH, WATCH_STATE_API } watch_state_op_type; typedef struct watch_state_op { watch_state_op_type op_type; // from event.success union { struct { int success; // has been called back due to a cq next call int called_back; } api_callback_args; struct { bg_watched_channel* bg; } continuous_watch_callback_args; } op; } watch_state_op; static bg_watched_channel* bg_watched_channel_list_head = NULL; static void grpc_rb_channel_try_register_connection_polling( bg_watched_channel* bg); static void* wait_until_channel_polling_thread_started_no_gil(void*); static void wait_until_channel_polling_thread_started_unblocking_func(void*); static void* channel_init_try_register_connection_polling_without_gil( void* arg); typedef struct channel_init_try_register_stack { grpc_channel* channel; grpc_rb_channel* wrapper; } channel_init_try_register_stack; static grpc_completion_queue* channel_polling_cq; static gpr_mu global_connection_polling_mu; static gpr_cv global_connection_polling_cv; static int abort_channel_polling = 0; static int channel_polling_thread_started = 0; static int bg_watched_channel_list_lookup(bg_watched_channel* bg); static bg_watched_channel* bg_watched_channel_list_create_and_add( grpc_channel* channel); static void bg_watched_channel_list_free_and_remove(bg_watched_channel* bg); static void run_poll_channels_loop_unblocking_func(void* arg); // Needs to be called under global_connection_polling_mu static void grpc_rb_channel_watch_connection_state_op_complete( watch_state_op* op, int success) { GPR_ASSERT(!op->op.api_callback_args.called_back); op->op.api_callback_args.called_back = 1; op->op.api_callback_args.success = success; // wake up the watch API call thats waiting on this op gpr_cv_broadcast(&global_connection_polling_cv); } /* Avoids destroying a channel twice. */ static void grpc_rb_channel_safe_destroy(bg_watched_channel* bg) { gpr_mu_lock(&global_connection_polling_mu); GPR_ASSERT(bg_watched_channel_list_lookup(bg)); if (!bg->channel_destroyed) { grpc_channel_destroy(bg->channel); bg->channel_destroyed = 1; } bg->refcount--; if (bg->refcount == 0) { bg_watched_channel_list_free_and_remove(bg); } gpr_mu_unlock(&global_connection_polling_mu); } static void* channel_safe_destroy_without_gil(void* arg) { grpc_rb_channel_safe_destroy((bg_watched_channel*)arg); return NULL; } /* Destroys Channel instances. */ static void grpc_rb_channel_free(void* p) { grpc_rb_channel* ch = NULL; if (p == NULL) { return; }; ch = (grpc_rb_channel*)p; if (ch->bg_wrapped != NULL) { /* assumption made here: it's ok to directly gpr_mu_lock the global * connection polling mutex becuse we're in a finalizer, * and we can count on this thread to not be interrupted or * yield the gil. */ grpc_rb_channel_safe_destroy(ch->bg_wrapped); ch->bg_wrapped = NULL; } xfree(p); } /* Protects the mark object from GC */ static void grpc_rb_channel_mark(void* p) { grpc_rb_channel* channel = NULL; if (p == NULL) { return; } channel = (grpc_rb_channel*)p; if (channel->credentials != Qnil) { rb_gc_mark(channel->credentials); } } static rb_data_type_t grpc_channel_data_type = {"grpc_channel", {grpc_rb_channel_mark, grpc_rb_channel_free, GRPC_RB_MEMSIZE_UNAVAILABLE, {NULL, NULL}}, NULL, NULL, #ifdef RUBY_TYPED_FREE_IMMEDIATELY RUBY_TYPED_FREE_IMMEDIATELY #endif }; /* Allocates grpc_rb_channel instances. */ static VALUE grpc_rb_channel_alloc(VALUE cls) { grpc_rb_channel* wrapper = ALLOC(grpc_rb_channel); wrapper->bg_wrapped = NULL; wrapper->credentials = Qnil; return TypedData_Wrap_Struct(cls, &grpc_channel_data_type, wrapper); } /* call-seq: insecure_channel = Channel:new("myhost:8080", {'arg1': 'value1'}, :this_channel_is_insecure) creds = ... secure_channel = Channel:new("myhost:443", {'arg1': 'value1'}, creds) Creates channel instances. */ static VALUE grpc_rb_channel_init(int argc, VALUE* argv, VALUE self) { VALUE channel_args = Qnil; VALUE credentials = Qnil; VALUE target = Qnil; grpc_rb_channel* wrapper = NULL; grpc_channel* ch = NULL; grpc_channel_credentials* creds = NULL; char* target_chars = NULL; grpc_channel_args args; channel_init_try_register_stack stack; int stop_waiting_for_thread_start = 0; MEMZERO(&args, grpc_channel_args, 1); grpc_ruby_once_init(); rb_thread_call_without_gvl( wait_until_channel_polling_thread_started_no_gil, &stop_waiting_for_thread_start, wait_until_channel_polling_thread_started_unblocking_func, &stop_waiting_for_thread_start); /* "3" == 3 mandatory args */ rb_scan_args(argc, argv, "3", &target, &channel_args, &credentials); TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); target_chars = StringValueCStr(target); grpc_rb_hash_convert_to_channel_args(channel_args, &args); if (TYPE(credentials) == T_SYMBOL) { if (id_insecure_channel != SYM2ID(credentials)) { rb_raise(rb_eTypeError, "bad creds symbol, want :this_channel_is_insecure"); return Qnil; } ch = grpc_insecure_channel_create(target_chars, &args, NULL); } else { wrapper->credentials = credentials; creds = grpc_rb_get_wrapped_channel_credentials(credentials); ch = grpc_secure_channel_create(creds, target_chars, &args, NULL); } GPR_ASSERT(ch); stack.channel = ch; stack.wrapper = wrapper; rb_thread_call_without_gvl( channel_init_try_register_connection_polling_without_gil, &stack, NULL, NULL); if (args.args != NULL) { xfree(args.args); /* Allocated by grpc_rb_hash_convert_to_channel_args */ } if (ch == NULL) { rb_raise(rb_eRuntimeError, "could not create an rpc channel to target:%s", target_chars); return Qnil; } rb_ivar_set(self, id_target, target); return self; } typedef struct get_state_stack { bg_watched_channel* bg; int try_to_connect; int out; } get_state_stack; static void* get_state_without_gil(void* arg) { get_state_stack* stack = (get_state_stack*)arg; gpr_mu_lock(&global_connection_polling_mu); GPR_ASSERT(abort_channel_polling || channel_polling_thread_started); if (stack->bg->channel_destroyed) { stack->out = GRPC_CHANNEL_SHUTDOWN; } else { stack->out = grpc_channel_check_connectivity_state(stack->bg->channel, stack->try_to_connect); } gpr_mu_unlock(&global_connection_polling_mu); return NULL; } /* call-seq: ch.connectivity_state -> state ch.connectivity_state(true) -> state Indicates the current state of the channel, whose value is one of the constants defined in GRPC::Core::ConnectivityStates. It also tries to connect if the chennel is idle in the second form. */ static VALUE grpc_rb_channel_get_connectivity_state(int argc, VALUE* argv, VALUE self) { VALUE try_to_connect_param = Qfalse; grpc_rb_channel* wrapper = NULL; get_state_stack stack; /* "01" == 0 mandatory args, 1 (try_to_connect) is optional */ rb_scan_args(argc, argv, "01", &try_to_connect_param); TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); if (wrapper->bg_wrapped == NULL) { rb_raise(rb_eRuntimeError, "closed!"); return Qnil; } stack.bg = wrapper->bg_wrapped; stack.try_to_connect = RTEST(try_to_connect_param) ? 1 : 0; rb_thread_call_without_gvl(get_state_without_gil, &stack, NULL, NULL); return LONG2NUM(stack.out); } typedef struct watch_state_stack { grpc_channel* channel; gpr_timespec deadline; int last_state; } watch_state_stack; static void* wait_for_watch_state_op_complete_without_gvl(void* arg) { watch_state_stack* stack = (watch_state_stack*)arg; watch_state_op* op = NULL; void* success = (void*)0; gpr_mu_lock(&global_connection_polling_mu); // its unsafe to do a "watch" after "channel polling abort" because the cq has // been shut down. if (abort_channel_polling) { gpr_mu_unlock(&global_connection_polling_mu); return (void*)0; } op = gpr_zalloc(sizeof(watch_state_op)); op->op_type = WATCH_STATE_API; grpc_channel_watch_connectivity_state(stack->channel, stack->last_state, stack->deadline, channel_polling_cq, op); while (!op->op.api_callback_args.called_back) { gpr_cv_wait(&global_connection_polling_cv, &global_connection_polling_mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } if (op->op.api_callback_args.success) { success = (void*)1; } gpr_free(op); gpr_mu_unlock(&global_connection_polling_mu); return success; } static void wait_for_watch_state_op_complete_unblocking_func(void* arg) { bg_watched_channel* bg = (bg_watched_channel*)arg; gpr_mu_lock(&global_connection_polling_mu); if (!bg->channel_destroyed) { grpc_channel_destroy(bg->channel); bg->channel_destroyed = 1; } gpr_mu_unlock(&global_connection_polling_mu); } /* Wait until the channel's connectivity state becomes different from * "last_state", or "deadline" expires. * Returns true if the channel's connectivity state becomes different * from "last_state" within "deadline". * Returns false if "deadline" expires before the channel's connectivity * state changes from "last_state". * */ static VALUE grpc_rb_channel_watch_connectivity_state(VALUE self, VALUE last_state, VALUE deadline) { grpc_rb_channel* wrapper = NULL; watch_state_stack stack; void* op_success = 0; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); if (wrapper->bg_wrapped == NULL) { rb_raise(rb_eRuntimeError, "closed!"); return Qnil; } if (!FIXNUM_P(last_state)) { rb_raise( rb_eTypeError, "bad type for last_state. want a GRPC::Core::ChannelState constant"); return Qnil; } stack.channel = wrapper->bg_wrapped->channel; stack.deadline = grpc_rb_time_timeval(deadline, 0), stack.last_state = NUM2LONG(last_state); op_success = rb_thread_call_without_gvl( wait_for_watch_state_op_complete_without_gvl, &stack, wait_for_watch_state_op_complete_unblocking_func, wrapper->bg_wrapped); return op_success ? Qtrue : Qfalse; } /* Create a call given a grpc_channel, in order to call method. The request is not sent until grpc_call_invoke is called. */ static VALUE grpc_rb_channel_create_call(VALUE self, VALUE parent, VALUE mask, VALUE method, VALUE host, VALUE deadline) { VALUE res = Qnil; grpc_rb_channel* wrapper = NULL; grpc_call* call = NULL; grpc_call* parent_call = NULL; grpc_completion_queue* cq = NULL; int flags = GRPC_PROPAGATE_DEFAULTS; grpc_slice method_slice; grpc_slice host_slice; grpc_slice* host_slice_ptr = NULL; char* tmp_str = NULL; if (host != Qnil) { host_slice = grpc_slice_from_copied_buffer(RSTRING_PTR(host), RSTRING_LEN(host)); host_slice_ptr = &host_slice; } if (mask != Qnil) { flags = NUM2UINT(mask); } if (parent != Qnil) { parent_call = grpc_rb_get_wrapped_call(parent); } cq = grpc_completion_queue_create_for_pluck(NULL); TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); if (wrapper->bg_wrapped == NULL) { rb_raise(rb_eRuntimeError, "closed!"); return Qnil; } method_slice = grpc_slice_from_copied_buffer(RSTRING_PTR(method), RSTRING_LEN(method)); call = grpc_channel_create_call(wrapper->bg_wrapped->channel, parent_call, flags, cq, method_slice, host_slice_ptr, grpc_rb_time_timeval(deadline, /* absolute time */ 0), NULL); if (call == NULL) { tmp_str = grpc_slice_to_c_string(method_slice); rb_raise(rb_eRuntimeError, "cannot create call with method %s", tmp_str); return Qnil; } grpc_slice_unref(method_slice); if (host_slice_ptr != NULL) { grpc_slice_unref(host_slice); } res = grpc_rb_wrap_call(call, cq); /* Make this channel an instance attribute of the call so that it is not GCed * before the call. */ rb_ivar_set(res, id_channel, self); return res; } /* Closes the channel, calling it's destroy method */ /* Note this is an API-level call; a wrapped channel's finalizer doesn't call * this */ static VALUE grpc_rb_channel_destroy(VALUE self) { grpc_rb_channel* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); if (wrapper->bg_wrapped != NULL) { rb_thread_call_without_gvl(channel_safe_destroy_without_gil, wrapper->bg_wrapped, NULL, NULL); wrapper->bg_wrapped = NULL; } return Qnil; } /* Called to obtain the target that this channel accesses. */ static VALUE grpc_rb_channel_get_target(VALUE self) { grpc_rb_channel* wrapper = NULL; VALUE res = Qnil; char* target = NULL; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); target = grpc_channel_get_target(wrapper->bg_wrapped->channel); res = rb_str_new2(target); gpr_free(target); return res; } /* Needs to be called under global_connection_polling_mu */ static int bg_watched_channel_list_lookup(bg_watched_channel* target) { bg_watched_channel* cur = bg_watched_channel_list_head; while (cur != NULL) { if (cur == target) { return 1; } cur = cur->next; } return 0; } /* Needs to be called under global_connection_polling_mu */ static bg_watched_channel* bg_watched_channel_list_create_and_add( grpc_channel* channel) { bg_watched_channel* watched = gpr_zalloc(sizeof(bg_watched_channel)); watched->channel = channel; watched->next = bg_watched_channel_list_head; watched->refcount = 1; bg_watched_channel_list_head = watched; return watched; } /* Needs to be called under global_connection_polling_mu */ static void bg_watched_channel_list_free_and_remove( bg_watched_channel* target) { bg_watched_channel* bg = NULL; GPR_ASSERT(bg_watched_channel_list_lookup(target)); GPR_ASSERT(target->channel_destroyed && target->refcount == 0); if (bg_watched_channel_list_head == target) { bg_watched_channel_list_head = target->next; gpr_free(target); return; } bg = bg_watched_channel_list_head; while (bg != NULL && bg->next != NULL) { if (bg->next == target) { bg->next = bg->next->next; gpr_free(target); return; } bg = bg->next; } GPR_ASSERT(0); } /* Initialize a grpc_rb_channel's "protected grpc_channel" and try to push * it onto the background thread for constant watches. */ static void* channel_init_try_register_connection_polling_without_gil( void* arg) { channel_init_try_register_stack* stack = (channel_init_try_register_stack*)arg; gpr_mu_lock(&global_connection_polling_mu); stack->wrapper->bg_wrapped = bg_watched_channel_list_create_and_add(stack->channel); grpc_rb_channel_try_register_connection_polling(stack->wrapper->bg_wrapped); gpr_mu_unlock(&global_connection_polling_mu); return NULL; } // Needs to be called under global_connection_poolling_mu static void grpc_rb_channel_try_register_connection_polling( bg_watched_channel* bg) { grpc_connectivity_state conn_state; watch_state_op* op = NULL; GPR_ASSERT(channel_polling_thread_started || abort_channel_polling); if (bg->refcount == 0) { GPR_ASSERT(bg->channel_destroyed); bg_watched_channel_list_free_and_remove(bg); return; } GPR_ASSERT(bg->refcount == 1); if (bg->channel_destroyed || abort_channel_polling) { return; } conn_state = grpc_channel_check_connectivity_state(bg->channel, 0); if (conn_state == GRPC_CHANNEL_SHUTDOWN) { return; } GPR_ASSERT(bg_watched_channel_list_lookup(bg)); // prevent bg from being free'd by GC while background thread is watching it bg->refcount++; op = gpr_zalloc(sizeof(watch_state_op)); op->op_type = CONTINUOUS_WATCH; op->op.continuous_watch_callback_args.bg = bg; grpc_channel_watch_connectivity_state(bg->channel, conn_state, gpr_inf_future(GPR_CLOCK_REALTIME), channel_polling_cq, op); } // Note this loop breaks out with a single call of // "run_poll_channels_loop_no_gil". // This assumes that a ruby call the unblocking func // indicates process shutdown. // In the worst case, this stops polling channel connectivity // early and falls back to current behavior. static void* run_poll_channels_loop_no_gil(void* arg) { grpc_event event; watch_state_op* op = NULL; bg_watched_channel* bg = NULL; (void)arg; gpr_log(GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop_no_gil - begin"); gpr_mu_lock(&global_connection_polling_mu); GPR_ASSERT(!channel_polling_thread_started); channel_polling_thread_started = 1; gpr_cv_broadcast(&global_connection_polling_cv); gpr_mu_unlock(&global_connection_polling_mu); for (;;) { event = grpc_completion_queue_next( channel_polling_cq, gpr_inf_future(GPR_CLOCK_REALTIME), NULL); if (event.type == GRPC_QUEUE_SHUTDOWN) { break; } gpr_mu_lock(&global_connection_polling_mu); if (event.type == GRPC_OP_COMPLETE) { op = (watch_state_op*)event.tag; if (op->op_type == CONTINUOUS_WATCH) { bg = (bg_watched_channel*)op->op.continuous_watch_callback_args.bg; bg->refcount--; grpc_rb_channel_try_register_connection_polling(bg); gpr_free(op); } else if (op->op_type == WATCH_STATE_API) { grpc_rb_channel_watch_connection_state_op_complete( (watch_state_op*)event.tag, event.success); } else { GPR_ASSERT(0); } } gpr_mu_unlock(&global_connection_polling_mu); } grpc_completion_queue_destroy(channel_polling_cq); gpr_log(GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop_no_gil - exit connection polling " "loop"); return NULL; } // Notify the channel polling loop to cleanup and shutdown. static void run_poll_channels_loop_unblocking_func(void* arg) { bg_watched_channel* bg = NULL; (void)arg; gpr_mu_lock(&global_connection_polling_mu); gpr_log(GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop_unblocking_func - begin aborting " "connection polling"); // early out after first time through if (abort_channel_polling) { gpr_mu_unlock(&global_connection_polling_mu); return; } abort_channel_polling = 1; // force pending watches to end by switching to shutdown state bg = bg_watched_channel_list_head; while (bg != NULL) { if (!bg->channel_destroyed) { grpc_channel_destroy(bg->channel); bg->channel_destroyed = 1; } bg = bg->next; } grpc_completion_queue_shutdown(channel_polling_cq); gpr_cv_broadcast(&global_connection_polling_cv); gpr_mu_unlock(&global_connection_polling_mu); gpr_log(GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop_unblocking_func - end aborting " "connection polling"); } // Poll channel connectivity states in background thread without the GIL. static VALUE run_poll_channels_loop(VALUE arg) { (void)arg; gpr_log( GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop - create connection polling thread"); rb_thread_call_without_gvl(run_poll_channels_loop_no_gil, NULL, run_poll_channels_loop_unblocking_func, NULL); return Qnil; } static void* wait_until_channel_polling_thread_started_no_gil(void* arg) { int* stop_waiting = (int*)arg; gpr_log(GPR_DEBUG, "GRPC_RUBY: wait for channel polling thread to start"); gpr_mu_lock(&global_connection_polling_mu); while (!channel_polling_thread_started && !abort_channel_polling && !*stop_waiting) { gpr_cv_wait(&global_connection_polling_cv, &global_connection_polling_mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&global_connection_polling_mu); return NULL; } static void wait_until_channel_polling_thread_started_unblocking_func( void* arg) { int* stop_waiting = (int*)arg; gpr_mu_lock(&global_connection_polling_mu); gpr_log(GPR_DEBUG, "GRPC_RUBY: interrupt wait for channel polling thread to start"); *stop_waiting = 1; gpr_cv_broadcast(&global_connection_polling_cv); gpr_mu_unlock(&global_connection_polling_mu); } static void* set_abort_channel_polling_without_gil(void* arg) { (void)arg; gpr_mu_lock(&global_connection_polling_mu); abort_channel_polling = 1; gpr_cv_broadcast(&global_connection_polling_cv); gpr_mu_unlock(&global_connection_polling_mu); return NULL; } /* Temporary fix for * https://github.com/GoogleCloudPlatform/google-cloud-ruby/issues/899. * Transports in idle channels can get destroyed. Normally c-core re-connects, * but in grpc-ruby core never gets a thread until an RPC is made, because ruby * only calls c-core's "completion_queu_pluck" API. * This uses a global background thread that calls * "completion_queue_next" on registered "watch_channel_connectivity_state" * calls - so that c-core can reconnect if needed, when there aren't any RPC's. * TODO(apolcyn) remove this when core handles new RPCs on dead connections. */ void grpc_rb_channel_polling_thread_start() { VALUE background_thread = Qnil; GPR_ASSERT(!abort_channel_polling); GPR_ASSERT(!channel_polling_thread_started); GPR_ASSERT(channel_polling_cq == NULL); gpr_mu_init(&global_connection_polling_mu); gpr_cv_init(&global_connection_polling_cv); channel_polling_cq = grpc_completion_queue_create_for_next(NULL); background_thread = rb_thread_create(run_poll_channels_loop, NULL); if (!RTEST(background_thread)) { gpr_log(GPR_DEBUG, "GRPC_RUBY: failed to spawn channel polling thread"); rb_thread_call_without_gvl(set_abort_channel_polling_without_gil, NULL, NULL, NULL); } } static void Init_grpc_propagate_masks() { /* Constants representing call propagation masks in grpc.h */ VALUE grpc_rb_mPropagateMasks = rb_define_module_under(grpc_rb_mGrpcCore, "PropagateMasks"); rb_define_const(grpc_rb_mPropagateMasks, "DEADLINE", UINT2NUM(GRPC_PROPAGATE_DEADLINE)); rb_define_const(grpc_rb_mPropagateMasks, "CENSUS_STATS_CONTEXT", UINT2NUM(GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)); rb_define_const(grpc_rb_mPropagateMasks, "CENSUS_TRACING_CONTEXT", UINT2NUM(GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT)); rb_define_const(grpc_rb_mPropagateMasks, "CANCELLATION", UINT2NUM(GRPC_PROPAGATE_CANCELLATION)); rb_define_const(grpc_rb_mPropagateMasks, "DEFAULTS", UINT2NUM(GRPC_PROPAGATE_DEFAULTS)); } static void Init_grpc_connectivity_states() { /* Constants representing call propagation masks in grpc.h */ VALUE grpc_rb_mConnectivityStates = rb_define_module_under(grpc_rb_mGrpcCore, "ConnectivityStates"); rb_define_const(grpc_rb_mConnectivityStates, "IDLE", LONG2NUM(GRPC_CHANNEL_IDLE)); rb_define_const(grpc_rb_mConnectivityStates, "CONNECTING", LONG2NUM(GRPC_CHANNEL_CONNECTING)); rb_define_const(grpc_rb_mConnectivityStates, "READY", LONG2NUM(GRPC_CHANNEL_READY)); rb_define_const(grpc_rb_mConnectivityStates, "TRANSIENT_FAILURE", LONG2NUM(GRPC_CHANNEL_TRANSIENT_FAILURE)); rb_define_const(grpc_rb_mConnectivityStates, "FATAL_FAILURE", LONG2NUM(GRPC_CHANNEL_SHUTDOWN)); } void Init_grpc_channel() { grpc_rb_cChannelArgs = rb_define_class("TmpChannelArgs", rb_cObject); grpc_rb_cChannel = rb_define_class_under(grpc_rb_mGrpcCore, "Channel", rb_cObject); /* Allocates an object managed by the ruby runtime */ rb_define_alloc_func(grpc_rb_cChannel, grpc_rb_channel_alloc); /* Provides a ruby constructor and support for dup/clone. */ rb_define_method(grpc_rb_cChannel, "initialize", grpc_rb_channel_init, -1); rb_define_method(grpc_rb_cChannel, "initialize_copy", grpc_rb_cannot_init_copy, 1); /* Add ruby analogues of the Channel methods. */ rb_define_method(grpc_rb_cChannel, "connectivity_state", grpc_rb_channel_get_connectivity_state, -1); rb_define_method(grpc_rb_cChannel, "watch_connectivity_state", grpc_rb_channel_watch_connectivity_state, 2); rb_define_method(grpc_rb_cChannel, "create_call", grpc_rb_channel_create_call, 5); rb_define_method(grpc_rb_cChannel, "target", grpc_rb_channel_get_target, 0); rb_define_method(grpc_rb_cChannel, "destroy", grpc_rb_channel_destroy, 0); rb_define_alias(grpc_rb_cChannel, "close", "destroy"); id_channel = rb_intern("__channel"); id_target = rb_intern("__target"); rb_define_const(grpc_rb_cChannel, "SSL_TARGET", ID2SYM(rb_intern(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG))); rb_define_const(grpc_rb_cChannel, "ENABLE_CENSUS", ID2SYM(rb_intern(GRPC_ARG_ENABLE_CENSUS))); rb_define_const(grpc_rb_cChannel, "MAX_CONCURRENT_STREAMS", ID2SYM(rb_intern(GRPC_ARG_MAX_CONCURRENT_STREAMS))); rb_define_const(grpc_rb_cChannel, "MAX_MESSAGE_LENGTH", ID2SYM(rb_intern(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH))); id_insecure_channel = rb_intern("this_channel_is_insecure"); Init_grpc_propagate_masks(); Init_grpc_connectivity_states(); } /* Gets the wrapped channel from the ruby wrapper */ grpc_channel* grpc_rb_get_wrapped_channel(VALUE v) { grpc_rb_channel* wrapper = NULL; TypedData_Get_Struct(v, grpc_rb_channel, &grpc_channel_data_type, wrapper); return wrapper->bg_wrapped->channel; }
614527.c
/* light.c * Designed to run on the Create module * * The basic architecture of this program can be re-used to easily * write a wide variety of Create control programs. All sensor values * are polled in the background (using the serial rx interrupt) and * stored in the sensors array as long as the function * delayAndUpdateSensors() is called periodically. Users can send commands * directly a byte at a time using byteTx() or they can use the * provided functions, such as baud() and drive(). */ // Includes #include <avr/interrupt.h> #include <avr/io.h> #include <stdlib.h> #include "oi.h" // Constants #define START_SONG 0 #define ALARM_SONG 1 // Global variables volatile uint16_t timer_cnt = 0; volatile uint8_t timer_on = 0; volatile uint8_t sensors_flag = 0; volatile uint8_t sensors_index = 0; volatile uint8_t sensors_in[Sen6Size]; volatile uint8_t sensors[Sen6Size]; volatile int16_t distance = 0; volatile int16_t angle = 0; // Functions void byteTx(uint8_t value); void delayMs(uint16_t time_ms); void delayAndUpdateSensors(unsigned int time_ms); void initialize(void); void powerOnRobot(void); void baud(uint8_t baud_code); void drive(int16_t velocity, int16_t radius); uint16_t randomAngle(void); void defineSongs(void); int main (void) { int16_t turn_angle = 0; uint8_t turn_dir = 1; uint8_t turning = 0; uint8_t backing_up = 0; uint8_t leds_on = 0; int16_t light_start = 0; int16_t light_now = 0; uint8_t alarm = 0; // Set up Create and the Command Module initialize(); LEDBothOn; powerOnRobot(); byteTx(CmdStart); baud(Baud28800); defineSongs(); byteTx(CmdControl); byteTx(CmdFull); for(;;) { // Turn on all the leds byteTx(CmdLeds); byteTx(LEDsBoth); // Make Create's power LED orange byteTx(128); byteTx(255); LEDBothOn; delayAndUpdateSensors(1); if(UserButtonPressed) { // Play start song and wait byteTx(CmdPlay); byteTx(START_SONG); delayAndUpdateSensors(2250); // Sample the light level ADCSRA |= 0x40; while(ADCSRA & 0x40) ; light_start = ADC; // drive around while no alarm and until cliff detected, plugged in, or button pressed while(!alarm && (!UserButtonPressed) && (!sensors[SenCliffL]) && (!sensors[SenCliffFL]) && (!sensors[SenCliffFR]) && (!sensors[SenCliffR]) && (!sensors[SenChAvailable]) ) { // Sample the light level ADCSRA |= 0x40; while(ADCSRA & 0x40) ; light_now = ADC; // Compare and set the alarm if the light is brighter if(light_now > (light_start + (light_start >> 1))) alarm = 1; // Keep turning until the specified angle is reached if(turning) { if(backing_up) { if((-distance) > 12) backing_up = 0; drive(-200, RadStraight); } else { if(turn_dir) { if(angle > turn_angle) turning = 0; drive(200, RadCCW); } else { if((-angle) > turn_angle) turning = 0; drive(200, RadCW); } } } else if(sensors[SenBumpDrop] & BumpBoth) // Check for a bump { // Set the turn paramters and reset the angle if(sensors[SenBumpDrop] & BumpLeft) turn_dir = 0; else turn_dir = 1; backing_up = 1; turning = 1; distance = 0; angle = 0; turn_angle = randomAngle(); } else { // Otherwise, drive straight drive(300, RadStraight); } delayAndUpdateSensors(1); } // Stop drive(0, RadStraight); if(alarm) { alarm = 0; while(!UserButtonPressed) { // Play the alarm continuously byteTx(CmdPlay); byteTx(ALARM_SONG); // Flash the leds leds_on = !leds_on; if(leds_on) { byteTx(CmdLeds); byteTx(LEDsBoth); byteTx(128); byteTx(255); LEDBothOn; } else { byteTx(CmdLeds); byteTx(0x00); byteTx(0); byteTx(0); LEDBothOff; } // Delay between flashes delayAndUpdateSensors(100); } } // Turn off leds and delay before restarting byteTx(CmdLeds); byteTx(0x00); byteTx(0); byteTx(0); LEDBothOff; delayAndUpdateSensors(1500); } } } // Serial receive interrupt to store sensor values SIGNAL(SIG_USART_RECV) { uint8_t temp; temp = UDR0; if(sensors_flag) { sensors_in[sensors_index++] = temp; if(sensors_index >= Sen6Size) sensors_flag = 0; } } // Timer 1 interrupt to time delays in ms SIGNAL(SIG_OUTPUT_COMPARE1A) { if(timer_cnt) timer_cnt--; else timer_on = 0; } // Transmit a byte over the serial port void byteTx(uint8_t value) { while(!(UCSR0A & _BV(UDRE0))) ; UDR0 = value; } // Delay for the specified time in ms without updating sensor values void delayMs(uint16_t time_ms) { timer_on = 1; timer_cnt = time_ms; while(timer_on) ; } // Delay for the specified time in ms and update sensor values void delayAndUpdateSensors(uint16_t time_ms) { uint8_t temp; timer_on = 1; timer_cnt = time_ms; while(timer_on) { if(!sensors_flag) { for(temp = 0; temp < Sen6Size; temp++) sensors[temp] = sensors_in[temp]; // Update running totals of distance and angle distance += (int)((sensors[SenDist1] << 8) | sensors[SenDist0]); angle += (int)((sensors[SenAng1] << 8) | sensors[SenAng0]); byteTx(CmdSensors); byteTx(6); sensors_index = 0; sensors_flag = 1; } } } // Initialize the Mind Control's ATmega168 microcontroller void initialize(void) { cli(); // Set I/O pins DDRB = 0x10; PORTB = 0xCF; DDRC = 0x00; PORTC = 0xFF; DDRD = 0xE6; PORTD = 0x7D; // Set up timer 1 to generate an interrupt every 1 ms TCCR1A = 0x00; TCCR1B = (_BV(WGM12) | _BV(CS12)); OCR1A = 71; TIMSK1 = _BV(OCIE1A); // Set up the serial port with rx interrupt UBRR0 = 19; UCSR0B = (_BV(RXCIE0) | _BV(TXEN0) | _BV(RXEN0)); UCSR0C = (_BV(UCSZ00) | _BV(UCSZ01)); // Set up the ADC on pin C5 DIDR0 |= 0x20; // disable digital input on C5 PRR &= ~_BV(PRADC); // Turn off ADC power save ADCSRA = (_BV(ADEN) | _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0)); // Enabled, prescaler = 128 ADMUX = (_BV(REFS0) | 0x05); // set voltage reference, select channel C5 // Turn on interrupts sei(); } void powerOnRobot(void) { // If Create's power is off, turn it on if(!RobotIsOn) { while(!RobotIsOn) { RobotPwrToggleLow; delayMs(500); // Delay in this state RobotPwrToggleHigh; // Low to high transition to toggle power delayMs(100); // Delay in this state RobotPwrToggleLow; } delayMs(3500); // Delay for startup } } // Switch the baud rate on both Create and module void baud(uint8_t baud_code) { if(baud_code <= 11) { byteTx(CmdBaud); UCSR0A |= _BV(TXC0); byteTx(baud_code); // Wait until transmit is complete while(!(UCSR0A & _BV(TXC0))) ; cli(); // Switch the baud rate register if(baud_code == Baud115200) UBRR0 = Ubrr115200; else if(baud_code == Baud57600) UBRR0 = Ubrr57600; else if(baud_code == Baud38400) UBRR0 = Ubrr38400; else if(baud_code == Baud28800) UBRR0 = Ubrr28800; else if(baud_code == Baud19200) UBRR0 = Ubrr19200; else if(baud_code == Baud14400) UBRR0 = Ubrr14400; else if(baud_code == Baud9600) UBRR0 = Ubrr9600; else if(baud_code == Baud4800) UBRR0 = Ubrr4800; else if(baud_code == Baud2400) UBRR0 = Ubrr2400; else if(baud_code == Baud1200) UBRR0 = Ubrr1200; else if(baud_code == Baud600) UBRR0 = Ubrr600; else if(baud_code == Baud300) UBRR0 = Ubrr300; sei(); delayMs(100); } } // Send Create drive commands in terms of velocity and radius void drive(int16_t velocity, int16_t radius) { byteTx(CmdDrive); byteTx((uint8_t)((velocity >> 8) & 0x00FF)); byteTx((uint8_t)(velocity & 0x00FF)); byteTx((uint8_t)((radius >> 8) & 0x00FF)); byteTx((uint8_t)(radius & 0x00FF)); } // Return an angle value in the range 53 to 180 (degrees) uint16_t randomAngle(void) { return (53 + ((uint16_t)(random() & 0xFF) >> 1)); } // Define songs to be played later void defineSongs(void) { // Start song byteTx(CmdSong); byteTx(START_SONG); byteTx(5); byteTx(60); byteTx(24); byteTx(79); byteTx(24); byteTx(75); byteTx(24); byteTx(72); byteTx(24); byteTx(76); byteTx(48); // Alarm song byteTx(CmdSong); byteTx(ALARM_SONG); byteTx(7); byteTx(86); byteTx(24); byteTx(83); byteTx(24); byteTx(86); byteTx(24); byteTx(83); byteTx(24); byteTx(86); byteTx(24); byteTx(83); byteTx(24); byteTx(0); byteTx(96); }
633261.c
/* miniunz.c Version 1.1, February 14h, 2010 sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) Modifications of Unzip for Zip64 Copyright (C) 2007-2008 Even Rouault Modifications for Zip64 support on both zip and unzip Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) */ #if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) #ifndef __USE_FILE_OFFSET64 #define __USE_FILE_OFFSET64 #endif #ifndef __USE_LARGEFILE64 #define __USE_LARGEFILE64 #endif #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #endif #ifndef _FILE_OFFSET_BIT #define _FILE_OFFSET_BIT 64 #endif #endif #ifdef __APPLE__ // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions #define FOPEN_FUNC(filename, mode) fopen(filename, mode) #define FTELLO_FUNC(stream) ftello(stream) #define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) #else #define FOPEN_FUNC(filename, mode) fopen64(filename, mode) #define FTELLO_FUNC(stream) ftello64(stream) #define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #ifdef _WIN32 # include <direct.h> # include <io.h> #else # include <unistd.h> # include <utime.h> #endif #include "unzip.h" #define CASESENSITIVITY (0) #define WRITEBUFFERSIZE (8192) #define MAXFILENAME (256) #ifdef _WIN32 #define USEWIN32IOAPI #include "iowin32.h" #endif /* mini unzip, demo of unzip package usage : Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir] list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT if it exists */ /* change_file_date : change the date/time of a file filename : the filename of the file where date/time must be modified dosdate : the new date at the MSDos format (4 bytes) tmu_date : the SAME new date at the tm_unz format */ void change_file_date(filename,dosdate,tmu_date) const char *filename; uLong dosdate; tm_unz tmu_date; { #ifdef _WIN32 HANDLE hFile; FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, 0,NULL,OPEN_EXISTING,0,NULL); GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); LocalFileTimeToFileTime(&ftLocal,&ftm); SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); CloseHandle(hFile); #else #ifdef unix || __APPLE__ struct utimbuf ut; struct tm newdate; newdate.tm_sec = tmu_date.tm_sec; newdate.tm_min=tmu_date.tm_min; newdate.tm_hour=tmu_date.tm_hour; newdate.tm_mday=tmu_date.tm_mday; newdate.tm_mon=tmu_date.tm_mon; if (tmu_date.tm_year > 1900) newdate.tm_year=tmu_date.tm_year - 1900; else newdate.tm_year=tmu_date.tm_year ; newdate.tm_isdst=-1; ut.actime=ut.modtime=mktime(&newdate); utime(filename,&ut); #endif #endif } /* mymkdir and change_file_date are not 100 % portable As I don't know well Unix, I wait feedback for the unix portion */ int mymkdir(dirname) const char* dirname; { int ret=0; #ifdef _WIN32 ret = _mkdir(dirname); #elif unix ret = mkdir (dirname,0775); #elif __APPLE__ ret = mkdir (dirname,0775); #endif return ret; } int makedir (newdir) char *newdir; { char *buffer ; char *p; int len = (int)strlen(newdir); if (len <= 0) return 0; buffer = (char*)malloc(len+1); if (buffer==NULL) { printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } strcpy(buffer,newdir); if (buffer[len-1] == '/') { buffer[len-1] = '\0'; } if (mymkdir(buffer) == 0) { free(buffer); return 1; } p = buffer+1; while (1) { char hold; while(*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; if ((mymkdir(buffer) == -1) && (errno == ENOENT)) { printf("couldn't create directory %s\n",buffer); free(buffer); return 0; } if (hold == 0) break; *p++ = hold; } free(buffer); return 1; } void do_banner() { printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n"); printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); } void do_help() { printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ " -e Extract without pathname (junk paths)\n" \ " -x Extract with pathname\n" \ " -v list files\n" \ " -l list files\n" \ " -d directory to extract into\n" \ " -o overwrite files without prompting\n" \ " -p extract crypted file using password\n\n"); } void Display64BitsSize(ZPOS64_T n, int size_char) { /* to avoid compatibility problem , we do here the conversion */ char number[21]; int offset=19; int pos_string = 19; number[20]=0; for (;;) { number[offset]=(char)((n%10)+'0'); if (number[offset] != '0') pos_string=offset; n/=10; if (offset==0) break; offset--; } { int size_display_string = 19-pos_string; while (size_char > size_display_string) { size_char--; printf(" "); } } printf("%s",&number[pos_string]); } int do_list(uf) unzFile uf; { uLong i; unz_global_info64 gi; int err; err = unzGetGlobalInfo64(uf,&gi); if (err!=UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); for (i=0;i<gi.number_entry;i++) { char filename_inzip[256]; unz_file_info64 file_info; uLong ratio=0; const char *string_method; char charCrypt=' '; err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); break; } if (file_info.uncompressed_size>0) ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); /* display a '*' if the file is crypted */ if ((file_info.flag & 1) != 0) charCrypt='*'; if (file_info.compression_method==0) string_method="Stored"; else if (file_info.compression_method==Z_DEFLATED) { uInt iLevel=(uInt)((file_info.flag & 0x6)/2); if (iLevel==0) string_method="Defl:N"; else if (iLevel==1) string_method="Defl:X"; else if ((iLevel==2) || (iLevel==3)) string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ } else if (file_info.compression_method==Z_BZIP2ED) { string_method="BZip2 "; } else string_method="Unkn. "; Display64BitsSize(file_info.uncompressed_size,7); printf(" %6s%c",string_method,charCrypt); Display64BitsSize(file_info.compressed_size,7); printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", ratio, (uLong)file_info.tmu_date.tm_mon + 1, (uLong)file_info.tmu_date.tm_mday, (uLong)file_info.tmu_date.tm_year % 100, (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, (uLong)file_info.crc,filename_inzip); if ((i+1)<gi.number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGoToNextFile\n",err); break; } } } return 0; } int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password) unzFile uf; const int* popt_extract_without_path; int* popt_overwrite; const char* password; { char filename_inzip[256]; char* filename_withoutpath; char* p; int err=UNZ_OK; FILE *fout=NULL; void* buf; uInt size_buf; unz_file_info64 file_info; uLong ratio=0; err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); return err; } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) { printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; while ((*p) != '\0') { if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } if ((*filename_withoutpath)=='\0') { if ((*popt_extract_without_path)==0) { printf("creating directory: %s\n",filename_inzip); mymkdir(filename_inzip); } } else { const char* write_filename; int skip=0; if ((*popt_extract_without_path)==0) write_filename = filename_inzip; else write_filename = filename_withoutpath; err = unzOpenCurrentFilePassword(uf,password); if (err!=UNZ_OK) { printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); } if (((*popt_overwrite)==0) && (err==UNZ_OK)) { char rep=0; FILE* ftestexist; ftestexist = FOPEN_FUNC(write_filename,"rb"); if (ftestexist!=NULL) { fclose(ftestexist); do { char answer[128]; int ret; printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); } if (rep == 'N') skip = 1; if (rep == 'A') *popt_overwrite=1; } if ((skip==0) && (err==UNZ_OK)) { fout=FOPEN_FUNC(write_filename,"wb"); /* some zipfile don't contain directory alone before file */ if ((fout==NULL) && ((*popt_extract_without_path)==0) && (filename_withoutpath!=(char*)filename_inzip)) { char c=*(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; makedir(write_filename); *(filename_withoutpath-1)=c; fout=FOPEN_FUNC(write_filename,"wb"); } if (fout==NULL) { printf("error opening %s\n",write_filename); } } if (fout!=NULL) { printf(" extracting: %s\n",write_filename); do { err = unzReadCurrentFile(uf,buf,size_buf); if (err<0) { printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } if (err>0) if (fwrite(buf,err,1,fout)!=1) { printf("error in writing extracted file\n"); err=UNZ_ERRNO; break; } } while (err>0); if (fout) fclose(fout); if (err==0) change_file_date(write_filename,file_info.dosDate, file_info.tmu_date); } if (err==UNZ_OK) { err = unzCloseCurrentFile (uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzCloseCurrentFile\n",err); } } else unzCloseCurrentFile(uf); /* don't lose the error */ } free(buf); return err; } int do_extract(uf,opt_extract_without_path,opt_overwrite,password) unzFile uf; int opt_extract_without_path; int opt_overwrite; const char* password; { uLong i; unz_global_info64 gi; int err; FILE* fout=NULL; err = unzGetGlobalInfo64(uf,&gi); if (err!=UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n",err); for (i=0;i<gi.number_entry;i++) { if (do_extract_currentfile(uf,&opt_extract_without_path, &opt_overwrite, password) != UNZ_OK) break; if ((i+1)<gi.number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGoToNextFile\n",err); break; } } } return 0; } int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password) unzFile uf; const char* filename; int opt_extract_without_path; int opt_overwrite; const char* password; { int err = UNZ_OK; if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK) { printf("file %s not found in the zipfile\n",filename); return 2; } if (do_extract_currentfile(uf,&opt_extract_without_path, &opt_overwrite, password) == UNZ_OK) return 0; else return 1; } int main(argc,argv) int argc; char *argv[]; { const char *zipfilename=NULL; const char *filename_to_extract=NULL; const char *password=NULL; char filename_try[MAXFILENAME+16] = ""; int i; int ret_value=0; int opt_do_list=0; int opt_do_extract=1; int opt_do_extract_withoutpath=0; int opt_overwrite=0; int opt_extractdir=0; const char *dirname=NULL; unzFile uf=NULL; do_banner(); if (argc==1) { do_help(); return 0; } else { for (i=1;i<argc;i++) { if ((*argv[i])=='-') { const char *p=argv[i]+1; while ((*p)!='\0') { char c=*(p++);; if ((c=='l') || (c=='L')) opt_do_list = 1; if ((c=='v') || (c=='V')) opt_do_list = 1; if ((c=='x') || (c=='X')) opt_do_extract = 1; if ((c=='e') || (c=='E')) opt_do_extract = opt_do_extract_withoutpath = 1; if ((c=='o') || (c=='O')) opt_overwrite=1; if ((c=='d') || (c=='D')) { opt_extractdir=1; dirname=argv[i+1]; } if (((c=='p') || (c=='P')) && (i+1<argc)) { password=argv[i+1]; i++; } } } else { if (zipfilename == NULL) zipfilename = argv[i]; else if ((filename_to_extract==NULL) && (!opt_extractdir)) filename_to_extract = argv[i] ; } } } if (zipfilename!=NULL) { # ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc; # endif strncpy(filename_try, zipfilename,MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ filename_try[ MAXFILENAME ] = '\0'; # ifdef USEWIN32IOAPI fill_win32_filefunc64A(&ffunc); uf = unzOpen2_64(zipfilename,&ffunc); # else uf = unzOpen64(zipfilename); # endif if (uf==NULL) { strcat(filename_try,".zip"); # ifdef USEWIN32IOAPI uf = unzOpen2_64(filename_try,&ffunc); # else uf = unzOpen64(filename_try); # endif } } if (uf==NULL) { printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename); return 1; } printf("%s opened\n",filename_try); if (opt_do_list==1) ret_value = do_list(uf); else if (opt_do_extract==1) { #ifdef _WIN32 if (opt_extractdir && _chdir(dirname)) #else if (opt_extractdir && chdir(dirname)) #endif { printf("Error changing into %s, aborting\n", dirname); exit(-1); } if (filename_to_extract == NULL) ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password); else ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password); } unzClose(uf); return ret_value; }
907285.c
/* * Copyright 2021 Benjamin Edgington * * 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 fft_common.c * * Code shared between the FFTs over field elements and FFTs over G1 group elements. */ #include "fft_common.h" #include "c_kzg_util.h" /** * Generate powers of a root of unity in the field for use in the FFTs. * * @remark @p root must be such that @p root ^ @p width is equal to one, but no smaller power of @p root is equal to * one. * * @param[out] out The generated powers of the root of unity (array size @p width + 1) * @param[in] root A root of unity * @param[in] width One less than the size of @p out * @retval C_CZK_OK All is well * @retval C_CZK_BADARGS Invalid parameters were supplied */ C_KZG_RET expand_root_of_unity(fr_t *out, const fr_t *root, uint64_t width) { out[0] = fr_one; out[1] = *root; for (uint64_t i = 2; !fr_is_one(&out[i - 1]); i++) { CHECK(i <= width); fr_mul(&out[i], &out[i - 1], root); } CHECK(fr_is_one(&out[width])); return C_KZG_OK; } /** * Initialise an FFTSettings structure. * * Space is allocated for, and arrays are populated with, powers of the roots of unity. The two arrays contain the same * values in reverse order for convenience in inverse FFTs. * * `max_width` is the maximum size of FFT that can be calculated with these settings, and is a power of two by * construction. The same settings may be used to calculated FFTs of smaller power sizes. * * @remark As with all functions prefixed `new_`, this allocates memory that needs to be reclaimed by calling the * corresponding `free_` function. In this case, #free_fft_settings. * @remark These settings may be used for FFTs on both field elements and G1 group elements. * * @param[out] fs The new settings * @param[in] max_scale Log base 2 of the max FFT size to be used with these settings * @retval C_CZK_OK All is well * @retval C_CZK_BADARGS Invalid parameters were supplied * @retval C_CZK_ERROR An internal error occurred * @retval C_CZK_MALLOC Memory allocation failed */ C_KZG_RET new_fft_settings(FFTSettings *fs, unsigned int max_scale) { fs->max_width = (uint64_t)1 << max_scale; CHECK((max_scale < sizeof scale2_root_of_unity / sizeof scale2_root_of_unity[0])); fr_from_uint64s(&fs->root_of_unity, scale2_root_of_unity[max_scale]); // Allocate space for the roots of unity TRY(new_fr_array(&fs->expanded_roots_of_unity, fs->max_width + 1)); TRY(new_fr_array(&fs->reverse_roots_of_unity, fs->max_width + 1)); // Populate the roots of unity TRY(expand_root_of_unity(fs->expanded_roots_of_unity, &fs->root_of_unity, fs->max_width)); // Populate reverse roots of unity for (uint64_t i = 0; i <= fs->max_width; i++) { fs->reverse_roots_of_unity[i] = fs->expanded_roots_of_unity[fs->max_width - i]; } return C_KZG_OK; } /** * Free the memory that was previously allocated by #new_fft_settings. * * @param fs The settings to be freed */ void free_fft_settings(FFTSettings *fs) { free(fs->expanded_roots_of_unity); free(fs->reverse_roots_of_unity); fs->max_width = 0; }
473033.c
#include<stdio.h> int main(){ int a; a=2; 3=a; return 0; }
454775.c
/* -------------------------------------------------------------------- */ /* ACCORDS PLATFORM */ /* (C) 2011 by Iain James Marshall (Prologue) <[email protected]> */ /* -------------------------------------------------------------------- */ /* 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. */ /* -------------------------------------------------------------------- */ #ifndef _strukt_c #define _strukt_c #include "strukt.h" public struct strukt_context C = { 0, /* schema */ (char *) 0, /* license */ (char *) 0, /* scheme */ (char *) 0, /* klass */ (char *) 0, /* rel */ "", /* prefix */ 0,0,0,0, 0,0,0,0, 0,0, 0,0,0,0, 0,0, (FILE *) 0, (char *) 0, (struct item *) 0, (struct item *) 0 }; #include "item.c" public void reset_strukt() { struct item * iptr; while ((iptr=C.first) != (struct item *) 0) { C.first = iptr->next; liberate_item( iptr ); } C.first = C.last = (struct item *) 0; if ( C.license ) C.license = liberate( C.license ); if ( C.scheme ) C.scheme = liberate( C.scheme ); if ( C.klass ) C.klass = liberate( C.klass ); if ( C.rel ) C.rel = liberate( C.rel ); memset( &C, 0, sizeof( struct strukt_context )); return; } public int strukt_set_license(char * filename) { if (!( C.license = allocate_string(filename) )) return(27); else return(0); } public void strukt_set_prefix(char * value ) { C.prefix = allocate_string( value ); } public void strukt_set_gencrud(int value) { C.gencrud = value; return; } public void strukt_set_genxml(int value) { C.genxml = value; return; } public void strukt_set_schema(int value) { C.schema = value; return; } public void strukt_set_genrest(int value) { C.genrest = value; return; } public void strukt_set_genocci(int value) { C.genocci = value; return; } private void expand( FILE * h, char * sptr ) { int c; while ((c = *(sptr++)) != 0) fprintf(h,"%c ",c); return; } private void gener( FILE * h, int c ,int n ) { while ( n-- ) fprintf(h,"%c",c); return; } public void title( FILE * h, char * sptr ) { fprintf(h,"\n/*\t"); gener( h, '-', strlen( sptr ) * 2 ); fprintf(h,"\t*/\n"); fprintf(h,"/*\t"); expand( h, sptr ); fprintf(h,"\t*/\n"); fprintf(h,"/*\t"); gener( h, '-', strlen( sptr ) * 2 ); fprintf(h,"\t*/\n"); return; } private void generate_reset( FILE *h, char * nptr ) { int i; struct item * iptr; char buffer[512]; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public struct %s * %s(struct %s * sptr)\n{\n",C.name,buffer,C.name); fprintf(h,"\tif ( sptr )\n\t{\n"); for ( iptr= C.first; iptr != (struct item *) 0; iptr = iptr->next ) { if (!( iptr->dimension )) { fprintf(h,"\t\tsptr->%s = ",iptr->name); if ( iptr->indirection ) { fprintf(h,"("); if (!( strcmp( iptr->basic,"struct" ) )) fprintf(h,"struct %s",iptr->type); else fprintf(h,"%s",iptr->basic); for ( i=0;i < iptr->indirection; i++ ) fprintf(h,"*"); fprintf(h,") 0;\n"); } else fprintf(h," 0;\n"); } else { fprintf(h,"\t\tmemset(&sptr->%s,0,sizeof(",iptr->name); if (!( strcmp( iptr->basic,"struct" ) )) fprintf(h,"struct %s",iptr->type); else fprintf(h,"%s",iptr->basic); for ( i=0;i < iptr->indirection; i++ ) fprintf(h,"*"); fprintf(h,")*%u);\n",iptr->dimension); } } fprintf(h,"\t}\n"); fprintf(h,"\treturn(sptr);\n"); fprintf(h,"\n}\n"); } private void generate_allocate( FILE *h, char * nptr ) { int i; struct item * iptr; char buffer[512]; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public struct %s * %s()\n{\n",C.name,buffer); fprintf(h,"\tstruct %s * sptr;\n",C.name); fprintf(h,"\tif (!( sptr = allocate( sizeof( struct %s ) ) ))\n\t\treturn( sptr );\n",C.name); fprintf(h,"\telse\treturn( reset_%s(sptr) );",C.name); fprintf(h,"\n}\n"); } private void generate_add( FILE *h, char * nptr ) { int i; struct item * iptr; char buffer[512]; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public struct %s * %s(struct %s * pptr)\n{\n",C.name,buffer,C.parent); fprintf(h,"\tstruct %s * sptr;\n",C.name); fprintf(h,"\tif (!( sptr = allocate( sizeof( struct %s ) ) ))\n\t\treturn( sptr );\n",C.name); fprintf(h,"\telse if (!( sptr = reset_%s(sptr) ))\n\t\treturn( sptr );\n",C.name); fprintf(h,"\telse\n\t{\n"); fprintf(h,"\t\tif (!( sptr->previous = pptr->last ))\n"); fprintf(h,"\t\t\tpptr->first = sptr;\n"); fprintf(h,"\t\telse\tsptr->previous->next = sptr;\n"); fprintf(h,"\t\tpptr->last = sptr;\n"); fprintf(h,"\t\tsptr->parent = pptr;\n"); fprintf(h,"\t\treturn( sptr );\n"); fprintf(h,"\t}\n"); fprintf(h,"\n}\n"); } private void generate_drop( FILE *h, char * nptr ) { int i; struct item * iptr; char buffer[512]; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public struct %s * %s(struct %s * sptr)\n{\n",C.name,buffer,C.name); fprintf(h,"\tif ( sptr )\n\t{\n"); fprintf(h,"\t\tif (!( sptr->parent )) return(sptr);\n"); fprintf(h,"\t\tif (!( sptr->previous ))\n"); fprintf(h,"\t\t{\n"); fprintf(h,"\t\t\tif (!( sptr->parent->first = sptr->next ))\n"); fprintf(h,"\t\t\t\tsptr->parent->last = (struct %s *) 0;\n",C.name); fprintf(h,"\t\t\telse sptr->parent->first->previous = (struct %s *) 0;\n",C.name); fprintf(h,"\t\t}\n"); fprintf(h,"\t\telse if (!( sptr->previous->next = sptr->next ))\n"); fprintf(h,"\t\t\tsptr->parent->last = sptr->previous;\n"); fprintf(h,"\t\tif (!( sptr->next ))\n"); fprintf(h,"\t\t{\n"); fprintf(h,"\t\t\tif (!( sptr->parent->last = sptr->previous ))\n"); fprintf(h,"\t\t\t\tsptr->parent->first = (struct %s *) 0;\n",C.name); fprintf(h,"\t\t\telse sptr->parent->last->next = (struct %s *) 0;\n",C.name); fprintf(h,"\t\t}\n"); fprintf(h,"\t\telse if (!( sptr->next->previous = sptr->previous ))\n"); fprintf(h,"\t\t\tsptr->parent->first = sptr->next;\n"); fprintf(h,"\t\tsptr = liberate_%s(sptr);\n",C.name); fprintf(h,"\t}\n"); fprintf(h,"\treturn((struct %s *) 0);",C.name); fprintf(h,"\n}\n"); } private void generate_occi_request2file( FILE * h, char * nptr ) { char * prefix; int item=0; char buffer[512]; struct item * iptr; prefix = "c1"; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public int %s(FILE * fh,struct %s * sptr,char * prefix, char * nptr)\n{\n",buffer,C.name); fprintf(h,"\tstruct xml_element * wptr;\n"); fprintf(h,"\tif (!( sptr )) return(0);\n"); fprintf(h,"\tfprintf(fh,%cPOST /%cs/ HTTP/1.1\\r\\n%c,nptr);\n",0x0022,0x0025,0X0022); fprintf(h,"\tfprintf(fh,%cCategory: %cs; scheme='http://scheme.%cs.org/occi/%cs#'; class='kind';\\r\\n%c,nptr,prefix,prefix);\n", 0x0022, 0x0025, 0x0025,0x0025,0x0022); for ( iptr= C.first; iptr != (struct item *) 0; iptr = iptr->next ) { if (!( strcmp( iptr->basic,"struct" ) )) continue; else if ( iptr->indirection ) { fprintf(h,"\tfprintf(fh,%cX-OCCI-Attribute: %cs.%cs.%s='%cs'\\r\\n%c,prefix,nptr,(sptr->%s?sptr->%s:%c%c));\n", 0x0022,0x0025,0x0025,iptr->name,0x0025,0x0022,iptr->name,iptr->name,0x0022,0x0022); } else { fprintf(h,"\tfprintf(fh,%cX-OCCI-Attribute: %cs.%cs.%s='%cu'\\r\\n%c,prefix,nptr,sptr->%s);\n", 0x0022,0x0025,0x0025,iptr->name,0x0025,0x0022,iptr->name); } } fprintf(h,"\treturn(0);\n"); fprintf(h,"\n}\n"); } private void generate_interpret_xml( FILE * h, char * nptr ) { char * prefix; int item=0; char buffer[512]; struct item * iptr; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public int %s(struct %s * sptr,struct xml_element * eptr)\n{\n",buffer,C.name); fprintf(h,"\tstruct xml_element * wptr;\n"); fprintf(h,"\tif (!( eptr )) return(0);\n"); fprintf(h,"\tif (!( sptr )) return(0);\n"); fprintf(h,"\tfor ( wptr=eptr->first; wptr != (struct xml_element *) 0; wptr=wptr->next)\n\t{\n"); prefix = "\0"; for ( iptr= C.first; iptr != (struct item *) 0; iptr = iptr->next ) { if (!( strcmp( iptr->basic,"struct" ) )) continue; fprintf(h,"\t\t%sif (!( strcmp(wptr->name,%c%s%c) ))\n",prefix,0x0022,iptr->name,0x0022); prefix = "else "; fprintf(h,"\t\t{\n"); if ( iptr->indirection ) { fprintf(h,"\t\t\tif ( wptr->value ) { sptr->%s = allocate_string(wptr->value); }\n",iptr->name); } else { fprintf(h,"\t\t\tif ( wptr->value ) { sptr->%s = atoi(wptr->value); }\n",iptr->name); } fprintf(h,"\t\t}\n"); } fprintf(h,"\t}\n"); fprintf(h,"\treturn(0);\n"); fprintf(h,"\n}\n"); } private void generate_liberate( FILE *h, char * nptr ) { char buffer[512]; struct item * iptr; sprintf(buffer,"%s_%s",nptr,C.name); title(h, buffer ); fprintf(h,"public struct %s * %s(struct %s * sptr)\n{\n",C.name,buffer,C.name); if ( C.hasfirst ) { fprintf(h,"\tstruct %s * mptr;\n",C.premier); } fprintf(h,"\tif ( sptr )\n\t{\n"); for ( iptr= C.first; iptr != (struct item *) 0; iptr = iptr->next ) { if ( C.hasfirst ) { if (!( strcmp( iptr->name, "last" ) )) continue; if (!( strcmp( iptr->name, "first" ) )) { fprintf(h,"\t\twhile ((mptr = sptr->first) != (struct %s *) 0)\n\t\t{\n",C.premier); fprintf(h,"\t\t\tsptr->first = mptr->next;\n"); fprintf(h,"\t\t\tmptr = liberate_%s( mptr );\n\t\t}\n",C.premier); continue; } } if (!( strcmp( iptr->name, "parent" ) )) continue; else if (!( strcmp( iptr->basic, "void" ) )) continue; else if ( iptr->indirection == 1 ) { if (!( strcmp( iptr->name, "previous" ))) continue; else if (!( strcmp( iptr->name, "next" ))) continue; fprintf(h,"\t\tif ( sptr->%s )\n\t\t\t sptr->%s = liberate",iptr->name,iptr->name); if (!( strcmp( iptr->basic, "struct" ) )) fprintf(h,"_%s",iptr->type); fprintf(h,"(sptr->%s);\n",iptr->name); } } fprintf(h,"\t\tsptr = liberate( sptr );\n"); fprintf(h,"\t}\n"); fprintf(h,"\treturn((struct %s *) 0);\n",C.name); fprintf(h,"\n}\n"); } public int generate() { struct item * iptr; if ( C.schema ) { fprintf(C.target,"\n<xsd:complexType name=%c%s%c>\n",0x0022,C.name,0x0022); for ( iptr= C.first; iptr != (struct item *) 0; iptr = iptr->next ) { fprintf(C.target,"\t<xsd:attribute name=%c%s%c",0x0022,iptr->name,0x0022); if (!( strcmp( iptr->basic , "int" ) )) fprintf(C.target," type=%c%s%c",0x0022,"xsd:integer"); else fprintf(C.target," type=%c%s%c",0x0022,"xsd:string"); fprintf(C.target,"/>\n"); } fprintf(C.target,"</xsd:complexType>\n"); } else if ( C.genrest ) { switch ( C.genrest ) { case _OCCI_KIND : C.klass = allocate_string("kind"); C.scheme = allocate_string("http://scheme.compatibleone.fr/scheme/compatible#"); C.rel = allocate_string("http://scheme.ogf.org/occi/resource#"); break; case _OCCI_LINK : C.klass = allocate_string("link"); C.scheme = allocate_string("http://scheme.compatibleone.fr/scheme/compatible#"); C.rel = allocate_string("http://scheme.ogf.org/occi/link#"); break; case _STRUKT_OCCI_ACTION : C.klass = allocate_string("action"); C.scheme = allocate_string("http://scheme.compatibleone.fr/scheme/compatible#"); C.rel = allocate_string("http://scheme.ogf.org/occi/mixin#"); break; case _STRUKT_OCCI_MIXIN : C.klass = allocate_string("mixin"); C.scheme = allocate_string("http://scheme.compatibleone.fr/scheme/compatible#"); C.rel = allocate_string("http://scheme.ogf.org/occi/action#"); break; default : return( failure(30,"incorrect","cords value") ); } if ( C.gensql ) { generate_occi_sql_builder( C.target, "occi" ); } else { generate_occi_rest_builder( C.target, "occi" ); generate_occi_rest_request( C.target, "rest_occi" ); } } else { generate_liberate( C.target, "liberate" ); generate_reset( C.target, "reset" ); generate_allocate( C.target, "allocate" ); if (( C.hasparent ) && ( C.hasprevious ) && ( C.hasnext )) { generate_add( C.target, "add" ); generate_drop( C.target, "drop" ); } if ( C.genxml ) { generate_interpret_xml( C.target, "xmlin" ); } if ( C.genocci ) { generate_occi_request2file( C.target, "rest_occi" ); } } return(0); } private int is_punctuation(int c) { if (( c >= 0x0021 ) && ( c <= 0x002F )) return(1); else if (( c >= 0x003a ) && ( c <= 0x003f )) return(1); else if (( c >= 0x005b) && ( c <= 0x005e )) return(1); else if (( c >= 0x007b) && ( c <= 0x007f )) return(1); else return(0); } private int ungetch(int c) { return((C.ungotc = c)); } private int getch(FILE *h) { int c; if ((c = C.ungotc) != 0) C.ungotc = 0; else if ((c = fgetc(h)) == -1) c = 0; else if ( C.echo ) printf("%c",c); return( c ); } private int is_white( int c ) { switch ( c ) { case ' ' : case '\r' : case '\t' : case '\n' : return( c ); default : return( 0 ); } } private int remove_white_space(FILE * h) { int c; while (1) { switch ((c = getch(h))) { case 0x23 : while (((c = getch(h)) != 0) && ( c != '\n')); if ( c == '\n' ) continue; case 0 : case 26 : return(0); default : if ( is_white( c ) ) continue; else return(ungetch(c)); } } } private int get_token( FILE * h, char * token, int tlen ) { int c; int i=0; int quoting=0; while ( i < tlen ) { if (!(c = getch(h))) break; else if ( c == '"' ) { quoting = c; continue; } else if ( c == quoting ) { quoting = 0; break; } else if ( quoting ) { *(token+i) = c; i++; continue; } else if ( is_white( c ) ) { ungetch( c ); break; } else if ( is_punctuation( c ) ) { ungetch( c ); break; } else { *(token+i) = c; i++; continue; } } *(token+i) = 0; return(i); } public int add_member() { struct item * iptr; if (!( iptr = allocate_item())) return( failure( 27,"allocation","item") ); else if (!( iptr->name = allocate_string( C.member ))) return( failure( 27,"allocation","item->name") ); else if (!( iptr->basic = allocate_string( C.basic ))) return( failure( 27,"allocation","item->basic") ); else { if (!( strcmp( C.basic, "struct" ) )) if (!( iptr->type = allocate_string( C.special ))) return( failure( 27,"allocation","item->type") ); iptr->dimension = C.dimension; iptr->indirection = C.isptr; C.isptr = 0; C.dimension=0; if (!( iptr->previous = C.last )) C.first = iptr; else iptr->previous->next = iptr; C.last = iptr; if (!( strcmp( C.basic, "struct" ) )) { if (!( strcmp(C.member, "first" ) )) { C.hasfirst=1; strcpy( C.premier, C.special ); } else if (!( strcmp(C.member, "parent" ) )) { C.hasparent=1; strcpy( C.parent, C.special ); } else if (!( strcmp(C.member, "previous" ) )) { C.hasprevious=1; } else if (!( strcmp(C.member, "next" ) )) { C.hasnext=1; } } return( 0 ); } } private int handle_comment( FILE * sh ) { int c; int state=0; switch ( getch(sh) ) { case '/' : while (((c = getch(sh)) > 0) && ( c != '\n')); break; case '*' : while ((c = getch(sh)) > 0) { if (!( state )) { if ( c == '*' ) state = 1; } else if ( c == '/' ) break; else state = 0; } break; } return(0); } private int handle_punctuation( FILE * sh, int c ) { int status; char b[2]; switch ( C.state ) { case 0 : /* awaiting struct */ if ( c == '/' ) { handle_comment(sh); return(0); } case 1 : /* awaiting struct name */ break; case 2 : if ( c == '{' ) { C.state = C.next; return( 0 ); } else break; case 3 : /* awaiting type keyword */ if ( c == '}' ) { C.state = 9; return(0); } else if ( c == '/' ) { handle_comment(sh); return(0); } else break; case 4 : /* awaiting extended type */ case 5 : /* awaiting name or pointer */ if ( c == '*' ) { C.isptr++; return(0); } break; case 6 : /* awaiting colon or dimension */ if ( c == ';' ) { if (!( status = add_member() )) { C.state = C.next; return( 0 ); } else break; } else if ( c == '[' ) { C.state = 7; return( 0 ); } else break; case 8 : /* awaiting closure of dimension */ if ( c == ']' ) { C.state = 6; return(0); } else break; case 9 : /* awaiting colon or dimension */ if ( c == ';' ) { C.state = 0; return(generate()); } else if ( c == '/' ) { handle_comment(sh); return(0); } } b[0] = c; b[1] = 0; return(failure(30,"incorrect punctuation",b)); } private char * is_basic_type(char * tptr) { if (!(strcmp( tptr,"struct"))) return( "struct" ); else if (!(strcmp( tptr,"float"))) return( "float" ); else if (!(strcmp( tptr,"double"))) return( "double" ); else if (!(strcmp( tptr,"char"))) return( "char" ); else if (!(strcmp( tptr,"int"))) return( "int" ); else if (!(strcmp( tptr,"short"))) return( "short" ); else if (!(strcmp( tptr,"long"))) return( "long" ); else if (!(strcmp( tptr,"void"))) return( "void" ); else return( (char *) 0); } private int handle_token( FILE * sh, char * tptr ) { switch ( C.state ) { case 0 : /* awaiting struct */ if (!( strcmp( tptr, "struct" ) )) { C.state = 1; return(0); } else break; case 1 : /* awaiting struct name */ strcpy( C.name, tptr ); C.next = 3; C.state = 2; return(0); case 2 : /* awaiting opener */ break; case 3 : /* awaiting type */ if ((C.basic = is_basic_type( tptr )) != (char *) 0) { if (!(strcmp( C.basic,"struct"))) C.state = 4; else C.state = 5; return(0); } else break; case 4 : /* awaiting type name */ strcpy(C.special,tptr); C.state = 5; return(0); case 5 : /* awaiting name */ strcpy(C.member,tptr); C.state = 6; return(0); case 6 : /* awaiting semi or dimensions */ break; case 7 : /* awaiting dimension */ C.dimension = atoi( tptr ); C.state = 8; return(0); } return( failure( 30 , "incorrect token", tptr ) ); } private void file_symbol( FILE * h, char * sptr ) { int c; fprintf(h,"_"); while ((c = *(sptr++)) != 0) { if ( is_punctuation( c ) ) fprintf(h,"_"); else fprintf(h,"%c",c); } fprintf(h,"_"); return; } private void prepend_license( FILE * target, char * filename ) { int c; FILE * h; if ((h = fopen( filename, "r")) != (FILE *) 0) { while ((c = fgetc(h)) > 0) fputc(c,target); fclose(h); } return; } private void schema_header( FILE * h, char * nptr, char * iptr) { fprintf(h,"\n<xsd:sxhema xmlns:xsd=%chttp://www.w3c.org/2001/XMLSchema%c>\n",0x0022,0x0022); return; } private void schema_footer( FILE * h, char * nptr ) { fprintf(h,"\n</xsd:sxhema>\n"); return; } private void file_header( FILE * h, char * nptr, char * iptr) { char buffer[1024]; if ( C.genrest ) sprintf(buffer,"occi%s",nptr); else strcpy(buffer,nptr); if ( C.license ) { prepend_license( h, C.license ); } fprintf(h,"/* STRUKT WARNING : this file has been generated and should not be modified by hand */\n"); fprintf(h,"#ifndef "); file_symbol( h, buffer ); fprintf(h,"\n"); fprintf(h,"#define "); file_symbol( h, buffer ); fprintf(h,"\n"); if ( C.genxml ) { fprintf(h,"\n#include %c%s%c\n",0x0022,"element.h",0x0022); } fprintf(h,"\n#include %c%s%c\n",0x0022,iptr,0x0022); return; } private void file_footer( FILE * h, char * nptr) { char buffer[1024]; if ( C.genrest ) sprintf(buffer,"occi%s",nptr); else strcpy(buffer,nptr); fprintf(h,"\n#endif\t/* "); file_symbol( h, buffer ); fprintf(h," */\n"); return; } public int process( char * nptr ) { int status; int c; int l; char sn[512]; char tn[512]; char token[512]; FILE * sh; sprintf(sn,"%s.h",nptr); sprintf(tn,"%s%s.c",C.prefix,nptr); if (!( sh = fopen( sn, "r" ))) return( failure(40,"file not found",sn) ); else if (!( C.target = fopen( tn, "w" ))) { fclose(sh); return( failure(46,"creating file",tn) ); } else { file_header( C.target, tn, sn ); while ((c = remove_white_space( sh ))) { if ( is_punctuation(c) ) { if (!(status = handle_punctuation(sh,getch(sh)))) continue; else break; } else if (!( l = get_token(sh,token,512) )) break; else if (!( status = handle_token(sh,token) )) continue; else break; } file_footer( C.target, tn ); fclose(C.target); C.target = (FILE *) 0; fclose(sh); } return( 0 ); } public int schema( char * nptr ) { int status; int c; int l; char sn[512]; char tn[512]; char token[512]; FILE * sh; sprintf(sn,"%s.h",nptr); sprintf(tn,"%s.xsd",nptr); if (!( sh = fopen( sn, "r" ))) return( failure(40,"file not found",sn) ); else if (!( C.target = fopen( tn, "w" ))) { fclose(sh); return( failure(46,"creating file",tn) ); } else { schema_header( C.target, tn, sn ); while ((c = remove_white_space( sh ))) { if ( is_punctuation(c) ) { if (!(status = handle_punctuation(sh,getch(sh)))) continue; else break; } else if (!( l = get_token(sh,token,512) )) break; else if (!( status = handle_token(sh,token) )) continue; else break; } schema_footer( C.target, tn ); fclose(C.target); fclose(sh); } return( 0 ); } /* --------- */ #endif /* _strukt_c */ /* --------- */
752856.c
#ifdef HAVE_CONFIG_H #include "../../../ext_config.h" #endif #include <php.h> #include "../../../php_ext.h" #include "../../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/fcall.h" #include "kernel/memory.h" #include "ext/spl/spl_exceptions.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/operators.h" #include "kernel/string.h" /** * This file is part of the Phalcon Framework. * * (c) Phalcon Team <[email protected]> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ /** * Check for alphabetic character(s) * * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Alpha as AlphaValidator; * * $validator = new Validation(); * * $validator->add( * "username", * new AlphaValidator( * [ * "message" => ":field must contain only letters", * ] * ) * ); * * $validator->add( * [ * "username", * "name", * ], * new AlphaValidator( * [ * "message" => [ * "username" => "username must contain only letters", * "name" => "name must contain only letters", * ], * ] * ) * ); * ``` */ ZEPHIR_INIT_CLASS(Phalcon_Validation_Validator_Alpha) { ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Validation\\Validator, Alpha, phalcon, validation_validator_alpha, phalcon_validation_abstractvalidator_ce, phalcon_validation_validator_alpha_method_entry, 0); zend_declare_property_string(phalcon_validation_validator_alpha_ce, SL("template"), "Field :field must contain only letters", ZEND_ACC_PROTECTED); return SUCCESS; } /** * Constructor * * @param array options = [ * 'message' => '', * 'template' => '', * 'allowEmpty' => false * ] */ PHP_METHOD(Phalcon_Validation_Validator_Alpha, __construct) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zephir_fcall_cache_entry *_0 = NULL; zval *options_param = NULL; zval options; zval *this_ptr = getThis(); ZVAL_UNDEF(&options); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(0, 1) Z_PARAM_OPTIONAL Z_PARAM_ARRAY(options) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 1, &options_param); if (!options_param) { ZEPHIR_INIT_VAR(&options); array_init(&options); } else { ZEPHIR_OBS_COPY_OR_DUP(&options, options_param); } ZEPHIR_CALL_PARENT(NULL, phalcon_validation_validator_alpha_ce, getThis(), "__construct", &_0, 0, &options); zephir_check_call_status(); ZEPHIR_MM_RESTORE(); } /** * Executes the validation */ PHP_METHOD(Phalcon_Validation_Validator_Alpha, validate) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *validation, validation_sub, *field, field_sub, value, _0, _1, _2, _3, _4, _5$$4; zval *this_ptr = getThis(); ZVAL_UNDEF(&validation_sub); ZVAL_UNDEF(&field_sub); ZVAL_UNDEF(&value); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&_3); ZVAL_UNDEF(&_4); ZVAL_UNDEF(&_5$$4); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_OBJECT_OF_CLASS(validation, phalcon_validation_ce) Z_PARAM_ZVAL(field) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 2, 0, &validation, &field); ZEPHIR_CALL_METHOD(&value, validation, "getvalue", NULL, 0, field); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_0, this_ptr, "allowempty", NULL, 0, field, &value); zephir_check_call_status(); if (zephir_is_true(&_0)) { RETURN_MM_BOOL(1); } ZEPHIR_INIT_VAR(&_1); ZEPHIR_INIT_VAR(&_2); ZVAL_STRING(&_2, "/[^[:alpha:]]/imu"); ZEPHIR_INIT_VAR(&_3); ZEPHIR_INIT_VAR(&_4); ZVAL_STRING(&_4, "/[^[:alpha:]]/imu"); zephir_preg_match(&_3, &_4, &value, &_1, 0, 0 , 0 ); if (zephir_is_true(&_3)) { ZEPHIR_CALL_METHOD(&_5$$4, this_ptr, "messagefactory", NULL, 0, validation, field); zephir_check_call_status(); ZEPHIR_CALL_METHOD(NULL, validation, "appendmessage", NULL, 0, &_5$$4); zephir_check_call_status(); RETURN_MM_BOOL(0); } RETURN_MM_BOOL(1); }
253383.c
/******************************************************************************* System Initialization File File Name: initialization.c Summary: This file contains source code necessary to initialize the system. Description: This file contains source code necessary to initialize the system. It implements the "SYS_Initialize" function, defines the configuration bits, and allocates any necessary global system resources, *******************************************************************************/ // DOM-IGNORE-BEGIN /******************************************************************************* * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *******************************************************************************/ // DOM-IGNORE-END // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** #include "configuration.h" #include "definitions.h" #include "device.h" // **************************************************************************** // **************************************************************************** // Section: Configuration Bits // **************************************************************************** // **************************************************************************** #pragma config TCM_CONFIGURATION = 0 #pragma config SECURITY_BIT = CLEAR #pragma config BOOT_MODE = SET // ***************************************************************************** // ***************************************************************************** // Section: Driver Initialization Data // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** // Section: System Data // ***************************************************************************** // ***************************************************************************** /* Structure to hold the object handles for the modules in the system. */ SYSTEM_OBJECTS sysObj; // ***************************************************************************** // ***************************************************************************** // Section: Library/Stack Initialization Data // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** // Section: System Initialization // ***************************************************************************** // ***************************************************************************** // <editor-fold defaultstate="collapsed" desc="SYS_TIME Initialization Data"> const SYS_TIME_PLIB_INTERFACE sysTimePlibAPI = { .timerCallbackSet = (SYS_TIME_PLIB_CALLBACK_REGISTER)TC0_CH0_TimerCallbackRegister, .timerStart = (SYS_TIME_PLIB_START)TC0_CH0_TimerStart, .timerStop = (SYS_TIME_PLIB_STOP)TC0_CH0_TimerStop , .timerFrequencyGet = (SYS_TIME_PLIB_FREQUENCY_GET)TC0_CH0_TimerFrequencyGet, .timerPeriodSet = (SYS_TIME_PLIB_PERIOD_SET)TC0_CH0_TimerPeriodSet, .timerCompareSet = (SYS_TIME_PLIB_COMPARE_SET)TC0_CH0_TimerCompareSet, .timerCounterGet = (SYS_TIME_PLIB_COUNTER_GET)TC0_CH0_TimerCounterGet, }; const SYS_TIME_INIT sysTimeInitData = { .timePlib = &sysTimePlibAPI, .hwTimerIntNum = TC0_CH0_IRQn, }; // </editor-fold> // ***************************************************************************** // ***************************************************************************** // Section: Local initialization functions // ***************************************************************************** // ***************************************************************************** /******************************************************************************* Function: void STDIO_BufferModeSet ( void ) Summary: Sets the buffering mode for stdin and stdout Remarks: ********************************************************************************/ static void STDIO_BufferModeSet(void) { /* Make stdin unbuffered */ setbuf(stdin, NULL); /* Make stdout unbuffered */ setbuf(stdout, NULL); } /******************************************************************************* Function: void SYS_Initialize ( void *data ) Summary: Initializes the board, services, drivers, application and other modules. Remarks: */ void SYS_Initialize ( void* data ) { STDIO_BufferModeSet(); EFC_Initialize(); CLOCK_Initialize(); PIO_Initialize(); BSP_Initialize(); SYSTICK_TimerInitialize(); RSWDT_REGS->RSWDT_MR = RSWDT_MR_WDDIS_Msk; // Disable RSWDT WDT_REGS->WDT_MR = WDT_MR_WDDIS_Msk; // Disable WDT TC0_CH0_TimerInitialize(); USART1_Initialize(); sysObj.sysTime = SYS_TIME_Initialize(SYS_TIME_INDEX_0, (SYS_MODULE_INIT *)&sysTimeInitData); CRYPT_WCCB_Initialize(); APP_Initialize(); NVIC_Initialize(); } /******************************************************************************* End of File */